Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,11 @@ const layerTest = Layer.mergeAll(
Layer.provide(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
Layer.provide(ServerSettings.layerTest()),
Layer.provide(
ServerSettings.layerTest({
providerInstances: { [modelSelection.instanceId]: { driver: "codex", config: {} } },
}),
),
Layer.provide(layerTestProviderInstanceRegistry),
Layer.provide(layerPlatformTest),
Layer.provide(ProviderRegistryMock.layer()),
Expand Down
39 changes: 37 additions & 2 deletions apps/server/src/orchestration-v2/ModelAlertReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ let occurrence = 0;
const eventAlert = (finding: ThreadFinding): ThreadEventAlert => ({
type: "thread-event",
kind: finding.kind,
id: `env:thread:fleet:${finding.kind}:${finding.signature}:${(occurrence += 1)}`,
id: `env:thread:fleet:${finding.kind}:${finding.signature}:${DateTime.formatIso(DateTime.makeUnsafe(occurrence))}`,
environmentId: "env",
environmentLabel: "primary-r720",
threadId: "thread:fleet",
Expand All @@ -190,7 +190,7 @@ const eventAlert = (finding: ThreadFinding): ThreadEventAlert => ({
lastAssistantLine: "A background watch will wake this thread.",
lastError: null,
openPullRequests: [],
occurredAt: "2026-11-19T03:00:00.000Z",
occurredAt: DateTime.formatIso(DateTime.makeUnsafe(occurrence++)),
});

const finding = (kind: ThreadEventKind, signature: string): ThreadFinding => ({
Expand Down Expand Up @@ -235,6 +235,41 @@ it("reports a thread event once per kind and signature until its state changes",
);
});

it("deduplicates a stranded queue until the queue advances or drains", () => {
let state = EMPTY_MODEL_ALERT_STATE;
const step = (runId: string | null, actionable: boolean, nowMs: number) => {
const result = recordThreadEvents(
state,
{
threadId: "thread:fleet",
evaluated: ["stuck"],
findings: runId !== null && actionable ? [finding("stuck", `stranded-queue:${runId}`)] : [],
strandedQueue: runId === null ? null : { runId, requestedAt: DateTime.makeUnsafe(0) },
},
eventAlert,
["watcher"],
nowMs,
);
state = result.state;
return result.enqueued;
};
assert.isTrue(step("queued:1", true, 1));
assert.isFalse(step("queued:1", false, 2));
assert.isFalse(step("queued:1", true, 3));
const [undelivered] = state.outbox;
assert.isDefined(undelivered);
state = afterDrop(state, undelivered, 4);
assert.isTrue(step("queued:1", true, 5));
const [delivered] = state.outbox;
assert.isDefined(delivered);
state = afterDeliveryAttempt(state, delivered, true, 6);
assert.isFalse(step("queued:1", false, 7));
assert.isFalse(step("queued:1", true, 8));
assert.isTrue(step("queued:2", true, 9));
assert.isFalse(step(null, false, 10));
assert.isTrue(step("queued:3", true, 11));
});

it("a thread holding a question and an inbox flip reports each once, not on every trigger", () => {
const both = [finding("needs-person", "request:1"), finding("needs-person", "inbox:kameron")];
let state = EMPTY_MODEL_ALERT_STATE;
Expand Down
155 changes: 130 additions & 25 deletions apps/server/src/orchestration-v2/ModelAlertReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from "@t3tools/contracts";
import { runModelSignals, workerAlert } from "@t3tools/provider-core/server/subagentProjection";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
Expand Down Expand Up @@ -44,7 +45,10 @@ import * as Orchestrator from "./Orchestrator.ts";
import { ProviderExhaustion } from "./ProviderExhaustion.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import {
isStrandedQueueSignature,
judgeThread,
keepStrandedQueueReport,
type StrandedQueue,
threadEventAlert,
launchingThreadId,
ThreadEventAlert,
Expand Down Expand Up @@ -321,6 +325,51 @@ function enqueueAlert(
}

const reportedKey = (threadId: string, kind: ThreadEventKind) => `${threadId}\n${kind}`;
const deliveredQueuePrefix = "delivered:";
const queueReportSignature = (signature: string) =>
signature.startsWith(deliveredQueuePrefix)
? signature.slice(deliveredQueuePrefix.length)
: signature;

function strandedAlertSignature(alert: WatcherAlert): string | undefined {
if (alert.type !== "thread-event" || alert.kind !== "stuck") return undefined;
const prefix = `${alert.environmentId}:${alert.threadId}:${alert.kind}:`;
const suffix = `:${alert.occurredAt}`;
if (!alert.id.startsWith(prefix) || !alert.id.endsWith(suffix)) return undefined;
const signature = alert.id.slice(prefix.length, -suffix.length);
return isStrandedQueueSignature(signature) ? signature : undefined;
}

function setReported(
reported: ModelAlertState["reported"],
key: string,
signatures: ReadonlyArray<string>,
): ModelAlertState["reported"] {
const { [key]: _previous, ...rest } = reported;
return signatures.length === 0
? rest
: {
...Object.fromEntries(Object.entries(rest).slice(-(MAX_REPORTED - 1))),
[key]: signatures.join("\n"),
};
}

function recordStrandedDelivery(
reported: ModelAlertState["reported"],
entry: Delivery,
delivered: boolean,
) {
if (entry.alert.type !== "thread-event") return reported;
const signature = strandedAlertSignature(entry.alert);
if (signature === undefined) return reported;
const key = reportedKey(entry.alert.threadId, "stuck");
const known = (reported[key] ?? "").split("\n").filter(Boolean);
if (!delivered && !known.includes(signature)) return reported;
const next = known.filter((candidate) => candidate !== signature);
const sent = `${deliveredQueuePrefix}${signature}`;
if (delivered && !next.includes(sent)) next.push(sent);
return setReported(reported, key, next);
}

/**
* Records what a trigger found true of a thread. A kind reports once per signature: it stays quiet
Expand All @@ -332,6 +381,7 @@ export function recordThreadEvents(
readonly threadId: string;
readonly evaluated: ReadonlyArray<ThreadEventKind>;
readonly findings: ReadonlyArray<ThreadFinding>;
readonly strandedQueue?: StrandedQueue | null;
},
toAlert: (finding: ThreadFinding) => ThreadEventAlert,
destinations: ReadonlyArray<Destination>,
Expand All @@ -343,20 +393,34 @@ export function recordThreadEvents(
for (const kind of judged.evaluated) {
const key = reportedKey(judged.threadId, kind);
const kindFindings = judged.findings.filter((finding) => finding.kind === kind);
if (kindFindings.length === 0) {
if (reported[key] !== undefined) {
const { [key]: _cleared, ...rest } = reported;
reported = rest;
}
continue;
}
// A kind can hold several findings at once (a question and an inbox flip), so it remembers
// each signature it reported. One that stops being true is forgotten and can report again.
const known = (reported[key] ?? "").split("\n").filter((signature) => signature !== "");
const delivered: Array<string> = [];
const delivered = known.filter(
(signature) =>
kind === "stuck" &&
keepStrandedQueueReport(queueReportSignature(signature), judged.strandedQueue),
);
for (const finding of kindFindings) {
if (kind === "stuck" && isStrandedQueueSignature(finding.signature)) {
if (
delivered.some((signature) => queueReportSignature(signature) === finding.signature) ||
outbox.some(
(entry) =>
entry.alert.type === "thread-event" &&
entry.alert.threadId === judged.threadId &&
nowMs - entry.createdAt < OUTBOX_TTL_MS &&
strandedAlertSignature(entry.alert) === finding.signature,
)
)
continue;
const queued = enqueueAlert(outbox, toAlert(finding), destinations, nowMs);
outbox = queued.outbox;
enqueued ||= queued.enqueued;
continue;
}
if (known.includes(finding.signature)) {
delivered.push(finding.signature);
if (!delivered.includes(finding.signature)) delivered.push(finding.signature);
continue;
}
const queued = enqueueAlert(outbox, toAlert(finding), destinations, nowMs);
Expand All @@ -366,14 +430,8 @@ export function recordThreadEvents(
}
// A finding with nowhere to go stays unreported, so a later launcher or webhook still hears it.
const stored = delivered.join("\n");
if (reported[key] !== stored) {
const { [key]: _previous, ...rest } = reported;
reported = stored
? {
...Object.fromEntries(Object.entries(rest).slice(-(MAX_REPORTED - 1))),
[key]: stored,
}
: rest;
if ((reported[key] ?? "") !== stored) {
reported = setReported(reported, key, delivered);
}
}
if (reported === state.reported && outbox === state.outbox) return { state, enqueued };
Expand Down Expand Up @@ -487,7 +545,9 @@ export function afterDeliveryAttempt(
return {
...state,
incidentSentAt,
reported: delivered ? markLinkDelivered(state.reported, entry) : state.reported,
reported: delivered
? recordStrandedDelivery(markLinkDelivered(state.reported, entry), entry, true)
: state.reported,
outbox: pruneOutbox(state.outbox, nowMs).flatMap((candidate) => {
if (!sameDelivery(candidate, entry)) return [candidate];
if (delivered) {
Expand Down Expand Up @@ -536,6 +596,11 @@ export const afterDrop = (
nowMs: number,
): ModelAlertState => ({
...state,
reported: state.outbox.some(
(candidate) => candidate.alert.id === entry.alert.id && !sameDelivery(candidate, entry),
)
? state.reported
: recordStrandedDelivery(state.reported, entry, false),
outbox: state.outbox.flatMap((candidate) => {
if (!sameDelivery(candidate, entry)) return [candidate];
if (
Expand Down Expand Up @@ -746,7 +811,6 @@ export const watcherAlertMessage = (alert: WatcherAlert) => {
}
};


/** Alerts ride in the watcher's next digest; a newer alert on the same subject replaces an older one. */
function alertDelivery(alert: WatcherAlert): {
readonly coalesceKey: string;
Expand Down Expand Up @@ -1008,6 +1072,7 @@ export const make = Effect.gen(function* () {
shell: OrchestrationV2ThreadShell,
trigger: ThreadEventTrigger,
remoteTasks?: ReadonlyMap<string, number>,
queuedThreads?: ReadonlySet<ThreadId>,
) {
const remoteTaskCount =
trigger === "request" || trigger === "inbox"
Expand Down Expand Up @@ -1039,7 +1104,41 @@ export const make = Effect.gen(function* () {
)),
)
: null;
return { remoteTaskCount, childActivityMs };
if (trigger !== "sweep" || shell.activeRunId !== null || shell.activityRunStatus != null) {
return { remoteTaskCount, childActivityMs };
}
if (queuedThreads !== undefined && !queuedThreads.has(shell.id)) {
return { remoteTaskCount, childActivityMs, strandedQueue: null };
}
const now = yield* DateTime.now;
const { runs } = yield* projections.getThreadRecords(shell.id, ["runs"]);
const queued = runs
.filter(
(run) =>
run.status === "queued" &&
run.delivery?.class !== "digest" &&
(run.delivery?.expiresAt === undefined ||
DateTime.isGreaterThan(run.delivery.expiresAt, now)),
)
.toSorted(
(left, right) =>
DateTime.toEpochMillis(left.requestedAt) - DateTime.toEpochMillis(right.requestedAt),
);
const latestRun = latestExecutedRun(runs);
const oldest = queued.find((run) => run.queueHeld !== true) ?? queued[0];
const strandedQueue =
oldest === undefined
? null
: {
runId: oldest.id,
requestedAt: oldest.requestedAt,
lastCompletedAt: latestRun?.completedAt ?? null,
queueHeld:
oldest.queueHeld === true ||
(shell.lastErrorClass === "usage_limit" &&
latestRun?.providerInstanceId === oldest.providerInstanceId),
};
return { remoteTaskCount, childActivityMs, strandedQueue };
});

/** The watcher thread as one delivery needs it, or null when it cannot be read. */
Expand Down Expand Up @@ -1131,7 +1230,11 @@ export const make = Effect.gen(function* () {
}
if (entry.destination === "webhook") {
const url = current.modelAlertWebhookUrl.trim();
if (url === "") return { _tag: "sent" } satisfies DeliveryResult;
if (url === "") {
return {
_tag: strandedAlertSignature(alert) === undefined ? "sent" : "dropped",
} satisfies DeliveryResult;
}
// A webhook URL can embed a credential, so its failure names only the host.
const host = URL.canParse(url) ? new URL(url).host : "an unparsable URL";
yield* http
Expand Down Expand Up @@ -1359,22 +1462,23 @@ export const make = Effect.gen(function* () {
usageLimitReported: boolean,
/** Open delegated tasks by parent thread, when the caller read them once for many threads. */
remoteTasks?: ReadonlyMap<string, number>,
queuedThreads?: ReadonlySet<ThreadId>,
) {
const current = yield* settings.getSettings;
const here = yield* environment.getEnvironmentId;
const watcher = current.modelAlertWatcher;
// The watcher's own turns would report to itself forever.
if (watcher?.environmentId === here && watcher.threadId === threadId) return;
if (watcher === null && current.modelAlertWebhookUrl.trim() === "") return;
const shell = yield* projections.getThreadShell(threadId);
if (shell === null || shell.deletedAt !== null) return;
const nowMs = yield* Clock.currentTimeMillis;
const context = yield* judgeContext(shell, trigger, remoteTasks, queuedThreads);
const judged = judgeThread({
shell,
trigger,
nowMs,
stuckMinutes: current.watcherStuckMinutes,
...(yield* judgeContext(shell, trigger, remoteTasks)),
...context,
usageLimitReported,
});
const label = (yield* environment.getDescriptor).label;
Expand All @@ -1390,7 +1494,7 @@ export const make = Effect.gen(function* () {
const enqueued = yield* update((state) => {
const result = recordThreadEvents(
state,
{ threadId, evaluated: judged.evaluated, findings: judged.findings },
{ threadId, ...judged, ...context },
(finding) =>
threadEventAlert({
environmentId: here,
Expand Down Expand Up @@ -1519,6 +1623,7 @@ export const make = Effect.gen(function* () {
Effect.catchCause((cause) => Effect.logWarning("resume sweep failed", { cause })),
);
const index = yield* projections.listActiveShellIndex();
const queuedThreads = new Set(yield* projections.getRecoveryThreadIds("queued-runs"));
// One scan of the delegated tasks for the whole sweep, not one per thread.
const remoteTasks = new Map<string, number>();
for (const task of yield* projections.getOpenRemoteDelegatedTasks) {
Expand All @@ -1527,7 +1632,7 @@ export const make = Effect.gen(function* () {
yield* Effect.forEach(
index.filter((entry) => entry.mayBeLive && isListedThreadLineage(entry.lineage)),
(entry) =>
handleThreadEvents(entry.id, "sweep", false, remoteTasks).pipe(
handleThreadEvents(entry.id, "sweep", false, remoteTasks, queuedThreads).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("sweeping a thread for a watcher event failed", {
threadId: entry.id,
Expand Down
Loading
Loading