Bound persisted no-move layout with ordered successor traversal
of shared·codex-capacity-chair·
Version 130 · Files at version 131
5 files, 430 lines added, 10 removed.
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -15,6 +15,7 @@
18+import { OrderedIndex, orderedChildKey } from "./ordered-index.ts"; 1920 type GraphStateStorage, @@ -631,6 +632,46 @@
631632 else yield* listOf(this.#runStarts.get(code)); 635+ get hasOrderedChildren(): boolean { 636+ return this.#storage !== undefined; 638+ #childPriority(n: number): string { 639+ const seq = this.writerSeqOf(n); 640+ return orderedChildKey({ 642+ replaces: this.replacesN(n) ? 1 : 0, 643+ lamport: this.lamportOfSeq(seq), 648+ /** Persistent layout order with a strict successor cursor; moves are separate. */ 649+ *orderedChildrenN(code: number, after?: number): IterableIterator<number> { 650+ if (!this.#storage) throw new Error("ordered children require indexed storage"); 651+ const index = new OrderedIndex(this.#storage, "ordered-children", String(code)); 652+ if (this.#storage.read("ordered-children", "format") !== 1) 653+ throw new Error("ordered children require fresh adoption"); 654+ if (index.size !== this.#runStartPages!.length(String(code))) throw new Error("ordered child index count mismatch"); 655+ const cursor = after === undefined ? undefined : this.#childPriority(after); 656+ let implicit: number | undefined; 659+ code + 1 < this.#lineTotal && 660+ this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) && 661+ this.#lineParent.at(code + 1) === code 663+ implicit = code + 1; 664+ if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined; 665+ for (const n of index.values(cursor)) { 666+ if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) { 668+ implicit = undefined; 672+ if (implicit !== undefined) yield implicit; 634675 replacesN(n: number): boolean { 635676 return this.#replacing.at(n) === 1; @@ -904,6 +945,11 @@
906947 #add(atom: Atom): void { 948+ if (this.#storage && this.#storage.read("ordered-children", "format") !== 1) { 949+ if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 950+ this.#storage.write("ordered-children", "format", 1); 907953 validateShape(atom); 908954 const seq = this.#atoms.length; 909955 const bad = (why: string): never => { @@ -1001,6 +1047,18 @@
10011047 const file = this.#pathOf(run.file); 10021048 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent); 10031049 const first = this.#lineTotal; 1051+ new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert( 1054+ replaces: deletes?.has(run.parent) ? 1 : 0, 1057+ k: first - this.#lineBase[seq]!, 10041062 if (this.#runStartPages) this.#runStartPages.append(String(parent), first); 10051063 else pushOne(this.#runStarts, parent, first); 10061064 for (let i = 0; i < run.lines.length; i++) { --- /dev/null
+++ b/src/engine/ordered-index.ts
@@ -0,0 +1,152 @@
1+import type { GraphStateStorage } from "./state-source.ts"; 4+type Leaf = { prefix: string; value: number }; 5+type Branch = { prefix: string; children: (number | null)[] }; 6+type Node = Leaf | Branch; 7+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 9+/** Exact existing layout priority, encoded for ascending lexical traversal. */ 10+export function orderedChildKey(child: { 17+ if (![child.lamport, child.seq, child.k, child.n].every(safe) || ![0, 1].includes(child.replaces)) 18+ throw new Error("invalid ordered child priority"); 19+ const hex = (n: number) => n.toString(16).padStart(14, "0"); 20+ return `${1 - child.replaces}${hex(Number.MAX_SAFE_INTEGER - child.lamport)}${hex(Number.MAX_SAFE_INTEGER - child.seq)}${hex(child.k)}${hex(child.n)}`; 23+/** Compressed radix tree with at most 16 references per node and 57 levels. 24+ * No collection scan or history-sized sibling array is needed. Values are 25+ * immutable numeric identities; the caller owns namespace isolation. */ 26+export class OrderedIndex { 27+ readonly #storage: GraphStateStorage; 28+ readonly #collection: string; 29+ readonly #group: string; 30+ constructor(storage: GraphStateStorage, collection: string, group: string) { 31+ this.#storage = storage; 32+ this.#collection = collection; 35+ #key(id: number | "meta"): string { 36+ return JSON.stringify([this.#group, id]); 38+ #next(): number | undefined { 39+ const meta = this.#storage.read(this.#collection, this.#key("meta")) as 40+ | { format?: unknown; next?: unknown; count?: unknown } 42+ if (meta === undefined) { 43+ if (this.#storage.read(this.#collection, this.#key(0)) !== undefined) 44+ throw new Error("missing ordered index metadata"); 48+ meta?.format !== 1 || 53+ meta.count > meta.next 55+ throw new Error("invalid ordered index metadata"); 59+ if (this.#next() === undefined) return 0; 60+ return (this.#storage.read(this.#collection, this.#key("meta")) as { count: number }).count; 62+ #write(id: number, node: Node): void { 63+ this.#storage.write(this.#collection, this.#key(id), node); 65+ #read(id: number, expected: string): Node { 66+ const node = this.#storage.read(this.#collection, this.#key(id)) as Node | undefined; 69+ typeof node.prefix !== "string" || 70+ !/^[0-9a-f]*$/.test(node.prefix) || 71+ node.prefix.length > WIDTH || 72+ !node.prefix.startsWith(expected) 74+ throw new Error("invalid ordered index node"); 75+ if ("value" in node) { 76+ if (node.prefix.length !== WIDTH || !safe(node.value) || "children" in node) 77+ throw new Error("invalid ordered index leaf"); 79+ node.prefix.length >= WIDTH || 80+ !Array.isArray(node.children) || 81+ node.children.length !== 16 || 82+ !node.children.every((id) => id === null || safe(id)) || 83+ node.children.filter((id) => id !== null).length < 2 85+ throw new Error("invalid ordered index branch"); 89+ /** Nested host transactions must roll back all allocation, split and link writes. */ 90+ insert(key: string, value: number): void { 91+ if (key.length !== WIDTH || !/^[0-9a-f]+$/.test(key) || !safe(value)) 92+ throw new Error("invalid ordered index entry"); 93+ this.#storage.transaction(() => { 94+ let next = this.#next(); 95+ let count = this.size; 96+ if (next === undefined) { 97+ this.#write(0, { prefix: key, value }); 98+ this.#storage.write(this.#collection, this.#key("meta"), { format: 1, next: 1, count: 1 }); 101+ const allocate = (node: Node): number => { 102+ if (next! >= Number.MAX_SAFE_INTEGER) throw new Error("ordered index identity exhausted"); 104+ this.#write(id, node); 107+ const add = (id: number, expected: string): void => { 108+ const node = this.#read(id, expected); 110+ while (common < node.prefix.length && node.prefix[common] === key[common]) common++; 111+ if (common < node.prefix.length) { 113+ const children: (number | null)[] = Array(16).fill(null); 114+ children[parseInt(node.prefix[common]!, 16)] = allocate(node); 115+ children[parseInt(key[common]!, 16)] = allocate({ prefix: key, value }); 116+ this.#write(id, { prefix: key.slice(0, common), children }); 117+ } else if ("value" in node) { 118+ if (node.value !== value) throw new Error("ordered index key reused"); 120+ const digit = parseInt(key[common]!, 16); 121+ const child = node.children[digit]!; 122+ if (child === null) { 124+ node.children[digit] = allocate({ prefix: key, value }); 125+ this.#write(id, node); 126+ } else add(child, node.prefix + key[common]); 130+ this.#storage.write(this.#collection, this.#key("meta"), { format: 1, next, count }); 133+ *values(after?: string): IterableIterator<number> { 134+ if (after !== undefined && (after.length !== WIDTH || !/^[0-9a-f]+$/.test(after))) 135+ throw new Error("invalid ordered index cursor"); 136+ if (this.#next() === undefined) return; 137+ const walk = function* (this: OrderedIndex, id: number, expected: string): IterableIterator<number> { 138+ if (after !== undefined && expected < after.slice(0, expected.length)) return; 139+ const node = this.#read(id, expected); 140+ if (after !== undefined && node.prefix < after.slice(0, node.prefix.length)) return; 141+ if ("value" in node) { 142+ if (after === undefined || node.prefix > after) yield node.value; 145+ for (let digit = 0; digit < 16; digit++) { 146+ const child = node.children[digit]!; 147+ if (child !== null) yield* walk.call(this, child, node.prefix + digit.toString(16)); 150+ yield* walk.call(this, 0, ""); --- /dev/null
+++ b/src/engine/test/ordered-index.test.ts
@@ -0,0 +1,101 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { OrderedIndex, orderedChildKey } from "../ordered-index.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("ordered children retain priority across storage reopen and transactional split failures", () => { 7+ const storage = new SqlState(); 9+ const children = Array.from({ length: 513 }, (_, n) => ({ 13+ seq: Math.floor(n / 8), 16+ const expected = [...children] 17+ .sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k || a.n - b.n) 19+ const index = new OrderedIndex(storage, "ordered", "parent"); 20+ for (const child of [...children].reverse()) index.insert(orderedChildKey(child), child.n); 21+ assert.deepEqual([...new OrderedIndex(storage, "ordered", "parent").values()], expected); 23+ assert.equal(new OrderedIndex(storage, "ordered", "parent").values().next().value, expected[0]); 24+ assert.ok(storage.reads <= 59); 25+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 26+ const child = { n: 514, replaces: 1, lamport: Number.MAX_SAFE_INTEGER, seq: Number.MAX_SAFE_INTEGER, k: 0 }; 29+ for (let offset = 1; offset < 12; offset++) { 30+ storage.failWrite = storage.writes + offset; 32+ index.insert(orderedChildKey(child), child.n); 36+ assert.match(String(error), /injected/); 38+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 41+ assert.ok(complete && failed >= 3); 42+ storage.failWrite = Infinity; 43+ assert.deepEqual([...new OrderedIndex(storage, "ordered", "parent").values()], [514, ...expected]); 44+ index.insert(orderedChildKey(child), child.n); 45+ assert.deepEqual([...index.values()], [514, ...expected]); 46+ assert.throws(() => index.insert(orderedChildKey(child), 999), /reused/); 47+ assert.deepEqual([...new OrderedIndex(storage, "ordered", "other").values()], []); 53+test("ordered index refuses malformed state and cycles instead of following them", () => { 54+ const storage = new SqlState(); 56+ const index = new OrderedIndex(storage, "ordered", "parent"); 57+ assert.throws(() => orderedChildKey({ n: 0, replaces: 2, lamport: 0, seq: 0, k: 0 }), /priority/); 58+ assert.throws(() => index.insert("bad", 0), /entry/); 59+ index.insert("0".repeat(57), 0); 60+ index.insert("1".repeat(57), 1); 61+ const node = storage.read("ordered", JSON.stringify(["parent", 0])) as { 63+ children: (number | null)[]; 65+ node.children[0] = 0; 66+ storage.write("ordered", JSON.stringify(["parent", 0]), node); 67+ assert.throws(() => [...index.values()], /node/); 73+test("ordered successor cursors skip earlier subtrees and retain tied-priority order", () => { 74+ const storage = new SqlState(); 76+ const index = new OrderedIndex(storage, "ordered", "parent"); 77+ const children = Array.from({ length: 1025 }, (_, n) => ({ 81+ seq: Math.floor(n / 8), 84+ for (const child of children) index.insert(orderedChildKey(child), child.n); 85+ const ordered = [...children].sort((a, b) => orderedChildKey(a).localeCompare(orderedChildKey(b))); 86+ for (const position of [0, 1, 255, 511, 1023, 1024]) { 87+ const cursor = orderedChildKey(ordered[position]!); 89+ const first = new OrderedIndex(storage, "ordered", "parent").values(cursor).next().value; 90+ assert.equal(first, ordered[position + 1]?.n); 91+ assert.ok(storage.reads < 60, "first successor must skip earlier history"); 93+ [...index.values(cursor)], 94+ ordered.slice(position + 1).map((child) => child.n), 97+ assert.throws(() => [...index.values("bad")], /cursor/); --- a/src/engine/test/state-source.test.ts
+++ b/src/engine/test/state-source.test.ts
@@ -419,3 +419,73 @@
419419 storage.db.close(); 423+test("persistent layout uses ordered successors without retaining deep or wide history frontiers", () => { 424+ for (const shape of ["deep", "wide"] as const) { 425+ const storage = new SqlState(); 427+ const oracle = Repo.init({ 428+ "a.txt": shape === "deep" ? Array.from({ length: 1024 }, (_, n) => `line ${n}\n`).join("") : "base\n", 430+ if (shape === "wide") { 431+ const draft = oracle.draft({ edits: [{ file: "a.txt", old: "base", new: "branch" }] }); 432+ for (let seq = 1; seq <= 256; seq++) { 433+ const atom = { ...draft, id: `a${seq}`, seq }; 434+ oracle.graph.add(atom); 435+ oracle.shared.add(atom.id); 438+ const before = oracle.view().text("a.txt"); 439+ oracle.edit({ edits: [{ file: "a.txt", old: before, new: "live\n" }] }); 440+ const graph = new Graph({ storage }); 441+ for (const id of oracle.shared) graph.add(oracle.graph.atom(id)); 442+ const reopened = new Graph({ storage }); 443+ reopened.eachChildN = () => { 444+ throw Error("unordered child collection forbidden"); 446+ reopened.childrenN = () => { 447+ throw Error("materialized child collection forbidden"); 449+ const original = reopened.orderedChildrenN.bind(reopened); 452+ reopened.orderedChildrenN = function* (parent: number, after?: number) { 454+ maximum = Math.max(maximum, active); 456+ yield* original(parent, after); 461+ const view = new View(reopened, new StableOverlaySet(oracle.shared)); 462+ assert.equal(view.text("a.txt"), "live\n"); 463+ assert.equal(active, 0); 464+ assert.equal(maximum, 1, "no ordered iterator retained per historical ancestor"); 465+ assert.deepEqual(view.sequence("a.txt"), oracle.view().sequence("a.txt")); 472+test("ordered layout refuses missing format or child metadata instead of dropping history", () => { 473+ const storage = new SqlState(); 475+ const oracle = Repo.init({ "a.txt": "one\n" }); 476+ const graph = new Graph({ storage }); 477+ graph.add(oracle.graph.atom("a0")); 478+ storage.remove("ordered-children", "format"); 479+ assert.throws(() => new View(new Graph({ storage }), new StableOverlaySet(["a0"])).text("a.txt"), /fresh adoption/); 481+ () => new Graph({ storage }).add(oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "two" }] })), 484+ storage.write("ordered-children", "format", 1); 485+ const parent = graph.startCodeOf("a.txt")!; 486+ storage.remove("ordered-children", JSON.stringify([String(parent), "meta"])); 487+ assert.throws(() => [...graph.orderedChildrenN(parent)], /missing ordered index metadata/); --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -346,6 +346,53 @@
349+ /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */ 350+ *#layoutNodes(start: number): IterableIterator<number> { 351+ const graph = this.graph; 352+ if (graph.hasOrderedChildren && !this.#hasMoves) { 353+ const first = (parent: number, after?: number): number | undefined => { 354+ for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n; 357+ let n = first(start); 358+ while (n !== undefined) { 360+ const child = first(n); 361+ if (child !== undefined) { 367+ const parent = graph.parentCodeOf(previous); 368+ const sibling = first(parent, previous); 369+ if (sibling !== undefined) { 373+ if (parent === start) { 377+ if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry"); 383+ const stack: number[] = []; 384+ const push = (parent: number): void => { 385+ const children = this.#children(parent); 386+ for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n); 389+ while (stack.length) { 390+ const n = stack.pop()!; 349396 /** Lay out one file: its line tree from the set's atoms, linearized. */ 350397 #layout(path: string, complete: boolean): FileState { 351398 const graph = this.graph; @@ -363,17 +410,10 @@
363410 const seq: number[] = []; 364411 const vis: number[] = []; 365412 const deletedBy = new Map<number, readonly number[]>(); 366− // Depth-first, iteratively (a file of n lines can be a chain n deep).
367− const stack: number[] = [];
368− const pushChildren = (code: number): void => {
369− const list = this.#children(code);
370− for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
371− };
372414 const start = graph.startCodeOf(path); 373− if (start !== undefined) pushChildren(start);
374415 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b; 375− while (stack.length > 0) {
376− const n = stack.pop()!;
416+ for (const n of start === undefined ? [] : this.#layoutNodes(start)) { 377417 let deleted = false; 378418 const by: number[] = []; 379419 for (const deleter of graph.eachDeleterSeqOf(n)) { @@ -386,7 +426,6 @@
386426 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by); 387427 } else vis.push(n); 388428 if (complete) seq.push(n); 389− pushChildren(n);
391430 const attrs: FileAttrs = { 392431 exists: setters.get("exists")?.value === "1",