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

CheckpointService.test.ts

832 lines34.0 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import {
5 CheckpointRef,
6 CheckpointScopeId,
7 NodeId,
8 ProjectId,
9 ProviderThreadId,
10 RunId,
11 ThreadId,
12 type OrchestrationV2CheckpointScope,
13 VcsProcessExitError,
14 VcsProcessTimeoutError,
15 VcsUnsupportedOperationError,
16} from "@t3tools/contracts";
17import * as Cause from "effect/Cause";
18import * as DateTime from "effect/DateTime";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as TestClock from "effect/testing/TestClock";
27​
28import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
29import * as CheckpointService from "./CheckpointService.ts";
30import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
31import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts";
32​
33const layerNoTrackedFolders = Layer.merge(
34 NodeServices.layer,
35 Layer.mock(WorkspaceFolders.WorkspaceFolders)({
36 forThread: () => Effect.succeed({ folders: [], extraRoots: [] }),
37 submodules: () => Effect.succeed([]),
38 }),
39);
40​
41it.effect(
42 "skips unsupported baseline and turn checkpoints without swallowing capture failures",
43 () =>
44 Effect.gen(function* () {
45 const scope: OrchestrationV2CheckpointScope = {
46 id: CheckpointScopeId.make("checkpoint-scope:capture-failure"),
47 threadId: ThreadId.make("thread:capture-failure"),
48 runId: RunId.make("run:capture-failure:1"),
49 nodeId: NodeId.make("node:capture-failure:1"),
50 parentScopeId: null,
51 providerThreadId: ProviderThreadId.make("provider-thread:capture-failure"),
52 kind: "root_run",
53 ordinalWithinParent: 0,
54 advancesAppRunCount: true,
55 cwd: "/repo/ignored",
56 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
57 };
58 for (const captureError of [
59 new VcsProcessTimeoutError({
60 operation: "test.capture",
61 command: "git",
62 cwd: scope.cwd,
63 timeoutMs: 30000,
64 }),
65 new VcsUnsupportedOperationError({
66 operation: "test.capture",
67 kind: "git",
68 detail: "The workspace directory is ignored by its Git repository.",
69 }),
70 ]) {
71 const layerTest = CheckpointService.layer.pipe(
72 Layer.provide(
73 Layer.mergeAll(
74 IdAllocator.layer,
75 layerNoTrackedFolders,
76 Layer.mock(CheckpointStore.CheckpointStore)({
77 isGitRepository: () => Effect.succeed(true),
78 hasCheckpointRef: () => Effect.succeed(false),
79 captureCheckpoint: () => Effect.fail(captureError),
80 }),
81 ),
82 ),
83 Layer.provideMerge(NodeCrypto.layer),
84 );
85 yield* Effect.gen(function* () {
86 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
87 const baseline = yield* Effect.result(
88 checkpoints.captureBaseline({ scope, ordinalWithinScope: 0 }),
89 );
90 const checkpoint = yield* checkpoints.capture({
91 scope,
92 ordinalWithinScope: 1,
93 runId: scope.runId!,
94 nodeId: scope.nodeId!,
95 appRunOrdinal: 1,
96 capturedAt: scope.createdAt,
97 });
98​
99 assert.deepEqual(
100 { baseline: baseline._tag, turn: checkpoint.status, files: checkpoint.files },
101 captureError._tag === "VcsUnsupportedOperationError"
102 ? { baseline: "Success", turn: "missing", files: [] }
103 : { baseline: "Failure", turn: "error", files: [] },
104 );
105 if (baseline._tag === "Failure") {
106 assert.strictEqual(baseline.failure.cause, captureError);
107 } else {
108 const materialized = yield* checkpoints.materializeBaselineCheckpoint({
109 scope,
110 ordinalWithinScope: 0,
111 nodeId: scope.nodeId,
112 capturedAt: scope.createdAt,
113 });
114 assert.strictEqual(materialized.status, "missing");
115 }
116 }).pipe(Effect.provide(layerTest));
117 }
118 }),
119);
120​
121it.effect(
122 "bounds a slow baseline snapshot but waits for an in-flight capture of the same ref",
123 () =>
124 Effect.gen(function* () {
125 const scope: OrchestrationV2CheckpointScope = {
126 id: CheckpointScopeId.make("checkpoint-scope:slow-baseline"),
127 threadId: ThreadId.make("thread:slow-baseline"),
128 runId: RunId.make("run:slow-baseline:1"),
129 nodeId: NodeId.make("node:slow-baseline:1"),
130 parentScopeId: null,
131 providerThreadId: ProviderThreadId.make("provider-thread:slow-baseline"),
132 kind: "root_run",
133 ordinalWithinParent: 0,
134 advancesAppRunCount: true,
135 cwd: "/repo/slow",
136 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
137 };
138 const refs = yield* Ref.make<ReadonlySet<string>>(new Set());
139 const snapshots = yield* Ref.make(0);
140 const firstSnapshotStarted = yield* Deferred.make<void>();
141 const layerTest = CheckpointService.layer.pipe(
142 Layer.provide(
143 Layer.mergeAll(
144 IdAllocator.layer,
145 layerNoTrackedFolders,
146 Layer.mock(CheckpointStore.CheckpointStore)({
147 isGitRepository: () => Effect.succeed(true),
148 hasCheckpointRef: ({ checkpointRef }) =>
149 Ref.get(refs).pipe(Effect.map((current) => current.has(checkpointRef))),
150 captureCheckpoint: ({ checkpointRef }) =>
151 Effect.gen(function* () {
152 yield* Ref.update(snapshots, (count) => count + 1);
153 yield* Deferred.succeed(firstSnapshotStarted, undefined);
154 yield* Effect.sleep("10 seconds");
155 yield* Ref.update(refs, (current) => new Set([...current, checkpointRef]));
156 return null;
157 }),
158 }),
159 ),
160 ),
161 Layer.provideMerge(NodeCrypto.layer),
162 );
163​
164 yield* Effect.gen(function* () {
165 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
166 // A stopped run's post-turn capture writes the next run's baseline ref while holding the lock.
167 const postTurn = yield* checkpoints
168 .capture({
169 scope,
170 ordinalWithinScope: 1,
171 runId: scope.runId!,
172 nodeId: scope.nodeId!,
173 appRunOrdinal: 1,
174 capturedAt: scope.createdAt,
175 })
176 .pipe(Effect.forkChild);
177 yield* Deferred.await(firstSnapshotStarted);
178 const waitingBaseline = yield* checkpoints
179 .captureBaseline({ scope, ordinalWithinScope: 1 })
180 .pipe(Effect.result, Effect.forkChild);
181 yield* TestClock.adjust("10 seconds");
182 assert.strictEqual((yield* Fiber.join(postTurn)).status, "ready");
183 assert.strictEqual((yield* Fiber.join(waitingBaseline))._tag, "Success");
184​
185 for (const ordinalWithinScope of [2, 3]) {
186 const slowBaseline = yield* checkpoints
187 .captureBaseline({ scope, ordinalWithinScope })
188 .pipe(Effect.result, Effect.forkChild);
189 yield* TestClock.adjust("5 seconds");
190 const result = yield* Fiber.join(slowBaseline);
191 assert.strictEqual(result._tag, "Failure");
192 if (result._tag === "Failure") {
193 assert.isTrue(Cause.isTimeoutError(result.failure.cause));
194 }
195 }
196 const backedOffBaseline = yield* checkpoints
197 .captureBaseline({ scope, ordinalWithinScope: 4 })
198 .pipe(Effect.result, Effect.forkChild);
199 yield* TestClock.adjust("5 seconds");
200 assert.strictEqual((yield* Fiber.join(backedOffBaseline))._tag, "Success");
201 assert.strictEqual(yield* Ref.get(snapshots), 3);
202 assert.strictEqual((yield* Ref.get(refs)).size, 1);
203 }).pipe(Effect.provide(layerTest));
204 }),
205);
206​
207it.effect.each([
208 { label: "a reused checkpoint", source: 2, copy: true, calls: ["copy"] },
209 { label: "a declined copy", source: 2, copy: false, calls: ["copy", "snapshot"] },
210 { label: "a copy slower than its budget", source: 2, calls: ["copy", "snapshot"] },
211])("baselines a turn after steered queued messages with $label", (row) =>
212 Effect.gen(function* () {
213 const scope: OrchestrationV2CheckpointScope = {
214 id: CheckpointScopeId.make("checkpoint-scope:queue-gap"),
215 threadId: ThreadId.make("thread:queue-gap"),
216 runId: RunId.make("run:queue-gap:1"),
217 nodeId: NodeId.make("node:queue-gap:1"),
218 parentScopeId: null,
219 providerThreadId: ProviderThreadId.make("provider-thread:queue-gap"),
220 kind: "root_run",
221 ordinalWithinParent: 0,
222 advancesAppRunCount: true,
223 cwd: "/repo/queue-gap",
224 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
225 };
226 const calls = yield* Ref.make<ReadonlyArray<string>>([]);
227 const record = (call: string) => Ref.update(calls, (current) => [...current, call]);
228 const layerTest = CheckpointService.layer.pipe(
229 Layer.provide(
230 Layer.mergeAll(
231 IdAllocator.layer,
232 layerNoTrackedFolders,
233 Layer.mock(CheckpointStore.CheckpointStore)({
234 isGitRepository: () => Effect.succeed(true),
235 hasCheckpointRef: () => Effect.succeed(false),
236 copyCheckpointRef: () =>
237 record("copy").pipe(
238 Effect.andThen(row.copy === undefined ? Effect.never : Effect.succeed(row.copy)),
239 ),
240 captureCheckpoint: () => record("snapshot").pipe(Effect.as(null)),
241 }),
242 ),
243 ),
244 Layer.provideMerge(NodeCrypto.layer),
245 );
246​
247 yield* Effect.gen(function* () {
248 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
249 const baseline = yield* checkpoints
250 .captureBaseline({ scope, ordinalWithinScope: 4, sourceOrdinalWithinScope: row.source })
251 .pipe(Effect.forkChild);
252 yield* TestClock.adjust("5 seconds");
253 yield* Fiber.join(baseline);
254 assert.deepEqual(yield* Ref.get(calls), row.calls);
255 }).pipe(Effect.provide(layerTest));
256 }),
257);
258​
259it.effect(
260 "asks Git about a tracked repository once a turn and snapshots it only when changed",
261 () =>
262 Effect.gen(function* () {
263 const scope: OrchestrationV2CheckpointScope = {
264 id: CheckpointScopeId.make("checkpoint-scope:repositories"),
265 threadId: ThreadId.make("thread:repositories"),
266 runId: RunId.make("run:repositories:1"),
267 nodeId: NodeId.make("node:repositories:1"),
268 parentScopeId: null,
269 providerThreadId: ProviderThreadId.make("provider-thread:repositories"),
270 kind: "root_run",
271 ordinalWithinParent: 0,
272 advancesAppRunCount: true,
273 cwd: "/wrapper",
274 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
275 };
276 const thread = { projectId: ProjectId.make("project:repositories"), worktreePath: null };
277 const repositories = Array.from({ length: 30 }, (_, index) => `/wrapper/repo-${index}`);
278 const [slowRepository, changedRepository] = [repositories[7]!, repositories[3]!];
279 const unreadableRepository = repositories[5]!;
280 const startHead = "a".repeat(40);
281 const heads = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
282 const refs = yield* Ref.make<ReadonlySet<string>>(new Set());
283 const calls = yield* Ref.make<ReadonlyArray<string>>([]);
284 const record = (call: string) => Ref.update(calls, (current) => [...current, call]);
285 const slow = yield* Ref.make(true);
286 const slowStarted = yield* Deferred.make<void>();
287 const othersSeen = yield* Deferred.make<void>();
288 const layerTest = CheckpointService.layer.pipe(
289 Layer.provide(
290 Layer.mergeAll(
291 IdAllocator.layer,
292 NodeServices.layer,
293 Layer.mock(WorkspaceFolders.WorkspaceFolders)({
294 forThread: () =>
295 Effect.succeed({
296 folders: [
297 ...repositories.map((path) => ({
298 name: path,
299 path,
300 isGitRepository: true,
301 // The first is a task folder's worktree of a tracked checkout elsewhere.
302 ...(path === repositories[0] ? { repositoryPath: "/tracked/repo-0" } : {}),
303 })),
304 { name: "notes", path: "/wrapper/notes", isGitRepository: false },
305 ],
306 extraRoots: [],
307 }),
308 submodules: () => Effect.succeed([]),
309 }),
310 Layer.mock(CheckpointStore.CheckpointStore)({
311 isGitRepository: (cwd) => record(`probe ${cwd}`).pipe(Effect.as(cwd !== "/wrapper")),
312 resolveCleanHead: (cwd) =>
313 Effect.gen(function* () {
314 // One repository is too slow for the turn to wait on.
315 if (cwd === slowRepository && (yield* Ref.get(slow))) {
316 yield* Deferred.succeed(slowStarted, undefined);
317 yield* Effect.sleep("1 minute");
318 }
319 yield* record(`status ${cwd}`);
320 if ((yield* Ref.get(calls)).length === repositories.length - 1) {
321 yield* Deferred.succeed(othersSeen, undefined);
322 }
323 return (yield* Ref.get(heads)).get(cwd) ?? startHead;
324 }),
325 hasCheckpointRef: ({ checkpointRef }) =>
326 Ref.get(refs).pipe(Effect.map((current) => current.has(checkpointRef))),
327 captureHeadCheckpoint: ({ cwd, head, checkpointRef }) =>
328 record(`snapshot ${cwd} at ${head[0]}`).pipe(
329 Effect.andThen(
330 Ref.update(refs, (current) => new Set([...current, checkpointRef])),
331 ),
332 ),
333 diffCheckpoints: ({ cwd }) =>
334 cwd === unreadableRepository
335 ? Effect.fail(
336 new VcsProcessExitError({
337 operation: "test.diff",
338 command: "git",
339 cwd,
340 exitCode: 128,
341 detail: "fatal: unable to read tree",
342 }),
343 )
344 : Effect.succeed("1\t0\tfile.ts\0"),
345 listAuthoredPaths: () => Effect.succeed(null),
346 }),
347 ),
348 ),
349 Layer.provideMerge(NodeCrypto.layer),
350 );
351​
352 yield* Effect.gen(function* () {
353 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
354 const scopes = yield* checkpoints.repositoryScopes({ rootScope: scope, ...thread });
355 // The plain folder gets no scope.
356 assert.deepEqual(
357 scopes.map((repository) => repository.cwd),
358 repositories,
359 );
360 // A scope works in the thread's checkout and is known by the tracked folder it stands for.
361 assert.deepEqual(
362 scopes.slice(0, 2).map((repository) => repository.repositoryPath),
363 ["/tracked/repo-0", repositories[1]],
364 );
365 const captureAll = (ordinalWithinScope: number) =>
366 Effect.forEach(scopes, (repository) =>
367 checkpoints.captureRepository({
368 scope: repository,
369 runId: scope.runId!,
370 nodeId: scope.nodeId,
371 ordinalWithinScope,
372 capturedAt: scope.createdAt,
373 baselineCapturedAt: scope.createdAt,
374 baselineRecorded: false,
375 }),
376 );
377​
378 // Every baseline shares the turn's budget; the slow repository is left without one.
379 const firstTurn = yield* checkpoints
380 .captureBaseline({ scope, ordinalWithinScope: 0, thread })
381 .pipe(Effect.forkChild);
382 yield* Deferred.await(slowStarted);
383 yield* Deferred.await(othersSeen);
384 yield* TestClock.adjust("5 seconds");
385 yield* Fiber.join(firstTurn);
386 yield* Ref.set(slow, false);
387​
388 // A turn that changes nothing writes nothing and records nothing.
389 assert.isTrue((yield* captureAll(1)).every(Option.isNone));
390 assert.isFalse((yield* Ref.get(calls)).some((call) => call.startsWith("snapshot")));
391​
392 // The next turn starts from what each repository's last run ended with, so only the
393 // thread's own folder is read.
394 yield* Ref.set(calls, []);
395 yield* checkpoints.captureBaseline({ scope, ordinalWithinScope: 1, thread });
396 assert.deepEqual(yield* Ref.get(calls), ["probe /wrapper"]);
397​
398 // The turn commits in two repositories: each baseline is snapshotted from where it started.
399 // One of them cannot list what changed, which is not the same as nothing having changed.
400 yield* Ref.set(
401 heads,
402 new Map([
403 [changedRepository, "b".repeat(40)],
404 [unreadableRepository, "b".repeat(40)],
405 ]),
406 );
407 yield* Ref.set(calls, []);
408 const recorded = (yield* captureAll(2)).flatMap(Option.toArray);
409 assert.deepEqual(
410 recorded.map(({ baseline, checkpoint }) => ({
411 cwd: scopes.find((repository) => repository.id === checkpoint.scopeId)?.cwd,
412 baseline: baseline?.ordinalWithinScope,
413 ordinal: checkpoint.ordinalWithinScope,
414 files: checkpoint.files.map((file) => file.path),
415 })),
416 [
417 { cwd: changedRepository, baseline: 1, ordinal: 2, files: ["file.ts"] },
418 { cwd: unreadableRepository, baseline: 1, ordinal: 2, files: [] },
419 ],
420 );
421 assert.deepEqual(
422 (yield* Ref.get(calls)).filter((call) => call.startsWith("snapshot")),
423 [changedRepository, unreadableRepository].flatMap((cwd) => [
424 `snapshot ${cwd} at a`,
425 `snapshot ${cwd} at b`,
426 ]),
427 );
428 assert.lengthOf(
429 (yield* Ref.get(calls)).filter((call) => call.startsWith("status")),
430 repositories.length,
431 );
432 }).pipe(Effect.provide(layerTest));
433 }),
434);
435​
436it.effect("records a repository probe failure as an error checkpoint, not a missing one", () =>
437 Effect.gen(function* () {
438 const scope: OrchestrationV2CheckpointScope = {
439 id: CheckpointScopeId.make("checkpoint-scope:probe-failure"),
440 threadId: ThreadId.make("thread:probe-failure"),
441 runId: RunId.make("run:probe-failure:1"),
442 nodeId: NodeId.make("node:probe-failure:1"),
443 parentScopeId: null,
444 providerThreadId: ProviderThreadId.make("provider-thread:probe-failure"),
445 kind: "root_run",
446 ordinalWithinParent: 0,
447 advancesAppRunCount: true,
448 cwd: "/repo/bad-config",
449 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
450 };
451 const layerTest = CheckpointService.layer.pipe(
452 Layer.provide(
453 Layer.mergeAll(
454 IdAllocator.layer,
455 layerNoTrackedFolders,
456 Layer.mock(CheckpointStore.CheckpointStore)({
457 isGitRepository: () =>
458 Effect.fail(
459 new VcsProcessExitError({
460 operation: "GitVcsDriver.detectRepository",
461 command: "git",
462 cwd: scope.cwd,
463 exitCode: 128,
464 detail: "fatal: bad config line 1 in file .git/config",
465 }),
466 ),
467 }),
468 ),
469 ),
470 Layer.provideMerge(NodeCrypto.layer),
471 );
472​
473 const statuses = yield* Effect.gen(function* () {
474 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
475 const baseline = yield* checkpoints.materializeBaselineCheckpoint({
476 scope,
477 ordinalWithinScope: 0,
478 nodeId: scope.nodeId,
479 capturedAt: scope.createdAt,
480 });
481 const turn = yield* checkpoints.capture({
482 scope,
483 ordinalWithinScope: 1,
484 runId: scope.runId!,
485 nodeId: scope.nodeId!,
486 appRunOrdinal: 1,
487 capturedAt: scope.createdAt,
488 });
489 return { baseline: baseline.status, turn: turn.status };
490 }).pipe(Effect.provide(layerTest));
491​
492 assert.deepEqual(statuses, { baseline: "error", turn: "error" });
493 }),
494);
495​
496it.effect("backs off only baseline retries after repeated workspace capture timeouts", () =>
497 Effect.gen(function* () {
498 const scope: OrchestrationV2CheckpointScope = {
499 id: CheckpointScopeId.make("checkpoint-scope:slow-capture"),
500 threadId: ThreadId.make("thread:slow-capture"),
501 runId: RunId.make("run:slow-capture:1"),
502 nodeId: NodeId.make("node:slow-capture:1"),
503 parentScopeId: null,
504 providerThreadId: ProviderThreadId.make("provider-thread:slow-capture"),
505 kind: "root_run",
506 ordinalWithinParent: 0,
507 advancesAppRunCount: true,
508 cwd: "/repo/slow",
509 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
510 };
511 const timeout = new VcsProcessTimeoutError({
512 operation: "GitVcsDriver.checkpoints.captureCheckpoint",
513 command: "git",
514 cwd: scope.cwd,
515 timeoutMs: 30_000,
516 });
517 let attempts = 0;
518 let healthy = false;
519 let nonTimeoutFailure = false;
520 const failure = new VcsProcessExitError({
521 operation: "test.capture",
522 command: "git",
523 cwd: scope.cwd,
524 exitCode: 128,
525 detail: "capture failed",
526 });
527 const layerTest = CheckpointService.layer.pipe(
528 Layer.provide(
529 Layer.mergeAll(
530 IdAllocator.layer,
531 layerNoTrackedFolders,
532 Layer.mock(CheckpointStore.CheckpointStore)({
533 isGitRepository: () => Effect.succeed(true),
534 hasCheckpointRef: () => Effect.succeed(false),
535 captureCheckpoint: () =>
536 Effect.suspend(() => {
537 attempts++;
538 return healthy
539 ? Effect.succeed(null)
540 : Effect.fail(nonTimeoutFailure ? failure : timeout);
541 }),
542 }),
543 ),
544 ),
545 Layer.provideMerge(NodeCrypto.layer),
546 );
547 yield* Effect.gen(function* () {
548 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
549 const baseline = { scope, ordinalWithinScope: 0 };
550 const turn = {
551 scope,
552 ordinalWithinScope: 1,
553 runId: scope.runId,
554 nodeId: scope.nodeId,
555 appRunOrdinal: 1,
556 capturedAt: scope.createdAt,
557 };
558 yield* Effect.result(checkpoints.captureBaseline(baseline));
559 assert.strictEqual((yield* checkpoints.capture(turn)).status, "error");
560 assert.strictEqual(attempts, 2);
561​
562 const otherThread = { ...scope, id: CheckpointScopeId.make("checkpoint-scope:other") };
563 const skipped = yield* Effect.result(
564 checkpoints.captureBaseline({ scope: otherThread, ordinalWithinScope: 0 }),
565 );
566 assert.strictEqual(attempts, 2, "baseline retried a repeatedly timing-out workspace");
567 assert.strictEqual(skipped._tag, "Success");
568​
569 yield* Effect.result(
570 checkpoints.captureBaseline({
571 scope: { ...otherThread, cwd: "/repo/other" },
572 ordinalWithinScope: 0,
573 }),
574 );
575 assert.strictEqual(attempts, 3, "another workspace must still attempt capture");
576​
577 const failedTurn = yield* checkpoints.capture(turn);
578 assert.strictEqual(failedTurn.status, "error");
579 assert.strictEqual(attempts, 4, "post-turn capture must not back off");
580​
581 yield* checkpoints.captureBaseline(baseline);
582 assert.strictEqual(attempts, 4, "baseline retries must wait for post-turn recovery");
583 healthy = true;
584 assert.strictEqual((yield* checkpoints.capture(turn)).status, "ready");
585 assert.strictEqual(attempts, 5);
586 yield* checkpoints.captureBaseline(baseline);
587 assert.strictEqual(attempts, 6, "a successful post-turn capture must clear backoff");
588​
589 healthy = false;
590 yield* Effect.result(checkpoints.captureBaseline(baseline));
591 yield* Effect.result(checkpoints.captureBaseline(baseline));
592 yield* checkpoints.captureBaseline(baseline);
593 assert.strictEqual(attempts, 8);
594 nonTimeoutFailure = true;
595 assert.strictEqual((yield* checkpoints.capture(turn)).status, "error");
596 nonTimeoutFailure = false;
597 yield* Effect.result(checkpoints.captureBaseline(baseline));
598 assert.strictEqual(attempts, 10, "a non-timeout failure must clear backoff");
599 healthy = true;
600 yield* checkpoints.captureBaseline(baseline);
601 healthy = false;
602 yield* Effect.result(checkpoints.captureBaseline(baseline));
603 yield* Effect.result(checkpoints.captureBaseline(baseline));
604 assert.strictEqual(attempts, 13, "a successful baseline must clear the timeout streak");
605 }).pipe(Effect.provide(layerTest));
606 }),
607);
608​
609it.effect("skips post-turn captures that waited out another capture's timeout in the folder", () =>
610 Effect.gen(function* () {
611 const scopeFor = (name: string): OrchestrationV2CheckpointScope => ({
612 id: CheckpointScopeId.make(`checkpoint-scope:shared-folder:${name}`),
613 threadId: ThreadId.make(`thread:shared-folder:${name}`),
614 runId: RunId.make(`run:shared-folder:${name}:1`),
615 nodeId: NodeId.make(`node:shared-folder:${name}:1`),
616 parentScopeId: null,
617 providerThreadId: ProviderThreadId.make(`provider-thread:shared-folder:${name}`),
618 kind: "root_run",
619 ordinalWithinParent: 0,
620 advancesAppRunCount: true,
621 cwd: "/repo/shared",
622 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
623 });
624 const attempts = yield* Ref.make(0);
625 // Outcomes for upcoming attempts; an attempt with none scripted times out.
626 const script = yield* Ref.make<ReadonlyArray<"ready" | "timeout">>([]);
627 const started = yield* Queue.unbounded<void>();
628 const layerTest = CheckpointService.layer.pipe(
629 Layer.provide(
630 Layer.mergeAll(
631 IdAllocator.layer,
632 layerNoTrackedFolders,
633 Layer.mock(CheckpointStore.CheckpointStore)({
634 isGitRepository: () => Effect.succeed(true),
635 hasCheckpointRef: () => Effect.succeed(false),
636 resolveCleanHead: () => Effect.succeed(null),
637 captureCheckpoint: ({ cwd }) =>
638 Effect.gen(function* () {
639 yield* Ref.update(attempts, (count) => count + 1);
640 yield* Queue.offer(started, undefined);
641 yield* Effect.sleep("30 seconds");
642 const [next = "timeout", ...rest] = yield* Ref.get(script);
643 yield* Ref.set(script, rest);
644 if (next === "ready") return null;
645 return yield* new VcsProcessTimeoutError({
646 operation: "GitVcsDriver.checkpoints.captureCheckpoint",
647 command: "git",
648 cwd,
649 timeoutMs: 30_000,
650 });
651 }),
652 }),
653 ),
654 ),
655 Layer.provideMerge(NodeCrypto.layer),
656 );
657 yield* Effect.gen(function* () {
658 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
659 const captureTurn = (scope: OrchestrationV2CheckpointScope) =>
660 checkpoints
661 .capture({
662 scope,
663 ordinalWithinScope: 1,
664 runId: scope.runId!,
665 nodeId: scope.nodeId!,
666 appRunOrdinal: 1,
667 capturedAt: scope.createdAt,
668 })
669 .pipe(Effect.forkChild);
670 // A baseline's short budget running out says nothing about a post-turn capture.
671 const baseline = yield* checkpoints
672 .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 })
673 .pipe(Effect.result, Effect.forkChild);
674 yield* Queue.take(started);
675 const afterBaseline = yield* captureTurn(scopeFor("after-baseline"));
676 yield* TestClock.adjust("5 seconds");
677 yield* Fiber.join(baseline);
678 yield* Queue.take(started);
679 yield* TestClock.adjust("30 seconds");
680 assert.strictEqual((yield* Fiber.join(afterBaseline)).status, "error");
681 assert.strictEqual(yield* Ref.get(attempts), 2);
682​
683 const first = yield* captureTurn(scopeFor("first"));
684 yield* Queue.take(started);
685 // After repeated timeouts a new thread's baseline skips without waiting on that capture.
686 yield* checkpoints.captureBaseline({ scope: scopeFor("new-thread"), ordinalWithinScope: 0 });
687 assert.strictEqual(yield* Ref.get(attempts), 3);
688 // Other threads in the same folder finish their turns while the first capture hangs.
689 const waiting = [
690 yield* captureTurn(scopeFor("second")),
691 yield* captureTurn(scopeFor("third")),
692 ];
693 const repository = scopeFor("repository");
694 const repositoryWaiting = yield* checkpoints
695 .captureRepository({
696 scope: repository,
697 runId: repository.runId!,
698 nodeId: repository.nodeId!,
699 ordinalWithinScope: 1,
700 capturedAt: repository.createdAt,
701 baselineCapturedAt: repository.createdAt,
702 baselineRecorded: true,
703 })
704 .pipe(Effect.forkChild);
705 // A thread's root capture first materializes its baseline, which waits on the lock too.
706 const root = scopeFor("root");
707 const rootWaiting = yield* Effect.gen(function* () {
708 const capturesBeforeLock = yield* checkpoints.capturesSoFar(root.cwd);
709 yield* checkpoints.materializeBaselineCheckpoint({
710 scope: root,
711 ordinalWithinScope: 0,
712 nodeId: root.nodeId!,
713 capturedAt: root.createdAt,
714 });
715 return yield* checkpoints.capture({
716 scope: root,
717 ordinalWithinScope: 1,
718 runId: root.runId!,
719 nodeId: root.nodeId!,
720 appRunOrdinal: 1,
721 capturedAt: root.createdAt,
722 capturesBeforeLock,
723 });
724 }).pipe(Effect.forkChild);
725 yield* TestClock.adjust("30 seconds");
726 assert.strictEqual((yield* Fiber.join(first)).status, "error");
727 // Room for every waiter to probe, so the count below is what fails without the fix.
728 yield* TestClock.adjust("120 seconds");
729 for (const fiber of waiting) {
730 assert.strictEqual((yield* Fiber.join(fiber)).status, "error");
731 }
732 const repositoryCaptured = yield* Fiber.join(repositoryWaiting);
733 assert.strictEqual(Option.getOrThrow(repositoryCaptured).checkpoint.status, "error");
734 assert.strictEqual((yield* Fiber.join(rootWaiting)).status, "error");
735 assert.strictEqual(yield* Ref.get(attempts), 3, "each waiter spent its own full timeout");
736​
737 // A capture that starts after the timeout still probes for recovery.
738 const later = yield* captureTurn(scopeFor("later"));
739 yield* TestClock.adjust("30 seconds");
740 assert.strictEqual((yield* Fiber.join(later)).status, "error");
741 assert.strictEqual(yield* Ref.get(attempts), 4);
742​
743 // A success ahead in the queue does not hide a timeout that follows it.
744 yield* Ref.set(script, ["ready", "timeout"]);
745 const recovered = yield* captureTurn(scopeFor("recovered"));
746 const relapsed = yield* captureTurn(scopeFor("relapsed"));
747 const queuedBehind = yield* captureTurn(scopeFor("queued-behind"));
748 yield* TestClock.adjust("90 seconds");
749 assert.deepEqual(
750 [
751 (yield* Fiber.join(recovered)).status,
752 (yield* Fiber.join(relapsed)).status,
753 (yield* Fiber.join(queuedBehind)).status,
754 ],
755 ["ready", "error", "error"],
756 );
757 assert.strictEqual(yield* Ref.get(attempts), 6, "the waiter probed after a later timeout");
758 }).pipe(Effect.provide(layerTest));
759 }),
760);
761​
762it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not put back", () => {
763 const targets = ["first", "second"].map((name) => ({
764 scope: { id: CheckpointScopeId.make(`checkpoint-scope:rewind:${name}`), cwd: `/repo/${name}` },
765 checkpoint: {
766 ordinalWithinScope: 1,
767 ref: CheckpointRef.make(`refs/t3/test/rewind/${name}`),
768 status: "ready" as const,
769 },
770 }));
771 const failure = new VcsProcessTimeoutError({
772 operation: "test.restore",
773 command: "git",
774 cwd: "/repo",
775 timeoutMs: 30000,
776 });
777 const preRewindRefs = new Map<string, string>();
778 const captured: Array<string> = [];
779 const existing = new Set<string>();
780 const deleted: Array<{ readonly cwd: string; readonly ref: string }> = [];
781 const layerTest = CheckpointService.layer.pipe(
782 Layer.provide(
783 Layer.mergeAll(
784 IdAllocator.layer,
785 layerNoTrackedFolders,
786 Layer.mock(CheckpointStore.CheckpointStore)({
787 hasCheckpointRef: (input) =>
788 Effect.sync(
789 () =>
790 targets.some((target) => target.checkpoint.ref === input.checkpointRef) ||
791 existing.has(input.checkpointRef),
792 ),
793 captureCheckpoint: (input) =>
794 Effect.sync(() => {
795 captured.push(input.cwd);
796 existing.add(input.checkpointRef);
797 preRewindRefs.set(input.cwd, input.checkpointRef);
798 return null;
799 }),
800 // The second folder's rewind fails, and then so does putting the first one back.
801 restoreCheckpoint: (input) =>
802 input.checkpointRef === targets[1]!.checkpoint.ref ||
803 input.checkpointRef === preRewindRefs.get("/repo/first")
804 ? Effect.fail(failure)
805 : Effect.succeed(true),
806 deleteCheckpointRefs: (input) =>
807 Effect.sync(() => {
808 for (const ref of input.checkpointRefs) {
809 existing.delete(ref);
810 deleted.push({ cwd: input.cwd, ref });
811 }
812 }),
813 }),
814 ),
815 ),
816 Layer.provideMerge(NodeCrypto.layer),
817 );
818 return Effect.gen(function* () {
819 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
820 const result = yield* Effect.result(
821 checkpoints.restore({ targets, scopes: targets.map((target) => target.scope) }),
822 );
823 assert.strictEqual(result._tag, "Failure");
824 assert.deepEqual(deleted, [{ cwd: "/repo/second", ref: preRewindRefs.get("/repo/second")! }]);
825​
826 // A retry starts from a half-restored folder; the kept snapshot is not taken again.
827 yield* Effect.result(
828 checkpoints.restore({ targets, scopes: targets.map((target) => target.scope) }),
829 );
830 assert.deepEqual(captured, ["/repo/first", "/repo/second", "/repo/second"]);
831 }).pipe(Effect.provide(layerTest));
832});