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. Version 206 of shared· capacity· Oct 15 (2026-10-15 02:37 UTC) · 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 @@
256 256 return { seq, k }; 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; 259 268 export class Graph { 260 269 readonly #storage?: GraphStateStorage; 261 270 readonly #childCounts?: ChildCounts; @@ -294,6 +303,8 @@
294 303 storage?: GraphStateStorage; 295 304 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */ 296 305 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; 299 310 if (options.indexAcceptedAtom && !options.storage) @@ -583,9 +594,58 @@
583 594 JSON.stringify(["number", Number(key)]), 585 596 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; 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). */ 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; 624 + /** Whether this graph keeps each file's line history packed. */ 625 + get packedFiles(): boolean { 626 + return this.#packed; 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); 632 + /** The index of the path line n was written in. */ 633 + writtenInIndex(n: number): number { 634 + return this.#lineFile.at(n); 636 + *packedLines(file: number): IterableIterator<PackedLine> { 637 + yield* this.#fileLines!.values(String(file)); 639 + *packedTexts(file: number): IterableIterator<string | null> { 640 + yield* this.#fileTexts!.values(String(file)); 642 + *packedDeletes(file: number): IterableIterator<PackedDelete> { 643 + yield* this.#fileDeletes!.values(String(file)); 645 + *packedAttrs(file: number): IterableIterator<PackedAttr> { 646 + yield* this.#fileAttrs!.values(String(file)); 589 649 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */ 590 650 #lists: ((seq: number) => AtomLists) | undefined; 591 651 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */ @@ -1377,6 +1437,10 @@
1377 1437 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 1378 1438 this.#storage.write("ordered-children", "format", 2); 1440 + if (this.#storage && this.#atoms.length === 0 && this.#packFiles) { 1441 + this.#storage.write("file-lines:meta", "format", 1); 1442 + this.#packedKnown = true; 1381 1445 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch)); 1382 1446 else this.#validateAcceptedAtom(atom); @@ -1425,11 +1489,19 @@
1425 1489 if (deletedN) yield* deletedN; 1426 1490 else for (const line of atom.deletes) yield graph.#lineN(line); 1492 + const packedDeletes = new Map<number, PackedDelete[]>(); 1428 1493 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]]); 1429 1500 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq); 1430 1501 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq); 1431 1502 else pushIndex(this.#moreDeleters, n, seq); 1504 + for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list); 1433 1505 this.#lineBase.push(this.#lineTotal); 1434 1506 for (const run of atom.inserts) { 1435 1507 const file = this.#pathOf(run.file); @@ -1450,6 +1522,26 @@
1451 1523 if (this.#runStartPages) this.#runStartPages.append(String(parent), first); 1452 1524 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( 1531 + (_, i): PackedLine => [ 1533 + i === 0 ? parent : first + i - 1, 1536 + i === 0 ? replacesParent : 0, 1540 + this.#fileTexts!.appendAll( 1542 + run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)), 1453 1545 for (let i = 0; i < run.lines.length; i++) { 1454 1546 const n = this.#lineTotal; 1455 1547 this.#childCounts?.append(n); @@ -1473,6 +1565,8 @@
1473 1565 else pushIndex(this.#relocatedToCode, parentCode, info); 1475 1567 if (frozen.moves) this.#movers.push(frozen.id); 1569 + for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]); 1476 1570 for (const key of writes) { 1477 1571 const code = this.#code(key); 1478 1572 if (this.#writersPages) { --- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -413,6 +413,23 @@
413 413 storage.write(`${name}:pages`, pageKey(key, index), values); 414 414 storage.write(`${name}:lengths`, key, count + 1); 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); 430 + storage.write(`${name}:pages`, pageKey(key, index), values); 431 + storage.write(`${name}:lengths`, key, count + more.length); --- /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. 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]) => { 16 + sets.push(new Set(oracle.shared)); 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(); 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`); 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(); 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"); --- a/src/engine/test/state-source.test.ts
+++ b/src/engine/test/state-source.test.ts
@@ -47,6 +47,7 @@
50 + // The line-by-line layout, which a graph adopted before packed file history still uses (packFiles: false). 50 51 test("current visibility stops at the first included deletion while history retains every deleter", () => { 51 52 class ObservedStorage extends SqlState { @@ -59,7 +60,7 @@
60 61 const oracle = Repo.init({ "a.txt": "gone\nlive\n" }); 61 62 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 }); 63 64 graph.add(oracle.graph.atom("a0")); 65 66 for (let seq = 1; seq <= 514; seq++) { @@ -68,7 +69,7 @@
68 69 oracle.graph.add(atom); 71 − const reopened = new Graph({ storage });
72 + const reopened = new Graph({ storage, packFiles: false }); 72 73 const membership = new StableOverlaySet(ids); 73 74 const view = new View(reopened, membership); 74 75 storage.pageReads = 0; @@ -479,9 +480,9 @@
480 481 const before = oracle.view().text("a.txt"); 481 482 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 }); 483 484 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 }); 485 486 reopened.eachChildN = () => { 486 487 throw Error("unordered child collection forbidden"); @@ -540,14 +541,20 @@
540 541 const storage = new SqlState(); 542 543 const oracle = Repo.init({ "a.txt": "one\n" }); 543 − const graph = new Graph({ storage });
544 + const graph = new Graph({ storage, packFiles: false }); 544 545 graph.add(oracle.graph.atom("a0")); 545 546 storage.remove("ordered-children", "format"); 546 − assert.throws(() => new View(new Graph({ storage }), new StableOverlaySet(["a0"])).text("a.txt"), /fresh adoption/);
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"), 553 + new Graph({ storage, packFiles: false }).add( 554 + oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "two" }] }), 551 558 storage.write("ordered-children", "format", 2); 552 559 const parent = graph.startCodeOf("a.txt")!; 553 560 storage.remove("ordered-children", JSON.stringify([String(parent), "meta"])); --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -64,6 +64,8 @@
64 64 readonly vis: Int32Array; 65 65 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */ 66 66 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)[]; 67 69 /** Positions by n, built the first time they're asked for. */ 68 70 seqIndex?: Map<number, number>; 69 71 visIndex?: Map<number, number>; @@ -451,6 +453,7 @@
451 453 /** Lay out one file: its line tree from the set's atoms, linearized. */ 452 454 #layout(path: string, complete: boolean): FileState { 453 455 const graph = this.graph; 456 + if (graph.packedFiles && !this.#scratchMoves()) return this.#layoutPacked(path, complete); 454 457 if (this.#scratchMoves()) 455 458 return graph.withProjectionScratch((scratch) => 456 459 this.#layoutResolved( @@ -462,10 +465,133 @@
462 465 return this.#layoutResolved(path, complete); 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[] = []; 481 + let file: string | undefined; 482 + while (file === undefined) { 483 + if (cur < 0) file = graph.nodeOf(cur).slice(1); 485 + file = memo.get(cur); 486 + if (file === undefined) { 488 + cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur); 492 + for (const n of walked) memo.set(n, file); 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)); 502 + this.#movedFrom = out; 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. 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); 528 + let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k }; 530 + const mover = graph.atom(moved.r.atom).seq; 531 + child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k }; 534 + const list = children.get(at); 535 + if (list) list.push(child); 536 + else children.set(at, [child]); 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]); 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); 557 + if (list.length > 1) list.sort(order); 558 + for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n); 561 + while (stack.length) { 562 + const n = stack.pop()!; 563 + const by = deleters.get(n); 565 + if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by); 568 + visText.push(texts.get(n) ?? null); 570 + if (complete) seq.push(n); 573 + return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText }; 465 576 #attributes(path: string): FileAttrs { 466 577 const graph = this.graph; 467 578 // For each attribute, the highest-priority setter in the set wins. 468 579 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 }); 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, 469 595 for (const id of graph.eachAtomIn(path)) { 470 596 if (!this.#has(graph.atom(id).seq)) continue; 471 597 for (const a of graph.atom(id).attrs ?? []) { @@ -556,9 +682,9 @@
556 682 /** The projected text of a file ("" if it has no visible lines). */ 557 683 text(path: string): string { 558 684 if (this.#textCache?.path === path) return this.#textCache.text; 559 − const vis = this.#file(path).vis;
685 + const { vis, visText } = this.#file(path); 560 686 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]!); 562 688 const text = joinLines(lines); 563 689 this.#textCache = { path, text }; @@ -742,6 +868,7 @@
742 868 // headers are separate from their payload byte lengths below. 743 869 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES; 744 870 n += f.seq.byteLength + f.vis.byteLength; 871 + if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0); 745 872 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size; 746 873 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length; 747 874 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;