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 240 to 318

Compare

+233 −65 in 22 places
Lines 266–301 at 318 (were 266–271 at 240)
266266export type PackedAttr = [number, string, string | null];
267267/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
268268export 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+}
269299const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
270300/** At most this many path names kept in memory (Graph.#pathName). */
271301const PATH_NAMES = 4096;
Lines 470–480 at 318 (were 440–446 at 240)
440470 if (encoded.insertionFormat === 1) {
441471 const collection = `atom-inserts:${atom.seq}`;
442472 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
443− 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+ };
444478 const lines = `${collection}:lines:${index}`;
445479 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
446480 throw Error("invalid stored insertion run");
Lines 510–520 at 318 (were 476–482 at 240)
476510 const collection = `atom-inserts:${atom.seq}`;
477511 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
478512 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
479− 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+ };
480518 const lines = `${collection}:lines:${index}`;
481519 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
482520 throw Error("invalid stored insertion run");
Lines 531–540 at 318 (were 493–499 at 240)
493531 }),
494532 });
495533 });
496− Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
534+ Object.defineProperty(result, "inserts", {
535+ value: inserts,
536+ enumerable: true,
537+ });
497538 }
498539 for (const field of listFields) {
499540 const collection = encoded.lists?.[field];
Lines 545–554 at 318 (were 504–510 at 240)
504545 encoded.listFormat === 2
505546 ? readonlyPagedArray(storage, collection)
506547 : readonlyStoredArray(storage, collection);
507− Object.defineProperty(result, field, { value: list, enumerable: true });
548+ Object.defineProperty(result, field, {
549+ value: list,
550+ enumerable: true,
551+ });
508552 }
509553 return streamed(Object.freeze(result));
510554 },
Lines 586–596 at 318 (were 542–548 at 240)
542586 lines.push({ text });
543587 } else lines.push(line);
544588 }
545− 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+ });
546594 }
547595 return {
548596 insertionFormat: 1,
Lines 636–645 at 318 (were 588–594 at 240)
588636 "line-text",
589637 (value) => {
590638 if (typeof value === "string") return value;
591− const reference = value as unknown as { format: number; text: string };
639+ const reference = value as unknown as {
640+ format: number;
641+ text: string;
642+ };
592643 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
593644 return longText.read(reference.text);
594645 },
Lines 663–669 at 318 (were 612–617 at 240)
612663 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
613664 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
614665 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
666+ this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
615667 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
616668 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
617669 JSON.stringify(["number", Number(key)]),
Lines 742–754 at 318 (were 690–695 at 240)
690742 *packedTexts(file: number): IterableIterator<string | null> {
691743 yield* this.#fileTexts!.values(String(file));
692744 }
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+ }
693752 *packedDeletes(file: number): IterableIterator<PackedDelete> {
694753 yield* this.#fileDeletes!.values(String(file));
695754 }
Lines 759–811 at 318 (were 700–705 at 240)
700759 yield* this.#fileCrossings!.values(String(file));
701760 }
702761
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+ }
703809 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
704810 #lists: ((seq: number) => AtomLists) | undefined;
705811 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
Lines 909–924 at 318 (were 803–808 at 240)
803909 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
804910 #together: StateMap<AtomId, TogetherLink[]> = new Map();
805911 #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+ }
806922 #fileAtoms: StateMap<string, AtomId[]> = new Map();
807923 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
808924 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
Lines 1461–1476 at 318 (were 1345–1350 at 240)
13451461 else yield* listOf(this.#resolvers.get(id));
13461462 }
13471463
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+ }
13481474 /** `together` reasons touching this atom, in either direction. */
13491475 togetherLinks(id: AtomId): readonly TogetherLink[] {
13501476 return [...this.eachTogetherLink(id)];
Lines 1524–1562 at 318 (were 1398–1440 at 240)
13981524 * the search never descends below the target's lamport.
13991525 */
14001526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1401− const floor = this.#lamportAt(this.#seq(target));
1402− if (this.#storage) {
1403− return this.withProjectionScratch((scratch) => {
1404− let length = 0;
1405− const push = (id: AtomId): void => {
1406− if (scratch.read("seen", id)) return;
1407− scratch.write("seen", id, true);
1408− scratch.write("stack", String(length++), id);
1409− };
1410− for (const id of from) {
1411− if (id === target) return true;
1412− if (this.#lamportAt(this.#seq(id)) > floor) push(id);
1413− }
1414− while (length > 0) {
1415− const key = String(--length);
1416− const current = scratch.read("stack", key) as AtomId;
1417− scratch.remove("stack", key);
1418− if (this.#lamportAt(this.#seq(current)) <= floor) continue;
1419− for (const dependency of this.atom(current).deps) {
1420− if (dependency === target) return true;
1421− push(dependency);
1422− }
1423− }
1424− return false;
1425− });
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);
14261558 }
1427− const seen = new Set<AtomId>();
1428− const stack = [...from];
1429− while (stack.length > 0) {
1430− const cur = stack.pop()!;
1431− if (cur === target) return true;
1432− if (seen.has(cur)) continue;
1433− seen.add(cur);
1434− if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
1435− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1436− }
1437− return false;
1559+ return found;
14381560 }
14391561
14401562 /**
Lines 1565–1573 at 318 (were 1443–1448 at 240)
14431565 * The atom is frozen. Adding to the graph does not add it to any set.
14441566 */
14451567 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;
14461571 if (this.#storage)
14471572 this.#storage.transaction(() => {
14481573 this.#add(atom);
Lines 1581–1590 at 318 (were 1456–1462 at 240)
14561581 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
14571582 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
14581583 if (!scratch) return new Set<T>();
1459− 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+ };
14601588 };
14611589 validateShape(atom);
14621590 const seq = this.#atoms.length;
Lines 1606–1633 at 318 (were 1478–1500 at 240)
14781606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
14791607
14801608 // Everything it touches must come from its closure. Derived deps name the
1481− // writers directly, so this is usually one lookup per writer.
1482− const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1483− const below = {
1484− get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1485− set: (key: AtomId, value: boolean) => {
1486− if (scratch) scratch.write("below", key, value);
1487− else memoryBelow!.set(key, value);
1488− },
1489− };
1490− const inClosure = (writer: AtomId): boolean => {
1491− let hit = below.get(writer);
1492− if (hit === undefined) {
1493− hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1494− 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);
14951623 }
1496− return hit;
1497− };
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);
14981631 const checkLine = (line: LineId, what: string): void => {
14991632 const writer = this.lineAtom(line);
15001633 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
Lines 1679–1686 at 318 (were 1546–1551 at 240)
15461679 }
15471680 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
15481681 this.#storage.write("file-lines:meta", "format", 2);
1682+ this.#storage.write("reasons-in:meta", "kept", 1);
1683+ this.#reasonsInKnown = true;
15491684 this.#formatKnown = 2;
15501685 }
15511686
Lines 1803–1814 at 318 (were 1668–1674 at 240)
16681803 }
16691804 }
16701805 (frozen.moves ?? []).forEach((m, i) => {
1671− 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+ });
16721812 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
16731813 else pushIndex(this.#relocations, m.line, info);
16741814 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
Lines 1863–1877 at 318 (were 1723–1728 at 240)
17231863 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
17241864 else pushIndex(this.#fileAtoms, file, frozen.id);
17251865 }
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+ }
17261875 for (const r of frozen.reasons) {
17271876 if (r.kind !== "together" || r.to === frozen.id) continue;
17281877
Lines 1956–1967 at 318 (were 1807–1813 at 240)
18071956 // JSON -------------------------------------------------------------------
18081957
18091958 toJSON(): GraphJSON {
1810− 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+ };
18111965 }
18121966
18131967 /** Load a saved graph. Every atom is re-validated as it is added. */
Lines 2061–2072 at 318 (were 1907–1913 at 240)
19072061 // With text kept elsewhere (#46), a run's lines are read when asked for.
19082062 let k = 0;
19092063 const run = (r: InsertRun): InsertRun => {
1910− 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+ });
19112070 const start = k;
19122071 const length = r.lines.length;
19132072 k += length;
Lines 2081–2105 at 318 (were 1922–1937 at 240)
19222081 inserts: Object.freeze(atom.inserts.map(run)),
19232082 ...(lists
19242083 ? {}
1925− : { 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+ }),
19262090 needs: list(atom.needs, canon),
19272091 resolves: list(atom.resolves, canon),
19282092 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
19292093 deps: list(atom.deps, canon),
19302094 ...(atom.attrs && atom.attrs.length > 0
1931− ? { 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+ }
19322098 : {}),
19332099 ...(atom.moves
1934− ? { 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+ }
19352103 : {}),
19362104 } as Atom;
19372105 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
MCP
compare on this site's /mcp
CLI
abso diff 240 318 src/engine/graph.ts --json
JSON
/christopher/abso-core/compare/240..318?file=src%2Fengine%2Fgraph.ts&format=json