Bound persistent relocation projection memory with rollback-only scratch
of shared·codex-capacity-chair··Not checked
Version 131 · Files at version 132
6 files, 478 lines added, 1 removed.
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -16,6 +16,7 @@
1818import { OrderedIndex, orderedChildKey } from "./ordered-index.ts"; 19+import { withProjectionScratch } from "./projection-scratch.ts"; 2021 type GraphStateStorage, @@ -635,6 +636,19 @@
635636 get hasOrderedChildren(): boolean { 636637 return this.#storage !== undefined; 639+ /** Synchronous derived work against one graph identity. Scratch never commits. */ 640+ withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T { 641+ if (!this.#storage) throw new Error("projection scratch requires persistent graph storage"); 642+ const size = this.size; 643+ const lines = this.lineCount; 644+ return withProjectionScratch( 647+ if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed"); 638652 #childPriority(n: number): string { 639653 const seq = this.writerSeqOf(n); 640654 return orderedChildKey({ --- /dev/null
+++ b/src/engine/projection-scratch.ts
@@ -0,0 +1,60 @@
1+import type { GraphStateStorage } from "./state-source.ts"; 5+/** Synchronous derived-state work only. All scratch writes roll back, even on 6+ * success. The outer canonical transaction is left intact. Returned values 7+ * must be detached data, never iterators, promises or storage handles. */ 8+export function withProjectionScratch<T>( 9+ storage: GraphStateStorage, 10+ validateIdentity: () => void, 11+ operation: (scratch: GraphStateStorage) => T, 13+ if (nextScope >= Number.MAX_SAFE_INTEGER) throw new Error("projection scope identity exhausted"); 14+ const prefix = `projection-scratch:${++nextScope}:`; 18+ const collection = (name: string): string => { 19+ if (!active) throw new Error("projection scratch scope has ended"); 20+ return prefix + name; 22+ const scratch: GraphStateStorage = { 23+ read: (name, key) => storage.read(collection(name), key), 24+ write: (name, key, value) => storage.write(collection(name), key, value), 25+ remove: (name, key) => storage.remove(collection(name), key), 27+ for (const entry of storage.entries(collection(name))) { 32+ transaction: (body) => { 34+ return storage.transaction(body); 38+ storage.transaction(() => { 40+ const value = operation(scratch); 43+ (typeof (value as { then?: unknown }).then === "function" || 44+ typeof (value as { next?: unknown }).next === "function") 46+ throw new Error("projection must complete synchronously"); 47+ // Detach successful output before rollback; rejects embedded functions, 48+ // storage capabilities and generators instead of leaking their scope. 49+ result = structuredClone(value); 54+ if (error !== finished) throw error; 59+ throw new Error("storage did not propagate projection rollback"); --- /dev/null
+++ b/src/engine/relocation-scratch.ts
@@ -0,0 +1,144 @@
1+import type { Graph, RelocationInfo } from "./graph.ts"; 2+import { isStartNode } from "./keys.ts"; 3+import { OrderedIndex, orderedChildKey } from "./ordered-index.ts"; 4+import type { GraphStateStorage } from "./state-source.ts"; 5+import type { AtomId, LineId, NodeId } from "./types.ts"; 7+/** Scope-local relocation state. The caller must consume this handle inside 8+ * withProjectionScratch; selected moves and cycle bookkeeping live on disk. */ 9+export function resolveScratchMoves( 11+ has: (id: AtomId) => boolean, 12+ scratch: GraphStateStorage, 13+): { selected(line: LineId): RelocationInfo | undefined; parent(line: LineId): NodeId } { 14+ const selected = (line: LineId) => scratch.read("selected", line) as RelocationInfo | undefined; 15+ const identity = (move: RelocationInfo) => JSON.stringify([move.atom, move.k]); 16+ const stronger = (a: RelocationInfo, b: RelocationInfo) => graph.comparePriority(a.atom, b.atom) > 0; 17+ const pick = (line: LineId): RelocationInfo | undefined => { 18+ let best: RelocationInfo | undefined; 19+ for (const move of graph.eachRelocationOf(line)) { 20+ if (has(move.atom) && !scratch.read("ignored", identity(move)) && (!best || stronger(move, best))) best = move; 25+ for (const id of graph.movers()) { 26+ if (!has(id)) continue; 27+ for (const move of graph.atom(id).moves!) { 28+ if (scratch.read("seen", move.line)) continue; 29+ scratch.write("seen", move.line, true); 30+ scratch.write("work", String(work++), move.line); 31+ const best = pick(move.line); 32+ if (best) scratch.write("selected", move.line, best); 35+ const parent = (line: LineId): NodeId => { 36+ const node = selected(line)?.parent ?? graph.lineParent(line); 37+ if (node === undefined) throw new Error(`missing relocation ancestry for ${line}`); 40+ const terminal = (node: NodeId | null): boolean => 41+ node === null || isStartNode(node) || !!scratch.read("reached", node); 42+ const step = (node: NodeId | null): NodeId | null => (terminal(node) ? null : parent(node!)); 43+ for (let item = 0; item < work; item++) { 44+ const line = scratch.read("work", String(item)) as LineId; 46+ // Floyd's walk finds the exact cycle entry without a retained path. 47+ let slow: NodeId | null = line; 48+ let fast: NodeId | null = line; 49+ let meeting: NodeId | null = null; 52+ fast = step(step(fast)); 53+ if (terminal(slow) || terminal(fast)) break; 59+ if (meeting === null) { 60+ let current: NodeId = line; 61+ while (!terminal(current)) { 62+ const next = parent(current); 63+ scratch.write("reached", current, true); 68+ let entry: NodeId | null = line; 69+ while (entry !== meeting) { 71+ meeting = step(meeting); 73+ let current = entry!; 74+ let weakest: RelocationInfo | undefined; 76+ const move = selected(current); 77+ if (move && (!weakest || stronger(weakest, move))) weakest = move; 78+ current = parent(current); 79+ } while (current !== entry); 80+ if (!weakest) throw new Error("canonical ancestry unexpectedly cycles"); 81+ scratch.write("ignored", identity(weakest), true); 82+ const next = pick(weakest.line); 83+ if (next) scratch.write("selected", weakest.line, next); 84+ else scratch.remove("selected", weakest.line); 87+ return { selected, parent }; 90+/** Consume entirely within the projection scope. Traversal retains one line; 91+ * both priority ordering and parent links are held in rollback-only storage. */ 92+export function* scratchLayoutNodes( 94+ has: (id: AtomId) => boolean, 95+ scratch: GraphStateStorage, 97+): IterableIterator<number> { 98+ const moves = resolveScratchMoves(graph, has, scratch); 99+ for (let n = 0; n < graph.lineCount; n++) { 100+ if (!has(graph.idOfSeq(graph.writerSeqOf(n)))) continue; 101+ const line = graph.nodeOf(n); 102+ const move = moves.selected(line); 103+ const seq = move ? graph.atom(move.atom).seq : graph.writerSeqOf(n); 104+ const key = orderedChildKey({ 106+ replaces: move ? 0 : Number(graph.replacesN(n)), 107+ lamport: graph.lamportOfSeq(seq), 109+ k: move ? move.k : graph.kOf(n), 111+ const parent = moves.parent(line); 112+ scratch.write("layout-parent", line, { parent, key }); 113+ new OrderedIndex(scratch, "layout-children", parent).insert(key, n); 115+ const first = (parent: NodeId, after?: string): number | undefined => { 116+ for (const n of new OrderedIndex(scratch, "layout-children", parent).values(after)) return n; 119+ let n = first(start); 120+ while (n !== undefined) { 122+ const line = graph.nodeOf(n); 123+ const child = first(line); 124+ if (child !== undefined) { 128+ let previous = line; 130+ const row = scratch.read("layout-parent", previous) as { parent: NodeId; key: string } | undefined; 131+ if (!row) throw new Error("missing scratch layout ancestry"); 132+ const sibling = first(row.parent, row.key); 133+ if (sibling !== undefined) { 137+ if (row.parent === start) { 141+ previous = row.parent; --- /dev/null
+++ b/src/engine/test/projection-scratch.test.ts
@@ -0,0 +1,98 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { withProjectionScratch } from "../projection-scratch.ts"; 4+import { CachedStateStorage, type GraphStateStorage } from "../state-source.ts"; 5+import { SqlState } from "./storage-helper.ts"; 7+test("projection scratch is isolated, detached and rolled back inside canonical transactions", () => { 8+ const source = new SqlState(); 9+ const storage = new CachedStateStorage(source); 11+ storage.transaction(() => { 12+ storage.write("canonical", "before", 1); 13+ let escaped: GraphStateStorage | undefined; 14+ const result = withProjectionScratch( 19+ scratch.write("canonical", "before", 99); 20+ const inner = withProjectionScratch( 24+ assert.equal(nested.read("canonical", "before"), undefined); 25+ nested.write("canonical", "before", 101); 26+ return nested.read("canonical", "before"); 29+ assert.equal(inner, 101); 30+ return { value: scratch.read("canonical", "before"), data: new Int32Array([1, 2]) }; 33+ assert.deepEqual(result, { value: 99, data: new Int32Array([1, 2]) }); 34+ assert.throws(() => escaped!.write("x", "y", true), /ended/); 35+ assert.equal(storage.read("canonical", "before"), 1); 36+ storage.write("canonical", "after", 2); 38+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 2); 39+ assert.equal(storage.retainedEntries, 1); 40+ assert.equal(storage.read("canonical", "after"), 2); 46+test("projection errors, changed identities and escaping capabilities cannot commit scratch", () => { 47+ const source = new SqlState(); 52+ withProjectionScratch( 55+ if (++checks === 2) throw new Error("identity changed"); 58+ scratch.write("x", "y", 1); 66+ withProjectionScratch( 70+ scratch.write("x", "y", 1); 71+ throw new Error("failed computation"); 74+ /failed computation/, 78+ withProjectionScratch( 81+ (scratch) => scratch, 87+ withProjectionScratch( 90+ () => Promise.resolve(1), 94+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 0); --- /dev/null
+++ b/src/engine/test/relocation-scratch.test.ts
@@ -0,0 +1,135 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { Graph } from "../graph.ts"; 4+import { withProjectionScratch } from "../projection-scratch.ts"; 5+import { resolveScratchMoves } from "../relocation-scratch.ts"; 6+import { CachedStateStorage, StableOverlaySet } from "../state-source.ts"; 7+import { View } from "../view.ts"; 8+import { Repo, Rng } from "./helpers.ts"; 9+import { SqlState } from "./storage-helper.ts"; 11+test("scratch relocation cycle selection matches View across differing memberships and tied moves", () => { 12+ const rng = new Rng(45131); 13+ const source = new SqlState(); 14+ const storage = new CachedStateStorage(source, 4096, 16); 16+ for (let trial = 0; trial < 24; trial++) { 17+ const repo = Repo.init({ "f.txt": Array.from({ length: 24 }, (_, n) => `line ${n}\n`).join(""), "g.txt": "" }); 18+ const earlier = new Set(repo.shared); 19+ for (let j = 0; j < 32; j++) { 20+ const offset = rng.int(24); 21+ const moves = Array.from({ length: 3 }, (_, index) => { 22+ const line = `a0.${(offset + index) % 24}`; 23+ const candidate = `a0.${rng.int(24)}`; 24+ return { line, parent: candidate === line ? (j % 2 ? "^f.txt" : "^g.txt") : candidate }; 26+ const id = repo.graph.nextId(); 29+ seq: repo.graph.size, 35+ writes: moves.flatMap((move) => [`P:${move.line}`, `G:${move.parent}`]), 45+ if (j < 16) earlier.add(id); 47+ for (const membership of [repo.shared, earlier, repo.shared]) { 48+ const oracle = new View(repo.graph, membership); 49+ const parents = withProjectionScratch( 53+ const resolved = resolveScratchMoves(repo.graph, (id) => membership.has(id), scratch); 54+ return Array.from({ length: 24 }, (_, n) => resolved.parent(`a0.${n}`)); 59+ Array.from({ length: 24 }, (_, n) => oracle.parentOf(`a0.${n}`)), 61+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 0); 62+ assert.equal(storage.retainedEntries, 0); 65+ const persisted = new SqlState(); 67+ const indexed = new Graph({ storage: new CachedStateStorage(persisted, 8192, 32) }); 68+ for (const id of repo.shared) indexed.add(repo.graph.atom(id)); 69+ const before = persisted.db.prepare("SELECT * FROM state ORDER BY collection, key").all(); 70+ // Restart before projecting, then alternate membership on the same graph. 71+ const reopened = new Graph({ storage: new CachedStateStorage(persisted, 8192, 32) }); 72+ for (const membership of [repo.shared, earlier, repo.shared]) { 73+ const expected = new View(repo.graph, membership); 74+ const actual = new View(reopened, new StableOverlaySet(membership)); 75+ for (const path of ["f.txt", "g.txt"]) { 76+ assert.equal(actual.text(path), expected.text(path)); 77+ assert.deepEqual(actual.sequence(path), expected.sequence(path)); 79+ for (const n of [0, 11, 23]) { 80+ assert.equal(actual.parentOf(`a0.${n}`), expected.parentOf(`a0.${n}`)); 81+ assert.equal(actual.fileOf(`a0.${n}`), expected.fileOf(`a0.${n}`)); 83+ assert.deepEqual(persisted.db.prepare("SELECT * FROM state ORDER BY collection, key").all(), before); 86+ persisted.db.close(); 95+test("scratch relocation write failure rolls back without changing canonical graph state", () => { 96+ const repo = Repo.init({ f: "one\ntwo\n" }); 97+ const source = new SqlState(); 107+ writes: ["P:a0.0", "G:a0.1"], 114+ moves: [{ line: "a0.0", parent: "a0.1" }], 116+ repo.shared.add("a1"); 117+ const before = { size: repo.graph.size, lines: repo.graph.lineCount }; 118+ source.failWrite = 3; 121+ withProjectionScratch( 125+ resolveScratchMoves(repo.graph, (id) => repo.shared.has(id), scratch); 128+ /injected storage failure/, 130+ assert.deepEqual({ size: repo.graph.size, lines: repo.graph.lineCount }, before); 131+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 0); --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -11,6 +11,7 @@
1212import type { Graph, RelocationInfo } from "./graph.ts"; 1313import { isStartNode } from "./keys.ts"; 14+import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts"; 1415import { StableSet } from "./state-source.ts"; 1516import { joinLines } from "./text.ts"; 1617import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts"; @@ -264,6 +265,11 @@
265266 /** The node a line hangs off in this set: where it was written, or where a move put it. */ 266267 parentOf(line: LineId): NodeId { 268+ if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`); 269+ if (this.#hasMoves && this.graph.hasOrderedChildren) 270+ return this.graph.withProjectionScratch((scratch) => 271+ resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line), 267273 const r = this.#hasMoves ? this.#relocations().get(line) : undefined; 268274 if (r) return r.parent; 269275 const parent = this.graph.lineParent(line); @@ -290,6 +296,13 @@
290296 #fileOfN(n: number): string { 291297 const graph = this.graph; 292298 if (!this.#hasMoves) return graph.writtenIn(n); 299+ if (graph.hasOrderedChildren) 300+ return graph.withProjectionScratch((scratch) => { 301+ const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch); 302+ let current = graph.nodeOf(n); 303+ while (!isStartNode(current)) current = moves.parent(current); 304+ return current.slice(1); 293306 const relocs = this.#relocationsN(); 294307 // Keep only a fixed tail of the walk for path compression. The selected 295308 // relocation graph is acyclic, so traversal needs no history-sized stack. @@ -396,6 +409,19 @@
396409 /** Lay out one file: its line tree from the set's atoms, linearized. */ 397410 #layout(path: string, complete: boolean): FileState { 398411 const graph = this.graph; 412+ if (this.#hasMoves && graph.hasOrderedChildren) 413+ return graph.withProjectionScratch((scratch) => 414+ this.#layoutResolved( 417+ scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`), 420+ return this.#layoutResolved(path, complete); 423+ #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState { 424+ const graph = this.graph; 399425 // For each attribute, the highest-priority setter in the set wins. 400426 const setters = new Map<string, { id: AtomId; value: string | null }>(); 401427 for (const id of graph.eachAtomIn(path)) { @@ -413,7 +439,7 @@
414440 const start = graph.startCodeOf(path); 415441 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b; 416− for (const n of start === undefined ? [] : this.#layoutNodes(start)) {
442+ for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) { 417443 let deleted = false; 418444 const by: number[] = []; 419445 for (const deleter of graph.eachDeleterSeqOf(n)) {