Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
show on this site's /mcp
CLI
abso show 206 --json
JSON
/christopher/abso-core/versions/206?format=json

Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.

of shared·capacity··Not checked

Version 205 · Files at version 206

5 files, 310 lines added, 9 removed.

--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -256,6 +256,15 @@
256256 return { seq, k };
257257}
258258
259+/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
260+export type PackedLine = [number, number, number, number, number];
261+/** A delete of a line in a file's packed history: [n, deleter seq]. */
262+export type PackedDelete = [number, number];
263+/** An attribute set on a file: [seq, name, value]. */
264+export type PackedAttr = [number, string, string | null];
265+/** Lines longer than this aren't packed with their file; their text is read on its own. */
266+const PACKED_TEXT = 4096;
259268export class Graph {
260269 readonly #storage?: GraphStateStorage;
261270 readonly #childCounts?: ChildCounts;
@@ -294,6 +303,8 @@
294303 storage?: GraphStateStorage;
295304 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
296305 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
306+ /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
307+ packFiles?: boolean;
297308 } = {},
298309 ) {
299310 if (options.indexAcceptedAtom && !options.storage)
@@ -583,9 +594,58 @@
583594 JSON.stringify(["number", Number(key)]),
584595 );
585596 this.#labels = storedMap(storage, "labels");
597+ this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
598+ this.#fileTexts = storedLists<string | null>(storage, "file-texts");
599+ this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
600+ this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
601+ this.#packFiles = options.packFiles ?? true;
586602 }
587603 }
588604
605+ // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
606+ // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
607+ // text, every delete of one of those lines ([n, deleter seq]), and every attribute set on it ([seq, name, value]).
608+ // Appended as atoms are added, so a view lays a file out from a few pages instead of a row read per line. Kept from
609+ // a fresh adoption on; a graph adopted before has none, and views lay out as before.
611+ #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
612+ #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
613+ #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
614+ #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
615+ /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
616+ #packFiles = true;
617+ /** Whether this graph's files are packed: read once, when first asked, so opening reads nothing. */
618+ #packedKnown: boolean | undefined;
619+ get #packed(): boolean {
620+ this.#packedKnown ??= !!this.#storage && this.#storage.read("file-lines:meta", "format") === 1;
621+ return this.#packedKnown;
622+ }
624+ /** Whether this graph keeps each file's line history packed. */
625+ get packedFiles(): boolean {
626+ return this.#packed;
627+ }
628+ /** A path's index, or undefined when nothing was ever written or set in it. */
629+ pathIndexOf(path: string): number | undefined {
630+ return this.#pathIndex.get(path);
631+ }
632+ /** The index of the path line n was written in. */
633+ writtenInIndex(n: number): number {
634+ return this.#lineFile.at(n);
635+ }
636+ *packedLines(file: number): IterableIterator<PackedLine> {
637+ yield* this.#fileLines!.values(String(file));
638+ }
639+ *packedTexts(file: number): IterableIterator<string | null> {
640+ yield* this.#fileTexts!.values(String(file));
641+ }
642+ *packedDeletes(file: number): IterableIterator<PackedDelete> {
643+ yield* this.#fileDeletes!.values(String(file));
644+ }
645+ *packedAttrs(file: number): IterableIterator<PackedAttr> {
646+ yield* this.#fileAttrs!.values(String(file));
647+ }
589649 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
590650 #lists: ((seq: number) => AtomLists) | undefined;
591651 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
@@ -1377,6 +1437,10 @@
13771437 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
13781438 this.#storage.write("ordered-children", "format", 2);
13791439 }
1440+ if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
1441+ this.#storage.write("file-lines:meta", "format", 1);
1442+ this.#packedKnown = true;
1443+ }
13801444
13811445 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
13821446 else this.#validateAcceptedAtom(atom);
@@ -1425,11 +1489,19 @@
14251489 if (deletedN) yield* deletedN;
14261490 else for (const line of atom.deletes) yield graph.#lineN(line);
14271491 };
1492+ const packedDeletes = new Map<number, PackedDelete[]>();
14281493 for (const n of deletedNumbers(this)) {
1494+ if (this.#packed) {
1495+ const file = this.#lineFile.at(n);
1496+ const list = packedDeletes.get(file);
1497+ if (list) list.push([n, seq]);
1498+ else packedDeletes.set(file, [[n, seq]]);
1499+ }
14291500 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
14301501 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
14311502 else pushIndex(this.#moreDeleters, n, seq);
14321503 }
1504+ for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
14331505 this.#lineBase.push(this.#lineTotal);
14341506 for (const run of atom.inserts) {
14351507 const file = this.#pathOf(run.file);
@@ -1450,6 +1522,26 @@
14501522
14511523 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
14521524 else pushOne(this.#runStarts, parent, first);
1525+ const replacesParent = deletes(run.parent) ? 1 : 0;
1526+ if (this.#packed) {
1527+ const base = this.#lineBase[seq]!;
1528+ this.#fileLines!.appendAll(
1529+ String(file),
1530+ run.lines.map(
1531+ (_, i): PackedLine => [
1532+ first + i,
1533+ i === 0 ? parent : first + i - 1,
1534+ seq,
1535+ first + i - base,
1536+ i === 0 ? replacesParent : 0,
1537+ ],
1538+ ),
1539+ );
1540+ this.#fileTexts!.appendAll(
1541+ String(file),
1542+ run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1543+ );
1544+ }
14531545 for (let i = 0; i < run.lines.length; i++) {
14541546 const n = this.#lineTotal;
14551547 this.#childCounts?.append(n);
@@ -1473,6 +1565,8 @@
14731565 else pushIndex(this.#relocatedToCode, parentCode, info);
14741566 });
14751567 if (frozen.moves) this.#movers.push(frozen.id);
1568+ if (this.#packed)
1569+ for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
14761570 for (const key of writes) {
14771571 const code = this.#code(key);
14781572 if (this.#writersPages) {
--- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -413,6 +413,23 @@
413413 storage.write(`${name}:pages`, pageKey(key, index), values);
414414 storage.write(`${name}:lengths`, key, count + 1);
415415 },
416+ /** Append several values, writing each page they touch once. */
417+ appendAll(key: string, more: readonly V[]): void {
418+ if (more.length === 0) return;
419+ const count = length(key);
420+ let index = Math.floor(count / pageSize);
421+ let values = count % pageSize === 0 ? [] : page(key, index);
422+ if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);
423+ for (const value of more) {
424+ if (values.length === pageSize) {
425+ storage.write(`${name}:pages`, pageKey(key, index++), values);
426+ values = [];
427+ }
428+ values.push(value);
429+ }
430+ storage.write(`${name}:pages`, pageKey(key, index), values);
431+ storage.write(`${name}:lengths`, key, count + more.length);
432+ },
416433 };
417434}
418435
--- /dev/null
+++ b/src/engine/test/packed-files.test.ts
@@ -0,0 +1,56 @@
1+// Each file's line history packed (abso Capacity, Graph.packedLines): a stored graph lays files out from a few pages,
2+// and must give exactly what the in-memory graph gives, through edits, deletes, moves between files and back.
3+
4+import assert from "node:assert/strict";
5+import { test } from "node:test";
6+import { Graph, View } from "../index.ts";
7+import { StableOverlaySet } from "../state-source.ts";
8+import { lines, Repo } from "./helpers.ts";
9+import { SqlState } from "./storage-helper.ts";
11+test("a packed file lays out as the in-memory graph does, at every step, moves included", () => {
12+ const oracle = Repo.init({ "a.txt": lines("one", "two", "three", "four"), "b.txt": lines("bee"), "c.txt": "" });
13+ const sets: Set<string>[] = [new Set(oracle.shared)];
14+ const step = (change: Parameters<Repo["edit"]>[0]) => {
15+ oracle.edit(change);
16+ sets.push(new Set(oracle.shared));
17+ };
18+ step({ edits: [{ file: "a.txt", old: "two", new: "TWO" }] });
19+ step({ move: { file: "a.txt", start: 1, end: 3, to: "b.txt", at: 1 } });
20+ step({ edits: [{ file: "b.txt", old: "TWO", new: "two again" }] });
21+ step({ edits: [{ file: "a.txt", old: "four", new: "" }] });
22+ step({ move: { file: "b.txt", start: 0, end: 2, to: "c.txt", at: 0 } });
23+ step({ edits: [{ file: "c.txt", old: "bee", new: "bee\nafter bee" }] });
24+ const storage = new SqlState();
25+ try {
26+ const graph = new Graph({ storage });
27+ for (const atom of oracle.graph.atoms()) graph.add(atom);
28+ const reopened = new Graph({ storage });
29+ assert.equal(reopened.packedFiles, true);
30+ for (const [i, set] of sets.entries()) {
31+ const packed = new View(reopened, new StableOverlaySet(set));
32+ const memory = new View(oracle.graph, set);
33+ assert.deepEqual(packed.paths(), memory.paths(), `step ${i}: paths`);
34+ for (const path of ["a.txt", "b.txt", "c.txt"]) {
35+ assert.equal(packed.text(path), memory.text(path), `step ${i}: ${path}`);
36+ assert.deepEqual(packed.sequence(path), memory.sequence(path), `step ${i}: ${path}'s sequence`);
37+ assert.deepEqual(packed.attrs(path), memory.attrs(path), `step ${i}: ${path}'s attributes`);
38+ }
39+ }
40+ } finally {
41+ storage.db.close();
42+ }
43+});
45+test("a graph made with packFiles off keeps no packed history", () => {
46+ const oracle = Repo.init({ "a.txt": lines("one") });
47+ const storage = new SqlState();
48+ try {
49+ const graph = new Graph({ storage, packFiles: false });
50+ for (const atom of oracle.graph.atoms()) graph.add(atom);
51+ assert.equal(new Graph({ storage }).packedFiles, false);
52+ assert.equal(new View(new Graph({ storage }), new StableOverlaySet(oracle.shared)).text("a.txt"), "one\n");
53+ } finally {
54+ storage.db.close();
55+ }
56+});
--- a/src/engine/test/state-source.test.ts
+++ b/src/engine/test/state-source.test.ts
@@ -47,6 +47,7 @@
4747 }
4848});
4949
50+// The line-by-line layout, which a graph adopted before packed file history still uses (packFiles: false).
5051test("current visibility stops at the first included deletion while history retains every deleter", () => {
5152 class ObservedStorage extends SqlState {
5253 pageReads = 0;
@@ -59,7 +60,7 @@
5960 try {
6061 const oracle = Repo.init({ "a.txt": "gone\nlive\n" });
6162 const deletion = oracle.draft({ edits: [{ file: "a.txt", old: "gone\n", new: "" }] });
62− const graph = new Graph({ storage });
63+ const graph = new Graph({ storage, packFiles: false });
6364 graph.add(oracle.graph.atom("a0"));
6465 const ids = ["a0"];
6566 for (let seq = 1; seq <= 514; seq++) {
@@ -68,7 +69,7 @@
6869 oracle.graph.add(atom);
6970 ids.push(atom.id);
7071 }
71− const reopened = new Graph({ storage });
72+ const reopened = new Graph({ storage, packFiles: false });
7273 const membership = new StableOverlaySet(ids);
7374 const view = new View(reopened, membership);
7475 storage.pageReads = 0;
@@ -479,9 +480,9 @@
479480 }
480481 const before = oracle.view().text("a.txt");
481482 oracle.edit({ edits: [{ file: "a.txt", old: before, new: "live\n" }] });
482− const graph = new Graph({ storage });
483+ const graph = new Graph({ storage, packFiles: false });
483484 for (const id of oracle.shared) graph.add(oracle.graph.atom(id));
484− const reopened = new Graph({ storage });
485+ const reopened = new Graph({ storage, packFiles: false });
485486 reopened.eachChildN = () => {
486487 throw Error("unordered child collection forbidden");
487488 };
@@ -540,14 +541,20 @@
540541 const storage = new SqlState();
541542 try {
542543 const oracle = Repo.init({ "a.txt": "one\n" });
543− const graph = new Graph({ storage });
544+ const graph = new Graph({ storage, packFiles: false });
544545 graph.add(oracle.graph.atom("a0"));
545546 storage.remove("ordered-children", "format");
546− assert.throws(() => new View(new Graph({ storage }), new StableOverlaySet(["a0"])).text("a.txt"), /fresh adoption/);
547547 assert.throws(
548− () => new Graph({ storage }).add(oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "two" }] })),
548+ () => new View(new Graph({ storage, packFiles: false }), new StableOverlaySet(["a0"])).text("a.txt"),
549549 /fresh adoption/,
550550 );
551+ assert.throws(
552+ () =>
553+ new Graph({ storage, packFiles: false }).add(
554+ oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "two" }] }),
555+ ),
556+ /fresh adoption/,
557+ );
551558 storage.write("ordered-children", "format", 2);
552559 const parent = graph.startCodeOf("a.txt")!;
553560 storage.remove("ordered-children", JSON.stringify([String(parent), "meta"]));
--- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -64,6 +64,8 @@
6464 readonly vis: Int32Array;
6565 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
6666 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
67+ /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
68+ readonly visText?: readonly (string | null)[];
6769 /** Positions by n, built the first time they're asked for. */
6870 seqIndex?: Map<number, number>;
6971 visIndex?: Map<number, number>;
@@ -451,6 +453,7 @@
451453 /** Lay out one file: its line tree from the set's atoms, linearized. */
452454 #layout(path: string, complete: boolean): FileState {
453455 const graph = this.graph;
456+ if (graph.packedFiles && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
454457 if (this.#scratchMoves())
455458 return graph.withProjectionScratch((scratch) =>
456459 this.#layoutResolved(
@@ -462,10 +465,133 @@
462465 return this.#layoutResolved(path, complete);
463466 }
464467
468+ /** For each path, the files that lines moved into it were written in: worked out once per view. */
469+ #movedFrom: Map<string, Set<number>> | undefined;
470+ #movedInFrom(): Map<string, Set<number>> {
471+ if (this.#movedFrom) return this.#movedFrom;
472+ const graph = this.graph;
473+ const out = new Map<string, Set<number>>();
474+ if (this.#hasMoves) {
475+ const relocs = this.#relocationsN();
476+ // Where each node sits, walked once for the whole view: through the moves, up to a file's start.
477+ const memo = new Map<number, string>();
478+ const fileOf = (code: number): string => {
479+ const walked: number[] = [];
480+ let cur = code;
481+ let file: string | undefined;
482+ while (file === undefined) {
483+ if (cur < 0) file = graph.nodeOf(cur).slice(1);
484+ else {
485+ file = memo.get(cur);
486+ if (file === undefined) {
487+ walked.push(cur);
488+ cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
489+ }
490+ }
491+ }
492+ for (const n of walked) memo.set(n, file);
493+ return file;
494+ };
495+ for (const [n, { parent }] of relocs) {
496+ const into = fileOf(parent);
497+ let from = out.get(into);
498+ if (!from) out.set(into, (from = new Set()));
499+ from.add(graph.writtenInIndex(n));
500+ }
501+ }
502+ this.#movedFrom = out;
503+ return out;
504+ }
506+ /**
507+ * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, and in the
508+ * files its moved-in lines came from, read a page at a time; the same tree and order as #layoutResolved, built in
509+ * memory with no read per line.
510+ */
511+ #layoutPacked(path: string, complete: boolean): FileState {
512+ const graph = this.graph;
513+ const attrs = this.#attributes(path);
514+ const start = graph.startCodeOf(path);
515+ if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
516+ const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
517+ const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
518+ const children = new Map<number, Child[]>();
519+ const texts = new Map<number, string | null>();
520+ const deleters = new Map<number, number[]>();
521+ for (const file of files) {
522+ const lineTexts = graph.packedTexts(file);
523+ for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
524+ const text = lineTexts.next().value as string | null;
525+ if (!this.#has(seq)) continue;
526+ const moved = relocs?.get(n);
527+ let at = parent;
528+ let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k };
529+ if (moved) {
530+ const mover = graph.atom(moved.r.atom).seq;
531+ child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k };
532+ at = moved.parent;
533+ }
534+ const list = children.get(at);
535+ if (list) list.push(child);
536+ else children.set(at, [child]);
537+ texts.set(n, text);
538+ }
539+ for (const [n, deleter] of graph.packedDeletes(file)) {
540+ if (!this.#has(deleter)) continue;
541+ const by = deleters.get(n);
542+ if (by) by.push(deleter);
543+ else deleters.set(n, [deleter]);
544+ }
545+ }
546+ const order = (a: Child, b: Child) =>
547+ b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
548+ const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
549+ const seq: number[] = [];
550+ const vis: number[] = [];
551+ const visText: (string | null)[] = [];
552+ const deletedBy = new Map<number, readonly number[]>();
553+ const stack: number[] = [];
554+ const push = (code: number) => {
555+ const list = children.get(code);
556+ if (!list) return;
557+ if (list.length > 1) list.sort(order);
558+ for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
559+ };
560+ push(start);
561+ while (stack.length) {
562+ const n = stack.pop()!;
563+ const by = deleters.get(n);
564+ if (by) {
565+ if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
566+ } else {
567+ vis.push(n);
568+ visText.push(texts.get(n) ?? null);
569+ }
570+ if (complete) seq.push(n);
571+ push(n);
572+ }
573+ return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText };
574+ }
465576 #attributes(path: string): FileAttrs {
466577 const graph = this.graph;
467578 // For each attribute, the highest-priority setter in the set wins.
468579 const setters = new Map<string, { id: AtomId; value: string | null }>();
580+ const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
581+ if (graph.packedFiles) {
582+ for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
583+ if (!this.#has(seq)) continue;
584+ const id = graph.idOfSeq(seq);
585+ const best = setters.get(name);
586+ if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
587+ }
588+ return {
589+ exists: setters.get("exists")?.value === "1",
590+ exec: setters.get("exec")?.value === "1",
591+ link: setters.get("link")?.value ?? null,
592+ blob: setters.get("blob")?.value ?? null,
593+ };
594+ }
469595 for (const id of graph.eachAtomIn(path)) {
470596 if (!this.#has(graph.atom(id).seq)) continue;
471597 for (const a of graph.atom(id).attrs ?? []) {
@@ -556,9 +682,9 @@
556682 /** The projected text of a file ("" if it has no visible lines). */
557683 text(path: string): string {
558684 if (this.#textCache?.path === path) return this.#textCache.text;
559− const vis = this.#file(path).vis;
685+ const { vis, visText } = this.#file(path);
560686 const lines: string[] = new Array(vis.length);
561− for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
687+ for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
562688 const text = joinLines(lines);
563689 this.#textCache = { path, text };
564690 return text;
@@ -742,6 +868,7 @@
742868 // headers are separate from their payload byte lengths below.
743869 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
744870 n += f.seq.byteLength + f.vis.byteLength;
871+ if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
745872 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
746873 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
747874 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;