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

CheckpointRollbackService.test.ts

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