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 { 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";
48
49const unrelatedProject = Option.some({
50 workspaceRoot: "/nonexistent/t3-rollback-project",
51} as never);
52const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
53 Layer.provide(
54 Layer.mergeAll(
55 NodeServices.layer,
56 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
57 ServerSettings.layerTest(),
58 Layer.mock(GitWorkflow.GitWorkflowService)({}),
59 Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
60 ),
61 ),
62);
63
64it.effect.each(["initial", "waiting"])(
65 "rejects a non-ready checkpoint from %s before opening a session or restoring files",
66 (state) => {
67 const threadId = ThreadId.make("thread:rollback-non-ready");
68 const providerThreadId = ProviderThreadId.make("provider-thread:rollback-non-ready");
69 const providerSessionId = ProviderSessionId.make("provider-session:rollback-non-ready");
70 const checkpointId = CheckpointId.make("checkpoint:rollback-non-ready");
71 const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-non-ready");
72 const providerInstanceId = ProviderInstanceId.make("provider_rollback_non_ready");
73 const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
74 const open = vi.fn(() => Effect.die("provider session open must not run"));
75 const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
76 const readEntered = Deferred.makeUnsafe<void>();
77 const release = Deferred.makeUnsafe<void>();
78 let projection = {
79 thread: {
80 worktreePath: process.cwd(),
81 activeProviderThreadId: providerThreadId,
82 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
83 },
84 providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
85 checkpoint: {
86 id: checkpointId,
87 scopeId,
88 status: state === "waiting" ? "ready" : "stale",
89 appRunOrdinal: 0,
90 },
91 scope: { id: scopeId, cwd: process.cwd() },
92 } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
93 const getThread = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThread"]>(() =>
94 Deferred.succeed(readEntered, undefined).pipe(Effect.as(projection.thread)),
95 );
96 const getCheckpointRollbackContext = vi.fn(() => Effect.succeed(projection));
97 const testLayer = layerCheckpointRollbackService.pipe(
98 Layer.provide(
99 Layer.mergeAll(
100 ThreadCommandExecutor.layer,
101 Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }),
102 Layer.mock(EventSink.EventSinkV2)({}),
103 IdAllocator.layer,
104 Layer.mock(ProjectionStore.ProjectionStoreV2)({
105 getThread,
106 getCheckpointRollbackContext,
107 getShellSnapshot: () =>
108 Effect.succeed({
109 schemaVersion: 1,
110 snapshotSequence: 0,
111 threads: [],
112 archivedThreads: [],
113 }),
114 }),
115 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
116 Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
117 ),
118 ),
119 );
120
121 return Effect.gen(function* () {
122 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
123 const holder =
124 state === "waiting"
125 ? yield* withWorkspaceLease(process.cwd(), Deferred.await(release)).pipe(
126 Effect.forkChild({ startImmediately: true }),
127 )
128 : undefined;
129 const rollback = yield* service
130 .execute({
131 threadId,
132 providerThreadId,
133 checkpointId,
134 scopeId,
135 })
136 .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
137 if (state === "waiting") {
138 yield* Deferred.await(readEntered);
139 projection = {
140 ...projection,
141 checkpoint: { ...projection.checkpoint!, status: "stale" },
142 };
143 yield* Deferred.succeed(release, undefined);
144 if (holder !== undefined) yield* Fiber.join(holder);
145 }
146 const error = yield* Fiber.join(rollback);
147
148 assert.deepEqual(getThread.mock.calls, [[threadId]]);
149 assert.deepEqual(getCheckpointRollbackContext.mock.calls, [
150 [
151 threadId,
152 {
153 threadId,
154 providerThreadId,
155 checkpointId,
156 scopeId,
157 },
158 ],
159 ]);
160 assert.equal(error.reason, "rollback-target-invalid");
161 assert.equal(
162 error.message,
163 `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`,
164 );
165 assert.equal(error.cause, undefined);
166 assert.equal(resolveRuntimePolicy.mock.calls.length, 0);
167 assert.equal(open.mock.calls.length, 0);
168 assert.equal(restore.mock.calls.length, 0);
169 }).pipe(Effect.provide(testLayer));
170 },
171);
172
173it.effect.each([
174 { order: "cleanup-first", restoreFiles: true },
175 { order: "rollback-first", restoreFiles: true },
176 { order: "cleanup-first", restoreFiles: false, unmanaged: true },
177])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false }) =>
178 Effect.gen(function* () {
179 const fileSystem = yield* FileSystem.FileSystem;
180 const path = yield* Path.Path;
181 const workspaceRoot = yield* fileSystem.realPath(
182 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" }),
183 );
184 const worktreesDir = path.join(workspaceRoot, "worktrees");
185 const worktreePath = unmanaged
186 ? path.join(workspaceRoot, "elsewhere", "feature")
187 : path.join(worktreesDir, "repo", "feature");
188 yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
189 const threadId = ThreadId.make("rollback-worktree");
190 const projectId = ProjectId.make("rollback-worktree-project");
191 const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread");
192 const providerSessionId = ProviderSessionId.make("rollback-worktree-provider-session");
193 const providerInstanceId = ProviderInstanceId.make("rollback-worktree-provider-instance");
194 const checkpointId = CheckpointId.make("rollback-worktree-checkpoint");
195 const scopeId = CheckpointScopeId.make("rollback-worktree-scope");
196 const branch = "feature/rollback";
197 const release = Deferred.makeUnsafe<void>();
198 const openEntered = Deferred.makeUnsafe<void>();
199 const calls: string[] = [];
200 let cleanupEntered = false;
201 const providerThread = { id: providerThreadId, providerSessionId, providerInstanceId };
202 const projection = {
203 thread: {
204 id: threadId,
205 projectId,
206 worktreePath,
207 branch,
208 activeProviderThreadId: providerThreadId,
209 modelSelection: { instanceId: providerInstanceId, model: "test-model" },
210 },
211 providerThread,
212 providerSession: undefined,
213 checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 },
214 scope: { id: scopeId, cwd: worktreePath },
215 runsToRollback: [],
216 targetAttempt: undefined,
217 rolledBackAttemptIds: [],
218 staleCheckpoints: [],
219 rootNodes: [],
220 providerTurns: [],
221 } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
222 const testLayer = CheckpointRollbackService.layer.pipe(
223 Layer.provide(
224 Layer.mergeAll(
225 ThreadCommandExecutor.layer,
226 NodeServices.layer,
227 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
228 ServerSettings.layerTest(),
229 Layer.mock(ProjectStore.ProjectStoreV2)({
230 get: (id) => {
231 assert.equal(id, projectId);
232 return Effect.succeedSome({ workspaceRoot } as never);
233 },
234 }),
235 Layer.mock(GitWorkflow.GitWorkflowService)({
236 pruneWorktrees: (input) =>
237 Effect.sync(() => {
238 assert.deepEqual(input, { cwd: workspaceRoot });
239 calls.push("prune");
240 }),
241 createWorktree: (input) =>
242 Effect.gen(function* () {
243 assert.deepEqual(input, {
244 cwd: workspaceRoot,
245 refName: branch,
246 path: worktreePath,
247 });
248 calls.push("create");
249 yield* fileSystem.makeDirectory(worktreePath).pipe(Effect.orDie);
250 return {} as never;
251 }),
252 }),
253 Layer.mock(CheckpointService.CheckpointServiceV2)({
254 restore: () =>
255 Effect.gen(function* () {
256 assert.isTrue(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie));
257 calls.push("files");
258 }),
259 }),
260 Layer.mock(EventSink.EventSinkV2)({
261 write: () =>
262 Effect.sync(() => {
263 calls.push("projection");
264 return [];
265 }),
266 }),
267 IdAllocator.layer,
268 Layer.mock(ProjectionStore.ProjectionStoreV2)({
269 getThread: () => Effect.succeed(projection.thread),
270 getCheckpointRollbackContext: () => Effect.succeed(projection),
271 getShellSnapshot: () =>
272 Effect.succeed({
273 schemaVersion: 1,
274 snapshotSequence: 0,
275 threads: [],
276 archivedThreads: [],
277 }),
278 }),
279 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
280 open: (input) =>
281 Effect.gen(function* () {
282 assert.equal(input.runtimePolicy.cwd, worktreePath);
283 if (!(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie))) {
284 return yield* new ProviderWorkspaceMissingError({ threadId, cwd: worktreePath });
285 }
286 calls.push("session");
287 yield* Deferred.succeed(openEntered, undefined);
288 if (order === "rollback-first") yield* Deferred.await(release);
289 return {} as never;
290 }),
291 }),
292 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
293 resolve: ({ thread }) => {
294 assert.equal(thread.worktreePath, worktreePath);
295 return Effect.succeed({ cwd: thread.worktreePath } as never);
296 },
297 }),
298 ),
299 ),
300 );
301 yield* Effect.gen(function* () {
302 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
303 const cleanupEffect = withWorkspaceLease(
304 worktreePath,
305 Effect.gen(function* () {
306 cleanupEntered = true;
307 if (order === "cleanup-first") yield* Deferred.await(release);
308 yield* fileSystem.remove(worktreePath, { recursive: true, force: true });
309 calls.push("cleanup");
310 }),
311 );
312 const cleanup =
313 order === "cleanup-first"
314 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
315 : undefined;
316 const rollback = yield* service
317 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
318 .pipe(Effect.forkChild({ startImmediately: true }));
319 if (order === "cleanup-first") assert.deepEqual(calls, []);
320 if (order === "rollback-first") yield* Deferred.await(openEntered);
321 const laterCleanup =
322 order === "rollback-first"
323 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
324 : undefined;
325 if (order === "rollback-first") assert.isFalse(cleanupEntered);
326 yield* Deferred.succeed(release, undefined);
327 if (cleanup !== undefined) yield* Fiber.join(cleanup);
328 if (unmanaged) {
329 const error = yield* Fiber.join(rollback).pipe(Effect.flip);
330 assert.equal(error._tag, "CheckpointRollbackExecutionError");
331 assert.deepEqual(calls, ["cleanup"]);
332 return;
333 }
334 yield* Fiber.join(rollback);
335 if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
336 const rollbackCalls = restoreFiles
337 ? ["session", "files", "projection"]
338 : ["session", "projection"];
339 assert.deepEqual(
340 calls,
341 order === "cleanup-first"
342 ? ["cleanup", "prune", "create", ...rollbackCalls]
343 : [...rollbackCalls, "cleanup"],
344 );
345 }).pipe(Effect.provide(testLayer));
346 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
347);
348
349const seedRollbackHistory = Effect.gen(function* () {
350 const store = yield* ProjectionStore.ProjectionStoreV2;
351 const now = yield* DateTime.now;
352 const threadId = ThreadId.make("rollback-history");
353 const providerThreadId = ProviderThreadId.make("rollback-history-provider");
354 const providerSessionId = ProviderSessionId.make("rollback-history-session");
355 const providerInstanceId = ProviderInstanceId.make("codex");
356 const driver = ProviderDriverKind.make("codex");
357 const modelSelection = { instanceId: providerInstanceId, model: "test" };
358 const scopeId = CheckpointScopeId.make("rollback-history-root");
359 const otherScopeId = CheckpointScopeId.make("rollback-history-child");
360 const runId = (ordinal: number) => RunId.make(`rollback-history-run-${ordinal}`);
361 const nodeId = (ordinal: number) => NodeId.make(`rollback-history-node-${ordinal}`);
362 const attemptId = (ordinal: number) => RunAttemptId.make(`rollback-history-attempt-${ordinal}`);
363 const turnId = (ordinal: number) => ProviderTurnId.make(`rollback-history-turn-${ordinal}`);
364 const checkpointId = (ordinal: number) =>
365 CheckpointId.make(`rollback-history-checkpoint-${ordinal}`);
366 type EventInput<Event = OrchestrationV2DomainEvent> = Event extends OrchestrationV2DomainEvent
367 ? Omit<Event, "id" | "occurredAt" | "threadId">
368 : never;
369 let sequence = 0;
370 const apply = (event: EventInput) =>
371 store.apply({
372 ...event,
373 id: EventId.make(`rollback-history-event-${sequence++}`),
374 threadId,
375 occurredAt: now,
376 } as OrchestrationV2DomainEvent);
377 yield* apply({
378 type: "thread.created",
379 payload: {
380 id: threadId,
381 createdBy: "user",
382 creationSource: "web",
383 projectId: ProjectId.make("rollback-history-project"),
384 title: "Rollback history",
385 providerInstanceId,
386 modelSelection,
387 runtimeMode: "full-access",
388 interactionMode: "default",
389 branch: null,
390 worktreePath: process.cwd(),
391 activeProviderThreadId: providerThreadId,
392 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
393 forkedFrom: null,
394 createdAt: now,
395 updatedAt: now,
396 archivedAt: null,
397 settledOverride: null,
398 settledAt: null,
399 lastVisitedAt: null,
400 deletedAt: null,
401 },
402 });
403 const providerThread = {
404 id: providerThreadId,
405 driver,
406 providerInstanceId,
407 providerSessionId,
408 appThreadId: threadId,
409 ownerNodeId: null,
410 nativeThreadRef: null,
411 nativeConversationHeadRef: null,
412 status: "idle" as const,
413 firstRunOrdinal: 1,
414 lastRunOrdinal: 6,
415 handoffIds: [],
416 forkedFrom: null,
417 createdAt: now,
418 updatedAt: now,
419 };
420 yield* apply({ type: "provider-thread.updated", payload: providerThread });
421 for (const id of [scopeId, otherScopeId]) {
422 yield* apply({
423 type: "checkpoint-scope.created",
424 payload: {
425 id,
426 threadId,
427 runId: runId(1),
428 nodeId: nodeId(1),
429 parentScopeId: id === scopeId ? null : scopeId,
430 providerThreadId,
431 kind: id === scopeId ? "root_run" : "subagent",
432 ordinalWithinParent: 0,
433 advancesAppRunCount: id === scopeId,
434 cwd: process.cwd(),
435 createdAt: now,
436 },
437 });
438 }
439 const statuses = [
440 "completed",
441 "completed",
442 "completed",
443 "interrupted",
444 "failed",
445 "cancelled",
446 "rolled_back",
447 ] as const;
448 for (const [index, status] of statuses.entries()) {
449 const ordinal = index + 1;
450 yield* apply({
451 type: "run.created",
452 payload: {
453 id: runId(ordinal),
454 threadId,
455 ordinal,
456 providerInstanceId,
457 modelSelection,
458 providerThreadId,
459 userMessageId: MessageId.make(`rollback-history-message-${ordinal}`),
460 rootNodeId: nodeId(ordinal),
461 activeAttemptId: attemptId(ordinal),
462 status,
463 requestedAt: now,
464 startedAt: now,
465 completedAt: now,
466 checkpointId: checkpointId(ordinal),
467 contextHandoffId: null,
468 },
469 });
470 yield* apply({
471 type: "node.updated",
472 payload: {
473 id: nodeId(ordinal),
474 threadId,
475 runId: runId(ordinal),
476 parentNodeId: null,
477 rootNodeId: nodeId(ordinal),
478 kind: "root_turn",
479 status,
480 countsForRun: true,
481 providerThreadId,
482 providerTurnId: turnId(ordinal),
483 nativeItemRef: null,
484 runtimeRequestId: null,
485 checkpointScopeId: scopeId,
486 startedAt: now,
487 completedAt: now,
488 },
489 });
490 // Rollback must exclude every attempt of discarded runs, including an inactive retry.
491 for (const attemptOrdinal of ordinal === 7 ? [6.5, 7] : [ordinal]) {
492 yield* apply({
493 type: "run-attempt.created",
494 runId: runId(ordinal),
495 payload: {
496 id: attemptId(attemptOrdinal),
497 runId: runId(ordinal),
498 attemptOrdinal: attemptOrdinal === ordinal ? 2 : 1,
499 rootNodeId: nodeId(ordinal),
500 providerInstanceId,
501 providerThreadId,
502 providerTurnId: turnId(attemptOrdinal),
503 reason: "initial",
504 status: "completed",
505 startedAt: now,
506 completedAt: now,
507 },
508 });
509 yield* apply({
510 type: "provider-turn.updated",
511 payload: {
512 id: turnId(attemptOrdinal),
513 providerThreadId,
514 nodeId: nodeId(ordinal),
515 runAttemptId: attemptId(attemptOrdinal),
516 nativeTurnRef: { driver, nativeId: `native-turn-${attemptOrdinal}`, strength: "strong" },
517 ordinal: attemptOrdinal * 2,
518 status: status === "rolled_back" ? "completed" : status,
519 startedAt: now,
520 completedAt: now,
521 },
522 });
523 }
524 }
525 // A continuation shares the target attempt; its first provider turn is no longer the boundary.
526 yield* apply({
527 type: "provider-turn.updated",
528 payload: {
529 id: turnId(2.5),
530 providerThreadId,
531 nodeId: nodeId(2),
532 runAttemptId: attemptId(2),
533 nativeTurnRef: { driver, nativeId: "native-turn-2-continuation", strength: "strong" },
534 ordinal: 5,
535 status: "completed",
536 startedAt: now,
537 completedAt: now,
538 },
539 });
540 for (let ordinal = 0; ordinal <= 8; ordinal++) {
541 yield* apply({
542 type: "checkpoint.captured",
543 payload: {
544 id: checkpointId(ordinal),
545 threadId,
546 scopeId: ordinal === 8 ? otherScopeId : scopeId,
547 runId: ordinal === 0 ? null : runId(Math.min(ordinal, 7)),
548 nodeId: nodeId(Math.max(1, Math.min(ordinal, 7))),
549 parentCheckpointId: null,
550 ordinalWithinScope: ordinal,
551 appRunOrdinal: ordinal === 0 ? null : ordinal,
552 ref: CheckpointRef.make(`refs/t3/rollback-history/${ordinal}`),
553 status: ordinal === 7 ? "stale" : "ready",
554 files: [],
555 capturedAt: now,
556 },
557 });
558 }
559
560 const rollbackCounts: number[] = [];
561 const restored: CheckpointId[] = [];
562 const deletedRefs: CheckpointId[] = [];
563 const committed: OrchestrationV2DomainEvent[] = [];
564 const serviceLayer = layerCheckpointRollbackService.pipe(
565 Layer.provide(
566 Layer.mergeAll(
567 ThreadCommandExecutor.layer,
568 IdAllocator.layer,
569 Layer.mock(CheckpointService.CheckpointServiceV2)({
570 restore: ({ checkpoint }) =>
571 Effect.sync(() => {
572 restored.push(checkpoint.id);
573 }),
574 deleteStaleRefs: ({ checkpoints }) =>
575 Effect.sync(() => {
576 deletedRefs.push(...checkpoints.map((checkpoint) => checkpoint.id));
577 }),
578 }),
579 Layer.mock(EventSink.EventSinkV2)({
580 write: ({ events }) =>
581 Effect.gen(function* () {
582 for (const event of events) yield* store.apply(event);
583 committed.push(...events);
584 return [];
585 }).pipe(
586 Effect.mapError(
587 (cause) =>
588 new EventSink.EventSinkWriteError({
589 eventCount: events.length,
590 cause,
591 }),
592 ),
593 ),
594 }),
595 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
596 open: () =>
597 Effect.succeed({
598 rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) =>
599 Effect.gen(function* () {
600 rollbackCounts.push(yield* resolveCodexRollbackTurnCount(input));
601 return { providerThread: input.providerThread };
602 }),
603 } as never),
604 }),
605 Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
606 ),
607 ),
608 );
609 const rollback = (ordinal: number) =>
610 Effect.gen(function* () {
611 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
612 yield* service.execute({
613 threadId,
614 providerThreadId,
615 scopeId,
616 checkpointId: checkpointId(ordinal),
617 });
618 }).pipe(Effect.provide(serviceLayer));
619
620 return {
621 store,
622 now,
623 threadId,
624 runId,
625 nodeId,
626 checkpointId,
627 rollback,
628 rollbackCounts,
629 restored,
630 deletedRefs,
631 committed,
632 };
633});
634
635it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)))(
636 "rollback history reads",
637 (it) => {
638 it.effect("rolls back later terminal runs despite obsolete unrelated SQLite payloads", () =>
639 Effect.gen(function* () {
640 const history = yield* seedRollbackHistory;
641 const sql = yield* SqlClient.SqlClient;
642 const { threadId, runId, nodeId, checkpointId } = history;
643 yield* sql`
644 INSERT INTO orchestration_v2_projection_turn_items (
645 turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
646 parent_item_id, ordinal, type, status, updated_at, payload_json
647 ) VALUES ('rollback-obsolete-transcript', ${threadId}, ${runId(1)}, ${nodeId(1)},
648 NULL, NULL, NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(history.now)},
649 '{"obsolete":"transcript"}')`;
650 yield* sql`UPDATE orchestration_v2_projection_runs
651 SET payload_json = '{"obsolete":"run"}' WHERE run_id = ${runId(1)}`;
652 yield* sql`UPDATE orchestration_v2_projection_nodes
653 SET payload_json = '{"obsolete":"node"}' WHERE node_id = ${nodeId(1)}`;
654 yield* sql`UPDATE orchestration_v2_projection_checkpoints
655 SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
656 WHERE checkpoint_id IN (${checkpointId(0)}, ${checkpointId(1)}, ${checkpointId(7)}, ${checkpointId(8)})`;
657 assert.equal(
658 (yield* Effect.exit(history.store.getThreadProjection(threadId)))._tag,
659 "Failure",
660 );
661
662 yield* history.rollback(2);
663
664 assert.deepEqual(history.rollbackCounts, [4]);
665 assert.deepEqual(history.restored, [checkpointId(2)]);
666 assert.sameMembers(history.deletedRefs, [3, 4, 5, 6].map(checkpointId));
667 const runs = yield* sql<{ ordinal: number; status: string }>`
668 SELECT ordinal, status FROM orchestration_v2_projection_runs
669 WHERE thread_id = ${threadId} ORDER BY ordinal`;
670 assert.deepEqual(
671 runs.map((run) => run.status),
672 [
673 "completed",
674 "completed",
675 "rolled_back",
676 "rolled_back",
677 "rolled_back",
678 "rolled_back",
679 "rolled_back",
680 ],
681 );
682 const nodes = yield* sql<{ status: string }>`
683 SELECT status FROM orchestration_v2_projection_nodes
684 WHERE thread_id = ${threadId} ORDER BY node_id`;
685 assert.deepEqual(
686 nodes.map((node) => node.status),
687 runs.map((run) => run.status),
688 );
689 const checkpoints = yield* sql<{ status: string }>`
690 SELECT status FROM orchestration_v2_projection_checkpoints
691 WHERE thread_id = ${threadId} ORDER BY ordinal_within_scope`;
692 assert.deepEqual(
693 checkpoints.map((checkpoint) => checkpoint.status),
694 ["ready", "ready", "ready", "stale", "stale", "stale", "stale", "stale", "ready"],
695 );
696 }),
697 );
698
699 it.effect(
700 "rewinds stopped runs repeatedly without counting discarded provider turns again",
701 () =>
702 Effect.gen(function* () {
703 const history = yield* seedRollbackHistory;
704 yield* history.rollback(5);
705 yield* history.rollback(2);
706 yield* history.rollback(0);
707 yield* history.rollback(0);
708
709 assert.deepEqual(history.rollbackCounts, [1, 3, 3]);
710 assert.sameMembers(history.deletedRefs, [1, 2, 3, 4, 5, 6].map(history.checkpointId));
711 assert.sameMembers(
712 history.committed
713 .filter((event) => event.type === "run.updated")
714 .map((event) => event.payload.id),
715 [1, 2, 3, 4, 5, 6].map(history.runId),
716 );
717 const records = yield* history.store.getThreadRecords(history.threadId, [
718 "runs",
719 "nodes",
720 "checkpoints",
721 ]);
722 assert.isTrue(records.runs.every((run) => run.status === "rolled_back"));
723 assert.isTrue(records.nodes.every((node) => node.status === "rolled_back"));
724 assert.sameMembers(
725 records.checkpoints
726 .filter((checkpoint) => checkpoint.status === "ready")
727 .map((checkpoint) => checkpoint.id),
728 [history.checkpointId(0), history.checkpointId(8)],
729 );
730 }),
731 );
732 },
733);