fix(server): restarts keep delegated tasks, queued threads, and stops intact #15323
Mergedmaria-rcksmerged 11 commits into
main fromrefs/pull/15323/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts line 436Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -433,3 +433,4 @@433433 dispatch: orchestrator.dispatch,434434 getThreadRecords: orchestrator.getThreadRecords,435435 getThreadProjection: orchestrator.getThreadProjection,436+ recoverDelegatedTask: orchestrator.recoverDelegatedTask,apps/server/src/orchestration-v2/ProjectionStore.ts line 3437OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3427,4 +3429,9 @@34273429 ELSE 0 END34283430 )34293431 SELECT thread_id FROM orchestration_v2_projection_runs3430- WHERE status IN ('queued', 'preparing', 'starting', 'running', 'waiting')3432+ WHERE status IN ('preparing', 'starting', 'running', 'waiting')3433+ UNION3434+ -- A held queue already went through recovery; rereading it on3435+ -- every boot costs a projection read per held thread.3436+ SELECT thread_id FROM orchestration_v2_projection_runs3437+ WHERE status = 'queued' AND json_extract(payload_json, '$.queueHeld') IS NOT 1
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/Orchestrator.ts line 81OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -77,4 +77,5 @@7777 import { isRestartNoteSource } from "./RestartBackgroundNote.ts";7878 import { isUndeliveredMailboxSteer } from "./NotificationMailbox.ts";7979 import { EventSinkV2 } from "./EventSink.ts";80-import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";80+import {81+ EffectOutboxV2,
- @@ -8437,0 +8454,21 @@8454+ * RestartContinuation recovers the thread when it declines to continue.8455+ */8456+ const awaitsRestartContinuation = (run: OrchestrationV2Run) =>8457+ effectOutbox8458+ .get(`effect:restart-continuation:${run.id}`)8459+ .pipe(8460+ Effect.map(8461+ Option.exists((effect) => effect.status === "pending" || effect.status === "running"),8462+ ),8463+ );8464+8465+ /**8466+ * A delegated child's result is held while its result run, or a later run a8467+ * second restart cut before it started, still has a continuation pending.8468+ */8469+ const childAwaitsRestartContinuation = (8470+ runs: ReadonlyArray<OrchestrationV2Run>,8471+ resultRun: OrchestrationV2Run,8472+ ) =>8473+ Effect.forEach(8474+ runs.filter((run) => run.id === resultRun.id || run.ordinal > resultRun.ordinal),apps/server/src/orchestration-v2/Orchestrator.ts line 9013OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -8954,3 +9007,7 @@89549007 }8955900889569009 const now = yield* DateTime.now;9010+ // The provider already received this delivery's message; a restart9011+ // continuation resumes that turn, so offering it again would duplicate it.9012+ const redeliver =9013+ deliveryRun.status === "cancelled" && !(yield* awaitsRestartContinuation(deliveryRun));@@ -1055,4 +1055,8 @@10551055 messages: [...childControls.messages, ...resultRecords.messages],10561056 turnItems: resultRecords.turnItems,10571057 };1058- const workState = task.result !== null ? "result_available" : progress.state;1058+ // A restart cut the child's run and its continuation has not settled yet.1059+ const heldForRestart =1060+ task.result === null &&1061+ progress.state === "result_available" &&1062+ (yield* threadManagement.delegatedTaskAwaitsRestart(task.childThreadId));
- apps/server/src/orchestration-v2/ProjectionStore.ts lines 3812 to 3832OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3801,0 +3812,21 @@3812+ -- A background roster belongs to the run that ended last3813+ -- (ranAfter), which a queued or resumed run can outrank.3814+ OR (3815+ run.run_id = (3816+ SELECT ended.run_id FROM orchestration_v2_projection_runs AS ended3817+ WHERE ended.thread_id = ${threadId}3818+ AND ended.status != 'queued'3819+ ORDER BY3820+ CASE WHEN json_valid(ended.payload_json)3821+ THEN json_extract(ended.payload_json, '$.completedAt') END DESC,3822+ ended.ordinal DESC3823+ LIMIT 13824+ )3825+ AND EXISTS (3826+ SELECT 1 FROM orchestration_v2_projection_provider_threads AS roster3827+ WHERE roster.thread_id = ${threadId}3828+ AND CASE WHEN json_valid(roster.payload_json)3829+ THEN json_array_length(roster.payload_json, '$.pendingBackgroundTasks') > 03830+ ELSE 0 END3831+ )3832+ )
- @@ -1055,4 +1055,9 @@10551055 messages: [...childControls.messages, ...resultRecords.messages],10561056 turnItems: resultRecords.turnItems,10571057 };1058- const workState = task.result !== null ? "result_available" : progress.state;1058+ // A restart cut the child's run and its continuation has not settled, or1059+ // the child started working again after this read.1060+ const heldForRestart =1061+ task.result === null &&1062+ progress.state === "result_available" &&1063+ (yield* threadManagement.delegatedTaskResultPending(task.childThreadId));apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 365 to 383Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -363,2 +363,21 @@363363 );364364 const layerScope = yield* Effect.scope;365+ // Ctrl+C, or a stop that signals the whole process group, reaches the366+ // provider CLIs with the server. They report their own background work367+ // stopped before shutdown captures restart continuations, so provider368+ // events after the signal are dropped; restart recovery owns that state.369+ const shutdownSignal = { received: false };370+ const onShutdownSignal = () => {371+ shutdownSignal.received = true;372+ };373+ yield* Effect.acquireRelease(374+ Effect.sync(() => {375+ process.on("SIGINT", onShutdownSignal);376+ process.on("SIGTERM", onShutdownSignal);377+ }),378+ () =>379+ Effect.sync(() => {380+ process.off("SIGINT", onShutdownSignal);381+ process.off("SIGTERM", onShutdownSignal);382+ }),383+ );
- apps/server/src/orchestration-v2/ProjectionStore.ts line 3818OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3799,3 +3812,7 @@37993812 WHERE latest.thread_id = ${threadId}38003813 ORDER BY latest.ordinal DESC LIMIT 138013814 )3815+ -- A background roster belongs to the run that ended last3816+ -- (ranAfter), which a queued or resumed run can outrank.3817+ OR (3818+ run.run_id = (
- apps/server/src/orchestration-v2/RestartBackgroundNote.ts lines 141 to 143OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -123 +124,20 @@123-/** A restart continuation whose prompt is the note rather than a resume. */124+/**125+ * The note a restart continuation of `source` carries, and whether the turn it126+ * continues had settled (the note is then the whole prompt). A continuation cut127+ * before its provider turn completed may not have delivered its own note:128+ * adapters can announce a running turn before accepting the prompt. Carry the129+ * note forward until a completed turn proves delivery.130+ */131+export function restartContinuationNote(132+ source: OrchestrationV2Run,133+ runs: ReadonlyArray<OrchestrationV2Run>,134+ providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,135+): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {136+ let current = source;137+ let work = current.restartCancelledBackgroundWork ?? [];138+ const visited = new Set([current.id]);139+ while (140+ current.restartContinuationOfRunId !== undefined &&141+ !providerTurns.some(142+ (turn) => turn.runAttemptId === current.activeAttemptId && turn.status === "completed",143+ )
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
maria-rcks merged this5108c97
maria-rcks closed this
Sign in to join this conversation.

macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed