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