8 files, 288 lines added, 26 removed.
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -913,8 +913,11 @@
913913 this.#lineParent.at(code + 1) === code 916− if (this.#runStartPages) yield* this.#runStartPages.values(String(code));
917− else yield* listOf(this.#runStarts.get(code));
916+ if (this.#runStartPages) { 917+ // The paged child counts say a line has no other children without a row read per line (abso Capacity). 918+ if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return; 919+ yield* this.#runStartPages.values(String(code)); 920+ } else yield* listOf(this.#runStarts.get(code)); 920923 get hasOrderedChildren(): boolean { --- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -127,6 +127,19 @@
131+ * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project 132+ * given one skips proving it again, which read every atom and every dependency in the history. 134+const closedSets = new WeakSet<object>(); 135+export function markClosed<S extends ReadonlySet<unknown>>(set: S): S { 136+ closedSets.add(set); 139+export function isClosedSet(set: unknown): boolean { 140+ return typeof set === "object" && set !== null && closedSets.has(set); 130143/** Immutable membership whose implementation does not retain its enumerated keys. */ 131144export abstract class StableSet<T> implements ReadonlySet<T> { 132145 abstract has(value: T): boolean; @@ -167,6 +180,12 @@
167180 get retainedBytes(): number { 168181 return 32 + this.#left.retainedBytes + this.#right.retainedBytes; 183+ get left(): StableSet<T> { 186+ get right(): StableSet<T> { 170189 has(value: T): boolean { 171190 return this.#left.has(value) || this.#right.has(value); --- a/src/engine/test/visible-neighbours.test.ts
+++ b/src/engine/test/visible-neighbours.test.ts
@@ -45,7 +45,8 @@
48− assert.equal(actual.weight(), weight, "neighbour lookup retains no file/history projection");
48+ // It may keep the moves it resolved, once per view and bounded (abso Capacity); never a file or its history. 49+ assert.ok(actual.weight() - weight <= 4096, "neighbour lookup retains no file/history projection"); 4950 assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, rows); --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -12,7 +12,7 @@
1212import type { Graph, RelocationInfo } from "./graph.ts"; 1313import { isStartNode } from "./keys.ts"; 1414import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts"; 15−import { StableSet } from "./state-source.ts";
15+import { isClosedSet, StableSet } from "./state-source.ts"; 1616import { joinLines } from "./text.ts"; 1717import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts"; @@ -91,6 +91,13 @@
9191const SET_ENTRY_BYTES = 32; 9292const REFERENCE_BYTES = 8; 9393const FILE_LOCATION_MEMO_ENTRIES = 256; 95+ * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on 96+ * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that. 98+export const MOVED_LINES_KEPT = 20_000; 99+class TooManyMoves extends Error {} 100+const NO_LINES: readonly number[] = Object.freeze([]); 96103 * The projection of a closed set. Construct once, then ask for files, lines @@ -118,6 +125,10 @@
118125 #relocs: Map<LineId, RelocationInfo> | undefined; 119126 /** The same, by n, with the new parent's code. */ 120127 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined; 128+ /** The moved lines under each node, by its code, made from the relocations on first use. */ 129+ #movedInto: Map<number, number[]> | undefined; 130+ /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */ 131+ #movesOnDisk: boolean | undefined; 121132 /** Bounded memo: ancestry can span the entire history even for one visible line. */ 122133 #fileOf = new Map<number, string>(); 123134 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */ @@ -131,7 +142,8 @@
131142 this.#stable = set; 133144 this.#in = new Uint8Array(0); 134− for (const id of set) {
145+ // A set kept closed when it was written needs no proof here (abso Capacity). 146+ for (const id of isClosedSet(set) ? [] : set) { 135147 const atom = graph.atom(id); 136148 for (const dependency of atom.deps) { 137149 graph.atom(dependency); @@ -220,6 +232,7 @@
220232 for (const id of this.#eachMover()) { 221233 for (const m of graph.atom(id).moves!) { 222234 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!); 235+ if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves(); 225238 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!; @@ -259,6 +272,21 @@
275+ /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */ 276+ #scratchMoves(): boolean { 277+ if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false; 278+ if (this.#movesOnDisk === undefined) { 280+ this.#relocations(); 281+ this.#movesOnDisk = false; 283+ if (!(error instanceof TooManyMoves)) throw error; 284+ this.#movesOnDisk = true; 287+ return this.#movesOnDisk; 262290 /** The relocations by n, with each new parent's code. */ 263291 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> { 264292 if (this.#relocsN) return this.#relocsN; @@ -272,7 +300,7 @@
272300 /** The node a line hangs off in this set: where it was written, or where a move put it. */ 273301 parentOf(line: LineId): NodeId { 274302 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`); 275− if (this.#hasMoves && this.graph.hasOrderedChildren)
303+ if (this.#scratchMoves()) 276304 return this.graph.withProjectionScratch((scratch) => 277305 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line), @@ -302,7 +330,7 @@
302330 #fileOfN(n: number): string { 303331 const graph = this.graph; 304332 if (!this.#hasMoves) return graph.writtenIn(n); 305− if (graph.hasOrderedChildren)
333+ if (this.#scratchMoves()) 306334 return graph.withProjectionScratch((scratch) => { 307335 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch); 308336 let current = graph.nodeOf(n); @@ -345,10 +373,18 @@
345373 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) }); 348− for (const r of graph.eachRelocatedToCode(code)) {
349− const n = graph.lineN(r.line);
350− const selected = relocs.get(n)?.r;
351− if (!selected || selected.atom !== r.atom || selected.k !== r.k) continue;
376+ // The lines this set's moves put under each node, from the moves it already resolved: no row read per node 378+ if (!this.#movedInto) { 379+ this.#movedInto = new Map(); 380+ for (const [n, { parent }] of relocs) { 381+ const into = this.#movedInto.get(parent); 382+ if (into) into.push(n); 383+ else this.#movedInto.set(parent, [n]); 386+ for (const n of this.#movedInto.get(code) ?? NO_LINES) { 387+ const r = relocs.get(n)!.r; 352388 const seq = graph.atom(r.atom).seq; 353389 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k }); @@ -415,7 +451,7 @@
415451 /** Lay out one file: its line tree from the set's atoms, linearized. */ 416452 #layout(path: string, complete: boolean): FileState { 417453 const graph = this.graph; 418− if (this.#hasMoves && graph.hasOrderedChildren)
454+ if (this.#scratchMoves()) 419455 return graph.withProjectionScratch((scratch) => 420456 this.#layoutResolved( @@ -635,7 +671,7 @@
636672 return found && previous !== undefined ? [previous] : []; 638− if (this.#hasMoves && graph.hasOrderedChildren)
674+ if (this.#scratchMoves()) 639675 return graph.withProjectionScratch((scratch) => 640676 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))), --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -17,6 +17,8 @@
1919 type GraphStateStorage, @@ -174,7 +176,7 @@
174176import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts"; 175177import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts"; 176178import { restore as hostedRestore, type RestoreHost } from "./restore.ts"; 177−import { last, Membership, SHARED, SharedAdditions, type Space, sharedBaseOf } from "./spaces.ts";
179+import { indexClosure, last, Membership, SHARED, SharedAdditions, type Space, sharedBaseOf } from "./spaces.ts"; 178180import { starting as hostedStarting, type StartingHost } from "./start.ts"; 179181import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts"; 180182import { sync as hostedSync, type SyncHost } from "./sync.ts"; @@ -1584,6 +1586,10 @@
15841586 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0; 15861588 this.#applyEntry(entry, at, keptTime); 1589+ // Shared's closure, kept per version on disk (abso Capacity): after the entry, since its atoms join the graph after 1591+ if (this.#writerStorage && (this.#spaces.get(SHARED)?.versions.length ?? 0) > versionsBefore) 1592+ indexClosure(this.#writerStorage, this.#spaces.get(SHARED)!, this.#graph); 15881594 // Positions by version: where each version of shared was made. 15891595 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0; @@ -2719,9 +2725,12 @@
27192725 * (abso issue 80). A closed set is unchanged. 27212727 #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> { 2728+ if (isClosedSet(set)) return set as ReadonlySet<AtomId>; 27222729 if (set instanceof StableSet) { 27232730 // Keep indexed membership external. Only dependencies absent from 2724− // that snapshot belong in the operation's closure overlay.
2731+ // that snapshot belong in the operation's closure overlay. Over a stored closed base (abso Capacity), 2732+ // only the overlay's atoms can reach outside it. 2733+ const walk = set instanceof StableUnionSet && isClosedSet(set.left) ? set.right : set; 27252734 const missing = new Set<AtomId>(); 27262735 const visit = (id: AtomId) => { 27272736 const stack = [id]; @@ -2734,8 +2743,8 @@
2737− for (const id of set) visit(id);
2738− return missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set;
2746+ for (const id of walk) visit(id); 2747+ return markClosed(missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set); 27402749 return this.#graph.closureOf(set); --- a/worker/project/spaces.ts
+++ b/worker/project/spaces.ts
@@ -6,6 +6,7 @@
66import type { AtomId } from "../../src/engine/index.ts"; 88 type GraphStateStorage, @@ -119,6 +120,111 @@
124+ * Shared's closure on disk (abso Capacity): the atoms a version's views hold beyond what it published, because 125+ * something in it depends on them (a discarded atom a later publish still needs, abso issue 80). Kept per version as 126+ * events like membership's, so "is a in shared's closure at v" is two lookups, and no read proves closure again. 127+ * Indexed from the first version only: a writer adopted before this has none and is proved as before. 129+const CLOSURE = 'closure:""'; 130+const OWN = `membership:${JSON.stringify(SHARED)}`; 132+function extraEvent(storage: GraphStateStorage, atom: AtomId, version: number): MembershipEvent | undefined { 133+ return membershipEvent(storage, CLOSURE, atom, version); 136+/** The newest shared version whose closure is indexed, or undefined when this writer has none. */ 137+export function closureIndexed(storage: GraphStateStorage): number | undefined { 138+ return storage.read(`${CLOSURE}:meta`, "indexed") as number | undefined; 141+export interface ClosureGraph { 142+ atom(id: AtomId): { readonly deps: readonly AtomId[]; readonly seq: number }; 143+ eachDependentOf(id: AtomId): Iterable<AtomId>; 146+/** Index shared's closure for every version applied since the last call. */ 147+export function indexClosure(storage: GraphStateStorage, shared: Space, graph: ClosureGraph): void { 148+ const indexed = closureIndexed(storage); 149+ const newest = last(shared); 150+ if (indexed === undefined && newest > 0) return; 151+ for (let v = (indexed ?? -1) + 1; v <= newest; v++) indexClosureVersion(storage, shared.versions[v]!, graph); 152+ if (newest >= 0) storage.write(`${CLOSURE}:meta`, "indexed", newest); 155+function indexClosureVersion(storage: GraphStateStorage, version: Published, graph: ClosureGraph): void { 156+ const v = version.version; 157+ const own = (atom: AtomId) => membershipEvent(storage, OWN, atom, v)?.present ?? false; 158+ const extra = (atom: AtomId) => extraEvent(storage, atom, v)?.present ?? false; 159+ const present = (atom: AtomId) => own(atom) || extra(atom); 160+ const order = storedArray<MembershipEvent>(storage, `${CLOSURE}:events`); 161+ const set = (atom: AtomId, on: boolean) => { 162+ if (extra(atom) === on) return; 163+ const event = { atom, version: v, present: on, slot: order.length }; 164+ storedArray<MembershipEvent>(storage, `${CLOSURE}:events:${atom}`).push(event); 167+ for (const added of version.atoms) { 168+ const stack = [added]; 169+ while (stack.length) 170+ for (const dep of graph.atom(stack.pop()!).deps) 171+ if (!present(dep)) { 176+ // A dropped atom stays while something in the set depends on it, and so on down its deps: newest first, so an atom 177+ // is decided after everything that could depend on it. 178+ const candidates = new Map<AtomId, number>(); 179+ for (const dropped of version.dropped ?? []) if (!own(dropped)) candidates.set(dropped, graph.atom(dropped).seq); 180+ while (candidates.size) { 181+ let atom: AtomId | undefined; 183+ for (const [a, s] of candidates) 188+ candidates.delete(atom!); 189+ if (own(atom!)) continue; 191+ for (const dependent of graph.eachDependentOf(atom!)) 192+ if (present(dependent)) { 198+ for (const dep of graph.atom(atom!).deps) 199+ if (!own(dep) && extra(dep) && !candidates.has(dep)) candidates.set(dep, graph.atom(dep).seq); 203+/** Shared at a version with its closure: what it published, and what that depends on. Marked closed. */ 204+class ClosedVersionSet extends StableSet<AtomId> { 205+ readonly retainedBytes = 96; 206+ readonly #storage: GraphStateStorage; 207+ readonly #version: number; 208+ readonly #own: StoredVersionSet; 209+ constructor(storage: GraphStateStorage, version: number) { 211+ this.#storage = storage; 212+ this.#version = version; 213+ this.#own = new StoredVersionSet(storage, OWN, version); 215+ has(atom: AtomId): boolean { 216+ return this.#own.has(atom) || (extraEvent(this.#storage, atom, this.#version)?.present ?? false); 218+ *values(): SetIterator<AtomId> { 220+ for (const event of storedArray<MembershipEvent>(this.#storage, `${CLOSURE}:events`)) { 221+ if (event.version > this.#version) break; 222+ if (!event.present || this.#own.has(event.atom)) continue; 223+ if (extraEvent(this.#storage, event.atom, this.#version)?.slot === event.slot) yield event.atom; 122228/** Immutable historical shared membership; iteration reads one event at a time. */ 123229class StoredVersionSet extends StableSet<AtomId> { 124230 readonly retainedBytes = 64; @@ -356,16 +462,15 @@
357463 at(space: Space, version: number): ReadonlySet<AtomId> { 358464 if (this.#storage) { 359− const own = new StoredVersionSet(this.#storage, `membership:${JSON.stringify(space.name)}`, version);
360− if (space.name === SHARED) return own;
465+ const storage = this.#storage; 466+ const closed = (v: number) => (closureIndexed(storage) ?? -1) >= v; 467+ const sharedAt = (v: number): StableSet<AtomId> => 468+ closed(v) ? markClosed(new ClosedVersionSet(storage, v)) : new StoredVersionSet(storage, OWN, v); 469+ if (space.name === SHARED) return sharedAt(version); 470+ const own = new StoredVersionSet(storage, `membership:${JSON.stringify(space.name)}`, version); 361471 // Named drafts add local atoms over an immutable shared base; drop 362472 // entries target shared, never a named draft's local membership. 363− const base = new StoredVersionSet(
364− this.#storage,
365− `membership:${JSON.stringify(SHARED)}`,
366− space.versions[version]!.sharedBase!,
367− );
368− return new StableUnionSet(base, own);
473+ return new StableUnionSet(sharedAt(space.versions[version]!.sharedBase!), own); 370475 if (space.name === SHARED && version === last(space)) return space.own; 371476 const key = `${spaceId(space)}:${version}`; --- /dev/null
+++ b/worker/project/test/stored-closure.test.ts
@@ -0,0 +1,88 @@
1+// Shared's closure kept on disk (abso Capacity, spaces.ts indexClosure): a writer-backed project answers every 2+// version as the in-memory one does, through drops that leave atoms a later version still needs. 4+import assert from "node:assert/strict"; 5+import { test } from "node:test"; 6+import { isClosedSet, storedArray } from "../../../src/engine/state-source.ts"; 7+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 8+import { MemoryStore, Project } from "../project.ts"; 9+import type { Entry, ProjectStore } from "../project-types.ts"; 10+import { addVersion, closureIndexed, indexClosure, Membership } from "../spaces.ts"; 13+ const storage = new SqlState(); 14+ const entries = storedArray<Entry>(storage, "canonical-log"); 15+ const store: ProjectStore = { 17+ for (const entry of batch) entries.push(entry); 20+ return { storage, project: new Project(store, { writerStorage: storage }) }; 23+/** The same history on both: edits on top of edits, then drops of the earlier ones, then more. */ 24+function history(project: Project) { 25+ project.init({ "a.txt": "one\ntwo\nthree\n", "b.txt": "b\n" }, 0); 26+ project.record("ann", { "a.txt": "ONE\ntwo\nthree\n" }, 1); 27+ assert.equal(project.publish("ann", "First", 2).ok, true); 28+ project.record("ann", { "a.txt": "ONE\nTWO\nthree\n", "b.txt": "b\nmore\n" }, 3); 29+ assert.equal(project.publish("ann", "Second", 4).ok, true); 30+ project.record("bob", { "a.txt": "ONE!\nTWO\nthree\n" }, 5); 31+ assert.equal(project.publish("bob", "Third, on the first", 6).ok, true); 32+ const answers: unknown[] = []; 33+ for (const versions of [[1], [2]]) 35+ answers.push(project.drop("ann", versions, `Drop ${versions}`, 7 + versions[0]!)); 37+ answers.push(String(error)); 39+ project.record("cy", { "c.txt": "new\n" }, 10); 40+ assert.equal(project.publish("cy", "Fourth", 11).ok, true); 44+test("every version reads the same from the stored closure as from memory", () => { 45+ const oracle = new Project(new MemoryStore()); 46+ const { storage, project } = writer(); 47+ assert.deepEqual(history(project), history(oracle)); 48+ assert.equal(closureIndexed(storage), oracle.version); 49+ for (let v = 0; v <= oracle.version; v++) { 50+ const want = oracle.viewAt(v); 51+ const got = project.viewAt(v); 52+ assert.ok(isClosedSet(got.set), `version ${v}'s set is known closed`); 53+ assert.deepEqual(got.files(), want.files(), `version ${v}`); 54+ assert.deepEqual([...got.set].sort(), [...want.set].sort(), `version ${v}'s atoms`); 56+ assert.deepEqual(project.files(), oracle.files()); 59+test("an atom only a published one needs is in the closure until nothing in shared needs it", () => { 60+ const storage = new SqlState(); 61+ const membership = new Membership(storage); 62+ const shared = membership.shared; 63+ // a1 was never published (a discarded draft atom); a2, published, builds on it. 64+ const deps: Record<string, string[]> = { a0: [], a1: ["a0"], a2: ["a1"], a3: ["a0"] }; 66+ atom: (id: string) => ({ deps: deps[id]!, seq: Number(id.slice(1)) }), 67+ *eachDependentOf(id: string) { 68+ for (const [atom, list] of Object.entries(deps)) if (list.includes(id)) yield atom; 71+ const version = (v: number, atoms: string[], dropped?: string[]) => { 72+ addVersion(shared, { version: v, agent: "w", message: `v${v}`, time: v, atoms, ...(dropped ? { dropped } : {}) }); 73+ indexClosure(storage, shared, graph); 75+ const at = (v: number) => [...membership.at(shared, v)].sort(); 79+ version(3, [], ["a2"]); 80+ assert.deepEqual(at(0), ["a0"]); 81+ assert.deepEqual(at(1), ["a0", "a1", "a2"], "a1 is in because a2 needs it"); 82+ assert.deepEqual(at(2), ["a0", "a1", "a2", "a3"]); 83+ assert.deepEqual(at(3), ["a0", "a3"], "dropping a2 takes a1 out too"); 84+ assert.equal(membership.at(shared, 1).has("a1"), true); 85+ assert.equal(membership.at(shared, 3).has("a1"), false); 86+ for (let v = 0; v <= 3; v++) assert.ok(isClosedSet(membership.at(shared, v))); --- a/worker/project/test/stored-membership.test.ts
+++ b/worker/project/test/stored-membership.test.ts
@@ -143,7 +143,8 @@
143143 const shared = reopened.shared; 144144 const reads = storage.reads; 145145 const old = reopened.at(shared, 20); 146− assert.equal(storage.reads - reads, 0, "opening a historical membership does not read historical state");
146+ // One read: whether shared's closure is kept on disk (abso Capacity). Nothing of the history. 147+ assert.equal(storage.reads - reads, 1, "opening a historical membership does not read historical state"); 147148 assert.equal(old.size, 41); 148149 assert.equal(old.has("a0"), true); 149150 assert.equal(old.has("a79"), false);