Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 223 to 318

Compare

+322 −84 in 38 places
Lines 21–34 at 318 (were 21–32 at 223)
2121import { withProjectionScratch } from "./projection-scratch.ts";
2222import {
2323 type GraphStateStorage,
24+ readonlyPagedArray,
2425 readonlyStoredArray,
2526 type StateMap,
2627 storedArray,
2728 storedLists,
2829 storedMap,
2930 storedNumbers,
31+ writePagedArray,
3032} from "./state-source.ts";
3133import { StoredText } from "./stored-text.ts";
3234import {
Lines 266–304 at 318 (were 264–270 at 223)
264266export type PackedAttr = [number, string, string | null];
265267/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
266268export type PackedCrossing = [number, number];
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+ */
274+export 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+ */
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[] = [];
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+}
267299const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
300+/** At most this many path names kept in memory (Graph.#pathName). */
301+const PATH_NAMES = 4096;
268302/** Lines longer than this aren't packed with their file; their text is read on its own. */
269303const PACKED_TEXT = 4096;
270304
Lines 307–324 at 318 (were 273–278 at 223)
273307 readonly #childCounts?: ChildCounts;
274308 #atoms: Atom[] = [];
275309 #lamport: number[] = [];
310+ /**
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+ }
276322 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
277323 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
278324 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
Lines 387–393 at 318 (were 341–347 at 223)
341387 insertionFormat?: 1;
342388 insertionRuns?: string;
343389 textFormat?: 1;
344− listFormat?: 1;
390+ listFormat?: 1 | 2;
345391 listCount?: number;
346392 lists?: Partial<Record<(typeof listFields)[number], string>>;
347393 atom: Atom;
Lines 399–407 at 318 (were 353–361 at 223)
353399 const encoded = value as unknown as Partial<EncodedAtom>;
354400 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
355401 throw Error("invalid stored atom text format");
356− if (encoded.listFormat !== undefined && encoded.listFormat !== 1)
402+ if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)
357403 throw Error("invalid stored atom list format");
358− if (encoded.listFormat === 1) {
404+ if (encoded.listFormat === 1 || encoded.listFormat === 2) {
359405 if (
360406 !encoded.lists ||
361407 typeof encoded.lists !== "object" ||
Lines 416–425 at 318 (were 370–376 at 223)
370416 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
371417 throw Error("invalid stored insertion format");
372418 const atom =
373− 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
374423 ? encoded.atom!
375424 : value;
376425 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
Lines 470–480 at 318 (were 421–427 at 223)
421470 if (encoded.insertionFormat === 1) {
422471 const collection = `atom-inserts:${atom.seq}`;
423472 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
424− const run = raw as { file: string; parent: string; lines: string };
473+ const run = raw as {
474+ file: string;
475+ parent: string;
476+ lines: string;
477+ };
425478 const lines = `${collection}:lines:${index}`;
426479 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
427480 throw Error("invalid stored insertion run");
Lines 503–520 at 318 (were 450–462 at 223)
450503 (author) => author,
451504 text,
452505 );
453− if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);
506+ if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)
507+ return streamed(frozen);
454508 const result = { ...frozen };
455509 if (encoded.insertionFormat === 1) {
456510 const collection = `atom-inserts:${atom.seq}`;
457511 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
458512 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
459− const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
513+ const run = raw as {
514+ file: string;
515+ parent: InsertRun["parent"];
516+ lines: string;
517+ };
460518 const lines = `${collection}:lines:${index}`;
461519 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
462520 throw Error("invalid stored insertion run");
Lines 531–554 at 318 (were 473–486 at 223)
473531 }),
474532 });
475533 });
476− Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
534+ Object.defineProperty(result, "inserts", {
535+ value: inserts,
536+ enumerable: true,
537+ });
477538 }
478539 for (const field of listFields) {
479540 const collection = encoded.lists?.[field];
480541 if (collection === undefined) continue;
481542 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
482543 throw Error("invalid stored atom list reference");
483− Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
544+ const list =
545+ encoded.listFormat === 2
546+ ? readonlyPagedArray(storage, collection)
547+ : readonlyStoredArray(storage, collection);
548+ Object.defineProperty(result, field, {
549+ value: list,
550+ enumerable: true,
551+ });
484552 }
485553 return streamed(Object.freeze(result));
486554 },
Lines 558–566 at 318 (were 490–498 at 223)
490558 for (const field of listFields) {
491559 const values = input[field];
492560 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.
493562 const collection = `atom-list:${input.seq}:${field}`;
494− const saved = storedArray<unknown>(storage, collection);
495− for (const value of values) saved.push(value);
563+ writePagedArray(storage, collection, values);
496564 lists[field] = collection;
497565 Object.defineProperty(atom, field, { value: [], enumerable: true });
498566 }
Lines 586–606 at 318 (were 518–534 at 223)
518586 lines.push({ text });
519587 } else lines.push(line);
520588 }
521− runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
589+ runs.push({
590+ file: run.file,
591+ parent: run.parent,
592+ lines: lineCollection,
593+ });
522594 }
523595 return {
524596 insertionFormat: 1,
525597 insertionRuns: collection,
526− ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
598+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
527599 atom: { ...atom, inserts: [] },
528600 };
529601 }
530602 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
531− return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
603+ return hasLists ? { listFormat: 2, listCount, lists, atom } : atom;
532604 let index = 0;
533605 const inserts = atom.inserts.map((run) => ({
534606 ...run,
Lines 613–625 at 318 (were 541–552 at 223)
541613 }));
542614 return {
543615 textFormat: 1,
544− ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
616+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
545617 atom: { ...atom, inserts },
546618 };
547619 },
548620 );
549621 this.#lamport = storedArray(storage, "lamport");
622+ this.#lamportPaged = storedNumbers(storage, "lamport-pages");
550623 this.#lineBase = storedArray(storage, "line-base");
551624 this.#paths = storedArray(storage, "paths");
552625 this.#movers = storedArray(storage, "movers");
Lines 636–645 at 318 (were 563–569 at 223)
563636 "line-text",
564637 (value) => {
565638 if (typeof value === "string") return value;
566− const reference = value as unknown as { format: number; text: string };
639+ const reference = value as unknown as {
640+ format: number;
641+ text: string;
642+ };
567643 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
568644 return longText.read(reference.text);
569645 },
Lines 663–669 at 318 (were 587–592 at 223)
587663 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
588664 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
589665 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
666+ this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
590667 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
591668 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
592669 JSON.stringify(["number", Number(key)]),
Lines 742–754 at 318 (were 665–670 at 223)
665742 *packedTexts(file: number): IterableIterator<string | null> {
666743 yield* this.#fileTexts!.values(String(file));
667744 }
745+ /**
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+ }
668752 *packedDeletes(file: number): IterableIterator<PackedDelete> {
669753 yield* this.#fileDeletes!.values(String(file));
670754 }
Lines 759–811 at 318 (were 675–680 at 223)
675759 yield* this.#fileCrossings!.values(String(file));
676760 }
677761
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;
766+ /**
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+ }
678809 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
679810 #lists: ((seq: number) => AtomLists) | undefined;
680811 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
Lines 909–924 at 318 (were 778–783 at 223)
778909 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
779910 #together: StateMap<AtomId, TogetherLink[]> = new Map();
780911 #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;
921+ }
781922 #fileAtoms: StateMap<string, AtomId[]> = new Map();
782923 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
783924 /** 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 793–798 at 223)
793934 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
794935 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
795936 #movers: AtomId[] = [];
937+ /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
938+ #moverList: AtomId[] | undefined;
796939 #atomFiles: (readonly string[])[] = [];
797940 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
798941 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
Lines 948–963 at 318 (were 805–810 at 223)
805948 return this.#atoms.length;
806949 }
807950
951+ /**
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;
808961 /** The id the next accepted atom must have. */
809962 nextId(): AtomId {
810963 return atomId(this.#atoms.length);
Lines 983–989 at 318 (were 830–836 at 223)
830983 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
831984 lamport(id: AtomId): number {
832985 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
833− return this.#lamport[this.#seq(id)]!;
986+ return this.#lamportAt(this.#seq(id));
834987 }
835988
836989 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
Lines 999–1005 at 318 (were 846–852 at 223)
846999 id,
8471000 atom: this.idOfSeq(seq),
8481001 k: n - this.#lineBase[seq]!,
849− file: this.#paths[this.#lineFile.at(n)]!,
1002+ file: this.#pathName(this.#lineFile.at(n)),
8501003 parent: this.#nodeName(this.#lineParent.at(n)),
8511004 text: this.#text(n),
8521005 };
Lines 1020–1026 at 318 (were 867–873 at 223)
8671020 /** The file a line was written in, or undefined: line(id).file without making the record. */
8681021 lineFile(id: LineId): string | undefined {
8691022 const n = this.#lineN(id);
870− return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
1023+ return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));
8711024 }
8721025
8731026 /** The node a line was written after, or undefined: line(id).parent without making the record. */
Lines 1122–1138 at 318 (were 969–981 at 223)
9691122 return atomId(seq);
9701123 }
9711124
1125+ #lamportAt(seq: number): number {
1126+ return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
1127+ }
9721129 lamportOfSeq(seq: number): number {
973− return this.#lamport[seq]!;
1130+ return this.#lamportAt(seq);
9741131 }
9751132
9761133 /** The file line n was written in. */
9771134 writtenIn(n: number): string {
978− return this.#paths[this.#lineFile.at(n)]!;
1135+ return this.#pathName(this.#lineFile.at(n));
9791136 }
9801137
9811138 /** The code of the node line n was written after. */
Lines 1295–1324 at 318 (were 1138–1146 at 223)
11381295 }
11391296
11401297 #nodeName(code: number): NodeId {
1141− return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1298+ return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));
11421299 }
11431300
1301+ /**
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;
11441322 #pathOf(file: string): number {
11451323 let p = this.#pathIndex.get(file);
11461324 if (p === undefined) {
Lines 1434–1446 at 318 (were 1256–1262 at 223)
12561434
12571435 /** Atoms that move lines, in seq order. */
12581436 movers(): readonly AtomId[] {
1259− 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;
12601444 }
12611445
12621446 /** Atoms that list this one directly in their deps. */
Lines 1461–1476 at 318 (were 1277–1282 at 223)
12771461 else yield* listOf(this.#resolvers.get(id));
12781462 }
12791463
1464+ /**
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+ }
12801474 /** `together` reasons touching this atom, in either direction. */
12811475 togetherLinks(id: AtomId): readonly TogetherLink[] {
12821476 return [...this.eachTogetherLink(id)];
Lines 1524–1562 at 318 (were 1330–1372 at 223)
13301524 * the search never descends below the target's lamport.
13311525 */
13321526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1333− const floor = this.#lamport[this.#seq(target)]!;
1334− if (this.#storage) {
1335− return this.withProjectionScratch((scratch) => {
1336− let length = 0;
1337− const push = (id: AtomId): void => {
1338− if (scratch.read("seen", id)) return;
1339− scratch.write("seen", id, true);
1340− scratch.write("stack", String(length++), id);
1341− };
1342− for (const id of from) {
1343− if (id === target) return true;
1344− if (this.#lamport[this.#seq(id)]! > floor) push(id);
1345− }
1346− while (length > 0) {
1347− const key = String(--length);
1348− const current = scratch.read("stack", key) as AtomId;
1349− scratch.remove("stack", key);
1350− if (this.#lamport[this.#seq(current)]! <= floor) continue;
1351− for (const dependency of this.atom(current).deps) {
1352− if (dependency === target) return true;
1353− push(dependency);
1354− }
1355− }
1356− return false;
1357− });
1527+ 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);
13581558 }
1359− const seen = new Set<AtomId>();
1360− const stack = [...from];
1361− while (stack.length > 0) {
1362− const cur = stack.pop()!;
1363− if (cur === target) return true;
1364− if (seen.has(cur)) continue;
1365− seen.add(cur);
1366− if (this.#lamport[this.#seq(cur)]! <= floor) continue;
1367− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1368− }
1369− return false;
1559+ return found;
13701560 }
13711561
13721562 /**
Lines 1565–1573 at 318 (were 1375–1380 at 223)
13751565 * The atom is frozen. Adding to the graph does not add it to any set.
13761566 */
13771567 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;
13781571 if (this.#storage)
13791572 this.#storage.transaction(() => {
13801573 this.#add(atom);
Lines 1581–1590 at 318 (were 1388–1394 at 223)
13881581 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
13891582 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
13901583 if (!scratch) return new Set<T>();
1391− return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1584+ return {
1585+ has: (key) => scratch.read(name, key) === true,
1586+ add: (key) => scratch.write(name, key, true),
1587+ };
13921588 };
13931589 validateShape(atom);
13941590 const seq = this.#atoms.length;
Lines 1606–1633 at 318 (were 1410–1432 at 223)
14101606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
14111607
14121608 // Everything it touches must come from its closure. Derived deps name the
1413− // writers directly, so this is usually one lookup per writer.
1414− const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1415− const below = {
1416− get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1417− set: (key: AtomId, value: boolean) => {
1418− if (scratch) scratch.write("below", key, value);
1419− else memoryBelow!.set(key, value);
1420− },
1421− };
1422− const inClosure = (writer: AtomId): boolean => {
1423− let hit = below.get(writer);
1424− if (hit === undefined) {
1425− hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1426− 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);
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);
14271623 }
1428− return hit;
1429− };
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);
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);
14301631 const checkLine = (line: LineId, what: string): void => {
14311632 const writer = this.lineAtom(line);
14321633 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
Lines 1679–1686 at 318 (were 1478–1483 at 223)
14781679 }
14791680 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
14801681 this.#storage.write("file-lines:meta", "format", 2);
1682+ this.#storage.write("reasons-in:meta", "kept", 1);
1683+ this.#reasonsInKnown = true;
14811684 this.#formatKnown = 2;
14821685 }
14831686
Lines 1708–1718 at 318 (were 1505–1513 at 223)
15051708 this.#lists ? this.#listReader(seq) : undefined,
15061709 );
15071710 this.#atoms.push(this.#storage ? atom : frozen);
1711+ this.#accepted++;
15081712 let lam = 0;
15091713 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1510− this.#lamport.push(lam);
1714+ if (this.#lamportPages) this.#lamportPages.push(lam);
1715+ else this.#lamport.push(lam);
15111716
15121717 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
15131718 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
Lines 1803–1814 at 318 (were 1598–1604 at 223)
15981803 }
15991804 }
16001805 (frozen.moves ?? []).forEach((m, i) => {
1601− const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1806+ const info: RelocationInfo = Object.freeze({
1807+ atom: frozen.id,
1808+ line: m.line,
1809+ parent: m.parent,
1810+ k: i,
1811+ });
16021812 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
16031813 else pushIndex(this.#relocations, m.line, info);
16041814 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
Lines 1852–1858 at 318 (were 1642–1648 at 223)
16421852 }
16431853 const files = new Set<string>();
16441854 for (const run of atom.inserts) files.add(run.file);
1645− 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)));
16461856 for (const a of frozen.attrs ?? []) files.add(a.file);
16471857 for (const m of frozen.moves ?? []) {
16481858 files.add(this.lineFile(m.line)!);
Lines 1863–1877 at 318 (were 1653–1658 at 223)
16531863 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
16541864 else pushIndex(this.#fileAtoms, file, frozen.id);
16551865 }
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+ }
1874+ }
16561875 for (const r of frozen.reasons) {
16571876 if (r.kind !== "together" || r.to === frozen.id) continue;
16581877
Lines 1956–1967 at 318 (were 1737–1743 at 223)
17371956 // JSON -------------------------------------------------------------------
17381957
17391958 toJSON(): GraphJSON {
1740− return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1959+ return {
1960+ format: GRAPH_FORMAT,
1961+ version: 1,
1962+ atoms: this.#atoms,
1963+ labels: this.labels(),
1964+ };
17411965 }
17421966
17431967 /** Load a saved graph. Every atom is re-validated as it is added. */
Lines 2061–2072 at 318 (were 1837–1843 at 223)
18372061 // With text kept elsewhere (#46), a run's lines are read when asked for.
18382062 let k = 0;
18392063 const run = (r: InsertRun): InsertRun => {
1840− if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
2064+ if (!text)
2065+ return Object.freeze({
2066+ file: r.file,
2067+ parent: r.parent,
2068+ lines: Object.freeze([...r.lines]),
2069+ });
18412070 const start = k;
18422071 const length = r.lines.length;
18432072 k += length;
Lines 2081–2105 at 318 (were 1852–1867 at 223)
18522081 inserts: Object.freeze(atom.inserts.map(run)),
18532082 ...(lists
18542083 ? {}
1855− : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
2084+ : {
2085+ deletes: list(atom.deletes),
2086+ writes: list(atom.writes),
2087+ reads: list(atom.reads),
2088+ holds: list(atom.holds),
2089+ }),
18562090 needs: list(atom.needs, canon),
18572091 resolves: list(atom.resolves, canon),
18582092 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
18592093 deps: list(atom.deps, canon),
18602094 ...(atom.attrs && atom.attrs.length > 0
1861− ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
2095+ ? {
2096+ attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))),
2097+ }
18622098 : {}),
18632099 ...(atom.moves
1864− ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
2100+ ? {
2101+ moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))),
2102+ }
18652103 : {}),
18662104 } as Atom;
18672105 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
MCP
compare on this site's /mcp
CLI
abso diff 223 318 src/engine/graph.ts --json
JSON
/christopher/abso-core/compare/223..318?file=src%2Fengine%2Fgraph.ts&format=json