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