- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/test/properties.test.ts?format=json
354 linesFirst import 99% · pinch 1%Last change pinch in version 78, 2 versions changed it
1// Property tests over random edit histories (docs/prototype.md, "Property tests").
2// Seeded: a failure prints its seed; rerun one case with
3// PROP_SEED=<seed> PROP_CASES=1 node --test src/engine/test/properties.test.ts
5import assert from "node:assert/strict";
6import { describe, it } from "node:test";
7import {
8 type AtomId,
9 type AtomInput,
10 buildAtom,
11 type Conflict,
12 checkDraft,
13 conflicts,
14 type DraftReport,
15 Graph,
16 isStartNode,
17 unresolvedConflicts,
18 View,
19 writerOf,
20} from "../index.ts";
21import { EditGen, type Files, filesFromView, filesToRecord, sameFiles } from "./gen.ts";
22import { Repo, Rng } from "./helpers.ts";
24const BASE_SEED = Number(process.env.PROP_SEED ?? 20260621);
25const CASES = Number(process.env.PROP_CASES ?? 250);
27/** Run `body` once per seed; on failure report the seed and the steps taken. */
28export function forCases(name: string, body: (rng: Rng, log: string[]) => void): void {
29 for (let c = 0; c < CASES; c++) {
30 const seed = BASE_SEED + c;
31 const log: string[] = [];
32 try {
33 body(new Rng(seed), log);
34 } catch (err) {
35 const detail = err instanceof Error ? err.message : String(err);
36 assert.fail(
37 `${name} failed at seed ${seed} (rerun: PROP_SEED=${seed} PROP_CASES=1)\nsteps:\n ${log.join("\n ")}\n${detail}`,
38 );
39 }
40 }
41}
43interface SimOptions {
44 readonly duplicates: boolean;
45 /** Allow wide mode and reliesOn (explicit holds). */
46 readonly holds: boolean;
47 /** Probability that an atom is written against an older snapshot instead of the shared set. */
48 readonly pinned: number;
49}
51/**
52 * A random history: each step builds one atom and accepts it into the shared
53 * set. Unpinned atoms are written against the full current projection and
54 * also applied to a plain-text model (`plain`), which stays the ground truth
55 * as long as no pinned atom has been accepted.
56 */
57class Sim {
58 readonly rng: Rng;
59 readonly log: string[];
60 readonly opts: SimOptions;
61 readonly gen: EditGen;
62 readonly repo: Repo;
63 plain: Files;
64 plainIsTruth = true;
65 snapshots: Set<AtomId>[] = [];
66 /** The set each accepted atom was written against. */
67 viewOf = new Map<AtomId, ReadonlySet<AtomId>>();
68 /** The plain-text result of each atom's edit applied to the projection of its view. */
69 expected = new Map<AtomId, Record<string, string>>();
70 #time = 1;
72 constructor(rng: Rng, log: string[], opts: SimOptions) {
73 this.rng = rng;
74 this.log = log;
75 this.opts = opts;
76 this.gen = new EditGen(rng, { duplicates: opts.duplicates, wide: opts.holds });
77 const initial = this.gen.initialFiles();
78 this.repo = Repo.init(filesToRecord(initial));
79 this.plain = new Map([...initial].filter(([, lines]) => lines.length > 0));
80 this.snapshots.push(new Set(this.repo.shared));
81 log.push(`a0: ${JSON.stringify(filesToRecord(initial))}`);
82 }
84 /** One step. Returns the draft report of the accepted atom, or undefined if the step was skipped. */
85 step(): DraftReport | undefined {
86 const pinned = this.opts.pinned > 0 && this.snapshots.length > 1 && this.rng.chance(this.opts.pinned);
87 const against = pinned ? this.rng.pick(this.snapshots) : this.repo.shared;
88 const view = this.repo.view(against);
89 const files = pinned ? filesFromView(view) : this.plain;
90 const gen = this.gen.next(files, view);
91 if (!gen) return undefined;
92 const next = gen.apply(files);
93 if (sameFiles(next, files)) return undefined;
94 const reliance = this.opts.holds && this.rng.chance(0.25) ? this.gen.reliance(files) : undefined;
95 const input: AtomInput = {
96 author: `agent${this.rng.int(3)}`,
97 message: gen.describe,
98 time: this.#time++,
99 edits: gen.edits,
100 ...(reliance ? { reliesOn: [reliance] } : {}),
101 };
102 const draft = buildAtom(view, input);
103 this.log.push(
104 `${draft.id}${pinned ? ` [against {${[...against].join(",")}}]` : ""}: ${gen.describe}` +
105 (reliance ? ` reliesOn ${reliance.file}[${reliance.start},${reliance.end})` : ""),
106 );
107 const report = checkDraft(this.repo.graph, this.repo.shared, draft);
108 this.viewOf.set(draft.id, new Set(against));
109 this.expected.set(draft.id, filesToRecord(next));
110 this.repo.graph.add(draft);
111 this.repo.shared.add(draft.id);
112 this.snapshots.push(new Set(this.repo.shared));
113 if (pinned) this.plainIsTruth = false;
114 this.plain = pinned ? filesFromView(this.repo.view()) : next;
115 return report;
116 }
117}
119describe("property: ground truth", () => {
120 it("edits applied one after another to the projection match plain-text editing", () => {
121 forCases("ground truth", (rng, log) => {
122 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: rng.chance(0.5), pinned: 0 });
123 const steps = rng.range(5, 30);
124 for (let s = 0; s < steps; s++) {
125 sim.step();
126 assert.deepEqual(sim.repo.files(), filesToRecord(sim.plain));
127 }
128 });
129 });
130});
132describe("property: no false conflicts", () => {
133 it("atoms written against the full current projection without explicit holds never conflict", () => {
134 forCases("no false conflicts", (rng, log) => {
135 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: false, pinned: 0 });
136 const steps = rng.range(5, 30);
137 for (let s = 0; s < steps; s++) {
138 const report = sim.step();
139 if (report) assert.deepEqual(report.conflicts, [], "the live check reported a conflict");
140 assert.deepEqual(conflicts(sim.repo.graph, sim.repo.shared), []);
141 }
142 });
143 });
144});
146describe("property: order independence", () => {
147 it("projecting the same set from shuffled atom lists gives identical files and sequences", () => {
148 forCases("order independence", (rng, log) => {
149 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: rng.chance(0.5), pinned: 0.35 });
150 const steps = rng.range(5, 25);
151 for (let s = 0; s < steps; s++) sim.step();
152 const graph = sim.repo.graph;
153 const reference = new View(graph, sim.repo.shared);
154 const sequences = (v: View) =>
155 v.knownPaths().map((p) => [p, v.sequence(p).map((l) => `${l.id}${l.visible ? "" : "-"}`)]);
156 for (let k = 0; k < 3; k++) {
157 const shuffled = new View(graph, rng.shuffle([...sim.repo.shared]));
158 assert.deepEqual(shuffled.files(), reference.files());
159 assert.deepEqual(sequences(shuffled), sequences(reference));
160 }
161 // A graph reloaded from JSON projects the same.
162 const reloaded = Graph.fromJSON(JSON.parse(JSON.stringify(graph)));
163 assert.deepEqual(new View(reloaded, rng.shuffle([...sim.repo.shared])).files(), reference.files());
164 });
165 });
166});
168describe("property: subset consistency", () => {
169 it("an atom's closure keeps the full set's line order and every visible line it wrote", () => {
170 forCases("subset consistency", (rng, log) => {
171 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: rng.chance(0.5), pinned: 0.35 });
172 const steps = rng.range(5, 25);
173 for (let s = 0; s < steps; s++) sim.step();
174 const graph = sim.repo.graph;
175 const full = new View(graph, sim.repo.shared);
176 const atoms = rng.shuffle([...sim.repo.shared]).slice(0, 10);
177 for (const atom of atoms) {
178 const inside = graph.closure(atom);
179 const sub = new View(graph, inside);
180 for (const path of full.knownPaths()) {
181 const fullSeq = full.sequence(path).map((l) => l.id);
182 // The closure's sequence is the full sequence restricted to lines written inside the closure.
183 assert.deepEqual(
184 sub.sequence(path).map((l) => l.id),
185 fullSeq.filter((id) => inside.has(writerOf(id))),
186 `sequence of ${path} under closure(${atom})`,
187 );
188 // The spec's two conditions, stated directly on visible lines.
189 const subVisible = sub.lines(path).map((l) => l.id);
190 const subSet = new Set(subVisible);
191 const fullVisible = full.lines(path).map((l) => l.id);
192 for (const id of fullVisible) {
193 if (inside.has(writerOf(id)))
194 assert.ok(subSet.has(id), `${id} is visible in the full set but missing under closure(${atom})`);
195 }
196 const fullSet = new Set(fullVisible);
197 assert.deepEqual(
198 fullVisible.filter((id) => subSet.has(id)),
199 subVisible.filter((id) => fullSet.has(id)),
200 `relative order of ${path} under closure(${atom})`,
201 );
202 }
203 }
204 });
205 });
206});
208describe("property: placement", () => {
209 it("each atom, added to the set it was written against, is exactly its plain-text edit, and in its closure each run sits right after its parent", () => {
210 forCases("placement", (rng, log) => {
211 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: rng.chance(0.5), pinned: 0.35 });
212 const steps = rng.range(5, 25);
213 for (let s = 0; s < steps; s++) sim.step();
214 const graph = sim.repo.graph;
215 for (const [id, against] of sim.viewOf) {
216 const atom = graph.atom(id);
217 const result = new View(graph, [...against, id]);
218 assert.deepEqual(result.files(), sim.expected.get(id), `${id} against {${[...against].join(",")}}`);
219 // The run outranks every other line hanging off its parent there, so it
220 // comes right after the parent (the first run per parent, when an atom
221 // inserts twice after one line).
222 for (const view of [result, new View(graph, graph.closure(id))]) {
223 const seenParents = new Set<string>();
224 let k = 0;
225 for (const run of atom.inserts) {
226 const first = `${id}.${k}`;
227 k += run.lines.length;
228 if (seenParents.has(run.parent)) continue;
229 seenParents.add(run.parent);
230 const parentAt = isStartNode(run.parent) ? -1 : view.sequenceIndex(run.file, run.parent);
231 assert.equal(view.sequenceIndex(run.file, first), parentAt + 1, `${first} right after ${run.parent}`);
232 }
233 }
234 }
235 });
236 });
237});
239describe("property: live holds", () => {
240 it("written against the full projection, the collisions are exactly the edits into holds of atoms they do not name", () => {
241 let reported = 0;
242 forCases("live holds", (rng, log) => {
243 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: true, pinned: 0 });
244 const steps = rng.range(5, 30);
245 for (let s = 0; s < steps; s++) {
246 const report = sim.step();
247 if (!report) continue;
248 const graph = sim.repo.graph;
249 const draft = graph.atoms()[graph.size - 1]!;
250 // Every earlier holder of a key the draft writes, and only those.
251 const expected = new Map<AtomId, string[]>();
252 for (const key of draft.writes) {
253 for (const holder of graph.holdersOf(key)) {
254 if (holder === draft.id || draft.needs.includes(holder)) continue;
255 expected.set(holder, [...(expected.get(holder) ?? []), key]);
256 }
257 }
258 assert.deepEqual(
259 report.conflicts.map((c) => [c.atoms[0], c.keys.map((k) => k.key)]),
260 [...expected]
261 .sort((p, q) => graph.atom(p[0]).seq - graph.atom(q[0]).seq)
262 .map(([h, keys]) => [h, keys.sort()]),
263 `holds written by ${draft.id}`,
264 );
265 reported += report.conflicts.length;
266 for (const c of report.conflicts) {
267 assert.equal(c.kind, "semantic");
268 for (const key of c.keys) {
269 assert.equal(key.writer, c.atoms[1], `${key.key}: the draft must be the writer`);
270 assert.equal(key.relation, "hold");
271 }
272 }
273 }
274 for (const c of conflicts(sim.repo.graph, sim.repo.shared)) {
275 assert.equal(c.kind, "semantic", `${c.atoms.join(" vs ")}`);
276 for (const key of c.keys) {
277 assert.equal(
278 key.writer,
279 c.atoms[1],
280 `${c.atoms.join(" vs ")} on ${key.key}: the later atom must be the writer`,
281 );
282 assert.equal(key.relation, "hold");
283 }
284 }
285 });
286 if (CASES >= 100) assert.ok(reported > CASES / 4, `only ${reported} live collisions were checked`);
287 });
288});
290// Conflicted sets are the normal state after plain-git ingest or pinned
291// views, and agents keep editing live on top of them.
292describe("property: live edits on a conflicted set", () => {
293 it("still match plain-text editing of the projection and never collide", () => {
294 let onConflicted = 0;
295 forCases("live on conflicted", (rng, log) => {
296 const gen = new EditGen(rng, { duplicates: rng.chance(0.5), wide: false });
297 const initial = gen.initialFiles();
298 const repo = Repo.init(filesToRecord(initial));
299 log.push(`a0: ${JSON.stringify(filesToRecord(initial))}`);
300 const snapshots: Set<AtomId>[] = [new Set(repo.shared)];
301 const steps = rng.range(8, 30);
302 for (let s = 0; s < steps; s++) {
303 const pinned = snapshots.length > 1 && rng.chance(0.35);
304 const against = pinned ? rng.pick(snapshots) : repo.shared;
305 const view = repo.view(against);
306 const files = filesFromView(view);
307 const g = gen.next(files, view);
308 if (!g) continue;
309 const next = g.apply(files);
310 if (sameFiles(next, files)) continue;
311 const draft = buildAtom(view, { author: `agent${rng.int(3)}`, message: g.describe, edits: g.edits });
312 log.push(`${draft.id}${pinned ? ` [against {${[...against].join(",")}}]` : ""}: ${g.describe}`);
313 if (!pinned) {
314 if (unresolvedConflicts(repo.graph, repo.shared).length > 0) onConflicted++;
315 assert.deepEqual(checkDraft(repo.graph, repo.shared, draft).conflicts, [], "a live edit collided");
316 }
317 repo.graph.add(draft);
318 repo.shared.add(draft.id);
319 snapshots.push(new Set(repo.shared));
320 if (!pinned) {
321 assert.deepEqual(repo.files(), filesToRecord(next), "live edit on top of the shared projection");
322 assert.ok(
323 !conflicts(repo.graph, repo.shared).some((c) => c.atoms.includes(draft.id)),
324 "the live atom is in a conflict",
325 );
326 }
327 }
328 });
329 if (CASES >= 100) assert.ok(onConflicted > CASES / 2, `only ${onConflicted} live edits ran on a conflicted set`);
330 });
331});
333// The CLI rejects a draft from checkDraft's report, while `conflicts` reads
334// the stored set. They must agree, holds and pinned views included.
335describe("property: the live check agrees with the set", () => {
336 it("checkDraft reports exactly the conflicts that accepting the draft adds", () => {
337 let reportedTotal = 0;
338 forCases("checkDraft vs conflicts", (rng, log) => {
339 const sim = new Sim(rng, log, { duplicates: rng.chance(0.5), holds: true, pinned: 0.35 });
340 const steps = rng.range(5, 25);
341 for (let s = 0; s < steps; s++) {
342 const report = sim.step();
343 if (!report) continue;
344 const graph = sim.repo.graph;
345 const id = graph.atoms()[graph.size - 1]!.id;
346 const shape = (c: Conflict) => ({ atoms: c.atoms, kind: c.kind, keys: c.keys, sides: c.sides });
347 const added = conflicts(graph, sim.repo.shared).filter((c) => c.atoms.includes(id));
348 assert.deepEqual(report.conflicts.map(shape), added.map(shape), `conflicts of ${id}`);
349 reportedTotal += added.length;
350 }
351 });
352 if (CASES >= 100) assert.ok(reportedTotal > CASES / 4, `only ${reportedTotal} conflicts were checked`);
353 });
354});