{"draft":null,"from":215,"to":318,"files":[{"path":"src/engine/graph.ts","added":361,"removed":91,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -21,12 +21,14 @@\n import { withProjectionScratch } from \"./projection-scratch.ts\";\n import {\n \ttype GraphStateStorage,\n+\treadonlyPagedArray,\n \treadonlyStoredArray,\n \ttype StateMap,\n \tstoredArray,\n \tstoredLists,\n \tstoredMap,\n \tstoredNumbers,\n+\twritePagedArray,\n } from \"./state-source.ts\";\n import { StoredText } from \"./stored-text.ts\";\n import {\n@@ -262,7 +264,41 @@\n export type PackedDelete = [number, number];\n /** An attribute set on a file: [seq, name, value]. */\n export type PackedAttr = [number, string, string | null];\n+/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */\n+export type PackedCrossing = [number, number];\n+\n+/**\n+ * A file's packed history decoded, without texts (Graph.packedHistory): PackedLine's five numbers per line, then\n+ * PackedDelete's two per delete and PackedCrossing's two per crossing, each list flat.\n+ */\n+export interface PackedHistory {\n+\treadonly lines: ArrayLike<number>;\n+\treadonly deletes: ArrayLike<number>;\n+\treadonly crossings: ArrayLike<number>;\n+}\n+\n+/**\n+ * Bytes of decoded file histories a stored graph keeps between layouts (abso Capacity). Every view of a file read its\n+ * whole history from pages: compare lays each file out once per side, collisions once per draft touching it, and a\n+ * file whose lines moved in from another read that one's history too (abso's worker files, split out of index.ts).\n+ * abso's index.ts, 46,000 lines of history, takes about 1 MB.\n+ */\n+export const PACKED_HISTORY_BUDGET = 4_000_000;\n+\n+/** Numbers packed flat: 4 bytes each while they fit in 32 bits, else 8. */\n+function packNumbers(rows: Iterable<readonly number[]>): Int32Array | Float64Array {\n+\tconst flat: number[] = [];\n+\tlet small = true;\n+\tfor (const row of rows)\n+\t\tfor (const value of row) {\n+\t\t\tif ((value | 0) !== value) small = false;\n+\t\t\tflat.push(value);\n+\t\t}\n+\treturn small ? Int32Array.from(flat) : Float64Array.from(flat);\n+}\n const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);\n+/** At most this many path names kept in memory (Graph.#pathName). */\n+const PATH_NAMES = 4096;\n /** Lines longer than this aren't packed with their file; their text is read on its own. */\n const PACKED_TEXT = 4096;\n \n@@ -271,6 +307,18 @@\n \treadonly #childCounts?: ChildCounts;\n \t#atoms: Atom[] = [];\n \t#lamport: number[] = [];\n+\t/**\n+\t * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)\n+\t * keeps that; the choice is made when first needed, so opening reads nothing.\n+\t */\n+\t#lamportPaged: ReturnType<typeof storedNumbers> | undefined;\n+\t#lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;\n+\tget #lamportPages(): ReturnType<typeof storedNumbers> | null {\n+\t\tif (this.#lamportPagesKnown === undefined)\n+\t\t\tthis.#lamportPagesKnown =\n+\t\t\t\tthis.#lamportPaged && this.#storage!.read(\"lamport:meta\", \"length\") === undefined ? this.#lamportPaged : null;\n+\t\treturn this.#lamportPagesKnown;\n+\t}\n \t// Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its\n \t// atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a\n \t// path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only\n@@ -339,7 +387,7 @@\n \t\t\t\tinsertionFormat?: 1;\n \t\t\t\tinsertionRuns?: string;\n \t\t\t\ttextFormat?: 1;\n-\t\t\t\tlistFormat?: 1;\n+\t\t\t\tlistFormat?: 1 | 2;\n \t\t\t\tlistCount?: number;\n \t\t\t\tlists?: Partial<Record<(typeof listFields)[number], string>>;\n \t\t\t\tatom: Atom;\n@@ -351,9 +399,9 @@\n \t\t\t\t\tconst encoded = value as unknown as Partial<EncodedAtom>;\n \t\t\t\t\tif (encoded.textFormat !== undefined && encoded.textFormat !== 1)\n \t\t\t\t\t\tthrow Error(\"invalid stored atom text format\");\n-\t\t\t\t\tif (encoded.listFormat !== undefined && encoded.listFormat !== 1)\n+\t\t\t\t\tif (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)\n \t\t\t\t\t\tthrow Error(\"invalid stored atom list format\");\n-\t\t\t\t\tif (encoded.listFormat === 1) {\n+\t\t\t\t\tif (encoded.listFormat === 1 || encoded.listFormat === 2) {\n \t\t\t\t\t\tif (\n \t\t\t\t\t\t\t!encoded.lists ||\n \t\t\t\t\t\t\ttypeof encoded.lists !== \"object\" ||\n@@ -368,7 +416,10 @@\n \t\t\t\t\tif (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)\n \t\t\t\t\t\tthrow Error(\"invalid stored insertion format\");\n \t\t\t\t\tconst atom =\n-\t\t\t\t\t\tencoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1\n+\t\t\t\t\t\tencoded.textFormat === 1 ||\n+\t\t\t\t\t\tencoded.listFormat === 1 ||\n+\t\t\t\t\t\tencoded.listFormat === 2 ||\n+\t\t\t\t\t\tencoded.insertionFormat === 1\n \t\t\t\t\t\t\t? encoded.atom!\n \t\t\t\t\t\t\t: value;\n \t\t\t\t\tif (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))\n@@ -419,7 +470,11 @@\n \t\t\t\t\t\t\tif (encoded.insertionFormat === 1) {\n \t\t\t\t\t\t\t\tconst collection = `atom-inserts:${atom.seq}`;\n \t\t\t\t\t\t\t\tinserts = readonlyStoredArray(storage, collection, (raw, index) => {\n-\t\t\t\t\t\t\t\t\tconst run = raw as { file: string; parent: string; lines: string };\n+\t\t\t\t\t\t\t\t\tconst run = raw as {\n+\t\t\t\t\t\t\t\t\t\tfile: string;\n+\t\t\t\t\t\t\t\t\t\tparent: string;\n+\t\t\t\t\t\t\t\t\t\tlines: string;\n+\t\t\t\t\t\t\t\t\t};\n \t\t\t\t\t\t\t\t\tconst lines = `${collection}:lines:${index}`;\n \t\t\t\t\t\t\t\t\tif (run.lines !== lines || typeof run.file !== \"string\" || typeof run.parent !== \"string\")\n \t\t\t\t\t\t\t\t\t\tthrow Error(\"invalid stored insertion run\");\n@@ -448,13 +503,18 @@\n \t\t\t\t\t\t(author) => author,\n \t\t\t\t\t\ttext,\n \t\t\t\t\t);\n-\t\t\t\t\tif (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);\n+\t\t\t\t\tif (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)\n+\t\t\t\t\t\treturn streamed(frozen);\n \t\t\t\t\tconst result = { ...frozen };\n \t\t\t\t\tif (encoded.insertionFormat === 1) {\n \t\t\t\t\t\tconst collection = `atom-inserts:${atom.seq}`;\n \t\t\t\t\t\tif (encoded.insertionRuns !== collection) throw Error(\"invalid stored insertion reference\");\n \t\t\t\t\t\tconst inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {\n-\t\t\t\t\t\t\tconst run = raw as { file: string; parent: InsertRun[\"parent\"]; lines: string };\n+\t\t\t\t\t\t\tconst run = raw as {\n+\t\t\t\t\t\t\t\tfile: string;\n+\t\t\t\t\t\t\t\tparent: InsertRun[\"parent\"];\n+\t\t\t\t\t\t\t\tlines: string;\n+\t\t\t\t\t\t\t};\n \t\t\t\t\t\t\tconst lines = `${collection}:lines:${index}`;\n \t\t\t\t\t\t\tif (run.lines !== lines || typeof run.file !== \"string\" || typeof run.parent !== \"string\")\n \t\t\t\t\t\t\t\tthrow Error(\"invalid stored insertion run\");\n@@ -471,14 +531,24 @@\n \t\t\t\t\t\t\t\t}),\n \t\t\t\t\t\t\t});\n \t\t\t\t\t\t});\n-\t\t\t\t\t\tObject.defineProperty(result, \"inserts\", { value: inserts, enumerable: true });\n+\t\t\t\t\t\tObject.defineProperty(result, \"inserts\", {\n+\t\t\t\t\t\t\tvalue: inserts,\n+\t\t\t\t\t\t\tenumerable: true,\n+\t\t\t\t\t\t});\n \t\t\t\t\t}\n \t\t\t\t\tfor (const field of listFields) {\n \t\t\t\t\t\tconst collection = encoded.lists?.[field];\n \t\t\t\t\t\tif (collection === undefined) continue;\n \t\t\t\t\t\tif (typeof collection !== \"string\" || collection !== `atom-list:${atom.seq}:${field}`)\n \t\t\t\t\t\t\tthrow Error(\"invalid stored atom list reference\");\n-\t\t\t\t\t\tObject.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });\n+\t\t\t\t\t\tconst list =\n+\t\t\t\t\t\t\tencoded.listFormat === 2\n+\t\t\t\t\t\t\t\t? readonlyPagedArray(storage, collection)\n+\t\t\t\t\t\t\t\t: readonlyStoredArray(storage, collection);\n+\t\t\t\t\t\tObject.defineProperty(result, field, {\n+\t\t\t\t\t\t\tvalue: list,\n+\t\t\t\t\t\t\tenumerable: true,\n+\t\t\t\t\t\t});\n \t\t\t\t\t}\n \t\t\t\t\treturn streamed(Object.freeze(result));\n \t\t\t\t},\n@@ -488,9 +558,9 @@\n \t\t\t\t\tfor (const field of listFields) {\n \t\t\t\t\t\tconst values = input[field];\n \t\t\t\t\t\tif (!values || values.length <= 256) continue;\n+\t\t\t\t\t\t// 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value.\n \t\t\t\t\t\tconst collection = `atom-list:${input.seq}:${field}`;\n-\t\t\t\t\t\tconst saved = storedArray<unknown>(storage, collection);\n-\t\t\t\t\t\tfor (const value of values) saved.push(value);\n+\t\t\t\t\t\twritePagedArray(storage, collection, values);\n \t\t\t\t\t\tlists[field] = collection;\n \t\t\t\t\t\tObject.defineProperty(atom, field, { value: [], enumerable: true });\n \t\t\t\t\t}\n@@ -516,17 +586,21 @@\n \t\t\t\t\t\t\t\t\tlines.push({ text });\n \t\t\t\t\t\t\t\t} else lines.push(line);\n \t\t\t\t\t\t\t}\n-\t\t\t\t\t\t\truns.push({ file: run.file, parent: run.parent, lines: lineCollection });\n+\t\t\t\t\t\t\truns.push({\n+\t\t\t\t\t\t\t\tfile: run.file,\n+\t\t\t\t\t\t\t\tparent: run.parent,\n+\t\t\t\t\t\t\t\tlines: lineCollection,\n+\t\t\t\t\t\t\t});\n \t\t\t\t\t\t}\n \t\t\t\t\t\treturn {\n \t\t\t\t\t\t\tinsertionFormat: 1,\n \t\t\t\t\t\t\tinsertionRuns: collection,\n-\t\t\t\t\t\t\t...(hasLists ? { listFormat: 1, listCount, lists } : {}),\n+\t\t\t\t\t\t\t...(hasLists ? { listFormat: 2, listCount, lists } : {}),\n \t\t\t\t\t\t\tatom: { ...atom, inserts: [] },\n \t\t\t\t\t\t};\n \t\t\t\t\t}\n \t\t\t\t\tif (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))\n-\t\t\t\t\t\treturn hasLists ? { listFormat: 1, listCount, lists, atom } : atom;\n+\t\t\t\t\t\treturn hasLists ? { listFormat: 2, listCount, lists, atom } : atom;\n \t\t\t\t\tlet index = 0;\n \t\t\t\t\tconst inserts = atom.inserts.map((run) => ({\n \t\t\t\t\t\t...run,\n@@ -539,12 +613,13 @@\n \t\t\t\t\t}));\n \t\t\t\t\treturn {\n \t\t\t\t\t\ttextFormat: 1,\n-\t\t\t\t\t\t...(hasLists ? { listFormat: 1, listCount, lists } : {}),\n+\t\t\t\t\t\t...(hasLists ? { listFormat: 2, listCount, lists } : {}),\n \t\t\t\t\t\tatom: { ...atom, inserts },\n \t\t\t\t\t};\n \t\t\t\t},\n \t\t\t);\n \t\t\tthis.#lamport = storedArray(storage, \"lamport\");\n+\t\t\tthis.#lamportPaged = storedNumbers(storage, \"lamport-pages\");\n \t\t\tthis.#lineBase = storedArray(storage, \"line-base\");\n \t\t\tthis.#paths = storedArray(storage, \"paths\");\n \t\t\tthis.#movers = storedArray(storage, \"movers\");\n@@ -561,7 +636,10 @@\n \t\t\t\t\"line-text\",\n \t\t\t\t(value) => {\n \t\t\t\t\tif (typeof value === \"string\") return value;\n-\t\t\t\t\tconst reference = value as unknown as { format: number; text: string };\n+\t\t\t\t\tconst reference = value as unknown as {\n+\t\t\t\t\t\tformat: number;\n+\t\t\t\t\t\ttext: string;\n+\t\t\t\t\t};\n \t\t\t\t\tif (reference?.format !== 1 || typeof reference.text !== \"string\") throw Error(\"invalid long line reference\");\n \t\t\t\t\treturn longText.read(reference.text);\n \t\t\t\t},\n@@ -585,6 +663,7 @@\n \t\t\tthis.#dependentsPages = storedLists<AtomId>(storage, \"dependents\");\n \t\t\tthis.#resolversPages = storedLists<AtomId>(storage, \"resolvers\");\n \t\t\tthis.#togetherPages = storedLists<TogetherLink>(storage, \"together\");\n+\t\t\tthis.#reasonsInPages = storedLists<AtomId>(storage, \"reasons-in\");\n \t\t\tthis.#fileAtomPages = storedLists<AtomId>(storage, \"file-atoms\");\n \t\t\tthis.#runStartPages = storedLists<number>(storage, \"run-starts\", (key) =>\n \t\t\t\tJSON.stringify([\"number\", Number(key)]),\n@@ -599,13 +678,16 @@\n \t\t\tthis.#fileTexts = storedLists<string | null>(storage, \"file-texts\");\n \t\t\tthis.#fileDeletes = storedLists<PackedDelete>(storage, \"file-deletes\");\n \t\t\tthis.#fileAttrs = storedLists<PackedAttr>(storage, \"file-attrs\");\n+\t\t\tthis.#fileCrossings = storedLists<PackedCrossing>(storage, \"file-crossings\");\n \t\t\tthis.#packFiles = options.packFiles ?? true;\n \t\t}\n \t}\n \n \t// Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------\n \t// For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its\n-\t// text, every delete of one of those lines ([n, deleter seq]), and every attribute set on it ([seq, name, value]).\n+\t// text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and\n+\t// every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,\n+\t// so a run written while its parent was moved elsewhere lays out wherever the parent is.\n \t// 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\n \t// a fresh adoption on; a graph adopted before has none, and views lay out as before.\n \n@@ -613,19 +695,39 @@\n \t#fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;\n \t#fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;\n \t#fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;\n+\t#fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;\n \t/** Whether a new stored graph starts packing (GraphOptions.packFiles). */\n \t#packFiles = true;\n-\t/** Whether this graph's files are packed: read once, when first asked, so opening reads nothing. */\n-\t#packedKnown: boolean | undefined;\n+\t/**\n+\t * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,\n+\t * deletes and attributes, 2 the runs written across files as well.\n+\t */\n+\t#formatKnown: number | undefined;\n+\tget #format(): number {\n+\t\tif (this.#formatKnown === undefined) {\n+\t\t\tconst format = this.#storage?.read(\"file-lines:meta\", \"format\");\n+\t\t\tthis.#formatKnown = format === 1 || format === 2 ? format : 0;\n+\t\t}\n+\t\treturn this.#formatKnown;\n+\t}\n \tget #packed(): boolean {\n-\t\tthis.#packedKnown ??= !!this.#storage && this.#storage.read(\"file-lines:meta\", \"format\") === 1;\n-\t\treturn this.#packedKnown;\n+\t\treturn this.#format >= 1;\n \t}\n+\tget #crossings(): boolean {\n+\t\treturn this.#format >= 2;\n+\t}\n \n \t/** Whether this graph keeps each file's line history packed. */\n \tget packedFiles(): boolean {\n \t\treturn this.#packed;\n \t}\n+\t/**\n+\t * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph\n+\t * packed before those were kept lays files out line by line.\n+\t */\n+\tget packedLayout(): boolean {\n+\t\treturn this.#crossings;\n+\t}\n \t/** A path's index, or undefined when nothing was ever written or set in it. */\n \tpathIndexOf(path: string): number | undefined {\n \t\treturn this.#pathIndex.get(path);\n@@ -640,13 +742,70 @@\n \t*packedTexts(file: number): IterableIterator<string | null> {\n \t\tyield* this.#fileTexts!.values(String(file));\n \t}\n+\t/**\n+\t * The texts at positions [page * 256, (page + 1) * 256) of packedTexts(file) (abso Capacity): a layout reads only the\n+\t * pages holding a line it shows.\n+\t */\n+\tpackedTextPage(file: number, page: number): readonly (string | null)[] {\n+\t\treturn this.#fileTexts!.pageAt(String(file), page);\n+\t}\n \t*packedDeletes(file: number): IterableIterator<PackedDelete> {\n \t\tyield* this.#fileDeletes!.values(String(file));\n \t}\n \t*packedAttrs(file: number): IterableIterator<PackedAttr> {\n \t\tyield* this.#fileAttrs!.values(String(file));\n \t}\n+\t*packedCrossings(file: number): IterableIterator<PackedCrossing> {\n+\t\tyield* this.#fileCrossings!.values(String(file));\n+\t}\n \n+\t/** Decoded file histories by path index, most recently used last, under PACKED_HISTORY_BUDGET bytes. */\n+\treadonly #histories = new Map<number, { counts: string; history: PackedHistory; bytes: number }>();\n+\t#historyBytes = 0;\n+\n+\t/**\n+\t * A file's line, delete and crossing history, decoded once and kept while it fits (abso Capacity). Kept under its\n+\t * three lists' lengths: the lists only grow, and add() lets every kept history go, so a kept one is always whole.\n+\t */\n+\tpackedHistory(file: number): PackedHistory {\n+\t\tconst key = String(file);\n+\t\tconst counts = `${this.#fileLines!.length(key)} ${this.#fileDeletes!.length(key)} ${this.#fileCrossings!.length(key)}`;\n+\t\tconst kept = this.#histories.get(file);\n+\t\tif (kept) {\n+\t\t\tthis.#histories.delete(file);\n+\t\t\tif (kept.counts === counts) {\n+\t\t\t\tthis.#histories.set(file, kept);\n+\t\t\t\treturn kept.history;\n+\t\t\t}\n+\t\t\tthis.#historyBytes -= kept.bytes;\n+\t\t}\n+\t\tconst history: PackedHistory = {\n+\t\t\tlines: packNumbers(this.#fileLines!.values(key)),\n+\t\t\tdeletes: packNumbers(this.#fileDeletes!.values(key)),\n+\t\t\tcrossings: packNumbers(this.#fileCrossings!.values(key)),\n+\t\t};\n+\t\tconst bytes =\n+\t\t\t(history.lines as Int32Array).byteLength +\n+\t\t\t(history.deletes as Int32Array).byteLength +\n+\t\t\t(history.crossings as Int32Array).byteLength +\n+\t\t\t200;\n+\t\tif (bytes <= PACKED_HISTORY_BUDGET) {\n+\t\t\tthis.#histories.set(file, { counts, history, bytes });\n+\t\t\tthis.#historyBytes += bytes;\n+\t\t\tfor (const [old, entry] of this.#histories) {\n+\t\t\t\tif (this.#historyBytes <= PACKED_HISTORY_BUDGET) break;\n+\t\t\t\tthis.#histories.delete(old);\n+\t\t\t\tthis.#historyBytes -= entry.bytes;\n+\t\t\t}\n+\t\t}\n+\t\treturn history;\n+\t}\n+\n+\t/** Bytes of decoded file histories kept (packedHistory). */\n+\tget historyBytes(): number {\n+\t\treturn this.#historyBytes;\n+\t}\n+\n \t/** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */\n \t#lists: ((seq: number) => AtomLists) | undefined;\n \t/** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */\n@@ -750,6 +909,16 @@\n \t#resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;\n \t#together: StateMap<AtomId, TogetherLink[]> = new Map();\n \t#togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;\n+\t/** The atoms whose reasons point at each atom, in seq order, once each (abso Capacity). */\n+\t#reasonsIn = new Map<AtomId, AtomId[]>();\n+\t#reasonsInPages: ReturnType<typeof storedLists<AtomId>> | undefined;\n+\t/** Whether a stored graph keeps reasons-in: from a fresh graph on, worked out when first needed. */\n+\t#reasonsInKnown: boolean | undefined;\n+\tget #reasonsInKept(): boolean {\n+\t\tif (!this.#storage) return true;\n+\t\tthis.#reasonsInKnown ??= this.#storage.read(\"reasons-in:meta\", \"kept\") === 1;\n+\t\treturn this.#reasonsInKnown;\n+\t}\n \t#fileAtoms: StateMap<string, AtomId[]> = new Map();\n \t#fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;\n \t/** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */\n@@ -765,6 +934,8 @@\n \t#relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();\n \t#relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;\n \t#movers: AtomId[] = [];\n+\t/** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */\n+\t#moverList: AtomId[] | undefined;\n \t#atomFiles: (readonly string[])[] = [];\n \t/** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */\n \t#atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];\n@@ -777,6 +948,16 @@\n \t\treturn this.#atoms.length;\n \t}\n \n+\t/**\n+\t * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the\n+\t * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a\n+\t * cache look again.\n+\t */\n+\tget accepted(): number {\n+\t\treturn this.#accepted;\n+\t}\n+\t#accepted = 0;\n+\n \t/** The id the next accepted atom must have. */\n \tnextId(): AtomId {\n \t\treturn atomId(this.#atoms.length);\n@@ -802,7 +983,7 @@\n \t/** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */\n \tlamport(id: AtomId): number {\n \t\tif (!this.has(id)) throw new EngineError(\"unknown-atom\", `no atom ${id}`);\n-\t\treturn this.#lamport[this.#seq(id)]!;\n+\t\treturn this.#lamportAt(this.#seq(id));\n \t}\n \n \t/** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */\n@@ -818,7 +999,7 @@\n \t\t\tid,\n \t\t\tatom: this.idOfSeq(seq),\n \t\t\tk: n - this.#lineBase[seq]!,\n-\t\t\tfile: this.#paths[this.#lineFile.at(n)]!,\n+\t\t\tfile: this.#pathName(this.#lineFile.at(n)),\n \t\t\tparent: this.#nodeName(this.#lineParent.at(n)),\n \t\t\ttext: this.#text(n),\n \t\t};\n@@ -839,7 +1020,7 @@\n \t/** The file a line was written in, or undefined: line(id).file without making the record. */\n \tlineFile(id: LineId): string | undefined {\n \t\tconst n = this.#lineN(id);\n-\t\treturn n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];\n+\t\treturn n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));\n \t}\n \n \t/** The node a line was written after, or undefined: line(id).parent without making the record. */\n@@ -941,13 +1122,17 @@\n \t\treturn atomId(seq);\n \t}\n \n+\t#lamportAt(seq: number): number {\n+\t\treturn this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;\n+\t}\n+\n \tlamportOfSeq(seq: number): number {\n-\t\treturn this.#lamport[seq]!;\n+\t\treturn this.#lamportAt(seq);\n \t}\n \n \t/** The file line n was written in. */\n \twrittenIn(n: number): string {\n-\t\treturn this.#paths[this.#lineFile.at(n)]!;\n+\t\treturn this.#pathName(this.#lineFile.at(n));\n \t}\n \n \t/** The code of the node line n was written after. */\n@@ -1110,9 +1295,30 @@\n \t}\n \n \t#nodeName(code: number): NodeId {\n-\t\treturn code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);\n+\t\treturn code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));\n \t}\n \n+\t/**\n+\t * A path's name by its index, kept in memory once read (abso Capacity): finding a deleted line's file names the file\n+\t * it reaches, and a stored graph read the path list each time. Cleared when the graph accepts an atom, so a name a\n+\t * rolled-back add made never stays.\n+\t */\n+\t#pathName(index: number): string {\n+\t\tif (this.#pathNamesAt !== this.#accepted) {\n+\t\t\tthis.#pathNames.clear();\n+\t\t\tthis.#pathNamesAt = this.#accepted;\n+\t\t}\n+\t\tlet name = this.#pathNames.get(index);\n+\t\tif (name === undefined) {\n+\t\t\tname = this.#paths[index]!;\n+\t\t\tif (this.#pathNames.size >= PATH_NAMES) this.#pathNames.clear();\n+\t\t\tthis.#pathNames.set(index, name);\n+\t\t}\n+\t\treturn name;\n+\t}\n+\treadonly #pathNames = new Map<number, string>();\n+\t#pathNamesAt = -1;\n+\n \t#pathOf(file: string): number {\n \t\tlet p = this.#pathIndex.get(file);\n \t\tif (p === undefined) {\n@@ -1228,7 +1434,13 @@\n \n \t/** Atoms that move lines, in seq order. */\n \tmovers(): readonly AtomId[] {\n-\t\treturn this.#movers;\n+\t\tif (!this.#storage) return this.#movers;\n+\t\t// Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.\n+\t\tconst length = this.#movers.length;\n+\t\tconst list = this.#moverList;\n+\t\tif (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;\n+\t\tthis.#moverList = [...this.#movers];\n+\t\treturn this.#moverList;\n \t}\n \n \t/** Atoms that list this one directly in their deps. */\n@@ -1249,6 +1461,16 @@\n \t\telse yield* listOf(this.#resolvers.get(id));\n \t}\n \n+\t/**\n+\t * The atoms whose reasons point at this one, in seq order, once each; or undefined when a stored graph made before\n+\t * this index keeps none, and the caller looks at every atom (abso Capacity).\n+\t */\n+\treasonsTo(id: AtomId): readonly AtomId[] | undefined {\n+\t\tif (!this.#reasonsInKept) return undefined;\n+\t\tif (this.#reasonsInPages) return [...this.#reasonsInPages.values(id)];\n+\t\treturn this.#reasonsIn.get(id) ?? [];\n+\t}\n+\n \t/** `together` reasons touching this atom, in either direction. */\n \ttogetherLinks(id: AtomId): readonly TogetherLink[] {\n \t\treturn [...this.eachTogetherLink(id)];\n@@ -1302,43 +1524,39 @@\n \t * the search never descends below the target's lamport.\n \t */\n \t#reaches(from: Iterable<AtomId>, target: AtomId): boolean {\n-\t\tconst floor = this.#lamport[this.#seq(target)]!;\n-\t\tif (this.#storage) {\n-\t\t\treturn this.withProjectionScratch((scratch) => {\n-\t\t\t\tlet length = 0;\n-\t\t\t\tconst push = (id: AtomId): void => {\n-\t\t\t\t\tif (scratch.read(\"seen\", id)) return;\n-\t\t\t\t\tscratch.write(\"seen\", id, true);\n-\t\t\t\t\tscratch.write(\"stack\", String(length++), id);\n-\t\t\t\t};\n-\t\t\t\tfor (const id of from) {\n-\t\t\t\t\tif (id === target) return true;\n-\t\t\t\t\tif (this.#lamport[this.#seq(id)]! > floor) push(id);\n-\t\t\t\t}\n-\t\t\t\twhile (length > 0) {\n-\t\t\t\t\tconst key = String(--length);\n-\t\t\t\t\tconst current = scratch.read(\"stack\", key) as AtomId;\n-\t\t\t\t\tscratch.remove(\"stack\", key);\n-\t\t\t\t\tif (this.#lamport[this.#seq(current)]! <= floor) continue;\n-\t\t\t\t\tfor (const dependency of this.atom(current).deps) {\n-\t\t\t\t\t\tif (dependency === target) return true;\n-\t\t\t\t\t\tpush(dependency);\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t\treturn false;\n-\t\t\t});\n+\t\treturn this.#reachable(from, new Set([target])).has(target);\n+\t}\n+\n+\t/**\n+\t * Which of `targets` are reachable along deps from any of `from` (themselves included), in one walk: it never\n+\t * descends below the lowest target's lamport, and stops once every target is found (abso 714, piece 4: record\n+\t * walked once per line writer).\n+\t * The walk's seen marks and stack are in memory, by atom number: one byte and four bytes an atom at most, so about\n+\t * 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows in storage\n+\t * (abso-core 139, bounding memory with the graph), which cost a read and a write per atom visited: on abso's Oct 14\n+\t * tables, 41,000 of a 1470-shaped record's 77,767 statements.\n+\t */\n+\t#reachable(from: Iterable<AtomId>, targets: ReadonlySet<AtomId>): Set<AtomId> {\n+\t\tconst found = new Set<AtomId>();\n+\t\tlet floor = Number.POSITIVE_INFINITY;\n+\t\tfor (const target of targets) floor = Math.min(floor, this.#lamportAt(this.#seq(target)));\n+\t\tconst seen = new Uint8Array(this.#atoms.length);\n+\t\tconst stack = new Int32Array(this.#atoms.length);\n+\t\tlet length = 0;\n+\t\tconst visit = (id: AtomId): void => {\n+\t\t\tif (targets.has(id)) found.add(id);\n+\t\t\tconst seq = this.#seq(id);\n+\t\t\tif (seen[seq]) return;\n+\t\t\tseen[seq] = 1;\n+\t\t\tstack[length++] = seq;\n+\t\t};\n+\t\tfor (const id of from) visit(id);\n+\t\twhile (length > 0 && found.size < targets.size) {\n+\t\t\tconst seq = stack[--length]!;\n+\t\t\tif (this.#lamportAt(seq) <= floor) continue;\n+\t\t\tfor (const dependency of this.atom(atomId(seq)).deps) visit(dependency);\n \t\t}\n-\t\tconst seen = new Set<AtomId>();\n-\t\tconst stack = [...from];\n-\t\twhile (stack.length > 0) {\n-\t\t\tconst cur = stack.pop()!;\n-\t\t\tif (cur === target) return true;\n-\t\t\tif (seen.has(cur)) continue;\n-\t\t\tseen.add(cur);\n-\t\t\tif (this.#lamport[this.#seq(cur)]! <= floor) continue;\n-\t\t\tfor (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);\n-\t\t}\n-\t\treturn false;\n+\t\treturn found;\n \t}\n \n \t/**\n@@ -1347,6 +1565,9 @@\n \t * The atom is frozen. Adding to the graph does not add it to any set.\n \t */\n \tadd(atom: Atom): void {\n+\t\t// A new atom appends to its files' histories; a failed one may leave a kept history longer than the lists.\n+\t\tthis.#histories.clear();\n+\t\tthis.#historyBytes = 0;\n \t\tif (this.#storage)\n \t\t\tthis.#storage.transaction(() => {\n \t\t\t\tthis.#add(atom);\n@@ -1360,7 +1581,10 @@\n \t#validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {\n \t\tconst membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {\n \t\t\tif (!scratch) return new Set<T>();\n-\t\t\treturn { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };\n+\t\t\treturn {\n+\t\t\t\thas: (key) => scratch.read(name, key) === true,\n+\t\t\t\tadd: (key) => scratch.write(name, key, true),\n+\t\t\t};\n \t\t};\n \t\tvalidateShape(atom);\n \t\tconst seq = this.#atoms.length;\n@@ -1382,23 +1606,28 @@\n \t\tfor (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);\n \n \t\t// Everything it touches must come from its closure. Derived deps name the\n-\t\t// writers directly, so this is usually one lookup per writer.\n-\t\tconst memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();\n-\t\tconst below = {\n-\t\t\tget: (key: AtomId) => (scratch ? (scratch.read(\"below\", key) as boolean | undefined) : memoryBelow!.get(key)),\n-\t\t\tset: (key: AtomId, value: boolean) => {\n-\t\t\t\tif (scratch) scratch.write(\"below\", key, value);\n-\t\t\t\telse memoryBelow!.set(key, value);\n-\t\t\t},\n-\t\t};\n-\t\tconst inClosure = (writer: AtomId): boolean => {\n-\t\t\tlet hit = below.get(writer);\n-\t\t\tif (hit === undefined) {\n-\t\t\t\thit = deps.has(writer) || this.#reaches(atom.deps, writer);\n-\t\t\t\tbelow.set(writer, hit);\n+\t\t// writers directly, so this is usually one lookup per writer. The writers\n+\t\t// that aren't deps are walked for together, once (abso 714, piece 4).\n+\t\tconst touched: LineId[] = [];\n+\t\tfor (const run of atom.inserts) if (!isStartNode(run.parent)) touched.push(run.parent);\n+\t\tfor (const m of atom.moves ?? []) {\n+\t\t\ttouched.push(m.line);\n+\t\t\tif (!isStartNode(m.parent)) touched.push(m.parent);\n+\t\t}\n+\t\ttouched.push(...atom.deletes);\n+\t\tfor (const list of [atom.writes, atom.reads, atom.holds])\n+\t\t\tfor (const key of list) {\n+\t\t\t\tconst parsed = parseKey(key);\n+\t\t\t\tif (parsed.kind === \"line\" || ((parsed.kind === \"gap\" || parsed.kind === \"pos\") && !isStartNode(parsed.node)))\n+\t\t\t\t\ttouched.push(parsed.node);\n \t\t\t}\n-\t\t\treturn hit;\n-\t\t};\n+\t\tconst beyond = new Set<AtomId>();\n+\t\tfor (const line of touched) {\n+\t\t\tconst writer = this.lineAtom(line);\n+\t\t\tif (writer !== undefined && !deps.has(writer)) beyond.add(writer);\n+\t\t}\n+\t\tconst reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond;\n+\t\tconst inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer);\n \t\tconst checkLine = (line: LineId, what: string): void => {\n \t\t\tconst writer = this.lineAtom(line);\n \t\t\tif (writer === undefined) return bad(`${what} names unknown line ${line}`);\n@@ -1449,8 +1678,10 @@\n \t\t\tthis.#storage.write(\"ordered-children\", \"format\", 2);\n \t\t}\n \t\tif (this.#storage && this.#atoms.length === 0 && this.#packFiles) {\n-\t\t\tthis.#storage.write(\"file-lines:meta\", \"format\", 1);\n-\t\t\tthis.#packedKnown = true;\n+\t\t\tthis.#storage.write(\"file-lines:meta\", \"format\", 2);\n+\t\t\tthis.#storage.write(\"reasons-in:meta\", \"kept\", 1);\n+\t\t\tthis.#reasonsInKnown = true;\n+\t\t\tthis.#formatKnown = 2;\n \t\t}\n \n \t\tif (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));\n@@ -1477,9 +1708,11 @@\n \t\t\t\t\tthis.#lists ? this.#listReader(seq) : undefined,\n \t\t\t\t);\n \t\tthis.#atoms.push(this.#storage ? atom : frozen);\n+\t\tthis.#accepted++;\n \t\tlet lam = 0;\n \t\tfor (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);\n-\t\tthis.#lamport.push(lam);\n+\t\tif (this.#lamportPages) this.#lamportPages.push(lam);\n+\t\telse this.#lamport.push(lam);\n \n \t\t// The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.\n \t\t// The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.\n@@ -1535,6 +1768,10 @@\n \t\t\telse pushOne(this.#runStarts, parent, first);\n \t\t\tconst replacesParent = deletes(run.parent) ? 1 : 0;\n \t\t\tif (this.#packed) {\n+\t\t\t\tif (this.#crossings && parent >= 0) {\n+\t\t\t\t\tconst from = this.#lineFile.at(parent);\n+\t\t\t\t\tif (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);\n+\t\t\t\t}\n \t\t\t\tconst base = this.#lineBase[seq]!;\n \t\t\t\tthis.#fileLines!.appendAll(\n \t\t\t\t\tString(file),\n@@ -1566,7 +1803,12 @@\n \t\t\t}\n \t\t}\n \t\t(frozen.moves ?? []).forEach((m, i) => {\n-\t\t\tconst info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });\n+\t\t\tconst info: RelocationInfo = Object.freeze({\n+\t\t\t\tatom: frozen.id,\n+\t\t\t\tline: m.line,\n+\t\t\t\tparent: m.parent,\n+\t\t\t\tk: i,\n+\t\t\t});\n \t\t\tif (this.#relocationPages) this.#relocationPages.append(m.line, info);\n \t\t\telse pushIndex(this.#relocations, m.line, info);\n \t\t\tif (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);\n@@ -1610,7 +1852,7 @@\n \t\t}\n \t\tconst files = new Set<string>();\n \t\tfor (const run of atom.inserts) files.add(run.file);\n-\t\tfor (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);\n+\t\tfor (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n)));\n \t\tfor (const a of frozen.attrs ?? []) files.add(a.file);\n \t\tfor (const m of frozen.moves ?? []) {\n \t\t\tfiles.add(this.lineFile(m.line)!);\n@@ -1621,6 +1863,15 @@\n \t\t\tif (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);\n \t\t\telse pushIndex(this.#fileAtoms, file, frozen.id);\n \t\t}\n+\t\tif (this.#reasonsInKept) {\n+\t\t\tconst pointed = new Set<AtomId>();\n+\t\t\tfor (const r of frozen.reasons) {\n+\t\t\t\tif (pointed.has(r.to)) continue;\n+\t\t\t\tpointed.add(r.to);\n+\t\t\t\tif (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id);\n+\t\t\t\telse pushIndex(this.#reasonsIn, r.to, frozen.id);\n+\t\t\t}\n+\t\t}\n \t\tfor (const r of frozen.reasons) {\n \t\t\tif (r.kind !== \"together\" || r.to === frozen.id) continue;\n \n@@ -1705,7 +1956,12 @@\n \t// JSON -------------------------------------------------------------------\n \n \ttoJSON(): GraphJSON {\n-\t\treturn { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };\n+\t\treturn {\n+\t\t\tformat: GRAPH_FORMAT,\n+\t\t\tversion: 1,\n+\t\t\tatoms: this.#atoms,\n+\t\t\tlabels: this.labels(),\n+\t\t};\n \t}\n \n \t/** Load a saved graph. Every atom is re-validated as it is added. */\n@@ -1805,7 +2061,12 @@\n \t// With text kept elsewhere (#46), a run's lines are read when asked for.\n \tlet k = 0;\n \tconst run = (r: InsertRun): InsertRun => {\n-\t\tif (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });\n+\t\tif (!text)\n+\t\t\treturn Object.freeze({\n+\t\t\t\tfile: r.file,\n+\t\t\t\tparent: r.parent,\n+\t\t\t\tlines: Object.freeze([...r.lines]),\n+\t\t\t});\n \t\tconst start = k;\n \t\tconst length = r.lines.length;\n \t\tk += length;\n@@ -1820,16 +2081,25 @@\n \t\tinserts: Object.freeze(atom.inserts.map(run)),\n \t\t...(lists\n \t\t\t? {}\n-\t\t\t: { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),\n+\t\t\t: {\n+\t\t\t\t\tdeletes: list(atom.deletes),\n+\t\t\t\t\twrites: list(atom.writes),\n+\t\t\t\t\treads: list(atom.reads),\n+\t\t\t\t\tholds: list(atom.holds),\n+\t\t\t\t}),\n \t\tneeds: list(atom.needs, canon),\n \t\tresolves: list(atom.resolves, canon),\n \t\treasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),\n \t\tdeps: list(atom.deps, canon),\n \t\t...(atom.attrs && atom.attrs.length > 0\n-\t\t\t? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }\n+\t\t\t? {\n+\t\t\t\t\tattrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))),\n+\t\t\t\t}\n \t\t\t: {}),\n \t\t...(atom.moves\n-\t\t\t? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }\n+\t\t\t? {\n+\t\t\t\t\tmoves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))),\n+\t\t\t\t}\n \t\t\t: {}),\n \t} as Atom;\n \treturn Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);"}],"unmatched":[]}