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

CheckpointCaptureService.test.ts

739 lines26.9 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { assert, it } from "@effect/vitest";
3import {
4 CheckpointId,
5 CheckpointRef,
6 CheckpointScopeId,
7 EventId,
8 MessageId,
9 NodeId,
10 type OrchestrationV2DomainEvent,
11 type OrchestrationV2Run,
12 ProjectId,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 ProviderThreadId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Ref from "effect/Ref";
23import * as SqlClient from "effect/sql/SqlClient";
24​
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
27import { VcsProcessTimeoutError } from "@t3tools/contracts";
28import * as CheckpointService from "./CheckpointService.ts";
29import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
30import * as EventSink from "./EventSink.ts";
31import * as IdAllocator from "./IdAllocator.ts";
32import * as ProjectionStore from "./ProjectionStore.ts";
33​
34const layerProjectionStoreTest = Layer.mergeAll(
35 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
36 SqlitePersistence.layerMemory,
37);
38​
39const threadId = ThreadId.make("thread:checkpoint-capture-delegated");
40const projectId = ProjectId.make("project:checkpoint-capture-delegated");
41const runId = RunId.make("run:checkpoint-capture-delegated");
42const scopeId = CheckpointScopeId.make("scope:checkpoint-capture-delegated");
43const rootNodeId = NodeId.make("node:checkpoint-capture-delegated-root");
44const taskId = NodeId.make("node:checkpoint-capture-task");
45const deliveryMessageId = MessageId.make("message:checkpoint-capture-delivery");
46const providerThreadId = ProviderThreadId.make("provider-thread:checkpoint-capture-delegated");
47const providerInstanceId = ProviderInstanceId.make("codex");
48const driver = ProviderDriverKind.make("codex");
49const modelSelection = {
50 instanceId: providerInstanceId,
51 model: "gpt-5.4",
52} as const;
53​
54it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
55 it.effect.each([false, true])(
56 "captures without decoding history or losing newer delegated completion, ref lookup fails=%s",
57 (refLookupFails) =>
58 Effect.gen(function* () {
59 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
60 const now = yield* DateTime.now;
61 const later = DateTime.add(now, { seconds: 1 });
62​
63 const staleDelegatedCompletion = {
64 disposition: "open" as const,
65 nextGeneration: 1,
66 delivery: null,
67 };
68 const newerCohort = {
69 disposition: "open" as const,
70 nextGeneration: 2,
71 delivery: {
72 generation: 1,
73 messageId: deliveryMessageId,
74 taskIds: [taskId],
75 },
76 };
77 const staleRun: OrchestrationV2Run = {
78 id: runId,
79 threadId,
80 ordinal: 1,
81 providerInstanceId,
82 modelSelection,
83 providerThreadId,
84 userMessageId: MessageId.make("message:checkpoint-capture-user"),
85 rootNodeId,
86 activeAttemptId: null,
87 status: "waiting",
88 requestedAt: now,
89 startedAt: now,
90 completedAt: null,
91 checkpointId: null,
92 contextHandoffId: null,
93 // Snapshot taken before a concurrent cohort advanced during capture work.
94 delegatedCompletion: staleDelegatedCompletion,
95 };
96 const rootNode = {
97 id: rootNodeId,
98 threadId,
99 runId,
100 parentNodeId: null,
101 rootNodeId,
102 kind: "root_turn" as const,
103 status: "waiting" as const,
104 countsForRun: true,
105 providerThreadId,
106 providerTurnId: null,
107 nativeItemRef: null,
108 runtimeRequestId: null,
109 checkpointScopeId: scopeId,
110 startedAt: now,
111 completedAt: null,
112 };
113 const scope = {
114 id: scopeId,
115 threadId,
116 runId,
117 nodeId: rootNodeId,
118 parentScopeId: null,
119 providerThreadId,
120 kind: "root_run" as const,
121 ordinalWithinParent: 0,
122 advancesAppRunCount: true,
123 cwd: "/repo",
124 createdAt: now,
125 };
126 const providerThread = {
127 id: providerThreadId,
128 driver,
129 providerInstanceId,
130 providerSessionId: null,
131 appThreadId: threadId,
132 ownerNodeId: rootNodeId,
133 nativeThreadRef: null,
134 nativeConversationHeadRef: null,
135 status: "idle" as const,
136 firstRunOrdinal: 1,
137 lastRunOrdinal: 1,
138 handoffIds: [],
139 forkedFrom: null,
140 createdAt: now,
141 updatedAt: now,
142 };
143 const readyBaseline = {
144 id: CheckpointId.make("checkpoint:baseline-0"),
145 threadId,
146 scopeId,
147 runId: null,
148 nodeId: rootNodeId,
149 parentCheckpointId: null,
150 ordinalWithinScope: 0,
151 appRunOrdinal: null,
152 ref: CheckpointRef.make("checkpoint-ref:baseline-0"),
153 status: "ready" as const,
154 files: [],
155 capturedAt: now,
156 };
157 const captured = {
158 id: CheckpointId.make("checkpoint:captured-1"),
159 threadId,
160 scopeId,
161 runId,
162 nodeId: rootNodeId,
163 parentCheckpointId: readyBaseline.id,
164 ordinalWithinScope: 1,
165 appRunOrdinal: 1,
166 ref: CheckpointRef.make("checkpoint-ref:captured-1"),
167 status: "ready" as const,
168 files: [],
169 capturedAt: now,
170 };
171​
172 yield* projectionStore.apply({
173 id: EventId.make("event:checkpoint-capture:thread"),
174 type: "thread.created",
175 threadId,
176 occurredAt: now,
177 payload: {
178 createdBy: "user",
179 creationSource: "web",
180 id: threadId,
181 projectId,
182 title: "Checkpoint capture delegated completion",
183 providerInstanceId,
184 modelSelection,
185 runtimeMode: "full-access",
186 interactionMode: "default",
187 branch: null,
188 worktreePath: null,
189 activeProviderThreadId: null,
190 lineage: {
191 parentThreadId: null,
192 relationshipToParent: null,
193 rootThreadId: threadId,
194 },
195 forkedFrom: null,
196 createdAt: now,
197 updatedAt: now,
198 archivedAt: null,
199 settledOverride: null,
200 settledAt: null,
201 lastVisitedAt: null,
202 deletedAt: null,
203 },
204 });
205 yield* projectionStore.apply({
206 id: EventId.make("event:checkpoint-capture:run-stale"),
207 type: "run.updated",
208 threadId,
209 runId,
210 nodeId: rootNodeId,
211 providerInstanceId,
212 occurredAt: now,
213 payload: staleRun,
214 });
215 yield* projectionStore.apply({
216 id: EventId.make("event:checkpoint-capture:node"),
217 type: "node.updated",
218 threadId,
219 runId,
220 nodeId: rootNodeId,
221 providerInstanceId,
222 occurredAt: now,
223 payload: rootNode,
224 });
225 yield* projectionStore.apply({
226 id: EventId.make("event:checkpoint-capture:provider-thread"),
227 type: "provider-thread.updated",
228 threadId,
229 nodeId: rootNodeId,
230 driver,
231 providerInstanceId,
232 occurredAt: now,
233 payload: providerThread,
234 });
235 yield* projectionStore.apply({
236 id: EventId.make("event:checkpoint-capture:scope"),
237 type: "checkpoint-scope.created",
238 threadId,
239 runId,
240 nodeId: rootNodeId,
241 occurredAt: now,
242 payload: scope,
243 });
244 yield* projectionStore.apply({
245 id: EventId.make("event:checkpoint-capture:baseline"),
246 type: "checkpoint.captured",
247 threadId,
248 nodeId: rootNodeId,
249 driver,
250 providerInstanceId,
251 occurredAt: now,
252 payload: readyBaseline,
253 });
254 const sql = yield* SqlClient.SqlClient;
255 yield* sql`INSERT OR REPLACE INTO orchestration_v2_projection_turn_items
256 (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
257 parent_item_id, ordinal, type, status, updated_at, payload_json)
258 VALUES ('obsolete-history', ${threadId}, ${runId}, ${rootNodeId}, NULL, NULL,
259 NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(now)}, '{"obsolete":true}')`;
260 yield* sql`UPDATE orchestration_v2_projection_checkpoints
261 SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
262 WHERE checkpoint_id = ${readyBaseline.id}`;
263 assert.equal(
264 (yield* Effect.exit(projectionStore.getThreadProjection(threadId)))._tag,
265 "Failure",
266 );
267​
268 const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
269 const layerCapture = CheckpointCaptureService.layer.pipe(
270 Layer.provide(
271 Layer.mergeAll(
272 IdAllocator.layer,
273 refLookupFails
274 ? CheckpointService.layer.pipe(
275 Layer.provide(
276 Layer.mergeAll(
277 IdAllocator.layer,
278 NodeCrypto.layer,
279 Layer.mock(CheckpointStore.CheckpointStore)({
280 isGitRepository: () => Effect.succeed(true),
281 captureCheckpoint: () => Effect.void,
282 hasCheckpointRef: () =>
283 Effect.fail(
284 new VcsProcessTimeoutError({
285 operation: "test.hasCheckpointRef",
286 command: "git",
287 cwd: "/repo",
288 timeoutMs: 30000,
289 }),
290 ),
291 }),
292 ),
293 ),
294 )
295 : Layer.mock(CheckpointService.CheckpointServiceV2)({
296 materializeBaselineCheckpoint: () =>
297 Effect.die(
298 "baseline materialization must be skipped when ordinal 0 is ready",
299 ),
300 capture: () => Effect.succeed(captured),
301 }),
302 Layer.mock(EventSink.EventSinkV2)({
303 commitCommand: (input) =>
304 Ref.set(committed, input.events).pipe(
305 Effect.as({
306 commandId: input.commandId,
307 committed: true,
308 sequence: 1,
309 events: input.events,
310 effects: [],
311 } as never),
312 ),
313 }),
314 ),
315 ),
316 );
317​
318 yield* Effect.gen(function* () {
319 const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
320 const incomplete = yield* service
321 .execute({ threadId, runId, scopeId: CheckpointScopeId.make("missing-scope") })
322 .pipe(Effect.flip);
323 assert.instanceOf(incomplete, CheckpointCaptureService.CheckpointCaptureExecutionError);
324 // Capture reads the waiting run while the projection still holds the stale cohort.
325 yield* service.execute({ threadId, runId, scopeId });
326​
327 const events = yield* Ref.get(committed);
328 const runUpdated = events.find((event) => event.type === "run.updated");
329 assert.isDefined(runUpdated);
330 if (runUpdated?.type !== "run.updated") {
331 return;
332 }
333 assert.equal(runUpdated.payload.status, "completed");
334 const capturedEvent = events.find((event) => event.type === "checkpoint.captured");
335 assert.equal(
336 runUpdated.payload.checkpointId,
337 refLookupFails ? capturedEvent?.payload.id : captured.id,
338 );
339 if (refLookupFails && capturedEvent?.type === "checkpoint.captured") {
340 assert.equal(capturedEvent.payload.status, "ready");
341 assert.deepEqual(capturedEvent.payload.files, []);
342 }
343 assert.isUndefined(
344 runUpdated.payload.delegatedCompletion,
345 "checkpoint capture must omit delegatedCompletion so ProjectionStore can keep a newer cohort",
346 );
347​
348 // Race: a newer cohort lands on the projection after capture read the stale
349 // waiting run and before the capture command's run.updated is applied.
350 yield* projectionStore.apply({
351 id: EventId.make("event:checkpoint-capture:newer-cohort"),
352 type: "run.updated",
353 threadId,
354 runId,
355 nodeId: rootNodeId,
356 providerInstanceId,
357 occurredAt: later,
358 payload: {
359 ...staleRun,
360 delegatedCompletion: newerCohort,
361 },
362 });
363​
364 // Apply the real capture-emitted run.updated through ProjectionStore.
365 yield* projectionStore.apply(runUpdated);
366​
367 const projectedRun = (yield* projectionStore.getCheckpointCaptureContext(threadId, {
368 runId,
369 scopeId,
370 })).run;
371 assert.isDefined(projectedRun);
372 assert.equal(projectedRun?.status, "completed");
373 assert.equal(projectedRun?.checkpointId, runUpdated.payload.checkpointId);
374 assert.deepEqual(projectedRun?.delegatedCompletion, newerCohort);
375 assert.equal(projectedRun?.delegatedCompletion?.delivery?.messageId, deliveryMessageId);
376 assert.deepEqual(projectedRun?.delegatedCompletion?.delivery?.taskIds, [taskId]);
377 // The persisted completion is the at-least-once capture receipt.
378 yield* Ref.set(committed, []);
379 yield* service.execute({ threadId, runId, scopeId });
380 assert.deepEqual(yield* Ref.get(committed), []);
381 }).pipe(Effect.provide(layerCapture));
382 }),
383 );
384​
385 // Capture and rollback share the thread's effect lane, so a rollback can only
386 // commit before a capture runs: while it waits out a retry, or when a restart
387 // requeues it behind a pending rollback. It must not revive the run.
388 it.effect("does not capture a stopped run that a rollback already discarded", () =>
389 Effect.gen(function* () {
390 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
391 const now = yield* DateTime.now;
392 const stoppedThreadId = ThreadId.make("thread:checkpoint-capture-rolled-back");
393 const stoppedRunId = RunId.make("run:checkpoint-capture-rolled-back");
394 yield* projectionStore.apply({
395 id: EventId.make("event:checkpoint-capture-rolled-back:thread"),
396 type: "thread.created",
397 threadId: stoppedThreadId,
398 occurredAt: now,
399 payload: {
400 createdBy: "user",
401 creationSource: "web",
402 id: stoppedThreadId,
403 projectId,
404 title: "Checkpoint capture after rollback",
405 providerInstanceId,
406 modelSelection,
407 runtimeMode: "full-access",
408 interactionMode: "default",
409 branch: null,
410 worktreePath: null,
411 activeProviderThreadId: null,
412 lineage: {
413 parentThreadId: null,
414 relationshipToParent: null,
415 rootThreadId: stoppedThreadId,
416 },
417 forkedFrom: null,
418 createdAt: now,
419 updatedAt: now,
420 archivedAt: null,
421 settledOverride: null,
422 settledAt: null,
423 lastVisitedAt: null,
424 deletedAt: null,
425 },
426 });
427 const stoppedRun: OrchestrationV2Run = {
428 id: stoppedRunId,
429 threadId: stoppedThreadId,
430 ordinal: 2,
431 providerInstanceId,
432 modelSelection,
433 providerThreadId,
434 userMessageId: MessageId.make("message:checkpoint-capture-rolled-back"),
435 rootNodeId,
436 activeAttemptId: null,
437 status: "interrupted",
438 requestedAt: now,
439 startedAt: now,
440 completedAt: now,
441 checkpointId: null,
442 contextHandoffId: null,
443 };
444 // The rollback's write, which landed before the capture ran.
445 yield* projectionStore.apply({
446 id: EventId.make("event:checkpoint-capture-rolled-back:run"),
447 type: "run.updated",
448 threadId: stoppedThreadId,
449 runId: stoppedRunId,
450 providerInstanceId,
451 occurredAt: now,
452 payload: { ...stoppedRun, status: "rolled_back" },
453 });
454​
455 const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
456 const layerCapture = CheckpointCaptureService.layer.pipe(
457 Layer.provide(
458 Layer.mergeAll(
459 IdAllocator.layer,
460 Layer.mock(CheckpointService.CheckpointServiceV2)({
461 materializeBaselineCheckpoint: () => Effect.die("a discarded run has no baseline"),
462 capture: () => Effect.die("a discarded run must not be captured"),
463 }),
464 Layer.mock(EventSink.EventSinkV2)({
465 commitCommand: (input) =>
466 Ref.set(committed, input.events).pipe(Effect.as({ committed: true } as never)),
467 }),
468 ),
469 ),
470 );
471​
472 // Settles without retrying, and commits nothing that would revive the run.
473 yield* CheckpointCaptureService.CheckpointCaptureServiceV2.pipe(
474 Effect.flatMap((service) =>
475 service.execute({ threadId: stoppedThreadId, runId: stoppedRunId, scopeId }),
476 ),
477 Effect.provide(layerCapture),
478 );
479​
480 assert.deepEqual(yield* Ref.get(committed), []);
481 const projected = yield* projectionStore.getCheckpointCaptureContext(stoppedThreadId, {
482 runId: stoppedRunId,
483 scopeId,
484 });
485 assert.equal(projected.run?.status, "rolled_back");
486 assert.isNull(projected.run?.checkpointId ?? null);
487 }),
488 );
489​
490 // A cancelled run's checkpoint is the rollback point for the message after
491 // it, so capture records it without reporting the run as completed.
492 it.effect("records the checkpoint of a cancelled run and keeps it cancelled", () =>
493 Effect.gen(function* () {
494 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
495 const now = yield* DateTime.now;
496 const cancelledAt = DateTime.add(now, { seconds: 1 });
497 const cancelledThreadId = ThreadId.make("thread:checkpoint-capture-cancelled");
498 const cancelledRunId = RunId.make("run:checkpoint-capture-cancelled");
499 const cancelledScopeId = CheckpointScopeId.make("scope:checkpoint-capture-cancelled");
500 const cancelledRootNodeId = NodeId.make("node:checkpoint-capture-cancelled-root");
501 const cancelledProviderThreadId = ProviderThreadId.make(
502 "provider-thread:checkpoint-capture-cancelled",
503 );
504 yield* projectionStore.apply({
505 id: EventId.make("event:checkpoint-capture-cancelled:thread"),
506 type: "thread.created",
507 threadId: cancelledThreadId,
508 occurredAt: now,
509 payload: {
510 createdBy: "user",
511 creationSource: "web",
512 id: cancelledThreadId,
513 projectId,
514 title: "Checkpoint capture after cancel",
515 providerInstanceId,
516 modelSelection,
517 runtimeMode: "full-access",
518 interactionMode: "default",
519 branch: null,
520 worktreePath: null,
521 activeProviderThreadId: null,
522 lineage: {
523 parentThreadId: null,
524 relationshipToParent: null,
525 rootThreadId: cancelledThreadId,
526 },
527 forkedFrom: null,
528 createdAt: now,
529 updatedAt: now,
530 archivedAt: null,
531 settledOverride: null,
532 settledAt: null,
533 lastVisitedAt: null,
534 deletedAt: null,
535 },
536 });
537 const runningRun: OrchestrationV2Run = {
538 id: cancelledRunId,
539 threadId: cancelledThreadId,
540 ordinal: 1,
541 providerInstanceId,
542 modelSelection,
543 providerThreadId: cancelledProviderThreadId,
544 userMessageId: MessageId.make("message:checkpoint-capture-cancelled"),
545 rootNodeId: cancelledRootNodeId,
546 activeAttemptId: null,
547 status: "running",
548 requestedAt: now,
549 startedAt: now,
550 completedAt: null,
551 checkpointId: null,
552 contextHandoffId: null,
553 };
554 const runningRootNode = {
555 id: cancelledRootNodeId,
556 threadId: cancelledThreadId,
557 runId: cancelledRunId,
558 parentNodeId: null,
559 rootNodeId: cancelledRootNodeId,
560 kind: "root_turn" as const,
561 status: "running" as const,
562 countsForRun: true,
563 providerThreadId: cancelledProviderThreadId,
564 providerTurnId: null,
565 nativeItemRef: null,
566 runtimeRequestId: null,
567 checkpointScopeId: cancelledScopeId,
568 startedAt: now,
569 completedAt: null,
570 };
571 const scope = {
572 id: cancelledScopeId,
573 threadId: cancelledThreadId,
574 runId: cancelledRunId,
575 nodeId: cancelledRootNodeId,
576 parentScopeId: null,
577 providerThreadId: cancelledProviderThreadId,
578 kind: "root_run" as const,
579 ordinalWithinParent: 0,
580 advancesAppRunCount: true,
581 cwd: "/repo",
582 createdAt: now,
583 };
584 yield* projectionStore.apply({
585 id: EventId.make("event:checkpoint-capture-cancelled:provider-thread"),
586 type: "provider-thread.updated",
587 threadId: cancelledThreadId,
588 nodeId: cancelledRootNodeId,
589 driver,
590 providerInstanceId,
591 occurredAt: now,
592 payload: {
593 id: cancelledProviderThreadId,
594 driver,
595 providerInstanceId,
596 providerSessionId: null,
597 appThreadId: cancelledThreadId,
598 ownerNodeId: cancelledRootNodeId,
599 nativeThreadRef: null,
600 nativeConversationHeadRef: null,
601 status: "idle",
602 firstRunOrdinal: 1,
603 lastRunOrdinal: 1,
604 handoffIds: [],
605 forkedFrom: null,
606 createdAt: now,
607 updatedAt: now,
608 },
609 });
610 yield* projectionStore.apply({
611 id: EventId.make("event:checkpoint-capture-cancelled:scope"),
612 type: "checkpoint-scope.created",
613 threadId: cancelledThreadId,
614 runId: cancelledRunId,
615 nodeId: cancelledRootNodeId,
616 occurredAt: now,
617 payload: scope,
618 });
619 yield* projectionStore.apply({
620 id: EventId.make("event:checkpoint-capture-cancelled:baseline"),
621 type: "checkpoint.captured",
622 threadId: cancelledThreadId,
623 nodeId: cancelledRootNodeId,
624 driver,
625 providerInstanceId,
626 occurredAt: now,
627 payload: {
628 id: CheckpointId.make("checkpoint:cancelled-baseline-0"),
629 threadId: cancelledThreadId,
630 scopeId: cancelledScopeId,
631 runId: null,
632 nodeId: cancelledRootNodeId,
633 parentCheckpointId: null,
634 ordinalWithinScope: 0,
635 appRunOrdinal: null,
636 ref: CheckpointRef.make("checkpoint-ref:cancelled-baseline-0"),
637 status: "ready",
638 files: [],
639 capturedAt: now,
640 },
641 });
642 // The turn runs, then finalizes as cancelled the way RunExecutionService
643 // writes it, which also enqueues this capture.
644 for (const [status, completedAt] of [
645 ["running", null],
646 ["cancelled", cancelledAt],
647 ] as const) {
648 yield* projectionStore.apply({
649 id: EventId.make(`event:checkpoint-capture-cancelled:run-${status}`),
650 type: "run.updated",
651 threadId: cancelledThreadId,
652 runId: cancelledRunId,
653 nodeId: cancelledRootNodeId,
654 providerInstanceId,
655 occurredAt: completedAt ?? now,
656 payload: { ...runningRun, status, completedAt },
657 });
658 yield* projectionStore.apply({
659 id: EventId.make(`event:checkpoint-capture-cancelled:node-${status}`),
660 type: "node.updated",
661 threadId: cancelledThreadId,
662 runId: cancelledRunId,
663 nodeId: cancelledRootNodeId,
664 providerInstanceId,
665 occurredAt: completedAt ?? now,
666 payload: { ...runningRootNode, status, completedAt },
667 });
668 }
669​
670 const captured = {
671 id: CheckpointId.make("checkpoint:cancelled-captured-1"),
672 threadId: cancelledThreadId,
673 scopeId: cancelledScopeId,
674 runId: cancelledRunId,
675 nodeId: cancelledRootNodeId,
676 parentCheckpointId: CheckpointId.make("checkpoint:cancelled-baseline-0"),
677 ordinalWithinScope: 1,
678 appRunOrdinal: 1,
679 ref: CheckpointRef.make("checkpoint-ref:cancelled-captured-1"),
680 status: "ready" as const,
681 files: [],
682 capturedAt: cancelledAt,
683 };
684 const commits = yield* Ref.make(0);
685 const layerCapture = CheckpointCaptureService.layer.pipe(
686 Layer.provide(
687 Layer.mergeAll(
688 IdAllocator.layer,
689 Layer.mock(CheckpointService.CheckpointServiceV2)({
690 materializeBaselineCheckpoint: () =>
691 Effect.die("baseline materialization must be skipped when ordinal 0 is ready"),
692 capture: () => Effect.succeed(captured),
693 }),
694 // Commit straight into the projection so the test reads what a
695 // client would see after the capture lands.
696 Layer.mock(EventSink.EventSinkV2)({
697 commitCommand: (input) =>
698 Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe(
699 Effect.andThen(Ref.update(commits, (count) => count + 1)),
700 Effect.as({ committed: true } as never),
701 Effect.orDie,
702 ),
703 }),
704 ),
705 ),
706 );
707​
708 yield* Effect.gen(function* () {
709 const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
710 yield* service.execute({
711 threadId: cancelledThreadId,
712 runId: cancelledRunId,
713 scopeId: cancelledScopeId,
714 });
715 // A redelivered effect finds the recorded checkpoint and commits nothing.
716 yield* service.execute({
717 threadId: cancelledThreadId,
718 runId: cancelledRunId,
719 scopeId: cancelledScopeId,
720 });
721 }).pipe(Effect.provide(layerCapture));
722​
723 assert.equal(yield* Ref.get(commits), 1);
724 const projected = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, {
725 runId: cancelledRunId,
726 scopeId: cancelledScopeId,
727 });
728 assert.equal(projected.run?.status, "cancelled");
729 assert.equal(projected.run?.checkpointId, captured.id);
730 const completedAt = projected.run?.completedAt;
731 assert.equal(
732 completedAt ? DateTime.formatIso(completedAt) : completedAt,
733 DateTime.formatIso(cancelledAt),
734 );
735 assert.equal(projected.rootNode?.status, "cancelled");
736 assert.deepEqual([...projected.readyCheckpointOrdinals].toSorted(), [0, 1]);
737 }),
738 );
739});