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

CheckpointService.test.ts

777 lines31.6 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(
208 "asks Git about a tracked repository once a turn and snapshots it only when changed",
209 () =>
210 Effect.gen(function* () {
211 const scope: OrchestrationV2CheckpointScope = {
212 id: CheckpointScopeId.make("checkpoint-scope:repositories"),
213 threadId: ThreadId.make("thread:repositories"),
214 runId: RunId.make("run:repositories:1"),
215 nodeId: NodeId.make("node:repositories:1"),
216 parentScopeId: null,
217 providerThreadId: ProviderThreadId.make("provider-thread:repositories"),
218 kind: "root_run",
219 ordinalWithinParent: 0,
220 advancesAppRunCount: true,
221 cwd: "/wrapper",
222 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
223 };
224 const thread = { projectId: ProjectId.make("project:repositories"), worktreePath: null };
225 const repositories = Array.from({ length: 30 }, (_, index) => `/wrapper/repo-${index}`);
226 const [slowRepository, changedRepository] = [repositories[7]!, repositories[3]!];
227 const unreadableRepository = repositories[5]!;
228 const startHead = "a".repeat(40);
229 const heads = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
230 const refs = yield* Ref.make<ReadonlySet<string>>(new Set());
231 const calls = yield* Ref.make<ReadonlyArray<string>>([]);
232 const record = (call: string) => Ref.update(calls, (current) => [...current, call]);
233 const slow = yield* Ref.make(true);
234 const slowStarted = yield* Deferred.make<void>();
235 const othersSeen = yield* Deferred.make<void>();
236 const layerTest = CheckpointService.layer.pipe(
237 Layer.provide(
238 Layer.mergeAll(
239 IdAllocator.layer,
240 NodeServices.layer,
241 Layer.mock(WorkspaceFolders.WorkspaceFolders)({
242 forThread: () =>
243 Effect.succeed({
244 folders: [
245 ...repositories.map((path) => ({
246 name: path,
247 path,
248 isGitRepository: true,
249 // The first is a task folder's worktree of a tracked checkout elsewhere.
250 ...(path === repositories[0] ? { repositoryPath: "/tracked/repo-0" } : {}),
251 })),
252 { name: "notes", path: "/wrapper/notes", isGitRepository: false },
253 ],
254 extraRoots: [],
255 }),
256 submodules: () => Effect.succeed([]),
257 }),
258 Layer.mock(CheckpointStore.CheckpointStore)({
259 isGitRepository: (cwd) => record(`probe ${cwd}`).pipe(Effect.as(cwd !== "/wrapper")),
260 resolveCleanHead: (cwd) =>
261 Effect.gen(function* () {
262 // One repository is too slow for the turn to wait on.
263 if (cwd === slowRepository && (yield* Ref.get(slow))) {
264 yield* Deferred.succeed(slowStarted, undefined);
265 yield* Effect.sleep("1 minute");
266 }
267 yield* record(`status ${cwd}`);
268 if ((yield* Ref.get(calls)).length === repositories.length - 1) {
269 yield* Deferred.succeed(othersSeen, undefined);
270 }
271 return (yield* Ref.get(heads)).get(cwd) ?? startHead;
272 }),
273 hasCheckpointRef: ({ checkpointRef }) =>
274 Ref.get(refs).pipe(Effect.map((current) => current.has(checkpointRef))),
275 captureHeadCheckpoint: ({ cwd, head, checkpointRef }) =>
276 record(`snapshot ${cwd} at ${head[0]}`).pipe(
277 Effect.andThen(
278 Ref.update(refs, (current) => new Set([...current, checkpointRef])),
279 ),
280 ),
281 diffCheckpoints: ({ cwd }) =>
282 cwd === unreadableRepository
283 ? Effect.fail(
284 new VcsProcessExitError({
285 operation: "test.diff",
286 command: "git",
287 cwd,
288 exitCode: 128,
289 detail: "fatal: unable to read tree",
290 }),
291 )
292 : Effect.succeed("1\t0\tfile.ts\0"),
293 listAuthoredPaths: () => Effect.succeed(null),
294 }),
295 ),
296 ),
297 Layer.provideMerge(NodeCrypto.layer),
298 );
299​
300 yield* Effect.gen(function* () {
301 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
302 const scopes = yield* checkpoints.repositoryScopes({ rootScope: scope, ...thread });
303 // The plain folder gets no scope.
304 assert.deepEqual(
305 scopes.map((repository) => repository.cwd),
306 repositories,
307 );
308 // A scope works in the thread's checkout and is known by the tracked folder it stands for.
309 assert.deepEqual(
310 scopes.slice(0, 2).map((repository) => repository.repositoryPath),
311 ["/tracked/repo-0", repositories[1]],
312 );
313 const captureAll = (ordinalWithinScope: number) =>
314 Effect.forEach(scopes, (repository) =>
315 checkpoints.captureRepository({
316 scope: repository,
317 runId: scope.runId!,
318 nodeId: scope.nodeId,
319 ordinalWithinScope,
320 capturedAt: scope.createdAt,
321 baselineCapturedAt: scope.createdAt,
322 baselineRecorded: false,
323 }),
324 );
325​
326 // Every baseline shares the turn's budget; the slow repository is left without one.
327 const firstTurn = yield* checkpoints
328 .captureBaseline({ scope, ordinalWithinScope: 0, thread })
329 .pipe(Effect.forkChild);
330 yield* Deferred.await(slowStarted);
331 yield* Deferred.await(othersSeen);
332 yield* TestClock.adjust("5 seconds");
333 yield* Fiber.join(firstTurn);
334 yield* Ref.set(slow, false);
335​
336 // A turn that changes nothing writes nothing and records nothing.
337 assert.isTrue((yield* captureAll(1)).every(Option.isNone));
338 assert.isFalse((yield* Ref.get(calls)).some((call) => call.startsWith("snapshot")));
339​
340 // The next turn starts from what each repository's last run ended with, so only the
341 // thread's own folder is read.
342 yield* Ref.set(calls, []);
343 yield* checkpoints.captureBaseline({ scope, ordinalWithinScope: 1, thread });
344 assert.deepEqual(yield* Ref.get(calls), ["probe /wrapper"]);
345​
346 // The turn commits in two repositories: each baseline is snapshotted from where it started.
347 // One of them cannot list what changed, which is not the same as nothing having changed.
348 yield* Ref.set(
349 heads,
350 new Map([
351 [changedRepository, "b".repeat(40)],
352 [unreadableRepository, "b".repeat(40)],
353 ]),
354 );
355 yield* Ref.set(calls, []);
356 const recorded = (yield* captureAll(2)).flatMap(Option.toArray);
357 assert.deepEqual(
358 recorded.map(({ baseline, checkpoint }) => ({
359 cwd: scopes.find((repository) => repository.id === checkpoint.scopeId)?.cwd,
360 baseline: baseline?.ordinalWithinScope,
361 ordinal: checkpoint.ordinalWithinScope,
362 files: checkpoint.files.map((file) => file.path),
363 })),
364 [
365 { cwd: changedRepository, baseline: 1, ordinal: 2, files: ["file.ts"] },
366 { cwd: unreadableRepository, baseline: 1, ordinal: 2, files: [] },
367 ],
368 );
369 assert.deepEqual(
370 (yield* Ref.get(calls)).filter((call) => call.startsWith("snapshot")),
371 [changedRepository, unreadableRepository].flatMap((cwd) => [
372 `snapshot ${cwd} at a`,
373 `snapshot ${cwd} at b`,
374 ]),
375 );
376 assert.lengthOf(
377 (yield* Ref.get(calls)).filter((call) => call.startsWith("status")),
378 repositories.length,
379 );
380 }).pipe(Effect.provide(layerTest));
381 }),
382);
383​
384it.effect("records a repository probe failure as an error checkpoint, not a missing one", () =>
385 Effect.gen(function* () {
386 const scope: OrchestrationV2CheckpointScope = {
387 id: CheckpointScopeId.make("checkpoint-scope:probe-failure"),
388 threadId: ThreadId.make("thread:probe-failure"),
389 runId: RunId.make("run:probe-failure:1"),
390 nodeId: NodeId.make("node:probe-failure:1"),
391 parentScopeId: null,
392 providerThreadId: ProviderThreadId.make("provider-thread:probe-failure"),
393 kind: "root_run",
394 ordinalWithinParent: 0,
395 advancesAppRunCount: true,
396 cwd: "/repo/bad-config",
397 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
398 };
399 const layerTest = CheckpointService.layer.pipe(
400 Layer.provide(
401 Layer.mergeAll(
402 IdAllocator.layer,
403 layerNoTrackedFolders,
404 Layer.mock(CheckpointStore.CheckpointStore)({
405 isGitRepository: () =>
406 Effect.fail(
407 new VcsProcessExitError({
408 operation: "GitVcsDriver.detectRepository",
409 command: "git",
410 cwd: scope.cwd,
411 exitCode: 128,
412 detail: "fatal: bad config line 1 in file .git/config",
413 }),
414 ),
415 }),
416 ),
417 ),
418 Layer.provideMerge(NodeCrypto.layer),
419 );
420​
421 const statuses = yield* Effect.gen(function* () {
422 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
423 const baseline = yield* checkpoints.materializeBaselineCheckpoint({
424 scope,
425 ordinalWithinScope: 0,
426 nodeId: scope.nodeId,
427 capturedAt: scope.createdAt,
428 });
429 const turn = yield* checkpoints.capture({
430 scope,
431 ordinalWithinScope: 1,
432 runId: scope.runId!,
433 nodeId: scope.nodeId!,
434 appRunOrdinal: 1,
435 capturedAt: scope.createdAt,
436 });
437 return { baseline: baseline.status, turn: turn.status };
438 }).pipe(Effect.provide(layerTest));
439​
440 assert.deepEqual(statuses, { baseline: "error", turn: "error" });
441 }),
442);
443​
444it.effect("backs off only baseline retries after repeated workspace capture timeouts", () =>
445 Effect.gen(function* () {
446 const scope: OrchestrationV2CheckpointScope = {
447 id: CheckpointScopeId.make("checkpoint-scope:slow-capture"),
448 threadId: ThreadId.make("thread:slow-capture"),
449 runId: RunId.make("run:slow-capture:1"),
450 nodeId: NodeId.make("node:slow-capture:1"),
451 parentScopeId: null,
452 providerThreadId: ProviderThreadId.make("provider-thread:slow-capture"),
453 kind: "root_run",
454 ordinalWithinParent: 0,
455 advancesAppRunCount: true,
456 cwd: "/repo/slow",
457 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
458 };
459 const timeout = new VcsProcessTimeoutError({
460 operation: "GitVcsDriver.checkpoints.captureCheckpoint",
461 command: "git",
462 cwd: scope.cwd,
463 timeoutMs: 30_000,
464 });
465 let attempts = 0;
466 let healthy = false;
467 let nonTimeoutFailure = false;
468 const failure = new VcsProcessExitError({
469 operation: "test.capture",
470 command: "git",
471 cwd: scope.cwd,
472 exitCode: 128,
473 detail: "capture failed",
474 });
475 const layerTest = CheckpointService.layer.pipe(
476 Layer.provide(
477 Layer.mergeAll(
478 IdAllocator.layer,
479 layerNoTrackedFolders,
480 Layer.mock(CheckpointStore.CheckpointStore)({
481 isGitRepository: () => Effect.succeed(true),
482 hasCheckpointRef: () => Effect.succeed(false),
483 captureCheckpoint: () =>
484 Effect.suspend(() => {
485 attempts++;
486 return healthy
487 ? Effect.succeed(null)
488 : Effect.fail(nonTimeoutFailure ? failure : timeout);
489 }),
490 }),
491 ),
492 ),
493 Layer.provideMerge(NodeCrypto.layer),
494 );
495 yield* Effect.gen(function* () {
496 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
497 const baseline = { scope, ordinalWithinScope: 0 };
498 const turn = {
499 scope,
500 ordinalWithinScope: 1,
501 runId: scope.runId,
502 nodeId: scope.nodeId,
503 appRunOrdinal: 1,
504 capturedAt: scope.createdAt,
505 };
506 yield* Effect.result(checkpoints.captureBaseline(baseline));
507 assert.strictEqual((yield* checkpoints.capture(turn)).status, "error");
508 assert.strictEqual(attempts, 2);
509​
510 const otherThread = { ...scope, id: CheckpointScopeId.make("checkpoint-scope:other") };
511 const skipped = yield* Effect.result(
512 checkpoints.captureBaseline({ scope: otherThread, ordinalWithinScope: 0 }),
513 );
514 assert.strictEqual(attempts, 2, "baseline retried a repeatedly timing-out workspace");
515 assert.strictEqual(skipped._tag, "Success");
516​
517 yield* Effect.result(
518 checkpoints.captureBaseline({
519 scope: { ...otherThread, cwd: "/repo/other" },
520 ordinalWithinScope: 0,
521 }),
522 );
523 assert.strictEqual(attempts, 3, "another workspace must still attempt capture");
524​
525 const failedTurn = yield* checkpoints.capture(turn);
526 assert.strictEqual(failedTurn.status, "error");
527 assert.strictEqual(attempts, 4, "post-turn capture must not back off");
528​
529 yield* checkpoints.captureBaseline(baseline);
530 assert.strictEqual(attempts, 4, "baseline retries must wait for post-turn recovery");
531 healthy = true;
532 assert.strictEqual((yield* checkpoints.capture(turn)).status, "ready");
533 assert.strictEqual(attempts, 5);
534 yield* checkpoints.captureBaseline(baseline);
535 assert.strictEqual(attempts, 6, "a successful post-turn capture must clear backoff");
536​
537 healthy = false;
538 yield* Effect.result(checkpoints.captureBaseline(baseline));
539 yield* Effect.result(checkpoints.captureBaseline(baseline));
540 yield* checkpoints.captureBaseline(baseline);
541 assert.strictEqual(attempts, 8);
542 nonTimeoutFailure = true;
543 assert.strictEqual((yield* checkpoints.capture(turn)).status, "error");
544 nonTimeoutFailure = false;
545 yield* Effect.result(checkpoints.captureBaseline(baseline));
546 assert.strictEqual(attempts, 10, "a non-timeout failure must clear backoff");
547 healthy = true;
548 yield* checkpoints.captureBaseline(baseline);
549 healthy = false;
550 yield* Effect.result(checkpoints.captureBaseline(baseline));
551 yield* Effect.result(checkpoints.captureBaseline(baseline));
552 assert.strictEqual(attempts, 13, "a successful baseline must clear the timeout streak");
553 }).pipe(Effect.provide(layerTest));
554 }),
555);
556​
557it.effect("skips post-turn captures that waited out another capture's timeout in the folder", () =>
558 Effect.gen(function* () {
559 const scopeFor = (name: string): OrchestrationV2CheckpointScope => ({
560 id: CheckpointScopeId.make(`checkpoint-scope:shared-folder:${name}`),
561 threadId: ThreadId.make(`thread:shared-folder:${name}`),
562 runId: RunId.make(`run:shared-folder:${name}:1`),
563 nodeId: NodeId.make(`node:shared-folder:${name}:1`),
564 parentScopeId: null,
565 providerThreadId: ProviderThreadId.make(`provider-thread:shared-folder:${name}`),
566 kind: "root_run",
567 ordinalWithinParent: 0,
568 advancesAppRunCount: true,
569 cwd: "/repo/shared",
570 createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
571 });
572 const attempts = yield* Ref.make(0);
573 // Outcomes for upcoming attempts; an attempt with none scripted times out.
574 const script = yield* Ref.make<ReadonlyArray<"ready" | "timeout">>([]);
575 const started = yield* Queue.unbounded<void>();
576 const layerTest = CheckpointService.layer.pipe(
577 Layer.provide(
578 Layer.mergeAll(
579 IdAllocator.layer,
580 layerNoTrackedFolders,
581 Layer.mock(CheckpointStore.CheckpointStore)({
582 isGitRepository: () => Effect.succeed(true),
583 hasCheckpointRef: () => Effect.succeed(false),
584 resolveCleanHead: () => Effect.succeed(null),
585 captureCheckpoint: ({ cwd }) =>
586 Effect.gen(function* () {
587 yield* Ref.update(attempts, (count) => count + 1);
588 yield* Queue.offer(started, undefined);
589 yield* Effect.sleep("30 seconds");
590 const [next = "timeout", ...rest] = yield* Ref.get(script);
591 yield* Ref.set(script, rest);
592 if (next === "ready") return null;
593 return yield* new VcsProcessTimeoutError({
594 operation: "GitVcsDriver.checkpoints.captureCheckpoint",
595 command: "git",
596 cwd,
597 timeoutMs: 30_000,
598 });
599 }),
600 }),
601 ),
602 ),
603 Layer.provideMerge(NodeCrypto.layer),
604 );
605 yield* Effect.gen(function* () {
606 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
607 const captureTurn = (scope: OrchestrationV2CheckpointScope) =>
608 checkpoints
609 .capture({
610 scope,
611 ordinalWithinScope: 1,
612 runId: scope.runId!,
613 nodeId: scope.nodeId!,
614 appRunOrdinal: 1,
615 capturedAt: scope.createdAt,
616 })
617 .pipe(Effect.forkChild);
618 // A baseline's short budget running out says nothing about a post-turn capture.
619 const baseline = yield* checkpoints
620 .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 })
621 .pipe(Effect.result, Effect.forkChild);
622 yield* Queue.take(started);
623 const afterBaseline = yield* captureTurn(scopeFor("after-baseline"));
624 yield* TestClock.adjust("5 seconds");
625 yield* Fiber.join(baseline);
626 yield* Queue.take(started);
627 yield* TestClock.adjust("30 seconds");
628 assert.strictEqual((yield* Fiber.join(afterBaseline)).status, "error");
629 assert.strictEqual(yield* Ref.get(attempts), 2);
630​
631 const first = yield* captureTurn(scopeFor("first"));
632 yield* Queue.take(started);
633 // Other threads in the same folder finish their turns while the first capture hangs.
634 const waiting = [
635 yield* captureTurn(scopeFor("second")),
636 yield* captureTurn(scopeFor("third")),
637 ];
638 const repository = scopeFor("repository");
639 const repositoryWaiting = yield* checkpoints
640 .captureRepository({
641 scope: repository,
642 runId: repository.runId!,
643 nodeId: repository.nodeId!,
644 ordinalWithinScope: 1,
645 capturedAt: repository.createdAt,
646 baselineCapturedAt: repository.createdAt,
647 baselineRecorded: true,
648 })
649 .pipe(Effect.forkChild);
650 // A thread's root capture first materializes its baseline, which waits on the lock too.
651 const root = scopeFor("root");
652 const rootWaiting = yield* Effect.gen(function* () {
653 const capturesBeforeLock = yield* checkpoints.capturesSoFar(root.cwd);
654 yield* checkpoints.materializeBaselineCheckpoint({
655 scope: root,
656 ordinalWithinScope: 0,
657 nodeId: root.nodeId!,
658 capturedAt: root.createdAt,
659 });
660 return yield* checkpoints.capture({
661 scope: root,
662 ordinalWithinScope: 1,
663 runId: root.runId!,
664 nodeId: root.nodeId!,
665 appRunOrdinal: 1,
666 capturedAt: root.createdAt,
667 capturesBeforeLock,
668 });
669 }).pipe(Effect.forkChild);
670 yield* TestClock.adjust("30 seconds");
671 assert.strictEqual((yield* Fiber.join(first)).status, "error");
672 // Room for every waiter to probe, so the count below is what fails without the fix.
673 yield* TestClock.adjust("120 seconds");
674 for (const fiber of waiting) {
675 assert.strictEqual((yield* Fiber.join(fiber)).status, "error");
676 }
677 const repositoryCaptured = yield* Fiber.join(repositoryWaiting);
678 assert.strictEqual(Option.getOrThrow(repositoryCaptured).checkpoint.status, "error");
679 assert.strictEqual((yield* Fiber.join(rootWaiting)).status, "error");
680 assert.strictEqual(yield* Ref.get(attempts), 3, "each waiter spent its own full timeout");
681​
682 // A capture that starts after the timeout still probes for recovery.
683 const later = yield* captureTurn(scopeFor("later"));
684 yield* TestClock.adjust("30 seconds");
685 assert.strictEqual((yield* Fiber.join(later)).status, "error");
686 assert.strictEqual(yield* Ref.get(attempts), 4);
687​
688 // A success ahead in the queue does not hide a timeout that follows it.
689 yield* Ref.set(script, ["ready", "timeout"]);
690 const recovered = yield* captureTurn(scopeFor("recovered"));
691 const relapsed = yield* captureTurn(scopeFor("relapsed"));
692 const queuedBehind = yield* captureTurn(scopeFor("queued-behind"));
693 yield* TestClock.adjust("90 seconds");
694 assert.deepEqual(
695 [
696 (yield* Fiber.join(recovered)).status,
697 (yield* Fiber.join(relapsed)).status,
698 (yield* Fiber.join(queuedBehind)).status,
699 ],
700 ["ready", "error", "error"],
701 );
702 assert.strictEqual(yield* Ref.get(attempts), 6, "the waiter probed after a later timeout");
703 }).pipe(Effect.provide(layerTest));
704 }),
705);
706​
707it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not put back", () => {
708 const targets = ["first", "second"].map((name) => ({
709 scope: { id: CheckpointScopeId.make(`checkpoint-scope:rewind:${name}`), cwd: `/repo/${name}` },
710 checkpoint: {
711 ordinalWithinScope: 1,
712 ref: CheckpointRef.make(`refs/t3/test/rewind/${name}`),
713 status: "ready" as const,
714 },
715 }));
716 const failure = new VcsProcessTimeoutError({
717 operation: "test.restore",
718 command: "git",
719 cwd: "/repo",
720 timeoutMs: 30000,
721 });
722 const preRewindRefs = new Map<string, string>();
723 const captured: Array<string> = [];
724 const existing = new Set<string>();
725 const deleted: Array<{ readonly cwd: string; readonly ref: string }> = [];
726 const layerTest = CheckpointService.layer.pipe(
727 Layer.provide(
728 Layer.mergeAll(
729 IdAllocator.layer,
730 layerNoTrackedFolders,
731 Layer.mock(CheckpointStore.CheckpointStore)({
732 hasCheckpointRef: (input) =>
733 Effect.sync(
734 () =>
735 targets.some((target) => target.checkpoint.ref === input.checkpointRef) ||
736 existing.has(input.checkpointRef),
737 ),
738 captureCheckpoint: (input) =>
739 Effect.sync(() => {
740 captured.push(input.cwd);
741 existing.add(input.checkpointRef);
742 preRewindRefs.set(input.cwd, input.checkpointRef);
743 return null;
744 }),
745 // The second folder's rewind fails, and then so does putting the first one back.
746 restoreCheckpoint: (input) =>
747 input.checkpointRef === targets[1]!.checkpoint.ref ||
748 input.checkpointRef === preRewindRefs.get("/repo/first")
749 ? Effect.fail(failure)
750 : Effect.succeed(true),
751 deleteCheckpointRefs: (input) =>
752 Effect.sync(() => {
753 for (const ref of input.checkpointRefs) {
754 existing.delete(ref);
755 deleted.push({ cwd: input.cwd, ref });
756 }
757 }),
758 }),
759 ),
760 ),
761 Layer.provideMerge(NodeCrypto.layer),
762 );
763 return Effect.gen(function* () {
764 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
765 const result = yield* Effect.result(
766 checkpoints.restore({ targets, scopes: targets.map((target) => target.scope) }),
767 );
768 assert.strictEqual(result._tag, "Failure");
769 assert.deepEqual(deleted, [{ cwd: "/repo/second", ref: preRewindRefs.get("/repo/second")! }]);
770​
771 // A retry starts from a half-restored folder; the kept snapshot is not taken again.
772 yield* Effect.result(
773 checkpoints.restore({ targets, scopes: targets.map((target) => target.scope) }),
774 );
775 assert.deepEqual(captured, ["/repo/first", "/repo/second", "/repo/second"]);
776 }).pipe(Effect.provide(layerTest));
777});