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