{"draft":null,"from":233,"to":318,"files":[{"path":"src/engine/graph.ts","added":292,"removed":80,"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@@ -264,7 +266,39 @@\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@@ -353,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@@ -365,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@@ -382,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@@ -433,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@@ -462,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@@ -485,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@@ -502,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@@ -530,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@@ -553,7 +613,7 @@\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@@ -576,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@@ -600,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@@ -678,6 +742,13 @@\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@@ -688,6 +759,53 @@\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@@ -791,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@@ -820,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@@ -861,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@@ -882,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@@ -994,7 +1132,7 @@\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@@ -1157,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@@ -1302,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@@ -1355,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.#lamportAt(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.#lamportAt(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.#lamportAt(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.#lamportAt(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@@ -1400,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@@ -1413,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@@ -1435,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@@ -1503,6 +1679,8 @@\n \t\t}\n \t\tif (this.#storage && this.#atoms.length === 0 && this.#packFiles) {\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@@ -1530,6 +1708,7 @@\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\tif (this.#lamportPages) this.#lamportPages.push(lam);\n@@ -1624,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@@ -1668,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@@ -1679,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@@ -1763,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@@ -1863,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@@ -1878,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":[]}