diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index aff11dacad26..4c8f12e38eae 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -378,7 +378,7 @@ const cancelBackgroundOnlyTask = ( (event) => event.type === "run.updated" && event.payload.id === child.turn.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); const nativeSubagentEvents = [ { @@ -560,7 +560,8 @@ const cancelBackgroundOnlyTask = ( } const before = yield* service.taskStatus(scope, task.id); assert.equal(before.status, "running"); - assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working"); + // The child's run completes when its turn ends, before its checkpoint capture runs. + assert.equal(before.workState, cancelAt === "turn" ? "working" : "waiting_for_children"); const parentTask = Effect.map(orchestrator.getThreadProjection(parentThreadId), (parent) => parent.subagents.find((entry) => entry.id === task.id), @@ -592,7 +593,8 @@ const cancelBackgroundOnlyTask = ( event.payload.type === "run_interrupt_request", ), ); - assert.equal((yield* parentTask)?.status, "running"); + // The child's turn already ended, so the cancel settles its finished run in this commit. + assert.equal((yield* parentTask)?.status, "interrupted"); return { scope, taskId: task.id, settled: undefined }; } if (cancelAt === "refused") { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index afb1d0814711..b256c83c4b12 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5515,7 +5515,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -7342,9 +7342,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { createdBy: "user", creationSource: "web", }); - const waiting = yield* orchestrator.streamDomainEvents.pipe( + const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -7362,7 +7362,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); yield* worker.drain(); assert.isNull((yield* Ref.get(replayDriver.state)).failure); - yield* Fiber.join(waiting); + yield* Fiber.join(completed); yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); const run = projection.runs.at(-1)!; @@ -7465,9 +7465,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); const settled = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => - event.type === "run.updated" && - (event.payload.status === "waiting" || event.payload.status === "completed"), + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts index 2faa33ec8fcb..f78eb10ac3e0 100644 --- a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts +++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts @@ -536,7 +536,7 @@ const stopEarlierBackgroundWork = ({ (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); yield* Queue.offer(events, { type: "provider_turn.updated", diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index cc570a9ef113..5856196b01f5 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -103,10 +103,10 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { userMessageId: MessageId.make("message:checkpoint-capture-user"), rootNodeId, activeAttemptId: null, - status: "waiting", + status: "completed", requestedAt: now, startedAt: now, - completedAt: null, + completedAt: now, checkpointId: null, contextHandoffId: null, delegatedCompletion: staleDelegatedCompletion, @@ -118,7 +118,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { parentNodeId: null, rootNodeId, kind: "root_turn" as const, - status: "waiting" as const, + status: "completed" as const, countsForRun: true, providerThreadId, providerTurnId: null, @@ -126,7 +126,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { runtimeRequestId: null, checkpointScopeId: scopeId, startedAt: now, - completedAt: null, + completedAt: now, }; const scope = { id: scopeId, @@ -351,7 +351,10 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { if (runUpdated?.type !== "run.updated") { return; } + // The run completed when its provider turn ended; capture only attaches the checkpoint. assert.equal(runUpdated.payload.status, "completed"); + assert.deepEqual(runUpdated.payload.completedAt, now); + assert.isFalse(events.some((event) => event.type === "node.updated")); const capturedEvent = events.find((event) => event.type === "checkpoint.captured"); assert.equal( runUpdated.payload.checkpointId, diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index dd7f27079a4e..7dd2d1a3629e 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -76,15 +76,12 @@ export const layer: Layer.Layer< const context = yield* projections.getCheckpointCaptureContext(input.threadId, input); const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } = context; - // Stopped runs remain terminal; their checkpoint is the next message's rollback point. - const stopped = run?.status === "interrupted" || run?.status === "cancelled"; + // Runs settle before capture; `waiting` is a run persisted before captures ran after settling. + const settled = + run?.status === "completed" || run?.status === "interrupted" || run?.status === "cancelled"; // A checkpoint on a settled run proves this at-least-once effect already committed. - if ( - run !== undefined && - run.checkpointId !== null && - (run.status === "completed" || stopped) - ) { + if (run !== undefined && run.checkpointId !== null && settled) { return; } // Rollback uses the same lane and can precede a capture retry; preserve the restored workspace and discarded run. @@ -94,7 +91,7 @@ export const layer: Layer.Layer< if ( run === undefined || - (run.status !== "waiting" && !stopped) || + (run.status !== "waiting" && !settled) || rootNode === undefined || scope === undefined || rootNode.checkpointScopeId !== scope.id || @@ -104,7 +101,7 @@ export const layer: Layer.Layer< threadId: input.threadId, runId: input.runId, scopeId: input.scopeId, - cause: "The persisted checkpoint capture target is incomplete or no longer waiting.", + cause: "The persisted checkpoint capture target is incomplete or was discarded.", }); } @@ -254,9 +251,13 @@ export const layer: Layer.Layer< if (currentRun === undefined || currentRun.activeAttemptId !== run.activeAttemptId) { return; } - const stoppedNow = - currentRun.status === "interrupted" || currentRun.status === "cancelled"; - if (currentRun.status !== "waiting" && !stoppedNow) { + const legacyWaiting = currentRun.status === "waiting"; + if ( + !legacyWaiting && + currentRun.status !== "completed" && + currentRun.status !== "interrupted" && + currentRun.status !== "cancelled" + ) { return; } // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. @@ -336,16 +337,16 @@ export const layer: Layer.Layer< nodeId: rootNode.id, providerInstanceId: run.providerInstanceId, occurredAt: capturedAt, - payload: stoppedNow - ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id } - : { + payload: legacyWaiting + ? { ...runWithoutDelegatedCompletion, status: "completed", completedAt: capturedAt, checkpointId: checkpoint.id, - }, + } + : { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id }, }, - ...(stoppedNow + ...(!legacyWaiting ? [] : [ { diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index de951ab23477..46f4728a4a18 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -416,7 +416,7 @@ it.effect.each(deliveries)( (event) => event.type === "run.updated" && event.payload.id === parent.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); yield* Queue.offer(sdkMessages, toolResult("build", false)); for (const id of statusIds) @@ -437,7 +437,7 @@ it.effect.each(deliveries)( (event) => event.type === "run.updated" && event.payload.id === queued.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); yield* Queue.offer(sdkMessages, result("notice-completed", false)); yield* Fiber.join(noticeFinished); @@ -926,7 +926,7 @@ it.effect("offers a continuation for a later wake after a queued continuation is }); yield* worker.drain(); yield* Fiber.join(running); - const waiting = yield* runUpdated(id, "waiting"); + const waiting = yield* runUpdated(id, "completed"); yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId)); yield* Queue.offer(sdkMessages, result(`result-${id}`, false)); yield* Fiber.join(waiting); @@ -1006,7 +1006,7 @@ it.effect("offers a continuation for a later wake after a queued continuation is (event) => event.type === "run.updated" && event.payload.id === secondContinuation.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); yield* offerAndWait(result("wake-2-result", false)); yield* Fiber.join(secondWaiting); @@ -1108,7 +1108,7 @@ it.effect.each([ Stream.runDrain, Effect.forkScoped, ); - const settled = (runId: RunId, status: "waiting") => + const settled = (runId: RunId, status: "completed") => watch( (event) => event.type === "run.updated" && @@ -1207,7 +1207,7 @@ it.effect.each([ ); if (outcome === "Claude cancels it twice") { - const ended = yield* settled(parent.id, "waiting"); + const ended = yield* settled(parent.id, "completed"); const nextRunning = yield* watch( (event) => event.type === "provider-turn.updated" && @@ -1249,7 +1249,7 @@ it.effect.each([ }); yield* worker.drain(); assert.equal(offers[3]?.priority, "next"); - const beforeEnded = yield* settled(before.id, "waiting"); + const beforeEnded = yield* settled(before.id, "completed"); const steerStarting = yield* watch( (event) => event.type === "run.updated" && @@ -1513,9 +1513,7 @@ const exitWhileIdle = (options: { yield* Fiber.join(awaitedRoster); } const settled = yield* watch( - (event) => - event.type === "run.updated" && - (event.payload.status === "waiting" || event.payload.status === "completed"), + (event) => event.type === "run.updated" && event.payload.status === "completed", ); yield* Queue.offer(firstProcess, result("waiting-on-sleep", false)); yield* Fiber.join(settled); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ae06077992d0..8bda9631ffe3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1280,6 +1280,15 @@ function queuedRunCancellationEvents( return events; } +function latestStartedRun(runs: ReadonlyArray): OrchestrationV2Run | undefined { + return runs + .filter((run) => run.status !== "queued") + .reduce( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + ); +} + function latestStableRun( projection: Pick, ): OrchestrationV2Run | null { @@ -1873,9 +1882,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio visibleTurnItems: [], updatedAt: records.thread.updatedAt, })), + Effect.flatMap(holdRunAwaitingCapture), Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), ); + // Commands decide as if the latest run were still `waiting` until its turn-end capture commits: + // the capture keeps the thread's effect lane, and steers and queued turns must line up behind it. + const holdRunAwaitingCapture = Effect.fn("Orchestrator.holdRunAwaitingCapture")(function* ( + projection: OrchestrationV2ThreadProjection, + ) { + const latest = latestStartedRun(projection.runs); + if (latest === undefined || !(yield* awaitsCheckpointCapture(latest))) return projection; + return { + ...projection, + runs: projection.runs.map((run) => + run.id === latest.id ? { ...run, status: "waiting" as const, completedAt: null } : run, + ), + }; + }); + // Command reads omit settled tasks, but a completion notice counts its whole cohort. const notificationTasks = ( threadId: ThreadId, @@ -3511,6 +3536,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A steer still pending after its run ended was never read: the provider marks one it read // completed, and one Stop dropped cancelled. It runs next, in its place among waiting messages. + // A run completes before its turn-end checkpoint capture. Steers and queued turns advance when + // the capture commits and repeats the update, after the deliveries ahead of it on the lane. + const awaitsCheckpointCapture = (run: OrchestrationV2Run) => + run.status !== "completed" || run.checkpointId !== null + ? Effect.succeed(false) + : effectOutbox.get(`effect:checkpoint.capture:${run.id}`).pipe( + Effect.map( + Option.exists((effect) => effect.status === "pending" || effect.status === "running"), + ), + Effect.orElseSucceed(() => false), + ); + + const awaitLatestRunCapture = Effect.fn("Orchestrator.awaitLatestRunCapture")( + function* (threadId: ThreadId) { + const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"]); + const latest = latestStartedRun(runs); + if (latest === undefined || !(yield* awaitsCheckpointCapture(latest))) return; + yield* effectOutbox.awaitSettled(`effect:checkpoint.capture:${latest.id}`); + }, + (effect) => Effect.ignore(effect), + ); + const requeueUnreadSteers = Effect.fn("Orchestrator.requeueUnreadSteers")(function* ( threadId: ThreadId, runIds?: ReadonlyArray, @@ -3538,7 +3585,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio candidate.id === item.messageId && candidate.runId === item.runId, ); - if (run === undefined || message === undefined || isActiveRun(run)) continue; + if ( + run === undefined || + message === undefined || + isActiveRun(run) || + (yield* awaitsCheckpointCapture(run)) + ) { + continue; + } // Stop drops a steer it reached; say so, as the adapter does for steers it still held. if (yield* projectionStore.hasRunInterruptRequest(threadId, run.id)) { const now = yield* DateTime.now; @@ -16612,6 +16666,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // dispatchWithReceiptEffect owns the dispatch span; this wrapper selects the thread locks. const dispatchWithReceipt = Effect.fnUntraced(function* (command: OrchestrationV2ServerCommand) { + // The latest stable run is the one with a checkpoint. Wait for a just-completed run's capture, + // outside the locks its commit takes, so a fork right after a turn starts from that turn. + if ( + (command.type === "thread.fork" || command.type === "thread.merge_back") && + command.sourcePoint.type === "latest_stable" + ) { + yield* awaitLatestRunCapture(command.sourceThreadId); + } const dispatch = threadDispatch.withLock( commandThreadId(command), dispatchWithReceiptEffect(command), @@ -16726,7 +16788,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Take parent and child locks sequentially, never nested: delegation holds the parent // while writing child events, so nesting parent inside child would invert the order. // The keyed semaphores are neither reentrant nor deadlock-aware. - if (delegatedTaskTerminalStatus(run.status) !== null) { + if ( + delegatedTaskTerminalStatus(run.status) !== null && + !(yield* awaitsCheckpointCapture(run)) + ) { // Before the parent hears of the failure: a pending continuation keeps the task open. if (run.status === "failed" && run.restartContinuationOfRunId !== undefined) { yield* threadDispatch.withLock(threadId, retryContinuationStart(threadId, run.id)).pipe( diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 3667867904ec..059ce4429a0c 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3050,7 +3050,7 @@ it.effect("settles native subagents when a workspace handoff completes the root assert.deepEqual(statusOf("turn-item.updated", runningTurnItem.id), ["interrupted"]); assert.deepEqual(statusOf("node.updated", runningNode.id), ["interrupted"]); assert.deepEqual(statusOf("node.updated", runningChildNode.id), ["interrupted"]); - assert.deepEqual(statusOf("run.updated", ids.runId), ["waiting"]); + assert.deepEqual(statusOf("run.updated", ids.runId), ["completed"]); assert.deepEqual(statusOf("run-attempt.updated", ids.attemptId), ["completed"]); assert.isFalse( events.some( @@ -3739,8 +3739,8 @@ it.effect.each([ : [], ), ended - ? ["run.updated:waiting", "subagent.updated:failed", "turn-item.updated:failed"] - : ["run.updated:waiting"], + ? ["run.updated:completed", "subagent.updated:failed", "turn-item.updated:failed"] + : ["run.updated:completed"], ); }), ); @@ -4013,7 +4013,7 @@ it.effect("keeps completed runs completed when pull request refresh fails", () = events: (ids) => Stream.make(rootTerminalEvent(ids, "completed")), refreshAfterTurn: Effect.die("refresh failed"), }); - assert.deepEqual(observed, ["run:waiting", "pull-requests-refreshed"]); + assert.deepEqual(observed, ["run:completed", "pull-requests-refreshed"]); }), ); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 21065b41a5f3..1f9383094904 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -846,20 +846,20 @@ export const layer: Layer.Layer< allocateEventId, }) : []; - const persistedStatus = - input.terminal.status === "completed" ? "waiting" : input.terminal.status; + // The run settles now; turn-end checkpoint capture follows on this thread's effect lane. + const persistedStatus = input.terminal.status; // Omit delegatedCompletion; the startup snapshot must not overwrite newer acknowledgements, successors, or Stop barriers. const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = input.run; const finalizedRun: OrchestrationV2Run = { ...runWithoutDelegatedCompletion, status: persistedStatus, - completedAt: input.terminal.status === "completed" ? null : completedAt, + completedAt, }; const finalizedRootNode: OrchestrationV2ExecutionNode = { ...input.rootNode, status: persistedStatus, - completedAt: input.terminal.status === "completed" ? null : completedAt, + completedAt, checkpointScopeId: input.checkpointScope.id, }; const finalizedProviderThread: OrchestrationV2ProviderThread = { diff --git a/apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts b/apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts index 3ca71f384eba..9d9a53893d49 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts @@ -1,6 +1,8 @@ import { assert, it } from "@effect/vitest"; import { CheckpointScopeId, CommandId, GitCommandError, RunId, ThreadId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -24,20 +26,26 @@ import * as RuntimeRequests from "./RuntimeRequestService.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; import * as ThreadTitles from "./ThreadTitleRegenerationService.ts"; -it.effect.each([ - ["starts the next turn after a post-capture Git status failure", false], - ["keeps the next turn queued when checkpoint capture fails", true], -] as const)("%s", ([, captureFails]) => { - const threadId = ThreadId.make("thread:finalization-queue"); - const runId = RunId.make("run:finalization-queue"); - const scopeId = CheckpointScopeId.make("scope:finalization-queue"); - const calls: string[] = []; - const checkpointFailure = new CheckpointCapture.CheckpointCaptureExecutionError({ - threadId, - runId, - scopeId, - cause: "checkpoint storage unavailable", - }); +const threadId = ThreadId.make("thread:finalization-queue"); +const runId = RunId.make("run:finalization-queue"); +const scopeId = CheckpointScopeId.make("scope:finalization-queue"); +const captureEffect = { + id: "effect:finalization-queue:capture", + commandId: CommandId.make("command:finalization-queue:capture"), + threadId, + request: { type: "checkpoint.capture" as const, runId, scopeId }, +}; +const startEffect = { + id: "effect:finalization-queue:start", + commandId: CommandId.make("command:finalization-queue:start"), + threadId, + request: { type: "provider-turn.start" as const, runId: RunId.make("run:next") }, +}; + +const makeWorker = ( + calls: string[], + capture: Effect.Effect, +) => { const projections = Layer.mock(ProjectionStore.ProjectionStoreV2)({ getCheckpointContext: () => Effect.succeed({ @@ -76,11 +84,7 @@ it.effect.each([ projections, observer, Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({ - execute: () => - Effect.gen(function* () { - calls.push("capture"); - if (captureFails) return yield* checkpointFailure; - }), + execute: () => Effect.sync(() => calls.push("capture")).pipe(Effect.andThen(capture)), }), ), ), @@ -106,25 +110,24 @@ it.effect.each([ ), ); const outbox = EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)); - const worker = EffectWorker.layer.pipe(Layer.provideMerge(Layer.merge(executor, outbox))); + return Layer.fresh(EffectWorker.layer.pipe(Layer.provideMerge(Layer.merge(executor, outbox)))); +}; +it.effect.each([ + ["starts the next turn after a post-capture Git status failure", false], + ["keeps the next turn queued when checkpoint capture fails", true], +] as const)("%s", ([, captureFails]) => { + const calls: string[] = []; + const checkpointFailure = new CheckpointCapture.CheckpointCaptureExecutionError({ + threadId, + runId, + scopeId, + cause: "checkpoint storage unavailable", + }); return Effect.gen(function* () { const queue = yield* EffectOutbox.EffectOutboxV2; const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2; - yield* queue.enqueue([ - { - id: "effect:finalization-queue:capture", - commandId: CommandId.make("command:finalization-queue:capture"), - threadId, - request: { type: "checkpoint.capture", runId, scopeId }, - }, - { - id: "effect:finalization-queue:start", - commandId: CommandId.make("command:finalization-queue:start"), - threadId, - request: { type: "provider-turn.start", runId: RunId.make("run:next") }, - }, - ]); + yield* queue.enqueue([captureEffect, startEffect]); assert.equal(yield* effectWorker.drain(2), captureFails ? 1 : 2); const captured = Option.getOrThrow(yield* queue.get("effect:finalization-queue:capture")); @@ -136,5 +139,32 @@ it.effect.each([ assert.deepEqual(calls, captureFails ? ["capture"] : ["capture", "refresh", "start"]); if (captureFails) assert.include(captured.lastError ?? "", "checkpoint storage unavailable"); else assert.equal(captured.lastError, null); - }).pipe(Effect.provide(Layer.fresh(worker))); + }).pipe(Effect.provide(makeWorker(calls, captureFails ? checkpointFailure : Effect.void))); +}); + +// A run completes before its capture, so the next turn's start is enqueued while capture runs. +it.effect("keeps a next turn started during capture behind that capture", () => { + const calls: string[] = []; + return Effect.gen(function* () { + const captureStarted = yield* Deferred.make(); + const releaseCapture = yield* Deferred.make(); + const capture = Deferred.succeed(captureStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseCapture)), + ); + return yield* Effect.gen(function* () { + const queue = yield* EffectOutbox.EffectOutboxV2; + const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* queue.enqueue([captureEffect]); + const draining = yield* Effect.forkChild(effectWorker.drain(2)); + yield* Deferred.await(captureStarted); + + yield* queue.enqueue([startEffect]); + assert.isTrue(Option.isNone(yield* queue.claimNext({ workerId: "second-slot" }))); + assert.deepEqual(calls, ["capture"]); + + yield* Deferred.succeed(releaseCapture, undefined); + assert.equal(yield* Fiber.join(draining), 2); + assert.deepEqual(calls, ["capture", "refresh", "start"]); + }).pipe(Effect.provide(makeWorker(calls, capture))); + }); }); diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index d199eea71440..424d2da83514 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -364,7 +364,7 @@ it.effect.each( (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); const projection = yield* orchestrator.getThreadProjection(threadId); const turn = projection.providerTurns[0]!; @@ -1448,7 +1448,7 @@ it.effect.each(["complete", "stop-before-end"] as const)( (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -1690,7 +1690,7 @@ it.effect.each(declinedSteerTimings)( (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -1762,7 +1762,7 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it" (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -1831,7 +1831,7 @@ it.effect("delivers agent messages queued behind /compact before a later one ste (event) => event.type === "run.updated" && event.payload.id === turnInput.runId && - (event.payload.status === "waiting" || event.payload.status === "completed"), + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -1963,7 +1963,7 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( const providerTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns.find( (candidate) => candidate.runAttemptId === turn.attemptId, )!; - const settled = yield* watchRun(turn.runId, "waiting"); + const settled = yield* watchRun(turn.runId, "completed"); yield* Queue.offer(harness.events, { type: "provider_turn.updated", driver, @@ -2365,7 +2365,7 @@ it.effect("keeps a held commentary draft before the steer when turn end flushes (event) => event.type === "run.updated" && event.payload.id === first.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); yield* Queue.offer(events, assistantItem("answer", "All fixed.", false)); yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false)); @@ -3538,7 +3538,7 @@ it.effect("replays an accepted steer after its target turn completes", () => (event) => event.type === "run.updated" && event.payload.id === accepted.run.id && - event.payload.status === "waiting", + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -3765,7 +3765,7 @@ it.effect.each(["next", "/goal ship it", "fresh next"])( (event) => event.type === "run.updated" && event.payload.id === started[0]!.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ), Stream.take(1), Stream.runDrain, @@ -3968,7 +3968,7 @@ it.effect("a side chat that opens with /goal gets its context on the next questi (event) => event.type === "provider-turn.updated" && event.payload.status === "running", ); const settled = yield* sideChatEvent( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ); yield* ask("goal", "/goal clear"); yield* worker.drain(); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 15ac7ecb8d3f..199ad9022f8d 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -223,9 +223,12 @@ function scenarioCommands(scenario: OrchestratorV2Scenario): ReadonlyArray projection.runtimeRequests.find((request) => request.status === "pending"); +// A run completes before its turn-end checkpoint capture; the scenario settles after both. const hasActiveRun = (projection: OrchestrationV2ThreadProjection) => - projection.runs.some((run) => - ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + projection.runs.some( + (run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status) || + (run.status === "completed" && run.checkpointId === null), ); const SCENARIO_WAIT_ATTEMPTS = 10_000; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 811279357d91..e1da0ecbde78 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -3197,7 +3197,7 @@ describe("orchestration v2 provider switching", () => { // The handoff itself is not a failure: the run completes once the session closes. const runSettled = yield* awaitEvent( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ); yield* orchestrator.dispatch({ type: "thread.metadata.update", @@ -4549,7 +4549,10 @@ describe("orchestration v2 provider switching", () => { } yield* worker.drain(); - const afterFirst = yield* waitForIdle(handoffThreadId); + yield* waitForIdle(handoffThreadId); + // The run completes before its checkpoint capture; let the capture finish first. + yield* worker.drain(); + const afterFirst = yield* orchestrator.getThreadProjection(handoffThreadId); const firstSession = afterFirst.providerSessions.find( (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId, ); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_after_root/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_after_root/output.ts index 1c2b65252879..71c37545f6af 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_after_root/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_after_root/output.ts @@ -40,14 +40,14 @@ export function assertClaudeBackgroundTaskAfterRootOutput( (event) => event.type === "run.updated" && event.runId === rootRun.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); const waitingRootNodeIndex = result.domainEvents.findIndex( (event) => event.type === "node.updated" && event.payload.runId === rootRun.id && event.payload.kind === "root_turn" && - event.payload.status === "waiting", + event.payload.status === "completed", ); const clearedRosterIndex = result.domainEvents.findIndex( (event, index) => diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/output.ts index 832c5dad4063..46dc67a7dc84 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/output.ts @@ -63,7 +63,7 @@ export function assertGrokBackgroundBashOutput( (event) => event.type === "run.updated" && event.payload.id === rootRun?.id && - (event.payload.status === "waiting" || event.payload.status === "completed"), + event.payload.status === "completed", ); assert.isAtLeast(rootTurnEndedAt, 0); assert.isBelow(rootTurnEndedAt, commandCompletedAt, "run 1 waited for the command to end"); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_background/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_background/output.ts index d9d6ef11697e..e26b84edded7 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_background/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_background/output.ts @@ -50,7 +50,7 @@ export function assertOpenCode2BackgroundOutput( (event) => event.type === "run.updated" && event.payload.id === rootRun?.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); const subagentDone = indexOf( (event) => diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/output.ts index 404efdf434e2..5e8422574ea1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/output.ts @@ -44,7 +44,7 @@ export function assertOpenCode2NestedBackgroundOutput( (event) => event.type === "run.updated" && event.payload.id === projection.runs[0]?.id && - event.payload.status === "waiting", + event.payload.status === "completed", ); const grandchildDone = indexOf( (event) => @@ -52,15 +52,16 @@ export function assertOpenCode2NestedBackgroundOutput( event.payload.id === grandchild.id && event.payload.status === "completed", ); - const runCompleted = indexOf( + // The run completes at turn end; its checkpoint capture settles after the grandchild. + const runCaptured = indexOf( (event) => event.type === "run.updated" && event.payload.id === projection.runs[0]?.id && - event.payload.status === "completed", + event.payload.checkpointId !== null, ); assert.isAtLeast(rootTurnEnded, 0); assert.isAbove(grandchildDone, rootTurnEnded, "the thread's turn ends before the grandchild"); - assert.isAbove(runCompleted, grandchildDone, "the run waits for the grandchild"); + assert.isAbove(runCaptured, grandchildDone, "the run's capture waits for the grandchild"); const shell = result.shellSnapshot.threads.find((thread) => thread.id === projection.thread.id); assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []); diff --git a/docs/internals/overview.md b/docs/internals/overview.md index 19029cd1d9f3..c204b93ecd70 100644 --- a/docs/internals/overview.md +++ b/docs/internals/overview.md @@ -78,12 +78,17 @@ what the newest client sends. ## Turn completion and checkpoints -A provider turn ending and its follow-up work settling are separate milestones. Orchestration -records provider turn and run state independently from -[run finalization](../../apps/server/src/orchestration-v2/RunFinalizationService.ts). A late -checkpoint or diff must not extend the recorded provider duration or keep the client showing -provider work as active. PR discovery after completion also checks that the checkout still matches -the thread's non-default branch and that a newer run is not active. +A provider turn ending and its follow-up work settling are separate milestones. A run is +`completed` when its provider turn ends, so clients stop showing it as active. The turn-end +checkpoint is captured afterwards by +[run finalization](../../apps/server/src/orchestration-v2/RunFinalizationService.ts), an outbox +effect on the thread's effect lane, which runs a thread's effects in order. Until that capture +commits, the completed run has no checkpoint record, and readers treat it as pending, not missing. +Command decisions still see the run as `waiting`, so steers, queued turns, rollback and restore +line up behind the capture exactly as they did when runs completed only after it. Runs stored as +`waiting` come from servers that completed a run only after capture. +PR discovery after completion also checks that the checkout still matches the thread's +non-default branch and that a newer run is not active. [Checkpoints](../../apps/server/src/checkpointing/CheckpointStore.ts) use hidden Git refs to capture workspace state without adding commits to the user's branch. A revert must coordinate