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

CheckpointService.test.ts

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