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

CheckpointDiffQuery.test.ts

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