- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/test/concurrent.test.ts?version=36&format=json
476 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 36. The newest is 318, and 2 versions since then changed this file.
1// Property: concurrent edits. Atoms written against the same older view
2// conflict exactly when their claim keys overlap, and otherwise project to the
3// same bytes in every acceptance order, equal to applying all their hunks to
4// the old text at once.
5// PROP_SEED=<seed> PROP_CASES=1 node --test src/engine/test/concurrent.test.ts
7import assert from "node:assert/strict";
8import { describe, it } from "node:test";
9import {
10 type Atom,
11 type AtomId,
12 type AtomInput,
13 buildAtom,
14 claimsOf,
15 conflicts,
16 diffLines,
17 type EditInput,
18 Graph,
19 independent,
20 keyOverlap,
21 type Mode,
22 splitLines,
23 type TextEdit,
24 View,
25} from "../index.ts";
27const textOf = (lines: readonly string[]): string => (lines.length === 0 ? "" : lines.join("\n") + "\n");
29import { EditGen, type Files, filesFromView, filesToRecord, sameFiles } from "./gen.ts";
30import { Repo, Rng } from "./helpers.ts";
32const BASE_SEED = Number(process.env["PROP_SEED"] ?? 20260621);
33const CASES = Number(process.env["PROP_CASES"] ?? 250);
35/** A hunk in terms of the old view's visible lines. start === end is a pure insertion at gap start. */
36interface PlainHunk {
37 readonly file: string;
38 readonly start: number;
39 readonly end: number;
40 readonly lines: readonly string[];
41}
43interface Concurrent {
44 readonly input: AtomInput;
45 readonly hunks: readonly PlainHunk[];
46 readonly describe: string;
47}
49/** Apply hunks from several atoms to the old text at once (the oracle). */
50function applyAll(base: Files, hunks: readonly PlainHunk[]): Files {
51 const out: Files = new Map(base);
52 const byFile = new Map<string, PlainHunk[]>();
53 for (const h of hunks) byFile.set(h.file, [...(byFile.get(h.file) ?? []), h]);
54 for (const [file, list] of byFile) {
55 const old = base.get(file) ?? [];
56 const inserts = new Map<number, readonly string[]>();
57 const deleted = new Set<number>();
58 const afterLine = new Map<number, readonly string[]>();
59 for (const h of list) {
60 if (h.start === h.end) {
61 assert.ok(!inserts.has(h.start), "two non-conflicting insertions into one gap");
62 inserts.set(h.start, h.lines);
63 } else {
64 for (let i = h.start; i < h.end; i++) {
65 assert.ok(!deleted.has(i), "two non-conflicting atoms deleted the same line");
66 deleted.add(i);
67 }
68 afterLine.set(h.end - 1, h.lines);
69 }
70 }
71 const result: string[] = [];
72 for (let p = 0; p <= old.length; p++) {
73 result.push(...(inserts.get(p) ?? []));
74 if (p < old.length) {
75 if (!deleted.has(p)) result.push(old[p]!);
76 result.push(...(afterLine.get(p) ?? []));
77 }
78 }
79 if (result.length > 0) out.set(file, result);
80 else out.delete(file);
81 }
82 return out;
83}
85/** One random single-hunk (sometimes two-file) concurrent edit against the old files. */
86function concurrentEdit(gen: EditGen, rng: Rng, files: Files, index: number, deadPaths: readonly string[]): Concurrent {
87 const hunks: PlainHunk[] = [];
88 const edits: EditInput[] = [];
89 const parts: string[] = [];
90 const fresh = (n: number) => Array.from({ length: n }, () => gen.fresh());
91 const usedFiles = new Set<string>();
92 const addHunk = (): void => {
93 const paths = [...files.keys()].filter((p) => !usedFiles.has(p) && files.get(p)!.length > 0).sort();
94 const mode: Mode = rng.pick<Mode>(["both", "both", "after", "after", "before", "before", "wide"]);
95 if (paths.length === 0 || rng.chance(0.08)) {
96 const path = rng.pick(["c0.txt", "c1.txt", ...deadPaths]);
97 if (usedFiles.has(path) || (files.get(path) ?? []).length > 0) return;
98 usedFiles.add(path);
99 const lines = fresh(rng.range(1, 3));
100 hunks.push({ file: path, start: 0, end: 0, lines });
101 edits.push({ file: path, old: "", new: lines.join("\n") + "\n" });
102 parts.push(`create ${path} ${JSON.stringify(lines)}`);
103 return;
104 }
105 const path = rng.pick(paths);
106 usedFiles.add(path);
107 const old = files.get(path)!;
108 const n = old.length;
109 const roll = rng.int(3);
110 let start: number;
111 let end: number;
112 let lines: string[];
113 if (roll === 0) {
114 start = end = rng.int(n + 1);
115 lines = fresh(rng.range(1, 3));
116 } else {
117 start = rng.int(n);
118 end = rng.range(start + 1, Math.min(n, start + 3));
119 lines = roll === 1 ? fresh(rng.range(1, 3)) : [];
120 }
121 if (rng.chance(0.5)) {
122 // As a text edit with context. With repeated lines several alignments
123 // give the same text; step 2 of the spec (a line diff of old against
124 // new) picks one, so the oracle's hunks come from that diff.
125 const edit = gen.textEdit(path, old, start, end, lines, mode) as TextEdit;
126 const at = textOf(old).indexOf(edit.old);
127 const offset = textOf(old).slice(0, at).split("\n").length - 1;
128 for (const h of diffLines(splitLines(edit.old), splitLines(edit.new))) {
129 hunks.push({ file: path, start: offset + h.start, end: offset + h.end, lines: h.lines });
130 }
131 edits.push(edit);
132 } else {
133 hunks.push({ file: path, start, end, lines });
134 edits.push({ file: path, start, end, lines, mode });
135 }
136 parts.push(
137 `${roll === 0 ? "insert" : roll === 1 ? "replace" : "delete"} ${path}[${start},${end}) -> ${JSON.stringify(lines)} mode=${mode}`,
138 );
139 };
140 addHunk();
141 if (rng.chance(0.15)) addHunk();
142 if (edits.length === 0) addHunk();
143 const reliance = rng.chance(0.2) ? gen.reliance(files) : undefined;
144 return {
145 input: {
146 author: `agent${index}`,
147 message: `concurrent edit ${index}`,
148 time: index,
149 edits,
150 ...(reliance ? { reliesOn: [reliance] } : {}),
151 },
152 hunks,
153 describe: parts.join(" + ") + (reliance ? ` reliesOn ${reliance.file}[${reliance.start},${reliance.end})` : ""),
154 };
155}
157describe("property: concurrent edits", () => {
158 it("conflict exactly when claim keys overlap; otherwise the same bytes in every acceptance order", (t) => {
159 let nonTrivialMerges = 0;
160 let conflictPairs = 0;
161 for (let c = 0; c < CASES; c++) {
162 const seed = BASE_SEED + c;
163 const rng = new Rng(seed);
164 const log: string[] = [];
165 try {
166 // An older view with some history (and tombstones) behind it.
167 const gen = new EditGen(rng, { duplicates: rng.chance(0.5), wide: false });
168 const initial = gen.initialFiles();
169 const repo = Repo.init(filesToRecord(initial));
170 log.push(`a0: ${JSON.stringify(filesToRecord(initial))}`);
171 const baseSteps = rng.range(0, 12);
172 for (let s = 0; s < baseSteps; s++) {
173 const view = repo.view();
174 const g = gen.next(filesFromView(view), view);
175 if (!g) continue;
176 try {
177 const atom = repo.edit({ message: g.describe, edits: g.edits });
178 log.push(`${atom.id}: ${g.describe}`);
179 } catch (err) {
180 if ((err as { code?: string }).code !== "empty-atom") throw err;
181 }
182 }
183 const oldSet: ReadonlySet<AtomId> = new Set(repo.shared);
184 const oldView = repo.view(oldSet);
185 const oldFiles = filesFromView(oldView);
186 const deadPaths = oldView.knownPaths().filter((p) => !oldView.hasFile(p));
187 const saved = JSON.stringify(repo.graph);
189 // k edits, each written against the same old view.
190 const k = rng.range(2, 5);
191 const edits = Array.from({ length: k }, (_, i) => concurrentEdit(gen, rng, oldFiles, i, deadPaths));
192 const graph = repo.graph;
193 const full = new Set(oldSet);
194 const ids: AtomId[] = [];
195 for (const e of edits) {
196 const atom = buildAtom(new View(graph, oldSet), e.input);
197 log.push(
198 `${atom.id} (concurrent): ${e.describe} ${JSON.stringify(e.input.edits)} deletes ${atom.deletes.join(",") || "nothing"}`,
199 );
200 graph.add(atom);
201 full.add(atom.id);
202 ids.push(atom.id);
203 }
205 // They are pairwise independent, and depend only on the old view.
206 for (const id of ids) for (const d of graph.atom(id).deps) assert.ok(oldSet.has(d), `${id} depends on ${d}`);
207 // Conflicts: exactly the independent pairs with overlapping write/claim keys.
208 const reported = new Set(conflicts(graph, full).map((x) => x.atoms.join(" ")));
209 const expected = new Set<string>();
210 const all = [...full].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq);
211 for (let i = 0; i < all.length; i++) {
212 for (let j = i + 1; j < all.length; j++) {
213 const a = all[i]!;
214 const b = all[j]!;
215 if (independent(graph, a, b) && keyOverlap(graph.atom(a), graph.atom(b)).length > 0)
216 expected.add(`${a} ${b}`);
217 }
218 }
219 assert.deepEqual([...reported].sort(), [...expected].sort(), "reported conflicts");
220 for (const pair of expected) {
221 const [a, b] = pair.split(" ");
222 assert.ok(ids.includes(a!) && ids.includes(b!), `conflict ${pair} involves an atom of the old view`);
223 }
224 conflictPairs += expected.size;
226 // The non-conflicting ones commute: same bytes in every acceptance order, equal to the oracle.
227 const chosen: number[] = [];
228 for (let i = 0; i < k; i++) {
229 if (chosen.every((j) => !expected.has(`${ids[j]} ${ids[i]}`))) chosen.push(i);
230 }
231 if (chosen.length >= 2) nonTrivialMerges++;
232 log.push(`merged without conflicts: ${chosen.map((i) => ids[i]).join(", ")}`);
233 const want = filesToRecord(
234 applyAll(
235 oldFiles,
236 chosen.flatMap((i) => edits[i]!.hunks),
237 ),
238 );
239 const orders = [chosen, [...chosen].reverse(), rng.shuffle(chosen)];
240 for (const order of orders) {
241 const fresh = Graph.fromJSON(JSON.parse(saved));
242 const set = new Set(oldSet);
243 for (const i of order) {
244 const atom = buildAtom(new View(fresh, oldSet), edits[i]!.input);
245 fresh.add(atom);
246 set.add(atom.id);
247 }
248 assert.deepEqual(conflicts(fresh, set), [], `order ${order.join(",")} has conflicts`);
249 assert.deepEqual(new View(fresh, set).files(), want, `acceptance order ${order.join(",")}`);
250 }
251 } catch (err) {
252 const detail = err instanceof Error ? err.message : String(err);
253 assert.fail(
254 `concurrent edits failed at seed ${seed} (rerun: PROP_SEED=${seed} PROP_CASES=1)\nsteps:\n ${log.join("\n ")}\n${detail}`,
255 );
256 }
257 }
258 // The generator must actually produce both outcomes.
259 t.diagnostic(`${CASES} cases: ${nonTrivialMerges} merged two or more atoms, ${conflictPairs} conflicting pairs`);
260 if (CASES >= 100) {
261 assert.ok(nonTrivialMerges > CASES / 4, `only ${nonTrivialMerges} cases merged two or more atoms`);
262 assert.ok(conflictPairs > CASES / 10, `only ${conflictPairs} conflicting pairs`);
263 }
264 });
265});
267function forCases(name: string, body: (rng: Rng, log: string[]) => void): void {
268 for (let c = 0; c < CASES; c++) {
269 const seed = BASE_SEED + c;
270 const log: string[] = [];
271 try {
272 body(new Rng(seed), log);
273 } catch (err) {
274 const detail = err instanceof Error ? err.message : String(err);
275 assert.fail(
276 `${name} failed at seed ${seed} (rerun: PROP_SEED=${seed} PROP_CASES=1)\nsteps:\n ${log.join("\n ")}\n${detail}`,
277 );
278 }
279 }
280}
282/** A repo with some live history behind it, so the old view has tombstones and siblings. */
283function withHistory(rng: Rng, log: string[]): { repo: Repo; gen: EditGen } {
284 const gen = new EditGen(rng, { duplicates: rng.chance(0.5), wide: false });
285 const initial = gen.initialFiles();
286 const repo = Repo.init(filesToRecord(initial));
287 log.push(`a0: ${JSON.stringify(filesToRecord(initial))}`);
288 const steps = rng.range(0, 12);
289 for (let s = 0; s < steps; s++) {
290 const view = repo.view();
291 const files = filesFromView(view);
292 const g = gen.next(files, view);
293 if (!g || sameFiles(g.apply(files), files)) continue;
294 const atom = repo.edit({ message: g.describe, edits: g.edits });
295 log.push(`${atom.id}: ${g.describe}`);
296 }
297 return { repo, gen };
298}
300const pairKey = (a: AtomId, b: AtomId): string =>
301 [a, b].sort((p, q) => Number(p.slice(1)) - Number(q.slice(1))).join(" ");
303/** One concurrent splice, in line numbers of the old view (`n` lines in its file). */
304interface Splice {
305 readonly file: string;
306 readonly start: number;
307 readonly end: number;
308 readonly mode: Mode;
309 readonly n: number;
310}
312/**
313 * The git floor, stated on line numbers alone (no keys): two replacements
314 * touch when their ranges overlap; two insertions when they are at the same
315 * place; an insertion and a replacement when the replacement covers a line
316 * the insertion sits against. An insertion sits against the line above unless
317 * in before mode and the line below unless in after mode; at the edge of the
318 * file, against the one line there is.
319 */
320function touch(a: Splice, b: Splice): boolean {
321 if (a.file !== b.file) return false;
322 const isInsert = (h: Splice) => h.start === h.end;
323 if (!isInsert(a) && !isInsert(b)) return a.start < b.end && b.start < a.end;
324 if (isInsert(a) && isInsert(b)) return a.start === b.start;
325 const [r, i] = isInsert(a) ? [b, a] : [a, b];
326 const inR = (x: number) => x >= r.start && x < r.end;
327 const p = i.start;
328 const above = p > 0 && (i.mode !== "before" || p === i.n);
329 const below = p < i.n && (i.mode !== "after" || p === 0);
330 return (above && inR(p - 1)) || (below && inR(p));
331}
333// The concurrent property above compares conflicts() with keyOverlap(), the
334// engine's own definition; this one checks the keys against line numbers.
335describe("property: the git floor", () => {
336 it("concurrent splice edits conflict exactly when their line ranges touch, in every mode", () => {
337 let conflicting = 0;
338 let clean = 0;
339 forCases("git floor", (rng, log) => {
340 const { repo, gen } = withHistory(rng, log);
341 const oldSet = new Set(repo.shared);
342 const oldView = repo.view(oldSet);
343 const files = filesFromView(oldView);
344 const paths = [...files.keys()].sort();
345 if (paths.length === 0) return;
346 const k = rng.range(2, 4);
347 const splices = new Map<AtomId, Splice>();
348 for (let i = 0; i < k; i++) {
349 const file = rng.pick(paths);
350 const n = files.get(file)!.length;
351 const mode = rng.pick<Mode>(["both", "after", "before", "wide"]);
352 const roll = rng.int(3);
353 let start: number;
354 let end: number;
355 let add: string[];
356 if (roll === 0) {
357 start = end = rng.int(n + 1);
358 add = [gen.fresh()];
359 } else {
360 start = rng.int(n);
361 end = rng.range(start + 1, Math.min(n, start + 3));
362 add = roll === 1 ? [gen.fresh(), gen.fresh()].slice(0, rng.range(1, 2)) : [];
363 }
364 const atom = buildAtom(new View(repo.graph, oldSet), {
365 author: `agent${i}`,
366 message: `${roll === 0 ? "insert" : roll === 1 ? "replace" : "delete"} ${file}[${start},${end}) mode=${mode}`,
367 edits: [{ file, start, end, lines: add, mode }],
368 });
369 log.push(`${atom.id} (concurrent): ${atom.message}`);
370 repo.graph.add(atom);
371 repo.shared.add(atom.id);
372 splices.set(atom.id, { file, start, end, mode, n });
373 }
374 const ids = [...splices.keys()];
375 const expected: string[] = [];
376 for (let i = 0; i < ids.length; i++) {
377 for (let j = i + 1; j < ids.length; j++) {
378 if (touch(splices.get(ids[i]!)!, splices.get(ids[j]!)!)) expected.push(pairKey(ids[i]!, ids[j]!));
379 else clean++;
380 }
381 }
382 conflicting += expected.length;
383 const reported = conflicts(repo.graph, repo.shared).map((c) => pairKey(c.atoms[0], c.atoms[1]));
384 assert.deepEqual(reported.sort(), expected.sort());
385 });
386 if (CASES >= 100) {
387 assert.ok(conflicting > CASES / 4, `only ${conflicting} touching pairs`);
388 assert.ok(clean > CASES / 2, `only ${clean} clean pairs`);
389 }
390 });
391});
393// June: claim width is the lever. A narrow claim lets more run in parallel,
394// a wide one serializes more.
395describe("property: claim width", () => {
396 it("narrowing a claim never adds a conflict and widening never removes one (after, before ⊆ both ⊆ wide)", () => {
397 let narrowerHelped = 0;
398 let widerBit = 0;
399 forCases("claim width", (rng, log) => {
400 const { repo, gen } = withHistory(rng, log);
401 const oldView = repo.view(new Set(repo.shared));
402 const files = filesFromView(oldView);
403 // Concurrent atoms written against the same old view, some with reliances.
404 const pool: Atom[] = [];
405 for (let i = 0; i < 8; i++) {
406 const g = gen.next(files, oldView);
407 if (!g || sameFiles(g.apply(files), files)) continue;
408 const reliance = rng.chance(0.2) ? gen.reliance(files) : undefined;
409 pool.push(
410 buildAtom(oldView, {
411 author: `p${i}`,
412 message: g.describe,
413 edits: g.edits,
414 ...(reliance ? { reliesOn: [reliance] } : {}),
415 }),
416 );
417 }
418 // The subject: one hunk as a text edit with up to two lines of unchanged
419 // context on each side (the context is what wide holds).
420 const paths = [...files.keys()].sort();
421 if (paths.length === 0) return;
422 const file = rng.pick(paths);
423 const all = files.get(file)!;
424 const n = all.length;
425 const insert = rng.chance(0.5);
426 const i = insert ? rng.int(n + 1) : rng.int(n);
427 const j = insert ? i : rng.range(i + 1, Math.min(n, i + 2));
428 const add = insert ? [gen.fresh()] : rng.chance(0.3) ? [] : [gen.fresh()];
429 const a = Math.max(0, i - rng.range(0, 2));
430 const b = Math.min(n, j + rng.range(0, 2));
431 const edit = gen.textEdit(file, all, i, j, add, "both") as { old: string; new: string };
432 const text = (ls: readonly string[]) => (ls.length ? ls.join("\n") + "\n" : "");
433 const whole = text(all);
434 const wider = { file, old: text(all.slice(a, b)), new: text([...all.slice(a, i), ...add, ...all.slice(j, b)]) };
435 const unique = wider.old !== "" && whole.indexOf(wider.old) === whole.lastIndexOf(wider.old);
436 const subject = unique ? wider : { file, old: edit.old, new: edit.new };
437 log.push(`subject: ${file}[${i},${j}) -> ${JSON.stringify(add)} as ${JSON.stringify(subject)}`);
438 const build = (mode: Mode) =>
439 buildAtom(oldView, { author: "subject", message: "subject", edits: [{ ...subject, mode }] });
440 const [after, before, both, wide] = (["after", "before", "both", "wide"] as const).map(build) as [
441 Atom,
442 Atom,
443 Atom,
444 Atom,
445 ];
446 for (const v of [after, before, wide]) assert.deepEqual(v.writes, both.writes);
447 const subset = (x: readonly string[], y: readonly string[], what: string) => {
448 const ys = new Set(y);
449 for (const s of x) assert.ok(ys.has(s), `${what}: ${s} missing`);
450 };
451 for (const [narrow, name] of [
452 [after, "after"],
453 [before, "before"],
454 ] as const) {
455 subset(claimsOf(narrow), claimsOf(both), `claims ${name} ⊆ both`);
456 subset(narrow.deps, both.deps, `deps ${name} ⊆ both`);
457 }
458 subset(claimsOf(both), claimsOf(wide), "claims both ⊆ wide");
459 subset(both.deps, wide.deps, "deps both ⊆ wide");
460 for (const other of pool) {
461 const [hitAfter, hitBefore, hitBoth, hitWide] = [after, before, both, wide].map(
462 (v) => keyOverlap(v, other).length > 0,
463 );
464 if (hitAfter || hitBefore) assert.ok(hitBoth, `a narrow mode conflicts with ${other.author} but both does not`);
465 if (hitBoth) assert.ok(hitWide, `both conflicts with ${other.author} but wide does not`);
466 if (hitBoth && !(hitAfter && hitBefore)) narrowerHelped++;
467 if (!hitBoth && hitWide) widerBit++;
468 }
469 });
470 // The lever must actually move in the generated cases.
471 if (CASES >= 100) {
472 assert.ok(narrowerHelped > 10, `a narrow mode avoided only ${narrowerHelped} conflicts that both had`);
473 assert.ok(widerBit > 10, `wide added only ${widerBit} conflicts that both lacked`);
474 }
475 });
476});