- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/graph.ts --version 315 --json
- JSON
- /christopher/abso-core/blame/src/engine/graph.ts?version=315&format=json
2,106 linesFirst import 46% · codex-capacity-chair 32% · capacity 22%Last change capacity in version 312,
2,106 lines from 36 changes in 34 versions.
init0Start the project1// The graph: every atom ever accepted, plus labels. Sets of atoms (states of
2// the codebase) are separate values; the graph only answers questions about
3// atoms and keeps indexes so those questions are cheap.
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare5import { ChildCounts } from "./child-counts.ts";
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare6import { JsonStringChunks, registerJsonChunkValue } from "./json-value-chunks.ts";
8 atomId,
9 attrKey,
10 gapKey,
11 isAtomId,
12 isStartNode,
13 lineId,
14 lineKey,
15 parseKey,
16 posKey,
17 seqOf,
18 startNode,
19} from "./keys.ts";
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare20import { OrderedIndex, orderedChildKey } from "./ordered-index.ts";
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare21import { withProjectionScratch } from "./projection-scratch.ts";
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare23 type GraphStateStorage,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare24 readonlyPagedArray,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare25 readonlyStoredArray,
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare26 type StateMap,
27 storedArray,
28 storedLists,
29 storedMap,
30 storedNumbers,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare31 writePagedArray,
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare32} from "./state-source.ts";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare33import { StoredText } from "./stored-text.ts";
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare34import {
36 type Atom,
37 type AtomId,
38 EngineError,
39 type InsertRun,
40 type Key,
41 type Label,
42 type LineId,
43 type NodeId,
44 REASON_KINDS,
45 type Reason,
46} from "./types.ts";
48/**
49 * Where a line was written and what it says. Its text never changes. A move
50 * can give it another parent in a set, even in another file: `view.parentOf`
51 * and `view.fileOf` say where it is in a set.
52 */
53export interface LineInfo {
54 readonly id: LineId;
55 readonly atom: AtomId;
56 readonly k: number;
57 /** The file it was written in. */
58 readonly file: string;
59 /** The node it was written after. */
60 readonly parent: NodeId;
61 readonly text: string;
62}
64/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
65export interface RelocationInfo {
66 readonly atom: AtomId;
67 readonly line: LineId;
68 readonly parent: NodeId;
69 readonly k: number;
70}
72/** A `together` reason seen from one end: `other` is the atom at the far end. */
73export interface TogetherLink {
74 readonly other: AtomId;
75 readonly text: string;
76 /** The atom that carries the reason. */
77 readonly from: AtomId;
78}
80export const GRAPH_FORMAT = "ai-first-vcs.graph";
82/** The saved form of a graph. Atoms are in seq order. */
83export interface GraphJSON {
84 readonly format: typeof GRAPH_FORMAT;
85 readonly version: 1;
86 readonly atoms: readonly Atom[];
87 readonly labels: readonly Label[];
88}
90/**
91 * An index entry that holds a lone value as itself, and a list only once there
92 * are two (#46): most keys name one atom, and a list for each costs more than
93 * the value.
94 */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare95function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
97 if (had === undefined) map.set(key, value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare98 else if (Array.isArray(had)) {
99 had.push(value);
100 map.set(key, had);
101 } else map.set(key, [had, value]);
104function listOf<V>(had: V | V[] | undefined): readonly V[] {
105 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
106}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare108function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare110 if (list) {
111 list.push(value);
112 map.set(key, list);
113 } else map.set(key, [value]);
116const EMPTY: readonly never[] = Object.freeze([]);
118/**
119 * A run whose lines are read when asked for (#46, text on disk): a few fields
120 * and a shared reader, where an object with its own accessor cost about 400
121 * bytes a run.
122 */
123class LazyRun implements InsertRun {
124 readonly file: string;
125 readonly parent: NodeId;
126 readonly #text: (start: number, length: number) => readonly string[];
127 readonly #start: number;
128 readonly #length: number;
129 constructor(
130 file: string,
131 parent: NodeId,
132 text: (start: number, length: number) => readonly string[],
133 start: number,
134 length: number,
135 ) {
136 this.file = file;
137 this.parent = parent;
138 this.#text = text;
139 this.#start = start;
140 this.#length = length;
141 }
142 get lines(): readonly string[] {
143 return this.#text(this.#start, this.#length);
144 }
145 toJSON(): InsertRun {
146 return { file: this.file, parent: this.parent, lines: this.lines };
147 }
148}
150/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
151const TEXT_CACHE = 4_000_000;
152/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
153const LIST_CACHE = 50_000;
155/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
156export interface AtomLists {
157 readonly deletes: readonly LineId[];
158 readonly writes: readonly Key[];
159 readonly reads: readonly Key[];
160 readonly holds: readonly Key[];
161}
163function listItems(l: AtomLists): number {
164 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
165}
167function frozenList<T>(xs: readonly T[]): readonly T[] {
168 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
169}
171/**
172 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
173 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
174 */
175class ListedAtom {
176 readonly #read: () => AtomLists;
177 constructor(fields: object, read: () => AtomLists) {
178 Object.assign(this, fields);
179 this.#read = read;
180 }
181 get deletes(): readonly LineId[] {
182 return this.#read().deletes;
183 }
184 get writes(): readonly Key[] {
185 return this.#read().writes;
186 }
187 get reads(): readonly Key[] {
188 return this.#read().reads;
189 }
190 get holds(): readonly Key[] {
191 return this.#read().holds;
192 }
193 toJSON(): object {
194 return { ...this, ...this.#read() };
195 }
196}
198/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare199interface NumberIndex {
200 readonly length: number;
201 push(n: number): void;
202 at(i: number): number;
203 set(i: number, n: number): void;
204}
206class Ints implements NumberIndex {
208 /** bytes: values 0-255 only, one byte each. */
209 constructor(bytes = false) {
210 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
211 }
212 length = 0;
213 push(n: number): void {
214 if (this.length === this.#buf.length) {
215 const bigger =
216 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
217 bigger.set(this.#buf);
218 this.#buf = bigger;
219 }
220 this.#buf[this.length++] = n;
221 }
222 at(i: number): number {
223 return this.#buf[i]!;
224 }
225 set(i: number, n: number): void {
226 this.#buf[i] = n;
227 }
228}
230/**
231 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
232 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
233 * zeros, and k within the lines its atom wrote.
234 */
235function parseLineId(id: string): { seq: number; k: number } | undefined {
236 if (typeof id !== "string") return undefined;
237 const n = id.length;
238 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
239 let i = 1;
240 let seq = 0;
241 const seqStart = i;
242 for (; i < n; i++) {
243 const c = id.charCodeAt(i);
244 if (c === 46 /* . */) break;
245 if (c < 48 || c > 57) return undefined;
246 seq = seq * 10 + (c - 48);
247 }
248 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
249 return undefined;
250 const kStart = ++i;
251 let k = 0;
252 for (; i < n; i++) {
253 const c = id.charCodeAt(i);
254 if (c < 48 || c > 57) return undefined;
255 k = k * 10 + (c - 48);
256 }
257 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
258 return { seq, k };
259}
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare261/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
262export type PackedLine = [number, number, number, number, number];
263/** A delete of a line in a file's packed history: [n, deleter seq]. */
264export type PackedDelete = [number, number];
265/** An attribute set on a file: [seq, name, value]. */
266export type PackedAttr = [number, string, string | null];
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare267/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
268export type PackedCrossing = [number, number];
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare269
270/**
271 * A file's packed history decoded, without texts (Graph.packedHistory): PackedLine's five numbers per line, then
272 * PackedDelete's two per delete and PackedCrossing's two per crossing, each list flat.
273 */
274export interface PackedHistory {
275 readonly lines: ArrayLike<number>;
276 readonly deletes: ArrayLike<number>;
277 readonly crossings: ArrayLike<number>;
278}
280/**
281 * Bytes of decoded file histories a stored graph keeps between layouts (abso Capacity). Every view of a file read its
282 * whole history from pages: compare lays each file out once per side, collisions once per draft touching it, and a
283 * file whose lines moved in from another read that one's history too (abso's worker files, split out of index.ts).
284 * abso's index.ts, 46,000 lines of history, takes about 1 MB.
285 */
286export const PACKED_HISTORY_BUDGET = 4_000_000;
288/** Numbers packed flat: 4 bytes each while they fit in 32 bits, else 8. */
289function packNumbers(rows: Iterable<readonly number[]>): Int32Array | Float64Array {
290 const flat: number[] = [];
291 let small = true;
292 for (const row of rows)
293 for (const value of row) {
294 if ((value | 0) !== value) small = false;
295 flat.push(value);
296 }
297 return small ? Int32Array.from(flat) : Float64Array.from(flat);
298}
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export.
- where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line.
- Draft files (overlaps.ts) go by number the same way.
- An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this).
- Draft collisions:
- build the union view only when two drafts share a file;
- work out each agent's touched files and its "shared now plus draft" view once;
- find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history;
- have the definition rule keep a draft's uses, and the newer work's definitions, across partners.
- A stored list read in order reads its length once, not before every element.
draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail.
On website's export (1,387 entries) the answers match Project.load:
- status: 17 s to 4.5 s
- where: over 60 s to 8.8 s
- drafts: 14 s to 5.3 s
- collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare299const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare300/** At most this many path names kept in memory (Graph.#pathName). */
301const PATH_NAMES = 4096;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare302/** Lines longer than this aren't packed with their file; their text is read on its own. */
303const PACKED_TEXT = 4096;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare306 readonly #storage?: GraphStateStorage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare307 readonly #childCounts?: ChildCounts;
309 #lamport: number[] = [];
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare310 /**
311 * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)
312 * keeps that; the choice is made when first needed, so opening reads nothing.
313 */
314 #lamportPaged: ReturnType<typeof storedNumbers> | undefined;
315 #lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;
316 get #lamportPages(): ReturnType<typeof storedNumbers> | null {
317 if (this.#lamportPagesKnown === undefined)
318 this.#lamportPagesKnown =
319 this.#lamportPaged && this.#storage!.read("lamport:meta", "length") === undefined ? this.#lamportPaged : null;
320 return this.#lamportPagesKnown;
321 }
init0Start the project322 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
323 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
324 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
325 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
326 #lineBase: number[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare327 #lineAtom: NumberIndex = new Ints();
328 #lineFile: NumberIndex = new Ints();
329 #lineParent: NumberIndex = new Ints();
init0Start the project330 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
331 #lineText: string[] | undefined = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare332 get #lineTotal(): number {
333 return this.#lineAtom.length;
334 }
init0Start the project335 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
336 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
337 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
338 #textCache = new Map<number, readonly string[]>();
339 #textCached = 0;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare341 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
344 * `texts`, when given, says where each atom's lines' text can be read back
345 * (#46): the graph then keeps no text, only each line's place, and reads an
346 * atom's text when a line of it is asked for, keeping the most recent.
347 */
348 constructor(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare349 options: {
350 texts?: (seq: number) => readonly (readonly string[])[];
351 lists?: (seq: number) => AtomLists;
352 storage?: GraphStateStorage;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare353 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
354 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare355 /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
356 packFiles?: boolean;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare357 } = {},
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare359 if (options.indexAcceptedAtom && !options.storage)
360 throw Error("accepted atom indexing requires persistent storage");
361 this.#indexAcceptedAtom = options.indexAcceptedAtom;
363 this.#texts = options.texts;
364 this.#lineText = undefined;
365 }
366 if (options.lists) this.#lists = options.lists;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare367 this.#storage = options.storage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare368 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare369 if (options.storage) {
370 const storage = options.storage;
codex-capacity-chair113Page disk-first numeric graph indexes under bounded storage cacheCompare371 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare372 const atomText = new StoredText(storage, "atom-text:long");
373 type TextReference = { text: string };
374 const listFields = [
375 "deletes",
376 "writes",
377 "reads",
378 "holds",
379 "needs",
380 "resolves",
381 "deps",
382 "reasons",
383 "attrs",
384 "moves",
385 ] as const;
386 type EncodedAtom = {
387 insertionFormat?: 1;
388 insertionRuns?: string;
389 textFormat?: 1;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare390 listFormat?: 1 | 2;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare391 listCount?: number;
392 lists?: Partial<Record<(typeof listFields)[number], string>>;
393 atom: Atom;
394 };
395 this.#atoms = storedArray<Atom>(
396 storage,
397 "atoms",
398 (value) => {
399 const encoded = value as unknown as Partial<EncodedAtom>;
400 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
401 throw Error("invalid stored atom text format");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare402 if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare403 throw Error("invalid stored atom list format");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare404 if (encoded.listFormat === 1 || encoded.listFormat === 2) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare405 if (
406 !encoded.lists ||
407 typeof encoded.lists !== "object" ||
408 Array.isArray(encoded.lists) ||
409 !Number.isSafeInteger(encoded.listCount) ||
410 encoded.listCount! < 1 ||
411 Object.keys(encoded.lists).length !== encoded.listCount ||
412 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
413 )
414 throw Error("invalid stored atom list references");
415 }
416 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
417 throw Error("invalid stored insertion format");
418 const atom =
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare419 encoded.textFormat === 1 ||
420 encoded.listFormat === 1 ||
421 encoded.listFormat === 2 ||
422 encoded.insertionFormat === 1
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare423 ? encoded.atom!
424 : value;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare425 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
426 throw Error("invalid stored insertion placeholder");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare427 const text =
428 encoded.textFormat === 1
429 ? (start: number, length: number): readonly string[] => {
430 const result: string[] = [];
431 let index = 0;
432 for (const run of atom.inserts)
433 for (const raw of run.lines) {
434 if (index >= start && index < start + length) {
435 const reference = raw as unknown as TextReference;
436 if (typeof raw === "string") result.push(raw);
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare437 else if (reference && reference.text === JSON.stringify([String(atom.seq), index]))
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare438 result.push(atomText.read(reference.text));
439 else throw Error("invalid stored atom text reference");
440 }
441 if (++index >= start + length) return result;
442 }
443 throw Error("stored atom text range missing");
444 }
445 : undefined;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare446 // Sequential reads advance once per run without retaining a history-sized offset array.
447 let offsetRun = 0;
448 let offsetLine = 0;
449 const insertionStart = (index: number): number => {
450 if (index < offsetRun) {
451 offsetRun = 0;
452 offsetLine = 0;
453 }
454 while (offsetRun < index) {
455 offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
456 offsetRun++;
457 }
458 return offsetLine;
459 };
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare460 const streamed = (target: Atom): Atom => {
461 registerJsonChunkValue(target, () => {
462 const line = (raw: unknown, index: number): unknown => {
463 if (typeof raw === "string") return raw;
464 const reference = raw as TextReference;
465 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
466 throw Error("invalid stored atom text reference");
467 return new JsonStringChunks(() => atomText.chunks(reference.text));
468 };
469 let inserts: readonly unknown[];
470 if (encoded.insertionFormat === 1) {
471 const collection = `atom-inserts:${atom.seq}`;
472 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare473 const run = raw as {
474 file: string;
475 parent: string;
476 lines: string;
477 };
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare478 const lines = `${collection}:lines:${index}`;
479 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
480 throw Error("invalid stored insertion run");
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare481 const start = insertionStart(index);
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare482 return {
483 file: run.file,
484 parent: run.parent,
485 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
486 };
487 });
488 } else {
489 let index = 0;
490 inserts = atom.inserts.map((run) => ({
491 file: run.file,
492 parent: run.parent,
493 lines: run.lines.map((raw) => line(raw, index++)),
494 }));
495 }
496 return { ...target, inserts };
497 });
498 return target;
499 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare500 const frozen = freezeAtom(
501 atom,
502 (id) => id,
503 (author) => author,
504 text,
505 );
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare506 if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)
507 return streamed(frozen);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare508 const result = { ...frozen };
509 if (encoded.insertionFormat === 1) {
510 const collection = `atom-inserts:${atom.seq}`;
511 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
512 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare513 const run = raw as {
514 file: string;
515 parent: InsertRun["parent"];
516 lines: string;
517 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare518 const lines = `${collection}:lines:${index}`;
519 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
520 throw Error("invalid stored insertion run");
521 return Object.freeze({
522 file: run.file,
523 parent: run.parent,
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare524 lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare525 if (typeof rawLine === "string") return rawLine;
526 const ref = rawLine as TextReference;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare527 const atomLine = insertionStart(index) + lineIndex;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare528 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
529 throw Error("invalid stored insertion text");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare530 return atomText.read(ref.text);
531 }),
532 });
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare533 });
534 Object.defineProperty(result, "inserts", {
535 value: inserts,
536 enumerable: true,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare537 });
538 }
539 for (const field of listFields) {
540 const collection = encoded.lists?.[field];
541 if (collection === undefined) continue;
542 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
543 throw Error("invalid stored atom list reference");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare544 const list =
545 encoded.listFormat === 2
546 ? readonlyPagedArray(storage, collection)
547 : readonlyStoredArray(storage, collection);
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare548 Object.defineProperty(result, field, {
549 value: list,
550 enumerable: true,
551 });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare552 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare553 return streamed(Object.freeze(result));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare554 },
555 (input, key) => {
556 const atom = { ...input };
557 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
558 for (const field of listFields) {
559 const values = input[field];
560 if (!values || values.length <= 256) continue;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare561 // 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare562 const collection = `atom-list:${input.seq}:${field}`;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare563 writePagedArray(storage, collection, values);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare564 lists[field] = collection;
565 Object.defineProperty(atom, field, { value: [], enumerable: true });
566 }
567 const listCount = Object.keys(lists).length;
568 const hasLists = listCount > 0;
codex-capacity-chair166Read long insertion text lazily and stream files through Git commit constructionCompare569 let insertionCharacters = 0;
570 if (
571 atom.inserts.length > 256 ||
572 atom.inserts.some((run) => run.lines.length > 256) ||
573 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
574 ) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare575 const collection = `atom-inserts:${input.seq}`;
576 const runs = storedArray<unknown>(storage, collection);
577 let runIndex = 0;
578 let lineIndex = 0;
579 for (const run of atom.inserts) {
580 const lineCollection = `${collection}:lines:${runIndex++}`;
581 const lines = storedArray<unknown>(storage, lineCollection);
582 for (const line of run.lines) {
583 const text = JSON.stringify([key, lineIndex++]);
584 if (line.length > StoredText.chunkCharacters) {
585 atomText.write(text, line);
586 lines.push({ text });
587 } else lines.push(line);
588 }
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare589 runs.push({
590 file: run.file,
591 parent: run.parent,
592 lines: lineCollection,
593 });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare594 }
595 return {
596 insertionFormat: 1,
597 insertionRuns: collection,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare598 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare599 atom: { ...atom, inserts: [] },
600 };
601 }
602 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare603 return hasLists ? { listFormat: 2, listCount, lists, atom } : atom;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare604 let index = 0;
605 const inserts = atom.inserts.map((run) => ({
606 ...run,
607 lines: run.lines.map((line) => {
608 const text = JSON.stringify([key, index++]);
609 if (line.length <= StoredText.chunkCharacters) return line;
610 atomText.write(text, line);
611 return { text };
612 }),
613 }));
614 return {
615 textFormat: 1,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity).
Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys).
- New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index.
- An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages.
On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s.
Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare616 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare617 atom: { ...atom, inserts },
618 };
619 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare620 );
621 this.#lamport = storedArray(storage, "lamport");
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare622 this.#lamportPaged = storedNumbers(storage, "lamport-pages");
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare623 this.#lineBase = storedArray(storage, "line-base");
624 this.#paths = storedArray(storage, "paths");
625 this.#movers = storedArray(storage, "movers");
626 this.#atomFiles = storedArray(storage, "atom-files");
627 this.#atomDeletes = storedArray(storage, "atom-deletes");
628 this.#lineAtom = numbers("line-atom");
629 this.#lineFile = numbers("line-file");
630 this.#lineParent = numbers("line-parent");
631 this.#deleter = numbers("deleter");
632 this.#replacing = numbers("replacing");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare633 const longText = atomText;
634 this.#lineText = storedArray<string>(
635 storage,
636 "line-text",
637 (value) => {
638 if (typeof value === "string") return value;
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare639 const reference = value as unknown as {
640 format: number;
641 text: string;
642 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare643 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
644 return longText.read(reference.text);
645 },
646 (value, key) => {
647 if (value.length <= StoredText.chunkCharacters) return value;
648 const number = Number(key);
649 const seq = this.#lineAtom.at(number);
650 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
651 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
652 if (header?.characters !== value.length) throw Error("long line atom text is missing");
653 return { format: 1, text };
654 },
655 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare656 this.#pathIndex = storedMap(storage, "path-index");
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare657 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
658 JSON.stringify(["number", Number(key)]),
659 );
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare660 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
661 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
662 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare663 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
664 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
codex-capacity-chair129Page together relationship history for bounded traversalCompare665 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity).
why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms.
- Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before.
- Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before.
- trail takes atoms' numbers from their ids instead of reading each atom.
On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB.
New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare666 this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare667 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
codex-capacity-chair130Stream paged child history into layout filteringCompare668 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
669 JSON.stringify(["number", Number(key)]),
670 );
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare671 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
672 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
673 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
674 JSON.stringify(["number", Number(key)]),
675 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare676 this.#labels = storedMap(storage, "labels");
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare677 this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
678 this.#fileTexts = storedLists<string | null>(storage, "file-texts");
679 this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
680 this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare681 this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings");
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare682 this.#packFiles = options.packFiles ?? true;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare683 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare685
686 // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
687 // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare688 // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
689 // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
690 // so a run written while its parent was moved elsewhere lays out wherever the parent is.
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare691 // 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
692 // a fresh adoption on; a graph adopted before has none, and views lay out as before.
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare694 #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
695 #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
696 #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
697 #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare698 #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare699 /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
700 #packFiles = true;
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare701 /**
702 * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
703 * deletes and attributes, 2 the runs written across files as well.
704 */
705 #formatKnown: number | undefined;
706 get #format(): number {
707 if (this.#formatKnown === undefined) {
708 const format = this.#storage?.read("file-lines:meta", "format");
709 this.#formatKnown = format === 1 || format === 2 ? format : 0;
710 }
711 return this.#formatKnown;
712 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare713 get #packed(): boolean {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare714 return this.#format >= 1;
715 }
716 get #crossings(): boolean {
717 return this.#format >= 2;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare718 }
720 /** Whether this graph keeps each file's line history packed. */
721 get packedFiles(): boolean {
722 return this.#packed;
723 }
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare724 /**
725 * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
726 * packed before those were kept lays files out line by line.
727 */
728 get packedLayout(): boolean {
729 return this.#crossings;
730 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare731 /** A path's index, or undefined when nothing was ever written or set in it. */
732 pathIndexOf(path: string): number | undefined {
733 return this.#pathIndex.get(path);
734 }
735 /** The index of the path line n was written in. */
736 writtenInIndex(n: number): number {
737 return this.#lineFile.at(n);
738 }
739 *packedLines(file: number): IterableIterator<PackedLine> {
740 yield* this.#fileLines!.values(String(file));
741 }
742 *packedTexts(file: number): IterableIterator<string | null> {
743 yield* this.#fileTexts!.values(String(file));
744 }
capacity274Cold reads (abso Capacity, issue 664): a packed layout reads only the text pages holding a line it shows; definition code stays in memory up to 4 MB; a stored array's element read skips its length read.
- Layout: each line's file and place are kept and texts are read after the walk, a page at a time, only for shown lines. Every text a file and the files its moved-in lines came from ever had was read for every layout; abso's worker files, split out of index.ts, each read all of index.ts's history. Cold compare 612 to 1224 on abso read text pages 17,080 times, now 2,856.
- Definition code: at 64 KB every large file's parsed code went row by row into scratch and back (25,000 rows each for index.ts). The visible lines are already in memory, so 4 MB at most doubles a file's text for the call. withDefinitionCode takes the limit; its scratch test passes 64 KB.
- storedArray: set writes the row and the length together and nothing shrinks, so no row lies past the length; half of a cold layout's reads were the length.
Side by side on abso's export, same machine, three rounds: cold collisions 10.5 s to 6.2 s, cold compare 12.6 s to 8.6 s. tsc clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, definition-code, definitions, changed-definition, collisions-kept-views and draft-reads-stored tests: 73 pass.Compare745 /**
746 * The texts at positions [page * 256, (page + 1) * 256) of packedTexts(file) (abso Capacity): a layout reads only the
747 * pages holding a line it shows.
748 */
749 packedTextPage(file: number, page: number): readonly (string | null)[] {
750 return this.#fileTexts!.pageAt(String(file), page);
751 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare752 *packedDeletes(file: number): IterableIterator<PackedDelete> {
753 yield* this.#fileDeletes!.values(String(file));
754 }
755 *packedAttrs(file: number): IterableIterator<PackedAttr> {
756 yield* this.#fileAttrs!.values(String(file));
757 }
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare758 *packedCrossings(file: number): IterableIterator<PackedCrossing> {
759 yield* this.#fileCrossings!.values(String(file));
760 }
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare761
762 /** Decoded file histories by path index, most recently used last, under PACKED_HISTORY_BUDGET bytes. */
763 readonly #histories = new Map<number, { counts: string; history: PackedHistory; bytes: number }>();
764 #historyBytes = 0;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare765
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare766 /**
767 * A file's line, delete and crossing history, decoded once and kept while it fits (abso Capacity). Kept under its
768 * three lists' lengths: the lists only grow, and add() lets every kept history go, so a kept one is always whole.
769 */
770 packedHistory(file: number): PackedHistory {
771 const key = String(file);
772 const counts = `${this.#fileLines!.length(key)} ${this.#fileDeletes!.length(key)} ${this.#fileCrossings!.length(key)}`;
773 const kept = this.#histories.get(file);
774 if (kept) {
775 this.#histories.delete(file);
776 if (kept.counts === counts) {
777 this.#histories.set(file, kept);
778 return kept.history;
779 }
780 this.#historyBytes -= kept.bytes;
781 }
782 const history: PackedHistory = {
783 lines: packNumbers(this.#fileLines!.values(key)),
784 deletes: packNumbers(this.#fileDeletes!.values(key)),
785 crossings: packNumbers(this.#fileCrossings!.values(key)),
786 };
787 const bytes =
788 (history.lines as Int32Array).byteLength +
789 (history.deletes as Int32Array).byteLength +
790 (history.crossings as Int32Array).byteLength +
791 200;
792 if (bytes <= PACKED_HISTORY_BUDGET) {
793 this.#histories.set(file, { counts, history, bytes });
794 this.#historyBytes += bytes;
795 for (const [old, entry] of this.#histories) {
796 if (this.#historyBytes <= PACKED_HISTORY_BUDGET) break;
797 this.#histories.delete(old);
798 this.#historyBytes -= entry.bytes;
799 }
800 }
801 return history;
802 }
804 /** Bytes of decoded file histories kept (packedHistory). */
805 get historyBytes(): number {
806 return this.#historyBytes;
807 }
init0Start the project809 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
810 #lists: ((seq: number) => AtomLists) | undefined;
811 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
812 #listCache = new Map<number, AtomLists>();
813 #listCached = 0;
815 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
816 #listsOf(seq: number): AtomLists {
817 const hit = this.#listCache.get(seq);
818 if (hit) {
819 this.#listCache.delete(seq);
820 this.#listCache.set(seq, hit);
821 return hit;
822 }
823 const got = this.#lists!(seq);
824 const lists: AtomLists = {
825 deletes: frozenList(got.deletes),
826 writes: frozenList(got.writes),
827 reads: frozenList(got.reads),
828 holds: frozenList(got.holds),
829 };
830 this.#listCache.set(seq, lists);
831 this.#listCached += listItems(lists);
832 for (const [old, kept] of this.#listCache) {
833 if (this.#listCached <= LIST_CACHE || old === seq) break;
834 this.#listCache.delete(old);
835 this.#listCached -= listItems(kept);
836 }
837 return lists;
838 }
840 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
841 #listReader(seq: number): () => AtomLists {
842 return () => this.#listsOf(seq);
843 }
845 /**
846 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
847 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
848 * naming a line the graph doesn't have stays a string, which nothing has claimed.
849 */
850 #code(key: Key): Key | number {
851 const t = key.charCodeAt(0);
852 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
853 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
854 if (k < 0) return key;
855 const n = this.#lineN(key.slice(2));
856 return n < 0 ? key : n * 4 + k;
857 }
859 /** An atom's lines' text, in k order. */
860 #textOf(seq: number): readonly string[] {
861 const hit = this.#textCache.get(seq);
862 if (hit) {
863 this.#textCache.delete(seq);
864 this.#textCache.set(seq, hit);
865 return hit;
866 }
867 const flat = this.#texts!(seq).flat();
868 let chars = 0;
869 for (const t of flat) chars += t.length + 1;
870 this.#textCache.set(seq, flat);
871 this.#textCached += chars;
872 for (const [old, lines] of this.#textCache) {
873 if (this.#textCached <= TEXT_CACHE || old === seq) break;
874 this.#textCache.delete(old);
875 for (const t of lines) this.#textCached -= t.length + 1;
876 }
877 return flat;
878 }
880 /**
881 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
882 * keep add()'s whole scope alive, the atom as given with all its text included.
883 */
884 #reader(seq: number): (start: number, length: number) => readonly string[] {
885 return (start, length) => this.#textOf(seq).slice(start, start + length);
886 }
888 /** Line n's text. */
889 #text(n: number): string {
890 if (this.#lineText) return this.#lineText[n]!;
891 const seq = this.#lineAtom.at(n);
892 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
893 }
894 #paths: string[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare895 #pathIndex: StateMap<string, number> = new Map();
init0Start the project896 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare897 #deleter: NumberIndex = new Ints();
898 #moreDeleters: StateMap<number, number[]> = new Map();
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare899 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare900 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare901 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare902 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare903 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare904 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare905 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare906 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare907 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare908 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare909 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare910 #together: StateMap<AtomId, TogetherLink[]> = new Map();
codex-capacity-chair129Page together relationship history for bounded traversalCompare911 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity).
why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms.
- Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before.
- Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before.
- trail takes atoms' numbers from their ids instead of reading each atom.
On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB.
New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare912 /** The atoms whose reasons point at each atom, in seq order, once each (abso Capacity). */
913 #reasonsIn = new Map<AtomId, AtomId[]>();
914 #reasonsInPages: ReturnType<typeof storedLists<AtomId>> | undefined;
915 /** Whether a stored graph keeps reasons-in: from a fresh graph on, worked out when first needed. */
916 #reasonsInKnown: boolean | undefined;
917 get #reasonsInKept(): boolean {
918 if (!this.#storage) return true;
919 this.#reasonsInKnown ??= this.#storage.read("reasons-in:meta", "kept") === 1;
920 return this.#reasonsInKnown;
921 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare922 #fileAtoms: StateMap<string, AtomId[]> = new Map();
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare923 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
init0Start the project924 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare925 #runStarts: StateMap<number, number | number[]> = new Map();
codex-capacity-chair130Stream paged child history into layout filteringCompare926 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
init0Start the project927 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare928 #replacing: NumberIndex = new Ints(true);
929 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare930 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare931 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare932 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
init0Start the project933 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare934 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare935 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare937 /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
938 #moverList: AtomId[] | undefined;
940 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare941 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
942 #labels: StateMap<string, Label> = new Map();
944 #authors = new Map<string, string>();
946 /** Number of atoms (also the seq the next atom gets). */
947 get size(): number {
948 return this.#atoms.length;
949 }
capacity238Collisions: deleted lines found by number, and the move index skips graphs that gained nothing (disk-first 2; abso Capacity).
Collisions on website took 20.7 s cold with one opened writer (replay 0.4 s), and 46 s on typescript-rs (replay 5 s).
- touchedFiles finds each deleted line's file by its number where the view can (fileOfNumber). A draft deleting a big file has thousands; making each one's id only to look its number up again was most of the time.
- Graph.accepted counts the atoms a graph object has taken in, in memory. The move index (MoveSkeleton) is brought up to date on every lookup of a line's file. It now reads the movers list only when that count has changed: checking the stored list's length and last mover each time cost 3.3 s of collisions on website. A rolled-back add still counts, which only makes it look again.
On website adopted fresh, cold: collisions 20.7 s to 9.6 s. On typescript-rs: 46 s to 11.7 s. Both match replay, and all 27 typescript-rs answers match. Still slow: reading every draft atom's write keys, a row per key once there are more than 256 (75,000 rows on website).
Named tests: every engine test (288 of 288), every worker/project test (341 of 341); tsc and biome clean.Compare951 /**
952 * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the
953 * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a
954 * cache look again.
955 */
956 get accepted(): number {
957 return this.#accepted;
958 }
959 #accepted = 0;
962 nextId(): AtomId {
963 return atomId(this.#atoms.length);
964 }
966 has(id: AtomId): boolean {
967 const seq = this.#seq(id);
968 return seq >= 0 && seq < this.#atoms.length;
969 }
971 atom(id: AtomId): Atom {
972 const seq = this.#seq(id);
973 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
974 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
975 return atom;
976 }
978 /** All atoms in seq order. */
979 atoms(): readonly Atom[] {
980 return this.#atoms;
981 }
983 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
984 lamport(id: AtomId): number {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare985 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare986 return this.#lamportAt(this.#seq(id));
989 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
990 comparePriority(a: AtomId, b: AtomId): number {
991 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
992 }
994 line(id: LineId): LineInfo | undefined {
995 const n = this.#lineN(id);
996 if (n < 0) return undefined;
997 const seq = this.#lineAtom.at(n);
998 return {
999 id,
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1000 atom: this.idOfSeq(seq),
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1002 file: this.#pathName(this.#lineFile.at(n)),
1004 text: this.#text(n),
1005 };
1006 }
1008 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
1009 lineText(id: LineId): string | undefined {
1010 const n = this.#lineN(id);
1011 return n < 0 ? undefined : this.#text(n);
1012 }
1014 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
1015 lineAtom(id: LineId): AtomId | undefined {
1016 const n = this.#lineN(id);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1017 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
1020 /** The file a line was written in, or undefined: line(id).file without making the record. */
1021 lineFile(id: LineId): string | undefined {
1022 const n = this.#lineN(id);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1023 return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));
1026 /** The node a line was written after, or undefined: line(id).parent without making the record. */
1027 lineParent(id: LineId): NodeId | undefined {
1028 const n = this.#lineN(id);
1029 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
1030 }
1032 // By number, for views (#46) ------------------------------------------------------
1033 // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph
1034 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
1036 /** A line id's n, or -1 for an unknown line. */
1037 lineN(id: LineId): number {
1038 return this.#lineN(id);
1039 }
1041 /** A line's id from its n. */
1042 lineIdOf(n: number): LineId {
1043 return this.#lineName(n);
1044 }
1046 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
1047 deletedLines(id: AtomId): readonly LineId[] {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1048 const seq = this.#seq(id);
1049 const count = this.#storage?.read("atom-delete-counts", String(seq));
1050 if (count !== undefined) {
1051 const out: LineId[] = [];
1052 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
1053 out.push(this.#lineName(n));
1054 if (out.length !== count) throw Error("incomplete atom deletion index");
1055 return out;
1056 }
1058 if (!ns) return EMPTY;
1059 const out: LineId[] = new Array(ns.length);
1060 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
1061 return out;
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export.
- where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line.
- Draft files (overlaps.ts) go by number the same way.
- An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this).
- Draft collisions:
- build the union view only when two drafts share a file;
- work out each agent's touched files and its "shared now plus draft" view once;
- find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history;
- have the definition rule keep a draft's uses, and the newer work's definitions, across partners.
- A stored list read in order reads its length once, not before every element.
draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail.
On website's export (1,387 entries) the answers match Project.load:
- status: 17 s to 4.5 s
- where: over 60 s to 8.8 s
- drafts: 14 s to 5.3 s
- collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare1062 }
1064 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
1065 *deletedNumbers(id: AtomId): IterableIterator<number> {
1066 const seq = this.#seq(id);
1067 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
1068 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
1069 return;
1070 }
1071 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
1074 /** How many lines an atom deletes, without reading its lists. */
1075 deleteCount(id: AtomId): number {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1076 const seq = this.#seq(id);
1077 const count = this.#storage?.read("atom-delete-counts", String(seq));
1078 if (count !== undefined) {
1079 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
1080 return count as number;
1081 }
1082 return this.#atomDeletes[seq]?.length ?? 0;
1085 textOf(n: number): string {
1086 return this.#text(n);
1087 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare1089 /** Historical text in bounded chunks, without decoding a whole stored line. */
1090 *textChunks(n: number): IterableIterator<string> {
1091 if (!this.#storage) {
1092 const text = this.#text(n);
1093 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
1094 yield text.slice(offset, offset + StoredText.chunkCharacters);
1095 return;
1096 }
1097 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
1098 const value = this.#storage.read("line-text", String(n));
1099 if (typeof value === "string") {
1100 yield value;
1101 return;
1102 }
1103 const reference = value as { format?: number; text?: string } | undefined;
1104 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
1105 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
1106 }
1109 writerSeqOf(n: number): number {
1110 return this.#lineAtom.at(n);
1111 }
1113 /** Line n's k: its place among its atom's lines. */
1114 kOf(n: number): number {
1115 return n - this.#lineBase[this.#lineAtom.at(n)]!;
1116 }
1118 /** The atom id with this seq, as the graph keeps it. */
1119 idOfSeq(seq: number): AtomId {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1120 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
1121 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
1122 return atomId(seq);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1123 }
1125 #lamportAt(seq: number): number {
1126 return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
1129 lamportOfSeq(seq: number): number {
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1130 return this.#lamportAt(seq);
1133 /** The file line n was written in. */
1134 writtenIn(n: number): string {
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1135 return this.#pathName(this.#lineFile.at(n));
1138 /** The code of the node line n was written after. */
1139 parentCodeOf(n: number): number {
1140 return this.#lineParent.at(n);
1141 }
1143 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
1144 codeOf(node: NodeId): number | undefined {
1145 return this.#nodeCode(node);
1146 }
1148 /** The node a code names. */
1149 nodeOf(code: number): NodeId {
1150 return this.#nodeName(code);
1151 }
1153 /** The start node's code for a path, or undefined when nothing was ever written in it. */
1154 startCodeOf(path: string): number | undefined {
1155 const p = this.#pathIndex.get(path);
1156 return p === undefined ? undefined : -1 - p;
1157 }
1159 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1162 for (const n of this.eachChildN(code)) out.push(n);
1163 }
1164 *eachChildN(code: number): IterableIterator<number> {
1166 code >= 0 &&
1167 code + 1 < this.#lineTotal &&
1168 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1169 this.#lineParent.at(code + 1) === code
1170 )
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare1172 if (this.#runStartPages) {
1173 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1174 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1175 yield* this.#runStartPages.values(String(code));
1176 } else yield* listOf(this.#runStarts.get(code));
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1179 get hasOrderedChildren(): boolean {
1180 return this.#storage !== undefined;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare1181 }
1182 /** Synchronous derived work against one graph identity. Scratch never commits. */
1183 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1184 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1185 const size = this.size;
1186 const lines = this.lineCount;
1187 return withProjectionScratch(
1188 this.#storage,
1189 () => {
1190 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1191 },
1192 operation,
1193 );
1195 #childPriority(n: number): string {
1196 const seq = this.writerSeqOf(n);
1197 return orderedChildKey({
1198 n,
1199 replaces: this.replacesN(n) ? 1 : 0,
1200 lamport: this.lamportOfSeq(seq),
1201 seq,
1202 k: this.kOf(n),
1203 });
1204 }
1205 /** Persistent layout order with a strict successor cursor; moves are separate. */
1206 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1207 if (!this.#storage) throw new Error("ordered children require indexed storage");
1208 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1209 if (this.#storage.read("ordered-children", "format") !== 2)
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1210 throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1211 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1212 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1213 throw new Error("ordered child index count mismatch");
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1214 let implicit: number | undefined;
1215 if (
1216 code >= 0 &&
1217 code + 1 < this.#lineTotal &&
1218 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1219 this.#lineParent.at(code + 1) === code
1220 )
1221 implicit = code + 1;
codex-capacity-chair135Skip priority decoding for implicit-only child traversalCompare1222 // Most historical run lines have no explicit child. With zero or one
1223 // child, traversal needs no priority decoding or radix lookup. Keep the
1224 // format/count checks above even on this path.
1225 if (count === 0 && (after === undefined || after === implicit)) {
1226 if (implicit !== undefined && after !== implicit) yield implicit;
1227 return;
1228 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1229 const cursor = after === undefined ? undefined : this.#childPriority(after);
1230 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1231 for (const n of index.values(cursor)) {
1232 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1233 yield implicit;
1234 implicit = undefined;
1235 }
1236 yield n;
1237 }
1238 if (implicit !== undefined) yield implicit;
1239 }
1242 return this.#replacing.at(n) === 1;
1243 }
1245 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1246 deleterSeqsOf(n: number): readonly number[] {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1247 return [...this.eachDeleterSeqOf(n)];
1248 }
1249 *eachDeleterSeqOf(n: number): IterableIterator<number> {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1251 if (first < 0) return;
1252 yield first;
1253 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1254 else yield* this.#moreDeleters.get(n) ?? EMPTY;
1257 /** Every relocation that puts a line right after the node with this code. */
1258 relocatedToCode(code: number): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1259 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
1262 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1263 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1264 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
1267 /** How many lines every atom together has written. */
1268 get lineCount(): number {
1269 return this.#lineTotal;
1270 }
1272 /** A line id's n, or -1 when no accepted atom wrote it. */
1273 #lineN(id: LineId): number {
1274 const p = parseLineId(id);
1275 if (!p || p.seq >= this.#atoms.length) return -1;
1276 const base = this.#lineBase[p.seq]!;
1277 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1278 return p.k < end - base ? base + p.k : -1;
1279 }
1281 /** A line's id from its n. */
1282 #lineName(n: number): LineId {
1283 const seq = this.#lineAtom.at(n);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1284 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
1287 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1288 #nodeCode(node: NodeId): number | undefined {
1289 if (isStartNode(node)) {
1290 const p = this.#pathIndex.get(node.slice(1));
1291 return p === undefined ? undefined : -1 - p;
1292 }
1293 const n = this.#lineN(node);
1294 return n < 0 ? undefined : n;
1295 }
1297 #nodeName(code: number): NodeId {
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1298 return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1301 /**
1302 * A path's name by its index, kept in memory once read (abso Capacity): finding a deleted line's file names the file
1303 * it reaches, and a stored graph read the path list each time. Cleared when the graph accepts an atom, so a name a
1304 * rolled-back add made never stays.
1305 */
1306 #pathName(index: number): string {
1307 if (this.#pathNamesAt !== this.#accepted) {
1308 this.#pathNames.clear();
1309 this.#pathNamesAt = this.#accepted;
1310 }
1311 let name = this.#pathNames.get(index);
1312 if (name === undefined) {
1313 name = this.#paths[index]!;
1314 if (this.#pathNames.size >= PATH_NAMES) this.#pathNames.clear();
1315 this.#pathNames.set(index, name);
1316 }
1317 return name;
1318 }
1319 readonly #pathNames = new Map<number, string>();
1320 #pathNamesAt = -1;
1323 let p = this.#pathIndex.get(file);
1324 if (p === undefined) {
1325 p = this.#paths.push(file) - 1;
1326 this.#pathIndex.set(file, p);
1327 }
1328 return p;
1329 }
1331 /** The line ids an atom inserted, in k order. */
1332 linesOf(id: AtomId): LineId[] {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare1333 return [...this.eachInsertedLine(id)];
1334 }
1335 /** Inserted identities without decoding or allocating the atom's text. */
1336 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1337 const seq = this.atom(id).seq;
init0Start the project1338 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare1339 for (let k = 0; k < count; k++) yield lineId(id, k);
1342 /** Every atom that deletes this line (across the whole graph). */
1343 deletersOf(line: LineId): readonly AtomId[] {
1344 const n = this.#lineN(line);
1345 if (n < 0) return EMPTY;
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1346 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
1349 writersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1350 return [...this.eachWriterOf(key)];
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1352 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1353 const code = this.#code(key);
1354 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1355 else yield* listOf(this.#writers.get(code));
1356 }
1358 /** Atoms whose implicit reads include the key. */
1359 readersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1360 return [...this.eachReaderOf(key)];
1361 }
1362 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1363 const code = this.#code(key);
1364 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1365 else yield* listOf(this.#readers.get(code));
1368 /** Atoms whose explicit holds include the key. */
1369 holdersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1370 return [...this.eachHolderOf(key)];
1371 }
1372 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1373 const code = this.#code(key);
1374 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1375 else yield* listOf(this.#holders.get(code));
1378 /** Every atom that inserts or deletes a line of the file, in seq order. */
1379 atomsIn(file: string): readonly AtomId[] {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1380 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1382 }
1383 *eachAtomIn(file: string): IterableIterator<AtomId> {
1384 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1385 else yield* this.#fileAtoms.get(file) ?? EMPTY;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1387 hasAtomsIn(file: string): boolean {
1388 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1389 }
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1391 /** Unique historical file paths, streamed without collecting their names. */
1392 *knownFiles(): IterableIterator<string> {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1393 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1394 }
1397 * The files an atom inserts, deletes or moves lines in, or sets attributes
1398 * of, sorted. For lines, the file each was written in (or, for a move to a
1399 * start node, that file): a set's moves can have taken them elsewhere.
1400 */
1401 filesOf(id: AtomId): readonly string[] {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1402 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1404 }
1406 /** Lines written right after a node (not counting moves), in seq order. */
1409 const code = this.#nodeCode(node);
codex-capacity-chair130Stream paged child history into layout filteringCompare1410 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1413 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1414 replaces(line: LineId): boolean {
1415 const n = this.#lineN(line);
1416 return n >= 0 && this.#replacing.at(n) === 1;
1417 }
1419 /** Every relocation of a line, in seq order. */
1420 relocationsOf(line: LineId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1421 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1423 }
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1424 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1425 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1426 else yield* this.#relocations.get(line) ?? EMPTY;
1427 }
1429 /** Every relocation that puts a line right after this node, in seq order. */
1430 relocatedTo(node: NodeId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1431 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1433 }
1435 /** Atoms that move lines, in seq order. */
1436 movers(): readonly AtomId[] {
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1437 if (!this.#storage) return this.#movers;
1438 // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1439 const length = this.#movers.length;
1440 const list = this.#moverList;
1441 if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1442 this.#moverList = [...this.#movers];
1443 return this.#moverList;
1446 /** Atoms that list this one directly in their deps. */
1447 dependentsOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1448 return [...this.eachDependentOf(id)];
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1450 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1451 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1452 else yield* listOf(this.#dependents.get(id));
1453 }
1455 /** Atoms whose `resolves` names this one. */
1456 resolversOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1457 return [...this.eachResolverOf(id)];
1458 }
1459 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1460 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1461 else yield* listOf(this.#resolvers.get(id));
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity).
why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms.
- Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before.
- Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before.
- trail takes atoms' numbers from their ids instead of reading each atom.
On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB.
New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1464 /**
1465 * The atoms whose reasons point at this one, in seq order, once each; or undefined when a stored graph made before
1466 * this index keeps none, and the caller looks at every atom (abso Capacity).
1467 */
1468 reasonsTo(id: AtomId): readonly AtomId[] | undefined {
1469 if (!this.#reasonsInKept) return undefined;
1470 if (this.#reasonsInPages) return [...this.#reasonsInPages.values(id)];
1471 return this.#reasonsIn.get(id) ?? [];
1472 }
1475 togetherLinks(id: AtomId): readonly TogetherLink[] {
codex-capacity-chair129Page together relationship history for bounded traversalCompare1476 return [...this.eachTogetherLink(id)];
codex-capacity-chair129Page together relationship history for bounded traversalCompare1478 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1479 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1480 else yield* this.#together.get(id) ?? EMPTY;
1481 }
1483 /**
1484 * The atom plus everything it depends on, transitively. Computed on demand
1485 * and not cached: a cached set per atom costs memory quadratic in the length
1486 * of a dependency chain. Use `dependsOn` to ask about one pair.
1487 */
1488 closure(id: AtomId): Set<AtomId> {
1489 return this.closureOf([id]);
1490 }
1492 /** The atoms plus everything they depend on, transitively. */
1493 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1494 const out = new Set<AtomId>();
1495 const stack: AtomId[] = [];
1496 for (const id of ids) {
1497 this.atom(id);
1498 if (!out.has(id)) {
1499 out.add(id);
1500 stack.push(id);
1501 }
1502 }
1503 while (stack.length > 0) {
1504 for (const d of this.atom(stack.pop()!).deps) {
1505 if (!out.has(d)) {
1506 out.add(d);
1507 stack.push(d);
1508 }
1509 }
1510 }
1511 return out;
1512 }
1514 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1515 dependsOn(a: AtomId, b: AtomId): boolean {
1516 const atom = this.atom(a);
1517 this.atom(b);
1518 return a === b || this.#reaches(atom.deps, b);
1519 }
1521 /**
1522 * Whether `target` is reachable along deps from any of `from` (themselves
1523 * included). A dependency always has a lower lamport than its dependent, so
1524 * the search never descends below the target's lamport.
1525 */
1526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
capacity312Atom validation checks all its line writers in one walk, in memory, not one walk per writer in storage rows (abso 714, piece 4a)
- Graph #validateAcceptedAtom checks that every line an atom touches comes from its closure. It used to walk the dependencies once for each writer, with the walk's seen set and stack as rolled-back projection-scratch rows: a read and a write in storage for each atom visited.
- Now the writers that aren't direct deps are collected first, and one walk (#reachable) finds them all. It never goes below the lowest writer's lamport and stops once every writer is found. #reaches (dependsOn) uses the same walk.
- The walk's seen marks and stack are typed arrays by atom number: 1 and 4 bytes an atom at most, about 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows since abso-core 139 ("Bound persistent dependency reachability with rollback scratch", one of ten "Bound … memory" versions on Oct 12, none of which records a measured failure). The sizing is in the comment where the rows were.
- Error messages and their order are unchanged: checkLine still runs in the same order; only the closure answers come from the one walk.
Lab, abso's Oct 14 tables with abso 1478's tree, 1470-shaped, 38 changed lines:
- record: 77,767 statements and 19,415 writes, now 53,664 and 2,405. The 24,103 statements gone are the walk's scratch rows. What's left grows with the project: membership reads (27,270), the file's text one line at a time (11,947), knownPaths' filesOf (9,162).
- publish: 9,408 statements and 1,438 writes, now 8,010 and 418.
Checks: tsc clean; Biome clean; core tests (worker/project and src): 765 of 766 passed, 1 skipped, none failed; engine tests 295 of 295, including reachability-scratch.test.ts.Compare1527 return this.#reachable(from, new Set([target])).has(target);
1528 }
1530 /**
1531 * Which of `targets` are reachable along deps from any of `from` (themselves included), in one walk: it never
1532 * descends below the lowest target's lamport, and stops once every target is found (abso 714, piece 4: record
1533 * walked once per line writer).
1534 * The walk's seen marks and stack are in memory, by atom number: one byte and four bytes an atom at most, so about
1535 * 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
1536 * (abso-core 139, bounding memory with the graph), which cost a read and a write per atom visited: on abso's Oct 14
1537 * tables, 41,000 of a 1470-shaped record's 77,767 statements.
1538 */
1539 #reachable(from: Iterable<AtomId>, targets: ReadonlySet<AtomId>): Set<AtomId> {
1540 const found = new Set<AtomId>();
1541 let floor = Number.POSITIVE_INFINITY;
1542 for (const target of targets) floor = Math.min(floor, this.#lamportAt(this.#seq(target)));
1543 const seen = new Uint8Array(this.#atoms.length);
1544 const stack = new Int32Array(this.#atoms.length);
1545 let length = 0;
1546 const visit = (id: AtomId): void => {
1547 if (targets.has(id)) found.add(id);
1548 const seq = this.#seq(id);
1549 if (seen[seq]) return;
1550 seen[seq] = 1;
1551 stack[length++] = seq;
1552 };
1553 for (const id of from) visit(id);
1554 while (length > 0 && found.size < targets.size) {
1555 const seq = stack[--length]!;
1556 if (this.#lamportAt(seq) <= floor) continue;
1557 for (const dependency of this.atom(atomId(seq)).deps) visit(dependency);
capacity312Atom validation checks all its line writers in one walk, in memory, not one walk per writer in storage rows (abso 714, piece 4a)
- Graph #validateAcceptedAtom checks that every line an atom touches comes from its closure. It used to walk the dependencies once for each writer, with the walk's seen set and stack as rolled-back projection-scratch rows: a read and a write in storage for each atom visited.
- Now the writers that aren't direct deps are collected first, and one walk (#reachable) finds them all. It never goes below the lowest writer's lamport and stops once every writer is found. #reaches (dependsOn) uses the same walk.
- The walk's seen marks and stack are typed arrays by atom number: 1 and 4 bytes an atom at most, about 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows since abso-core 139 ("Bound persistent dependency reachability with rollback scratch", one of ten "Bound … memory" versions on Oct 12, none of which records a measured failure). The sizing is in the comment where the rows were.
- Error messages and their order are unchanged: checkLine still runs in the same order; only the closure answers come from the one walk.
Lab, abso's Oct 14 tables with abso 1478's tree, 1470-shaped, 38 changed lines:
- record: 77,767 statements and 19,415 writes, now 53,664 and 2,405. The 24,103 statements gone are the walk's scratch rows. What's left grows with the project: membership reads (27,270), the file's text one line at a time (11,947), knownPaths' filesOf (9,162).
- publish: 9,408 statements and 1,438 writes, now 8,010 and 418.
Checks: tsc clean; Biome clean; core tests (worker/project and src): 765 of 766 passed, 1 skipped, none failed; engine tests 295 of 295, including reachability-scratch.test.ts.Compare1559 return found;
1562 /**
1563 * Accept an atom into the graph. It must carry the next id and seq, and
1564 * everything it touches must come from atoms in its dependency closure.
1565 * The atom is frozen. Adding to the graph does not add it to any set.
1566 */
1567 add(atom: Atom): void {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare1568 // A new atom appends to its files' histories; a failed one may leave a kept history longer than the lists.
1569 this.#histories.clear();
1570 this.#historyBytes = 0;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare1571 if (this.#storage)
1572 this.#storage.transaction(() => {
1573 this.#add(atom);
1574 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1575 if (result && typeof result === "object" && "then" in result)
1576 throw Error("accepted atom indexing must be synchronous");
1577 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1578 else this.#add(atom);
1579 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1581 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1582 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1583 if (!scratch) return new Set<T>();
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare1584 return {
1585 has: (key) => scratch.read(name, key) === true,
1586 add: (key) => scratch.write(name, key, true),
1587 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1588 };
1590 const seq = this.#atoms.length;
1591 const bad = (why: string): never => {
1592 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1593 };
1594 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1596 const deps = membership<AtomId>("deps");
1598 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1599 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1600 deps.add(d);
1601 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1602 for (const list of [atom.needs, atom.resolves])
1603 for (const d of list) {
1604 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1605 }
init0Start the project1606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1608 // Everything it touches must come from its closure. Derived deps name the
capacity312Atom validation checks all its line writers in one walk, in memory, not one walk per writer in storage rows (abso 714, piece 4a)
- Graph #validateAcceptedAtom checks that every line an atom touches comes from its closure. It used to walk the dependencies once for each writer, with the walk's seen set and stack as rolled-back projection-scratch rows: a read and a write in storage for each atom visited.
- Now the writers that aren't direct deps are collected first, and one walk (#reachable) finds them all. It never goes below the lowest writer's lamport and stops once every writer is found. #reaches (dependsOn) uses the same walk.
- The walk's seen marks and stack are typed arrays by atom number: 1 and 4 bytes an atom at most, about 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows since abso-core 139 ("Bound persistent dependency reachability with rollback scratch", one of ten "Bound … memory" versions on Oct 12, none of which records a measured failure). The sizing is in the comment where the rows were.
- Error messages and their order are unchanged: checkLine still runs in the same order; only the closure answers come from the one walk.
Lab, abso's Oct 14 tables with abso 1478's tree, 1470-shaped, 38 changed lines:
- record: 77,767 statements and 19,415 writes, now 53,664 and 2,405. The 24,103 statements gone are the walk's scratch rows. What's left grows with the project: membership reads (27,270), the file's text one line at a time (11,947), knownPaths' filesOf (9,162).
- publish: 9,408 statements and 1,438 writes, now 8,010 and 418.
Checks: tsc clean; Biome clean; core tests (worker/project and src): 765 of 766 passed, 1 skipped, none failed; engine tests 295 of 295, including reachability-scratch.test.ts.Compare1609 // writers directly, so this is usually one lookup per writer. The writers
1610 // that aren't deps are walked for together, once (abso 714, piece 4).
1611 const touched: LineId[] = [];
1612 for (const run of atom.inserts) if (!isStartNode(run.parent)) touched.push(run.parent);
1613 for (const m of atom.moves ?? []) {
1614 touched.push(m.line);
1615 if (!isStartNode(m.parent)) touched.push(m.parent);
1616 }
1617 touched.push(...atom.deletes);
1618 for (const list of [atom.writes, atom.reads, atom.holds])
1619 for (const key of list) {
1620 const parsed = parseKey(key);
1621 if (parsed.kind === "line" || ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)))
1622 touched.push(parsed.node);
capacity312Atom validation checks all its line writers in one walk, in memory, not one walk per writer in storage rows (abso 714, piece 4a)
- Graph #validateAcceptedAtom checks that every line an atom touches comes from its closure. It used to walk the dependencies once for each writer, with the walk's seen set and stack as rolled-back projection-scratch rows: a read and a write in storage for each atom visited.
- Now the writers that aren't direct deps are collected first, and one walk (#reachable) finds them all. It never goes below the lowest writer's lamport and stops once every writer is found. #reaches (dependsOn) uses the same walk.
- The walk's seen marks and stack are typed arrays by atom number: 1 and 4 bytes an atom at most, about 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows since abso-core 139 ("Bound persistent dependency reachability with rollback scratch", one of ten "Bound … memory" versions on Oct 12, none of which records a measured failure). The sizing is in the comment where the rows were.
- Error messages and their order are unchanged: checkLine still runs in the same order; only the closure answers come from the one walk.
Lab, abso's Oct 14 tables with abso 1478's tree, 1470-shaped, 38 changed lines:
- record: 77,767 statements and 19,415 writes, now 53,664 and 2,405. The 24,103 statements gone are the walk's scratch rows. What's left grows with the project: membership reads (27,270), the file's text one line at a time (11,947), knownPaths' filesOf (9,162).
- publish: 9,408 statements and 1,438 writes, now 8,010 and 418.
Checks: tsc clean; Biome clean; core tests (worker/project and src): 765 of 766 passed, 1 skipped, none failed; engine tests 295 of 295, including reachability-scratch.test.ts.Compare1624 const beyond = new Set<AtomId>();
1625 for (const line of touched) {
1626 const writer = this.lineAtom(line);
1627 if (writer !== undefined && !deps.has(writer)) beyond.add(writer);
1628 }
1629 const reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond;
1630 const inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer);
1632 const writer = this.lineAtom(line);
1633 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1634 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1635 };
1637 for (const run of atom.inserts) {
1638 if (isStartNode(run.parent)) {
1639 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1640 } else {
1641 // The parent may have been moved into run.file, so its own file can differ.
1642 checkLine(run.parent, "an insert");
1643 }
1644 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1645 const writes = membership<Key>("writes");
1646 for (const key of atom.writes) writes.add(key);
1647 const moved = membership<LineId>("moved");
1649 checkLine(m.line, "a move");
1650 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1651 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1652 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1653 moved.add(m.line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1654 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
init0Start the project1655 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1656 }
1657 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1658 const deleted = membership<LineId>("deleted");
1660 checkLine(line, "a delete");
1661 if (deleted.has(line)) bad(`deletes ${line} twice`);
1662 deleted.add(line);
1663 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1664 for (const line of atom.deletes)
1665 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1666 for (const list of [atom.writes, atom.reads, atom.holds])
1667 for (const key of list) {
1668 const parsed = parseKey(key);
1669 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1670 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1671 checkLine(parsed.node, `key ${key}`);
1672 }
1673 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1675 #add(atom: Atom): void {
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1676 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1677 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1678 this.#storage.write("ordered-children", "format", 2);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1679 }
1680 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare1681 this.#storage.write("file-lines:meta", "format", 2);
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity).
why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms.
- Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before.
- Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before.
- trail takes atoms' numbers from their ids instead of reading each atom.
On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB.
New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1682 this.#storage.write("reasons-in:meta", "kept", 1);
1683 this.#reasonsInKnown = true;
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare1684 this.#formatKnown = 2;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1686
1687 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1688 else this.#validateAcceptedAtom(atom);
1689 const seq = this.#atoms.length;
1690 const deps = atom.deps;
1691 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1692 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1694 // Accept.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1695 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1696 const frozen = this.#storage
1697 ? atom
1698 : freezeAtom(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1699 atom,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1700 (id) => this.idOfSeq(seqOf(id)),
1701 (author) => {
1702 if (this.#storage) return author;
1703 let a = this.#authors.get(author);
1704 if (a === undefined) this.#authors.set(author, (a = author));
1705 return a;
1706 },
1707 this.#texts ? this.#reader(seq) : undefined,
1708 this.#lists ? this.#listReader(seq) : undefined,
1709 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1710 this.#atoms.push(this.#storage ? atom : frozen);
capacity238Collisions: deleted lines found by number, and the move index skips graphs that gained nothing (disk-first 2; abso Capacity).
Collisions on website took 20.7 s cold with one opened writer (replay 0.4 s), and 46 s on typescript-rs (replay 5 s).
- touchedFiles finds each deleted line's file by its number where the view can (fileOfNumber). A draft deleting a big file has thousands; making each one's id only to look its number up again was most of the time.
- Graph.accepted counts the atoms a graph object has taken in, in memory. The move index (MoveSkeleton) is brought up to date on every lookup of a line's file. It now reads the movers list only when that count has changed: checking the stored list's length and last mover each time cost 3.3 s of collisions on website. A rolled-back add still counts, which only makes it look again.
On website adopted fresh, cold: collisions 20.7 s to 9.6 s. On typescript-rs: 46 s to 11.7 s. Both match replay, and all 27 typescript-rs answers match. Still slow: reading every draft atom's write keys, a row per key once there are more than 256 (75,000 rows on website).
Named tests: every engine test (288 of 288), every worker/project test (341 of 341); tsc and biome clean.Compare1711 this.#accepted++;
1713 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1714 if (this.#lamportPages) this.#lamportPages.push(lam);
1715 else this.#lamport.push(lam);
1717 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1718 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1719 const deletes = (line: LineId | NodeId): boolean => {
1720 if (isStartNode(line)) return false;
1721 if (deleted) return deleted.has(line);
1722 const n = this.#lineN(line);
1723 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1724 };
1725 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1726 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1727 if (this.#storage) {
1728 const pages = storedLists<number>(this.#storage, "atom-deletes");
1729 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1730 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1731 }
1732 const deletedNumbers = function* (graph: Graph) {
1733 if (deletedN) yield* deletedN;
1734 else for (const line of atom.deletes) yield graph.#lineN(line);
1735 };
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1736 const packedDeletes = new Map<number, PackedDelete[]>();
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1737 for (const n of deletedNumbers(this)) {
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1738 if (this.#packed) {
1739 const file = this.#lineFile.at(n);
1740 const list = packedDeletes.get(file);
1741 if (list) list.push([n, seq]);
1742 else packedDeletes.set(file, [[n, seq]]);
1743 }
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1745 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1748 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
1750 for (const run of atom.inserts) {
1751 const file = this.#pathOf(run.file);
1752 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1753 const first = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1754 if (parent >= 0) this.#childCounts?.increment(parent, first);
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1755 if (this.#storage)
1756 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1757 orderedChildKey({
1758 n: first,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1759 replaces: deletes(run.parent) ? 1 : 0,
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1760 lamport: lam,
1761 seq,
1762 k: first - this.#lineBase[seq]!,
1763 }),
1764 first,
1765 );
codex-capacity-chair130Stream paged child history into layout filteringCompare1767 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1768 else pushOne(this.#runStarts, parent, first);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1769 const replacesParent = deletes(run.parent) ? 1 : 0;
1770 if (this.#packed) {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare1771 if (this.#crossings && parent >= 0) {
1772 const from = this.#lineFile.at(parent);
1773 if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
1774 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1775 const base = this.#lineBase[seq]!;
1776 this.#fileLines!.appendAll(
1777 String(file),
1778 run.lines.map(
1779 (_, i): PackedLine => [
1780 first + i,
1781 i === 0 ? parent : first + i - 1,
1782 seq,
1783 first + i - base,
1784 i === 0 ? replacesParent : 0,
1785 ],
1786 ),
1787 );
1788 this.#fileTexts!.appendAll(
1789 String(file),
1790 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1791 );
1792 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1794 const n = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1795 this.#childCounts?.append(n);
1797 this.#lineFile.push(file);
1798 this.#lineParent.push(parent);
1799 this.#lineText?.push(run.lines[i]!);
1800 this.#deleter.push(-1);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1801 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1803 }
1804 }
1805 (frozen.moves ?? []).forEach((m, i) => {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare1806 const info: RelocationInfo = Object.freeze({
1807 atom: frozen.id,
1808 line: m.line,
1809 parent: m.parent,
1810 k: i,
1811 });
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1812 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1813 else pushIndex(this.#relocations, m.line, info);
1814 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1815 else pushIndex(this.#relocatedTo, m.parent, info);
1816 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1817 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1818 else pushIndex(this.#relocatedToCode, parentCode, info);
1820 if (frozen.moves) this.#movers.push(frozen.id);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1821 if (this.#packed)
1822 for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1823 for (const key of writes) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1824 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1825 if (this.#writersPages) {
1826 const key = JSON.stringify([typeof code, code]);
1827 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1828 } else pushOne(this.#writers, code, frozen.id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1830 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1831 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1832 if (this.#readersPages) {
1833 const key = JSON.stringify([typeof code, code]);
1834 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1835 } else pushOne(this.#readers, code, frozen.id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1837 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1838 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1839 if (this.#holdersPages) {
1840 const key = JSON.stringify([typeof code, code]);
1841 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1842 } else pushOne(this.#holders, code, frozen.id);
1844 for (const d of deps) {
1845 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1846 else pushOne(this.#dependents, d, frozen.id);
1847 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1848 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1849 if (this.#resolversPages) {
1850 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1851 } else pushOne(this.#resolvers, r, frozen.id);
1853 const files = new Set<string>();
1854 for (const run of atom.inserts) files.add(run.file);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity).
After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way.
Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays.
On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match.
Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1855 for (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n)));
1857 for (const m of frozen.moves ?? []) {
1858 files.add(this.lineFile(m.line)!);
1859 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1860 }
1861 this.#atomFiles.push(Object.freeze([...files].sort()));
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1862 for (const file of files) {
1863 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1864 else pushIndex(this.#fileAtoms, file, frozen.id);
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity).
why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms.
- Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before.
- Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before.
- trail takes atoms' numbers from their ids instead of reading each atom.
On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB.
New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1865 }
1866 if (this.#reasonsInKept) {
1867 const pointed = new Set<AtomId>();
1868 for (const r of frozen.reasons) {
1869 if (pointed.has(r.to)) continue;
1870 pointed.add(r.to);
1871 if (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id);
1872 else pushIndex(this.#reasonsIn, r.to, frozen.id);
1873 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1874 }
1876 if (r.kind !== "together" || r.to === frozen.id) continue;
1878 const forward = { other: r.to, text: r.text, from: frozen.id };
1879 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1880 if (this.#togetherPages) {
1881 this.#togetherPages.append(frozen.id, forward);
1882 this.#togetherPages.append(r.to, reverse);
1883 } else {
1884 pushIndex(this.#together, frozen.id, forward);
1885 pushIndex(this.#together, r.to, reverse);
1886 }
1888 }
1890 // Labels -----------------------------------------------------------------
1892 /**
1893 * Add or replace a label. Label names may not look like atom ids. A base is
1894 * resolved to its head only when it is used, never followed further, so
1895 * bases may name each other in any shape.
1896 */
1897 setLabel(label: Label): void {
1898 this.#putLabel(label, (name) => this.#labels.has(name));
1899 }
1901 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1902 const bad = (why: string): never => {
1903 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1904 };
1905 if (typeof label !== "object" || label === null) bad("not an object");
1906 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1907 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1908 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1909 if (
1910 label.base !== undefined &&
1911 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1912 ) {
1913 bad(`base ${label.base} is neither a label nor an atom`);
1914 }
1915 if (label.base === label.name) bad("a label cannot be its own base");
1916 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1917 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1918 const copy: Label = {
1919 name: label.name,
1920 head: label.head,
1921 ...(label.base !== undefined ? { base: label.base } : {}),
1922 title: label.title,
1923 message: label.message,
1924 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1925 };
1926 this.#labels.set(label.name, Object.freeze(copy));
1927 }
1929 label(name: string): Label | undefined {
1930 return this.#labels.get(name);
1931 }
1933 /** Labels sorted by name. */
1934 labels(): Label[] {
1935 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1936 }
1938 /**
1939 * Remove a label. Labels that used it as their base get its head atom as
1940 * their base instead, so their contents don't change.
1941 */
1942 removeLabel(name: string): boolean {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1943 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1944 }
1946 #removeLabel(name: string): boolean {
1948 if (!gone) return false;
1949 this.#labels.delete(name);
1950 for (const label of [...this.#labels.values()]) {
1951 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1952 }
1953 return true;
1954 }
1956 // JSON -------------------------------------------------------------------
1958 toJSON(): GraphJSON {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare1959 return {
1960 format: GRAPH_FORMAT,
1961 version: 1,
1962 atoms: this.#atoms,
1963 labels: this.labels(),
1964 };
1967 /** Load a saved graph. Every atom is re-validated as it is added. */
1968 static fromJSON(data: unknown): Graph {
1969 const bad = (why: string): never => {
1970 throw new EngineError("bad-json", why);
1971 };
1972 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1973 const obj = data as Partial<GraphJSON>;
1974 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1975 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1976 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1977 const graph = new Graph();
1978 for (const atom of obj.atoms!) graph.add(atom);
1979 // Labels may name each other as bases, in any order and any shape.
1980 const names = new Set<string>();
1981 for (const label of obj.labels!) {
1982 const name: unknown = (label as Partial<Label> | null)?.name;
1983 if (typeof name !== "string") return bad("every label needs a name");
1984 if (names.has(name)) bad(`label ${name} appears twice`);
1985 names.add(name);
1986 }
1987 for (const label of obj.labels!) {
1988 try {
1989 graph.#putLabel(label, (name) => names.has(name));
1990 } catch (err) {
1991 if (err instanceof EngineError) bad(err.message);
1992 throw err;
1993 }
1994 }
1995 return graph;
1996 }
1998 #seq(id: AtomId): number {
1999 return typeof id === "string" ? seqOf(id) : -1;
2000 }
2001}
2003function validateShape(atom: Atom): void {
2004 const bad = (why: string): never => {
2005 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
2006 };
2007 if (typeof atom !== "object" || atom === null) bad("not an object");
2008 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
2009 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
2010 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
2011 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
2012 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
2013 for (const run of atom.inserts as readonly InsertRun[]) {
2014 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
2015 if (typeof run.parent !== "string") bad("a run needs a parent");
2016 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
2017 for (const text of run.lines) {
2018 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
2019 bad("run lines must be strings without line breaks");
2020 }
2021 }
2022 if (atom.attrs !== undefined) {
2023 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
2024 for (const a of atom.attrs) {
2025 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
2026 bad("an attr needs a file and a name");
2027 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
2028 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
2029 }
2030 }
2031 if (atom.moves !== undefined) {
2032 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
2033 for (const m of atom.moves) {
2034 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
2035 }
2036 }
2037 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
2038 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
2039 }
2040 for (const r of atom.reasons as readonly Reason[]) {
2041 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
2042 bad("a reason needs to, kind (together, because-of or supersedes) and text");
2043 }
2044 }
2045}
2047/**
2048 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
2049 * ids and authors are the graph's own strings (`canon`, `author`), so each is
2050 * kept once however often it's named (#46).
2051 */
2052function freezeAtom(
2053 atom: Atom,
2054 canon: (id: AtomId) => AtomId,
2055 author: (name: string) => string,
2056 text?: (start: number, length: number) => readonly string[],
2057 lists?: () => AtomLists,
2058): Atom {
2059 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
2060 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
2061 // With text kept elsewhere (#46), a run's lines are read when asked for.
2062 let k = 0;
2063 const run = (r: InsertRun): InsertRun => {
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare2064 if (!text)
2065 return Object.freeze({
2066 file: r.file,
2067 parent: r.parent,
2068 lines: Object.freeze([...r.lines]),
2069 });
2071 const length = r.lines.length;
2072 k += length;
2073 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
2074 };
2075 const copy: Atom = {
2076 id: atom.id,
2077 seq: atom.seq,
2078 author: author(atom.author),
2079 message: atom.message,
2080 time: atom.time,
2081 inserts: Object.freeze(atom.inserts.map(run)),
2082 ...(lists
2083 ? {}
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare2084 : {
2085 deletes: list(atom.deletes),
2086 writes: list(atom.writes),
2087 reads: list(atom.reads),
2088 holds: list(atom.holds),
2089 }),
2091 resolves: list(atom.resolves, canon),
2092 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
2093 deps: list(atom.deps, canon),
2094 ...(atom.attrs && atom.attrs.length > 0
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare2095 ? {
2096 attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))),
2097 }
2099 ...(atom.moves
capacity276A stored graph keeps files' decoded line histories between layouts (abso Capacity, issue 664): Graph.packedHistory, under 4 MB.
Every view of a file read its whole history from pages again: compare lays each file out once per side, collisions once per draft touching it, and a file whose lines moved in from another reads that one's history too (abso's worker files, split out of index.ts). The history (lines, deletes and crossings, no texts) is decoded once into flat 32-bit arrays, kept under its three lists' lengths, most recently used last, and add() lets every kept history go. abso's index.ts, 46,000 lines of history, takes about 1 MB.
Side by side on abso's export, same machine, two rounds, against 273: cold compare 612 to 1224 from 12.4 s to 5.0-6.5 s, cold collisions from 10.4 s to 5.0-6.9 s, cold where from 4.4 s to 1.5-2.6 s.
Tests: packed-files.test.ts adds a test that a kept history saves reads, add() lets it go, and the next layout matches the in-memory graph. tsc and Biome clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, graph-replacement-membership, graph-insertion-storage, packed-files, definition-code, definitions, changed-definition, collisions-kept-views, draft-reads-stored and collision-streaming pass.Compare2100 ? {
2101 moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))),
2102 }
2104 } as Atom;
2105 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
2106}