diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index cc570a9ef113d..a6be6d977dffc 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -10,6 +10,7 @@ import { NodeId, type OrchestrationV2DomainEvent, type OrchestrationV2Run, + type OrchestrationV2TurnItem, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -985,6 +986,271 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { }), ); + it.effect("keeps a waiting run waiting when Stop landed around finalization", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const stopThreadId = ThreadId.make("thread:checkpoint-capture-stop"); + const stopRunId = RunId.make("run:checkpoint-capture-stop"); + const stopScopeId = CheckpointScopeId.make("scope:checkpoint-capture-stop"); + const stopRootNodeId = NodeId.make("node:checkpoint-capture-stop-root"); + const stopProviderThreadId = ProviderThreadId.make("provider-thread:checkpoint-capture-stop"); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:thread"), + type: "thread.created", + threadId: stopThreadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: stopThreadId, + projectId, + title: "Checkpoint capture after stop", + 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, + }, + }); + const waitingRun: OrchestrationV2Run = { + id: stopRunId, + threadId: stopThreadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: stopProviderThreadId, + userMessageId: MessageId.make("message:checkpoint-capture-stop"), + rootNodeId: stopRootNodeId, + activeAttemptId: null, + status: "waiting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const waitingRootNode = { + id: stopRootNodeId, + threadId: stopThreadId, + runId: stopRunId, + parentNodeId: null, + rootNodeId: stopRootNodeId, + kind: "root_turn" as const, + status: "waiting" as const, + countsForRun: true, + providerThreadId: stopProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: stopScopeId, + startedAt: now, + completedAt: null, + }; + const scope = { + id: stopScopeId, + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + parentScopeId: null, + providerThreadId: stopProviderThreadId, + kind: "root_run" as const, + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo", + createdAt: now, + }; + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:provider-thread"), + type: "provider-thread.updated", + threadId: stopThreadId, + nodeId: stopRootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: stopProviderThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: stopThreadId, + ownerNodeId: stopRootNodeId, + 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:scope"), + type: "checkpoint-scope.created", + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + occurredAt: now, + payload: scope, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:baseline"), + type: "checkpoint.captured", + threadId: stopThreadId, + nodeId: stopRootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: CheckpointId.make("checkpoint:stop-baseline-0"), + threadId: stopThreadId, + scopeId: stopScopeId, + runId: null, + nodeId: stopRootNodeId, + parentCheckpointId: null, + ordinalWithinScope: 0, + appRunOrdinal: null, + ref: CheckpointRef.make("checkpoint-ref:stop-baseline-0"), + status: "ready", + files: [], + capturedAt: now, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:run"), + type: "run.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + providerInstanceId, + occurredAt: now, + payload: waitingRun, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:node"), + type: "node.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + providerInstanceId, + occurredAt: now, + payload: waitingRootNode, + }); + // Stop pressed while the provider terminal was finalizing: the request is recorded + // but no result exists yet, and the run's status still reads waiting. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-stop:request"), + type: "turn-item.updated", + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + providerInstanceId, + occurredAt: now, + payload: { + id: IdAllocator.derive.runSignalTurnItem({ + runId: stopRunId, + signal: "interrupt-request", + }), + threadId: stopThreadId, + runId: stopRunId, + nodeId: stopRootNodeId, + providerThreadId: stopProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 99, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_request", + message: "Stopped by user", + } satisfies OrchestrationV2TurnItem, + }); + + const captured = { + id: CheckpointId.make("checkpoint:stop-captured-1"), + threadId: stopThreadId, + scopeId: stopScopeId, + runId: stopRunId, + nodeId: stopRootNodeId, + parentCheckpointId: CheckpointId.make("checkpoint:stop-baseline-0"), + ordinalWithinScope: 1, + appRunOrdinal: 1, + ref: CheckpointRef.make("checkpoint-ref:stop-captured-1"), + status: "ready" as const, + files: [], + capturedAt: now, + }; + const commits = yield* Ref.make(0); + 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("baseline materialization must be skipped when ordinal 0 is ready"), + capture: () => Effect.succeed(captured), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe( + Effect.andThen(Ref.update(commits, (count) => count + 1)), + Effect.as({ committed: true } as never), + Effect.orDie, + ), + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2; + yield* service.execute({ + threadId: stopThreadId, + runId: stopRunId, + scopeId: stopScopeId, + }); + yield* service.execute({ + threadId: stopThreadId, + runId: stopRunId, + scopeId: stopScopeId, + }); + }).pipe(Effect.provide(layerCapture)); + + assert.equal(yield* Ref.get(commits), 1); + const projected = yield* projectionStore.getCheckpointCaptureContext(stopThreadId, { + runId: stopRunId, + scopeId: stopScopeId, + }); + assert.equal(projected.run?.status, "waiting"); + assert.equal(projected.run?.checkpointId, captured.id); + assert.isNull(projected.run?.completedAt); + assert.equal(projected.rootNode?.status, "waiting"); + assert.deepEqual([...projected.preservedCheckpointOrdinals].toSorted(), [0, 1]); + }), + ); + it.effect("completes a side chat run with a missing checkpoint and never touches git", () => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index dd7f27079a4e5..ad40fef5bb699 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -78,12 +78,22 @@ export const layer: Layer.Layer< context; // Stopped runs remain terminal; their checkpoint is the next message's rollback point. const stopped = run?.status === "interrupted" || run?.status === "cancelled"; + // Stop records an interrupt request without changing the run's status, so a Stop that + // lands around finalization is invisible to the status check. An unpaired request is + // the same signal: the run was stopped, even though the provider terminal already + // persisted it as waiting. + const hasUnpairedInterruptRequest = (runId: RunId) => + projections.hasUnpairedRunInterruptRequest( + input.threadId, + ids.derive.runSignalTurnItem({ runId, signal: "interrupt-request" }), + ids.derive.runSignalTurnItem({ runId, signal: "interrupt-result" }), + ); // A checkpoint on a settled run proves this at-least-once effect already committed. if ( run !== undefined && run.checkpointId !== null && - (run.status === "completed" || stopped) + (run.status === "completed" || stopped || (yield* hasUnpairedInterruptRequest(run.id))) ) { return; } @@ -244,6 +254,7 @@ export const layer: Layer.Layer< }), ); // Stop and deletion may commit while Git captures; reread under their lock before finalizing. + // An unpaired interrupt request is a Stop the persisted status does not show yet. yield* threadCommands.withLock( input.threadId, Effect.gen(function* () { @@ -255,7 +266,9 @@ export const layer: Layer.Layer< return; } const stoppedNow = - currentRun.status === "interrupted" || currentRun.status === "cancelled"; + currentRun.status === "interrupted" || + currentRun.status === "cancelled" || + (yield* hasUnpairedInterruptRequest(run.id)); if (currentRun.status !== "waiting" && !stoppedNow) { return; } diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e93b794b7ad71..58a4c9b163be7 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13187,10 +13187,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run === undefined || rootNode === undefined || run.activeAttemptId !== attempt.id || - run.status !== "running" || attempt.status === "pending" ) return; + // A run the provider already finished waits for its checkpoint; a Stop that landed + // around finalization still owns it until the interrupt result arrives. + if (run.status === "waiting") { + const stopPending = yield* projectionStore + .hasUnpairedRunInterruptRequest( + run.threadId, + idAllocator.derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-request" }), + idAllocator.derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-result" }), + ) + .pipe(mapDispatchError(input.command)); + if (!stopPending) return; + } else if (run.status !== "running") { + return; + } const emitEvent = emit(input.events, input.command); const base = { threadId: input.command.threadId, @@ -13712,7 +13725,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) return; const now = yield* DateTime.now; - if (stopped.providerTurn !== undefined && stoppedRun.status === "running") { + // A run the provider already finished may still be waiting for its checkpoint when + // the interrupt lands; settleInterruptedRun decides whether Stop owns it. + if ( + stopped.providerTurn !== undefined && + (stoppedRun.status === "running" || stoppedRun.status === "waiting") + ) { const output = yield* projectionStore .getThreadRecords(command.threadId, ["messages"], { messageRunIds: [stoppedRun.id], diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index fc52191d32b29..e4f6adbf97642 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -28,6 +28,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import * as EventStore from "./EventStore.ts"; import * as TestClock from "effect/testing/TestClock"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -1761,6 +1762,110 @@ it.effect("an unanswered Stop is flagged until Force stop ends the run with its }).pipe(Effect.provide(layerTest)), ); +it.effect.each([true, false])( + "settling an interrupt ends a run its provider finished only when Stop was accepted (%s)", + (stopAccepted) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make(`thread:stop-waiting-run:${stopAccepted}`); + yield* createWatchingThread(threadId, 8); + yield* send(threadId, "work", "start_immediately"); + const now = yield* DateTime.now; + const started = yield* orchestrator.getThreadProjection(threadId); + const run = started.runs[0]!; + const attempt = started.attempts[0]!; + const rootNode = started.nodes.find((node) => node.id === run.rootNodeId)!; + const providerThreadId = run.providerThreadId!; + const providerTurnId = ProviderTurnId.make("provider-turn:stop-waiting-run"); + const apply = (event: Omit) => + projections.apply({ + ...event, + id: EventId.make(`event:stop-waiting-run:${event.type}`), + threadId, + } as OrchestrationV2DomainEvent); + // The provider's completed terminal landed after Stop: the run waits for its checkpoint. + yield* apply({ + type: "run.updated", + runId: run.id, + occurredAt: now, + payload: { ...run, status: "waiting", startedAt: now, activeAttemptId: attempt.id }, + }); + yield* apply({ + type: "node.updated", + runId: run.id, + nodeId: rootNode.id, + occurredAt: now, + payload: { ...rootNode, status: "waiting" }, + }); + yield* apply({ + type: "run-attempt.updated", + occurredAt: now, + payload: { ...attempt, status: "completed", startedAt: now, completedAt: now }, + }); + yield* apply({ + type: "provider-turn.updated", + occurredAt: now, + payload: { + id: providerTurnId, + providerThreadId, + nodeId: rootNode.id, + runAttemptId: attempt.id, + nativeTurnRef: null, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + }, + }); + if (stopAccepted) { + yield* apply({ + type: "turn-item.updated", + runId: run.id, + occurredAt: now, + payload: { + id: IdAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: "interrupt-request", + }), + threadId, + runId: run.id, + nodeId: rootNode.id, + providerThreadId, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 1_000, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_request", + message: "Stopped by user", + }, + }); + } + + yield* orchestrator.dispatch({ + type: "thread.background-work.settle", + commandId: CommandId.make(`stop-waiting-run:${stopAccepted}:settle`), + threadId, + providerThreadId, + providerTurnId, + }); + const settled = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + settled.runs.map((candidate) => candidate.status), + [stopAccepted ? "interrupted" : "waiting"], + ); + assert.equal( + settled.turnItems.some((item) => item.type === "run_interrupt_result"), + stopAccepted, + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect.each(["Stop", "Force stop"] as const)( "%s ends a running run whose provider turn already completed", (action) =>