Lines 3–9 at 318 (were 3–8 at 164)
33// atoms and keeps indexes so those questions are cheap. 55import { ChildCounts } from "./child-counts.ts"; 6+import { JsonStringChunks, registerJsonChunkValue } from "./json-value-chunks.ts"; Lines 21–34 at 318 (were 20–31 at 164)
2021import { withProjectionScratch } from "./projection-scratch.ts"; 2223 type GraphStateStorage, 2325 readonlyStoredArray, 2932} from "./state-source.ts"; 3033import { StoredText } from "./stored-text.ts"; Lines 258–324 at 318 (were 255–265 at 164)
255258 return { seq, k }; 261+/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */ 262+export type PackedLine = [number, number, number, number, number]; 263+/** A delete of a line in a file's packed history: [n, deleter seq]. */ 264+export type PackedDelete = [number, number]; 265+/** An attribute set on a file: [seq, name, value]. */ 266+export type PackedAttr = [number, string, string | null]; 267+/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */ 268+export type PackedCrossing = [number, number]; 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. 274+export interface PackedHistory { 275+ readonly lines: ArrayLike<number>; 276+ readonly deletes: ArrayLike<number>; 277+ readonly crossings: ArrayLike<number>; 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. 286+export const PACKED_HISTORY_BUDGET = 4_000_000; 288+/** Numbers packed flat: 4 bytes each while they fit in 32 bits, else 8. */ 289+function packNumbers(rows: Iterable<readonly number[]>): Int32Array | Float64Array { 290+ const flat: number[] = []; 292+ for (const row of rows) 293+ for (const value of row) { 294+ if ((value | 0) !== value) small = false; 297+ return small ? Int32Array.from(flat) : Float64Array.from(flat); 299+const EMPTY_NUMBERS: readonly number[] = Object.freeze([]); 300+/** At most this many path names kept in memory (Graph.#pathName). */ 301+const PATH_NAMES = 4096; 302+/** Lines longer than this aren't packed with their file; their text is read on its own. */ 303+const PACKED_TEXT = 4096; 258305export class Graph { 259306 readonly #storage?: GraphStateStorage; 260307 readonly #childCounts?: ChildCounts; 261308 #atoms: Atom[] = []; 262309 #lamport: number[] = []; 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. 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; 263322 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its 264323 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a 265324 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only Lines 352–359 at 318 (were 293–298 at 164)
293352 storage?: GraphStateStorage; 294353 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */ 295354 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void; 355+ /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */ 356+ packFiles?: boolean; 298359 if (options.indexAcceptedAtom && !options.storage) Lines 387–393 at 318 (were 326–332 at 164)
326387 insertionFormat?: 1; 327388 insertionRuns?: string; 329− listFormat?: 1;
330391 listCount?: number; 331392 lists?: Partial<Record<(typeof listFields)[number], string>>; Lines 399–407 at 318 (were 338–346 at 164)
338399 const encoded = value as unknown as Partial<EncodedAtom>; 339400 if (encoded.textFormat !== undefined && encoded.textFormat !== 1) 340401 throw Error("invalid stored atom text format"); 341− if (encoded.listFormat !== undefined && encoded.listFormat !== 1)
402+ if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2) 342403 throw Error("invalid stored atom list format"); 343− if (encoded.listFormat === 1) {
404+ if (encoded.listFormat === 1 || encoded.listFormat === 2) { 346407 typeof encoded.lists !== "object" || Lines 416–429 at 318 (were 355–363 at 164)
355416 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1) 356417 throw Error("invalid stored insertion format"); 358− encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1
419+ encoded.textFormat === 1 || 420+ encoded.listFormat === 1 || 421+ encoded.listFormat === 2 || 422+ encoded.insertionFormat === 1 425+ if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0)) 426+ throw Error("invalid stored insertion placeholder"); 362428 encoded.textFormat === 1 363429 ? (start: number, length: number): readonly string[] => { Lines 434–440 at 318 (were 368–374 at 164)
368434 if (index >= start && index < start + length) { 369435 const reference = raw as unknown as TextReference; 370436 if (typeof raw === "string") result.push(raw); 371− else if (reference && typeof reference.text === "string")
437+ else if (reference && reference.text === JSON.stringify([String(atom.seq), index])) 372438 result.push(atomText.read(reference.text)); 373439 else throw Error("invalid stored atom text reference"); Lines 443–556 at 318 (were 377–419 at 164)
377443 throw Error("stored atom text range missing"); 446+ // Sequential reads advance once per run without retaining a history-sized offset array. 449+ const insertionStart = (index: number): number => { 450+ if (index < offsetRun) { 454+ while (offsetRun < index) { 455+ offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length; 460+ 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)); 469+ let inserts: readonly unknown[]; 470+ if (encoded.insertionFormat === 1) { 471+ const collection = `atom-inserts:${atom.seq}`; 472+ inserts = readonlyStoredArray(storage, collection, (raw, index) => { 473+ const run = raw as { 478+ 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"); 481+ const start = insertionStart(index); 485+ lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)), 490+ inserts = atom.inserts.map((run) => ({ 493+ lines: run.lines.map((raw) => line(raw, index++)), 496+ return { ...target, inserts }; 380500 const frozen = freezeAtom( 383503 (author) => author, 386− if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen;
506+ if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1) 507+ return streamed(frozen); 387508 const result = { ...frozen }; 388509 if (encoded.insertionFormat === 1) { 389510 const collection = `atom-inserts:${atom.seq}`; 390511 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference"); 391512 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => { 392− const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
513+ const run = raw as { 515+ parent: InsertRun["parent"]; 393518 const lines = `${collection}:lines:${index}`; 394519 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string") 395520 throw Error("invalid stored insertion run"); 396521 return Object.freeze({ 398523 parent: run.parent, 399− lines: readonlyStoredArray<string>(storage, lines, (rawLine) => {
524+ lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => { 400525 if (typeof rawLine === "string") return rawLine; 401526 const ref = rawLine as TextReference; 402− if (!ref || typeof ref.text !== "string") throw Error("invalid stored insertion text");
527+ const atomLine = insertionStart(index) + lineIndex; 528+ if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine])) 529+ throw Error("invalid stored insertion text"); 403530 return atomText.read(ref.text); 407− Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
534+ Object.defineProperty(result, "inserts", { 409539 for (const field of listFields) { 410540 const collection = encoded.lists?.[field]; 411541 if (collection === undefined) continue; 412542 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`) 413543 throw Error("invalid stored atom list reference"); 414− Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
545+ encoded.listFormat === 2 546+ ? readonlyPagedArray(storage, collection) 547+ : readonlyStoredArray(storage, collection); 548+ Object.defineProperty(result, field, { 416− return Object.freeze(result);
553+ return streamed(Object.freeze(result)); 419556 const atom = { ...input }; Lines 558–577 at 318 (were 421–435 at 164)
421558 for (const field of listFields) { 422559 const values = input[field]; 423560 if (!values || values.length <= 256) continue; 561+ // 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value. 424562 const collection = `atom-list:${input.seq}:${field}`; 425− const saved = storedArray<unknown>(storage, collection);
426− for (const value of values) saved.push(value);
563+ writePagedArray(storage, collection, values); 427564 lists[field] = collection; 428565 Object.defineProperty(atom, field, { value: [], enumerable: true }); 430567 const listCount = Object.keys(lists).length; 431568 const hasLists = listCount > 0; 432− if (atom.inserts.length > 256 || atom.inserts.some((run) => run.lines.length > 256)) {
569+ let insertionCharacters = 0; 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)) 433575 const collection = `atom-inserts:${input.seq}`; 434576 const runs = storedArray<unknown>(storage, collection); Lines 586–606 at 318 (were 444–460 at 164)
444586 lines.push({ text }); 445587 } else lines.push(line); 447− runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
592+ lines: lineCollection, 450596 insertionFormat: 1, 451597 insertionRuns: collection, 452− ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
598+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}), 453599 atom: { ...atom, inserts: [] }, 456602 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters))) 457− return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
603+ return hasLists ? { listFormat: 2, listCount, lists, atom } : atom; 459605 const inserts = atom.inserts.map((run) => ({ Lines 613–625 at 318 (were 467–478 at 164)
470− ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
616+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}), 471617 atom: { ...atom, inserts }, 475621 this.#lamport = storedArray(storage, "lamport"); 622+ this.#lamportPaged = storedNumbers(storage, "lamport-pages"); 476623 this.#lineBase = storedArray(storage, "line-base"); 477624 this.#paths = storedArray(storage, "paths"); 478625 this.#movers = storedArray(storage, "movers"); Lines 636–645 at 318 (were 489–495 at 164)
491638 if (typeof value === "string") return value; 492− const reference = value as unknown as { format: number; text: string };
639+ const reference = value as unknown as { 493643 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference"); 494644 return longText.read(reference.text); Lines 663–669 at 318 (were 513–518 at 164)
513663 this.#dependentsPages = storedLists<AtomId>(storage, "dependents"); 514664 this.#resolversPages = storedLists<AtomId>(storage, "resolvers"); 515665 this.#togetherPages = storedLists<TogetherLink>(storage, "together"); 666+ this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in"); 516667 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms"); 517668 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) => 518669 JSON.stringify(["number", Number(key)]), Lines 674–811 at 318 (were 523–531 at 164)
523674 JSON.stringify(["number", Number(key)]), 525676 this.#labels = storedMap(storage, "labels"); 677+ 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"); 681+ this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings"); 682+ this.#packFiles = options.packFiles ?? true; 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 688+ // 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. 691+ // 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. 694+ #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; 698+ #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined; 699+ /** Whether a new stored graph starts packing (GraphOptions.packFiles). */ 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. 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; 711+ return this.#formatKnown; 713+ get #packed(): boolean { 714+ return this.#format >= 1; 716+ get #crossings(): boolean { 717+ return this.#format >= 2; 720+ /** Whether this graph keeps each file's line history packed. */ 721+ get packedFiles(): boolean { 722+ return this.#packed; 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. 728+ get packedLayout(): boolean { 729+ return this.#crossings; 731+ /** 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); 735+ /** The index of the path line n was written in. */ 736+ writtenInIndex(n: number): number { 737+ return this.#lineFile.at(n); 739+ *packedLines(file: number): IterableIterator<PackedLine> { 740+ yield* this.#fileLines!.values(String(file)); 742+ *packedTexts(file: number): IterableIterator<string | null> { 743+ yield* this.#fileTexts!.values(String(file)); 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. 749+ packedTextPage(file: number, page: number): readonly (string | null)[] { 750+ return this.#fileTexts!.pageAt(String(file), page); 752+ *packedDeletes(file: number): IterableIterator<PackedDelete> { 753+ yield* this.#fileDeletes!.values(String(file)); 755+ *packedAttrs(file: number): IterableIterator<PackedAttr> { 756+ yield* this.#fileAttrs!.values(String(file)); 758+ *packedCrossings(file: number): IterableIterator<PackedCrossing> { 759+ yield* this.#fileCrossings!.values(String(file)); 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 }>(); 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. 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); 775+ this.#histories.delete(file); 776+ if (kept.counts === counts) { 777+ this.#histories.set(file, kept); 778+ return kept.history; 780+ this.#historyBytes -= kept.bytes; 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)), 788+ (history.lines as Int32Array).byteLength + 789+ (history.deletes as Int32Array).byteLength + 790+ (history.crossings as Int32Array).byteLength + 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; 804+ /** Bytes of decoded file histories kept (packedHistory). */ 805+ get historyBytes(): number { 806+ return this.#historyBytes; 529809 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */ 530810 #lists: ((seq: number) => AtomLists) | undefined; 531811 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */ Lines 909–924 at 318 (were 629–634 at 164)
629909 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined; 630910 #together: StateMap<AtomId, TogetherLink[]> = new Map(); 631911 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined; 912+ /** 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; 632922 #fileAtoms: StateMap<string, AtomId[]> = new Map(); 633923 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined; 634924 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */ Lines 934–941 at 318 (were 644–649 at 164)
644934 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map(); 645935 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined; 646936 #movers: AtomId[] = []; 937+ /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */ 938+ #moverList: AtomId[] | undefined; 647939 #atomFiles: (readonly string[])[] = []; 648940 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */ 649941 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = []; Lines 948–963 at 318 (were 656–661 at 164)
656948 return this.#atoms.length; 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 956+ get accepted(): number { 957+ return this.#accepted; 659961 /** The id the next accepted atom must have. */ 660962 nextId(): AtomId { 661963 return atomId(this.#atoms.length); Lines 983–989 at 318 (were 681–687 at 164)
681983 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */ 682984 lamport(id: AtomId): number { 683985 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`); 684− return this.#lamport[this.#seq(id)]!;
986+ return this.#lamportAt(this.#seq(id)); 687989 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */ Lines 999–1005 at 318 (were 697–703 at 164)
6981000 atom: this.idOfSeq(seq), 6991001 k: n - this.#lineBase[seq]!, 700− file: this.#paths[this.#lineFile.at(n)]!,
1002+ file: this.#pathName(this.#lineFile.at(n)), 7011003 parent: this.#nodeName(this.#lineParent.at(n)), 7021004 text: this.#text(n), Lines 1020–1026 at 318 (were 718–724 at 164)
7181020 /** The file a line was written in, or undefined: line(id).file without making the record. */ 7191021 lineFile(id: LineId): string | undefined { 7201022 const n = this.#lineN(id); 721− return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
1023+ return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n)); 7241026 /** The node a line was written after, or undefined: line(id).parent without making the record. */ Lines 1061–1076 at 318 (were 759–764 at 164)
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)); 1071+ yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS; 7621074 /** How many lines an atom deletes, without reading its lists. */ 7631075 deleteCount(id: AtomId): number { 7641076 const seq = this.#seq(id); Lines 1086–1110 at 318 (were 774–779 at 164)
7741086 return this.#text(n); 1089+ /** 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); 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") { 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); 7771108 /** The seq of the atom that wrote line n. */ 7781109 writerSeqOf(n: number): number { 7791110 return this.#lineAtom.at(n); Lines 1122–1138 at 318 (were 791–803 at 164)
7911122 return atomId(seq); 1125+ #lamportAt(seq: number): number { 1126+ return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!; 7941129 lamportOfSeq(seq: number): number { 795− return this.#lamport[seq]!;
1130+ return this.#lamportAt(seq); 7981133 /** The file line n was written in. */ 7991134 writtenIn(n: number): string { 800− return this.#paths[this.#lineFile.at(n)]!;
1135+ return this.#pathName(this.#lineFile.at(n)); 8031138 /** The code of the node line n was written after. */ Lines 1169–1179 at 318 (were 834–841 at 164)
8341169 this.#lineParent.at(code + 1) === code 837− if (this.#runStartPages) yield* this.#runStartPages.values(String(code));
838− else yield* listOf(this.#runStarts.get(code));
1172+ 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)); 8411179 get hasOrderedChildren(): boolean { Lines 1295–1324 at 318 (were 957–965 at 164)
9591297 #nodeName(code: number): NodeId { 960− return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1298+ return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code)); 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. 1306+ #pathName(index: number): string { 1307+ if (this.#pathNamesAt !== this.#accepted) { 1308+ this.#pathNames.clear(); 1309+ this.#pathNamesAt = this.#accepted; 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); 1319+ readonly #pathNames = new Map<number, string>(); 9631322 #pathOf(file: string): number { 9641323 let p = this.#pathIndex.get(file); 9651324 if (p === undefined) { Lines 1330–1342 at 318 (were 971–982 at 164)
9721331 /** The line ids an atom inserted, in k order. */ 9731332 linesOf(id: AtomId): LineId[] { 974− const atom = this.atom(id);
975− const out: LineId[] = [];
976− const seq = atom.seq;
1333+ return [...this.eachInsertedLine(id)]; 1335+ /** Inserted identities without decoding or allocating the atom's text. */ 1336+ *eachInsertedLine(id: AtomId): IterableIterator<LineId> { 1337+ const seq = this.atom(id).seq; 9771338 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!; 978− for (let k = 0; k < count; k++) out.push(lineId(id, k));
979− return out;
1339+ for (let k = 0; k < count; k++) yield lineId(id, k); 9821342 /** Every atom that deletes this line (across the whole graph). */ Lines 1434–1446 at 318 (were 1074–1080 at 164)
10751435 /** Atoms that move lines, in seq order. */ 10761436 movers(): readonly AtomId[] { 1077− return this.#movers;
1437+ 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; 10801446 /** Atoms that list this one directly in their deps. */ Lines 1461–1476 at 318 (were 1095–1100 at 164)
10951461 else yield* listOf(this.#resolvers.get(id)); 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). 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) ?? []; 10981474 /** `together` reasons touching this atom, in either direction. */ 10991475 togetherLinks(id: AtomId): readonly TogetherLink[] { 11001476 return [...this.eachTogetherLink(id)]; Lines 1524–1562 at 318 (were 1148–1190 at 164)
11481524 * the search never descends below the target's lamport. 11501526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean { 1151− const floor = this.#lamport[this.#seq(target)]!;
1152− if (this.#storage) {
1153− return this.withProjectionScratch((scratch) => {
1154− let length = 0;
1155− const push = (id: AtomId): void => {
1156− if (scratch.read("seen", id)) return;
1157− scratch.write("seen", id, true);
1158− scratch.write("stack", String(length++), id);
1159− };
1160− for (const id of from) {
1161− if (id === target) return true;
1162− if (this.#lamport[this.#seq(id)]! > floor) push(id);
1163− }
1164− while (length > 0) {
1165− const key = String(--length);
1166− const current = scratch.read("stack", key) as AtomId;
1167− scratch.remove("stack", key);
1168− if (this.#lamport[this.#seq(current)]! <= floor) continue;
1169− for (const dependency of this.atom(current).deps) {
1170− if (dependency === target) return true;
1171− push(dependency);
1172− }
1173− }
1174− return false;
1175− });
1527+ return this.#reachable(from, new Set([target])).has(target); 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. 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); 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; 1551+ stack[length++] = seq; 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); 1177− const seen = new Set<AtomId>();
1178− const stack = [...from];
1179− while (stack.length > 0) {
1180− const cur = stack.pop()!;
1181− if (cur === target) return true;
1182− if (seen.has(cur)) continue;
1183− seen.add(cur);
1184− if (this.#lamport[this.#seq(cur)]! <= floor) continue;
1185− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1186− }
1187− return false;
Lines 1565–1573 at 318 (were 1193–1198 at 164)
11931565 * The atom is frozen. Adding to the graph does not add it to any set. 11951567 add(atom: Atom): void { 1568+ // 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; 11961571 if (this.#storage) 11971572 this.#storage.transaction(() => { 11981573 this.#add(atom); Lines 1581–1590 at 318 (were 1206–1212 at 164)
12061581 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void { 12071582 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => { 12081583 if (!scratch) return new Set<T>(); 1209− return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1585+ has: (key) => scratch.read(name, key) === true, 1586+ add: (key) => scratch.write(name, key, true), 12111589 validateShape(atom); 12121590 const seq = this.#atoms.length; Lines 1606–1633 at 318 (were 1228–1250 at 164)
12281606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`); 12301608 // Everything it touches must come from its closure. Derived deps name the 1231− // writers directly, so this is usually one lookup per writer.
1232− const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1233− const below = {
1234− get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1235− set: (key: AtomId, value: boolean) => {
1236− if (scratch) scratch.write("below", key, value);
1237− else memoryBelow!.set(key, value);
1238− },
1239− };
1240− const inClosure = (writer: AtomId): boolean => {
1241− let hit = below.get(writer);
1242− if (hit === undefined) {
1243− hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1244− below.set(writer, hit);
1609+ // 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); 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); 1246− return hit;
1247− };
1624+ 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); 1629+ const reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond; 1630+ const inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer); 12481631 const checkLine = (line: LineId, what: string): void => { 12491632 const writer = this.lineAtom(line); 12501633 if (writer === undefined) return bad(`${what} names unknown line ${line}`); Lines 1677–1688 at 318 (were 1294–1299 at 164)
12941677 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 12951678 this.#storage.write("ordered-children", "format", 2); 1680+ if (this.#storage && this.#atoms.length === 0 && this.#packFiles) { 1681+ this.#storage.write("file-lines:meta", "format", 2); 1682+ this.#storage.write("reasons-in:meta", "kept", 1); 1683+ this.#reasonsInKnown = true; 1684+ this.#formatKnown = 2; 12981687 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch)); 12991688 else this.#validateAcceptedAtom(atom); Lines 1708–1718 at 318 (were 1319–1327 at 164)
13191708 this.#lists ? this.#listReader(seq) : undefined, 13211710 this.#atoms.push(this.#storage ? atom : frozen); 13231713 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1); 1324− this.#lamport.push(lam);
1714+ if (this.#lamportPages) this.#lamportPages.push(lam); 1715+ else this.#lamport.push(lam); 13261717 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist. 13271718 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log. Lines 1733–1751 at 318 (were 1342–1352 at 164)
13421733 if (deletedN) yield* deletedN; 13431734 else for (const line of atom.deletes) yield graph.#lineN(line); 1736+ const packedDeletes = new Map<number, PackedDelete[]>(); 13451737 for (const n of deletedNumbers(this)) { 1738+ 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]]); 13461744 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq); 13471745 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq); 13481746 else pushIndex(this.#moreDeleters, n, seq); 1748+ for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list); 13501749 this.#lineBase.push(this.#lineTotal); 13511750 for (const run of atom.inserts) { 13521751 const file = this.#pathOf(run.file); Lines 1766–1795 at 318 (were 1367–1372 at 164)
13681767 if (this.#runStartPages) this.#runStartPages.append(String(parent), first); 13691768 else pushOne(this.#runStarts, parent, first); 1769+ const replacesParent = deletes(run.parent) ? 1 : 0; 1770+ if (this.#packed) { 1771+ if (this.#crossings && parent >= 0) { 1772+ const from = this.#lineFile.at(parent); 1773+ if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]); 1775+ const base = this.#lineBase[seq]!; 1776+ this.#fileLines!.appendAll( 1779+ (_, i): PackedLine => [ 1781+ i === 0 ? parent : first + i - 1, 1784+ i === 0 ? replacesParent : 0, 1788+ this.#fileTexts!.appendAll( 1790+ run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)), 13701793 for (let i = 0; i < run.lines.length; i++) { 13711794 const n = this.#lineTotal; 13721795 this.#childCounts?.append(n); Lines 1803–1814 at 318 (were 1380–1386 at 164)
13821805 (frozen.moves ?? []).forEach((m, i) => { 1383− const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1806+ const info: RelocationInfo = Object.freeze({ 13841812 if (this.#relocationPages) this.#relocationPages.append(m.line, info); 13851813 else pushIndex(this.#relocations, m.line, info); 13861814 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info); Lines 1818–1825 at 318 (were 1390–1395 at 164)
13901818 else pushIndex(this.#relocatedToCode, parentCode, info); 13921820 if (frozen.moves) this.#movers.push(frozen.id); 1822+ for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]); 13931823 for (const key of writes) { 13941824 const code = this.#code(key); 13951825 if (this.#writersPages) { Lines 1852–1858 at 318 (were 1422–1428 at 164)
14231853 const files = new Set<string>(); 14241854 for (const run of atom.inserts) files.add(run.file); 1425− for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
1855+ for (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n))); 14261856 for (const a of frozen.attrs ?? []) files.add(a.file); 14271857 for (const m of frozen.moves ?? []) { 14281858 files.add(this.lineFile(m.line)!); Lines 1863–1877 at 318 (were 1433–1438 at 164)
14331863 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id); 14341864 else pushIndex(this.#fileAtoms, file, frozen.id); 1866+ if (this.#reasonsInKept) { 1867+ const pointed = new Set<AtomId>(); 1868+ for (const r of frozen.reasons) { 1869+ if (pointed.has(r.to)) continue; 1871+ if (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id); 1872+ else pushIndex(this.#reasonsIn, r.to, frozen.id); 14361875 for (const r of frozen.reasons) { 14371876 if (r.kind !== "together" || r.to === frozen.id) continue; Lines 1956–1967 at 318 (were 1517–1523 at 164)
15171956 // JSON ------------------------------------------------------------------- 15191958 toJSON(): GraphJSON { 1520− return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1960+ format: GRAPH_FORMAT, 1962+ atoms: this.#atoms, 1963+ labels: this.labels(), 15231967 /** Load a saved graph. Every atom is re-validated as it is added. */ Lines 2061–2072 at 318 (were 1617–1623 at 164)
16172061 // With text kept elsewhere (#46), a run's lines are read when asked for. 16192063 const run = (r: InsertRun): InsertRun => { 1620− if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
2065+ return Object.freeze({ 2068+ lines: Object.freeze([...r.lines]), 16212070 const start = k; 16222071 const length = r.lines.length; Lines 2081–2105 at 318 (were 1632–1647 at 164)
16322081 inserts: Object.freeze(atom.inserts.map(run)), 1635− : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
2085+ deletes: list(atom.deletes), 2086+ writes: list(atom.writes), 2087+ reads: list(atom.reads), 2088+ holds: list(atom.holds), 16362090 needs: list(atom.needs, canon), 16372091 resolves: list(atom.resolves, canon), 16382092 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })), 16392093 deps: list(atom.deps, canon), 16402094 ...(atom.attrs && atom.attrs.length > 0 1641− ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
2096+ attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))), 1644− ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
2101+ moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))), 16472105 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);