From 528adb2fe055000a5e7b195800607269b519590e Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 23 Jul 2026 18:19:56 -0700 Subject: [PATCH] Harden open-task tracking against stale and replayed events Review fixes: gate the terminal-status task sweep behind the lifecycle guard so rejected stale events cannot erase the active turn's tasks; ignore task starts from a provider instance that doesn't match the projected session instead of letting them displace the current set; tombstone completed task ids so late/duplicate progress cannot re-open a finished task and park the thread on Waiting. Co-Authored-By: Claude Fable 5 --- .../Layers/ProviderRuntimeIngestion.test.ts | 95 +++++++++++++++++++ .../Layers/ProviderRuntimeIngestion.ts | 73 ++++++++++---- 2 files changed, 149 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 44a5d2c582..ab9db9cbb9 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -3327,6 +3327,101 @@ describe("ProviderRuntimeIngestion", () => { await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle"); }); + it("ignores late task progress for a completed task", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + + harness.emit({ + type: "task.started", + eventId: asEventId("evt-tombstone-task-started"), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + taskId: "tombstone-task-1", + }, + }); + harness.emit({ + type: "task.completed", + eventId: asEventId("evt-tombstone-task-completed"), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + taskId: "tombstone-task-1", + status: "completed", + }, + }); + // Duplicate/late progress must not re-open the finished task… + harness.emit({ + type: "task.progress", + eventId: asEventId("evt-tombstone-task-late-progress"), + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:01.000Z", + threadId: asThreadId("thread-1"), + payload: { + taskId: "tombstone-task-1", + description: "late duplicate progress", + }, + }); + // …so a subsequent turn completion settles on ready, not idle. + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-tombstone-turn-completed"), + provider: ProviderDriverKind.make("codex"), + threadId: asThreadId("thread-1"), + createdAt: "2026-01-01T00:00:02.000Z", + turnId: asTurnId("turn-tombstone"), + payload: { + state: "completed", + }, + }); + + await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready"); + }); + + it("ignores task events from a stale provider instance", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + + // Current instance ("codex", matching the seeded session) opens a task. + harness.emit({ + type: "task.started", + eventId: asEventId("evt-current-instance-task-started"), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + taskId: "current-task-1", + }, + }); + // A delayed start from a replaced instance must not displace it. + harness.emit({ + type: "task.started", + eventId: asEventId("evt-stale-instance-task-started"), + provider: ProviderDriverKind.make("claudeAgent"), + createdAt: "2026-01-01T00:00:01.000Z", + threadId: asThreadId("thread-1"), + payload: { + taskId: "stale-task-1", + }, + }); + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-stale-instance-turn-completed"), + provider: ProviderDriverKind.make("codex"), + threadId: asThreadId("thread-1"), + createdAt: "2026-01-01T00:00:02.000Z", + turnId: asTurnId("turn-stale-instance"), + payload: { + state: "completed", + }, + }); + + // The current instance's open task still parks the thread on Waiting. + await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle"); + }); + it("clears open tasks on session exit so they cannot park a later session", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 7264141b02..b9a5b3d63e 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -751,23 +751,55 @@ const make = Effect.gen(function* () { // "ready" ("Done"): the agent stopped, but a task completion is expected to // wake it, and flashing Done in between is a lie. Keyed by provider // instance so a replaced session can neither inherit nor close a - // predecessor's tasks. Plain mutable state is safe: ingestion is a single - // serial worker. Terminal session statuses sweep the entry. - const openTasksByThreadId = new Map }>(); + // predecessor's tasks; closed ids are kept as tombstones so a late or + // replayed start/progress cannot resurrect a finished task. Plain mutable + // state is safe: ingestion is a single serial worker. Terminal session + // statuses sweep the entry. + const openTasksByThreadId = new Map< + ThreadId, + { instanceKey: string; taskIds: Set; closedTaskIds: Set } + >(); const taskInstanceKey = (event: ProviderRuntimeEvent) => event.providerInstanceId ?? event.provider; - /** Returns true when this task is the instance's first open task. */ - const trackTaskStarted = (threadId: ThreadId, event: ProviderRuntimeEvent, taskId: string) => { + const sessionInstanceKeyFor = (session: { + providerInstanceId?: string | undefined; + providerName: string | null; + }): string | null => session.providerInstanceId ?? session.providerName; + + /** + * Returns true when this task is the instance's first open task. The + * projected session adjudicates cross-instance races: a delayed start from + * a replaced instance must neither seed a phantom set nor displace the + * current instance's tasks, while a current-instance start may reclaim an + * entry a dead instance leaked. + */ + const trackTaskStarted = ( + threadId: ThreadId, + event: ProviderRuntimeEvent, + taskId: string, + sessionInstanceKey: string | null, + ) => { const instanceKey = taskInstanceKey(event); + if (sessionInstanceKey !== null && instanceKey !== sessionInstanceKey) { + return false; + } const entry = openTasksByThreadId.get(threadId); if (!entry || entry.instanceKey !== instanceKey) { - openTasksByThreadId.set(threadId, { instanceKey, taskIds: new Set([taskId]) }); + openTasksByThreadId.set(threadId, { + instanceKey, + taskIds: new Set([taskId]), + closedTaskIds: new Set(), + }); return true; } + if (entry.closedTaskIds.has(taskId)) { + return false; + } + const wasEmpty = entry.taskIds.size === 0; entry.taskIds.add(taskId); - return false; + return wasEmpty; }; const trackTaskCompleted = (threadId: ThreadId, event: ProviderRuntimeEvent, taskId: string) => { @@ -776,9 +808,7 @@ const make = Effect.gen(function* () { return; } entry.taskIds.delete(taskId); - if (entry.taskIds.size === 0) { - openTasksByThreadId.delete(threadId); - } + entry.closedTaskIds.add(taskId); }; const hasOpenTasks = (threadId: ThreadId, event: ProviderRuntimeEvent) => { @@ -1448,12 +1478,6 @@ const make = Effect.gen(function* () { : restingStatus; } })(); - // A session leaving the resting/running loop can no longer be woken - // by its tasks; drop them so a stale set never parks a future - // session on Waiting. - if (status === "stopped" || status === "error" || status === "interrupted") { - clearOpenTasks(thread.id); - } const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) @@ -1476,6 +1500,13 @@ const make = Effect.gen(function* () { : (thread.session?.lastError ?? null); if (shouldApplyThreadLifecycle) { + // A session leaving the resting/running loop can no longer be woken + // by its tasks; drop them so a stale set never parks a future + // session on Waiting. Gated like the session.set below: a rejected + // stale event must not erase the active turn's tasks. + if (status === "stopped" || status === "error" || status === "interrupted") { + clearOpenTasks(thread.id); + } if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { yield* markSourceProposedPlanImplemented( acceptedTurnStartedSourcePlan.sourceThreadId, @@ -1823,7 +1854,12 @@ const make = Effect.gen(function* () { // task.progress tracks too: it re-opens a task the tracker lost // (server restart, missed start event) so the thread still parks on // Waiting instead of a false Done. - const firstOpenTask = trackTaskStarted(thread.id, event, event.payload.taskId); + const firstOpenTask = trackTaskStarted( + thread.id, + event, + event.payload.taskId, + thread.session ? sessionInstanceKeyFor(thread.session) : null, + ); // A task can outlive its turn: when its start (or surviving progress) // lands after the turn already settled the session on "ready", demote // to "idle" now — the turn-completion path never saw the task. @@ -1831,8 +1867,7 @@ const make = Effect.gen(function* () { firstOpenTask && thread.session?.status === "ready" && thread.session.activeTurnId === null && - (thread.session.providerInstanceId ?? thread.session.providerName) === - taskInstanceKey(event) + sessionInstanceKeyFor(thread.session) === taskInstanceKey(event) ) { yield* orchestrationEngine.dispatch({ type: "thread.session.set",