Page explicit child counts with bounded corruption checks
of shared·codex-capacity-chair··Not checked
Version 136 · Files at version 137
4 files, 163 lines added, 6 removed.
--- /dev/null
+++ b/src/engine/child-counts.ts
@@ -0,0 +1,72 @@
1+import type { GraphStateStorage } from "./state-source.ts"; 4+type Page = { format: 1; page: number; counts: number[]; digest: string }; 6+/** Two independent 32-bit checksums over page identity and contents. This 7+ * detects inconsistent storage corruption, not an adversarial coherent rewrite. */ 8+function digest(page: number, counts: readonly number[]): string { 9+ const text = JSON.stringify([1, page, counts]); 12+ for (let i = 0; i < text.length; i++) { 13+ a = Math.imul(a ^ text.charCodeAt(i), 16777619) >>> 0; 14+ b = (Math.imul(b, 33) ^ text.charCodeAt(i)) >>> 0; 16+ return a.toString(16).padStart(8, "0") + b.toString(16).padStart(8, "0"); 19+/** Dense line-node counts. Graph append owns the enclosing transaction. */ 20+export class ChildCounts { 21+ readonly #storage: GraphStateStorage; 22+ constructor(storage: GraphStateStorage) { 23+ this.#storage = storage; 25+ #read(page: number, total: number): Page { 26+ const value = this.#storage.read("ordered-child-counts", String(page)) as Page | undefined; 27+ const expected = Math.min(PAGE_SIZE, total - page * PAGE_SIZE); 30+ value.format !== 1 || 31+ value.page !== page || 32+ !Array.isArray(value.counts) || 34+ value.counts.length !== expected || 35+ Object.keys(value.counts).length !== expected || 36+ value.counts.some((count) => !Number.isSafeInteger(count) || count < 0) || 37+ value.digest !== digest(page, value.counts) 39+ throw new Error("invalid ordered child count page"); 42+ #write(page: number, counts: number[]): void { 43+ this.#storage.write("ordered-child-counts", String(page), { 47+ digest: digest(page, counts), 50+ at(index: number, total: number): number { 51+ if (!Number.isSafeInteger(index) || index < 0 || index >= total) 52+ throw new Error("ordered child count out of bounds"); 53+ return this.#read(Math.floor(index / PAGE_SIZE), total).counts[index % PAGE_SIZE]!; 55+ append(total: number): void { 56+ const page = Math.floor(total / PAGE_SIZE); 57+ const offset = total % PAGE_SIZE; 58+ const counts = offset === 0 ? [] : this.#read(page, total).counts; 59+ if (offset === 0 && this.#storage.read("ordered-child-counts", String(page)) !== undefined) 60+ throw new Error("unexpected existing ordered child count page"); 62+ this.#write(page, counts); 64+ increment(index: number, total: number): void { 65+ const count = this.at(index, total); 66+ if (count === Number.MAX_SAFE_INTEGER) throw new Error("ordered child count exhausted"); 67+ const page = Math.floor(index / PAGE_SIZE); 68+ const counts = this.#read(page, total).counts; 69+ counts[index % PAGE_SIZE] = count + 1; 70+ this.#write(page, counts); --- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -2,6 +2,7 @@
22// the codebase) are separate values; the graph only answers questions about 33// atoms and keeps indexes so those questions are cheap. 5+import { ChildCounts } from "./child-counts.ts"; @@ -254,6 +255,7 @@
255256export class Graph { 256257 readonly #storage?: GraphStateStorage; 258+ readonly #childCounts?: ChildCounts; 257259 #atoms: Atom[] = []; 258260 #lamport: number[] = []; 259261 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its @@ -293,6 +295,7 @@
294296 if (options.lists) this.#lists = options.lists; 295297 this.#storage = options.storage; 298+ if (options.storage) this.#childCounts = new ChildCounts(options.storage); 296299 if (options.storage) { 297300 const storage = options.storage; 298301 const numbers = (name: string): NumberIndex => storedNumbers(storage, name); @@ -663,10 +666,11 @@
663666 *orderedChildrenN(code: number, after?: number): IterableIterator<number> { 664667 if (!this.#storage) throw new Error("ordered children require indexed storage"); 665668 const index = new OrderedIndex(this.#storage, "ordered-children", String(code)); 666− if (this.#storage.read("ordered-children", "format") !== 1)
669+ if (this.#storage.read("ordered-children", "format") !== 2) 667670 throw new Error("ordered children require fresh adoption"); 668− const count = index.size;
669− if (count !== this.#runStartPages!.length(String(code))) throw new Error("ordered child index count mismatch");
671+ const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size; 672+ if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code)))) 673+ throw new Error("ordered child index count mismatch"); 670674 let implicit: number | undefined; @@ -967,9 +971,9 @@
969973 #add(atom: Atom): void { 970− if (this.#storage && this.#storage.read("ordered-children", "format") !== 1) {
974+ if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) { 971975 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 972− this.#storage.write("ordered-children", "format", 1);
976+ this.#storage.write("ordered-children", "format", 2); 975979 validateShape(atom); @@ -1069,6 +1073,7 @@
10691073 const file = this.#pathOf(run.file); 10701074 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent); 10711075 const first = this.#lineTotal; 1076+ if (parent >= 0) this.#childCounts?.increment(parent, first); 10721077 if (this.#storage) 10731078 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert( 10741079 orderedChildKey({ @@ -1085,6 +1090,7 @@
10851090 else pushOne(this.#runStarts, parent, first); 10861091 for (let i = 0; i < run.lines.length; i++) { 10871092 const n = this.#lineTotal; 1093+ this.#childCounts?.append(n); 10881094 this.#lineAtom.push(seq); 10891095 this.#lineFile.push(file); 10901096 this.#lineParent.push(parent); --- /dev/null
+++ b/src/engine/test/child-counts.test.ts
@@ -0,0 +1,79 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ChildCounts } from "../child-counts.ts"; 4+import { Graph } from "../graph.ts"; 5+import { CachedStateStorage } from "../state-source.ts"; 6+import { Repo } from "./helpers.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("child counts cross pages, reopen and roll back with the canonical transaction", () => { 10+ const source = new SqlState(); 12+ const cache = new CachedStateStorage(source); 13+ const counts = new ChildCounts(cache); 14+ for (let n = 0; n < 513; n++) cache.transaction(() => counts.append(n)); 15+ cache.transaction(() => counts.increment(255, 513)); 16+ assert.equal(new ChildCounts(cache).at(255, 513), 1); 17+ assert.equal(counts.at(256, 513), 0); 20+ cache.transaction(() => { 21+ counts.increment(255, 513); 23+ throw new Error("rollback"); 27+ assert.equal(counts.at(255, 513), 1); 28+ assert.equal(counts.at(512, 513), 0); 29+ assert.equal(cache.retainedEntries > 0, true); 35+test("child counts reject missing, relocated, truncated and inconsistent zero-count pages", () => { 36+ const source = new SqlState(); 38+ const counts = new ChildCounts(source); 41+ counts.increment(0, 2); 42+ const original = source.read("ordered-child-counts", "0") as Record<string, unknown>; 43+ for (const changed of [ 44+ { ...original, counts: [0, 0] }, 45+ { ...original, counts: [1] }, 46+ { ...original, page: 1 }, 47+ { ...original, format: 2 }, 48+ { ...original, digest: "invalid" }, 50+ source.write("ordered-child-counts", "0", changed); 51+ assert.throws(() => counts.at(0, 2), /invalid ordered child count page/); 53+ source.remove("ordered-child-counts", "0"); 54+ assert.throws(() => counts.at(0, 2), /invalid ordered child count page/); 60+test("graph rejects the previous ordered format and count corruption before empty-child shortcuts", () => { 61+ const source = new SqlState(); 63+ const repo = Repo.init({ "a.txt": "one\ntwo\n" }); 64+ const graph = new Graph({ storage: source }); 65+ graph.add(repo.graph.atom("a0")); 66+ assert.deepEqual([...graph.orderedChildrenN(0)], [1]); 67+ source.write("ordered-children", "format", 1); 68+ assert.throws(() => [...graph.orderedChildrenN(0)], /fresh adoption/); 69+ source.write("ordered-children", "format", 2); 70+ new ChildCounts(source).increment(0, 2); 71+ assert.throws(() => [...graph.orderedChildrenN(0)], /ordered child index count mismatch/); 72+ const page = source.read("ordered-child-counts", "0") as { counts: number[] }; 74+ source.write("ordered-child-counts", "0", page); 75+ assert.throws(() => [...graph.orderedChildrenN(0)], /invalid ordered child count page/); --- a/src/engine/test/state-source.test.ts
+++ b/src/engine/test/state-source.test.ts
@@ -506,7 +506,7 @@
506506 () => new Graph({ storage }).add(oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "two" }] })), 509− storage.write("ordered-children", "format", 1);
509+ storage.write("ordered-children", "format", 2); 510510 const parent = graph.startCodeOf("a.txt")!; 511511 storage.remove("ordered-children", JSON.stringify([String(parent), "meta"])); 512512 assert.throws(() => [...graph.orderedChildrenN(parent)], /missing ordered index metadata/);