Skip to content
TypeScript

fix(server): read only checkpoint rollback targets (#21804)

Julius Marmingeeb52bdc4efe2
diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
index c6213056322..640d5ce2b94 100644
--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
@@ -3,7 +3,6 @@ import { assert, it } from "@effect/vitest";
import {
CheckpointId,
CheckpointScopeId,
- type OrchestrationV2ThreadProjection,
ProjectId,
ProviderInstanceId,
ProviderSessionId,
@@ -25,7 +24,7 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
-import { ProjectionStoreV2 } from "./ProjectionStore.ts";
+import { ProjectionStoreV2, type ProjectionCheckpointRollbackContext } from "./ProjectionStore.ts";
import * as ProjectStore from "./ProjectStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
@@ -94,15 +93,17 @@ it.effect.each([
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId, model: "test" },
},
- providerThreads: [providerThread],
- providerSessions: [],
+ providerThread,
+ providerSession: undefined,
providerTurns: [],
- nodes: [],
- attempts: [],
- checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: null }],
- checkpointScopes: [{ id: scopeId, cwd }],
- runs: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
- } as unknown as OrchestrationV2ThreadProjection;
+ rootNodes: [],
+ targetAttempt: undefined,
+ rolledBackAttemptIds: [],
+ staleCheckpoints: [],
+ checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null },
+ scope: { id: scopeId, cwd },
+ runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
+ } as unknown as ProjectionCheckpointRollbackContext;
const layerTest = CheckpointRollbackService.layer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -116,7 +117,8 @@ it.effect.each([
get: () => Effect.succeed(Option.some({ workspaceRoot: parent } as never)),
}),
Layer.mock(ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
index abb9f72f9ff..cb11c4ba8f2 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
@@ -2,8 +2,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import {
CheckpointId,
+ CheckpointRef,
+ EventId,
+ MessageId,
+ NodeId,
+ type OrchestrationV2DomainEvent,
+ ProviderDriverKind,
+ ProviderTurnId,
+ RunAttemptId,
+ RunId,
CheckpointScopeId,
- type OrchestrationV2ThreadProjection,
ProjectId,
ProviderInstanceId,
ProviderSessionId,
@@ -11,6 +19,8 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as DateTime from "effect/DateTime";
+import * as SqlClient from "effect/sql/SqlClient";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -19,6 +29,7 @@ import * as Option from "effect/Option";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as Layer from "effect/Layer";
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitWorkflow from "../git/GitWorkflowService.ts";
@@ -67,33 +78,25 @@ it.effect.each(["initial", "waiting"])(
const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
const readEntered = Deferred.makeUnsafe<void>();
const release = Deferred.makeUnsafe<void>();
- let readCount = 0;
let projection = {
thread: {
worktreePath: process.cwd(),
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
},
- providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
- checkpoints: [
- {
- id: checkpointId,
- scopeId,
- status: state === "waiting" ? "ready" : "stale",
- appRunOrdinal: 0,
- },
- ],
- checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
- } as unknown as OrchestrationV2ThreadProjection;
- const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(
- () => {
- const current = projection;
- readCount++;
- return readCount === 1
- ? Deferred.succeed(readEntered, undefined).pipe(Effect.as(current))
- : Effect.succeed(current);
+ providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
+ checkpoint: {
+ id: checkpointId,
+ scopeId,
+ status: state === "waiting" ? "ready" : "stale",
+ appRunOrdinal: 0,
},
+ scope: { id: scopeId, cwd: process.cwd() },
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
+ const getThread = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThread"]>(() =>
+ Deferred.succeed(readEntered, undefined).pipe(Effect.as(projection.thread)),
);
+ const getCheckpointRollbackContext = vi.fn(() => Effect.succeed(projection));
const testLayer = layerCheckpointRollbackService.pipe(
Layer.provide(
Layer.mergeAll(
@@ -102,7 +105,8 @@ it.effect.each(["initial", "waiting"])(
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords,
+ getThread,
+ getCheckpointRollbackContext,
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -137,19 +141,25 @@ it.effect.each(["initial", "waiting"])(
yield* Deferred.await(readEntered);
projection = {
...projection,
- checkpoints: projection.checkpoints.map((checkpoint) => ({
- ...checkpoint,
- status: "stale",
- })),
+ checkpoint: { ...projection.checkpoint!, status: "stale" },
};
yield* Deferred.succeed(release, undefined);
if (holder !== undefined) yield* Fiber.join(holder);
}
const error = yield* Fiber.join(rollback);
- 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.deepEqual(getThread.mock.calls, [[threadId]]);
+ assert.deepEqual(getCheckpointRollbackContext.mock.calls, [
+ [
+ threadId,
+ {
+ threadId,
+ providerThreadId,
+ checkpointId,
+ scopeId,
+ },
+ ],
+ ]);
assert.equal(error.reason, "rollback-target-invalid");
assert.equal(
error.message,
@@ -186,16 +196,14 @@ it.effect("rejects a rollback when another provider thread became active", () =>
activeProviderThreadId,
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
},
- providerThreads: [
- {
- id: requestedProviderThreadId,
- providerSessionId,
- providerInstanceId,
- },
- ],
- checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
- checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
- } as unknown as OrchestrationV2ThreadProjection;
+ providerThread: {
+ id: requestedProviderThreadId,
+ providerSessionId,
+ providerInstanceId,
+ },
+ checkpoint: { id: checkpointId, scopeId, status: "ready" },
+ scope: { id: scopeId, cwd: process.cwd() },
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const layerTest = layerCheckpointRollbackService.pipe(
Layer.provide(
Layer.mergeAll(
@@ -204,7 +212,8 @@ it.effect("rejects a rollback when another provider thread became active", () =>
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -267,16 +276,14 @@ it.effect("rejects a rollback when provider selection changed before execution",
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId: selectedProviderInstanceId, model: "test-model" },
},
- providerThreads: [
- {
- id: providerThreadId,
- providerSessionId,
- providerInstanceId: originalProviderInstanceId,
- },
- ],
- checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
- checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
- } as unknown as OrchestrationV2ThreadProjection;
+ providerThread: {
+ id: providerThreadId,
+ providerSessionId,
+ providerInstanceId: originalProviderInstanceId,
+ },
+ checkpoint: { id: checkpointId, scopeId, status: "ready" },
+ scope: { id: scopeId, cwd: process.cwd() },
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const layerTest = layerCheckpointRollbackService.pipe(
Layer.provide(
Layer.mergeAll(
@@ -285,7 +292,8 @@ it.effect("rejects a rollback when provider selection changed before execution",
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -343,14 +351,16 @@ it.effect("rejects an unavailable rollback target before opening a session", ()
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
},
- providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
- providerSessions: [],
- checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 }],
- checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
- runs: [],
- attempts: [],
+ providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
+ providerSession: undefined,
+ checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 },
+ scope: { id: scopeId, cwd: process.cwd() },
+ runsToRollback: [],
+ targetAttempt: undefined,
+ rolledBackAttemptIds: [],
+ staleCheckpoints: [],
providerTurns: [],
- } as unknown as OrchestrationV2ThreadProjection;
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const layerTest = layerCheckpointRollbackService.pipe(
Layer.provide(
Layer.mergeAll(
@@ -359,7 +369,8 @@ it.effect("rejects an unavailable rollback target before opening a session", ()
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -435,15 +446,17 @@ it.effect.each([
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
},
- providerThreads: [providerThread],
- providerSessions: [],
- checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }],
- checkpointScopes: [{ id: scopeId, cwd: worktreePath }],
- runs: [],
- attempts: [],
- nodes: [],
+ providerThread,
+ providerSession: undefined,
+ checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 },
+ scope: { id: scopeId, cwd: worktreePath },
+ runsToRollback: [],
+ targetAttempt: undefined,
+ rolledBackAttemptIds: [],
+ staleCheckpoints: [],
+ rootNodes: [],
providerTurns: [],
- } as unknown as OrchestrationV2ThreadProjection;
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const testLayer = CheckpointRollbackService.layer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -491,7 +504,8 @@ it.effect.each([
}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -611,8 +625,8 @@ it.effect.each([
activeProviderThreadId: providerThreadId,
modelSelection: { instanceId, model: "test" },
},
- providerThreads: [providerThread],
- providerSessions: [],
+ providerThread,
+ providerSession: undefined,
providerTurns: [
...(multipleTurns
? [
@@ -633,20 +647,28 @@ it.effect.each([
status: "completed",
})),
],
- nodes: [],
- attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, runId: `run-${ordinal}` })),
- checkpoints: [
- { id: checkpointId, scopeId, status: "ready", appRunOrdinal: targetOrdinal || null },
- ],
- checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
- runs: [1, 2, 3].map((ordinal) => ({
- id: `run-${ordinal}`,
- ordinal,
- status: ordinal === 3 ? "rolled_back" : "completed",
- rootNodeId: null,
- activeAttemptId: `attempt-${ordinal}`,
- })),
- } as unknown as OrchestrationV2ThreadProjection;
+ rootNodes: [],
+ targetAttempt:
+ targetOrdinal === 0 ? undefined : { id: "attempt-1", providerTurnId: "turn-1" },
+ rolledBackAttemptIds: ["attempt-3"],
+ staleCheckpoints: [],
+ checkpoint: {
+ id: checkpointId,
+ scopeId,
+ status: "ready",
+ appRunOrdinal: targetOrdinal || null,
+ },
+ scope: { id: scopeId, cwd: process.cwd() },
+ runsToRollback: [1, 2]
+ .filter((ordinal) => ordinal > targetOrdinal)
+ .map((ordinal) => ({
+ id: `run-${ordinal}`,
+ ordinal,
+ status: "completed",
+ rootNodeId: null,
+ activeAttemptId: `attempt-${ordinal}`,
+ })),
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const layerTest = layerCheckpointRollbackService.pipe(
Layer.provide(
Layer.mergeAll(
@@ -673,7 +695,8 @@ it.effect.each([
}),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadRecords: () => Effect.succeed(projection),
+ getThread: () => Effect.succeed(projection.thread),
+ getCheckpointRollbackContext: () => Effect.succeed(projection),
getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never),
getCheckpointContext: () =>
Effect.succeed({
@@ -771,3 +794,389 @@ it.effect.skipIf(!symlinksSupported)(
assert.isFalse(isolated);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+const seedRollbackHistory = Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const now = yield* DateTime.now;
+ const threadId = ThreadId.make("rollback-history");
+ const providerThreadId = ProviderThreadId.make("rollback-history-provider");
+ const providerSessionId = ProviderSessionId.make("rollback-history-session");
+ const providerInstanceId = ProviderInstanceId.make("codex");
+ const driver = ProviderDriverKind.make("codex");
+ const modelSelection = { instanceId: providerInstanceId, model: "test" };
+ const scopeId = CheckpointScopeId.make("rollback-history-root");
+ const otherScopeId = CheckpointScopeId.make("rollback-history-child");
+ const runId = (ordinal: number) => RunId.make(`rollback-history-run-${ordinal}`);
+ const nodeId = (ordinal: number) => NodeId.make(`rollback-history-node-${ordinal}`);
+ const attemptId = (ordinal: number) => RunAttemptId.make(`rollback-history-attempt-${ordinal}`);
+ const turnId = (ordinal: number) => ProviderTurnId.make(`rollback-history-turn-${ordinal}`);
+ const checkpointId = (ordinal: number) =>
+ CheckpointId.make(`rollback-history-checkpoint-${ordinal}`);
+ type EventInput<Event = OrchestrationV2DomainEvent> = Event extends OrchestrationV2DomainEvent
+ ? Omit<Event, "id" | "occurredAt" | "threadId">
+ : never;
+ let sequence = 0;
+ const apply = (event: EventInput) =>
+ store.apply({
+ ...event,
+ id: EventId.make(`rollback-history-event-${sequence++}`),
+ threadId,
+ occurredAt: now,
+ } as OrchestrationV2DomainEvent);
+ yield* apply({
+ type: "thread.created",
+ payload: {
+ id: threadId,
+ createdBy: "user",
+ creationSource: "web",
+ projectId: ProjectId.make("rollback-history-project"),
+ title: "Rollback history",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ activeProviderThreadId: providerThreadId,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ });
+ const providerThread = {
+ id: providerThreadId,
+ driver,
+ providerInstanceId,
+ providerSessionId,
+ appThreadId: threadId,
+ ownerNodeId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "idle" as const,
+ firstRunOrdinal: 1,
+ lastRunOrdinal: 6,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ yield* apply({ type: "provider-thread.updated", payload: providerThread });
+ for (const id of [scopeId, otherScopeId]) {
+ yield* apply({
+ type: "checkpoint-scope.created",
+ payload: {
+ id,
+ threadId,
+ runId: runId(1),
+ nodeId: nodeId(1),
+ parentScopeId: id === scopeId ? null : scopeId,
+ providerThreadId,
+ kind: id === scopeId ? "root_run" : "subagent",
+ ordinalWithinParent: 0,
+ advancesAppRunCount: id === scopeId,
+ cwd: process.cwd(),
+ createdAt: now,
+ },
+ });
+ }
+ const statuses = [
+ "completed",
+ "completed",
+ "completed",
+ "interrupted",
+ "failed",
+ "cancelled",
+ "rolled_back",
+ ] as const;
+ for (const [index, status] of statuses.entries()) {
+ const ordinal = index + 1;
+ yield* apply({
+ type: "run.created",
+ payload: {
+ id: runId(ordinal),
+ threadId,
+ ordinal,
+ providerInstanceId,
+ modelSelection,
+ providerThreadId,
+ userMessageId: MessageId.make(`rollback-history-message-${ordinal}`),
+ rootNodeId: nodeId(ordinal),
+ activeAttemptId: attemptId(ordinal),
+ status,
+ requestedAt: now,
+ startedAt: now,
+ completedAt: now,
+ checkpointId: checkpointId(ordinal),
+ contextHandoffId: null,
+ },
+ });
+ yield* apply({
+ type: "node.updated",
+ payload: {
+ id: nodeId(ordinal),
+ threadId,
+ runId: runId(ordinal),
+ parentNodeId: null,
+ rootNodeId: nodeId(ordinal),
+ kind: "root_turn",
+ status,
+ countsForRun: true,
+ providerThreadId,
+ providerTurnId: turnId(ordinal),
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: scopeId,
+ startedAt: now,
+ completedAt: now,
+ },
+ });
+ // Rollback must exclude every attempt of discarded runs, including an inactive retry.
+ for (const attemptOrdinal of ordinal === 7 ? [6.5, 7] : [ordinal]) {
+ yield* apply({
+ type: "run-attempt.created",
+ runId: runId(ordinal),
+ payload: {
+ id: attemptId(attemptOrdinal),
+ runId: runId(ordinal),
+ attemptOrdinal: attemptOrdinal === ordinal ? 2 : 1,
+ rootNodeId: nodeId(ordinal),
+ providerInstanceId,
+ providerThreadId,
+ providerTurnId: turnId(attemptOrdinal),
+ reason: "initial",
+ status: "completed",
+ startedAt: now,
+ completedAt: now,
+ },
+ });
+ yield* apply({
+ type: "provider-turn.updated",
+ payload: {
+ id: turnId(attemptOrdinal),
+ providerThreadId,
+ nodeId: nodeId(ordinal),
+ runAttemptId: attemptId(attemptOrdinal),
+ nativeTurnRef: { driver, nativeId: `native-turn-${attemptOrdinal}`, strength: "strong" },
+ ordinal: attemptOrdinal * 2,
+ status: status === "rolled_back" ? "completed" : status,
+ startedAt: now,
+ completedAt: now,
+ },
+ });
+ }
+ }
+ // A continuation shares the target attempt; its first provider turn is no longer the boundary.
+ yield* apply({
+ type: "provider-turn.updated",
+ payload: {
+ id: turnId(2.5),
+ providerThreadId,
+ nodeId: nodeId(2),
+ runAttemptId: attemptId(2),
+ nativeTurnRef: { driver, nativeId: "native-turn-2-continuation", strength: "strong" },
+ ordinal: 5,
+ status: "completed",
+ startedAt: now,
+ completedAt: now,
+ },
+ });
+ for (let ordinal = 0; ordinal <= 8; ordinal++) {
+ yield* apply({
+ type: "checkpoint.captured",
+ payload: {
+ id: checkpointId(ordinal),
+ threadId,
+ scopeId: ordinal === 8 ? otherScopeId : scopeId,
+ runId: ordinal === 0 ? null : runId(Math.min(ordinal, 7)),
+ nodeId: nodeId(Math.max(1, Math.min(ordinal, 7))),
+ parentCheckpointId: null,
+ ordinalWithinScope: ordinal,
+ appRunOrdinal: ordinal === 0 ? null : ordinal,
+ ref: CheckpointRef.make(`refs/t3/rollback-history/${ordinal}`),
+ status: ordinal === 7 ? "stale" : "ready",
+ files: [],
+ capturedAt: now,
+ },
+ });
+ }
+
+ const rollbackCounts: number[] = [];
+ const restored: CheckpointId[] = [];
+ const deletedRefs: CheckpointId[] = [];
+ const committed: OrchestrationV2DomainEvent[] = [];
+ const serviceLayer = layerCheckpointRollbackService.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ ThreadCommandExecutor.layer,
+ IdAllocator.layer,
+ Layer.mock(CheckpointService.CheckpointServiceV2)({
+ restore: ({ checkpoint }) =>
+ Effect.sync(() => {
+ restored.push(checkpoint.id);
+ }),
+ deleteStaleRefs: ({ checkpoints }) =>
+ Effect.sync(() => {
+ deletedRefs.push(...checkpoints.map((checkpoint) => checkpoint.id));
+ }),
+ }),
+ Layer.mock(EventSink.EventSinkV2)({
+ write: ({ events }) =>
+ Effect.gen(function* () {
+ for (const event of events) yield* store.apply(event);
+ committed.push(...events);
+ return [];
+ }).pipe(
+ Effect.mapError(
+ (cause) =>
+ new EventSink.EventSinkWriteError({
+ eventCount: events.length,
+ cause,
+ }),
+ ),
+ ),
+ }),
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
+ open: () =>
+ Effect.succeed({
+ rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) =>
+ Effect.gen(function* () {
+ rollbackCounts.push(yield* resolveCodexRollbackTurnCount(input));
+ return { providerThread: input.providerThread };
+ }),
+ } as never),
+ }),
+ Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
+ ),
+ ),
+ );
+ const rollback = (ordinal: number) =>
+ Effect.gen(function* () {
+ const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
+ yield* service.execute({
+ threadId,
+ providerThreadId,
+ scopeId,
+ checkpointId: checkpointId(ordinal),
+ });
+ }).pipe(Effect.provide(serviceLayer));
+
+ return {
+ store,
+ now,
+ threadId,
+ runId,
+ nodeId,
+ checkpointId,
+ rollback,
+ rollbackCounts,
+ restored,
+ deletedRefs,
+ committed,
+ };
+});
+
+it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)))(
+ "rollback history reads",
+ (it) => {
+ it.effect("rolls back later terminal runs despite obsolete unrelated SQLite payloads", () =>
+ Effect.gen(function* () {
+ const history = yield* seedRollbackHistory;
+ const sql = yield* SqlClient.SqlClient;
+ const { threadId, runId, nodeId, checkpointId } = history;
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_turn_items (
+ turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
+ parent_item_id, ordinal, type, status, updated_at, payload_json
+ ) VALUES ('rollback-obsolete-transcript', ${threadId}, ${runId(1)}, ${nodeId(1)},
+ NULL, NULL, NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(history.now)},
+ '{"obsolete":"transcript"}')`;
+ yield* sql`UPDATE orchestration_v2_projection_runs
+ SET payload_json = '{"obsolete":"run"}' WHERE run_id = ${runId(1)}`;
+ yield* sql`UPDATE orchestration_v2_projection_nodes
+ SET payload_json = '{"obsolete":"node"}' WHERE node_id = ${nodeId(1)}`;
+ yield* sql`UPDATE orchestration_v2_projection_checkpoints
+ SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
+ WHERE checkpoint_id IN (${checkpointId(0)}, ${checkpointId(1)}, ${checkpointId(7)}, ${checkpointId(8)})`;
+ assert.equal(
+ (yield* Effect.exit(history.store.getThreadProjection(threadId)))._tag,
+ "Failure",
+ );
+
+ yield* history.rollback(2);
+
+ assert.deepEqual(history.rollbackCounts, [4]);
+ assert.deepEqual(history.restored, [checkpointId(2)]);
+ assert.sameMembers(history.deletedRefs, [3, 4, 5, 6].map(checkpointId));
+ const runs = yield* sql<{ ordinal: number; status: string }>`
+ SELECT ordinal, status FROM orchestration_v2_projection_runs
+ WHERE thread_id = ${threadId} ORDER BY ordinal`;
+ assert.deepEqual(
+ runs.map((run) => run.status),
+ [
+ "completed",
+ "completed",
+ "rolled_back",
+ "rolled_back",
+ "rolled_back",
+ "rolled_back",
+ "rolled_back",
+ ],
+ );
+ const nodes = yield* sql<{ status: string }>`
+ SELECT status FROM orchestration_v2_projection_nodes
+ WHERE thread_id = ${threadId} ORDER BY node_id`;
+ assert.deepEqual(
+ nodes.map((node) => node.status),
+ runs.map((run) => run.status),
+ );
+ const checkpoints = yield* sql<{ status: string }>`
+ SELECT status FROM orchestration_v2_projection_checkpoints
+ WHERE thread_id = ${threadId} ORDER BY ordinal_within_scope`;
+ assert.deepEqual(
+ checkpoints.map((checkpoint) => checkpoint.status),
+ ["ready", "ready", "ready", "stale", "stale", "stale", "stale", "stale", "ready"],
+ );
+ }),
+ );
+
+ it.effect(
+ "rewinds stopped runs repeatedly without counting discarded provider turns again",
+ () =>
+ Effect.gen(function* () {
+ const history = yield* seedRollbackHistory;
+ yield* history.rollback(5);
+ yield* history.rollback(2);
+ yield* history.rollback(0);
+ yield* history.rollback(0);
+
+ assert.deepEqual(history.rollbackCounts, [1, 3, 3]);
+ assert.sameMembers(history.deletedRefs, [1, 2, 3, 4, 5, 6].map(history.checkpointId));
+ assert.sameMembers(
+ history.committed
+ .filter((event) => event.type === "run.updated")
+ .map((event) => event.payload.id),
+ [1, 2, 3, 4, 5, 6].map(history.runId),
+ );
+ const records = yield* history.store.getThreadRecords(history.threadId, [
+ "runs",
+ "nodes",
+ "checkpoints",
+ ]);
+ assert.isTrue(records.runs.every((run) => run.status === "rolled_back"));
+ assert.isTrue(records.nodes.every((node) => node.status === "rolled_back"));
+ assert.sameMembers(
+ records.checkpoints
+ .filter((checkpoint) => checkpoint.status === "ready")
+ .map((checkpoint) => checkpoint.id),
+ [history.checkpointId(0), history.checkpointId(8)],
+ );
+ }),
+ );
+ },
+);
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
index 6e408e512ff..03efcaa7f38 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
@@ -141,23 +141,9 @@ export const layer: Layer.Layer<
readonly scopeId: CheckpointScopeId;
readonly restoreFiles?: boolean;
}) {
- const projection = yield* projections.getThreadRecords(input.threadId, [
- "providerThreads",
- "providerSessions",
- "checkpoints",
- "checkpointScopes",
- "runs",
- "attempts",
- "nodes",
- "providerTurns",
- ]);
- const providerThread = projection.providerThreads.find(
- (candidate) => candidate.id === input.providerThreadId,
- );
- const checkpoint = projection.checkpoints.find(
- (candidate) => candidate.id === input.checkpointId,
- );
- const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
+ const context = yield* projections.getCheckpointRollbackContext(input.threadId, input);
+ const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
+ context;
if (
providerThread === undefined ||
providerThread.providerSessionId === null ||
@@ -174,8 +160,8 @@ export const layer: Layer.Layer<
});
}
if (
- providerThread.id !== projection.thread.activeProviderThreadId ||
- providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
+ providerThread.id !== context.thread.activeProviderThreadId ||
+ providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
) {
return yield* new CheckpointRollbackExecutionError({
reason: "active-provider-changed",
@@ -194,13 +180,9 @@ export const layer: Layer.Layer<
appRunOrdinal: 0,
}
: yield* Effect.gen(function* () {
- const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
- const targetAttempt = projection.attempts.find(
- (attempt) => attempt.id === targetRun?.activeAttemptId,
- );
const targetTurn =
- latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ??
- projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
+ latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
+ context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
return yield* new CheckpointRollbackExecutionError({
reason: "provider-turn-unavailable",
@@ -217,7 +199,7 @@ export const layer: Layer.Layer<
};
});
- const { worktreePath, branch } = projection.thread;
+ const { worktreePath, branch } = context.thread;
// Recreated only where the server would have made it, as turn start does.
if (
worktreePath != null &&
@@ -225,7 +207,7 @@ export const layer: Layer.Layer<
!(yield* fileSystem.exists(worktreePath)) &&
(yield* isManagedWorktreePath(worktreePath))
) {
- const project = yield* projects.get(projection.thread.projectId);
+ const project = yield* projects.get(context.thread.projectId);
if (Option.isSome(project)) {
yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
yield* gitWorkflow.createWorktree({
@@ -238,7 +220,7 @@ export const layer: Layer.Layer<
if (
input.restoreFiles !== false &&
- !(yield* isCheckpointRestoreIsolated(projection.thread, scope, {
+ !(yield* isCheckpointRestoreIsolated(context.thread, scope, {
fileSystem,
projections,
projects,
@@ -253,14 +235,12 @@ export const layer: Layer.Layer<
});
}
- const modelSelection = projection.thread.modelSelection;
+ const modelSelection = context.thread.modelSelection;
const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
- thread: projection.thread,
+ thread: context.thread,
modelSelection,
});
- const existingSession = projection.providerSessions.find(
- (candidate) => candidate.id === providerThread.providerSessionId,
- );
+ const existingSession = context.providerSession;
const session = yield* sessions.open({
threadId: input.threadId,
providerSessionId: providerThread.providerSessionId,
@@ -277,25 +257,9 @@ export const layer: Layer.Layer<
}),
});
- 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(
+ // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
+ const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
+ const providerThreadTurns = context.providerTurns.filter(
(turn) =>
turn.providerThreadId === providerThread.id &&
(turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
@@ -310,13 +274,6 @@ export const layer: Layer.Layer<
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 });
}
@@ -366,7 +323,7 @@ export const layer: Layer.Layer<
);
}
for (const run of runsToRollback) {
- const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
+ const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
events.push(
yield* makeEvent({
type: "run.updated",
@@ -401,7 +358,7 @@ export const layer: Layer.Layer<
execute: (input) =>
Effect.gen(function* () {
// Storage cleanup removes worktrees under the same lease.
- const { thread } = yield* projections.getThreadRecords(input.threadId, []);
+ const thread = yield* projections.getThread(input.threadId);
yield* thread.worktreePath === null
? execute(input)
: withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 508365bd789..2aaa3875171 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -16,6 +16,7 @@ import {
import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
import type {
OrchestrationV2AppThread,
+ OrchestrationV2Checkpoint,
OrchestrationV2CheckpointScope,
OrchestrationV2ExecutionNode,
OrchestrationV2PlanArtifact,
@@ -61,6 +62,7 @@ import {
MessageId,
RuntimeRequestId,
CheckpointScopeId,
+ CheckpointId,
ThreadId,
TurnItemId,
NodeId,
@@ -243,6 +245,28 @@ export interface ProjectionCheckpointCaptureContext {
readonly readyCheckpointOrdinals: ReadonlyArray<number>;
}
+const RollbackTargetAttempts = Schema.Array(
+ OrchestrationV2RunAttemptJsonSchema.mapFields(({ id, providerTurnId }) => ({
+ id,
+ providerTurnId,
+ })),
+);
+const decodeRollbackTargetAttempts = Schema.decodeUnknownEffect(RollbackTargetAttempts);
+
+export interface ProjectionCheckpointRollbackContext {
+ readonly thread: OrchestrationV2AppThread;
+ readonly providerThread: OrchestrationV2ProviderThread | undefined;
+ readonly providerSession: OrchestrationV2ThreadProjection["providerSessions"][number] | undefined;
+ readonly checkpoint: OrchestrationV2Checkpoint | undefined;
+ readonly scope: OrchestrationV2CheckpointScope | undefined;
+ readonly targetAttempt: (typeof RollbackTargetAttempts.Type)[number] | undefined;
+ readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
+ readonly rolledBackAttemptIds: ReadonlyArray<RunAttemptId>;
+ readonly runsToRollback: ReadonlyArray<OrchestrationV2Run>;
+ readonly rootNodes: ReadonlyArray<OrchestrationV2ExecutionNode>;
+ readonly staleCheckpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
+}
+
export interface ProjectionProviderControlContext {
readonly providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] | undefined;
readonly providerTurn: OrchestrationV2ProviderTurn | undefined;
@@ -510,6 +534,14 @@ export interface ProjectionStoreV2Shape {
threadId: ThreadId,
target: { readonly runId: RunId; readonly scopeId: CheckpointScopeId },
) => Effect.Effect<ProjectionCheckpointCaptureContext, ProjectionStoreV2Error>;
+ readonly getCheckpointRollbackContext: (
+ threadId: ThreadId,
+ target: {
+ readonly providerThreadId: ProviderThreadId;
+ readonly checkpointId: CheckpointId;
+ readonly scopeId: CheckpointScopeId;
+ },
+ ) => Effect.Effect<ProjectionCheckpointRollbackContext, ProjectionStoreV2Error>;
readonly getRunMessage: (
threadId: ThreadId,
runId: RunId,
@@ -4799,6 +4831,124 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
)
.pipe(Effect.mapError(controlReadError(threadId)));
+ const getCheckpointRollbackContext: ProjectionStoreV2Shape["getCheckpointRollbackContext"] = (
+ threadId,
+ target,
+ ) =>
+ sql
+ .withTransaction(
+ Effect.gen(function* () {
+ const thread = yield* getThread(threadId);
+ const [providerRows, checkpointRows, scopeRows] = yield* Effect.all([
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_provider_threads
+ WHERE provider_thread_id = ${target.providerThreadId}
+ AND (thread_id = ${threadId}
+ OR owner_node_id IN (SELECT node_id FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId})
+ OR provider_thread_id IN (SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId}))`,
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoints
+ WHERE thread_id = ${threadId} AND checkpoint_id = ${target.checkpointId}`,
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes
+ WHERE thread_id = ${threadId} AND scope_id = ${target.scopeId}`,
+ ]);
+ const providerThread =
+ providerRows[0] === undefined
+ ? undefined
+ : yield* decodeProviderThreadPayload(providerRows[0].payload_json);
+ const checkpoint =
+ checkpointRows[0] === undefined
+ ? undefined
+ : yield* decodeCheckpointPayload(checkpointRows[0].payload_json);
+ const scope =
+ scopeRows[0] === undefined
+ ? undefined
+ : yield* decodeCheckpointScopePayload(scopeRows[0].payload_json);
+ const context: ProjectionCheckpointRollbackContext = {
+ thread,
+ providerThread,
+ checkpoint,
+ scope,
+ providerSession: undefined,
+ targetAttempt: undefined,
+ providerTurns: [],
+ rolledBackAttemptIds: [],
+ runsToRollback: [],
+ rootNodes: [],
+ staleCheckpoints: [],
+ };
+ if (
+ providerThread === undefined ||
+ providerThread.providerSessionId === null ||
+ checkpoint === undefined ||
+ scope === undefined ||
+ checkpoint.scopeId !== scope.id ||
+ checkpoint.status !== "ready" ||
+ providerThread.id !== thread.activeProviderThreadId ||
+ providerThread.providerInstanceId !== thread.modelSelection.instanceId
+ )
+ return context;
+
+ const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
+ const [attemptRows, runRows, sessionRows, rolledBackAttempts, staleRows] =
+ yield* Effect.all([
+ sql`SELECT attempt.attempt_id AS id, attempt.provider_turn_id AS "providerTurnId"
+ FROM orchestration_v2_projection_run_attempts AS attempt
+ JOIN orchestration_v2_projection_runs AS run
+ ON attempt.attempt_id = json_extract(run.payload_json, '$.activeAttemptId')
+ WHERE run.thread_id = ${threadId} AND run.ordinal = ${targetOrdinal}
+ AND attempt.thread_id = ${threadId}`,
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_runs
+ WHERE thread_id = ${threadId} AND ordinal > ${targetOrdinal}
+ AND status IN ('completed', 'interrupted', 'failed', 'cancelled')
+ ORDER BY ordinal ASC`,
+ sql<PayloadRow>`SELECT session.payload_json
+ FROM orchestration_v2_projection_provider_sessions AS session
+ JOIN orchestration_v2_projection_provider_session_bindings AS binding
+ ON binding.provider_session_id = session.provider_session_id
+ WHERE binding.thread_id = ${threadId}
+ AND session.provider_session_id = ${providerThread.providerSessionId}`,
+ sql<{ readonly id: RunAttemptId }>`SELECT attempt.attempt_id AS id
+ FROM orchestration_v2_projection_run_attempts AS attempt
+ JOIN orchestration_v2_projection_runs AS run ON run.run_id = attempt.run_id
+ WHERE run.thread_id = ${threadId} AND run.status = 'rolled_back'
+ AND attempt.thread_id = ${threadId}`,
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoints
+ WHERE thread_id = ${threadId} AND scope_id = ${scope.id} AND status = 'ready'
+ AND app_run_ordinal > ${targetOrdinal}
+ ORDER BY ordinal_within_scope ASC`,
+ ]);
+ const targetAttempt = (yield* decodeRollbackTargetAttempts(attemptRows))[0];
+ const runsToRollback = yield* decodeRows(decodeRunPayload, threadId)(runRows);
+ const [nodeRows, turnRows] = yield* Effect.all([
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_nodes
+ WHERE thread_id = ${threadId} AND ${sql.in(
+ "node_id",
+ runsToRollback.map((run) => run.rootNodeId),
+ )}
+ ORDER BY node_id ASC`,
+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_provider_turns
+ WHERE thread_id = ${threadId} AND (
+ provider_thread_id = ${providerThread.id}
+ OR provider_turn_id = ${targetAttempt?.providerTurnId ?? null}
+ OR run_attempt_id = ${targetAttempt?.id ?? null})
+ ORDER BY provider_thread_id ASC, ordinal ASC`,
+ ]);
+ return {
+ ...context,
+ targetAttempt,
+ runsToRollback,
+ providerSession:
+ sessionRows[0] === undefined
+ ? undefined
+ : yield* decodeProviderSessionPayload(sessionRows[0].payload_json),
+ rolledBackAttemptIds: rolledBackAttempts.map(({ id }) => id),
+ rootNodes: yield* decodeRows(decodeNodePayload, threadId)(nodeRows),
+ providerTurns: yield* decodeRows(decodeProviderTurnPayload, threadId)(turnRows),
+ staleCheckpoints: yield* decodeRows(decodeCheckpointPayload, threadId)(staleRows),
+ };
+ }),
+ )
+ .pipe(Effect.mapError(controlReadError(threadId)));
+
const getRunMessage: ProjectionStoreV2Shape["getRunMessage"] = (threadId, runId) =>
sql
.withTransaction(
@@ -6117,6 +6267,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
getRuntimeResponseContext,
getCheckpointContext,
getCheckpointCaptureContext,
+ getCheckpointRollbackContext,
getRunMessage,
canStartQueuedRun,
getPendingNativeUserInputs,
@@ -6632,6 +6783,92 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
.map((candidate) => candidate.ordinalWithinScope),
};
}),
+ getCheckpointRollbackContext: (threadId, target) =>
+ Effect.gen(function* () {
+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);
+ if (projection === undefined)
+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });
+ const { thread } = projection;
+ const providerThread = projection.providerThreads.find(
+ (candidate) => candidate.id === target.providerThreadId,
+ );
+ const checkpoint = projection.checkpoints.find(
+ (candidate) => candidate.id === target.checkpointId,
+ );
+ const scope = projection.checkpointScopes.find(
+ (candidate) => candidate.id === target.scopeId,
+ );
+ const context: ProjectionCheckpointRollbackContext = {
+ thread,
+ providerThread,
+ checkpoint,
+ scope,
+ providerSession: undefined,
+ targetAttempt: undefined,
+ providerTurns: [],
+ rolledBackAttemptIds: [],
+ runsToRollback: [],
+ rootNodes: [],
+ staleCheckpoints: [],
+ };
+ if (
+ providerThread === undefined ||
+ providerThread.providerSessionId === null ||
+ checkpoint === undefined ||
+ scope === undefined ||
+ checkpoint.scopeId !== scope.id ||
+ checkpoint.status !== "ready" ||
+ providerThread.id !== thread.activeProviderThreadId ||
+ providerThread.providerInstanceId !== thread.modelSelection.instanceId
+ )
+ return context;
+
+ const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
+ const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
+ const attempt = projection.attempts.find(
+ (attempt) => attempt.id === targetRun?.activeAttemptId,
+ );
+ const runsToRollback = projection.runs.filter(
+ (run) =>
+ run.ordinal > targetOrdinal &&
+ (run.status === "completed" ||
+ run.status === "interrupted" ||
+ run.status === "failed" ||
+ run.status === "cancelled"),
+ );
+ const rootNodeIds = new Set(runsToRollback.map((run) => run.rootNodeId));
+ const rolledBackRunIds = new Set(
+ projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
+ );
+ return {
+ ...context,
+ targetAttempt:
+ attempt === undefined
+ ? undefined
+ : { id: attempt.id, providerTurnId: attempt.providerTurnId },
+ runsToRollback,
+ rootNodes: projection.nodes.filter((node) => rootNodeIds.has(node.id)),
+ rolledBackAttemptIds: projection.attempts
+ .filter((attempt) => rolledBackRunIds.has(attempt.runId))
+ .map((attempt) => attempt.id),
+ providerSession: projection.providerSessions.find(
+ (session) => session.id === providerThread.providerSessionId,
+ ),
+ providerTurns: projection.providerTurns.filter(
+ (turn) =>
+ turn.providerThreadId === providerThread.id ||
+ turn.id === attempt?.providerTurnId ||
+ (attempt !== undefined && turn.runAttemptId === attempt.id),
+ ),
+ staleCheckpoints: projection.checkpoints.filter(
+ (candidate) =>
+ candidate.scopeId === scope.id &&
+ candidate.appRunOrdinal !== null &&
+ candidate.appRunOrdinal > targetOrdinal &&
+ candidate.status === "ready",
+ ),
+ };
+ }),
getRunMessage: (threadId, runId) =>
Effect.gen(function* () {
const projection = (yield* Ref.get(replayState)).projections.get(threadId);
diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
index b60c4215853..178c6ec3dcc 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
@@ -252,6 +252,7 @@ it.effect(
})),
),
getCheckpointContext: () => Effect.die("not used"),
+ getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
getCheckpointCaptureContext: () => Effect.die("not used"),
getRunMessage: () => Effect.die("not used"),
isNodeStored: () => Effect.die("not used"),