@devries-cameron20 / t3code-1 / commits / eb52bdc4ef
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Julius Marminge committed Oct 19, 2026 at 16:21 UTC eb52bdc4efe24b72d66d57b441b5bab37f1f1d0f
5 files changed +762 -156
apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+13 -11
@@ -3,7 +3,6 @@ import { assert, it } from "@effect/vitest";
3 import {
4 CheckpointId,
5 CheckpointScopeId,
6 - type OrchestrationV2ThreadProjection,
6 ProjectId,
7 ProviderInstanceId,
8 ProviderSessionId,
@@ -25,7 +24,7 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
24 import { CheckpointServiceV2 } from "./CheckpointService.ts";
25 import { EventSinkV2 } from "./EventSink.ts";
26 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
28 -import { ProjectionStoreV2 } from "./ProjectionStore.ts";
27 +import { ProjectionStoreV2, type ProjectionCheckpointRollbackContext } from "./ProjectionStore.ts";
28 import * as ProjectStore from "./ProjectStore.ts";
29 import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
30 import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
@@ -94,15 +93,17 @@ it.effect.each([
93 activeProviderThreadId: providerThreadId,
94 modelSelection: { instanceId, model: "test" },
95 },
97 - providerThreads: [providerThread],
98 - providerSessions: [],
96 + providerThread,
97 + providerSession: undefined,
98 providerTurns: [],
100 - nodes: [],
101 - attempts: [],
102 - checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: null }],
103 - checkpointScopes: [{ id: scopeId, cwd }],
104 - runs: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
105 - } as unknown as OrchestrationV2ThreadProjection;
99 + rootNodes: [],
100 + targetAttempt: undefined,
101 + rolledBackAttemptIds: [],
102 + staleCheckpoints: [],
103 + checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null },
104 + scope: { id: scopeId, cwd },
105 + runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
106 + } as unknown as ProjectionCheckpointRollbackContext;
107 const layerTest = CheckpointRollbackService.layer.pipe(
108 Layer.provide(
109 Layer.mergeAll(
@@ -116,7 +117,8 @@ it.effect.each([
117 get: () => Effect.succeed(Option.some({ workspaceRoot: parent } as never)),
118 }),
119 Layer.mock(ProjectionStoreV2)({
119 - getThreadRecords: () => Effect.succeed(projection),
120 + getThread: () => Effect.succeed(projection.thread),
121 + getCheckpointRollbackContext: () => Effect.succeed(projection),
122 getShellSnapshot: () =>
123 Effect.succeed({
124 schemaVersion: 1,
apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+493 -84
@@ -2,8 +2,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it, vi } from "@effect/vitest";
3 import {
4 CheckpointId,
5 + CheckpointRef,
6 + EventId,
7 + MessageId,
8 + NodeId,
9 + type OrchestrationV2DomainEvent,
10 + ProviderDriverKind,
11 + ProviderTurnId,
12 + RunAttemptId,
13 + RunId,
14 CheckpointScopeId,
6 - type OrchestrationV2ThreadProjection,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderSessionId,
@@ -11,6 +19,8 @@ import {
19 ThreadId,
20 } from "@t3tools/contracts";
21 import * as Effect from "effect/Effect";
22 +import * as DateTime from "effect/DateTime";
23 +import * as SqlClient from "effect/sql/SqlClient";
24 import * as Deferred from "effect/Deferred";
25 import * as Fiber from "effect/Fiber";
26 import * as FileSystem from "effect/FileSystem";
@@ -19,6 +29,7 @@ import * as Option from "effect/Option";
29 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
30 import * as Layer from "effect/Layer";
31
32 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
33 import * as ServerConfig from "../config.ts";
34 import * as ServerSettings from "../serverSettings.ts";
35 import * as GitWorkflow from "../git/GitWorkflowService.ts";
@@ -67,33 +78,25 @@ it.effect.each(["initial", "waiting"])(
78 const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
79 const readEntered = Deferred.makeUnsafe<void>();
80 const release = Deferred.makeUnsafe<void>();
70 - let readCount = 0;
81 let projection = {
82 thread: {
83 worktreePath: process.cwd(),
84 activeProviderThreadId: providerThreadId,
85 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
86 },
77 - providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
78 - checkpoints: [
79 - {
80 - id: checkpointId,
81 - scopeId,
82 - status: state === "waiting" ? "ready" : "stale",
83 - appRunOrdinal: 0,
84 - },
85 - ],
86 - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
87 - } as unknown as OrchestrationV2ThreadProjection;
88 - const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(
89 - () => {
90 - const current = projection;
91 - readCount++;
92 - return readCount === 1
93 - ? Deferred.succeed(readEntered, undefined).pipe(Effect.as(current))
94 - : Effect.succeed(current);
87 + providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
88 + checkpoint: {
89 + id: checkpointId,
90 + scopeId,
91 + status: state === "waiting" ? "ready" : "stale",
92 + appRunOrdinal: 0,
93 },
94 + scope: { id: scopeId, cwd: process.cwd() },
95 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
96 + const getThread = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThread"]>(() =>
97 + Deferred.succeed(readEntered, undefined).pipe(Effect.as(projection.thread)),
98 );
99 + const getCheckpointRollbackContext = vi.fn(() => Effect.succeed(projection));
100 const testLayer = layerCheckpointRollbackService.pipe(
101 Layer.provide(
102 Layer.mergeAll(
@@ -102,7 +105,8 @@ it.effect.each(["initial", "waiting"])(
105 Layer.mock(EventSink.EventSinkV2)({}),
106 IdAllocator.layer,
107 Layer.mock(ProjectionStore.ProjectionStoreV2)({
105 - getThreadRecords,
108 + getThread,
109 + getCheckpointRollbackContext,
110 getShellSnapshot: () =>
111 Effect.succeed({
112 schemaVersion: 1,
@@ -137,19 +141,25 @@ it.effect.each(["initial", "waiting"])(
141 yield* Deferred.await(readEntered);
142 projection = {
143 ...projection,
140 - checkpoints: projection.checkpoints.map((checkpoint) => ({
141 - ...checkpoint,
142 - status: "stale",
143 - })),
144 + checkpoint: { ...projection.checkpoint!, status: "stale" },
145 };
146 yield* Deferred.succeed(release, undefined);
147 if (holder !== undefined) yield* Fiber.join(holder);
148 }
149 const error = yield* Fiber.join(rollback);
150
150 - assert.equal(getThreadRecords.mock.calls.length, 2);
151 - assert.deepEqual(getThreadRecords.mock.calls[0]?.[1], []);
152 - assert.equal(getThreadRecords.mock.calls[1]?.[1].includes("checkpoints"), true);
151 + assert.deepEqual(getThread.mock.calls, [[threadId]]);
152 + assert.deepEqual(getCheckpointRollbackContext.mock.calls, [
153 + [
154 + threadId,
155 + {
156 + threadId,
157 + providerThreadId,
158 + checkpointId,
159 + scopeId,
160 + },
161 + ],
162 + ]);
163 assert.equal(error.reason, "rollback-target-invalid");
164 assert.equal(
165 error.message,
@@ -186,16 +196,14 @@ it.effect("rejects a rollback when another provider thread became active", () =>
196 activeProviderThreadId,
197 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
198 },
189 - providerThreads: [
190 - {
191 - id: requestedProviderThreadId,
192 - providerSessionId,
193 - providerInstanceId,
194 - },
195 - ],
196 - checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
197 - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
198 - } as unknown as OrchestrationV2ThreadProjection;
199 + providerThread: {
200 + id: requestedProviderThreadId,
201 + providerSessionId,
202 + providerInstanceId,
203 + },
204 + checkpoint: { id: checkpointId, scopeId, status: "ready" },
205 + scope: { id: scopeId, cwd: process.cwd() },
206 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
207 const layerTest = layerCheckpointRollbackService.pipe(
208 Layer.provide(
209 Layer.mergeAll(
@@ -204,7 +212,8 @@ it.effect("rejects a rollback when another provider thread became active", () =>
212 Layer.mock(EventSink.EventSinkV2)({}),
213 IdAllocator.layer,
214 Layer.mock(ProjectionStore.ProjectionStoreV2)({
207 - getThreadRecords: () => Effect.succeed(projection),
215 + getThread: () => Effect.succeed(projection.thread),
216 + getCheckpointRollbackContext: () => Effect.succeed(projection),
217 getShellSnapshot: () =>
218 Effect.succeed({
219 schemaVersion: 1,
@@ -267,16 +276,14 @@ it.effect("rejects a rollback when provider selection changed before execution",
276 activeProviderThreadId: providerThreadId,
277 modelSelection: { instanceId: selectedProviderInstanceId, model: "test-model" },
278 },
270 - providerThreads: [
271 - {
272 - id: providerThreadId,
273 - providerSessionId,
274 - providerInstanceId: originalProviderInstanceId,
275 - },
276 - ],
277 - checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
278 - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
279 - } as unknown as OrchestrationV2ThreadProjection;
279 + providerThread: {
280 + id: providerThreadId,
281 + providerSessionId,
282 + providerInstanceId: originalProviderInstanceId,
283 + },
284 + checkpoint: { id: checkpointId, scopeId, status: "ready" },
285 + scope: { id: scopeId, cwd: process.cwd() },
286 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
287 const layerTest = layerCheckpointRollbackService.pipe(
288 Layer.provide(
289 Layer.mergeAll(
@@ -285,7 +292,8 @@ it.effect("rejects a rollback when provider selection changed before execution",
292 Layer.mock(EventSink.EventSinkV2)({}),
293 IdAllocator.layer,
294 Layer.mock(ProjectionStore.ProjectionStoreV2)({
288 - getThreadRecords: () => Effect.succeed(projection),
295 + getThread: () => Effect.succeed(projection.thread),
296 + getCheckpointRollbackContext: () => Effect.succeed(projection),
297 getShellSnapshot: () =>
298 Effect.succeed({
299 schemaVersion: 1,
@@ -343,14 +351,16 @@ it.effect("rejects an unavailable rollback target before opening a session", ()
351 activeProviderThreadId: providerThreadId,
352 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
353 },
346 - providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
347 - providerSessions: [],
348 - checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 }],
349 - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
350 - runs: [],
351 - attempts: [],
354 + providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
355 + providerSession: undefined,
356 + checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 },
357 + scope: { id: scopeId, cwd: process.cwd() },
358 + runsToRollback: [],
359 + targetAttempt: undefined,
360 + rolledBackAttemptIds: [],
361 + staleCheckpoints: [],
362 providerTurns: [],
353 - } as unknown as OrchestrationV2ThreadProjection;
363 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
364 const layerTest = layerCheckpointRollbackService.pipe(
365 Layer.provide(
366 Layer.mergeAll(
@@ -359,7 +369,8 @@ it.effect("rejects an unavailable rollback target before opening a session", ()
369 Layer.mock(EventSink.EventSinkV2)({}),
370 IdAllocator.layer,
371 Layer.mock(ProjectionStore.ProjectionStoreV2)({
362 - getThreadRecords: () => Effect.succeed(projection),
372 + getThread: () => Effect.succeed(projection.thread),
373 + getCheckpointRollbackContext: () => Effect.succeed(projection),
374 getShellSnapshot: () =>
375 Effect.succeed({
376 schemaVersion: 1,
@@ -435,15 +446,17 @@ it.effect.each([
446 activeProviderThreadId: providerThreadId,
447 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
448 },
438 - providerThreads: [providerThread],
439 - providerSessions: [],
440 - checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }],
441 - checkpointScopes: [{ id: scopeId, cwd: worktreePath }],
442 - runs: [],
443 - attempts: [],
444 - nodes: [],
449 + providerThread,
450 + providerSession: undefined,
451 + checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 },
452 + scope: { id: scopeId, cwd: worktreePath },
453 + runsToRollback: [],
454 + targetAttempt: undefined,
455 + rolledBackAttemptIds: [],
456 + staleCheckpoints: [],
457 + rootNodes: [],
458 providerTurns: [],
446 - } as unknown as OrchestrationV2ThreadProjection;
459 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
460 const testLayer = CheckpointRollbackService.layer.pipe(
461 Layer.provide(
462 Layer.mergeAll(
@@ -491,7 +504,8 @@ it.effect.each([
504 }),
505 IdAllocator.layer,
506 Layer.mock(ProjectionStore.ProjectionStoreV2)({
494 - getThreadRecords: () => Effect.succeed(projection),
507 + getThread: () => Effect.succeed(projection.thread),
508 + getCheckpointRollbackContext: () => Effect.succeed(projection),
509 getShellSnapshot: () =>
510 Effect.succeed({
511 schemaVersion: 1,
@@ -611,8 +625,8 @@ it.effect.each([
625 activeProviderThreadId: providerThreadId,
626 modelSelection: { instanceId, model: "test" },
627 },
614 - providerThreads: [providerThread],
615 - providerSessions: [],
628 + providerThread,
629 + providerSession: undefined,
630 providerTurns: [
631 ...(multipleTurns
632 ? [
@@ -633,20 +647,28 @@ it.effect.each([
647 status: "completed",
648 })),
649 ],
636 - nodes: [],
637 - attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, runId: `run-${ordinal}` })),
638 - checkpoints: [
639 - { id: checkpointId, scopeId, status: "ready", appRunOrdinal: targetOrdinal || null },
640 - ],
641 - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
642 - runs: [1, 2, 3].map((ordinal) => ({
643 - id: `run-${ordinal}`,
644 - ordinal,
645 - status: ordinal === 3 ? "rolled_back" : "completed",
646 - rootNodeId: null,
647 - activeAttemptId: `attempt-${ordinal}`,
648 - })),
649 - } as unknown as OrchestrationV2ThreadProjection;
650 + rootNodes: [],
651 + targetAttempt:
652 + targetOrdinal === 0 ? undefined : { id: "attempt-1", providerTurnId: "turn-1" },
653 + rolledBackAttemptIds: ["attempt-3"],
654 + staleCheckpoints: [],
655 + checkpoint: {
656 + id: checkpointId,
657 + scopeId,
658 + status: "ready",
659 + appRunOrdinal: targetOrdinal || null,
660 + },
661 + scope: { id: scopeId, cwd: process.cwd() },
662 + runsToRollback: [1, 2]
663 + .filter((ordinal) => ordinal > targetOrdinal)
664 + .map((ordinal) => ({
665 + id: `run-${ordinal}`,
666 + ordinal,
667 + status: "completed",
668 + rootNodeId: null,
669 + activeAttemptId: `attempt-${ordinal}`,
670 + })),
671 + } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
672 const layerTest = layerCheckpointRollbackService.pipe(
673 Layer.provide(
674 Layer.mergeAll(
@@ -673,7 +695,8 @@ it.effect.each([
695 }),
696 IdAllocator.layer,
697 Layer.mock(ProjectionStore.ProjectionStoreV2)({
676 - getThreadRecords: () => Effect.succeed(projection),
698 + getThread: () => Effect.succeed(projection.thread),
699 + getCheckpointRollbackContext: () => Effect.succeed(projection),
700 getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never),
701 getCheckpointContext: () =>
702 Effect.succeed({
@@ -771,3 +794,389 @@ it.effect.skipIf(!symlinksSupported)(
794 assert.isFalse(isolated);
795 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
796 );
797 +
798 +const seedRollbackHistory = Effect.gen(function* () {
799 + const store = yield* ProjectionStore.ProjectionStoreV2;
800 + const now = yield* DateTime.now;
801 + const threadId = ThreadId.make("rollback-history");
802 + const providerThreadId = ProviderThreadId.make("rollback-history-provider");
803 + const providerSessionId = ProviderSessionId.make("rollback-history-session");
804 + const providerInstanceId = ProviderInstanceId.make("codex");
805 + const driver = ProviderDriverKind.make("codex");
806 + const modelSelection = { instanceId: providerInstanceId, model: "test" };
807 + const scopeId = CheckpointScopeId.make("rollback-history-root");
808 + const otherScopeId = CheckpointScopeId.make("rollback-history-child");
809 + const runId = (ordinal: number) => RunId.make(`rollback-history-run-${ordinal}`);
810 + const nodeId = (ordinal: number) => NodeId.make(`rollback-history-node-${ordinal}`);
811 + const attemptId = (ordinal: number) => RunAttemptId.make(`rollback-history-attempt-${ordinal}`);
812 + const turnId = (ordinal: number) => ProviderTurnId.make(`rollback-history-turn-${ordinal}`);
813 + const checkpointId = (ordinal: number) =>
814 + CheckpointId.make(`rollback-history-checkpoint-${ordinal}`);
815 + type EventInput<Event = OrchestrationV2DomainEvent> = Event extends OrchestrationV2DomainEvent
816 + ? Omit<Event, "id" | "occurredAt" | "threadId">
817 + : never;
818 + let sequence = 0;
819 + const apply = (event: EventInput) =>
820 + store.apply({
821 + ...event,
822 + id: EventId.make(`rollback-history-event-${sequence++}`),
823 + threadId,
824 + occurredAt: now,
825 + } as OrchestrationV2DomainEvent);
826 + yield* apply({
827 + type: "thread.created",
828 + payload: {
829 + id: threadId,
830 + createdBy: "user",
831 + creationSource: "web",
832 + projectId: ProjectId.make("rollback-history-project"),
833 + title: "Rollback history",
834 + providerInstanceId,
835 + modelSelection,
836 + runtimeMode: "full-access",
837 + interactionMode: "default",
838 + branch: null,
839 + worktreePath: process.cwd(),
840 + activeProviderThreadId: providerThreadId,
841 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
842 + forkedFrom: null,
843 + createdAt: now,
844 + updatedAt: now,
845 + archivedAt: null,
846 + settledOverride: null,
847 + settledAt: null,
848 + lastVisitedAt: null,
849 + deletedAt: null,
850 + },
851 + });
852 + const providerThread = {
853 + id: providerThreadId,
854 + driver,
855 + providerInstanceId,
856 + providerSessionId,
857 + appThreadId: threadId,
858 + ownerNodeId: null,
859 + nativeThreadRef: null,
860 + nativeConversationHeadRef: null,
861 + status: "idle" as const,
862 + firstRunOrdinal: 1,
863 + lastRunOrdinal: 6,
864 + handoffIds: [],
865 + forkedFrom: null,
866 + createdAt: now,
867 + updatedAt: now,
868 + };
869 + yield* apply({ type: "provider-thread.updated", payload: providerThread });
870 + for (const id of [scopeId, otherScopeId]) {
871 + yield* apply({
872 + type: "checkpoint-scope.created",
873 + payload: {
874 + id,
875 + threadId,
876 + runId: runId(1),
877 + nodeId: nodeId(1),
878 + parentScopeId: id === scopeId ? null : scopeId,
879 + providerThreadId,
880 + kind: id === scopeId ? "root_run" : "subagent",
881 + ordinalWithinParent: 0,
882 + advancesAppRunCount: id === scopeId,
883 + cwd: process.cwd(),
884 + createdAt: now,
885 + },
886 + });
887 + }
888 + const statuses = [
889 + "completed",
890 + "completed",
891 + "completed",
892 + "interrupted",
893 + "failed",
894 + "cancelled",
895 + "rolled_back",
896 + ] as const;
897 + for (const [index, status] of statuses.entries()) {
898 + const ordinal = index + 1;
899 + yield* apply({
900 + type: "run.created",
901 + payload: {
902 + id: runId(ordinal),
903 + threadId,
904 + ordinal,
905 + providerInstanceId,
906 + modelSelection,
907 + providerThreadId,
908 + userMessageId: MessageId.make(`rollback-history-message-${ordinal}`),
909 + rootNodeId: nodeId(ordinal),
910 + activeAttemptId: attemptId(ordinal),
911 + status,
912 + requestedAt: now,
913 + startedAt: now,
914 + completedAt: now,
915 + checkpointId: checkpointId(ordinal),
916 + contextHandoffId: null,
917 + },
918 + });
919 + yield* apply({
920 + type: "node.updated",
921 + payload: {
922 + id: nodeId(ordinal),
923 + threadId,
924 + runId: runId(ordinal),
925 + parentNodeId: null,
926 + rootNodeId: nodeId(ordinal),
927 + kind: "root_turn",
928 + status,
929 + countsForRun: true,
930 + providerThreadId,
931 + providerTurnId: turnId(ordinal),
932 + nativeItemRef: null,
933 + runtimeRequestId: null,
934 + checkpointScopeId: scopeId,
935 + startedAt: now,
936 + completedAt: now,
937 + },
938 + });
939 + // Rollback must exclude every attempt of discarded runs, including an inactive retry.
940 + for (const attemptOrdinal of ordinal === 7 ? [6.5, 7] : [ordinal]) {
941 + yield* apply({
942 + type: "run-attempt.created",
943 + runId: runId(ordinal),
944 + payload: {
945 + id: attemptId(attemptOrdinal),
946 + runId: runId(ordinal),
947 + attemptOrdinal: attemptOrdinal === ordinal ? 2 : 1,
948 + rootNodeId: nodeId(ordinal),
949 + providerInstanceId,
950 + providerThreadId,
951 + providerTurnId: turnId(attemptOrdinal),
952 + reason: "initial",
953 + status: "completed",
954 + startedAt: now,
955 + completedAt: now,
956 + },
957 + });
958 + yield* apply({
959 + type: "provider-turn.updated",
960 + payload: {
961 + id: turnId(attemptOrdinal),
962 + providerThreadId,
963 + nodeId: nodeId(ordinal),
964 + runAttemptId: attemptId(attemptOrdinal),
965 + nativeTurnRef: { driver, nativeId: `native-turn-${attemptOrdinal}`, strength: "strong" },
966 + ordinal: attemptOrdinal * 2,
967 + status: status === "rolled_back" ? "completed" : status,
968 + startedAt: now,
969 + completedAt: now,
970 + },
971 + });
972 + }
973 + }
974 + // A continuation shares the target attempt; its first provider turn is no longer the boundary.
975 + yield* apply({
976 + type: "provider-turn.updated",
977 + payload: {
978 + id: turnId(2.5),
979 + providerThreadId,
980 + nodeId: nodeId(2),
981 + runAttemptId: attemptId(2),
982 + nativeTurnRef: { driver, nativeId: "native-turn-2-continuation", strength: "strong" },
983 + ordinal: 5,
984 + status: "completed",
985 + startedAt: now,
986 + completedAt: now,
987 + },
988 + });
989 + for (let ordinal = 0; ordinal <= 8; ordinal++) {
990 + yield* apply({
991 + type: "checkpoint.captured",
992 + payload: {
993 + id: checkpointId(ordinal),
994 + threadId,
995 + scopeId: ordinal === 8 ? otherScopeId : scopeId,
996 + runId: ordinal === 0 ? null : runId(Math.min(ordinal, 7)),
997 + nodeId: nodeId(Math.max(1, Math.min(ordinal, 7))),
998 + parentCheckpointId: null,
999 + ordinalWithinScope: ordinal,
1000 + appRunOrdinal: ordinal === 0 ? null : ordinal,
1001 + ref: CheckpointRef.make(`refs/t3/rollback-history/${ordinal}`),
1002 + status: ordinal === 7 ? "stale" : "ready",
1003 + files: [],
1004 + capturedAt: now,
1005 + },
1006 + });
1007 + }
1008 +
1009 + const rollbackCounts: number[] = [];
1010 + const restored: CheckpointId[] = [];
1011 + const deletedRefs: CheckpointId[] = [];
1012 + const committed: OrchestrationV2DomainEvent[] = [];
1013 + const serviceLayer = layerCheckpointRollbackService.pipe(
1014 + Layer.provide(
1015 + Layer.mergeAll(
1016 + ThreadCommandExecutor.layer,
1017 + IdAllocator.layer,
1018 + Layer.mock(CheckpointService.CheckpointServiceV2)({
1019 + restore: ({ checkpoint }) =>
1020 + Effect.sync(() => {
1021 + restored.push(checkpoint.id);
1022 + }),
1023 + deleteStaleRefs: ({ checkpoints }) =>
1024 + Effect.sync(() => {
1025 + deletedRefs.push(...checkpoints.map((checkpoint) => checkpoint.id));
1026 + }),
1027 + }),
1028 + Layer.mock(EventSink.EventSinkV2)({
1029 + write: ({ events }) =>
1030 + Effect.gen(function* () {
1031 + for (const event of events) yield* store.apply(event);
1032 + committed.push(...events);
1033 + return [];
1034 + }).pipe(
1035 + Effect.mapError(
1036 + (cause) =>
1037 + new EventSink.EventSinkWriteError({
1038 + eventCount: events.length,
1039 + cause,
1040 + }),
1041 + ),
1042 + ),
1043 + }),
1044 + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
1045 + open: () =>
1046 + Effect.succeed({
1047 + rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) =>
1048 + Effect.gen(function* () {
1049 + rollbackCounts.push(yield* resolveCodexRollbackTurnCount(input));
1050 + return { providerThread: input.providerThread };
1051 + }),
1052 + } as never),
1053 + }),
1054 + Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
1055 + ),
1056 + ),
1057 + );
1058 + const rollback = (ordinal: number) =>
1059 + Effect.gen(function* () {
1060 + const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
1061 + yield* service.execute({
1062 + threadId,
1063 + providerThreadId,
1064 + scopeId,
1065 + checkpointId: checkpointId(ordinal),
1066 + });
1067 + }).pipe(Effect.provide(serviceLayer));
1068 +
1069 + return {
1070 + store,
1071 + now,
1072 + threadId,
1073 + runId,
1074 + nodeId,
1075 + checkpointId,
1076 + rollback,
1077 + rollbackCounts,
1078 + restored,
1079 + deletedRefs,
1080 + committed,
1081 + };
1082 +});
1083 +
1084 +it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)))(
1085 + "rollback history reads",
1086 + (it) => {
1087 + it.effect("rolls back later terminal runs despite obsolete unrelated SQLite payloads", () =>
1088 + Effect.gen(function* () {
1089 + const history = yield* seedRollbackHistory;
1090 + const sql = yield* SqlClient.SqlClient;
1091 + const { threadId, runId, nodeId, checkpointId } = history;
1092 + yield* sql`
1093 + INSERT INTO orchestration_v2_projection_turn_items (
1094 + turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
1095 + parent_item_id, ordinal, type, status, updated_at, payload_json
1096 + ) VALUES ('rollback-obsolete-transcript', ${threadId}, ${runId(1)}, ${nodeId(1)},
1097 + NULL, NULL, NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(history.now)},
1098 + '{"obsolete":"transcript"}')`;
1099 + yield* sql`UPDATE orchestration_v2_projection_runs
1100 + SET payload_json = '{"obsolete":"run"}' WHERE run_id = ${runId(1)}`;
1101 + yield* sql`UPDATE orchestration_v2_projection_nodes
1102 + SET payload_json = '{"obsolete":"node"}' WHERE node_id = ${nodeId(1)}`;
1103 + yield* sql`UPDATE orchestration_v2_projection_checkpoints
1104 + SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
1105 + WHERE checkpoint_id IN (${checkpointId(0)}, ${checkpointId(1)}, ${checkpointId(7)}, ${checkpointId(8)})`;
1106 + assert.equal(
1107 + (yield* Effect.exit(history.store.getThreadProjection(threadId)))._tag,
1108 + "Failure",
1109 + );
1110 +
1111 + yield* history.rollback(2);
1112 +
1113 + assert.deepEqual(history.rollbackCounts, [4]);
1114 + assert.deepEqual(history.restored, [checkpointId(2)]);
1115 + assert.sameMembers(history.deletedRefs, [3, 4, 5, 6].map(checkpointId));
1116 + const runs = yield* sql<{ ordinal: number; status: string }>`
1117 + SELECT ordinal, status FROM orchestration_v2_projection_runs
1118 + WHERE thread_id = ${threadId} ORDER BY ordinal`;
1119 + assert.deepEqual(
1120 + runs.map((run) => run.status),
1121 + [
1122 + "completed",
1123 + "completed",
1124 + "rolled_back",
1125 + "rolled_back",
1126 + "rolled_back",
1127 + "rolled_back",
1128 + "rolled_back",
1129 + ],
1130 + );
1131 + const nodes = yield* sql<{ status: string }>`
1132 + SELECT status FROM orchestration_v2_projection_nodes
1133 + WHERE thread_id = ${threadId} ORDER BY node_id`;
1134 + assert.deepEqual(
1135 + nodes.map((node) => node.status),
1136 + runs.map((run) => run.status),
1137 + );
1138 + const checkpoints = yield* sql<{ status: string }>`
1139 + SELECT status FROM orchestration_v2_projection_checkpoints
1140 + WHERE thread_id = ${threadId} ORDER BY ordinal_within_scope`;
1141 + assert.deepEqual(
1142 + checkpoints.map((checkpoint) => checkpoint.status),
1143 + ["ready", "ready", "ready", "stale", "stale", "stale", "stale", "stale", "ready"],
1144 + );
1145 + }),
1146 + );
1147 +
1148 + it.effect(
1149 + "rewinds stopped runs repeatedly without counting discarded provider turns again",
1150 + () =>
1151 + Effect.gen(function* () {
1152 + const history = yield* seedRollbackHistory;
1153 + yield* history.rollback(5);
1154 + yield* history.rollback(2);
1155 + yield* history.rollback(0);
1156 + yield* history.rollback(0);
1157 +
1158 + assert.deepEqual(history.rollbackCounts, [1, 3, 3]);
1159 + assert.sameMembers(history.deletedRefs, [1, 2, 3, 4, 5, 6].map(history.checkpointId));
1160 + assert.sameMembers(
1161 + history.committed
1162 + .filter((event) => event.type === "run.updated")
1163 + .map((event) => event.payload.id),
1164 + [1, 2, 3, 4, 5, 6].map(history.runId),
1165 + );
1166 + const records = yield* history.store.getThreadRecords(history.threadId, [
1167 + "runs",
1168 + "nodes",
1169 + "checkpoints",
1170 + ]);
1171 + assert.isTrue(records.runs.every((run) => run.status === "rolled_back"));
1172 + assert.isTrue(records.nodes.every((node) => node.status === "rolled_back"));
1173 + assert.sameMembers(
1174 + records.checkpoints
1175 + .filter((checkpoint) => checkpoint.status === "ready")
1176 + .map((checkpoint) => checkpoint.id),
1177 + [history.checkpointId(0), history.checkpointId(8)],
1178 + );
1179 + }),
1180 + );
1181 + },
1182 +);
apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+18 -61
@@ -141,23 +141,9 @@ export const layer: Layer.Layer<
141 readonly scopeId: CheckpointScopeId;
142 readonly restoreFiles?: boolean;
143 }) {
144 - const projection = yield* projections.getThreadRecords(input.threadId, [
145 - "providerThreads",
146 - "providerSessions",
147 - "checkpoints",
148 - "checkpointScopes",
149 - "runs",
150 - "attempts",
151 - "nodes",
152 - "providerTurns",
153 - ]);
154 - const providerThread = projection.providerThreads.find(
155 - (candidate) => candidate.id === input.providerThreadId,
156 - );
157 - const checkpoint = projection.checkpoints.find(
158 - (candidate) => candidate.id === input.checkpointId,
159 - );
160 - const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
144 + const context = yield* projections.getCheckpointRollbackContext(input.threadId, input);
145 + const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
146 + context;
147 if (
148 providerThread === undefined ||
149 providerThread.providerSessionId === null ||
@@ -174,8 +160,8 @@ export const layer: Layer.Layer<
160 });
161 }
162 if (
177 - providerThread.id !== projection.thread.activeProviderThreadId ||
178 - providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
163 + providerThread.id !== context.thread.activeProviderThreadId ||
164 + providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
165 ) {
166 return yield* new CheckpointRollbackExecutionError({
167 reason: "active-provider-changed",
@@ -194,13 +180,9 @@ export const layer: Layer.Layer<
180 appRunOrdinal: 0,
181 }
182 : yield* Effect.gen(function* () {
197 - const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
198 - const targetAttempt = projection.attempts.find(
199 - (attempt) => attempt.id === targetRun?.activeAttemptId,
200 - );
183 const targetTurn =
202 - latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ??
203 - projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
184 + latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
185 + context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
186 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
187 return yield* new CheckpointRollbackExecutionError({
188 reason: "provider-turn-unavailable",
@@ -217,7 +199,7 @@ export const layer: Layer.Layer<
199 };
200 });
201
220 - const { worktreePath, branch } = projection.thread;
202 + const { worktreePath, branch } = context.thread;
203 // Recreated only where the server would have made it, as turn start does.
204 if (
205 worktreePath != null &&
@@ -225,7 +207,7 @@ export const layer: Layer.Layer<
207 !(yield* fileSystem.exists(worktreePath)) &&
208 (yield* isManagedWorktreePath(worktreePath))
209 ) {
228 - const project = yield* projects.get(projection.thread.projectId);
210 + const project = yield* projects.get(context.thread.projectId);
211 if (Option.isSome(project)) {
212 yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
213 yield* gitWorkflow.createWorktree({
@@ -238,7 +220,7 @@ export const layer: Layer.Layer<
220
221 if (
222 input.restoreFiles !== false &&
241 - !(yield* isCheckpointRestoreIsolated(projection.thread, scope, {
223 + !(yield* isCheckpointRestoreIsolated(context.thread, scope, {
224 fileSystem,
225 projections,
226 projects,
@@ -253,14 +235,12 @@ export const layer: Layer.Layer<
235 });
236 }
237
256 - const modelSelection = projection.thread.modelSelection;
238 + const modelSelection = context.thread.modelSelection;
239 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
258 - thread: projection.thread,
240 + thread: context.thread,
241 modelSelection,
242 });
261 - const existingSession = projection.providerSessions.find(
262 - (candidate) => candidate.id === providerThread.providerSessionId,
263 - );
243 + const existingSession = context.providerSession;
244 const session = yield* sessions.open({
245 threadId: input.threadId,
246 providerSessionId: providerThread.providerSessionId,
@@ -277,25 +257,9 @@ export const layer: Layer.Layer<
257 }),
258 });
259
280 - const runsToRollback = projection.runs.filter(
281 - (run) =>
282 - run.ordinal > targetOrdinal &&
283 - (run.status === "completed" ||
284 - run.status === "interrupted" ||
285 - run.status === "failed" ||
286 - run.status === "cancelled"),
287 - );
288 - // Rolled-back turns stay in the audit history, but no longer exist in
289 - // the provider conversation and must not be counted by a later rewind.
290 - const rolledBackRunIds = new Set(
291 - projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
292 - );
293 - const rolledBackAttemptIds = new Set(
294 - projection.attempts
295 - .filter((attempt) => rolledBackRunIds.has(attempt.runId))
296 - .map((attempt) => attempt.id),
297 - );
298 - const providerThreadTurns = projection.providerTurns.filter(
260 + // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
261 + const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
262 + const providerThreadTurns = context.providerTurns.filter(
263 (turn) =>
264 turn.providerThreadId === providerThread.id &&
265 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
@@ -310,13 +274,6 @@ export const layer: Layer.Layer<
274 providerThreadTurns,
275 });
276 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
313 - const staleCheckpoints = projection.checkpoints.filter(
314 - (candidate) =>
315 - candidate.scopeId === scope.id &&
316 - candidate.appRunOrdinal !== null &&
317 - candidate.appRunOrdinal > targetOrdinal &&
318 - candidate.status === "ready",
319 - );
277 if (staleCheckpoints.length > 0) {
278 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
279 }
@@ -366,7 +323,7 @@ export const layer: Layer.Layer<
323 );
324 }
325 for (const run of runsToRollback) {
369 - const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
326 + const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
327 events.push(
328 yield* makeEvent({
329 type: "run.updated",
@@ -401,7 +358,7 @@ export const layer: Layer.Layer<
358 execute: (input) =>
359 Effect.gen(function* () {
360 // Storage cleanup removes worktrees under the same lease.
404 - const { thread } = yield* projections.getThreadRecords(input.threadId, []);
361 + const thread = yield* projections.getThread(input.threadId);
362 yield* thread.worktreePath === null
363 ? execute(input)
364 : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
apps/server/src/orchestration-v2/ProjectionStore.ts
+237
@@ -16,6 +16,7 @@ import {
16 import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
17 import type {
18 OrchestrationV2AppThread,
19 + OrchestrationV2Checkpoint,
20 OrchestrationV2CheckpointScope,
21 OrchestrationV2ExecutionNode,
22 OrchestrationV2PlanArtifact,
@@ -61,6 +62,7 @@ import {
62 MessageId,
63 RuntimeRequestId,
64 CheckpointScopeId,
65 + CheckpointId,
66 ThreadId,
67 TurnItemId,
68 NodeId,
@@ -243,6 +245,28 @@ export interface ProjectionCheckpointCaptureContext {
245 readonly readyCheckpointOrdinals: ReadonlyArray<number>;
246 }
247
248 +const RollbackTargetAttempts = Schema.Array(
249 + OrchestrationV2RunAttemptJsonSchema.mapFields(({ id, providerTurnId }) => ({
250 + id,
251 + providerTurnId,
252 + })),
253 +);
254 +const decodeRollbackTargetAttempts = Schema.decodeUnknownEffect(RollbackTargetAttempts);
255 +
256 +export interface ProjectionCheckpointRollbackContext {
257 + readonly thread: OrchestrationV2AppThread;
258 + readonly providerThread: OrchestrationV2ProviderThread | undefined;
259 + readonly providerSession: OrchestrationV2ThreadProjection["providerSessions"][number] | undefined;
260 + readonly checkpoint: OrchestrationV2Checkpoint | undefined;
261 + readonly scope: OrchestrationV2CheckpointScope | undefined;
262 + readonly targetAttempt: (typeof RollbackTargetAttempts.Type)[number] | undefined;
263 + readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
264 + readonly rolledBackAttemptIds: ReadonlyArray<RunAttemptId>;
265 + readonly runsToRollback: ReadonlyArray<OrchestrationV2Run>;
266 + readonly rootNodes: ReadonlyArray<OrchestrationV2ExecutionNode>;
267 + readonly staleCheckpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
268 +}
269 +
270 export interface ProjectionProviderControlContext {
271 readonly providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] | undefined;
272 readonly providerTurn: OrchestrationV2ProviderTurn | undefined;
@@ -510,6 +534,14 @@ export interface ProjectionStoreV2Shape {
534 threadId: ThreadId,
535 target: { readonly runId: RunId; readonly scopeId: CheckpointScopeId },
536 ) => Effect.Effect<ProjectionCheckpointCaptureContext, ProjectionStoreV2Error>;
537 + readonly getCheckpointRollbackContext: (
538 + threadId: ThreadId,
539 + target: {
540 + readonly providerThreadId: ProviderThreadId;
541 + readonly checkpointId: CheckpointId;
542 + readonly scopeId: CheckpointScopeId;
543 + },
544 + ) => Effect.Effect<ProjectionCheckpointRollbackContext, ProjectionStoreV2Error>;
545 readonly getRunMessage: (
546 threadId: ThreadId,
547 runId: RunId,
@@ -4799,6 +4831,124 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4831 )
4832 .pipe(Effect.mapError(controlReadError(threadId)));
4833
4834 + const getCheckpointRollbackContext: ProjectionStoreV2Shape["getCheckpointRollbackContext"] = (
4835 + threadId,
4836 + target,
4837 + ) =>
4838 + sql
4839 + .withTransaction(
4840 + Effect.gen(function* () {
4841 + const thread = yield* getThread(threadId);
4842 + const [providerRows, checkpointRows, scopeRows] = yield* Effect.all([
4843 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_provider_threads
4844 + WHERE provider_thread_id = ${target.providerThreadId}
4845 + AND (thread_id = ${threadId}
4846 + OR owner_node_id IN (SELECT node_id FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId})
4847 + OR provider_thread_id IN (SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId}))`,
4848 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoints
4849 + WHERE thread_id = ${threadId} AND checkpoint_id = ${target.checkpointId}`,
4850 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes
4851 + WHERE thread_id = ${threadId} AND scope_id = ${target.scopeId}`,
4852 + ]);
4853 + const providerThread =
4854 + providerRows[0] === undefined
4855 + ? undefined
4856 + : yield* decodeProviderThreadPayload(providerRows[0].payload_json);
4857 + const checkpoint =
4858 + checkpointRows[0] === undefined
4859 + ? undefined
4860 + : yield* decodeCheckpointPayload(checkpointRows[0].payload_json);
4861 + const scope =
4862 + scopeRows[0] === undefined
4863 + ? undefined
4864 + : yield* decodeCheckpointScopePayload(scopeRows[0].payload_json);
4865 + const context: ProjectionCheckpointRollbackContext = {
4866 + thread,
4867 + providerThread,
4868 + checkpoint,
4869 + scope,
4870 + providerSession: undefined,
4871 + targetAttempt: undefined,
4872 + providerTurns: [],
4873 + rolledBackAttemptIds: [],
4874 + runsToRollback: [],
4875 + rootNodes: [],
4876 + staleCheckpoints: [],
4877 + };
4878 + if (
4879 + providerThread === undefined ||
4880 + providerThread.providerSessionId === null ||
4881 + checkpoint === undefined ||
4882 + scope === undefined ||
4883 + checkpoint.scopeId !== scope.id ||
4884 + checkpoint.status !== "ready" ||
4885 + providerThread.id !== thread.activeProviderThreadId ||
4886 + providerThread.providerInstanceId !== thread.modelSelection.instanceId
4887 + )
4888 + return context;
4889 +
4890 + const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
4891 + const [attemptRows, runRows, sessionRows, rolledBackAttempts, staleRows] =
4892 + yield* Effect.all([
4893 + sql`SELECT attempt.attempt_id AS id, attempt.provider_turn_id AS "providerTurnId"
4894 + FROM orchestration_v2_projection_run_attempts AS attempt
4895 + JOIN orchestration_v2_projection_runs AS run
4896 + ON attempt.attempt_id = json_extract(run.payload_json, '$.activeAttemptId')
4897 + WHERE run.thread_id = ${threadId} AND run.ordinal = ${targetOrdinal}
4898 + AND attempt.thread_id = ${threadId}`,
4899 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_runs
4900 + WHERE thread_id = ${threadId} AND ordinal > ${targetOrdinal}
4901 + AND status IN ('completed', 'interrupted', 'failed', 'cancelled')
4902 + ORDER BY ordinal ASC`,
4903 + sql<PayloadRow>`SELECT session.payload_json
4904 + FROM orchestration_v2_projection_provider_sessions AS session
4905 + JOIN orchestration_v2_projection_provider_session_bindings AS binding
4906 + ON binding.provider_session_id = session.provider_session_id
4907 + WHERE binding.thread_id = ${threadId}
4908 + AND session.provider_session_id = ${providerThread.providerSessionId}`,
4909 + sql<{ readonly id: RunAttemptId }>`SELECT attempt.attempt_id AS id
4910 + FROM orchestration_v2_projection_run_attempts AS attempt
4911 + JOIN orchestration_v2_projection_runs AS run ON run.run_id = attempt.run_id
4912 + WHERE run.thread_id = ${threadId} AND run.status = 'rolled_back'
4913 + AND attempt.thread_id = ${threadId}`,
4914 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_checkpoints
4915 + WHERE thread_id = ${threadId} AND scope_id = ${scope.id} AND status = 'ready'
4916 + AND app_run_ordinal > ${targetOrdinal}
4917 + ORDER BY ordinal_within_scope ASC`,
4918 + ]);
4919 + const targetAttempt = (yield* decodeRollbackTargetAttempts(attemptRows))[0];
4920 + const runsToRollback = yield* decodeRows(decodeRunPayload, threadId)(runRows);
4921 + const [nodeRows, turnRows] = yield* Effect.all([
4922 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_nodes
4923 + WHERE thread_id = ${threadId} AND ${sql.in(
4924 + "node_id",
4925 + runsToRollback.map((run) => run.rootNodeId),
4926 + )}
4927 + ORDER BY node_id ASC`,
4928 + sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_provider_turns
4929 + WHERE thread_id = ${threadId} AND (
4930 + provider_thread_id = ${providerThread.id}
4931 + OR provider_turn_id = ${targetAttempt?.providerTurnId ?? null}
4932 + OR run_attempt_id = ${targetAttempt?.id ?? null})
4933 + ORDER BY provider_thread_id ASC, ordinal ASC`,
4934 + ]);
4935 + return {
4936 + ...context,
4937 + targetAttempt,
4938 + runsToRollback,
4939 + providerSession:
4940 + sessionRows[0] === undefined
4941 + ? undefined
4942 + : yield* decodeProviderSessionPayload(sessionRows[0].payload_json),
4943 + rolledBackAttemptIds: rolledBackAttempts.map(({ id }) => id),
4944 + rootNodes: yield* decodeRows(decodeNodePayload, threadId)(nodeRows),
4945 + providerTurns: yield* decodeRows(decodeProviderTurnPayload, threadId)(turnRows),
4946 + staleCheckpoints: yield* decodeRows(decodeCheckpointPayload, threadId)(staleRows),
4947 + };
4948 + }),
4949 + )
4950 + .pipe(Effect.mapError(controlReadError(threadId)));
4951 +
4952 const getRunMessage: ProjectionStoreV2Shape["getRunMessage"] = (threadId, runId) =>
4953 sql
4954 .withTransaction(
@@ -6117,6 +6267,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6267 getRuntimeResponseContext,
6268 getCheckpointContext,
6269 getCheckpointCaptureContext,
6270 + getCheckpointRollbackContext,
6271 getRunMessage,
6272 canStartQueuedRun,
6273 getPendingNativeUserInputs,
@@ -6632,6 +6783,92 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6783 .map((candidate) => candidate.ordinalWithinScope),
6784 };
6785 }),
6786 + getCheckpointRollbackContext: (threadId, target) =>
6787 + Effect.gen(function* () {
6788 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6789 + if (projection === undefined)
6790 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6791 + const { thread } = projection;
6792 + const providerThread = projection.providerThreads.find(
6793 + (candidate) => candidate.id === target.providerThreadId,
6794 + );
6795 + const checkpoint = projection.checkpoints.find(
6796 + (candidate) => candidate.id === target.checkpointId,
6797 + );
6798 + const scope = projection.checkpointScopes.find(
6799 + (candidate) => candidate.id === target.scopeId,
6800 + );
6801 + const context: ProjectionCheckpointRollbackContext = {
6802 + thread,
6803 + providerThread,
6804 + checkpoint,
6805 + scope,
6806 + providerSession: undefined,
6807 + targetAttempt: undefined,
6808 + providerTurns: [],
6809 + rolledBackAttemptIds: [],
6810 + runsToRollback: [],
6811 + rootNodes: [],
6812 + staleCheckpoints: [],
6813 + };
6814 + if (
6815 + providerThread === undefined ||
6816 + providerThread.providerSessionId === null ||
6817 + checkpoint === undefined ||
6818 + scope === undefined ||
6819 + checkpoint.scopeId !== scope.id ||
6820 + checkpoint.status !== "ready" ||
6821 + providerThread.id !== thread.activeProviderThreadId ||
6822 + providerThread.providerInstanceId !== thread.modelSelection.instanceId
6823 + )
6824 + return context;
6825 +
6826 + const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
6827 + const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
6828 + const attempt = projection.attempts.find(
6829 + (attempt) => attempt.id === targetRun?.activeAttemptId,
6830 + );
6831 + const runsToRollback = projection.runs.filter(
6832 + (run) =>
6833 + run.ordinal > targetOrdinal &&
6834 + (run.status === "completed" ||
6835 + run.status === "interrupted" ||
6836 + run.status === "failed" ||
6837 + run.status === "cancelled"),
6838 + );
6839 + const rootNodeIds = new Set(runsToRollback.map((run) => run.rootNodeId));
6840 + const rolledBackRunIds = new Set(
6841 + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
6842 + );
6843 + return {
6844 + ...context,
6845 + targetAttempt:
6846 + attempt === undefined
6847 + ? undefined
6848 + : { id: attempt.id, providerTurnId: attempt.providerTurnId },
6849 + runsToRollback,
6850 + rootNodes: projection.nodes.filter((node) => rootNodeIds.has(node.id)),
6851 + rolledBackAttemptIds: projection.attempts
6852 + .filter((attempt) => rolledBackRunIds.has(attempt.runId))
6853 + .map((attempt) => attempt.id),
6854 + providerSession: projection.providerSessions.find(
6855 + (session) => session.id === providerThread.providerSessionId,
6856 + ),
6857 + providerTurns: projection.providerTurns.filter(
6858 + (turn) =>
6859 + turn.providerThreadId === providerThread.id ||
6860 + turn.id === attempt?.providerTurnId ||
6861 + (attempt !== undefined && turn.runAttemptId === attempt.id),
6862 + ),
6863 + staleCheckpoints: projection.checkpoints.filter(
6864 + (candidate) =>
6865 + candidate.scopeId === scope.id &&
6866 + candidate.appRunOrdinal !== null &&
6867 + candidate.appRunOrdinal > targetOrdinal &&
6868 + candidate.status === "ready",
6869 + ),
6870 + };
6871 + }),
6872 getRunMessage: (threadId, runId) =>
6873 Effect.gen(function* () {
6874 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+1
@@ -252,6 +252,7 @@ it.effect(
252 })),
253 ),
254 getCheckpointContext: () => Effect.die("not used"),
255 + getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
256 getCheckpointCaptureContext: () => Effect.die("not used"),
257 getRunMessage: () => Effect.die("not used"),
258 isNodeStored: () => Effect.die("not used"),