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

CheckpointDiffQuery.test.ts

471 lines17.3 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it, vi } from "@effect/vitest";
4import { CheckpointRef, CheckpointScopeId, RunId, ThreadId } from "@t3tools/contracts";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9​
10import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
11import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
12import type { ProjectionCheckpointContext } from "../orchestration-v2/ProjectionStore.ts";
13import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
14import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
15import * as VcsProcess from "../vcs/VcsProcess.ts";
16import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
17import * as CheckpointStore from "./CheckpointStore.ts";
18import {
19 CheckpointRefUnavailableError,
20 CheckpointThreadNotFoundError,
21 CheckpointTurnRangeUnavailableError,
22} from "./Errors.ts";
23​
24const threadId = ThreadId.make("thread:checkpoint-diff-v2");
25const firstRunId = RunId.make("run:checkpoint-diff-v2:1");
26const secondRunId = RunId.make("run:checkpoint-diff-v2:2");
27const firstScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:1");
28const secondScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:2");
29const secondRef = CheckpointRef.make("refs/t3/test/second");
30​
31function makeProjection(): ProjectionCheckpointContext {
32 return {
33 runs: [
34 { id: firstRunId, ordinal: 1, status: "completed" },
35 { id: secondRunId, ordinal: 2, status: "completed" },
36 ],
37 checkpointScopes: [
38 { id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo" },
39 { id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo" },
40 ],
41 checkpoints: [
42 {
43 scopeId: secondScopeId,
44 runId: secondRunId,
45 ordinalWithinScope: 1,
46 appRunOrdinal: 2,
47 status: "ready",
48 ref: secondRef,
49 },
50 ],
51 };
53​
54function layerFor(input: {
55 readonly projection: Effect.Effect<ProjectionCheckpointContext, OrchestratorProjectionError>;
56 readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"];
57 readonly authoredPaths?: ReadonlySet<string>;
58}) {
59 return CheckpointDiffQuery.layer.pipe(
60 Layer.provide(
61 Layer.mergeAll(
62 Layer.mock(ThreadManagement.ThreadManagementService)({
63 getCheckpointContext: () => input.projection,
64 }),
65 Layer.mock(CheckpointStore.CheckpointStore)({
66 diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")),
67 listAuthoredPaths: () => Effect.succeed(input.authoredPaths ?? null),
68 }),
69 ),
70 ),
71 Layer.provideMerge(NodeCrypto.layer),
72 );
74​
75it.effect("computes V2 run diffs from projected checkpoint scopes", () => {
76 const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) =>
77 Effect.succeed("diff --git a/file b/file"),
78 );
79 const layer = layerFor({ projection: Effect.succeed(makeProjection()), diffCheckpoints });
80​
81 return Effect.gen(function* () {
82 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
83 const result = yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 });
84​
85 assert.deepEqual(result, {
86 threadId,
87 fromTurnCount: 0,
88 toTurnCount: 2,
89 diff: "diff --git a/file b/file",
90 });
91 assert.containSubset(diffCheckpoints.mock.calls[0]?.[0], {
92 cwd: "/repo",
93 fromCheckpointRef: yield* checkpointRefForScopeOrdinal({
94 scopeId: firstScopeId,
95 ordinalWithinScope: 0,
96 }),
97 toCheckpointRef: secondRef,
98 fallbackFromToHead: false,
99 ignoreWhitespace: true,
100 });
101 }).pipe(Effect.provide(layer));
102});
103​
104it.effect("leaves Git imports out of large turn diffs", () => {
105 const ownPaths = Array.from({ length: 1_000 }, (_, index) => `src/module-${index}/file.ts`);
106 const diffCheckpoints = vi.fn((input: CheckpointStore.DiffCheckpointsInput) =>
107 Effect.succeed(
108 input.format === "numstat"
109 ? [...ownPaths, "upstream.ts"].map((path) => `1\t0\t${path}\0`).join("")
110 : (input.filePaths ?? ["all"]).join("\n"),
111 ),
112 );
113 const layer = layerFor({
114 projection: Effect.succeed(makeProjection()),
115 diffCheckpoints,
116 authoredPaths: new Set(ownPaths),
117 });
118​
119 return Effect.gen(function* () {
120 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
121 yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 });
122​
123 const patchPaths = diffCheckpoints.mock.calls
124 .map(([call]) => call)
125 .filter((call) => call.format !== "numstat")
126 .map((call) => call.filePaths ?? ["all"]);
127 assert.isAbove(patchPaths.length, 1);
128 assert.sameMembers(patchPaths.flat(), ownPaths);
129 }).pipe(Effect.provide(layer));
130});
131​
132it.effect("preserves the typed missing-thread error contract", () => {
133 const layer = layerFor({
134 projection: Effect.fail(new OrchestratorProjectionError({ threadId })),
135 });
136​
137 return Effect.gen(function* () {
138 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
139 const error = yield* query
140 .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 })
141 .pipe(Effect.flip);
142​
143 assert.instanceOf(error, CheckpointThreadNotFoundError);
144 assert.deepEqual(
145 { operation: error.operation, threadId: error.threadId },
146 { operation: "CheckpointDiffQuery.getTurnDiff", threadId },
147 );
148 }).pipe(Effect.provide(layer));
149});
150​
151it.effect("preserves the typed unavailable-range error contract", () => {
152 const layer = layerFor({ projection: Effect.succeed(makeProjection()) });
153​
154 return Effect.gen(function* () {
155 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
156 const error = yield* query
157 .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 3 })
158 .pipe(Effect.flip);
159​
160 assert.instanceOf(error, CheckpointTurnRangeUnavailableError);
161 assert.deepEqual(
162 {
163 requestedTurnCount: error.requestedTurnCount,
164 availableTurnCount: error.availableTurnCount,
165 },
166 { requestedTurnCount: 3, availableTurnCount: 2 },
167 );
168 }).pipe(Effect.provide(layer));
169});
170​
171it.effect("excludes ready checkpoints from rolled-back runs", () => {
172 const projection = makeProjection();
173 const layer = layerFor({
174 projection: Effect.succeed({
175 ...projection,
176 runs: projection.runs.map((run) =>
177 run.id === secondRunId ? { ...run, status: "rolled_back" as const } : run,
178 ),
179 checkpoints: [
180 {
181 ...projection.checkpoints[0]!,
182 scopeId: firstScopeId,
183 runId: firstRunId,
184 appRunOrdinal: 1,
185 ref: CheckpointRef.make("refs/t3/test/first"),
186 },
187 ...projection.checkpoints,
188 ],
189 }),
190 });
191​
192 return Effect.gen(function* () {
193 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
194 const error = yield* query
195 .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 })
196 .pipe(Effect.flip);
197​
198 assert.instanceOf(error, CheckpointTurnRangeUnavailableError);
199 assert.deepEqual(
200 {
201 requestedTurnCount: error.requestedTurnCount,
202 availableTurnCount: error.availableTurnCount,
203 },
204 { requestedTurnCount: 2, availableTurnCount: 1 },
205 );
206 }).pipe(Effect.provide(layer));
207});
208​
209function makeProjectionAfterStoppedRun(stoppedRunCheckpoint: boolean) {
210 const thirdRunId = RunId.make("run:checkpoint-diff-v2:3");
211 const checkpoint = (
212 ordinalWithinScope: number,
213 runId: RunId | null,
214 ): ProjectionCheckpointContext["checkpoints"][number] => ({
215 scopeId: firstScopeId,
216 runId,
217 ordinalWithinScope,
218 appRunOrdinal: runId === null ? null : ordinalWithinScope,
219 status: "ready",
220 ref: CheckpointRef.make(`refs/t3/test/ordinal/${ordinalWithinScope}`),
221 });
222 return {
223 runs: [
224 { id: firstRunId, ordinal: 1, status: "completed" },
225 { id: secondRunId, ordinal: 2, status: "interrupted" },
226 { id: thirdRunId, ordinal: 3, status: "completed" },
227 ],
228 checkpointScopes: [
229 { id: firstScopeId, runId: thirdRunId, kind: "root_run", cwd: "/repo" },
230 { id: secondScopeId, runId: secondRunId, kind: "tool", cwd: "/repo" },
231 ],
232 checkpoints: [
233 {
234 ...checkpoint(2, null),
235 scopeId: secondScopeId,
236 ref: CheckpointRef.make("refs/t3/test/tool/2"),
237 },
238 checkpoint(0, null),
239 checkpoint(1, firstRunId),
240 checkpoint(2, stoppedRunCheckpoint ? secondRunId : null),
241 checkpoint(3, thirdRunId),
242 ],
243 } satisfies ProjectionCheckpointContext;
245​
246it.effect.each([false, true])(
247 "diffs the turn after a stopped run from its parent checkpoint (stopped run captured: %s)",
248 (stoppedRunCheckpoint) => {
249 const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) =>
250 Effect.succeed("diff --git a/file b/file"),
251 );
252 const layer = layerFor({
253 projection: Effect.succeed(makeProjectionAfterStoppedRun(stoppedRunCheckpoint)),
254 diffCheckpoints,
255 });
256​
257 return Effect.gen(function* () {
258 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
259 const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 2, toTurnCount: 3 });
260​
261 assert.strictEqual(result.diff, "diff --git a/file b/file");
262 yield* query.getTurnDiff({ threadId, fromTurnCount: 1, toTurnCount: 3 });
263 yield* query.getFullThreadDiff({ threadId, toTurnCount: 3 });
264 assert.deepEqual(
265 diffCheckpoints.mock.calls.map(([input]) => ({
266 from: input.fromCheckpointRef,
267 to: input.toCheckpointRef,
268 })),
269 [
270 { from: "refs/t3/test/ordinal/2", to: "refs/t3/test/ordinal/3" },
271 { from: "refs/t3/test/ordinal/1", to: "refs/t3/test/ordinal/3" },
272 {
273 from: yield* checkpointRefForScopeOrdinal({
274 scopeId: firstScopeId,
275 ordinalWithinScope: 0,
276 }),
277 to: "refs/t3/test/ordinal/3",
278 },
279 ],
280 );
281 const stoppedTurnError = yield* query
282 .getTurnDiff({ threadId, fromTurnCount: 1, toTurnCount: 2 })
283 .pipe(Effect.flip);
284 assert.instanceOf(stoppedTurnError, CheckpointRefUnavailableError);
285 assert.deepEqual(
286 { checkpoint: stoppedTurnError.checkpoint, turnCount: stoppedTurnError.turnCount },
287 { checkpoint: "to", turnCount: 2 },
288 );
289 }).pipe(Effect.provide(layer));
290 },
291);
292​
293it.effect("preserves the typed missing-baseline-ref error contract", () => {
294 const projection = makeProjection();
295 const layer = layerFor({
296 projection: Effect.succeed({
297 ...projection,
298 checkpointScopes: projection.checkpointScopes.map((scope) => ({
299 ...scope,
300 kind: "tool" as const,
301 })),
302 }),
303 });
304​
305 return Effect.gen(function* () {
306 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
307 const error = yield* query
308 .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 })
309 .pipe(Effect.flip);
310​
311 assert.instanceOf(error, CheckpointRefUnavailableError);
312 assert.deepEqual(
313 { checkpoint: error.checkpoint, turnCount: error.turnCount },
314 { checkpoint: "from", turnCount: 0 },
315 );
316 }).pipe(Effect.provide(layer));
317});
318​
319const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
320const layerStore = CheckpointStore.layer.pipe(
321 Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))),
322 Layer.provide(NodeServices.layer),
323);
324const layerTest = Layer.merge(layerStore, layerVcsProcess).pipe(
325 Layer.provideMerge(NodeServices.layer),
326 Layer.provideMerge(NodeCrypto.layer),
327);
328​
329it.effect("shares the turn and full-thread diff budget across real Git batches", () =>
330 Effect.gen(function* () {
331 const fs = yield* FileSystem.FileSystem;
332 const path = yield* Path.Path;
333 const process = yield* VcsProcess.VcsProcess;
334 const store = yield* CheckpointStore.CheckpointStore;
335 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-diff-aggregate-" });
336 const git = (args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
337 process.run({
338 operation: "CheckpointDiffQuery.test.git",
339 command: "git",
340 cwd,
341 args,
342 ...(env === undefined ? {} : { env }),
343 });
344 yield* git(["init"]);
345 yield* git(["config", "user.email", "test@test.com"]);
346 yield* git(["config", "user.name", "Test"]);
347 yield* fs.writeFileString(path.join(cwd, "README.md"), "initial\n");
348 yield* git(["add", "."]);
349 yield* git(["commit", "-m", "initial"]);
350​
351 const threadId = ThreadId.make("thread:aggregate-runtime");
352 const runId = RunId.make("run:aggregate-runtime");
353 const scopeId = CheckpointScopeId.make("scope:aggregate-runtime");
354 const fromCheckpointRef = yield* checkpointRefForScopeOrdinal({
355 scopeId,
356 ordinalWithinScope: 0,
357 });
358 const toCheckpointRef = CheckpointRef.make("refs/t3/test/aggregate-after");
359 yield* store.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef });
360 // The old commit models files imported by a pull after the baseline was captured.
361 yield* fs.writeFileString(path.join(cwd, "upstream.ts"), "imported\n");
362 yield* git(["add", "."]);
363 yield* git(["commit", "-m", "imported"], {
364 ...globalThis.process.env,
365 GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z",
366 });
367 const ownPaths = Array.from({ length: 1_600 }, (_, index) => `src/module-${index}/file.ts`);
368 yield* Effect.forEach(
369 ownPaths,
370 (file) =>
371 Effect.gen(function* () {
372 yield* fs.makeDirectory(path.dirname(path.join(cwd, file)), { recursive: true });
373 yield* fs.writeFileString(path.join(cwd, file), `${"x".repeat(12_000)}\n`);
374 }),
375 { concurrency: 16, discard: true },
376 );
377 yield* store.captureCheckpoint({ cwd, checkpointRef: toCheckpointRef });
378​
379 const patchSizes: number[] = [];
380 const query = yield* CheckpointDiffQuery.make.pipe(
381 Effect.provide(
382 Layer.mock(ThreadManagement.ThreadManagementService)({
383 getCheckpointContext: () =>
384 Effect.succeed({
385 runs: [{ id: runId, ordinal: 1, status: "completed" }],
386 checkpointScopes: [{ id: scopeId, runId, kind: "root_run", cwd }],
387 checkpoints: [
388 {
389 scopeId,
390 runId,
391 ordinalWithinScope: 1,
392 appRunOrdinal: 1,
393 status: "ready",
394 ref: toCheckpointRef,
395 },
396 ],
397 }),
398 }),
399 ),
400 Effect.provideService(CheckpointStore.CheckpointStore, {
401 ...store,
402 diffCheckpoints: (input) =>
403 store.diffCheckpoints(input).pipe(
404 Effect.tap((patch) =>
405 Effect.sync(() => {
406 if (input.format !== "numstat") {
407 patchSizes.push(Buffer.byteLength(patch));
408 }
409 }),
410 ),
411 ),
412 }),
413 );
414 const turn = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 });
415 const turnPatchSizes = patchSizes.splice(0);
416 const fullThread = yield* query.getFullThreadDiff({ threadId, toTurnCount: 1 });
417 assert.isTrue(fullThread.diff === turn.diff);
418 assert.isAtMost(Buffer.byteLength(turn.diff), 10_000_000);
419 assert.isTrue(turn.diff.endsWith("\n\n[truncated]"));
420 assert.include(turn.diff, "src/module-0/file.ts");
421 assert.notInclude(turn.diff, "upstream.ts");
422 assert.lengthOf(turnPatchSizes, 2);
423 assert.deepEqual(patchSizes, turnPatchSizes);
424 assert.isBelow(turnPatchSizes[0]!, 10_000_000);
425 assert.strictEqual(
426 turnPatchSizes.reduce((sum, size) => sum + size, 0),
427 10_000_001,
428 );
429 }).pipe(Effect.provide(layerTest), Effect.scoped),
430);
431​
432it.effect("truncates a storage-cut UTF-8 character without replacement text", () => {
433 const prefix = "x".repeat(9_999_985);
434 const layer = layerFor({
435 projection: Effect.succeed(makeProjection()),
436 diffCheckpoints: (input) =>
437 Effect.succeed(
438 Buffer.from(`${prefix}😀${"x".repeat(9)}😀tail`)
439 .subarray(0, input.maxOutputBytes)
440 .toString("utf8"),
441 ),
442 });
443 return Effect.gen(function* () {
444 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
445 const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 });
446 assert.isAtMost(Buffer.byteLength(result.diff), 10_000_000);
447 assert.isTrue(result.diff === `${prefix}\n\n[truncated]`);
448 }).pipe(Effect.provide(layer));
449});
450​
451it.effect("preserves an exact-fit filtered patch across batches without a marker", () => {
452 const ownPaths = Array.from({ length: 1_000 }, (_, index) => `src/module-${index}/file.ts`);
453 const patches = ["é".repeat(3_000_000), "x".repeat(4_000_000)];
454 let patchReads = 0;
455 const layer = layerFor({
456 projection: Effect.succeed(makeProjection()),
457 authoredPaths: new Set(ownPaths),
458 diffCheckpoints: (input) =>
459 Effect.sync(() =>
460 input.format === "numstat"
461 ? [...ownPaths, "upstream.ts"].map((path) => `1\t0\t${path}\0`).join("")
462 : patches[patchReads++]!,
463 ),
464 });
465 return Effect.gen(function* () {
466 const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
467 const result = yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 });
468 assert.isTrue(result.diff === patches.join(""));
469 assert.strictEqual(patchReads, 2);
470 }).pipe(Effect.provide(layer));
471});