Lines 20–33 at 162 (were 20–31 at 161)
2020import { withProjectionScratch } from "./projection-scratch.ts"; 2222 type GraphStateStorage, 2829} from "./state-source.ts"; 30+import { StoredText } from "./stored-text.ts"; Lines 308–476 at 162 (were 306–317 at 161)
306308 if (options.storage) { 307309 const storage = options.storage; 308310 const numbers = (name: string): NumberIndex => storedNumbers(storage, name); 309− this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
310− freezeAtom(
311− atom,
312− (id) => id,
313− (author) => author,
314− ),
311+ const atomText = new StoredText(storage, "atom-text:long"); 312+ type TextReference = { text: string }; 313+ const listFields = [ 325+ type EncodedAtom = { 326+ insertionFormat?: 1; 327+ insertionRuns?: string; 331+ lists?: Partial<Record<(typeof listFields)[number], string>>; 334+ this.#atoms = storedArray<Atom>( 338+ const encoded = value as unknown as Partial<EncodedAtom>; 339+ if (encoded.textFormat !== undefined && encoded.textFormat !== 1) 340+ throw Error("invalid stored atom text format"); 341+ if (encoded.listFormat !== undefined && encoded.listFormat !== 1) 342+ throw Error("invalid stored atom list format"); 343+ if (encoded.listFormat === 1) { 346+ typeof encoded.lists !== "object" || 347+ Array.isArray(encoded.lists) || 348+ !Number.isSafeInteger(encoded.listCount) || 349+ encoded.listCount! < 1 || 350+ Object.keys(encoded.lists).length !== encoded.listCount || 351+ Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number])) 353+ throw Error("invalid stored atom list references"); 355+ if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1) 356+ throw Error("invalid stored insertion format"); 358+ encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1 362+ encoded.textFormat === 1 363+ ? (start: number, length: number): readonly string[] => { 364+ const result: string[] = []; 366+ for (const run of atom.inserts) 367+ for (const raw of run.lines) { 368+ if (index >= start && index < start + length) { 369+ const reference = raw as unknown as TextReference; 370+ if (typeof raw === "string") result.push(raw); 371+ else if (reference && typeof reference.text === "string") 372+ result.push(atomText.read(reference.text)); 373+ else throw Error("invalid stored atom text reference"); 375+ if (++index >= start + length) return result; 377+ throw Error("stored atom text range missing"); 380+ const frozen = freezeAtom( 386+ if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen; 387+ const result = { ...frozen }; 388+ if (encoded.insertionFormat === 1) { 389+ const collection = `atom-inserts:${atom.seq}`; 390+ if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference"); 391+ const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => { 392+ const run = raw as { file: string; parent: InsertRun["parent"]; lines: string }; 393+ const lines = `${collection}:lines:${index}`; 394+ if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string") 395+ throw Error("invalid stored insertion run"); 396+ return Object.freeze({ 399+ lines: readonlyStoredArray<string>(storage, lines, (rawLine) => { 400+ if (typeof rawLine === "string") return rawLine; 401+ const ref = rawLine as TextReference; 402+ if (!ref || typeof ref.text !== "string") throw Error("invalid stored insertion text"); 403+ return atomText.read(ref.text); 407+ Object.defineProperty(result, "inserts", { value: inserts, enumerable: true }); 409+ for (const field of listFields) { 410+ const collection = encoded.lists?.[field]; 411+ if (collection === undefined) continue; 412+ if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`) 413+ throw Error("invalid stored atom list reference"); 414+ Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true }); 416+ return Object.freeze(result); 419+ const atom = { ...input }; 420+ const lists: Partial<Record<(typeof listFields)[number], string>> = {}; 421+ for (const field of listFields) { 422+ const values = input[field]; 423+ if (!values || values.length <= 256) continue; 424+ const collection = `atom-list:${input.seq}:${field}`; 425+ const saved = storedArray<unknown>(storage, collection); 426+ for (const value of values) saved.push(value); 427+ lists[field] = collection; 428+ Object.defineProperty(atom, field, { value: [], enumerable: true }); 430+ const listCount = Object.keys(lists).length; 431+ const hasLists = listCount > 0; 432+ if (atom.inserts.length > 256 || atom.inserts.some((run) => run.lines.length > 256)) { 433+ const collection = `atom-inserts:${input.seq}`; 434+ const runs = storedArray<unknown>(storage, collection); 437+ for (const run of atom.inserts) { 438+ const lineCollection = `${collection}:lines:${runIndex++}`; 439+ const lines = storedArray<unknown>(storage, lineCollection); 440+ for (const line of run.lines) { 441+ const text = JSON.stringify([key, lineIndex++]); 442+ if (line.length > StoredText.chunkCharacters) { 443+ atomText.write(text, line); 444+ lines.push({ text }); 445+ } else lines.push(line); 447+ runs.push({ file: run.file, parent: run.parent, lines: lineCollection }); 451+ insertionRuns: collection, 452+ ...(hasLists ? { listFormat: 1, listCount, lists } : {}), 453+ atom: { ...atom, inserts: [] }, 456+ if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters))) 457+ return hasLists ? { listFormat: 1, listCount, lists, atom } : atom; 459+ const inserts = atom.inserts.map((run) => ({ 461+ lines: run.lines.map((line) => { 462+ const text = JSON.stringify([key, index++]); 463+ if (line.length <= StoredText.chunkCharacters) return line; 464+ atomText.write(text, line); 470+ ...(hasLists ? { listFormat: 1, listCount, lists } : {}), 471+ atom: { ...atom, inserts }, 316475 this.#lamport = storedArray(storage, "lamport"); 317476 this.#lineBase = storedArray(storage, "line-base"); Lines 483–508 at 162 (were 324–330 at 161)
324483 this.#lineParent = numbers("line-parent"); 325484 this.#deleter = numbers("deleter"); 326485 this.#replacing = numbers("replacing"); 327− this.#lineText = storedArray(storage, "line-text");
486+ const longText = atomText; 487+ this.#lineText = storedArray<string>( 491+ if (typeof value === "string") return value; 492+ const reference = value as unknown as { format: number; text: string }; 493+ if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference"); 494+ return longText.read(reference.text); 497+ if (value.length <= StoredText.chunkCharacters) return value; 498+ const number = Number(key); 499+ const seq = this.#lineAtom.at(number); 500+ const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]); 501+ const header = storage.read("atom-text:long", text) as { characters?: number } | undefined; 502+ if (header?.characters !== value.length) throw Error("long line atom text is missing"); 503+ return { format: 1, text }; 328506 this.#pathIndex = storedMap(storage, "path-index"); 329507 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) => 330508 JSON.stringify(["number", Number(key)]), Lines 743–757 at 162 (were 565–570 at 161)
566744 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */ 567745 deletedLines(id: AtomId): readonly LineId[] { 746+ const seq = this.#seq(id); 747+ const count = this.#storage?.read("atom-delete-counts", String(seq)); 748+ if (count !== undefined) { 749+ const out: LineId[] = []; 750+ for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq))) 751+ out.push(this.#lineName(n)); 752+ if (out.length !== count) throw Error("incomplete atom deletion index"); 568755 const ns = this.#atomDeletes[this.#seq(id)]; 569756 if (!ns) return EMPTY; 570757 const out: LineId[] = new Array(ns.length); Lines 761–773 at 162 (were 574–580 at 161)
575762 /** How many lines an atom deletes, without reading its lists. */ 576763 deleteCount(id: AtomId): number { 577− return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
764+ const seq = this.#seq(id); 765+ const count = this.#storage?.read("atom-delete-counts", String(seq)); 766+ if (count !== undefined) { 767+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count"); 768+ return count as number; 770+ return this.#atomDeletes[seq]?.length ?? 0; 580773 textOf(n: number): string { Lines 1150–1155 at 162 (were 957–966 at 161)
9571150 #reaches(from: Iterable<AtomId>, target: AtomId): boolean { 9581151 const floor = this.#lamport[this.#seq(target)]!; 9591152 if (this.#storage) { 960− // Roots belong to the current atom's dependency list, not its history.
961− const roots = [...from];
962− if (roots.includes(target)) return true;
963− if (roots.every((id) => this.#lamport[this.#seq(id)]! <= floor)) return false;
9641153 return this.withProjectionScratch((scratch) => { 9661155 const push = (id: AtomId): void => { Lines 1157–1166 at 162 (were 968–974 at 161)
9681157 scratch.write("seen", id, true); 9691158 scratch.write("stack", String(length++), id); 971− for (const id of roots) push(id);
1160+ for (const id of from) { 1161+ if (id === target) return true; 1162+ if (this.#lamport[this.#seq(id)]! > floor) push(id); 9721164 while (length > 0) { 9731165 const key = String(--length); 9741166 const current = scratch.read("stack", key) as AtomId; Lines 1203–1213 at 162 (were 1011–1022 at 161)
10111203 else this.#add(atom); 1014− #add(atom: Atom): void {
1015− if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1016− if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1017− this.#storage.write("ordered-children", "format", 2);
1018− }
1019−
1206+ #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void { 1207+ const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => { 1208+ if (!scratch) return new Set<T>(); 1209+ return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) }; 10201211 validateShape(atom); 10211212 const seq = this.#atoms.length; 10221213 const bad = (why: string): never => { Lines 1215–1246 at 162 (were 1024–1047 at 161)
10251216 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`); 1027− const deps = new Set<AtomId>();
1218+ const deps = membership<AtomId>("deps"); 10281219 for (const d of atom.deps) { 10291220 if (!this.has(d)) bad(`dependency ${d} is not in the graph`); 10301221 if (deps.has(d)) bad(`dependency ${d} listed twice`); 1033− for (const d of [...atom.needs, ...atom.resolves]) {
1034− if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1035− }
1224+ for (const list of [atom.needs, atom.resolves]) 1225+ for (const d of list) { 1226+ if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`); 10361228 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`); 10381230 // Everything it touches must come from its closure. Derived deps name the 10391231 // writers directly, so this is usually one lookup per writer. 1040− const below = new Map<AtomId, boolean>();
1232+ const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>(); 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); 10411240 const inClosure = (writer: AtomId): boolean => { 10421241 let hit = below.get(writer); 10431242 if (hit === undefined) { 1044− hit = deps.has(writer) || this.#reaches(deps, writer);
1243+ hit = deps.has(writer) || this.#reaches(atom.deps, writer); 10451244 below.set(writer, hit); Lines 1259–1323 at 162 (were 1060–1104 at 161)
10601259 checkLine(run.parent, "an insert"); 1063− const moved = new Set<LineId>();
1262+ const writes = membership<Key>("writes"); 1263+ for (const key of atom.writes) writes.add(key); 1264+ const moved = membership<LineId>("moved"); 10641265 for (const m of atom.moves ?? []) { 10651266 checkLine(m.line, "a move"); 10661267 if (!isStartNode(m.parent)) checkLine(m.parent, "a move"); 10671268 if (m.line === m.parent) bad(`moves ${m.line} after itself`); 10681269 if (moved.has(m.line)) bad(`moves ${m.line} twice`); 10691270 moved.add(m.line); 1070− if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
1271+ if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) { 10711272 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`); 1074− const deleted = new Set<LineId>();
1275+ const deleted = membership<LineId>("deleted"); 10751276 for (const line of atom.deletes) { 10761277 checkLine(line, "a delete"); 10771278 if (deleted.has(line)) bad(`deletes ${line} twice`); 10781279 deleted.add(line); 1080− const writes = new Set(atom.writes);
1081− for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1082− for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
1083− const parsed = parseKey(key);
1084− if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1085− else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1086− checkLine(parsed.node, `key ${key}`);
1281+ for (const line of atom.deletes) 1282+ if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`); 1283+ for (const list of [atom.writes, atom.reads, atom.holds]) 1284+ for (const key of list) { 1285+ const parsed = parseKey(key); 1286+ if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`); 1287+ else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)) 1288+ checkLine(parsed.node, `key ${key}`); 1292+ #add(atom: Atom): void { 1293+ if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) { 1294+ if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 1295+ this.#storage.write("ordered-children", "format", 2); 1298+ if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch)); 1299+ else this.#validateAcceptedAtom(atom); 1300+ const seq = this.#atoms.length; 1301+ const deps = atom.deps; 1302+ const deleted = this.#storage ? undefined : new Set(atom.deletes); 1303+ const writes = this.#storage ? atom.writes : new Set(atom.writes); 1090− const frozen = freezeAtom(
1091− atom,
1092− (id) => this.idOfSeq(seqOf(id)),
1093− (author) => {
1094− if (this.#storage) return author;
1095− let a = this.#authors.get(author);
1096− if (a === undefined) this.#authors.set(author, (a = author));
1097− return a;
1098− },
1099− this.#texts ? this.#reader(seq) : undefined,
1100− this.#lists ? this.#listReader(seq) : undefined,
1101− );
1306+ // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists. 1307+ const frozen = this.#storage 1311+ (id) => this.idOfSeq(seqOf(id)), 1313+ if (this.#storage) return author; 1314+ let a = this.#authors.get(author); 1315+ if (a === undefined) this.#authors.set(author, (a = author)); 1318+ this.#texts ? this.#reader(seq) : undefined, 1319+ this.#lists ? this.#listReader(seq) : undefined, 11021321 this.#atoms.push(this.#storage ? atom : frozen); 11041323 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1); Lines 1325–1352 at 162 (were 1106–1114 at 161)
11071326 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist. 11081327 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log. 1109− const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
1110− const deletedN = atom.deletes.map((line) => this.#lineN(line));
1111− this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
1328+ const deletes = (line: LineId | NodeId): boolean => { 1329+ if (isStartNode(line)) return false; 1330+ if (deleted) return deleted.has(line); 1331+ const n = this.#lineN(line); 1332+ return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq; 1334+ const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line)); 1335+ this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined); 1336+ if (this.#storage) { 1337+ const pages = storedLists<number>(this.#storage, "atom-deletes"); 1338+ for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line)); 1339+ this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length); 1341+ const deletedNumbers = function* (graph: Graph) { 1342+ if (deletedN) yield* deletedN; 1343+ else for (const line of atom.deletes) yield graph.#lineN(line); 1345+ for (const n of deletedNumbers(this)) { 1346+ if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq); 1347+ else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq); 1348+ else pushIndex(this.#moreDeleters, n, seq); 11121350 this.#lineBase.push(this.#lineTotal); 11131351 for (const run of atom.inserts) { 11141352 const file = this.#pathOf(run.file); Lines 1357–1363 at 162 (were 1119–1125 at 161)
11191357 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert( 11201358 orderedChildKey({ 1122− replaces: deletes?.has(run.parent) ? 1 : 0,
1360+ replaces: deletes(run.parent) ? 1 : 0, 11251363 k: first - this.#lineBase[seq]!, Lines 1375–1381 at 162 (were 1137–1143 at 161)
11371375 this.#lineParent.push(parent); 11381376 this.#lineText?.push(run.lines[i]!); 11391377 this.#deleter.push(-1); 1140− this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1378+ this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0); Lines 1390–1428 at 162 (were 1152–1188 at 161)
11521390 else pushIndex(this.#relocatedToCode, parentCode, info); 11541392 if (frozen.moves) this.#movers.push(frozen.id); 1155− for (const n of deletedN) {
1156− if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1157− else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1158− else pushIndex(this.#moreDeleters, n, seq);
1159− }
1160− for (const key of new Set(atom.writes)) {
1393+ for (const key of writes) { 11611394 const code = this.#code(key); 1162− if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1163− else pushOne(this.#writers, code, frozen.id);
1395+ if (this.#writersPages) { 1396+ const key = JSON.stringify([typeof code, code]); 1397+ if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id); 1398+ } else pushOne(this.#writers, code, frozen.id); 1165− for (const key of new Set(atom.reads)) {
1400+ for (const key of this.#storage ? atom.reads : new Set(atom.reads)) { 11661401 const code = this.#code(key); 1167− if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1168− else pushOne(this.#readers, code, frozen.id);
1402+ if (this.#readersPages) { 1403+ const key = JSON.stringify([typeof code, code]); 1404+ if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id); 1405+ } else pushOne(this.#readers, code, frozen.id); 1170− for (const key of new Set(atom.holds)) {
1407+ for (const key of this.#storage ? atom.holds : new Set(atom.holds)) { 11711408 const code = this.#code(key); 1172− if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1173− else pushOne(this.#holders, code, frozen.id);
1409+ if (this.#holdersPages) { 1410+ const key = JSON.stringify([typeof code, code]); 1411+ if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id); 1412+ } else pushOne(this.#holders, code, frozen.id); 11751414 for (const d of deps) { 11761415 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id); 11771416 else pushOne(this.#dependents, d, frozen.id); 1179− for (const r of new Set(frozen.resolves)) {
1180− if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1181− else pushOne(this.#resolvers, r, frozen.id);
1418+ for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) { 1419+ if (this.#resolversPages) { 1420+ if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id); 1421+ } else pushOne(this.#resolvers, r, frozen.id); 11831423 const files = new Set<string>(); 11841424 for (const run of atom.inserts) files.add(run.file); 1185− for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1425+ for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!); 11861426 for (const a of frozen.attrs ?? []) files.add(a.file); 11871427 for (const m of frozen.moves ?? []) { 11881428 files.add(this.lineFile(m.line)!);