Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointRollbackService.test.ts

1,001 lines39.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, vi } from "@effect/vitest";
3import {
4 CheckpointId,
5 CheckpointRef,
6 EventId,
7 MessageId,
8 NodeId,
9 type OrchestrationV2DomainEvent,
10 ProviderDriverKind,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 CheckpointScopeId,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderSessionId,
18 ProviderThreadId,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Effect from "effect/Effect";
22import * as DateTime from "effect/DateTime";
23import * as SqlClient from "effect/sql/SqlClient";
24import * as Deferred from "effect/Deferred";
25import * as Fiber from "effect/Fiber";
26import * as FileSystem from "effect/FileSystem";
27import * as Path from "effect/Path";
28import * as Option from "effect/Option";
29import * as Layer from "effect/Layer";
30​
31import * as SqlitePersistence from "../persistence/Sqlite.ts";
32import * as ServerConfig from "../config.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as GitWorkflow from "../git/GitWorkflowService.ts";
35import { withTurnStartReservation, withWorkspaceLease } from "../workspace/workspaceLease.ts";
36import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
37import { resolveCodexRollbackTurnCount } from "./Adapters/CodexAdapterV2.ts";
38import * as CheckpointService from "./CheckpointService.ts";
39import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
40import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
41import * as EventSink from "./EventSink.ts";
42import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
43import * as ProjectionStore from "./ProjectionStore.ts";
44import * as ProjectStore from "./ProjectStore.ts";
45import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
46import * as ProviderSessionManager from "./ProviderSessionManager.ts";
47import * as RuntimePolicy from "./RuntimePolicy.ts";
48import { layerNoTaskFolders } from "./ProviderTurnStartService.testkit.ts";
49​
50const unrelatedProject = Option.some({
51 workspaceRoot: "/nonexistent/t3-rollback-project",
52} as never);
53const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
54 Layer.provide(
55 Layer.mergeAll(
56 NodeServices.layer,
57 layerNoTaskFolders,
58 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
59 ServerSettings.layerTest(),
60 Layer.mock(GitWorkflow.GitWorkflowService)({}),
61 Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
62 ),
63 ),
64);
65​
66it.effect.each(["initial", "waiting"])(
67 "rejects a non-ready checkpoint from %s before opening a session or restoring files",
68 (state) => {
69 const threadId = ThreadId.make("thread:rollback-non-ready");
70 const providerThreadId = ProviderThreadId.make("provider-thread:rollback-non-ready");
71 const providerSessionId = ProviderSessionId.make("provider-session:rollback-non-ready");
72 const checkpointId = CheckpointId.make("checkpoint:rollback-non-ready");
73 const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-non-ready");
74 const providerInstanceId = ProviderInstanceId.make("provider_rollback_non_ready");
75 const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
76 const open = vi.fn(() => Effect.die("provider session open must not run"));
77 const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
78 const readEntered = Deferred.makeUnsafe<void>();
79 const release = Deferred.makeUnsafe<void>();
80 let projection = {
81 thread: {
82 worktreePath: process.cwd(),
83 activeProviderThreadId: providerThreadId,
84 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
85 },
86 providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
87 checkpoint: {
88 id: checkpointId,
89 scopeId,
90 status: state === "waiting" ? "ready" : "stale",
91 appRunOrdinal: 0,
92 },
93 scope: { id: scopeId, cwd: process.cwd() },
94 } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
95 const getThread = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThread"]>(() =>
96 Deferred.succeed(readEntered, undefined).pipe(Effect.as(projection.thread)),
97 );
98 const getCheckpointRollbackContext = vi.fn(() => Effect.succeed(projection));
99 const testLayer = layerCheckpointRollbackService.pipe(
100 Layer.provide(
101 Layer.mergeAll(
102 ThreadCommandExecutor.layer,
103 Layer.mock(CheckpointService.CheckpointServiceV2)({
104 restore,
105 discardRepositorySnapshots: () => Effect.void,
106 }),
107 Layer.mock(EventSink.EventSinkV2)({}),
108 IdAllocator.layer,
109 Layer.mock(ProjectionStore.ProjectionStoreV2)({
110 getThread,
111 getCheckpointRollbackContext,
112 getShellSnapshot: () =>
113 Effect.succeed({
114 schemaVersion: 1,
115 snapshotSequence: 0,
116 threads: [],
117 archivedThreads: [],
118 }),
119 }),
120 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
121 Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
122 ),
123 ),
124 );
125​
126 return Effect.gen(function* () {
127 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
128 const holder =
129 state === "waiting"
130 ? yield* withWorkspaceLease(process.cwd(), Deferred.await(release)).pipe(
131 Effect.forkChild({ startImmediately: true }),
132 )
133 : undefined;
134 const rollback = yield* service
135 .execute({
136 threadId,
137 providerThreadId,
138 checkpointId,
139 scopeId,
140 })
141 .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
142 if (state === "waiting") {
143 yield* Deferred.await(readEntered);
144 projection = {
145 ...projection,
146 checkpoint: { ...projection.checkpoint!, status: "stale" },
147 };
148 yield* Deferred.succeed(release, undefined);
149 if (holder !== undefined) yield* Fiber.join(holder);
150 }
151 const error = yield* Fiber.join(rollback);
152​
153 assert.deepEqual(getThread.mock.calls, [[threadId]]);
154 assert.deepEqual(getCheckpointRollbackContext.mock.calls, [
155 [
156 threadId,
157 {
158 threadId,
159 providerThreadId,
160 checkpointId,
161 scopeId,
162 },
163 ],
164 ]);
165 assert.equal(error.reason, "rollback-target-invalid");
166 assert.equal(
167 error.message,
168 `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`,
169 );
170 assert.equal(error.cause, undefined);
171 assert.equal(resolveRuntimePolicy.mock.calls.length, 0);
172 assert.equal(open.mock.calls.length, 0);
173 assert.equal(restore.mock.calls.length, 0);
174 }).pipe(Effect.provide(testLayer));
175 },
176);
177​
178it.effect.each([
179 { order: "cleanup-first", restoreFiles: true },
180 { order: "rollback-first", restoreFiles: true },
181 { order: "cleanup-first", restoreFiles: false, unmanaged: true },
182 { order: "cleanup-first", restoreFiles: true, leavesFolder: true },
183 { order: "cleanup-first", restoreFiles: false, leavesFolder: true },
184 { order: "cleanup-first", restoreFiles: true, leavesFolder: true, shared: true },
185 { order: "cleanup-first", restoreFiles: true, leavesFolder: true, createFails: true },
186])("locks rollback with %s", (row) =>
187 Effect.gen(function* () {
188 const { order, restoreFiles, unmanaged, leavesFolder, shared, createFails } = row;
189 const fileSystem = yield* FileSystem.FileSystem;
190 const path = yield* Path.Path;
191 const workspaceRoot = yield* fileSystem.realPath(
192 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" }),
193 );
194 const worktreesDir = path.join(workspaceRoot, "worktrees");
195 const worktreePath = unmanaged
196 ? path.join(workspaceRoot, "elsewhere", "feature")
197 : path.join(worktreesDir, "repo", "feature");
198 yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true });
199 const threadId = ThreadId.make("rollback-worktree");
200 const projectId = ProjectId.make("rollback-worktree-project");
201 const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread");
202 const providerSessionId = ProviderSessionId.make("rollback-worktree-provider-session");
203 const providerInstanceId = ProviderInstanceId.make("rollback-worktree-provider-instance");
204 const checkpointId = CheckpointId.make("rollback-worktree-checkpoint");
205 const scopeId = CheckpointScopeId.make("rollback-worktree-scope");
206 const branch = "feature/rollback";
207 const release = Deferred.makeUnsafe<void>();
208 const openEntered = Deferred.makeUnsafe<void>();
209 const calls: string[] = [];
210 let cleanupEntered = false;
211 const providerThread = { id: providerThreadId, providerSessionId, providerInstanceId };
212 const projection = {
213 thread: {
214 id: threadId,
215 projectId,
216 worktreePath,
217 branch,
218 activeProviderThreadId: providerThreadId,
219 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
220 },
221 providerThread,
222 providerSession: undefined,
223 checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 },
224 scope: { id: scopeId, cwd: worktreePath },
225 runsToRollback: [],
226 targetAttempt: undefined,
227 rolledBackAttemptIds: [],
228 staleCheckpoints: [],
229 rootNodes: [],
230 providerTurns: [],
231 } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
232 const testLayer = CheckpointRollbackService.layer.pipe(
233 Layer.provide(
234 Layer.mergeAll(
235 ThreadCommandExecutor.layer,
236 NodeServices.layer,
237 layerNoTaskFolders,
238 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
239 ServerSettings.layerTest(),
240 Layer.mock(ProjectStore.ProjectStoreV2)({
241 get: (id) => {
242 assert.equal(id, projectId);
243 return Effect.succeedSome({ workspaceRoot } as never);
244 },
245 }),
246 Layer.mock(GitWorkflow.GitWorkflowService)({
247 pruneWorktrees: (input) =>
248 Effect.sync(() => {
249 assert.deepEqual(input, { cwd: workspaceRoot });
250 calls.push("prune");
251 }),
252 createWorktree: (input) =>
253 Effect.gen(function* () {
254 assert.deepEqual(input, {
255 cwd: workspaceRoot,
256 refName: branch,
257 path: worktreePath,
258 });
259 calls.push("create");
260 if (createFails) return yield* Effect.die("the branch is gone");
261 yield* fileSystem
262 .makeDirectory(path.join(worktreePath, ".git"), { recursive: true })
263 .pipe(Effect.orDie);
264 return {} as never;
265 }),
266 }),
267 Layer.mock(CheckpointService.CheckpointServiceV2)({
268 discardRepositorySnapshots: () => Effect.void,
269 restore: () =>
270 Effect.gen(function* () {
271 assert.isTrue(
272 yield* fileSystem.exists(path.join(worktreePath, ".git")).pipe(Effect.orDie),
273 );
274 calls.push("files");
275 }),
276 }),
277 Layer.mock(EventSink.EventSinkV2)({
278 write: () =>
279 Effect.sync(() => {
280 calls.push("projection");
281 return [];
282 }),
283 }),
284 IdAllocator.layer,
285 Layer.mock(ProjectionStore.ProjectionStoreV2)({
286 getThread: () => Effect.succeed(projection.thread),
287 getCheckpointRollbackContext: () => Effect.succeed(projection),
288 getShellSnapshot: () =>
289 Effect.succeed({
290 schemaVersion: 1,
291 snapshotSequence: 0,
292 threads: shared
293 ? [
294 {
295 id: ThreadId.make("rollback-worktree-sharer"),
296 projectId,
297 worktreePath,
298 deletedAt: null,
299 lineage: {},
300 },
301 ]
302 : [],
303 archivedThreads: [],
304 } as never),
305 getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] } as never),
306 getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never),
307 }),
308 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
309 open: (input) =>
310 Effect.gen(function* () {
311 assert.equal(input.runtimePolicy.cwd, worktreePath);
312 if (!(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie))) {
313 return yield* new ProviderWorkspaceMissingError({
314 threadId,
315 cwd: worktreePath,
316 });
317 }
318 calls.push("session");
319 yield* Deferred.succeed(openEntered, undefined);
320 if (order === "rollback-first") yield* Deferred.await(release);
321 return {} as never;
322 }),
323 }),
324 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
325 resolve: ({ thread }) => {
326 assert.equal(thread.worktreePath, worktreePath);
327 return Effect.succeed({ cwd: thread.worktreePath } as never);
328 },
329 }),
330 ),
331 ),
332 );
333 yield* Effect.gen(function* () {
334 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
335 const cleanupEffect = withWorkspaceLease(
336 worktreePath,
337 Effect.gen(function* () {
338 cleanupEntered = true;
339 if (order === "cleanup-first") yield* Deferred.await(release);
340 yield* fileSystem.remove(worktreePath, { recursive: true, force: true });
341 // A failed `git worktree remove` can leave the folder without its checkout.
342 if (leavesFolder) {
343 yield* fileSystem.makeDirectory(worktreePath);
344 yield* fileSystem.writeFileString(path.join(worktreePath, "unsaved.txt"), "keep");
345 }
346 calls.push("cleanup");
347 }),
348 );
349 const cleanup =
350 order === "cleanup-first"
351 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
352 : undefined;
353 const rollback = yield* service
354 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
355 .pipe(Effect.forkChild({ startImmediately: true }));
356 if (order === "cleanup-first") assert.deepEqual(calls, []);
357 if (order === "rollback-first") yield* Deferred.await(openEntered);
358 const laterCleanup =
359 order === "rollback-first"
360 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
361 : undefined;
362 if (order === "rollback-first") assert.isFalse(cleanupEntered);
363 yield* Deferred.succeed(release, undefined);
364 if (cleanup !== undefined) yield* Fiber.join(cleanup);
365 if (unmanaged || shared) {
366 const error = yield* Fiber.join(rollback).pipe(Effect.flip);
367 assert.equal(error._tag, "CheckpointRollbackExecutionError");
368 assert.deepEqual(calls, ["cleanup"]);
369 if (shared) {
370 assert.equal(error.reason, "shared-workspace");
371 assert.isTrue(yield* fileSystem.exists(path.join(worktreePath, "unsaved.txt")));
372 }
373 return;
374 }
375 if (createFails) {
376 yield* Fiber.join(rollback).pipe(Effect.exit);
377 assert.deepEqual(calls, ["cleanup", "prune", "create"]);
378 assert.equal(
379 yield* fileSystem.readFileString(path.join(worktreePath, "unsaved.txt")),
380 "keep",
381 );
382 assert.deepEqual(yield* fileSystem.readDirectory(path.dirname(worktreePath)), ["feature"]);
383 return;
384 }
385 yield* Fiber.join(rollback);
386 if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
387 const rollbackCalls = restoreFiles
388 ? ["session", "files", "projection"]
389 : ["session", "projection"];
390 const recreates = !leavesFolder || restoreFiles;
391 assert.deepEqual(
392 calls,
393 order === "cleanup-first"
394 ? ["cleanup", ...(recreates ? ["prune", "create"] : []), ...rollbackCalls]
395 : [...rollbackCalls, "cleanup"],
396 );
397 if (!recreates) {
398 assert.isTrue(yield* fileSystem.exists(path.join(worktreePath, "unsaved.txt")));
399 }
400 }).pipe(Effect.provide(testLayer));
401 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
402);
403​
404it.effect.each([
405 { restoreFiles: true, status: "ready" },
406 { restoreFiles: false, status: "ready" },
407 // A failed capture still pins the conversation.
408 { restoreFiles: false, status: "error" },
409])(
410 "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint",
411 ({ restoreFiles, status }) =>
412 Effect.gen(function* () {
413 const fileSystem = yield* FileSystem.FileSystem;
414 const path = yield* Path.Path;
415 const workspaceRoot = yield* fileSystem.realPath(
416 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-reservation-" }),
417 );
418 const worktreesDir = path.join(workspaceRoot, "worktrees");
419 const worktreePath = path.join(worktreesDir, "repo", "feature");
420 yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true });
421 const threadId = ThreadId.make("rollback-reservation");
422 const providerThreadId = ProviderThreadId.make("rollback-reservation-provider-thread");
423 const providerInstanceId = ProviderInstanceId.make("rollback-reservation-provider");
424 const checkpointId = CheckpointId.make("rollback-reservation-checkpoint");
425 const scopeId = CheckpointScopeId.make("rollback-reservation-scope");
426 const release = Deferred.makeUnsafe<void>();
427 const openEntered = Deferred.makeUnsafe<void>();
428 const restoreEntered = Deferred.makeUnsafe<void>();
429 const releaseRestore = Deferred.makeUnsafe<void>();
430 const calls: string[] = [];
431 const projection = {
432 thread: {
433 id: threadId,
434 projectId: ProjectId.make("rollback-reservation-project"),
435 worktreePath,
436 branch: "feature/rollback-reservation",
437 activeProviderThreadId: providerThreadId,
438 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
439 },
440 providerThread: {
441 id: providerThreadId,
442 providerSessionId: ProviderSessionId.make("rollback-reservation-session"),
443 providerInstanceId,
444 },
445 providerSession: undefined,
446 checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 },
447 scope: { id: scopeId, cwd: worktreePath },
448 runsToRollback: [],
449 targetAttempt: undefined,
450 rolledBackAttemptIds: [],
451 staleCheckpoints: [],
452 rootNodes: [],
453 providerTurns: [],
454 } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
455 const testLayer = CheckpointRollbackService.layer.pipe(
456 Layer.provide(
457 Layer.mergeAll(
458 ThreadCommandExecutor.layer,
459 NodeServices.layer,
460 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
461 ServerSettings.layerTest(),
462 Layer.mock(ProjectStore.ProjectStoreV2)({
463 get: () => Effect.succeedSome({ workspaceRoot } as never),
464 }),
465 layerNoTaskFolders,
466 Layer.mock(GitWorkflow.GitWorkflowService)({}),
467 Layer.mock(CheckpointService.CheckpointServiceV2)({
468 discardRepositorySnapshots: () => Effect.void,
469 restore: () =>
470 Deferred.succeed(restoreEntered, undefined).pipe(
471 Effect.andThen(Deferred.await(releaseRestore)),
472 Effect.andThen(Effect.sync(() => calls.push("files"))),
473 ),
474 }),
475 Layer.mock(EventSink.EventSinkV2)({ write: () => Effect.succeed([]) }),
476 IdAllocator.layer,
477 Layer.mock(ProjectionStore.ProjectionStoreV2)({
478 getThread: () => Effect.succeed(projection.thread),
479 getCheckpointRollbackContext: () => Effect.succeed(projection),
480 getShellSnapshot: () =>
481 Effect.succeed({
482 schemaVersion: 1,
483 snapshotSequence: 0,
484 threads: [],
485 archivedThreads: [],
486 }),
487 }),
488 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
489 open: () =>
490 Deferred.succeed(openEntered, undefined).pipe(
491 Effect.andThen(Deferred.await(release)),
492 Effect.as({} as never),
493 ),
494 }),
495 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
496 resolve: () => Effect.succeed({ cwd: worktreePath } as never),
497 }),
498 ),
499 ),
500 );
501 yield* Effect.gen(function* () {
502 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
503 const rollback = yield* service
504 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
505 .pipe(Effect.forkChild({ startImmediately: true }));
506 yield* Deferred.await(openEntered);
507 // A synchronous realPath lets the forked start reach the reservation
508 // before the next assertion, so "not entered" means "waiting".
509 const startTurn = withTurnStartReservation(
510 FileSystem.makeNoop({ realPath: (target) => Effect.succeed(target) }),
511 path,
512 path.join(worktreePath, "packages", "app"),
513 Effect.sync(() => calls.push("turn start")),
514 ).pipe(Effect.forkChild({ startImmediately: true }));
515 const turnStart = yield* startTurn;
516 if (restoreFiles) {
517 assert.deepEqual(calls, []);
518 yield* Deferred.succeed(release, undefined);
519 // The reservation must still be held while files are being restored,
520 // not only while the provider rollback is in flight.
521 yield* Deferred.await(restoreEntered);
522 const duringRestore = yield* startTurn;
523 assert.deepEqual(calls, []);
524 yield* Deferred.succeed(releaseRestore, undefined);
525 yield* Fiber.join(duringRestore);
526 } else {
527 // Nothing is rewritten, so the turn start must not wait for the provider.
528 yield* Fiber.join(turnStart);
529 yield* Deferred.succeed(release, undefined);
530 }
531 yield* Fiber.join(rollback);
532 yield* Fiber.join(turnStart);
533 assert.deepEqual(
534 calls,
535 restoreFiles ? ["files", "turn start", "turn start"] : ["turn start"],
536 );
537 }).pipe(Effect.provide(testLayer));
538 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
539);
540​
541const seedRollbackHistory = Effect.gen(function* () {
542 const store = yield* ProjectionStore.ProjectionStoreV2;
543 const now = yield* DateTime.now;
544 const threadId = ThreadId.make("rollback-history");
545 const providerThreadId = ProviderThreadId.make("rollback-history-provider");
546 const providerSessionId = ProviderSessionId.make("rollback-history-session");
547 const providerInstanceId = ProviderInstanceId.make("codex");
548 const driver = ProviderDriverKind.make("codex");
549 const modelSelection = { instanceId: providerInstanceId, model: "test" };
550 const scopeId = CheckpointScopeId.make("rollback-history-root");
551 const otherScopeId = CheckpointScopeId.make("rollback-history-child");
552 const repositoryScopeId = CheckpointScopeId.make("rollback-history-repository");
553 const runId = (ordinal: number) => RunId.make(`rollback-history-run-${ordinal}`);
554 const nodeId = (ordinal: number) => NodeId.make(`rollback-history-node-${ordinal}`);
555 const attemptId = (ordinal: number) => RunAttemptId.make(`rollback-history-attempt-${ordinal}`);
556 const turnId = (ordinal: number) => ProviderTurnId.make(`rollback-history-turn-${ordinal}`);
557 const checkpointId = (ordinal: number) =>
558 CheckpointId.make(`rollback-history-checkpoint-${ordinal}`);
559 type EventInput<Event = OrchestrationV2DomainEvent> = Event extends OrchestrationV2DomainEvent
560 ? Omit<Event, "id" | "occurredAt" | "threadId">
561 : never;
562 let sequence = 0;
563 const apply = (event: EventInput) =>
564 store.apply({
565 ...event,
566 id: EventId.make(`rollback-history-event-${sequence++}`),
567 threadId,
568 occurredAt: now,
569 } as OrchestrationV2DomainEvent);
570 yield* apply({
571 type: "thread.created",
572 payload: {
573 id: threadId,
574 createdBy: "user",
575 creationSource: "web",
576 projectId: ProjectId.make("rollback-history-project"),
577 title: "Rollback history",
578 providerInstanceId,
579 modelSelection,
580 runtimeMode: "full-access",
581 interactionMode: "default",
582 branch: null,
583 worktreePath: process.cwd(),
584 activeProviderThreadId: providerThreadId,
585 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
586 forkedFrom: null,
587 createdAt: now,
588 updatedAt: now,
589 archivedAt: null,
590 settledOverride: null,
591 settledAt: null,
592 lastVisitedAt: null,
593 deletedAt: null,
594 },
595 });
596 const providerThread = {
597 id: providerThreadId,
598 driver,
599 providerInstanceId,
600 providerSessionId,
601 appThreadId: threadId,
602 ownerNodeId: null,
603 nativeThreadRef: null,
604 nativeConversationHeadRef: null,
605 status: "idle" as const,
606 firstRunOrdinal: 1,
607 lastRunOrdinal: 6,
608 handoffIds: [],
609 forkedFrom: null,
610 createdAt: now,
611 updatedAt: now,
612 };
613 yield* apply({ type: "provider-thread.updated", payload: providerThread });
614 for (const id of [scopeId, otherScopeId]) {
615 yield* apply({
616 type: "checkpoint-scope.created",
617 payload: {
618 id,
619 threadId,
620 runId: runId(1),
621 nodeId: nodeId(1),
622 parentScopeId: id === scopeId ? null : scopeId,
623 providerThreadId,
624 kind: id === scopeId ? "root_run" : "subagent",
625 ordinalWithinParent: 0,
626 advancesAppRunCount: id === scopeId,
627 cwd: process.cwd(),
628 createdAt: now,
629 },
630 });
631 }
632 const statuses = [
633 "completed",
634 "completed",
635 "completed",
636 "interrupted",
637 "failed",
638 "cancelled",
639 "rolled_back",
640 ] as const;
641 for (const [index, status] of statuses.entries()) {
642 const ordinal = index + 1;
643 yield* apply({
644 type: "run.created",
645 payload: {
646 id: runId(ordinal),
647 threadId,
648 ordinal,
649 providerInstanceId,
650 modelSelection,
651 providerThreadId,
652 userMessageId: MessageId.make(`rollback-history-message-${ordinal}`),
653 rootNodeId: nodeId(ordinal),
654 activeAttemptId: attemptId(ordinal),
655 status,
656 requestedAt: now,
657 startedAt: now,
658 completedAt: now,
659 checkpointId: checkpointId(ordinal),
660 contextHandoffId: null,
661 },
662 });
663 yield* apply({
664 type: "node.updated",
665 payload: {
666 id: nodeId(ordinal),
667 threadId,
668 runId: runId(ordinal),
669 parentNodeId: null,
670 rootNodeId: nodeId(ordinal),
671 kind: "root_turn",
672 status,
673 countsForRun: true,
674 providerThreadId,
675 providerTurnId: turnId(ordinal),
676 nativeItemRef: null,
677 runtimeRequestId: null,
678 checkpointScopeId: scopeId,
679 startedAt: now,
680 completedAt: now,
681 },
682 });
683 // Rollback must exclude every attempt of discarded runs, including an inactive retry.
684 for (const attemptOrdinal of ordinal === 7 ? [6.5, 7] : [ordinal]) {
685 yield* apply({
686 type: "run-attempt.created",
687 runId: runId(ordinal),
688 payload: {
689 id: attemptId(attemptOrdinal),
690 runId: runId(ordinal),
691 attemptOrdinal: attemptOrdinal === ordinal ? 2 : 1,
692 rootNodeId: nodeId(ordinal),
693 providerInstanceId,
694 providerThreadId,
695 providerTurnId: turnId(attemptOrdinal),
696 reason: "initial",
697 status: "completed",
698 startedAt: now,
699 completedAt: now,
700 },
701 });
702 yield* apply({
703 type: "provider-turn.updated",
704 payload: {
705 id: turnId(attemptOrdinal),
706 providerThreadId,
707 nodeId: nodeId(ordinal),
708 runAttemptId: attemptId(attemptOrdinal),
709 nativeTurnRef: { driver, nativeId: `native-turn-${attemptOrdinal}`, strength: "strong" },
710 ordinal: attemptOrdinal * 2,
711 status: status === "rolled_back" ? "completed" : status,
712 startedAt: now,
713 completedAt: now,
714 },
715 });
716 }
717 }
718 // A continuation shares the target attempt; its first provider turn is no longer the boundary.
719 yield* apply({
720 type: "provider-turn.updated",
721 payload: {
722 id: turnId(2.5),
723 providerThreadId,
724 nodeId: nodeId(2),
725 runAttemptId: attemptId(2),
726 nativeTurnRef: { driver, nativeId: "native-turn-2-continuation", strength: "strong" },
727 ordinal: 5,
728 status: "completed",
729 startedAt: now,
730 completedAt: now,
731 },
732 });
733 for (let ordinal = 0; ordinal <= 8; ordinal++) {
734 yield* apply({
735 type: "checkpoint.captured",
736 payload: {
737 id: checkpointId(ordinal),
738 threadId,
739 scopeId: ordinal === 8 ? otherScopeId : scopeId,
740 runId: ordinal === 0 ? null : runId(Math.min(ordinal, 7)),
741 nodeId: nodeId(Math.max(1, Math.min(ordinal, 7))),
742 parentCheckpointId: null,
743 ordinalWithinScope: ordinal,
744 appRunOrdinal: ordinal === 0 ? null : ordinal,
745 ref: CheckpointRef.make(`refs/t3/rollback-history/${ordinal}`),
746 status: ordinal === 7 ? "stale" : "ready",
747 files: [],
748 capturedAt: now,
749 },
750 });
751 }
752​
753 // A tracked repository records only the turns that changed it: runs 2 and 4 here.
754 yield* apply({
755 type: "checkpoint-scope.created",
756 payload: {
757 id: repositoryScopeId,
758 threadId,
759 runId: runId(2),
760 nodeId: nodeId(2),
761 parentScopeId: scopeId,
762 providerThreadId,
763 kind: "manual",
764 ordinalWithinParent: 1,
765 advancesAppRunCount: false,
766 cwd: process.cwd(),
767 label: "api",
768 repositoryPath: process.cwd(),
769 createdAt: now,
770 },
771 });
772 for (const ordinal of [2, 4]) {
773 yield* apply({
774 type: "checkpoint.captured",
775 payload: {
776 id: CheckpointId.make(`rollback-history-repository-checkpoint-${ordinal}`),
777 threadId,
778 scopeId: repositoryScopeId,
779 runId: runId(ordinal),
780 nodeId: nodeId(ordinal),
781 parentCheckpointId: null,
782 ordinalWithinScope: ordinal,
783 appRunOrdinal: null,
784 ref: CheckpointRef.make(`refs/t3/rollback-history/repository/${ordinal}`),
785 status: "ready",
786 files: [],
787 capturedAt: now,
788 },
789 });
790 }
791​
792 const rollbackCounts: number[] = [];
793 const restored: CheckpointId[] = [];
794 const deletedRefs: CheckpointId[] = [];
795 const discardedRepositoryOrdinals: number[] = [];
796 const committed: OrchestrationV2DomainEvent[] = [];
797 const serviceLayer = layerCheckpointRollbackService.pipe(
798 Layer.provide(
799 Layer.mergeAll(
800 ThreadCommandExecutor.layer,
801 IdAllocator.layer,
802 Layer.mock(CheckpointService.CheckpointServiceV2)({
803 restore: ({ targets }) =>
804 Effect.sync(() => {
805 restored.push(
806 ...targets.map((target) => checkpointId(target.checkpoint.ordinalWithinScope)),
807 );
808 }),
809 deleteStaleRefs: ({ checkpoints }) =>
810 Effect.sync(() => {
811 deletedRefs.push(...checkpoints.map((checkpoint) => checkpoint.id));
812 }),
813 discardRepositorySnapshots: ({ ordinals }) =>
814 Effect.sync(() => {
815 discardedRepositoryOrdinals.push(...ordinals);
816 }),
817 }),
818 Layer.mock(EventSink.EventSinkV2)({
819 write: ({ events }) =>
820 Effect.gen(function* () {
821 for (const event of events) yield* store.apply(event);
822 committed.push(...events);
823 return [];
824 }).pipe(
825 Effect.mapError(
826 (cause) =>
827 new EventSink.EventSinkWriteError({
828 eventCount: events.length,
829 cause,
830 }),
831 ),
832 ),
833 }),
834 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
835 open: () =>
836 Effect.succeed({
837 rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) =>
838 Effect.gen(function* () {
839 rollbackCounts.push(yield* resolveCodexRollbackTurnCount(input));
840 return { providerThread: input.providerThread };
841 }),
842 } as never),
843 }),
844 Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
845 ),
846 ),
847 );
848 const rollback = (ordinal: number, restoreFiles?: boolean) =>
849 Effect.gen(function* () {
850 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
851 yield* service.execute({
852 threadId,
853 providerThreadId,
854 scopeId,
855 checkpointId: checkpointId(ordinal),
856 ...(restoreFiles === undefined ? {} : { restoreFiles }),
857 });
858 }).pipe(Effect.provide(serviceLayer));
859​
860 return {
861 store,
862 now,
863 threadId,
864 runId,
865 nodeId,
866 checkpointId,
867 rollback,
868 rollbackCounts,
869 restored,
870 deletedRefs,
871 discardedRepositoryOrdinals,
872 repositoryScopeId,
873 committed,
874 };
875});
876​
877it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)))(
878 "rollback history reads",
879 (it) => {
880 it.effect("rolls back later terminal runs despite obsolete unrelated SQLite payloads", () =>
881 Effect.gen(function* () {
882 const history = yield* seedRollbackHistory;
883 const sql = yield* SqlClient.SqlClient;
884 const { threadId, runId, nodeId, checkpointId } = history;
885 yield* sql`
886 INSERT INTO orchestration_v2_projection_turn_items (
887 turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
888 parent_item_id, ordinal, type, status, updated_at, payload_json
889 ) VALUES ('rollback-obsolete-transcript', ${threadId}, ${runId(1)}, ${nodeId(1)},
890 NULL, NULL, NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(history.now)},
891 '{"obsolete":"transcript"}')`;
892 yield* sql`UPDATE orchestration_v2_projection_runs
893 SET payload_json = '{"obsolete":"run"}' WHERE run_id = ${runId(1)}`;
894 yield* sql`UPDATE orchestration_v2_projection_nodes
895 SET payload_json = '{"obsolete":"node"}' WHERE node_id = ${nodeId(1)}`;
896 yield* sql`UPDATE orchestration_v2_projection_checkpoints
897 SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
898 WHERE checkpoint_id IN (${checkpointId(0)}, ${checkpointId(1)}, ${checkpointId(7)}, ${checkpointId(8)})`;
899 assert.equal(
900 (yield* Effect.exit(history.store.getThreadProjection(threadId)))._tag,
901 "Failure",
902 );
903​
904 yield* history.rollback(2);
905​
906 assert.deepEqual(history.rollbackCounts, [4]);
907 assert.deepEqual(history.restored, [checkpointId(2)]);
908 assert.sameMembers(history.deletedRefs, [3, 4, 5, 6].map(checkpointId));
909 const runs = yield* sql<{ ordinal: number; status: string }>`
910 SELECT ordinal, status FROM orchestration_v2_projection_runs
911 WHERE thread_id = ${threadId} ORDER BY ordinal`;
912 assert.deepEqual(
913 runs.map((run) => run.status),
914 [
915 "completed",
916 "completed",
917 "rolled_back",
918 "rolled_back",
919 "rolled_back",
920 "rolled_back",
921 "rolled_back",
922 ],
923 );
924 const nodes = yield* sql<{ status: string }>`
925 SELECT status FROM orchestration_v2_projection_nodes
926 WHERE thread_id = ${threadId} ORDER BY node_id`;
927 assert.deepEqual(
928 nodes.map((node) => node.status),
929 runs.map((run) => run.status),
930 );
931 const checkpoints = yield* sql<{ status: string }>`
932 SELECT status FROM orchestration_v2_projection_checkpoints
933 WHERE thread_id = ${threadId} AND scope_id != ${history.repositoryScopeId}
934 ORDER BY ordinal_within_scope`;
935 assert.deepEqual(
936 checkpoints.map((checkpoint) => checkpoint.status),
937 ["ready", "ready", "ready", "stale", "stale", "stale", "stale", "stale", "ready"],
938 );
939 // The repository keeps its state at the target and loses what the discarded runs recorded,
940 // including the snapshots that have no record.
941 const repositoryCheckpoints = yield* sql<{ status: string }>`
942 SELECT status FROM orchestration_v2_projection_checkpoints
943 WHERE scope_id = ${history.repositoryScopeId} ORDER BY ordinal_within_scope`;
944 assert.deepEqual(
945 repositoryCheckpoints.map((checkpoint) => checkpoint.status),
946 ["ready", "stale"],
947 );
948 assert.deepEqual(history.discardedRepositoryOrdinals, [3, 4, 5, 6]);
949 }),
950 );
951​
952 it.effect("rewinds the conversation to a run whose snapshot capture failed", () =>
953 Effect.gen(function* () {
954 const history = yield* seedRollbackHistory;
955 const sql = yield* SqlClient.SqlClient;
956 yield* sql`UPDATE orchestration_v2_projection_checkpoints
957 SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error')
958 WHERE checkpoint_id = ${history.checkpointId(2)}`;
959​
960 yield* history.rollback(2, false);
961​
962 assert.deepEqual(history.rollbackCounts, [4]);
963 assert.deepEqual(history.restored, []);
964 }),
965 );
966​
967 it.effect(
968 "rewinds stopped runs repeatedly without counting discarded provider turns again",
969 () =>
970 Effect.gen(function* () {
971 const history = yield* seedRollbackHistory;
972 yield* history.rollback(5);
973 yield* history.rollback(2);
974 yield* history.rollback(0);
975 yield* history.rollback(0);
976​
977 assert.deepEqual(history.rollbackCounts, [1, 3, 3]);
978 assert.sameMembers(history.deletedRefs, [1, 2, 3, 4, 5, 6].map(history.checkpointId));
979 assert.sameMembers(
980 history.committed
981 .filter((event) => event.type === "run.updated")
982 .map((event) => event.payload.id),
983 [1, 2, 3, 4, 5, 6].map(history.runId),
984 );
985 const records = yield* history.store.getThreadRecords(history.threadId, [
986 "runs",
987 "nodes",
988 "checkpoints",
989 ]);
990 assert.isTrue(records.runs.every((run) => run.status === "rolled_back"));
991 assert.isTrue(records.nodes.every((node) => node.status === "rolled_back"));
992 assert.sameMembers(
993 records.checkpoints
994 .filter((checkpoint) => checkpoint.status === "ready")
995 .map((checkpoint) => checkpoint.id),
996 [history.checkpointId(0), history.checkpointId(8)],
997 );
998 }),
999 );
1000 },