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
MCP
show on this site's /mcp
CLI
abso show 132 --json
JSON
/christopher/abso-core/versions/132?format=json

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 @@
1616 startNode,
1717} from "./keys.ts";
1818import { OrderedIndex, orderedChildKey } from "./ordered-index.ts";
19+import { withProjectionScratch } from "./projection-scratch.ts";
1920import {
2021 type GraphStateStorage,
2122 type StateMap,
@@ -635,6 +636,19 @@
635636 get hasOrderedChildren(): boolean {
636637 return this.#storage !== undefined;
637638 }
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(
645+ this.#storage,
646+ () => {
647+ if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
648+ },
649+ operation,
650+ );
651+ }
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";
2+
3+let nextScope = 0;
4+
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,
12+): T {
13+ if (nextScope >= Number.MAX_SAFE_INTEGER) throw new Error("projection scope identity exhausted");
14+ const prefix = `projection-scratch:${++nextScope}:`;
15+ const finished = {};
16+ let active = true;
17+ let result: T;
18+ const collection = (name: string): string => {
19+ if (!active) throw new Error("projection scratch scope has ended");
20+ return prefix + name;
21+ };
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),
26+ *entries(name) {
27+ for (const entry of storage.entries(collection(name))) {
28+ collection(name);
29+ yield entry;
30+ }
31+ },
32+ transaction: (body) => {
33+ collection("");
34+ return storage.transaction(body);
35+ },
36+ };
37+ try {
38+ storage.transaction(() => {
39+ validateIdentity();
40+ const value = operation(scratch);
41+ if (
42+ value &&
43+ (typeof (value as { then?: unknown }).then === "function" ||
44+ typeof (value as { next?: unknown }).next === "function")
45+ )
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);
50+ validateIdentity();
51+ throw finished;
52+ });
53+ } catch (error) {
54+ if (error !== finished) throw error;
55+ return result!;
56+ } finally {
57+ active = false;
58+ }
59+ throw new Error("storage did not propagate projection rollback");
60+}
--- /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";
6+
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(
10+ graph: Graph,
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;
21+ }
22+ return best;
23+ };
24+ let work = 0;
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);
33+ }
34+ }
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}`);
38+ return node;
39+ };
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;
45+ for (;;) {
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;
50+ for (;;) {
51+ slow = step(slow);
52+ fast = step(step(fast));
53+ if (terminal(slow) || terminal(fast)) break;
54+ if (slow === fast) {
55+ meeting = slow;
56+ break;
57+ }
58+ }
59+ if (meeting === null) {
60+ let current: NodeId = line;
61+ while (!terminal(current)) {
62+ const next = parent(current);
63+ scratch.write("reached", current, true);
64+ current = next;
65+ }
66+ break;
67+ }
68+ let entry: NodeId | null = line;
69+ while (entry !== meeting) {
70+ entry = step(entry);
71+ meeting = step(meeting);
72+ }
73+ let current = entry!;
74+ let weakest: RelocationInfo | undefined;
75+ do {
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);
85+ }
86+ }
87+ return { selected, parent };
88+}
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(
93+ graph: Graph,
94+ has: (id: AtomId) => boolean,
95+ scratch: GraphStateStorage,
96+ start: NodeId,
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({
105+ n,
106+ replaces: move ? 0 : Number(graph.replacesN(n)),
107+ lamport: graph.lamportOfSeq(seq),
108+ seq,
109+ k: move ? move.k : graph.kOf(n),
110+ });
111+ const parent = moves.parent(line);
112+ scratch.write("layout-parent", line, { parent, key });
113+ new OrderedIndex(scratch, "layout-children", parent).insert(key, n);
114+ }
115+ const first = (parent: NodeId, after?: string): number | undefined => {
116+ for (const n of new OrderedIndex(scratch, "layout-children", parent).values(after)) return n;
117+ return undefined;
118+ };
119+ let n = first(start);
120+ while (n !== undefined) {
121+ yield n;
122+ const line = graph.nodeOf(n);
123+ const child = first(line);
124+ if (child !== undefined) {
125+ n = child;
126+ continue;
127+ }
128+ let previous = line;
129+ for (;;) {
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) {
134+ n = sibling;
135+ break;
136+ }
137+ if (row.parent === start) {
138+ n = undefined;
139+ break;
140+ }
141+ previous = row.parent;
142+ }
143+ }
144+}
--- /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";
6+
7+test("projection scratch is isolated, detached and rolled back inside canonical transactions", () => {
8+ const source = new SqlState();
9+ const storage = new CachedStateStorage(source);
10+ try {
11+ storage.transaction(() => {
12+ storage.write("canonical", "before", 1);
13+ let escaped: GraphStateStorage | undefined;
14+ const result = withProjectionScratch(
15+ storage,
16+ () => {},
17+ (scratch) => {
18+ escaped = scratch;
19+ scratch.write("canonical", "before", 99);
20+ const inner = withProjectionScratch(
21+ storage,
22+ () => {},
23+ (nested) => {
24+ assert.equal(nested.read("canonical", "before"), undefined);
25+ nested.write("canonical", "before", 101);
26+ return nested.read("canonical", "before");
27+ },
28+ );
29+ assert.equal(inner, 101);
30+ return { value: scratch.read("canonical", "before"), data: new Int32Array([1, 2]) };
31+ },
32+ );
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);
37+ });
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);
41+ } finally {
42+ source.db.close();
43+ }
44+});
46+test("projection errors, changed identities and escaping capabilities cannot commit scratch", () => {
47+ const source = new SqlState();
48+ try {
49+ let checks = 0;
50+ assert.throws(
51+ () =>
52+ withProjectionScratch(
53+ source,
54+ () => {
55+ if (++checks === 2) throw new Error("identity changed");
56+ },
57+ (scratch) => {
58+ scratch.write("x", "y", 1);
59+ return 2;
60+ },
61+ ),
62+ /identity changed/,
63+ );
64+ assert.throws(
65+ () =>
66+ withProjectionScratch(
67+ source,
68+ () => {},
69+ (scratch) => {
70+ scratch.write("x", "y", 1);
71+ throw new Error("failed computation");
72+ },
73+ ),
74+ /failed computation/,
75+ );
76+ assert.throws(
77+ () =>
78+ withProjectionScratch(
79+ source,
80+ () => {},
81+ (scratch) => scratch,
82+ ),
83+ /clone|cloned/i,
84+ );
85+ assert.throws(
86+ () =>
87+ withProjectionScratch(
88+ source,
89+ () => {},
90+ () => Promise.resolve(1),
91+ ),
92+ /synchronously/,
93+ );
94+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 0);
95+ } finally {
96+ source.db.close();
97+ }
98+});
--- /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);
15+ try {
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 };
25+ });
26+ const id = repo.graph.nextId();
27+ repo.graph.add({
28+ id,
29+ seq: repo.graph.size,
30+ author: "fixture",
31+ message: "move",
32+ time: j,
33+ inserts: [],
34+ deletes: [],
35+ writes: moves.flatMap((move) => [`P:${move.line}`, `G:${move.parent}`]),
36+ reads: [],
37+ holds: [],
38+ needs: [],
39+ resolves: [],
40+ reasons: [],
41+ deps: ["a0"],
42+ moves,
43+ });
44+ repo.shared.add(id);
45+ if (j < 16) earlier.add(id);
46+ }
47+ for (const membership of [repo.shared, earlier, repo.shared]) {
48+ const oracle = new View(repo.graph, membership);
49+ const parents = withProjectionScratch(
50+ storage,
51+ () => {},
52+ (scratch) => {
53+ const resolved = resolveScratchMoves(repo.graph, (id) => membership.has(id), scratch);
54+ return Array.from({ length: 24 }, (_, n) => resolved.parent(`a0.${n}`));
55+ },
56+ );
57+ assert.deepEqual(
58+ parents,
59+ Array.from({ length: 24 }, (_, n) => oracle.parentOf(`a0.${n}`)),
60+ );
61+ assert.equal(source.db.prepare("SELECT count(*) AS n FROM state").get()!.n, 0);
62+ assert.equal(storage.retainedEntries, 0);
63+ }
64+ if (trial < 4) {
65+ const persisted = new SqlState();
66+ try {
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));
78+ }
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}`));
82+ }
83+ assert.deepEqual(persisted.db.prepare("SELECT * FROM state ORDER BY collection, key").all(), before);
84+ }
85+ } finally {
86+ persisted.db.close();
87+ }
88+ }
89+ }
90+ } finally {
91+ source.db.close();
92+ }
93+});
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();
98+ try {
99+ repo.graph.add({
100+ id: "a1",
101+ seq: 1,
102+ author: "fixture",
103+ message: "move",
104+ time: 1,
105+ inserts: [],
106+ deletes: [],
107+ writes: ["P:a0.0", "G:a0.1"],
108+ reads: [],
109+ holds: [],
110+ needs: [],
111+ resolves: [],
112+ reasons: [],
113+ deps: ["a0"],
114+ moves: [{ line: "a0.0", parent: "a0.1" }],
115+ });
116+ repo.shared.add("a1");
117+ const before = { size: repo.graph.size, lines: repo.graph.lineCount };
118+ source.failWrite = 3;
119+ assert.throws(
120+ () =>
121+ withProjectionScratch(
122+ source,
123+ () => {},
124+ (scratch) => {
125+ resolveScratchMoves(repo.graph, (id) => repo.shared.has(id), scratch);
126+ },
127+ ),
128+ /injected storage failure/,
129+ );
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);
132+ } finally {
133+ source.db.close();
134+ }
135+});
--- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -11,6 +11,7 @@
1111
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 @@
264265
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),
272+ );
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);
305+ });
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(
415+ path,
416+ complete,
417+ scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
418+ ),
419+ );
420+ return this.#layoutResolved(path, complete);
421+ }
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 @@
413439
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)) {