{"version":137,"agent":"codex-capacity-chair","message":"Page explicit child counts with bounded corruption checks","time":1791844187841,"timeIso":"2026-10-12T22:29:47.841Z","changes":4,"change":1284,"files":["src/engine/child-counts.ts","src/engine/graph.ts","src/engine/test/child-counts.test.ts","src/engine/test/state-source.test.ts"],"draft":null,"diff":[{"path":"src/engine/child-counts.ts","added":72,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/child-counts.ts\n@@ -0,0 +1,72 @@\n+import type { GraphStateStorage } from \"./state-source.ts\";\n+\n+const PAGE_SIZE = 256;\n+type Page = { format: 1; page: number; counts: number[]; digest: string };\n+\n+/** Two independent 32-bit checksums over page identity and contents. This\n+ * detects inconsistent storage corruption, not an adversarial coherent rewrite. */\n+function digest(page: number, counts: readonly number[]): string {\n+\tconst text = JSON.stringify([1, page, counts]);\n+\tlet a = 2166136261;\n+\tlet b = 5381;\n+\tfor (let i = 0; i < text.length; i++) {\n+\t\ta = Math.imul(a ^ text.charCodeAt(i), 16777619) >>> 0;\n+\t\tb = (Math.imul(b, 33) ^ text.charCodeAt(i)) >>> 0;\n+\t}\n+\treturn a.toString(16).padStart(8, \"0\") + b.toString(16).padStart(8, \"0\");\n+}\n+\n+/** Dense line-node counts. Graph append owns the enclosing transaction. */\n+export class ChildCounts {\n+\treadonly #storage: GraphStateStorage;\n+\tconstructor(storage: GraphStateStorage) {\n+\t\tthis.#storage = storage;\n+\t}\n+\t#read(page: number, total: number): Page {\n+\t\tconst value = this.#storage.read(\"ordered-child-counts\", String(page)) as Page | undefined;\n+\t\tconst expected = Math.min(PAGE_SIZE, total - page * PAGE_SIZE);\n+\t\tif (\n+\t\t\t!value ||\n+\t\t\tvalue.format !== 1 ||\n+\t\t\tvalue.page !== page ||\n+\t\t\t!Array.isArray(value.counts) ||\n+\t\t\texpected < 1 ||\n+\t\t\tvalue.counts.length !== expected ||\n+\t\t\tObject.keys(value.counts).length !== expected ||\n+\t\t\tvalue.counts.some((count) => !Number.isSafeInteger(count) || count < 0) ||\n+\t\t\tvalue.digest !== digest(page, value.counts)\n+\t\t)\n+\t\t\tthrow new Error(\"invalid ordered child count page\");\n+\t\treturn value;\n+\t}\n+\t#write(page: number, counts: number[]): void {\n+\t\tthis.#storage.write(\"ordered-child-counts\", String(page), {\n+\t\t\tformat: 1,\n+\t\t\tpage,\n+\t\t\tcounts,\n+\t\t\tdigest: digest(page, counts),\n+\t\t});\n+\t}\n+\tat(index: number, total: number): number {\n+\t\tif (!Number.isSafeInteger(index) || index < 0 || index >= total)\n+\t\t\tthrow new Error(\"ordered child count out of bounds\");\n+\t\treturn this.#read(Math.floor(index / PAGE_SIZE), total).counts[index % PAGE_SIZE]!;\n+\t}\n+\tappend(total: number): void {\n+\t\tconst page = Math.floor(total / PAGE_SIZE);\n+\t\tconst offset = total % PAGE_SIZE;\n+\t\tconst counts = offset === 0 ? [] : this.#read(page, total).counts;\n+\t\tif (offset === 0 && this.#storage.read(\"ordered-child-counts\", String(page)) !== undefined)\n+\t\t\tthrow new Error(\"unexpected existing ordered child count page\");\n+\t\tcounts.push(0);\n+\t\tthis.#write(page, counts);\n+\t}\n+\tincrement(index: number, total: number): void {\n+\t\tconst count = this.at(index, total);\n+\t\tif (count === Number.MAX_SAFE_INTEGER) throw new Error(\"ordered child count exhausted\");\n+\t\tconst page = Math.floor(index / PAGE_SIZE);\n+\t\tconst counts = this.#read(page, total).counts;\n+\t\tcounts[index % PAGE_SIZE] = count + 1;\n+\t\tthis.#write(page, counts);\n+\t}\n+}"},{"path":"src/engine/graph.ts","added":11,"removed":5,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -2,6 +2,7 @@\n // the codebase) are separate values; the graph only answers questions about\n // atoms and keeps indexes so those questions are cheap.\n \n+import { ChildCounts } from \"./child-counts.ts\";\n import {\n \tatomId,\n \tattrKey,\n@@ -254,6 +255,7 @@\n \n export class Graph {\n \treadonly #storage?: GraphStateStorage;\n+\treadonly #childCounts?: ChildCounts;\n \t#atoms: Atom[] = [];\n \t#lamport: number[] = [];\n \t// Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its\n@@ -293,6 +295,7 @@\n \t\t}\n \t\tif (options.lists) this.#lists = options.lists;\n \t\tthis.#storage = options.storage;\n+\t\tif (options.storage) this.#childCounts = new ChildCounts(options.storage);\n \t\tif (options.storage) {\n \t\t\tconst storage = options.storage;\n \t\t\tconst numbers = (name: string): NumberIndex => storedNumbers(storage, name);\n@@ -663,10 +666,11 @@\n \t*orderedChildrenN(code: number, after?: number): IterableIterator<number> {\n \t\tif (!this.#storage) throw new Error(\"ordered children require indexed storage\");\n \t\tconst index = new OrderedIndex(this.#storage, \"ordered-children\", String(code));\n-\t\tif (this.#storage.read(\"ordered-children\", \"format\") !== 1)\n+\t\tif (this.#storage.read(\"ordered-children\", \"format\") !== 2)\n \t\t\tthrow new Error(\"ordered children require fresh adoption\");\n-\t\tconst count = index.size;\n-\t\tif (count !== this.#runStartPages!.length(String(code))) throw new Error(\"ordered child index count mismatch\");\n+\t\tconst count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;\n+\t\tif ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))\n+\t\t\tthrow new Error(\"ordered child index count mismatch\");\n \t\tlet implicit: number | undefined;\n \t\tif (\n \t\t\tcode >= 0 &&\n@@ -967,9 +971,9 @@\n \t}\n \n \t#add(atom: Atom): void {\n-\t\tif (this.#storage && this.#storage.read(\"ordered-children\", \"format\") !== 1) {\n+\t\tif (this.#storage && this.#storage.read(\"ordered-children\", \"format\") !== 2) {\n \t\t\tif (this.#atoms.length !== 0) throw new Error(\"ordered children require fresh adoption\");\n-\t\t\tthis.#storage.write(\"ordered-children\", \"format\", 1);\n+\t\t\tthis.#storage.write(\"ordered-children\", \"format\", 2);\n \t\t}\n \n \t\tvalidateShape(atom);\n@@ -1069,6 +1073,7 @@\n \t\t\tconst file = this.#pathOf(run.file);\n \t\t\tlet parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);\n \t\t\tconst first = this.#lineTotal;\n+\t\t\tif (parent >= 0) this.#childCounts?.increment(parent, first);\n \t\t\tif (this.#storage)\n \t\t\t\tnew OrderedIndex(this.#storage, \"ordered-children\", String(parent)).insert(\n \t\t\t\t\torderedChildKey({\n@@ -1085,6 +1090,7 @@\n \t\t\telse pushOne(this.#runStarts, parent, first);\n \t\t\tfor (let i = 0; i < run.lines.length; i++) {\n \t\t\t\tconst n = this.#lineTotal;\n+\t\t\t\tthis.#childCounts?.append(n);\n \t\t\t\tthis.#lineAtom.push(seq);\n \t\t\t\tthis.#lineFile.push(file);\n \t\t\t\tthis.#lineParent.push(parent);"},{"path":"src/engine/test/child-counts.test.ts","added":79,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/child-counts.test.ts\n@@ -0,0 +1,79 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ChildCounts } from \"../child-counts.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"child counts cross pages, reopen and roll back with the canonical transaction\", () => {\n+\tconst source = new SqlState();\n+\ttry {\n+\t\tconst cache = new CachedStateStorage(source);\n+\t\tconst counts = new ChildCounts(cache);\n+\t\tfor (let n = 0; n < 513; n++) cache.transaction(() => counts.append(n));\n+\t\tcache.transaction(() => counts.increment(255, 513));\n+\t\tassert.equal(new ChildCounts(cache).at(255, 513), 1);\n+\t\tassert.equal(counts.at(256, 513), 0);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tcache.transaction(() => {\n+\t\t\t\t\tcounts.increment(255, 513);\n+\t\t\t\t\tcounts.append(513);\n+\t\t\t\t\tthrow new Error(\"rollback\");\n+\t\t\t\t}),\n+\t\t\t/rollback/,\n+\t\t);\n+\t\tassert.equal(counts.at(255, 513), 1);\n+\t\tassert.equal(counts.at(512, 513), 0);\n+\t\tassert.equal(cache.retainedEntries > 0, true);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});\n+\n+test(\"child counts reject missing, relocated, truncated and inconsistent zero-count pages\", () => {\n+\tconst source = new SqlState();\n+\ttry {\n+\t\tconst counts = new ChildCounts(source);\n+\t\tcounts.append(0);\n+\t\tcounts.append(1);\n+\t\tcounts.increment(0, 2);\n+\t\tconst original = source.read(\"ordered-child-counts\", \"0\") as Record<string, unknown>;\n+\t\tfor (const changed of [\n+\t\t\t{ ...original, counts: [0, 0] },\n+\t\t\t{ ...original, counts: [1] },\n+\t\t\t{ ...original, page: 1 },\n+\t\t\t{ ...original, format: 2 },\n+\t\t\t{ ...original, digest: \"invalid\" },\n+\t\t]) {\n+\t\t\tsource.write(\"ordered-child-counts\", \"0\", changed);\n+\t\t\tassert.throws(() => counts.at(0, 2), /invalid ordered child count page/);\n+\t\t}\n+\t\tsource.remove(\"ordered-child-counts\", \"0\");\n+\t\tassert.throws(() => counts.at(0, 2), /invalid ordered child count page/);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});\n+\n+test(\"graph rejects the previous ordered format and count corruption before empty-child shortcuts\", () => {\n+\tconst source = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\ntwo\\n\" });\n+\t\tconst graph = new Graph({ storage: source });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tassert.deepEqual([...graph.orderedChildrenN(0)], [1]);\n+\t\tsource.write(\"ordered-children\", \"format\", 1);\n+\t\tassert.throws(() => [...graph.orderedChildrenN(0)], /fresh adoption/);\n+\t\tsource.write(\"ordered-children\", \"format\", 2);\n+\t\tnew ChildCounts(source).increment(0, 2);\n+\t\tassert.throws(() => [...graph.orderedChildrenN(0)], /ordered child index count mismatch/);\n+\t\tconst page = source.read(\"ordered-child-counts\", \"0\") as { counts: number[] };\n+\t\tpage.counts[0] = 0;\n+\t\tsource.write(\"ordered-child-counts\", \"0\", page);\n+\t\tassert.throws(() => [...graph.orderedChildrenN(0)], /invalid ordered child count page/);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});"},{"path":"src/engine/test/state-source.test.ts","added":1,"removed":1,"diff":"--- a/src/engine/test/state-source.test.ts\n+++ b/src/engine/test/state-source.test.ts\n@@ -506,7 +506,7 @@\n \t\t\t() => new Graph({ storage }).add(oracle.draft({ edits: [{ file: \"a.txt\", old: \"one\", new: \"two\" }] })),\n \t\t\t/fresh adoption/,\n \t\t);\n-\t\tstorage.write(\"ordered-children\", \"format\", 1);\n+\t\tstorage.write(\"ordered-children\", \"format\", 2);\n \t\tconst parent = graph.startCodeOf(\"a.txt\")!;\n \t\tstorage.remove(\"ordered-children\", JSON.stringify([String(parent), \"meta\"]));\n \t\tassert.throws(() => [...graph.orderedChildrenN(parent)], /missing ordered index metadata/);"}],"ci":null}