From 19928311f4b5de6504d7fee5bf9ed625576a7d5d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 20:55:32 +0000 Subject: [PATCH 1/3] test(server): an accepted Stop on a waiting run must not finalize it as completed Reproduces #41617: checkpoint capture turns a waiting run with an unpaired run_interrupt_request into completed. Co-Authored-By: Claude Opus 5.5 --- .../CheckpointCaptureService.test.ts | 245 ++++++++++++++++++ 1 file changed, 245 insertions(+) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index cc570a9ef113d..adff9130bf47f 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -500,6 +500,251 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { }), ); + // Stop can be accepted while the provider's successful terminal is being written: the run is + // then `waiting` with a stored request and no result, and capture is what settles it. + it.effect("ends a waiting run as interrupted when Stop was accepted before capture", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const now = yield* DateTime.now; + const stopThreadId = ThreadId.make("thread:checkpoint-capture-stop-race"); + const stopRunId = RunId.make("run:checkpoint-capture-stop-race"); + const stopScopeId = CheckpointScopeId.make("scope:checkpoint-capture-stop-race"); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:thread"), + type: "thread.created", + threadId: stopThreadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: stopThreadId, + projectId, + title: "Stop accepted before capture", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: stopThreadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:run"), + type: "run.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + providerInstanceId, + occurredAt: now, + payload: { + id: stopRunId, + threadId: stopThreadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId, + userMessageId: MessageId.make("message:checkpoint-capture-stop-race"), + rootNodeId, + activeAttemptId: null, + status: "waiting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:node"), + type: "node.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + providerInstanceId, + occurredAt: now, + payload: { + id: rootNodeId, + threadId: stopThreadId, + runId: stopRunId, + parentNodeId: null, + rootNodeId, + kind: "root_turn", + status: "waiting", + countsForRun: true, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: stopScopeId, + startedAt: now, + completedAt: null, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:provider-thread"), + type: "provider-thread.updated", + threadId: stopThreadId, + nodeId: rootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: providerThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: stopThreadId, + ownerNodeId: rootNodeId, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:scope"), + type: "checkpoint-scope.created", + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + occurredAt: now, + payload: { + id: stopScopeId, + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + parentScopeId: null, + providerThreadId, + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo", + createdAt: now, + }, + }); + const baseline = { + id: CheckpointId.make("checkpoint:stop-race-baseline-0"), + threadId: stopThreadId, + scopeId: stopScopeId, + runId: null, + nodeId: rootNodeId, + parentCheckpointId: null, + ordinalWithinScope: 0, + appRunOrdinal: null, + ref: CheckpointRef.make("checkpoint-ref:stop-race-baseline-0"), + status: "ready" as const, + files: [], + capturedAt: now, + }; + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:baseline"), + type: "checkpoint.captured", + threadId: stopThreadId, + nodeId: rootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: baseline, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop-race:interrupt-request"), + type: "turn-item.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + providerInstanceId, + occurredAt: now, + payload: { + id: ids.derive.runSignalTurnItem({ runId: stopRunId, signal: "interrupt-request" }), + threadId: stopThreadId, + runId: stopRunId, + nodeId: rootNodeId, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_request", + message: "Stopped by user", + }, + }); + + const committed = yield* Ref.make>([]); + const layerCapture = CheckpointCaptureService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), + repositoryScopes: () => Effect.succeed([]), + materializeBaselineCheckpoint: () => Effect.die("the baseline is already ready"), + capture: () => + Effect.succeed({ + ...baseline, + id: CheckpointId.make("checkpoint:stop-race-captured-1"), + runId: stopRunId, + parentCheckpointId: baseline.id, + ordinalWithinScope: 1, + appRunOrdinal: 1, + ref: CheckpointRef.make("checkpoint-ref:stop-race-captured-1"), + }), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Ref.set(committed, input.events).pipe(Effect.as({ committed: true } as never)), + }), + ), + ), + ); + + yield* CheckpointCaptureService.CheckpointCaptureServiceV2.pipe( + Effect.flatMap((service) => + service.execute({ threadId: stopThreadId, runId: stopRunId, scopeId: stopScopeId }), + ), + Effect.provide(layerCapture), + ); + + const events = yield* Ref.get(committed); + const runUpdated = events.find((event) => event.type === "run.updated"); + assert.equal( + runUpdated?.type === "run.updated" ? runUpdated.payload.status : undefined, + "interrupted", + ); + assert.isTrue( + events.some( + (event) => + event.type === "turn-item.updated" && event.payload.type === "run_interrupt_result", + ), + "the accepted Stop request must be paired with a result", + ); + }).pipe(Effect.provide(IdAllocator.layer)), + ); + // A stopped run is captured after it ends; by then the next root run, dispatched or queued, may // have re-created the thread's one root scope with its own node and time. it.effect.each([1, 2])( From f1b808fcb862253a4b6a9aeae4c816eeb265e597 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 21:25:01 +0000 Subject: [PATCH 2/3] fix(server): an accepted Stop no longer ends the run as completed A Stop accepted after the provider's turn had already ended (or racing its successful finish) stored only its request: the terminal had written the run as waiting, and checkpoint capture then settled it as completed, leaving the request unanswered. Checkpoint capture now rereads the run's Stop request under the thread lock when it finalizes a waiting run. An unanswered request ends the run and its root node as interrupted and writes the paired result with the request's reason, whichever provider turn the request names. Co-Authored-By: Claude Fable 5.2 --- .../CheckpointCaptureService.ts | 39 +++++++++- .../src/orchestration-v2/Orchestrator.ts | 3 +- .../orchestration-v2/RunExecutionService.ts | 35 +-------- .../SteeringCompletion.integration.test.ts | 73 +++++++++++++++++++ .../orchestration-v2/runInterruptResult.ts | 42 +++++++++++ 5 files changed, 155 insertions(+), 37 deletions(-) create mode 100644 apps/server/src/orchestration-v2/runInterruptResult.ts diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index dd7f27079a4e5..e6106f13bbbe9 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -21,6 +21,7 @@ import * as CheckpointService from "./CheckpointService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { makeInterruptResultTurnItem } from "./runInterruptResult.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; // Git processes are already capped server-wide; this keeps one thread from taking every slot. @@ -259,6 +260,19 @@ export const layer: Layer.Layer< if (currentRun.status !== "waiting" && !stoppedNow) { return; } + // A Stop accepted once the provider's turn had ended stored only its request: the + // terminal already wrote `waiting`. That Stop still wins, and gets its result here. + const stopSignals = stoppedNow + ? [] + : (yield* projections.getThreadRecords(input.threadId, ["turnItems"], { + turnItemTypes: ["run_interrupt_request", "run_interrupt_result"], + turnItemRunIds: [run.id], + })).turnItems; + const stopRequest = stopSignals.some((item) => item.type === "run_interrupt_result") + ? undefined + : stopSignals.find((item) => item.type === "run_interrupt_request"); + const settledStatus = + stopRequest === undefined ? ("completed" as const) : ("interrupted" as const); // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = currentRun; @@ -328,6 +342,27 @@ export const layer: Layer.Layer< completedAt: capturedAt, }), }, + ...(stopRequest?.type !== "run_interrupt_request" + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "turn-item.updated" as const, + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: makeInterruptResultTurnItem({ + idAllocator: ids, + run, + rootNode, + providerThread, + reason: stopRequest.message, + completedAt: capturedAt, + }), + }, + ]), { id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), type: "run.updated", @@ -340,7 +375,7 @@ export const layer: Layer.Layer< ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id } : { ...runWithoutDelegatedCompletion, - status: "completed", + status: settledStatus, completedAt: capturedAt, checkpointId: checkpoint.id, }, @@ -358,7 +393,7 @@ export const layer: Layer.Layer< occurredAt: capturedAt, payload: { ...rootNode, - status: "completed" as const, + status: settledStatus, completedAt: capturedAt, checkpointScopeId: scope.id, }, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e93b794b7ad71..e68233b910af3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -200,6 +200,7 @@ import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import * as RunExecutionService from "./RunExecutionService.ts"; +import { makeInterruptResultTurnItem } from "./runInterruptResult.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; @@ -13311,7 +13312,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* emitEvent({ ...base, type: "turn-item.updated", - payload: RunExecutionService.makeInterruptResultTurnItem({ + payload: makeInterruptResultTurnItem({ idAllocator, run, rootNode, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 21065b41a5f3e..3d7ee4c2b1125 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -57,6 +57,7 @@ import { makeProviderFailure, makeProviderFailureTurnItem, } from "@t3tools/provider-core/server/failure"; +import { makeInterruptResultTurnItem } from "./runInterruptResult.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; @@ -2410,37 +2411,3 @@ export const layer: Layer.Layer< * always set one, so a missing reason means a person stopped the run. */ export const USER_STOP_REASON = "Stopped by user"; - -export function makeInterruptResultTurnItem(input: { - readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; - readonly run: OrchestrationV2Run; - readonly rootNode: OrchestrationV2ExecutionNode; - readonly providerThread: OrchestrationV2ProviderThread; - readonly reason: string | undefined; - readonly completedAt: DateTime.Utc; -}): OrchestrationV2TurnItem { - return { - id: input.idAllocator.derive.runSignalTurnItem({ - runId: input.run.id, - signal: "interrupt-result", - }), - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - providerThreadId: input.providerThread.id, - providerTurnId: input.rootNode.providerTurnId, - nativeItemRef: null, - parentItemId: input.idAllocator.derive.runSignalTurnItem({ - runId: input.run.id, - signal: "interrupt-request", - }), - ordinal: input.run.ordinal * 100 + 98, - status: "interrupted", - title: "Interrupted", - startedAt: input.completedAt, - completedAt: input.completedAt, - updatedAt: input.completedAt, - type: "run_interrupt_result", - message: input.reason ?? "Stopped by the provider", - }; -} diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 0fc200d0c5715..8d57c5d5930f6 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -3446,6 +3446,79 @@ it.effect("queues a plain send behind the stopped queue and releases its hold", }), ); +it.effect( + "ends the run as interrupted when the provider finishes before an accepted Stop reaches it", + () => + Effect.gen(function* () { + const interruptReached = yield* Deferred.make(); + const releaseInterrupt = yield* Deferred.make(); + const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "stop-loses-to-completion", + false, + true, + Deferred.succeed(interruptReached, undefined).pipe( + Effect.andThen(Deferred.await(releaseInterrupt)), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + }); + const draining = yield* worker.drain().pipe(Effect.forkScoped); + yield* Deferred.await(interruptReached); + const waiting = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(waiting); + yield* Deferred.succeed(releaseInterrupt, undefined); + yield* Fiber.join(draining); + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const run = projection.runs.find((candidate) => candidate.id === first.runId); + assert.equal(run?.status, "interrupted"); + assert.isNotNull(run?.checkpointId); + assert.deepEqual( + projection.turnItems.flatMap((item) => + item.type === "run_interrupt_result" ? [item.message] : [], + ), + ["Stopped by user"], + ); + }).pipe(Effect.provide(layer)); + }), +); + const goalHarness = Effect.fn("goalHarness")(function* (name: string, nativeGoals?: boolean) { const harness = yield* nextTurnSelectionHarness( name, diff --git a/apps/server/src/orchestration-v2/runInterruptResult.ts b/apps/server/src/orchestration-v2/runInterruptResult.ts new file mode 100644 index 0000000000000..52423fda2d9a0 --- /dev/null +++ b/apps/server/src/orchestration-v2/runInterruptResult.ts @@ -0,0 +1,42 @@ +import type { + OrchestrationV2ExecutionNode, + OrchestrationV2ProviderThread, + OrchestrationV2Run, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import type * as DateTime from "effect/DateTime"; +import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; + +export function makeInterruptResultTurnItem(input: { + readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; + readonly run: OrchestrationV2Run; + readonly rootNode: OrchestrationV2ExecutionNode; + readonly providerThread: OrchestrationV2ProviderThread; + readonly reason: string | undefined; + readonly completedAt: DateTime.Utc; +}): OrchestrationV2TurnItem { + return { + id: input.idAllocator.derive.runSignalTurnItem({ + runId: input.run.id, + signal: "interrupt-result", + }), + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerThreadId: input.providerThread.id, + providerTurnId: input.rootNode.providerTurnId, + nativeItemRef: null, + parentItemId: input.idAllocator.derive.runSignalTurnItem({ + runId: input.run.id, + signal: "interrupt-request", + }), + ordinal: input.run.ordinal * 100 + 98, + status: "interrupted", + title: "Interrupted", + startedAt: input.completedAt, + completedAt: input.completedAt, + updatedAt: input.completedAt, + type: "run_interrupt_result", + message: input.reason ?? "Stopped by the provider", + }; +} From 60032081d9d2884cf9b446ddab1f11cffc55016a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 21:40:01 +0000 Subject: [PATCH 3/3] test(server): a task_cancel during checkpoint capture ends the child's run as interrupted The background-work cancel test still expected the stopped run to end completed when Stop was accepted while the run captured its checkpoint or just before its turn finished. Those are the cases the fix settles as interrupted. Co-Authored-By: Claude Fable 5.2 --- .../src/mcp/TaskCancelNativeSubagent.integration.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index aff11dacad26e..feafe872f8760 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -651,7 +651,11 @@ const cancelBackgroundOnlyTask = ( // Stop reached the provider turn that owns the shell. if (background === "command") assert.deepEqual(interrupted, [["bg-sleep"]]); assert.equal(childAfter.runs.length, cancelAt === "monitor" || cancelAt === "turn" ? 2 : 1); - assert.equal(childAfter.runs[0]!.status, "completed"); + // A Stop accepted before the run's checkpoint settled it ends that run as interrupted. + assert.equal( + childAfter.runs.find((run) => run.id === child.turn.runId)?.status, + cancelAt === "checkpoint" || cancelAt === "turn" ? "interrupted" : "completed", + ); assert.deepEqual( childAfter.runtimeRequests.map((request) => [request.id, request.status]), [