From 2a1807149e84e9ff1d890003c475610f35be6303 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 15:24:33 +0000 Subject: [PATCH 1/4] fix(server): guard checkpoint rollback and preserve uncertain outcomes --- .../src/checkpointing/CheckpointStore.test.ts | 112 +++++ .../src/checkpointing/CheckpointStore.ts | 5 + .../CheckpointRestoreSafety.test.ts | 4 +- .../CheckpointRestoreSafety.ts | 62 ++- .../CheckpointRollbackService.test.ts | 97 ++++- .../CheckpointRollbackService.ts | 402 ++++++++++++------ .../src/orchestration-v2/CheckpointService.ts | 81 ++-- .../src/orchestration-v2/EffectOutbox.ts | 57 ++- .../src/orchestration-v2/EffectWorker.test.ts | 123 +++--- .../src/orchestration-v2/EffectWorker.ts | 49 ++- .../FoundationPersistence.test.ts | 70 ++- .../src/orchestration-v2/Orchestrator.ts | 67 ++- .../testkit/ProviderReplayHarness.ts | 1 + apps/server/src/vcs/GitVcsDriver.ts | 90 ++++ apps/server/src/vcs/VcsDriver.ts | 1 + packages/contracts/src/orchestrationV2.ts | 3 + packages/contracts/src/vcs.ts | 10 + .../src/server/GitLabCli.ts | 1 + 18 files changed, 979 insertions(+), 256 deletions(-) diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 00b7437caba44..00e018daee444 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -134,6 +135,117 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { expect(yield* checkpointStore.isGitRepository(nested)).toBe(true); }), ); + describe("restoreCheckpoint", () => { + it.effect("restores tracked, staged and untracked files only inside the workspace", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const fs = yield* FileSystem.FileSystem; + const cwd = NodePath.join(tmp, "app"); + yield* fs.makeDirectory(cwd); + const tracked = NodePath.join(cwd, "tracked.txt"); + yield* writeTextFile(tracked, "committed\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "workspace"]); + const head = yield* git(tmp, ["rev-parse", "HEAD"]); + const store = yield* CheckpointStore.CheckpointStore; + const input = { + cwd, + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("restore-subtree"), 0), + }; + yield* writeTextFile(tracked, "checkpoint\n"); + yield* writeTextFile(NodePath.join(cwd, "captured.txt"), "captured untracked\n"); + yield* store.captureCheckpoint(input); + + yield* writeTextFile(tracked, "staged\n"); + yield* writeTextFile(NodePath.join(cwd, "staged-new.txt"), "staged addition\n"); + yield* writeTextFile(NodePath.join(tmp, "README.md"), "sibling staged\n"); + yield* git(tmp, ["add", "."]); + yield* writeTextFile(tracked, "unstaged\n"); + yield* fs.remove(NodePath.join(cwd, "captured.txt")); + yield* writeTextFile(NodePath.join(cwd, "untracked.txt"), "discard\n"); + yield* writeTextFile(NodePath.join(tmp, "outside.txt"), "keep\n"); + const siblingIndex = yield* git(tmp, ["diff", "--cached", "--", "README.md"]); + + expect(yield* store.restoreCheckpoint(input)).toBe(true); + expect(yield* fs.readFileString(tracked)).toBe("checkpoint\n"); + expect(yield* fs.readFileString(NodePath.join(cwd, "captured.txt"))).toBe( + "captured untracked\n", + ); + expect(yield* fs.exists(NodePath.join(cwd, "staged-new.txt"))).toBe(false); + expect(yield* fs.exists(NodePath.join(cwd, "untracked.txt"))).toBe(false); + expect(yield* git(tmp, ["diff", "--cached", "--", "app"])).toBe(""); + expect(yield* fs.readFileString(NodePath.join(tmp, "outside.txt"))).toBe("keep\n"); + expect(yield* fs.readFileString(NodePath.join(tmp, "README.md"))).toBe("sibling staged\n"); + expect(yield* git(tmp, ["diff", "--cached", "--", "README.md"])).toBe(siblingIndex); + expect(yield* git(tmp, ["rev-parse", "HEAD"])).toBe(head); + }), + ); + + it.effect("leaves files and the index untouched when the checkpoint ref is missing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const fs = yield* FileSystem.FileSystem; + const store = yield* CheckpointStore.CheckpointStore; + yield* writeTextFile(NodePath.join(tmp, "README.md"), "staged\n"); + yield* git(tmp, ["add", "README.md"]); + yield* writeTextFile(NodePath.join(tmp, "README.md"), "unstaged\n"); + yield* writeTextFile(NodePath.join(tmp, "untracked.txt"), "keep\n"); + const index = yield* fs.readFile(NodePath.join(tmp, ".git/index")); + + expect( + yield* store.restoreCheckpoint({ + cwd: tmp, + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("missing-restore"), 0), + fallbackToHead: false, + }), + ).toBe(false); + expect(yield* fs.readFileString(NodePath.join(tmp, "README.md"))).toBe("unstaged\n"); + expect(yield* fs.readFileString(NodePath.join(tmp, "untracked.txt"))).toBe("keep\n"); + expect(yield* fs.readFile(NodePath.join(tmp, ".git/index"))).toEqual(index); + }), + ); + }); + + it.effect("fingerprints all destructive restore inputs without changing the index", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const store = yield* CheckpointStore.CheckpointStore; + const fs = yield* FileSystem.FileSystem; + const readme = NodePath.join(tmp, "README.md"); + const before = yield* store.readWorkspaceFingerprint(tmp); + yield* writeTextFile(readme, "staged\n"); + yield* git(tmp, ["add", "README.md"]); + yield* writeTextFile(readme, "# test\n"); + const index = yield* fs.readFile(NodePath.join(tmp, ".git/index")); + const stagedOnly = yield* store.readWorkspaceFingerprint(tmp); + expect(stagedOnly).not.toBe(before); + yield* writeTextFile(readme, "working tree\n"); + const tracked = yield* store.readWorkspaceFingerprint(tmp); + expect(tracked).not.toBe(stagedOnly); + yield* writeTextFile(NodePath.join(tmp, "untracked.txt"), "untracked\n"); + const untracked = yield* store.readWorkspaceFingerprint(tmp); + expect(untracked).not.toBe(tracked); + expect(yield* store.readWorkspaceFingerprint(tmp)).toBe(untracked); + yield* git(tmp, ["config", "core.autocrlf", "true"]); + yield* writeTextFile(readme, "same normalized contents\n"); + const lf = yield* store.readWorkspaceFingerprint(tmp); + yield* writeTextFile(readme, "same normalized contents\r\n"); + expect(yield* store.readWorkspaceFingerprint(tmp)).not.toBe(lf); + if ((yield* HostProcess.Platform) !== "win32") { + const link = NodePath.join(tmp, "raw-target-link"); + yield* Effect.tryPromise(() => NodeFSP.symlink(Buffer.from([0xfe]), link)); + const firstTarget = yield* store.readWorkspaceFingerprint(tmp); + yield* fs.remove(link); + yield* Effect.tryPromise(() => NodeFSP.symlink(Buffer.from([0xff]), link)); + expect(yield* store.readWorkspaceFingerprint(tmp)).not.toBe(firstTarget); + } + expect(yield* fs.readFile(NodePath.join(tmp, ".git/index"))).toEqual(index); + }), + ); + describe("diffCheckpoints", () => { it.effect("returns full oversized checkpoint diffs without truncation", () => Effect.gen(function* () { diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index b740653a21b1e..005807b4c9224 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -44,6 +44,7 @@ export interface DeleteCheckpointRefsInput { export class CheckpointStore extends Context.Service< CheckpointStore, { + readonly readWorkspaceFingerprint: (cwd: string) => Effect.Effect; readonly isGitRepository: (cwd: string) => Effect.Effect; readonly captureCheckpoint: ( @@ -146,6 +147,10 @@ export const make = Effect.gen(function* () { }); return CheckpointStore.of({ + readWorkspaceFingerprint: (cwd) => + resolveCheckpoints("CheckpointStore.readWorkspaceFingerprint", cwd).pipe( + Effect.flatMap((ops) => ops.readWorkspaceFingerprint(cwd)), + ), isGitRepository, captureCheckpoint, hasCheckpointRef, diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index c6213056322cf..474a4b55ae8ab 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -1,3 +1,4 @@ +import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { @@ -106,6 +107,7 @@ it.effect.each([ const layerTest = CheckpointRollbackService.layer.pipe( Layer.provide( Layer.mergeAll( + Layer.mock(CheckpointStore.CheckpointStore)({}), NodeServices.layer, Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never), ServerSettings.layerTest(), @@ -192,7 +194,7 @@ it.effect.each([ const error = yield* service .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }) .pipe(Effect.flip); - assert.equal(error.reason, "shared-workspace"); + assert.equal("reason" in error ? error.reason : undefined, "shared-workspace"); assert.deepEqual(calls, []); assert.equal(yield* fs.readFileString(otherFile), "other thread's uncommitted work"); } else { diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts index 1327e17dbdb01..ce1bc8db2d85b 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts @@ -1,4 +1,13 @@ -import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts"; +import { CheckpointId, CheckpointScopeId, ThreadId } from "@t3tools/contracts"; +// Synchronous hashing keeps the command decision pure; only the bounded digest is persisted. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; +import * as Schema from "effect/Schema"; +import type { + OrchestrationV2AppThread, + OrchestrationV2CheckpointScope, + OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import type * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -96,3 +105,54 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi return !shared; }, ); + +const encodeRestoreState = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +// Excludes rollback request metadata, which admission itself updates. +export const checkpointRestoreThreadState = ( + projection: Pick< + OrchestrationV2ThreadProjection, + | "thread" + | "runs" + | "attempts" + | "providerTurns" + | "providerThreads" + | "checkpointScopes" + | "checkpoints" + >, +) => + NodeCrypto.createHash("sha256") + .update( + encodeRestoreState([ + projection.thread.archivedAt, + projection.thread.deletedAt, + projection.thread.worktreePath, + projection.thread.modelSelection, + projection.thread.activeProviderThreadId, + projection.runs, + projection.attempts, + projection.providerTurns, + projection.providerThreads, + projection.checkpointScopes, + projection.checkpoints, + ]), + ) + .digest("hex"); + +export const checkpointRestoreThreadIdle = ( + projection: Pick, +) => + projection.thread.archivedAt == null && + projection.thread.deletedAt == null && + !projection.runs.some((run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + ); + +export const CheckpointRestoreRejectedRequest = Schema.fromJsonString( + Schema.Struct({ + type: Schema.Literal("checkpoint_restore_rejected"), + threadId: ThreadId, + scopeId: CheckpointScopeId, + checkpointId: CheckpointId, + }), +); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index abb9f72f9ff04..3398b6ca05b97 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -1,3 +1,4 @@ +import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it, vi } from "@effect/vitest"; import { @@ -45,6 +46,10 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe( Layer.provide( Layer.mergeAll( NodeServices.layer, + Layer.mock(CheckpointStore.CheckpointStore)({ + hasCheckpointRef: () => Effect.succeed(true), + readWorkspaceFingerprint: () => Effect.succeed("workspace-before"), + }), Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never), ServerSettings.layerTest(), Layer.mock(GitWorkflow.GitWorkflowService)({}), @@ -150,7 +155,7 @@ it.effect.each(["initial", "waiting"])( assert.equal(getThreadRecords.mock.calls.length, 2); assert.deepEqual(getThreadRecords.mock.calls[0]?.[1], []); assert.equal(getThreadRecords.mock.calls[1]?.[1].includes("checkpoints"), true); - assert.equal(error.reason, "rollback-target-invalid"); + assert.equal("reason" in error ? error.reason : undefined, "rollback-target-invalid"); assert.equal( error.message, `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`, @@ -230,7 +235,7 @@ it.effect("rejects a rollback when another provider thread became active", () => }) .pipe(Effect.flip); - assert.equal(error.reason, "active-provider-changed"); + assert.equal("reason" in error ? error.reason : undefined, "active-provider-changed"); assert.equal( error.message, `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`, @@ -311,7 +316,7 @@ it.effect("rejects a rollback when provider selection changed before execution", }) .pipe(Effect.flip); - assert.equal(error.reason, "active-provider-changed"); + assert.equal("reason" in error ? error.reason : undefined, "active-provider-changed"); assert.equal( error.message, `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`, @@ -384,7 +389,7 @@ it.effect("rejects an unavailable rollback target before opening a session", () .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles: false }) .pipe(Effect.flip); assert.equal(open.mock.calls.length, 0); - assert.equal(error.reason, "provider-turn-unavailable"); + assert.equal("reason" in error ? error.reason : undefined, "provider-turn-unavailable"); assert.equal( error.message, `Provider turn for rollback target ${checkpointId} is unavailable on provider thread ${providerThreadId}.`, @@ -449,6 +454,7 @@ it.effect.each([ Layer.mergeAll( ThreadCommandExecutor.layer, NodeServices.layer, + Layer.mock(CheckpointStore.CheckpointStore)({}), Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never), ServerSettings.layerTest(), Layer.mock(ProjectStore.ProjectStoreV2)({ @@ -581,9 +587,19 @@ it.effect.each([ { restoreFiles: true, shared: "historical" }, { restoreFiles: false, shared: "none", targetOrdinal: 1 }, { restoreFiles: false, shared: "none", targetOrdinal: 1, multipleTurns: true }, + { restoreFiles: true, shared: "none", guarded: true, queued: true }, + { restoreFiles: true, shared: "none", guarded: true, persistFails: true }, ])( "rewinds safely with %s", - ({ restoreFiles, shared, targetOrdinal = 0, multipleTurns = false }) => { + ({ + restoreFiles, + shared, + targetOrdinal = 0, + multipleTurns = false, + guarded = false, + queued = false, + persistFails = false, + }) => { const threadId = ThreadId.make("rewind-files"); const providerThreadId = ProviderThreadId.make("rewind-provider"); const providerSessionId = ProviderSessionId.make("rewind-session"); @@ -591,6 +607,10 @@ it.effect.each([ const checkpointId = CheckpointId.make("rewind-start"); const scopeId = CheckpointScopeId.make("rewind-scope"); const calls: string[] = []; + const persistenceError = new EventSink.EventSinkWriteError({ + eventCount: 3, + cause: "storage unavailable after restore", + }); let lockedThreads = Effect.succeed>([]); const layerThreadCommands = Layer.effect( ThreadCommandExecutor.ThreadCommandExecutor, @@ -636,13 +656,19 @@ it.effect.each([ nodes: [], attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, runId: `run-${ordinal}` })), checkpoints: [ - { id: checkpointId, scopeId, status: "ready", appRunOrdinal: targetOrdinal || null }, + { + id: checkpointId, + scopeId, + status: "ready", + appRunOrdinal: guarded ? targetOrdinal : targetOrdinal || null, + ordinalWithinScope: 0, + }, ], checkpointScopes: [{ id: scopeId, cwd: process.cwd() }], - runs: [1, 2, 3].map((ordinal) => ({ + runs: [1, 2, 3, ...(queued ? [4] : [])].map((ordinal) => ({ id: `run-${ordinal}`, ordinal, - status: ordinal === 3 ? "rolled_back" : "completed", + status: ordinal === 4 ? "queued" : ordinal === 3 ? "rolled_back" : "completed", rootNodeId: null, activeAttemptId: `attempt-${ordinal}`, })), @@ -652,6 +678,14 @@ it.effect.each([ Layer.mergeAll( layerThreadCommands, Layer.mock(CheckpointService.CheckpointServiceV2)({ + withRestoreLock: (_cwd, use) => + use({ + restore: () => + Effect.sync(() => { + calls.push("files"); + }), + deleteStaleRefs: () => Effect.void, + }), restore: () => Effect.sync(() => { calls.push("files"); @@ -659,7 +693,7 @@ it.effect.each([ }), Layer.mock(EventSink.EventSinkV2)({ write: ({ events }) => - Effect.map(lockedThreads, (locked) => { + Effect.flatMap(lockedThreads, (locked) => { assert.include(locked, threadId); assert.ok( events.some( @@ -668,7 +702,7 @@ it.effect.each([ ), ); calls.push("projection"); - return []; + return persistFails ? Effect.fail(persistenceError) : Effect.succeed([]); }), }), IdAllocator.layer, @@ -701,6 +735,15 @@ it.effect.each([ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open: () => Effect.succeed({ + providerSession: { + capabilities: { + threads: { canRollbackThread: true }, + checkpointing: { + providerCanRollbackConversation: true, + providerRollbackReturnsSnapshot: true, + }, + }, + }, rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) => Effect.gen(function* () { const count = yield* resolveCodexRollbackTurnCount(input); @@ -720,11 +763,41 @@ it.effect.each([ const error = yield* Effect.flip( service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }), ); - assert.equal(error.reason, "shared-workspace"); + assert.equal("reason" in error ? error.reason : undefined, "shared-workspace"); assert.deepEqual(calls, []); return; } - yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }); + const request = { + threadId, + providerThreadId, + checkpointId, + scopeId, + restoreFiles, + ...(guarded + ? { expectedIdle: true as const, expectedWorkspaceFingerprint: "workspace-before" } + : {}), + }; + if (queued) { + const error = yield* service + .execute(request) + .pipe(Effect.match({ onFailure: (cause) => cause, onSuccess: () => null })); + assert.deepEqual(calls, []); + assert.equal( + error !== null && "reason" in error ? error.reason : undefined, + "thread-not-idle", + ); + return; + } + if (persistFails) { + const error = yield* service.execute(request).pipe(Effect.flip); + assert.equal(error._tag, "CheckpointRollbackPartialError"); + assert.strictEqual(error.cause, persistenceError); + assert.include(calls, "provider"); + assert.include(calls, "files"); + assert.equal(calls.filter((call) => call === "provider").length, 1); + return; + } + yield* service.execute(request); assert.deepEqual( calls, restoreFiles ? ["provider", "files", "projection"] : ["provider", "projection"], diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index abacb6d666a96..4f6a21f221c44 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -1,11 +1,13 @@ import { CheckpointId, + checkpointRollbackAppRunOrdinal, CheckpointScopeId, latestProviderTurnForAttempt, type OrchestrationV2DomainEvent, ProviderThreadId, ThreadId, } from "@t3tools/contracts"; +import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -22,6 +24,8 @@ import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { isCheckpointRestoreIsolated, + checkpointRestoreThreadState, + checkpointRestoreThreadIdle, SHARED_WORKSPACE_RESTORE_MESSAGE, } from "./CheckpointRestoreSafety.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; @@ -46,6 +50,9 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError()( + "CheckpointRollbackPartialError", + { + threadId: ThreadId, + checkpointId: CheckpointId, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return ROLLBACK_PARTIAL_MESSAGE; + } +} +const isCheckpointRollbackError = Schema.is( + Schema.Union([CheckpointRollbackExecutionError, CheckpointRollbackPartialError]), +); export interface CheckpointRollbackServiceV2Shape { readonly execute: (input: { @@ -78,7 +108,10 @@ export interface CheckpointRollbackServiceV2Shape { readonly checkpointId: CheckpointId; readonly scopeId: CheckpointScopeId; readonly restoreFiles?: boolean; - }) => Effect.Effect; + readonly expectedIdle?: true; + readonly expectedWorkspaceFingerprint?: string; + readonly expectedThreadState?: string; + }) => Effect.Effect; } export class CheckpointRollbackServiceV2 extends Context.Service< @@ -90,6 +123,7 @@ export const layer: Layer.Layer< CheckpointRollbackServiceV2, never, | CheckpointServiceV2 + | CheckpointStore.CheckpointStore | GitWorkflowService.GitWorkflowService | EventSinkV2 | IdAllocator.IdAllocatorV2 @@ -106,6 +140,7 @@ export const layer: Layer.Layer< CheckpointRollbackServiceV2, Effect.gen(function* () { const checkpoints = yield* CheckpointServiceV2; + const checkpointStore = yield* CheckpointStore.CheckpointStore; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; const eventSink = yield* EventSinkV2; const ids = yield* IdAllocator.IdAllocatorV2; @@ -124,7 +159,21 @@ export const layer: Layer.Layer< readonly checkpointId: CheckpointId; readonly scopeId: CheckpointScopeId; readonly restoreFiles?: boolean; + readonly expectedIdle?: true; + readonly expectedWorkspaceFingerprint?: string; + readonly expectedThreadState?: string; }) { + const guarded = + input.expectedIdle === true || + input.expectedWorkspaceFingerprint !== undefined || + input.expectedThreadState !== undefined; + const reject = (reason: CheckpointRollbackExecutionError["reason"]) => + new CheckpointRollbackExecutionError({ + reason, + threadId: input.threadId, + providerThreadId: input.providerThreadId, + checkpointId: input.checkpointId, + }); const projection = yield* projections.getThreadRecords(input.threadId, [ "providerThreads", "providerSessions", @@ -169,7 +218,24 @@ export const layer: Layer.Layer< }); } - const targetOrdinal = checkpoint.appRunOrdinal ?? 0; + if (guarded && !checkpointRestoreThreadIdle(projection)) + return yield* reject("thread-not-idle"); + if ( + input.expectedThreadState !== undefined && + input.expectedThreadState !== checkpointRestoreThreadState(projection) + ) + return yield* reject("restore-precondition-changed"); + if ( + guarded && + scope.providerThreadId !== null && + scope.providerThreadId !== undefined && + scope.providerThreadId !== providerThread.id + ) + return yield* reject("active-provider-changed"); + const targetOrdinal = guarded + ? checkpointRollbackAppRunOrdinal(checkpoint, scope) + : (checkpoint.appRunOrdinal ?? 0); + if (targetOrdinal === null) return yield* reject("rollback-target-invalid"); const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget = targetOrdinal === 0 ? { @@ -237,161 +303,223 @@ export const layer: Layer.Layer< }); } - const modelSelection = projection.thread.modelSelection; - const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ - thread: projection.thread, - modelSelection, - }); - const existingSession = projection.providerSessions.find( - (candidate) => candidate.id === providerThread.providerSessionId, - ); - const session = yield* sessions.open({ - threadId: input.threadId, - providerSessionId: providerThread.providerSessionId, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }), - ...(providerThread.nativeThreadRef?.nativeId == null - ? {} - : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }), - ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined - ? {} - : { - initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion, - }), - }); + const providerSessionId = providerThread.providerSessionId; + let mutationStarted = false; + const run = ( + operations: Pick, + ) => + Effect.gen(function* () { + if (guarded) { + if ( + !(yield* checkpointStore.hasCheckpointRef({ + cwd: scope.cwd, + checkpointRef: checkpoint.ref, + })) + ) + return yield* reject("rollback-target-invalid"); + if ( + input.expectedWorkspaceFingerprint !== undefined && + (yield* checkpointStore.readWorkspaceFingerprint(scope.cwd)) !== + input.expectedWorkspaceFingerprint + ) + return yield* reject("restore-precondition-changed"); + } + const modelSelection = projection.thread.modelSelection; + const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ + thread: projection.thread, + modelSelection, + }); + const existingSession = projection.providerSessions.find( + (candidate) => candidate.id === providerSessionId, + ); + const session = yield* sessions.open({ + threadId: input.threadId, + providerSessionId, + modelSelection, + runtimePolicy: resolvedRuntimePolicy, + ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }), + ...(providerThread.nativeThreadRef?.nativeId == null + ? {} + : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }), + ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined + ? {} + : { + initialProviderItemIdentityVersion: + providerThread.nativeMetadata.itemIdentityVersion, + }), + }); - const runsToRollback = projection.runs.filter( - (run) => - run.ordinal > targetOrdinal && - (run.status === "completed" || - run.status === "interrupted" || - run.status === "failed" || - run.status === "cancelled"), - ); - // Rolled-back turns stay in the audit history, but no longer exist in - // the provider conversation and must not be counted by a later rewind. - const rolledBackRunIds = new Set( - projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), - ); - const rolledBackAttemptIds = new Set( - projection.attempts - .filter((attempt) => rolledBackRunIds.has(attempt.runId)) - .map((attempt) => attempt.id), - ); - const providerThreadTurns = projection.providerTurns.filter( - (turn) => - turn.providerThreadId === providerThread.id && - (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)), - ); + if ( + guarded && + (!session.providerSession.capabilities.threads.canRollbackThread || + !session.providerSession.capabilities.checkpointing.providerCanRollbackConversation || + !session.providerSession.capabilities.checkpointing.providerRollbackReturnsSnapshot) + ) + return yield* reject("provider-rollback-unsupported"); - const snapshot = - runsToRollback.length === 0 - ? { providerThread } - : yield* session.rollbackThread({ - providerThread, - target: rollbackTarget, - providerThreadTurns, - }); - if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint }); - const staleCheckpoints = projection.checkpoints.filter( - (candidate) => - candidate.scopeId === scope.id && - candidate.appRunOrdinal !== null && - candidate.appRunOrdinal > targetOrdinal && - candidate.status === "ready", - ); - if (staleCheckpoints.length > 0) { - yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints }); - } + const runsToRollback = projection.runs.filter( + (run) => + run.ordinal > targetOrdinal && + (run.status === "completed" || + run.status === "interrupted" || + run.status === "failed" || + run.status === "cancelled"), + ); + // Rolled-back turns stay in the audit history, but no longer exist in + // the provider conversation and must not be counted by a later rewind. + const rolledBackRunIds = new Set( + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), + ); + const rolledBackAttemptIds = new Set( + projection.attempts + .filter((attempt) => rolledBackRunIds.has(attempt.runId)) + .map((attempt) => attempt.id), + ); + const providerThreadTurns = projection.providerTurns.filter( + (turn) => + turn.providerThreadId === providerThread.id && + (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)), + ); - // Thread commands write full provider thread rows under this lock. Without - // it, a message sent during the rollback can plan against the old native - // session and commit after this, undoing the provider's fork. - yield* threadCommands.withLock( - input.threadId, - Effect.gen(function* () { - const now = yield* DateTime.now; - const makeEvent = (event: Omit) => - Effect.map( - ids.allocate.event({ threadId: event.threadId }), - (id) => - ({ - ...event, - id, - }) as Event, - ); - const events: Array = []; - events.push( - yield* makeEvent({ - type: "provider-thread.updated", - threadId: input.threadId, - driver: providerThread.driver, - providerInstanceId: providerThread.providerInstanceId, - occurredAt: now, - payload: { - ...snapshot.providerThread, - lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal, - updatedAt: now, - }, - }), + mutationStarted = runsToRollback.length > 0 || input.restoreFiles !== false; + const snapshot = + runsToRollback.length === 0 + ? { providerThread } + : yield* session.rollbackThread({ + providerThread, + target: rollbackTarget, + providerThreadTurns, + }); + if (input.restoreFiles !== false) yield* operations.restore({ scope, checkpoint }); + const staleCheckpoints = projection.checkpoints.filter( + (candidate) => + candidate.scopeId === scope.id && + candidate.appRunOrdinal !== null && + candidate.appRunOrdinal > targetOrdinal && + candidate.status === "ready", ); - for (const staleCheckpoint of staleCheckpoints) { - events.push( - yield* makeEvent({ - type: "checkpoint.captured", - threadId: input.threadId, - ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }), - nodeId: staleCheckpoint.nodeId, - providerInstanceId: providerThread.providerInstanceId, - occurredAt: now, - payload: { ...staleCheckpoint, status: "stale" }, - }), - ); + if (staleCheckpoints.length > 0) { + yield* operations.deleteStaleRefs({ scope, checkpoints: staleCheckpoints }); } - for (const run of runsToRollback) { - const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId); - events.push( - yield* makeEvent({ - type: "run.updated", - threadId: input.threadId, - runId: run.id, - ...(rootNode === undefined ? {} : { nodeId: rootNode.id }), - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...run, status: "rolled_back", completedAt: now }, - }), - ); - if (rootNode !== undefined) { + + // Thread commands write full provider thread rows under this lock. Without + // it, a message sent during the rollback can plan against the old native + // session and commit after this, undoing the provider's fork. + yield* ( + guarded + ? (effect: Effect.Effect) => effect + : (effect: Effect.Effect) => + threadCommands.withLock(input.threadId, effect) + )( + Effect.gen(function* () { + const now = yield* DateTime.now; + const makeEvent = ( + event: Omit, + ) => + Effect.map( + ids.allocate.event({ threadId: event.threadId }), + (id) => + ({ + ...event, + id, + }) as Event, + ); + const events: Array = []; events.push( yield* makeEvent({ - type: "node.updated", + type: "provider-thread.updated", threadId: input.threadId, - runId: run.id, - nodeId: rootNode.id, - providerInstanceId: run.providerInstanceId, + driver: providerThread.driver, + providerInstanceId: providerThread.providerInstanceId, occurredAt: now, - payload: { ...rootNode, status: "rolled_back", completedAt: now }, + payload: { + ...snapshot.providerThread, + lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal, + updatedAt: now, + }, }), ); - } - } - yield* eventSink.write({ events }); - }), - ); + for (const staleCheckpoint of staleCheckpoints) { + events.push( + yield* makeEvent({ + type: "checkpoint.captured", + threadId: input.threadId, + ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }), + nodeId: staleCheckpoint.nodeId, + providerInstanceId: providerThread.providerInstanceId, + occurredAt: now, + payload: { ...staleCheckpoint, status: "stale" }, + }), + ); + } + for (const run of runsToRollback) { + const rootNode = projection.nodes.find( + (candidate) => candidate.id === run.rootNodeId, + ); + events.push( + yield* makeEvent({ + type: "run.updated", + threadId: input.threadId, + runId: run.id, + ...(rootNode === undefined ? {} : { nodeId: rootNode.id }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "rolled_back", completedAt: now }, + }), + ); + if (rootNode !== undefined) { + events.push( + yield* makeEvent({ + type: "node.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...rootNode, status: "rolled_back", completedAt: now }, + }), + ); + } + } + yield* eventSink.write({ events }); + }), + ); + }).pipe( + Effect.catchCause((cause) => { + if (mutationStarted) + return Effect.fail( + new CheckpointRollbackPartialError({ + threadId: input.threadId, + checkpointId: input.checkpointId, + cause: cause.reasons.find((reason) => reason._tag === "Fail")?.error ?? cause, + }), + ); + return Effect.failCause(cause); + }), + ); + yield* guarded ? checkpoints.withRestoreLock(scope.cwd, run) : run(checkpoints); }); + const guardedExecute = ( + input: Parameters[0], + ) => + input.expectedIdle === true || + input.expectedWorkspaceFingerprint !== undefined || + input.expectedThreadState !== undefined + ? threadCommands.withLock(input.threadId, execute(input)) + : execute(input); + return CheckpointRollbackServiceV2.of({ execute: (input) => Effect.gen(function* () { // Storage cleanup removes worktrees under the same lease. const { thread } = yield* projections.getThreadRecords(input.threadId, []); yield* thread.worktreePath === null - ? execute(input) - : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input)); + ? guardedExecute(input) + : withWorkspaceLease(path.resolve(thread.worktreePath), guardedExecute(input)); }).pipe( Effect.mapError((cause) => - isCheckpointRollbackExecutionError(cause) + isCheckpointRollbackError(cause) ? cause : new CheckpointRollbackExecutionError({ reason: "unexpected-failure", diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index b49da7740b82c..aae113c0b61c1 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -116,6 +116,12 @@ export type CheckpointServiceV2Error = typeof CheckpointServiceV2Error.Type; const isCheckpointRestoreError = Schema.is(CheckpointRestoreError); export interface CheckpointServiceV2Shape { + readonly withRestoreLock: ( + cwd: string, + use: ( + operations: Pick, + ) => Effect.Effect, + ) => Effect.Effect; readonly prepareRootRunScope: (input: { readonly threadId: ThreadId; readonly runId: RunId; @@ -509,31 +515,28 @@ export const layer: Layer.Layer< ); const restore: CheckpointServiceV2Shape["restore"] = (input) => - withWorkspaceLock( - input.scope.cwd, - Effect.gen(function* () { - if (input.checkpoint.status !== "ready") { - return yield* new CheckpointRestoreError({ - scopeId: input.scope.id, - checkpointId: input.checkpoint.id, - cause: `Checkpoint status is ${input.checkpoint.status}.`, - }); - } + Effect.gen(function* () { + if (input.checkpoint.status !== "ready") { + return yield* new CheckpointRestoreError({ + scopeId: input.scope.id, + checkpointId: input.checkpoint.id, + cause: `Checkpoint status is ${input.checkpoint.status}.`, + }); + } - const restored = yield* checkpointStore.restoreCheckpoint({ - cwd: input.scope.cwd, - checkpointRef: input.checkpoint.ref, - fallbackToHead: false, + const restored = yield* checkpointStore.restoreCheckpoint({ + cwd: input.scope.cwd, + checkpointRef: input.checkpoint.ref, + fallbackToHead: false, + }); + if (!restored) { + return yield* new CheckpointRestoreError({ + scopeId: input.scope.id, + checkpointId: input.checkpoint.id, + cause: "Checkpoint ref is unavailable.", }); - if (!restored) { - return yield* new CheckpointRestoreError({ - scopeId: input.scope.id, - checkpointId: input.checkpoint.id, - cause: "Checkpoint ref is unavailable.", - }); - } - }), - ).pipe( + } + }).pipe( Effect.mapError((cause) => isCheckpointRestoreError(cause) ? cause @@ -546,22 +549,21 @@ export const layer: Layer.Layer< ); const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) => - withWorkspaceLock( - input.scope.cwd, - checkpointStore.deleteCheckpointRefs({ + checkpointStore + .deleteCheckpointRefs({ cwd: input.scope.cwd, checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref), - }), - ).pipe( - Effect.mapError( - (cause) => - new CheckpointDeleteStaleRefsError({ - scopeId: input.scope.id, - checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id), - cause, - }), - ), - ); + }) + .pipe( + Effect.mapError( + (cause) => + new CheckpointDeleteStaleRefsError({ + scopeId: input.scope.id, + checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id), + cause, + }), + ), + ); return CheckpointServiceV2.of({ prepareRootRunScope: (input) => @@ -579,8 +581,9 @@ export const layer: Layer.Layer< captureBaseline, materializeBaselineCheckpoint, capture, - restore, - deleteStaleRefs, + withRestoreLock: (cwd, use) => withWorkspaceLock(cwd, use({ restore, deleteStaleRefs })), + restore: (input) => withWorkspaceLock(input.scope.cwd, restore(input)), + deleteStaleRefs: (input) => withWorkspaceLock(input.scope.cwd, deleteStaleRefs(input)), } satisfies CheckpointServiceV2Shape); }), ); diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index cb41dc7365123..ec5326ec4f7a2 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -83,6 +83,9 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ }), Schema.Struct({ type: Schema.Literal("provider-thread.rollback"), + expectedIdle: Schema.optional(Schema.Literal(true)), + expectedWorkspaceFingerprint: Schema.optional(Schema.String), + expectedThreadState: Schema.optional(Schema.String), restoreFiles: Schema.optional(Schema.Boolean), providerThreadId: ProviderThreadId, checkpointId: CheckpointId, @@ -151,10 +154,22 @@ export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Typ * are re-enqueued only around one server restart, so a week is far longer than * either and leaves recent history for debugging. Failed rows are kept: storage * cleanup keeps a deleted thread's worktree while any of its effects failed. + * Guarded restore outcomes also stay: their request keys promise durable results. */ export const SETTLED_EFFECT_RETENTION = Duration.days(7); const PRUNE_BATCH_SIZE = 500; +export const OrchestrationEffectFailureCodeV2 = Schema.Literals([ + "checkpoint_restore_rejected", + "checkpoint_restore_partial", +]); +export type OrchestrationEffectFailureCodeV2 = typeof OrchestrationEffectFailureCodeV2.Type; +export const isGuardedCheckpointRestore = (request: OrchestrationEffectRequestV2) => + request.type === "provider-thread.rollback" && + (request.expectedIdle === true || + request.expectedWorkspaceFingerprint !== undefined || + request.expectedThreadState !== undefined); + export interface OrchestrationEffectV2 { readonly id: string; readonly commandId: CommandId; @@ -169,6 +184,7 @@ export interface OrchestrationEffectV2 { readonly updatedAt: string; readonly completedAt: string | null; readonly lastError: string | null; + readonly failureCode?: OrchestrationEffectFailureCodeV2; } export interface PendingOrchestrationEffectV2 { @@ -238,6 +254,7 @@ export interface EffectOutboxV2Shape { readonly delayMs: number; }) => Effect.Effect; readonly fail: (input: { + readonly failureCode?: OrchestrationEffectFailureCodeV2; readonly effectId: string; readonly workerId: string; readonly error: string; @@ -271,6 +288,23 @@ const decodeRequest = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationEffectRequestV2), ); +const StoredEffectFailure = Schema.fromJsonString( + Schema.Struct({ code: OrchestrationEffectFailureCodeV2, message: Schema.String }), +); +const encodeStoredFailure = Schema.encodeSync(StoredEffectFailure); +const decodeStoredFailure = Schema.decodeUnknownOption(StoredEffectFailure); +const FAILURE_PREFIX = "t3-effect-failure:"; +const storedFailure = (message: string, code?: OrchestrationEffectFailureCodeV2) => + code === undefined ? message : FAILURE_PREFIX + encodeStoredFailure({ code, message }); +const readFailure = (value: string | null) => { + const decoded = value?.startsWith(FAILURE_PREFIX) + ? decodeStoredFailure(value.slice(FAILURE_PREFIX.length)) + : Option.none(); + return Option.isSome(decoded) + ? { lastError: decoded.value.message, failureCode: decoded.value.code } + : { lastError: value }; +}; + const rowToEffect = (row: EffectRow) => decodeRequest(row.payload_json).pipe( Effect.map((request): OrchestrationEffectV2 => ({ @@ -286,7 +320,7 @@ const rowToEffect = (row: EffectRow) => createdAt: row.created_at, updatedAt: row.updated_at, completedAt: row.completed_at, - lastError: row.last_error, + ...readFailure(row.last_error), })), ); @@ -493,6 +527,19 @@ export const layer: Layer.Layer = La }), reconcileAfterProcessLoss: Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); + const uncertain = storedFailure( + "Restore outcome is uncertain because the server process ended during execution. Inspect files and conversation before retrying.", + "checkpoint_restore_partial", + ); + const uncertainRows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET status = 'failed', lease_owner = NULL, lease_expires_at = NULL, + completed_at = ${now}, updated_at = ${now}, last_error = ${uncertain} + WHERE status = 'running' AND effect_type = 'provider-thread.rollback' + AND (json_extract(payload_json, '$.expectedIdle') = 1 OR json_extract(payload_json, '$.expectedWorkspaceFingerprint') IS NOT NULL OR json_extract(payload_json, '$.expectedThreadState') IS NOT NULL) + RETURNING effect_id + `; + yield* signalSettled(uncertainRows.map((row) => row.effect_id)); const cancelledRows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET @@ -643,7 +690,7 @@ export const layer: Layer.Layer = La (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }), ), ), - fail: ({ effectId, workerId, error }) => + fail: ({ effectId, workerId, error, failureCode }) => Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); const rows = yield* sql<{ readonly effect_id: string }>` @@ -654,7 +701,7 @@ export const layer: Layer.Layer = La lease_expires_at = NULL, completed_at = ${now}, updated_at = ${now}, - last_error = ${error} + last_error = ${storedFailure(error, failureCode)} WHERE effect_id = ${effectId} AND status = 'running' AND lease_owner = ${workerId} @@ -682,6 +729,10 @@ export const layer: Layer.Layer = La FROM orchestration_v2_effect_outbox WHERE status IN ('succeeded', 'cancelled') AND completed_at < ${cutoff} + AND NOT ( + effect_type = 'provider-thread.rollback' + AND (COALESCE(json_extract(payload_json, '$.expectedIdle'), 0) = 1 OR json_extract(payload_json, '$.expectedWorkspaceFingerprint') IS NOT NULL OR json_extract(payload_json, '$.expectedThreadState') IS NOT NULL) + ) LIMIT ${PRUNE_BATCH_SIZE} ) RETURNING effect_id diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 99676e6613a59..2fd3b402ab90f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -1,6 +1,8 @@ import { assert, it } from "@effect/vitest"; import { CommandId, + CheckpointId, + CheckpointScopeId, NodeId, ProviderSessionId, ProviderThreadId, @@ -437,62 +439,75 @@ it.effect("terminalizes a process-bound claim when success settlement fails", () }), ); -it.effect("requeues a replay-safe claim when success settlement fails", () => - Effect.gen(function* () { - const now = DateTime.formatIso(yield* DateTime.now); - const effectId = "effect:worker-replay-safe-settlement-failure"; - const workerId = "worker-replay-safe-settlement-failure"; - const claimedEffect: EffectOutbox.OrchestrationEffectV2 = { - id: effectId, - commandId: CommandId.make("command:worker-replay-safe-settlement-failure"), - threadId: ThreadId.make("thread:worker-replay-safe-settlement-failure"), - request: { type: "terminal.cleanup" }, - status: "running", - attemptCount: 1, - availableAt: now, - leaseOwner: workerId, - leaseExpiresAt: now, - createdAt: now, - updatedAt: now, - completedAt: null, - lastError: null, - }; - const retries = yield* Ref.make(0); - const terminalizations = yield* Ref.make(0); - const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({ - claimNext: () => Effect.succeed(Option.some(claimedEffect)), - get: () => Effect.succeed(Option.some(claimedEffect)), - awaitCancellation: () => Effect.never, - clearCancellation: () => Effect.void, - succeed: () => - Effect.fail( - new EffectOutbox.EffectOutboxError({ - operation: "succeed", - effectId, - cause: "simulated replay-safe settlement failure", - }), - ), - retry: () => Ref.update(retries, (count) => count + 1).pipe(Effect.as(true)), - fail: () => Ref.update(terminalizations, (count) => count + 1).pipe(Effect.as(true)), - }); - const layerExecutor = Layer.succeed( - EffectWorker.OrchestrationEffectExecutorV2, - EffectWorker.OrchestrationEffectExecutorV2.of({ execute: () => Effect.void }), - ); - const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe( - Layer.provide(Layer.merge(layerOutbox, layerExecutor)), - ); +it.effect.each([false, true])( + "handles success settlement failure with guardedRestore=%s", + (guardedRestore) => + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const effectId = "effect:worker-replay-safe-settlement-failure"; + const workerId = "worker-replay-safe-settlement-failure"; + const claimedEffect: EffectOutbox.OrchestrationEffectV2 = { + id: effectId, + commandId: CommandId.make("command:worker-replay-safe-settlement-failure"), + threadId: ThreadId.make("thread:worker-replay-safe-settlement-failure"), + request: guardedRestore + ? { + type: "provider-thread.rollback", + providerThreadId, + checkpointId: CheckpointId.make("checkpoint:settlement"), + scopeId: CheckpointScopeId.make("scope:settlement"), + expectedWorkspaceFingerprint: "accepted", + } + : { type: "terminal.cleanup" }, + status: "running", + attemptCount: 1, + availableAt: now, + leaseOwner: workerId, + leaseExpiresAt: now, + createdAt: now, + updatedAt: now, + completedAt: null, + lastError: null, + }; + const retries = yield* Ref.make(0); + const terminalizations = yield* Ref.make(0); + const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({ + claimNext: () => Effect.succeed(Option.some(claimedEffect)), + get: () => Effect.succeed(Option.some(claimedEffect)), + awaitCancellation: () => Effect.never, + clearCancellation: () => Effect.void, + succeed: () => + Effect.fail( + new EffectOutbox.EffectOutboxError({ + operation: "succeed", + effectId, + cause: "simulated replay-safe settlement failure", + }), + ), + retry: () => Ref.update(retries, (count) => count + 1).pipe(Effect.as(true)), + fail: (input) => { + assert.equal(input.failureCode, "checkpoint_restore_partial"); + return Ref.update(terminalizations, (count) => count + 1).pipe(Effect.as(true)); + }, + }); + const layerExecutor = Layer.succeed( + EffectWorker.OrchestrationEffectExecutorV2, + EffectWorker.OrchestrationEffectExecutorV2.of({ execute: () => Effect.void }), + ); + const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe( + Layer.provide(Layer.merge(layerOutbox, layerExecutor)), + ); - const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe( - Effect.flatMap((worker) => worker.runOnce), - Effect.provide(layerWorker), - Effect.exit, - ); + const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide(layerWorker), + Effect.exit, + ); - assert.isTrue(Exit.isFailure(exit)); - assert.equal(yield* Ref.get(retries), 1); - assert.equal(yield* Ref.get(terminalizations), 0); - }), + assert.isTrue(Exit.isFailure(exit)); + assert.equal(yield* Ref.get(retries), guardedRestore ? 0 : 1); + assert.equal(yield* Ref.get(terminalizations), guardedRestore ? 1 : 0); + }), ); it.effect("keeps a process-bound executor failure retryable when retry settlement fails", () => diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 6227e3a5df217..cea2023f2e55e 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -34,6 +34,7 @@ export class OrchestrationEffectExecutionError extends Schema.TaggedError - willRetry || Cause.hasInterruptsOnly(cause) + (willRetry && + !cause.reasons.some( + (reason) => + reason._tag === "Fail" && + (reason.error._tag === "CheckpointRollbackPartialError" || + reason.error.reason !== "unexpected-failure"), + )) || + Cause.hasInterruptsOnly(cause) ? Effect.void : threads .dispatch({ @@ -422,7 +439,13 @@ export const layerExecutor: Layer.Layer< commandId: CommandId.make(`${effect.commandId}:rollback-failed`), threadId: effect.threadId, requestId: effect.commandId, - message: CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE, + message: cause.reasons.some( + (reason) => + reason._tag === "Fail" && + reason.error._tag === "CheckpointRollbackPartialError", + ) + ? CheckpointRollbackService.ROLLBACK_PARTIAL_MESSAGE + : CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE, }) .pipe( Effect.catchCause((recordCause) => @@ -439,6 +462,13 @@ export const layerExecutor: Layer.Layer< effectId: effect.id, effectType: effect.request.type, cause, + ...(!EffectOutbox.isGuardedCheckpointRestore(effect.request) + ? {} + : cause._tag === "CheckpointRollbackPartialError" + ? { failureCode: "checkpoint_restore_partial" as const } + : cause.reason === "unexpected-failure" + ? {} + : { failureCode: "checkpoint_restore_rejected" as const }), }), ), ); @@ -632,6 +662,9 @@ export const layerWithOptions = ( effectId: effect.id, workerId, error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`, + ...(EffectOutbox.isGuardedCheckpointRestore(effect.request) + ? { failureCode: "checkpoint_restore_partial" as const } + : {}), }) .pipe( Effect.flatMap((failed) => @@ -666,7 +699,7 @@ export const layerWithOptions = ( ) => EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some( (effectType) => effectType === effect.request.type, - ) + ) && !EffectOutbox.isGuardedCheckpointRestore(effect.request) ? requeueClaim(effect, cause) : terminalizeClaim(effect, cause); @@ -744,6 +777,7 @@ export const layerWithOptions = ( }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause))); } + const failureCode = Option.getOrUndefined(Cause.findErrorOption(exit.cause))?.failureCode; const error = Cause.pretty(exit.cause); const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error); yield* Effect.logWarning("Orchestration effect execution failed", { @@ -757,9 +791,14 @@ export const layerWithOptions = ( ? yield* outbox .succeed({ effectId: effect.id, workerId }) .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause))) - : effect.attemptCount >= maxAttempts + : failureCode !== undefined || effect.attemptCount >= maxAttempts ? yield* outbox - .fail({ effectId: effect.id, workerId, error }) + .fail({ + effectId: effect.id, + workerId, + error, + ...(failureCode === undefined ? {} : { failureCode }), + }) .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause))) : yield* outbox .retry({ diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 3a50b441a84ca..79572c0016a69 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2350,14 +2350,41 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { yield* insert("pending:", 1, "pending", null); yield* insert("running:", 1, "running", null); - assert.equal(yield* outbox.pruneSettled, 1_203); + const oldRestoreCompletedAt = DateTime.formatIso(DateTime.subtractDuration(now, old)); + for (const [id, request] of [ + ["restore-idle", { type: "provider-thread.rollback", expectedIdle: true }], + [ + "restore-fingerprint", + { type: "provider-thread.rollback", expectedWorkspaceFingerprint: "accepted" }, + ], + ["restore-state", { type: "provider-thread.rollback", expectedThreadState: "accepted" }], + ["rollback-unguarded", { type: "provider-thread.rollback" }], + ] as const) { + yield* sql`INSERT INTO orchestration_v2_effect_outbox ( + effect_id, command_id, thread_id, effect_type, payload_json, status, + available_at, created_at, updated_at, completed_at + ) VALUES ( + ${id}, 'command:prune-restore', 'thread:prune', 'provider-thread.rollback', + ${JSON.stringify(request)}, 'succeeded', ${oldRestoreCompletedAt}, ${oldRestoreCompletedAt}, + ${oldRestoreCompletedAt}, ${oldRestoreCompletedAt} + )`; + } + assert.equal(yield* outbox.pruneSettled, 1_204); const remaining = yield* sql<{ readonly effect_id: string }>` SELECT effect_id FROM orchestration_v2_effect_outbox ORDER BY effect_id `; assert.deepEqual( remaining.map((row) => row.effect_id), - ["failed-old:1", "pending:1", "running:1", "succeeded-recent:1"], + [ + "failed-old:1", + "pending:1", + "restore-fingerprint", + "restore-idle", + "restore-state", + "running:1", + "succeeded-recent:1", + ], ); assert.equal(yield* outbox.pruneSettled, 0); }).pipe(Effect.provide(layerIsolatedOutbox)), @@ -2970,6 +2997,45 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }), ); + it.effect.each([true, false])( + "never replays an uncertain guarded restore, expectedIdle=%s", + (expectedIdle) => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const commandId = CommandId.make("command:guarded-restore-process-loss"); + const effect = { + id: "effect:guarded-restore-process-loss", + commandId, + threadId: ThreadId.make("thread:guarded-restore-process-loss"), + request: { + type: "provider-thread.rollback" as const, + providerThreadId: ProviderThreadId.make("provider-thread:guarded-restore-process-loss"), + checkpointId: CheckpointId.make("checkpoint:guarded-restore-process-loss"), + scopeId: CheckpointScopeId.make("scope:guarded-restore-process-loss"), + ...(expectedIdle ? { expectedIdle: true as const } : {}), + expectedWorkspaceFingerprint: "before-destructive-restore", + }, + }; + yield* outbox.enqueue([effect]); + const claimed = yield* outbox.claimNext({ + workerId: "lost-worker", + leaseDurationMs: 30_000, + }); + assert.equal(Option.getOrThrow(claimed).id, effect.id); + + yield* outbox.reconcileAfterProcessLoss; + yield* outbox.reconcileAfterProcessLoss; + const settled = Option.getOrThrow(yield* outbox.get(effect.id)); + assert.equal(settled.status, "failed"); + assert.include(settled.lastError ?? "", "uncertain"); + assert.isTrue( + Option.isNone( + yield* outbox.claimNext({ workerId: "replacement-worker", leaseDurationMs: 30_000 }), + ), + ); + }).pipe(Effect.provide(layerIsolatedOutbox)), + ); + it.effect("atomically cancels stale runs and their process-bound effects", () => Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4464d09916e33..44884a89d1d65 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -51,6 +51,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, latestProviderTurnForAttempt, + checkpointRollbackAppRunOrdinal, orchestrationV2RunWorkStartedAt, ProviderInstanceId, ProviderInteractionMode, @@ -82,6 +83,9 @@ import * as Stream from "effect/Stream"; import * as ProjectStore from "./ProjectStore.ts"; import { isCheckpointRestoreIsolated, + checkpointRestoreThreadIdle, + checkpointRestoreThreadState, + CheckpointRestoreRejectedRequest, SHARED_WORKSPACE_RESTORE_MESSAGE, } from "./CheckpointRestoreSafety.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; @@ -237,6 +241,17 @@ export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError()( + "CheckpointRollbackAdmissionError", + { commandId: CommandId, threadId: ThreadId }, +) { + override get message(): string { + return "Checkpoint restore requires an unchanged, idle, unarchived thread with no queued work."; + } +} + export class OrchestratorCommandPreviouslyRejectedError extends Schema.TaggedError()( "OrchestratorCommandPreviouslyRejectedError", { @@ -278,6 +293,7 @@ export function canReplayCommandReceipt( } export const OrchestratorV2Error = Schema.Union([ + CheckpointRollbackAdmissionError, OrchestratorDispatchError, OrchestratorThreadAlreadyExistsError, OrchestratorCommandRejectedError, @@ -9790,6 +9806,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ["providerThreads", "checkpoints", "checkpointScopes", "runs", "providerTurns", "attempts"], { turnItemTypes: [], messageRoles: ["user"] }, ); + if ( + (command.expectedIdle === true && !checkpointRestoreThreadIdle(projection)) || + (command.expectedThreadState !== undefined && + command.expectedThreadState !== checkpointRestoreThreadState(projection)) + ) { + return yield* new CheckpointRollbackAdmissionError({ + commandId: command.commandId, + threadId: command.threadId, + }); + } const providerThread = projection.providerThreads.find( (candidate) => candidate.id === projection.thread.activeProviderThreadId, ); @@ -9887,7 +9913,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } - const targetOrdinal = targetCheckpoint.appRunOrdinal ?? 0; + const guarded = + command.expectedIdle === true || + command.expectedWorkspaceFingerprint !== undefined || + command.expectedThreadState !== undefined; + const targetOrdinal = guarded + ? checkpointRollbackAppRunOrdinal(targetCheckpoint, targetScope) + : (targetCheckpoint.appRunOrdinal ?? 0); + if ( + targetOrdinal === null || + (guarded && + (providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId || + (targetScope.providerThreadId !== null && + targetScope.providerThreadId !== providerThread.id))) + ) + return yield* new CheckpointRollbackAdmissionError({ + commandId: command.commandId, + threadId: command.threadId, + }); if (targetOrdinal > 0) { const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); const targetProviderTurn = @@ -9946,6 +9989,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, request: { type: "provider-thread.rollback", + ...(command.expectedIdle === undefined ? {} : { expectedIdle: command.expectedIdle }), + ...(command.expectedWorkspaceFingerprint === undefined + ? {} + : { expectedWorkspaceFingerprint: command.expectedWorkspaceFingerprint }), + ...(command.expectedThreadState === undefined + ? {} + : { expectedThreadState: command.expectedThreadState }), ...(command.restoreFiles === undefined ? {} : { restoreFiles: command.restoreFiles }), providerThreadId: providerThread.id, checkpointId: targetCheckpoint.id, @@ -11324,7 +11374,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: commandThreadId(command), commandType: command.type, rejectedAt, - error: cause instanceof Error ? cause.message : String(cause), + error: + command.type === "checkpoint.rollback" && + (command.expectedIdle === true || + command.expectedWorkspaceFingerprint !== undefined || + command.expectedThreadState !== undefined) + ? encodeRejectedRestore({ + type: "checkpoint_restore_rejected", + threadId: command.threadId, + scopeId: command.scopeId, + checkpointId: command.checkpointId, + }) + : cause instanceof Error + ? cause.message + : String(cause), }) .pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 0342a3ccc9d94..36556d6a5d919 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -416,6 +416,7 @@ export function layerWithRegistry( const layerCheckpointRollbackServiceProvided = CheckpointRollbackService.layer.pipe( Layer.provide( Layer.mergeAll( + layerCheckpointStore, layerCheckpointServiceProvided, layerEventSinkProvided, IdAllocator.layer, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 0f02b7107bad9..964cccb957ecc 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,3 +1,8 @@ +// FileSystem.stat follows symlinks; raw checkpoint fingerprints need lstat and streaming hashes. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; +import * as NodeFSP from "node:fs/promises"; +import * as Stream from "effect/Stream"; import * as NodeBuffer from "node:buffer"; import * as Context from "effect/Context"; @@ -13,6 +18,8 @@ import { ChildProcessSpawner } from "effect/process"; import { GitCommandError, VcsProcessExitError, + VcsCheckpointWorkspaceReadError, + VcsUnsupportedOperationError, type VcsSwitchRefInput, type VcsSwitchRefResult, type VcsCreateRefInput, @@ -793,6 +800,89 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ] as const; const checkpoints: VcsDriver.VcsCheckpointOps = { + readWorkspaceFingerprint: Effect.fn("GitVcsDriver.checkpoints.readWorkspaceFingerprint")( + function* (cwd) { + const operation = "GitVcsDriver.checkpoints.readWorkspaceFingerprint"; + const head = yield* resolveHeadCommit(cwd); + const staged = yield* execute({ + operation, + cwd, + args: ["ls-files", "--stage", "-z", "--", "."], + outputMode: "error", + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + }); + const paths = yield* execute({ + operation, + cwd, + args: ["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "."], + outputMode: "error", + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + }); + if ( + staged.stdoutTruncated || + paths.stdoutTruncated || + staged.stdoutInvalidUtf8 || + paths.stdoutInvalidUtf8 + ) + return yield* new VcsProcessExitError({ + operation, + command: "git ls-files", + cwd, + exitCode: 0, + detail: "Workspace fingerprint output is incomplete.", + }); + // Hash raw bytes: Git clean filters can map distinct edits to the same tree. + const hash = NodeCrypto.createHash("sha256") + .update(head ?? "") + .update("\0") + .update(staged.stdout); + yield* Effect.gen(function* () { + for (const file of [...new Set(paths.stdout.split("\0").filter(Boolean))].sort()) { + const absolute = path.resolve(cwd, file); + hash.update("\0path\0").update(file).update("\0"); + const stat = yield* Effect.tryPromise(() => NodeFSP.lstat(absolute)).pipe( + Effect.catchIf( + (error) => + error.cause instanceof Error && + "code" in error.cause && + error.cause.code === "ENOENT", + () => Effect.succeed(null), + ), + ); + if (stat === null) { + hash.update("missing"); + continue; + } + hash.update(String(stat.mode)).update("\0"); + if (stat.isSymbolicLink()) + hash.update( + yield* Effect.tryPromise(() => NodeFSP.readlink(absolute, { encoding: "buffer" })), + ); + else if (stat.isFile()) { + const content = NodeCrypto.createHash("sha256"); + yield* fileSystem.stream(absolute).pipe( + Stream.runForEach((chunk) => + Effect.sync(() => { + content.update(chunk); + }), + ), + ); + hash.update(content.digest()); + } else if (!stat.isDirectory()) + return yield* new VcsUnsupportedOperationError({ + operation, + kind: "git", + detail: "Unsupported workspace file type.", + }); + } + }).pipe( + Effect.mapError( + (cause) => new VcsCheckpointWorkspaceReadError({ operation, cwd, cause }), + ), + ); + return hash.digest("hex"); + }, + ), captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; // core.splitIndex governs every index Git writes, so an unguarded write to the diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 27fca61b5adb6..c967f9f83cc0b 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -49,6 +49,7 @@ export interface VcsDeleteCheckpointRefsInput { } export interface VcsCheckpointOps { + readonly readWorkspaceFingerprint: (cwd: string) => Effect.Effect; readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect; readonly hasCheckpointRef: ( input: Omit, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index d53c1322e141d..4486ad45da287 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2912,6 +2912,9 @@ export const OrchestrationV2Command = Schema.Union([ }), Schema.Struct({ type: Schema.Literal("checkpoint.rollback"), + expectedIdle: Schema.optional(Schema.Literal(true)), + expectedWorkspaceFingerprint: Schema.optional(Schema.String), + expectedThreadState: Schema.optional(Schema.String), restoreFiles: Schema.optional(Schema.Boolean), commandId: CommandId, threadId: ThreadId, diff --git a/packages/contracts/src/vcs.ts b/packages/contracts/src/vcs.ts index f92e4fc1d5c48..5fdb32efc0eb7 100644 --- a/packages/contracts/src/vcs.ts +++ b/packages/contracts/src/vcs.ts @@ -109,6 +109,15 @@ export class VcsProcessSpawnError extends Schema.TaggedError()( + "VcsCheckpointWorkspaceReadError", + { operation: Schema.String, cwd: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return "Unable to fingerprint the checkpoint workspace."; + } +} + export class VcsProcessExitError extends Schema.TaggedError()( "VcsProcessExitError", { @@ -273,6 +282,7 @@ export class VcsUnsupportedOperationError extends Schema.TaggedError new GitLabCliCommandError({ ...context, cause }), VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }), VcsProcessExitError: (cause) => { switch (cause.failureKind) { From 513b8e21c0fba051dc1018ebd83f4f4417696985 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 16:06:38 +0000 Subject: [PATCH 2/4] fix(server): reject missing guarded worktrees and stop partial rollback retries --- .../CheckpointRollbackService.test.ts | 32 +++++++++- .../CheckpointRollbackService.ts | 1 + .../src/orchestration-v2/EffectWorker.test.ts | 64 ++++++++++++++++++- .../src/orchestration-v2/EffectWorker.ts | 16 ++--- 4 files changed, 101 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 3398b6ca05b97..8d6f0767e4164 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -402,11 +402,12 @@ it.effect("rejects an unavailable rollback target before opening a session", () it.effect.each([ { order: "normal", restoreFiles: true }, { order: "cleanup-first", restoreFiles: true }, + { order: "cleanup-first", restoreFiles: true, guarded: true }, { order: "cleanup-first", restoreFiles: false }, { order: "rollback-first", restoreFiles: true }, // A path the server would not have made is left missing, not recreated. { order: "cleanup-first", restoreFiles: false, unmanaged: true }, -])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false }) => +])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false, guarded = false }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -454,7 +455,10 @@ it.effect.each([ Layer.mergeAll( ThreadCommandExecutor.layer, NodeServices.layer, - Layer.mock(CheckpointStore.CheckpointStore)({}), + Layer.mock(CheckpointStore.CheckpointStore)({ + hasCheckpointRef: () => Effect.succeed(true), + readWorkspaceFingerprint: () => Effect.succeed("recreated-worktree"), + }), Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never), ServerSettings.layerTest(), Layer.mock(ProjectStore.ProjectStoreV2)({ @@ -482,6 +486,11 @@ it.effect.each([ }), }), Layer.mock(CheckpointService.CheckpointServiceV2)({ + withRestoreLock: (_cwd, use) => + use({ + restore: () => Effect.die("guarded restore must not mutate files"), + deleteStaleRefs: () => Effect.die("guarded restore must not delete refs"), + }), restore: () => Effect.gen(function* () { assert.isTrue(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)); @@ -544,7 +553,16 @@ it.effect.each([ ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) : undefined; const rollback = yield* service - .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }) + .execute({ + threadId, + providerThreadId, + checkpointId, + scopeId, + restoreFiles, + ...(guarded + ? { expectedIdle: true as const, expectedWorkspaceFingerprint: "accepted-worktree" } + : {}), + }) .pipe(Effect.forkChild({ startImmediately: true })); if (order === "cleanup-first") assert.deepEqual(calls, []); if (order === "rollback-first") yield* Deferred.await(openEntered); @@ -555,6 +573,14 @@ it.effect.each([ if (order === "rollback-first") assert.isFalse(cleanupEntered); yield* Deferred.succeed(release, undefined); if (cleanup !== undefined) yield* Fiber.join(cleanup); + if (guarded) { + const error = yield* Fiber.join(rollback).pipe(Effect.flip); + assert.deepEqual(calls, ["cleanup"]); + assert.isFalse(yield* fileSystem.exists(worktreePath)); + assert.equal(error._tag, "CheckpointRollbackExecutionError"); + assert.equal("reason" in error ? error.reason : undefined, "restore-precondition-changed"); + return; + } if (unmanaged) { const error = yield* Fiber.join(rollback).pipe(Effect.flip); assert.equal(error._tag, "CheckpointRollbackExecutionError"); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 4f6a21f221c44..fb6a1abef83ff 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -275,6 +275,7 @@ export const layer: Layer.Layer< !(yield* fileSystem.exists(worktreePath)) && (yield* isManagedWorktreePath(worktreePath)) ) { + if (guarded) return yield* reject("restore-precondition-changed"); const project = yield* projects.get(projection.thread.projectId); if (Option.isSome(project)) { yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }); diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 2fd3b402ab90f..acf09af338450 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -85,6 +85,7 @@ function layerExecutorFor(input: { readonly threads?: Partial; readonly continueAfterRestart?: boolean; readonly interrupt?: ProviderTurnControlService.ProviderTurnControlServiceV2Shape["interrupt"]; + readonly rollback?: CheckpointRollbackService.CheckpointRollbackServiceV2Shape["execute"]; }) { const record = (event: string) => Ref.update(input.events, (events) => [...events, event]); const layerDependencies = Layer.mergeAll( @@ -138,7 +139,9 @@ function layerExecutorFor(input: { ), Layer.succeed( CheckpointRollbackService.CheckpointRollbackServiceV2, - CheckpointRollbackService.CheckpointRollbackServiceV2.of({ execute: () => Effect.void }), + CheckpointRollbackService.CheckpointRollbackServiceV2.of({ + execute: input.rollback ?? (() => Effect.void), + }), ), Layer.succeed( RuntimeRequestService.RuntimeRequestServiceV2, @@ -510,6 +513,65 @@ it.effect.each([false, true])( }), ); +it.effect.each([false, true])( + "terminalizes a typed partial rollback with guardedRestore=%s", + (guardedRestore) => + Effect.gen(function* () { + const events = yield* Ref.make>([]); + const record = (event: string) => Ref.update(events, (current) => [...current, event]); + const checkpointId = CheckpointId.make("checkpoint:partial"); + const effect: EffectOutbox.OrchestrationEffectV2 = { + ...restartEffect(yield* DateTime.now, { type: "detach" }), + request: { + type: "provider-thread.rollback", + providerThreadId, + checkpointId, + scopeId: CheckpointScopeId.make("scope:partial"), + ...(guardedRestore ? { expectedWorkspaceFingerprint: "accepted" } : {}), + }, + }; + const layerExecutor = layerExecutorFor({ + events, + rollback: () => + record("rollback").pipe( + Effect.andThen( + new CheckpointRollbackService.CheckpointRollbackPartialError({ + threadId, + checkpointId, + cause: "file restore failed after provider rollback", + }), + ), + ), + threads: { + dispatch: (command) => + record(command.type).pipe(Effect.as({ sequence: 1, storedEvents: [] })), + }, + }); + const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({ + claimNext: () => Effect.succeed(Option.some(effect)), + get: () => Effect.succeed(Option.some(effect)), + awaitCancellation: () => Effect.never, + clearCancellation: () => Effect.void, + retry: () => record("retry").pipe(Effect.as(true)), + fail: (input) => { + assert.equal(input.failureCode, "checkpoint_restore_partial"); + return record("terminal").pipe(Effect.as(true)); + }, + }); + yield* EffectWorker.OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide( + EffectWorker.layer.pipe(Layer.provide(Layer.merge(layerOutbox, layerExecutor))), + ), + ); + assert.deepEqual(yield* Ref.get(events), [ + "rollback", + "checkpoint.rollback.fail", + "terminal", + ]); + }), +); + it.effect("keeps a process-bound executor failure retryable when retry settlement fails", () => Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index cea2023f2e55e..050cfe64a2a45 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -429,7 +429,8 @@ export const layerExecutor: Layer.Layer< (reason) => reason._tag === "Fail" && (reason.error._tag === "CheckpointRollbackPartialError" || - reason.error.reason !== "unexpected-failure"), + (EffectOutbox.isGuardedCheckpointRestore(effect.request) && + reason.error.reason !== "unexpected-failure")), )) || Cause.hasInterruptsOnly(cause) ? Effect.void @@ -462,13 +463,12 @@ export const layerExecutor: Layer.Layer< effectId: effect.id, effectType: effect.request.type, cause, - ...(!EffectOutbox.isGuardedCheckpointRestore(effect.request) - ? {} - : cause._tag === "CheckpointRollbackPartialError" - ? { failureCode: "checkpoint_restore_partial" as const } - : cause.reason === "unexpected-failure" - ? {} - : { failureCode: "checkpoint_restore_rejected" as const }), + ...(cause._tag === "CheckpointRollbackPartialError" + ? { failureCode: "checkpoint_restore_partial" as const } + : !EffectOutbox.isGuardedCheckpointRestore(effect.request) || + cause.reason === "unexpected-failure" + ? {} + : { failureCode: "checkpoint_restore_rejected" as const }), }), ), ); From c74ce5a8673ae8231f85f0684553994ab8801fd3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 16:52:50 +0000 Subject: [PATCH 3/4] fix(server): recover terminal checkpoint rollback metadata --- .../FoundationPersistence.test.ts | 75 +++++++++++++++---- .../src/orchestration-v2/ProjectionStore.ts | 15 ++++ .../ProviderRuntimeRecoveryService.ts | 52 +++++++++++++ 3 files changed, 129 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 79572c0016a69..0b9b236bbb1f5 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2998,15 +2998,20 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { ); it.effect.each([true, false])( - "never replays an uncertain guarded restore, expectedIdle=%s", + "projects an uncertain guarded restore without replay after startup, expectedIdle=%s", (expectedIdle) => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; + const eventSink = yield* EventSink.EventSinkV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; const commandId = CommandId.make("command:guarded-restore-process-loss"); + const threadId = ThreadId.make("thread:guarded-restore-process-loss"); + const thread = makeThread(threadId, now); const effect = { id: "effect:guarded-restore-process-loss", commandId, - threadId: ThreadId.make("thread:guarded-restore-process-loss"), + threadId, request: { type: "provider-thread.rollback" as const, providerThreadId: ProviderThreadId.make("provider-thread:guarded-restore-process-loss"), @@ -3016,24 +3021,68 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { expectedWorkspaceFingerprint: "before-destructive-restore", }, }; - yield* outbox.enqueue([effect]); + yield* eventSink.commitCommand({ + commandId, + threadId, + commandType: "checkpoint.rollback", + acceptedAt: now, + events: [ + threadCreatedEvent({ id: "event:guarded-restore-process-loss:thread", thread, now }), + { + id: EventId.make("event:guarded-restore-process-loss:pending"), + type: "thread.metadata-updated", + threadId, + providerInstanceId, + occurredAt: now, + payload: { ...thread, rollbackRequestId: commandId, rollbackFailure: null }, + }, + { + id: EventId.make("event:guarded-restore-process-loss:requested"), + type: "checkpoint.rollback-requested", + threadId, + providerInstanceId, + occurredAt: now, + payload: { + scopeId: effect.request.scopeId, + checkpointId: effect.request.checkpointId, + requestedAt: now, + }, + }, + ], + effects: [effect], + }); + const pending = yield* projectionStore.getThreadProjection(threadId); + assert.equal(pending.thread.rollbackRequestId, commandId); + assert.isNull(pending.thread.rollbackFailure); const claimed = yield* outbox.claimNext({ workerId: "lost-worker", leaseDurationMs: 30_000, }); assert.equal(Option.getOrThrow(claimed).id, effect.id); - yield* outbox.reconcileAfterProcessLoss; - yield* outbox.reconcileAfterProcessLoss; - const settled = Option.getOrThrow(yield* outbox.get(effect.id)); - assert.equal(settled.status, "failed"); - assert.include(settled.lastError ?? "", "uncertain"); - assert.isTrue( - Option.isNone( - yield* outbox.claimNext({ workerId: "replacement-worker", leaseDurationMs: 30_000 }), - ), + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provide(ServerSettings.layerTest()), ); - }).pipe(Effect.provide(layerIsolatedOutbox)), + for (let pass = 0; pass < 2; pass++) { + yield* recovery.recover; + const settled = Option.getOrThrow(yield* outbox.get(effect.id)); + assert.equal(settled.status, "failed"); + assert.equal(settled.failureCode, "checkpoint_restore_partial"); + assert.include(settled.lastError ?? "", "uncertain"); + assert.equal(settled.attemptCount, 1); + assert.isTrue( + Option.isNone( + yield* outbox.claimNext({ workerId: "replacement-worker", leaseDurationMs: 30_000 }), + ), + ); + const projection = yield* projectionStore.getThreadProjection(threadId); + assert.equal(projection.thread.rollbackRequestId, commandId); + assert.deepEqual(projection.thread.rollbackFailure, { + requestId: commandId, + message: settled.lastError, + }); + } + }).pipe(Effect.provide(Layer.fresh(layerTest))), ); it.effect("atomically cancels stale runs and their process-bound effects", () => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 002ef7bafa950..66701ee0483eb 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -602,6 +602,8 @@ function needsRecovery( } case "runtime": return ( + (projection.thread.rollbackRequestId != null && + projection.thread.rollbackFailure == null) || projection.runs.some( (run) => ["preparing", "starting", "running", "waiting"].includes(run.status) || @@ -3788,6 +3790,19 @@ export const layer: Layer.Layer = UNION SELECT thread_id FROM orchestration_v2_effect_outbox WHERE status IN ('pending', 'running') + UNION + SELECT thread_id FROM orchestration_v2_projection_threads AS thread + WHERE CASE WHEN json_valid(thread.payload_json) THEN + json_extract(thread.payload_json, '$.rollbackRequestId') IS NOT NULL + AND json_extract(thread.payload_json, '$.rollbackFailure') IS NULL + AND EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox AS effect + WHERE effect.command_id = json_extract(thread.payload_json, '$.rollbackRequestId') + AND effect.thread_id = thread.thread_id + AND effect.effect_type = 'provider-thread.rollback' + AND effect.status = 'failed' + ) + ELSE 0 END `; } })(); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 32de3b9d6a4f4..c35daf4173eeb 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -713,6 +713,7 @@ export const make = Effect.gen(function* () { let closedRequests = 0; let retiredEffects = 0; const stoppedThisPass = new Map(); + const pendingRollbackThreadIds: Array = []; for (const threadId of threadIds) { const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe( Effect.mapError( @@ -724,6 +725,11 @@ export const make = Effect.gen(function* () { }), ), ); + if ( + projection.thread.rollbackRequestId != null && + projection.thread.rollbackFailure == null + ) + pendingRollbackThreadIds.push(threadId); const enabled = continueAfterRestart !== null && resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings @@ -744,6 +750,52 @@ export const make = Effect.gen(function* () { (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }), ), ); + // Revisit pending metadata even when a prior startup already settled the outbox. + for (const threadId of pendingRollbackThreadIds) { + yield* Effect.gen(function* () { + const thread = yield* projections.getThread(threadId); + const requestId = thread.rollbackRequestId; + if (thread.deletedAt !== null || requestId == null || thread.rollbackFailure != null) + return; + const effects = yield* outbox.listByCommandId(requestId); + const failed = effects.find( + (effect) => + effect.threadId === threadId && + effect.request.type === "provider-thread.rollback" && + effect.status === "failed" && + effect.failureCode === "checkpoint_restore_partial", + ); + if (failed?.lastError == null) return; + const now = yield* DateTime.now; + const commandId = CommandId.make(`command:runtime-reconcile:rollback:${requestId}`); + yield* eventSink.commitCommand({ + commandId, + threadId, + commandType: "provider-runtime.reconcile", + acceptedAt: now, + events: [ + { + id: yield* ids.allocate.event({ threadId, commandId }), + type: "thread.metadata-updated", + threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: { + ...thread, + rollbackFailure: { requestId, message: failed.lastError }, + updatedAt: now, + }, + }, + ], + effects: [], + }); + }).pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ operation: "reconcile", threadId, cause }), + ), + ); + } return { terminalizedRuns, stoppedSessions, From 50f502b198e84bc4c411aff067335cf3eaa74f6a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 17:09:18 +0000 Subject: [PATCH 4/4] fix(server): repair failed rollback metadata with safe messages --- .../FoundationPersistence.test.ts | 50 ++++++++++++++++--- .../src/orchestration-v2/ProjectionStore.ts | 21 ++++---- .../ProviderRuntimeRecoveryService.ts | 14 ++++-- 3 files changed, 63 insertions(+), 22 deletions(-) diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 0b9b236bbb1f5..2b2522e3b1e97 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -45,6 +45,7 @@ import * as Statement from "effect/sql/Statement"; import { LIVE_STREAM_MAX_ITEMS, LiveStreamBufferError } from "./LiveStreamBudget.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { ROLLBACK_FAILED_MESSAGE, ROLLBACK_PARTIAL_MESSAGE } from "./CheckpointRollbackService.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EffectWorker from "./EffectWorker.ts"; @@ -2997,9 +2998,30 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }), ); - it.effect.each([true, false])( - "projects an uncertain guarded restore without replay after startup, expectedIdle=%s", - (expectedIdle) => + it.effect.each([ + { + expectedIdle: true, + terminalFailureCode: null, + expectedMessage: ROLLBACK_PARTIAL_MESSAGE, + }, + { + expectedIdle: false, + terminalFailureCode: null, + expectedMessage: ROLLBACK_PARTIAL_MESSAGE, + }, + { + expectedIdle: true, + terminalFailureCode: "checkpoint_restore_rejected", + expectedMessage: ROLLBACK_FAILED_MESSAGE, + }, + { + expectedIdle: true, + terminalFailureCode: "checkpoint_restore_partial", + expectedMessage: ROLLBACK_PARTIAL_MESSAGE, + }, + ] as const)( + "projects a safe guarded restore failure without replay after startup, expectedIdle=$expectedIdle, terminalFailureCode=$terminalFailureCode", + ({ expectedIdle, terminalFailureCode, expectedMessage }) => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; const eventSink = yield* EventSink.EventSinkV2; @@ -3059,6 +3081,18 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { leaseDurationMs: 30_000, }); assert.equal(Option.getOrThrow(claimed).id, effect.id); + const internalDiagnostic = + "SqlError: private rollback diagnostic\n at commit (/private/workspace/secret-project/restore.ts:42:7)"; + if (terminalFailureCode !== null) { + assert.isTrue( + yield* outbox.fail({ + effectId: effect.id, + workerId: "lost-worker", + failureCode: terminalFailureCode, + error: internalDiagnostic, + }), + ); + } const recovery = yield* ProviderRuntimeRecovery.make.pipe( Effect.provide(ServerSettings.layerTest()), @@ -3067,8 +3101,12 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { yield* recovery.recover; const settled = Option.getOrThrow(yield* outbox.get(effect.id)); assert.equal(settled.status, "failed"); - assert.equal(settled.failureCode, "checkpoint_restore_partial"); - assert.include(settled.lastError ?? "", "uncertain"); + assert.equal(settled.failureCode, terminalFailureCode ?? "checkpoint_restore_partial"); + if (terminalFailureCode !== null) { + assert.equal(settled.lastError, internalDiagnostic); + } else { + assert.include(settled.lastError ?? "", "uncertain"); + } assert.equal(settled.attemptCount, 1); assert.isTrue( Option.isNone( @@ -3079,7 +3117,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { assert.equal(projection.thread.rollbackRequestId, commandId); assert.deepEqual(projection.thread.rollbackFailure, { requestId: commandId, - message: settled.lastError, + message: expectedMessage, }); } }).pipe(Effect.provide(Layer.fresh(layerTest))), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 66701ee0483eb..9b8d25b69b8c8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3791,18 +3791,15 @@ export const layer: Layer.Layer = SELECT thread_id FROM orchestration_v2_effect_outbox WHERE status IN ('pending', 'running') UNION - SELECT thread_id FROM orchestration_v2_projection_threads AS thread - WHERE CASE WHEN json_valid(thread.payload_json) THEN - json_extract(thread.payload_json, '$.rollbackRequestId') IS NOT NULL - AND json_extract(thread.payload_json, '$.rollbackFailure') IS NULL - AND EXISTS ( - SELECT 1 FROM orchestration_v2_effect_outbox AS effect - WHERE effect.command_id = json_extract(thread.payload_json, '$.rollbackRequestId') - AND effect.thread_id = thread.thread_id - AND effect.effect_type = 'provider-thread.rollback' - AND effect.status = 'failed' - ) - ELSE 0 END + SELECT effect.thread_id FROM orchestration_v2_effect_outbox AS effect + JOIN orchestration_v2_projection_threads AS thread + ON thread.thread_id = effect.thread_id + WHERE effect.status = 'failed' + AND effect.effect_type = 'provider-thread.rollback' + AND CASE WHEN json_valid(thread.payload_json) THEN + json_extract(thread.payload_json, '$.rollbackRequestId') = effect.command_id + AND json_extract(thread.payload_json, '$.rollbackFailure') IS NULL + ELSE 0 END `; } })(); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index c35daf4173eeb..5a4c38dd5cf47 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -17,6 +17,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -762,10 +763,9 @@ export const make = Effect.gen(function* () { (effect) => effect.threadId === threadId && effect.request.type === "provider-thread.rollback" && - effect.status === "failed" && - effect.failureCode === "checkpoint_restore_partial", + effect.status === "failed", ); - if (failed?.lastError == null) return; + if (failed === undefined) return; const now = yield* DateTime.now; const commandId = CommandId.make(`command:runtime-reconcile:rollback:${requestId}`); yield* eventSink.commitCommand({ @@ -782,7 +782,13 @@ export const make = Effect.gen(function* () { occurredAt: now, payload: { ...thread, - rollbackFailure: { requestId, message: failed.lastError }, + rollbackFailure: { + requestId, + message: + failed.failureCode === "checkpoint_restore_partial" + ? CheckpointRollbackService.ROLLBACK_PARTIAL_MESSAGE + : CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE, + }, updatedAt: now, }, },