- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/test/projection-atom-adoption.test.ts?format=json
327 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 146, 1 version changed it
1import assert from "node:assert/strict";
2import { createHash } from "node:crypto";
3import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { test } from "node:test";
7import { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts";
8import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts";
9import { adoptMovesStep } from "../experimental/projection-move-adoption.ts";
10import { Graph } from "../graph.ts";
11import { CachedStateStorage } from "../state-source.ts";
12import { Repo } from "./helpers.ts";
13import { SqlState } from "./storage-helper.ts";
15test("an unfinished atom resumes after closing and reopening its SQLite database", () => {
16 const directory = mkdtempSync(join(tmpdir(), "abso-atom-adoption-"));
17 const filename = join(directory, "state.sqlite");
18 let db = new SqlState(filename);
19 try {
20 const repo = Repo.init({ "a.txt": "one\ntwo\nthree\nfour\n" });
21 const atom = repo.graph.atom("a0");
22 new Graph({ storage: db }).add(atom);
23 const previous = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart").empty();
24 let done = false,
25 pages = 0;
26 while (!done) {
27 const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart");
28 const result = new ProjectionAtomAdoption(adapter, "initial").page({
29 previous,
30 atom,
31 remove: false,
32 source: "d".repeat(64),
33 maxSteps: 2,
34 validateSource: () => {},
35 });
36 assert.ok(result.steps <= 2);
37 done = result.done;
38 if (done)
39 assert.deepEqual(
40 adapter.lines(result.state),
41 repo
42 .view()
43 .lines("a.txt")
44 .map((line) => line.id),
45 );
46 assert.ok(++pages < 50);
47 db.db.close();
48 db = new SqlState(filename);
49 }
50 assert.ok(pages > 5);
51 } finally {
52 db.db.close();
53 unlinkSync(filename);
54 rmdirSync(directory);
55 }
56});
58test("atom adoption resumes small pages and matches atomic additions and reverse removals", () => {
59 const db = new SqlState();
60 try {
61 const repo = Repo.init({
62 "a.txt": Array.from({ length: 40 }, (_, i) => `line ${i}\n`).join(""),
63 "b.txt": "other\n",
64 });
65 const graph = new Graph({ storage: new CachedStateStorage(db) });
66 const atoms = [repo.graph.atom("a0")];
67 atoms.push(
68 repo.edit({
69 edits: [{ file: "a.txt", old: repo.view().text("a.txt"), new: "replacement\n" }],
70 attrs: [{ file: "b.txt", name: "exec", value: "1" }],
71 }),
72 );
73 atoms.push(repo.edit({ move: { file: "a.txt", start: 0, end: 1, to: "b.txt", at: 0 } }));
74 for (const atom of atoms) graph.add(atom);
75 const adapter = () => new ExperimentalMarkerProjection(db, graph, "a.txt", "paged");
76 const oracle = new ExperimentalMarkerProjection(db, graph, "a.txt", "atomic");
77 let state = adapter().empty(),
78 expected = oracle.empty(),
79 task = 0;
80 for (const [atom, remove] of [
81 ...atoms.map((a) => [a, false] as const),
82 ...atoms.toReversed().map((a) => [a, true] as const),
83 ]) {
84 const previous = state,
85 id = String(task++);
86 let done = false,
87 pages = 0,
88 atomicMovePages = 0;
89 while (!done) {
90 const result = new ProjectionAtomAdoption(adapter(), id).page({
91 previous,
92 atom,
93 remove,
94 source: "a".repeat(64),
95 maxSteps: 3,
96 validateSource: () => {},
97 });
98 assert.ok(result.steps <= 3);
99 if (result.atomicMoveWork) atomicMovePages++;
100 state = result.state;
101 done = result.done;
102 assert.ok(++pages < 200);
103 }
104 assert.ok(pages > 1);
105 assert.equal(atomicMovePages, 0);
106 assert.equal(
107 db.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?").get("%move-adoption:%")!.n,
108 0,
109 );
110 expected = remove ? oracle.removeAtom(expected, atom) : oracle.apply(expected, atom);
111 for (const path of ["a.txt", "b.txt"]) {
112 assert.deepEqual(adapter().lines(state, path), oracle.lines(expected, path));
113 assert.deepEqual(adapter().attrs(state, path), oracle.attrs(expected, path));
114 }
115 assert.deepEqual(adapter().knownPaths(state), oracle.knownPaths(expected));
116 }
117 } finally {
118 db.db.close();
119 }
120});
122test("source drift rolls back an atom page and a changed atom cannot resume its cursor", () => {
123 const db = new SqlState();
124 try {
125 const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n" });
126 const graph = new Graph({ storage: db });
127 const atom = repo.graph.atom("a0");
128 graph.add(atom);
129 const adapter = new ExperimentalMarkerProjection(db, graph, "a.txt", "failure");
130 const job = new ProjectionAtomAdoption(adapter, "one");
131 const input = {
132 previous: adapter.empty(),
133 atom,
134 remove: false,
135 source: "b".repeat(64),
136 maxSteps: 3,
137 validateSource: () => {},
138 };
139 job.page(input);
140 const rows = () => db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
141 const before = rows();
142 const saved = adapter.storage.read("atom-adoption:one", "cursor") as {
143 format: number;
144 checksum: string;
145 cursor: { index: number; run: number; phase: string; state: { sequence: { next: number } } };
146 };
147 for (const field of ["checksum", "index", "run", "sequence", "phase"]) {
148 const damaged = structuredClone(saved);
149 if (field === "checksum") damaged.checksum = "bad";
150 else {
151 if (field === "index") damaged.cursor.index = Number.MAX_SAFE_INTEGER;
152 if (field === "run") damaged.cursor.run = atom.inserts.length + 1;
153 if (field === "sequence") damaged.cursor.state.sequence.next = -1;
154 if (field === "phase") damaged.cursor.phase = "unknown";
155 damaged.checksum = createHash("sha256").update(JSON.stringify(damaged.cursor)).digest("hex");
156 }
157 adapter.storage.write("atom-adoption:one", "cursor", damaged);
158 const corruptRows = rows();
159 assert.throws(() => job.page(input), /invalid|damaged/, field);
160 assert.deepEqual(rows(), corruptRows, field);
161 adapter.storage.write("atom-adoption:one", "cursor", saved);
162 }
163 assert.deepEqual(rows(), before);
164 assert.throws(() => job.page({ ...input, validateSource: () => Promise.resolve() }), /must be synchronous/);
165 assert.deepEqual(rows(), before);
166 let asyncChecks = 0;
167 assert.throws(
168 () => job.page({ ...input, validateSource: () => (++asyncChecks === 2 ? Promise.resolve() : undefined) }),
169 /must be synchronous/,
170 );
171 assert.deepEqual(rows(), before);
172 let checks = 0;
173 assert.throws(
174 () =>
175 job.page({
176 ...input,
177 validateSource: () => {
178 if (++checks === 2) throw Error("source drift");
179 },
180 }),
181 /source drift/,
182 );
183 assert.deepEqual(rows(), before);
184 assert.throws(
185 () => job.page({ ...input, atom: { ...atom, message: "changed" } }),
186 /canonical adoption atom mismatch/,
187 );
188 assert.deepEqual(rows(), before);
189 assert.throws(() => job.page({ ...input, source: "c".repeat(64) }), /changed atom adoption cursor/);
190 assert.deepEqual(rows(), before);
191 assert.equal(job.page(input).steps, 3);
192 } finally {
193 db.db.close();
194 }
195});
197test("move adoption rolls back complete pages and resumes every phase after SQLite reopen", () => {
198 const directory = mkdtempSync(join(tmpdir(), "abso-move-restart-"));
199 const filename = join(directory, "state.sqlite");
200 let db = new SqlState(filename);
201 try {
202 const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n", "b.txt": "other\n" });
203 const initial = repo.graph.atom("a0");
204 const move = repo.edit({ move: { file: "a.txt", start: 0, end: 2, to: "b.txt", at: 1 } });
205 const graph = new Graph({ storage: db });
206 graph.add(initial);
207 graph.add(move);
208 const first = new ExperimentalMarkerProjection(db, graph, "a.txt", "restart-moves");
209 let state = first.apply(first.empty(), initial);
210 const phases = new Set<string>();
211 for (const remove of [false, true]) {
212 const previous = state;
213 let done = false,
214 pages = 0;
215 while (!done) {
216 const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart-moves");
217 const job = new ProjectionAtomAdoption(adapter, remove ? "remove" : "add");
218 const input = { previous, atom: move, remove, source: "f".repeat(64), maxSteps: 1, validateSource: () => {} };
219 const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
220 let validations = 0;
221 assert.throws(
222 () =>
223 job.page({
224 ...input,
225 validateSource: () => {
226 if (++validations === 2) throw Error("source changed after page");
227 },
228 }),
229 /source changed after page/,
230 );
231 assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
232 const result = job.page(input);
233 state = result.state;
234 done = result.done;
235 assert.equal(result.atomicMoveWork, false);
236 assert.ok(result.steps <= 1);
237 const saved = adapter.storage.read(`move-adoption:${remove ? "remove" : "add"}`, "cursor") as
238 | { cursor: { phase: string } }
239 | undefined;
240 if (saved) phases.add(saved.cursor.phase);
241 assert.ok(++pages < 300);
242 db.db.close();
243 db = new SqlState(filename);
244 }
245 const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart-moves");
246 const oracle = new ExperimentalMarkerProjection(
247 db,
248 new Graph({ storage: db }),
249 "a.txt",
250 remove ? "oracle-remove" : "oracle-add",
251 );
252 let expected = oracle.apply(oracle.empty(), initial);
253 if (!remove) expected = oracle.apply(expected, move);
254 for (const path of ["a.txt", "b.txt"]) assert.deepEqual(adapter.lines(state, path), oracle.lines(expected, path));
255 assert.equal(
256 db.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?").get("%move-adoption:%")!.n,
257 0,
258 );
259 }
260 for (const phase of ["files", "resolve", "plans", "park", "place", "cleanup"]) assert.ok(phases.has(phase), phase);
261 } finally {
262 db.db.close();
263 unlinkSync(filename);
264 rmdirSync(directory);
265 }
266});
268test("move application rejects damaged cursor envelopes and invalid positions without mutation", () => {
269 const db = new SqlState();
270 try {
271 const repo = Repo.init({ "a.txt": "one\ntwo\n" });
272 const adapter = new ExperimentalMarkerProjection(db, repo.graph, "a.txt", "corrupt-move");
273 const state = adapter.apply(adapter.empty(), repo.graph.atom("a0"));
274 const identity = "e".repeat(64);
275 adoptMovesStep(adapter, state, "job", identity);
276 const saved = adapter.storage.read("move-adoption:job", "cursor") as {
277 format: number;
278 checksum: string;
279 cursor: Record<string, unknown>;
280 };
281 const changes: Array<(record: typeof saved) => void> = [
282 (row) => {
283 row.checksum = "bad";
284 },
285 (row) => {
286 row.format = 2;
287 },
288 (row) => {
289 row.cursor.phase = "unknown";
290 },
291 (row) => {
292 row.cursor.identity = "another";
293 },
294 (row) => {
295 row.cursor.mover = 1;
296 },
297 (row) => {
298 row.cursor.move = 1;
299 },
300 (row) => {
301 row.cursor.count = repo.graph.lineCount + 1;
302 },
303 (row) => {
304 row.cursor.item = 1;
305 },
306 (row) => {
307 row.cursor.collection = 9;
308 },
309 (row) => {
310 row.cursor.extra = true;
311 },
312 ];
313 for (const [index, change] of changes.entries()) {
314 const bad = structuredClone(saved);
315 change(bad);
316 if (index > 0) bad.checksum = createHash("sha256").update(JSON.stringify(bad.cursor)).digest("hex");
317 adapter.storage.write("move-adoption:job", "cursor", bad);
318 const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
319 assert.throws(() => adoptMovesStep(adapter, state, "job", identity), /invalid|damaged/);
320 assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
321 }
322 adapter.storage.write("move-adoption:job", "cursor", saved);
323 assert.equal(adoptMovesStep(adapter, state, "job", identity).done, false);
324 } finally {
325 db.db.close();
326 }
327});