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 157 --json
JSON
/christopher/abso-core/versions/157?format=json

Share the SQLite writer and projection host with the open server

of shared·codex-capacity-chair··Not checked

Version 156 · Files at version 157

9 files, 1056 lines added, 9 removed.

--- a/scripts/check-changed.mjs
+++ b/scripts/check-changed.mjs
@@ -26,12 +26,18 @@
2626const TESTS = [
2727 {
2828 cwd: ".",
29− globs: ["src/**/*.test.ts", "worker/project/**/*.test.ts", "client/test/**/*.test.ts", "scripts/**/*.test.ts"],
29+ globs: [
30+ "src/**/*.test.ts",
31+ "worker/project/**/*.test.ts",
32+ "client/test/**/*.test.ts",
33+ "scripts/**/*.test.ts",
34+ "server/test/**/*.test.ts",
35+ ],
3036 args: ["--import", "./client/test/setup.ts"],
3137 },
3238];
3339/** Typechecks: a tsconfig, from the repo root. */
34−const TYPECHECKS = [{ tsconfig: "tsconfig.json" }];
40+const TYPECHECKS = [{ tsconfig: "tsconfig.json" }, { tsconfig: "server/tsconfig.json" }];
3541/** Files whose change can reach anything: the full check runs instead. */
3642const SETUP = [
3743 "**/package.json",
--- a/scripts/check-changed.test.ts
+++ b/scripts/check-changed.test.ts
@@ -14,7 +14,7 @@
1414 assert.ok(!files.includes("scripts/check-changed.test.ts"), "a test that doesn't reach the file stays out");
1515 assert.deepEqual(
1616 p.typechecks.map((c: { tsconfig: string }) => c.tsconfig),
17− ["tsconfig.json"],
17+ ["tsconfig.json", "server/tsconfig.json"],
1818 );
1919 assert.deepEqual(p.lint, ["src/engine/text.ts"]);
2020});
@@ -32,3 +32,9 @@
3232 assert.deepEqual(plan(["src/engine/text.ts", "package.json"]).full, ["package.json"]);
3333 assert.deepEqual(plan(["tsconfig.json"]).full, ["tsconfig.json"]);
3434});
36+test("server changes include their tests and worker types", () => {
37+ const p = plan(["server/src/engine-project.ts"]);
38+ assert.ok(p.tests.flatMap((t: { files: string[] }) => t.files).includes("server/test/engine-project.test.ts"));
39+ assert.ok(p.typechecks.some((c: { tsconfig: string }) => c.tsconfig === "server/tsconfig.json"));
40+});
--- a/server/src/engine-project.ts
+++ b/server/src/engine-project.ts
@@ -17,14 +17,14 @@
1717
1818// Characters per row. SQLite's 2 MB cap is in bytes, and a character is at
1919// most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it.
20−const PART = 600_000;
20+export const LOG_PART_CHARACTERS = 600_000;
2121
22−/** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */
22+/** An entry's JSON in rows of at most LOG_PART_CHARACTERS characters, never cutting an emoji's two halves apart. */
2323export function logParts(text: string): string[] {
2424 const parts: string[] = [];
2525 let at = 0;
2626 do {
27− let end = Math.min(at + PART, text.length);
27+ let end = Math.min(at + LOG_PART_CHARACTERS, text.length);
2828 const c = text.charCodeAt(end - 1);
2929 if (end < text.length && c >= 0xd800 && c <= 0xdbff) end--;
3030 parts.push(text.slice(at, end));
@@ -95,6 +95,41 @@
9595 return this.next;
9696 }
9797
98+ /** Reject an oversized canonical frame before loading its text into JavaScript. */
99+ boundedFrame(seq: number, maxBytes: number): string {
100+ if (
101+ !Number.isSafeInteger(seq) ||
102+ seq < 0 ||
103+ !Number.isSafeInteger(maxBytes) ||
104+ maxBytes < 1 ||
105+ maxBytes > 8_000_000
106+ )
107+ throw new Error("invalid canonical frame bound");
108+ const size = this.storage.sql
109+ .exec(
110+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?",
111+ seq,
112+ )
113+ .toArray()[0] as { parts: number; bytes: number };
114+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes > maxBytes)
115+ throw new Error("canonical frame exceeds adoption bound or is missing");
116+ const rows = this.storage.sql.exec("SELECT part, text FROM log WHERE seq = ? ORDER BY part", seq).toArray() as {
117+ part: number;
118+ text: string;
119+ }[];
120+ if (rows.length !== size.parts || rows.some((row, part) => row.part !== part))
121+ throw new Error("canonical frame parts are incomplete");
122+ return rows.map((row) => row.text).join("");
123+ }
125+ /** Refreshes the in-memory cursor after an enclosing transaction rolls back. */
126+ refreshSequence(): void {
127+ const rows = this.storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as {
128+ last: number;
129+ }[];
130+ this.next = (rows[0]?.last ?? -1) + 1;
131+ }
98133 /** Monotonic cache invalidation epoch for every canonical log mutation. */
99134 generation(): number {
100135 const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as {
--- /dev/null
+++ b/server/src/projection-store.ts
@@ -0,0 +1,410 @@
1+import { ProjectionAtomAdoption } from "../../src/engine/experimental/projection-atom-adoption.ts";
2+import { ProjectionAtomIndex } from "../../src/engine/experimental/projection-atom-index.ts";
3+import { ExperimentalMarkerProjection, type MarkerState } from "../../src/engine/experimental/projection-marker.ts";
4+import { ProjectionOverlayStorage } from "../../src/engine/experimental/projection-overlay-storage.ts";
5+import { ProjectionReadScope } from "../../src/engine/experimental/projection-read-scope.ts";
6+import {
7+ assertProjectionIdentity,
8+ type ProjectionHandle,
9+ type ProjectionIdentity,
10+} from "../../src/engine/experimental/projection-root.ts";
11+import { ProjectionSnapshots } from "../../src/engine/experimental/projection-snapshots.ts";
12+import { Graph } from "../../src/engine/graph.ts";
13+import { CachedStateStorage } from "../../src/engine/state-source.ts";
14+import { canonicalJson } from "../../worker/project/operation-protocol.ts";
15+import { projectedReader } from "../../worker/project/projection-provider.ts";
16+import { Membership, type Published } from "../../worker/project/spaces.ts";
17+import {
18+ advanceWriterRoot,
19+ type SqliteWriterState,
20+ type WriterProjectionHost,
21+ type WriterProjectionSession,
22+ type WriterRoot,
23+} from "./writer-host.ts";
25+type Context = Pick<ProjectionIdentity, "database" | "namespace" | "registry" | "defaultFile">;
26+interface Cursor {
27+ source: WriterRoot;
28+ version: number;
29+ offset: number;
30+ ordered: boolean;
31+ state: MarkerState;
32+ ready: boolean;
33+}
34+interface Head {
35+ version: number;
36+ handle: ProjectionHandle;
37+ source: WriterRoot;
38+}
39+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
40+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {
41+ const keys = fields.split(" ");
42+ if (
43+ !value ||
44+ typeof value !== "object" ||
45+ Array.isArray(value) ||
46+ Object.keys(value).length !== keys.length ||
47+ keys.some((key) => !Object.hasOwn(value, key))
48+ )
49+ throw Error("invalid projection host record");
50+}
51+function source(value: unknown): asserts value is WriterRoot {
52+ shape(value, "format generation logLength sharedVersion digest");
53+ if (
54+ value.format !== 1 ||
55+ !integer(value.generation) ||
56+ !integer(value.logLength) ||
57+ !integer(value.sharedVersion) ||
58+ typeof value.digest !== "string" ||
59+ !/^[a-f0-9]{64}$/.test(value.digest)
60+ )
61+ throw Error("invalid projection source root");
62+}
64+/** Private format experiment. Constructor injection only; production has no selection path. */
65+export class SqliteProjectionStore implements WriterProjectionHost {
66+ readonly #context: Context;
67+ readonly #generation: number;
68+ readonly #indexedAtoms: boolean;
69+ readonly #meta: string;
70+ #active = false;
71+ #nextOverlay = 0;
72+ constructor(context: Context, namespaceGeneration: number, options: { indexedAtoms?: boolean } = {}) {
73+ if (!Number.isSafeInteger(namespaceGeneration) || namespaceGeneration < 0)
74+ throw Error("invalid projection namespace generation");
75+ this.#context = Object.freeze({ ...context });
76+ this.#generation = namespaceGeneration;
77+ this.#indexedAtoms = options.indexedAtoms ?? false;
78+ this.#meta = `projection-host:${JSON.stringify(context.namespace)}`;
79+ }
80+ #bind(state: SqliteWriterState): void {
81+ const mode = state.read("host", "projection-atom-index-mode");
82+ if (this.#indexedAtoms ? mode !== 1 : mode === 1) throw Error("projection atom indexing mode mismatch");
83+ const expected = {
84+ ...this.#context,
85+ generation: this.#generation,
86+ ...(this.#indexedAtoms ? { atomIndexFormat: 1 } : {}),
87+ };
88+ const found = state.read(this.#meta, "binding");
89+ if (found !== undefined && canonicalJson(found) !== canonicalJson(expected))
90+ throw Error("projection namespace identity mismatch");
91+ if (found === undefined) state.write(this.#meta, "binding", expected);
92+ }
93+ #firstPending(state: SqliteWriterState, collection: string): readonly [string, unknown] | undefined {
94+ const iterator = state.entries(collection)[Symbol.iterator]();
95+ try {
96+ const next = iterator.next();
97+ return next.done ? undefined : next.value;
98+ } finally {
99+ iterator.return?.();
100+ }
101+ }
102+ #identity(source: WriterRoot, version: number): ProjectionIdentity {
103+ return {
104+ ...this.#context,
105+ sourceGeneration: this.#generation,
106+ sourceLength: source.logLength,
107+ sourceDigest: source.digest,
108+ membership: String(version),
109+ };
110+ }
111+ #cursor(value: unknown): Cursor | undefined {
112+ if (value === undefined) return undefined;
113+ shape(value, "source version offset ordered state ready");
114+ source(value.source);
115+ if (
116+ !integer(value.version) ||
117+ value.version > value.source.sharedVersion + 1 ||
118+ !integer(value.offset) ||
119+ typeof value.ordered !== "boolean" ||
120+ typeof value.ready !== "boolean" ||
121+ value.ready !== (value.version === value.source.sharedVersion + 1) ||
122+ (value.ready && (value.offset !== 0 || value.ordered))
123+ )
124+ throw Error("invalid projection adoption cursor");
125+ shape(value.state, "context sequence locator membership children attributeFiles");
126+ if (value.state.context !== JSON.stringify([this.#context.namespace, this.#context.defaultFile]))
127+ throw Error("projection adoption context mismatch");
128+ for (const key of ["locator", "membership", "children", "attributeFiles"])
129+ if (value.state[key] !== null && !integer(value.state[key])) throw Error("invalid adoption page reference");
130+ shape(value.state.sequence, "map root next");
131+ const seq = value.state.sequence;
132+ if (
133+ !integer(seq.next) ||
134+ seq.next > 2 ** 32 ||
135+ (seq.map !== null && !integer(seq.map)) ||
136+ (seq.root !== null && (!integer(seq.root) || seq.root >= seq.next)) ||
137+ (seq.root === null) !== (seq.next === 0) ||
138+ (seq.map === null) !== (seq.root === null)
139+ )
140+ throw Error("invalid adoption sequence state");
141+ return value as unknown as Cursor;
142+ }
143+ #head(value: unknown, expected: WriterRoot): Head | undefined {
144+ if (value === undefined) return undefined;
145+ shape(value, "version handle source");
146+ source(value.source);
147+ if (
148+ !integer(value.version) ||
149+ value.version !== expected.sharedVersion ||
150+ canonicalJson(value.source) !== canonicalJson(expected)
151+ )
152+ throw Error("projection head is stale");
153+ shape(value.handle, "format id identity");
154+ if (value.handle.format !== 1 || !integer(value.handle.id)) throw Error("invalid projection head handle");
155+ assertProjectionIdentity(value.handle.identity as ProjectionIdentity, this.#identity(expected, value.version));
156+ return value as unknown as Head;
157+ }
158+ #save(
159+ state: SqliteWriterState,
160+ snapshots: ProjectionSnapshots,
161+ value: MarkerState,
162+ source: WriterRoot,
163+ version: number,
164+ ): ProjectionHandle {
165+ const stored = state.read(this.#meta, "next-root");
166+ const next = stored === undefined ? 0 : stored;
167+ if (!integer(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid projection root allocation");
168+ const handle = snapshots.save(next, this.#identity(source, version), value);
169+ state.write(this.#meta, "next-root", next + 1);
170+ state.write(`${this.#meta}:versions`, String(version), handle);
171+ state.write(`${this.#meta}:prefixes`, String(source.logLength), source.digest);
172+ state.write(this.#meta, "head", { version, handle, source } satisfies Head);
173+ return handle;
174+ }
175+ #atoms(graph: Graph, delta: Published): { id: string; remove: boolean }[] {
176+ return [
177+ ...[...(delta.dropped ?? [])]
178+ .sort((a, b) => graph.atom(b).seq - graph.atom(a).seq)
179+ .map((id) => ({ id, remove: true })),
180+ ...[...delta.atoms].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq).map((id) => ({ id, remove: false })),
181+ ];
182+ }
183+ /** Each page is bounded in atoms and completed versions; the writer root is rechecked before commit. */
184+ adopt(input: {
185+ state: SqliteWriterState;
186+ expected: WriterRoot;
187+ currentRoot(): WriterRoot;
188+ maxAtoms: number;
189+ maxVersions: number;
190+ maxSteps?: number;
191+ }): { ready: boolean; version: number; applied: number; prepared: number; steps: number; atomicMoveWork: boolean } {
192+ if (this.#active) throw Error("projection writer is active");
193+ source(input.expected);
194+ const maxSteps = input.maxSteps ?? 64;
195+ if (![input.maxAtoms, input.maxVersions, maxSteps].every((n) => Number.isSafeInteger(n) && n > 0 && n <= 256))
196+ throw Error("invalid projection adoption bounds");
197+ return input.state.transaction(() => {
198+ const check = () => {
199+ if (canonicalJson(input.currentRoot()) !== canonicalJson(input.expected))
200+ throw Error("projection adoption source changed");
201+ };
202+ check();
203+ this.#bind(input.state);
204+ // One bounded cache per adoption page; no cache survives a return or rollback.
205+ const pageStorage = new CachedStateStorage(input.state, 262_144, 2048);
206+ const graph = new Graph({ storage: pageStorage });
207+ const atomIndex = this.#indexedAtoms ? new ProjectionAtomIndex(pageStorage) : undefined;
208+ const atomSeq = (id: string) => {
209+ if (!graph.has(id)) throw Error("missing projection atom");
210+ return Number(id.slice(1));
211+ };
212+ const adapter = new ExperimentalMarkerProjection(
213+ pageStorage,
214+ graph,
215+ this.#context.defaultFile,
216+ this.#context.namespace,
217+ );
218+ const snapshots = new ProjectionSnapshots(pageStorage, adapter, this.#context);
219+ const versions = new Membership(pageStorage).shared.versions;
220+ let cursor = this.#cursor(input.state.read(this.#meta, "adoption"));
221+ if (cursor && canonicalJson(cursor.source) !== canonicalJson(input.expected))
222+ throw Error("projection adoption cursor changed");
223+ cursor ??= {
224+ source: input.expected,
225+ version: 0,
226+ offset: 0,
227+ ordered: false,
228+ state: adapter.empty(),
229+ ready: false,
230+ };
231+ let applied = 0,
232+ prepared = 0,
233+ completed = 0,
234+ steps = 0,
235+ atomicMoveWork = false;
236+ const pending = `${this.#meta}:adoption-order`;
237+ while (
238+ !cursor.ready &&
239+ applied + prepared < input.maxAtoms &&
240+ completed < input.maxVersions &&
241+ steps < maxSteps
242+ ) {
243+ const delta = versions[cursor.version];
244+ if (!delta || delta.version !== cursor.version) throw Error("missing projection adoption version");
245+ const drops = delta.dropped ?? [];
246+ const count = drops.length + delta.atoms.length;
247+ if (cursor.offset > count || (cursor.ordered && cursor.offset !== count))
248+ throw Error("invalid projection adoption offset");
249+ while (!cursor.ordered && cursor.offset < count && applied + prepared < input.maxAtoms) {
250+ const remove = cursor.offset < drops.length;
251+ const id = remove ? drops[cursor.offset]! : delta.atoms[cursor.offset - drops.length]!;
252+ const seq = atomSeq(id);
253+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid adoption atom sequence");
254+ const rank = remove ? Number.MAX_SAFE_INTEGER - seq : seq;
255+ const key = `${remove ? "0" : "1"}:${rank.toString(16).padStart(14, "0")}`;
256+ input.state.write(pending, key, { id, remove, version: cursor.version, index: cursor.offset });
257+ cursor.offset++;
258+ prepared++;
259+ }
260+ if (cursor.offset === count) cursor.ordered = true;
261+ if (!cursor.ordered) break;
262+ while (applied + prepared < input.maxAtoms && steps < maxSteps) {
263+ const next = this.#firstPending(input.state, pending);
264+ if (!next) break;
265+ const [key, value] = next;
266+ shape(value, "id remove version index");
267+ if (
268+ typeof value.id !== "string" ||
269+ !value.id.length ||
270+ value.id.length > 4096 ||
271+ typeof value.remove !== "boolean" ||
272+ value.version !== cursor.version ||
273+ !integer(value.index) ||
274+ value.index >= count ||
275+ value.remove !== value.index < drops.length ||
276+ value.id !== (value.remove ? drops[value.index] : delta.atoms[value.index - drops.length])
277+ )
278+ throw Error("invalid projection pending atom");
279+ const item = value as { id: string; remove: boolean };
280+ const seq = atomSeq(item.id);
281+ const rank = item.remove ? Number.MAX_SAFE_INTEGER - seq : seq;
282+ if (key !== `${item.remove ? "0" : "1"}:${rank.toString(16).padStart(14, "0")}`)
283+ throw Error("projection pending order mismatch");
284+ const task = `${cursor.version}:${key}`;
285+ const page = new ProjectionAtomAdoption(adapter, task).page({
286+ previous: cursor.state,
287+ atom: atomIndex ? atomIndex.openAccepted(item.id) : graph.atom(item.id),
288+ remove: item.remove,
289+ source: input.expected.digest,
290+ maxSteps: maxSteps - steps,
291+ validateSource: check,
292+ });
293+ steps += page.steps;
294+ atomicMoveWork ||= page.atomicMoveWork;
295+ if (!page.done) break;
296+ cursor.state = page.state;
297+ adapter.storage.remove(`atom-adoption:${task}`, "cursor");
298+ input.state.remove(pending, key);
299+ applied++;
300+ }
301+ if (!this.#firstPending(input.state, pending)) {
302+ this.#save(input.state, snapshots, cursor.state, input.expected, cursor.version);
303+ cursor.version++;
304+ cursor.offset = 0;
305+ cursor.ordered = false;
306+ completed++;
307+ cursor.ready = cursor.version > input.expected.sharedVersion;
308+ }
309+ }
310+ check();
311+ input.state.write(this.#meta, "adoption", cursor);
312+ return { ready: cursor.ready, version: cursor.version - 1, applied, prepared, steps, atomicMoveWork };
313+ });
314+ }
315+ open({ state, log, root }: Parameters<WriterProjectionHost["open"]>[0]): WriterProjectionSession {
316+ if (this.#active) throw Error("nested projection writers are not supported");
317+ this.#bind(state);
318+ source(root);
319+ const adoption = this.#cursor(state.read(this.#meta, "adoption"));
320+ const head = this.#head(state.read(this.#meta, "head"), root);
321+ if (!adoption?.ready || !head || canonicalJson(head.source) !== canonicalJson(root))
322+ throw Error("projection head is missing, incomplete or stale");
323+ this.#active = true;
324+ let live = true,
325+ observed = root;
326+ const token = {};
327+ const overlays: ProjectionOverlayStorage[] = [];
328+ const scopes: ProjectionReadScope[] = [];
329+ const versions = new Membership(state).shared.versions;
330+ const current = (): WriterRoot => {
331+ if (!live) throw Error("closed projection writer");
332+ if (log.seq() === observed.logLength && log.generation() !== observed.generation)
333+ throw Error("projection source changed without an append");
334+ if (log.seq() !== observed.logLength)
335+ observed = advanceWriterRoot(log, observed, {
336+ generation: log.generation(),
337+ logLength: log.seq(),
338+ sharedVersion: versions.length - 1,
339+ });
340+ return observed;
341+ };
342+ return {
343+ readViewProvider: (graph) => {
344+ const scope = new ProjectionReadScope(graph, () => (live ? token : undefined));
345+ scopes.push(scope);
346+ return {
347+ keyed: (key) =>
348+ projectedReader(
349+ {
350+ graph,
351+ context: this.#context,
352+ sourceGeneration: this.#generation,
353+ sourceLength: () => current().logLength,
354+ prefixDigest: (length) =>
355+ length === current().logLength
356+ ? current().digest
357+ : (state.read(`${this.#meta}:prefixes`, String(length)) as string | undefined),
358+ version: () => versions.length - 1,
359+ committed: () => head,
360+ at: (version) => state.read(`${this.#meta}:versions`, String(version)) as ProjectionHandle | undefined,
361+ delta: (version) => versions[version],
362+ guard: () => scope.guard(graph),
363+ allocate: () => {
364+ const overlay = new ProjectionOverlayStorage(
365+ state,
366+ `${this.#context.namespace}:${this.#nextOverlay++}`,
367+ (collection) => state.clearProjectionOverlay(collection),
368+ );
369+ overlays.push(overlay);
370+ return new CachedStateStorage(overlay, overlays.length <= 32 ? 8192 : 0, 32);
371+ },
372+ },
373+ key,
374+ ),
375+ };
376+ },
377+ commit: (project, committed) => {
378+ if (canonicalJson(current()) !== canonicalJson(committed)) throw Error("projection commit source mismatch");
379+ const adapter = new ExperimentalMarkerProjection(
380+ state,
381+ project.graph,
382+ this.#context.defaultFile,
383+ this.#context.namespace,
384+ );
385+ const snapshots = new ProjectionSnapshots(state, adapter, this.#context);
386+ let value = snapshots.load(head.handle, this.#identity(head.source, head.version));
387+ let saved = false;
388+ for (let version = head.version + 1; version <= project.version; version++) {
389+ for (const item of this.#atoms(project.graph, versions[version]!))
390+ value = item.remove
391+ ? adapter.removeAtom(value, project.graph.atom(item.id))
392+ : adapter.apply(value, project.graph.atom(item.id));
393+ this.#save(state, snapshots, value, committed, version);
394+ saved = true;
395+ }
396+ if (!saved) this.#save(state, snapshots, value, committed, project.version);
397+ },
398+ close: () => {
399+ if (!live) return;
400+ live = false;
401+ try {
402+ for (const scope of scopes) scope.close();
403+ for (const overlay of overlays) overlay.close();
404+ } finally {
405+ this.#active = false;
406+ }
407+ },
408+ };
409+ }
410+}
--- /dev/null
+++ b/server/src/writer-host.ts
@@ -0,0 +1,429 @@
1+// Shared SQLite writer host.
2+// Callers provide current authority and own activation; this module adds no route.
3+import { createHash } from "node:crypto";
4+import { indexAcceptedProjectionAtom } from "../../src/engine/experimental/projection-atom-index.ts";
5+import type { GraphStateStorage } from "../../src/engine/state-source.ts";
6+import { Project, type WriterSource } from "../../worker/project/project.ts";
7+import type { ProjectOptions } from "../../worker/project/project-types.ts";
8+import {
9+ EngineProject,
10+ logParts,
11+ LOG_PART_CHARACTERS as PART,
12+ SqliteLog,
13+ type SqliteStorage,
14+} from "./engine-project.ts";
16+export class SqliteWriterState implements GraphStateStorage {
17+ readonly #storage: SqliteStorage;
18+ readonly #namespace: string;
19+ static readonly maxValueBytes = 8_000_000;
20+ constructor(storage: SqliteStorage, namespace: string) {
21+ if (!namespace || namespace.length > 128) throw new Error("invalid writer-state namespace");
22+ this.#storage = storage;
23+ this.#namespace = namespace;
24+ }
25+ /** Explicit schema setup, reserved for an authorized adoption host. */
26+ static initialize(storage: SqliteStorage): void {
27+ storage.sql.exec(
28+ "CREATE TABLE IF NOT EXISTS writer_state (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, part INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, collection, key, part))",
29+ );
30+ }
31+ read(collection: string, key: string): unknown {
32+ const header = this.#storage.sql
33+ .exec(
34+ "SELECT value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part = -1",
35+ this.#namespace,
36+ collection,
37+ key,
38+ )
39+ .toArray() as { value: string }[];
40+ if (!header.length) return undefined;
41+ const meta = JSON.parse(header[0]!.value) as { parts: number; characters: number; bytes: number };
42+ if (
43+ !Number.isSafeInteger(meta.parts) ||
44+ meta.parts < 1 ||
45+ meta.parts > Math.ceil(SqliteWriterState.maxValueBytes / (PART - 1)) ||
46+ !Number.isSafeInteger(meta.characters) ||
47+ meta.characters < 1 ||
48+ meta.characters > SqliteWriterState.maxValueBytes ||
49+ !Number.isSafeInteger(meta.bytes) ||
50+ meta.bytes < 1 ||
51+ meta.bytes > SqliteWriterState.maxValueBytes
52+ )
53+ throw new Error("invalid writer-state value header");
54+ const rows = this.#storage.sql
55+ .exec(
56+ "SELECT part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part >= 0 ORDER BY part LIMIT ?",
57+ this.#namespace,
58+ collection,
59+ key,
60+ meta.parts + 1,
61+ )
62+ .toArray() as { part: number; value: string }[];
63+ if (rows.length !== meta.parts || rows.some((row, index) => row.part !== index || row.value.length > PART))
64+ throw new Error("incomplete writer-state value");
65+ const json = rows.map((row) => row.value).join("");
66+ if (json.length !== meta.characters || new TextEncoder().encode(json).byteLength !== meta.bytes)
67+ throw new Error("writer-state value length mismatch");
68+ return (JSON.parse(json) as { value?: unknown }).value;
69+ }
70+ write(collection: string, key: string, value: unknown): void {
71+ const json = JSON.stringify({ value });
72+ if (json.length > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
73+ const bytes = new TextEncoder().encode(json).byteLength;
74+ if (bytes > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
75+ const parts = logParts(json);
76+ this.transaction(() => {
77+ this.remove(collection, key);
78+ this.#storage.sql.exec(
79+ "INSERT INTO writer_state VALUES (?, ?, ?, -1, ?)",
80+ this.#namespace,
81+ collection,
82+ key,
83+ JSON.stringify({ parts: parts.length, characters: json.length, bytes }),
84+ );
85+ for (const [part, text] of parts.entries())
86+ this.#storage.sql.exec(
87+ "INSERT INTO writer_state VALUES (?, ?, ?, ?, ?)",
88+ this.#namespace,
89+ collection,
90+ key,
91+ part,
92+ text,
93+ );
94+ });
95+ }
96+ remove(collection: string, key: string): void {
97+ this.#storage.sql.exec(
98+ "DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?",
99+ this.#namespace,
100+ collection,
101+ key,
102+ );
103+ }
104+ /** Delete one owned temporary projection collection without reading its values. */
105+ clearProjectionOverlay(collection: string): void {
106+ if (!collection.startsWith("projection:temporary:") || collection === "projection:temporary:")
107+ throw Error("invalid temporary projection collection");
108+ this.#storage.sql.exec(
109+ "DELETE FROM writer_state WHERE namespace = ? AND collection = ?",
110+ this.#namespace,
111+ collection,
112+ );
113+ }
114+ *entries(collection: string): Iterable<readonly [string, unknown]> {
115+ let after: string | undefined;
116+ for (;;) {
117+ const rows = (
118+ after === undefined
119+ ? this.#storage.sql.exec(
120+ "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 ORDER BY key LIMIT 1",
121+ this.#namespace,
122+ collection,
123+ )
124+ : this.#storage.sql.exec(
125+ "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 AND key > ? ORDER BY key LIMIT 1",
126+ this.#namespace,
127+ collection,
128+ after,
129+ )
130+ ).toArray() as { key: string }[];
131+ if (!rows.length) return;
132+ after = rows[0]!.key;
133+ yield [after, this.read(collection, after)];
134+ }
135+ }
136+ transaction<T>(body: () => T): T {
137+ return this.#storage.transactionSync(body);
138+ }
139+}
141+export interface WriterRoot extends WriterSource {
142+ readonly format: 1;
143+ readonly digest: string;
144+}
146+/** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */
147+export function writerFrameDigest(previous: string, seq: number, json: string): string {
148+ return createHash("sha256")
149+ .update("abso-writer-log-v1\n")
150+ .update(JSON.stringify([previous, seq]))
151+ .update("\n")
152+ .update(json, "utf8")
153+ .digest("hex");
154+}
156+export function advanceWriterRoot(log: SqliteLog, previous: WriterRoot, source: WriterSource): WriterRoot {
157+ let digest = previous.digest;
158+ if (source.logLength < previous.logLength) throw new Error("writer root cannot move backwards");
159+ for (let seq = previous.logLength; seq < source.logLength; seq++)
160+ digest = writerFrameDigest(digest, seq, log.boundedFrame(seq, 8_000_000));
161+ return { format: 1, ...source, digest };
162+}
164+/** Inactive host for explicit adoption and synchronous fenced writer operations. */
165+export interface WriterProjectionSession {
166+ readonly readViewProvider: NonNullable<ProjectOptions["readViewProvider"]>;
167+ commit(project: Project, root: WriterRoot): void;
168+ /** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */
169+ close(): void;
170+}
172+/** Private integration hook. No endpoint or persisted setting enables it. */
173+export interface WriterProjectionHost {
174+ open(input: { state: SqliteWriterState; log: SqliteLog; root: WriterRoot }): WriterProjectionSession;
175+}
177+export class SqliteWriterHost {
178+ readonly #storage: SqliteStorage;
179+ readonly #state: SqliteWriterState;
180+ readonly #log: SqliteLog;
181+ readonly #projection?: WriterProjectionHost;
182+ readonly #indexProjectionAtoms: boolean;
183+ constructor(
184+ storage: SqliteStorage,
185+ namespace: string,
186+ projection?: WriterProjectionHost,
187+ options: { indexProjectionAtoms?: boolean } = {},
188+ ) {
189+ this.#storage = storage;
190+ this.#state = new SqliteWriterState(storage, namespace);
191+ this.#log = new SqliteLog(storage);
192+ this.#projection = projection;
193+ this.#indexProjectionAtoms = options.indexProjectionAtoms ?? false;
194+ }
195+ #indexOptions(adopting = false) {
196+ const mode = this.#state.read("host", "projection-atom-index-mode");
197+ const expected = this.#indexProjectionAtoms ? 1 : 0;
198+ if (mode !== undefined && mode !== expected) throw Error("writer atom indexing mode mismatch");
199+ if (mode === undefined && this.#indexProjectionAtoms && (!adopting || this.#state.read("atoms:meta", "length")))
200+ throw Error("writer atom indexing requires fresh adoption");
201+ if (mode === undefined && adopting) this.#state.write("host", "projection-atom-index-mode", expected);
202+ return { indexAcceptedAtom: this.#indexProjectionAtoms ? indexAcceptedProjectionAtom : undefined };
203+ }
205+ source(): WriterSource {
206+ this.#log.refreshSequence();
207+ const shared = this.#storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
208+ value: number;
209+ }[];
210+ if (!Number.isSafeInteger(shared[0]?.value) || shared[0]!.value < 0)
211+ throw new Error("canonical shared head must be established before writer adoption");
212+ return { generation: this.#log.generation(), logLength: this.#log.seq(), sharedVersion: shared[0]!.value };
213+ }
214+ static #same(a: WriterSource | undefined, b: WriterSource): boolean {
215+ return a?.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
216+ }
217+ root(): WriterRoot {
218+ const root = this.#state.read("host", "canonical-root") as WriterRoot | undefined;
219+ if (root?.format !== 1 || !/^[a-f0-9]{64}$/.test(root.digest) || !SqliteWriterHost.#same(root, this.source()))
220+ throw new Error("writer canonical root is missing or stale");
221+ return root;
222+ }
223+ static #sync(value: unknown): void {
224+ if (value && (typeof value === "object" || typeof value === "function") && "then" in value)
225+ throw new Error("writer transaction callbacks must be synchronous");
226+ }
227+ /** Resume one bounded adoption page against an exact source and prior digest. */
228+ adoptVerifiedPage(
229+ input: {
230+ expected: WriterSource;
231+ from: number;
232+ digest: string;
233+ maxEntries: number;
234+ maxBytes: number;
235+ },
236+ validateAuthority: () => void,
237+ ) {
238+ return this.#storage.transactionSync(() => {
239+ SqliteWriterHost.#sync(validateAuthority());
240+ if (!SqliteWriterHost.#same(input.expected, this.source())) throw new Error("adoption source changed");
241+ if (
242+ !Number.isSafeInteger(input.from) ||
243+ input.from < 0 ||
244+ !Number.isSafeInteger(input.maxEntries) ||
245+ input.maxEntries < 1 ||
246+ input.maxEntries > 256 ||
247+ !Number.isSafeInteger(input.maxBytes) ||
248+ input.maxBytes < 1 ||
249+ input.maxBytes > 8_000_000 ||
250+ !(input.digest === "" || /^[a-f0-9]{64}$/.test(input.digest))
251+ )
252+ throw new Error("invalid bounded adoption request");
253+ const request = JSON.stringify([
254+ input.expected.generation,
255+ input.expected.logLength,
256+ input.expected.sharedVersion,
257+ input.from,
258+ input.digest,
259+ input.maxEntries,
260+ input.maxBytes,
261+ ]);
262+ const previous = this.#state.read("host", "adoption-page-receipt") as
263+ | { request: string; result: { next: number; ready: boolean; digest: string } }
264+ | undefined;
265+ if (previous?.request === request) return previous.result;
266+ const cursor = this.#state.read("host", "adoption-root") as { next: number; digest: string } | undefined;
267+ if ((cursor?.next ?? 0) !== input.from || (cursor?.digest ?? "") !== input.digest)
268+ throw new Error("adoption cursor or digest changed");
269+ const page = this.adoptPage(input.from, input, validateAuthority);
270+ const root = this.#state.read("host", "adoption-root") as { digest: string };
271+ const result = { next: page.next, ready: page.ready, digest: root.digest };
272+ this.#state.write("host", "adoption-page-receipt", { request, result });
273+ return result;
274+ });
275+ }
276+ adoptPage(from: number, limits: { maxEntries: number; maxBytes: number }, validateAuthority: () => void) {
277+ return this.#storage.transactionSync(() => {
278+ SqliteWriterHost.#sync(validateAuthority());
279+ const source = this.source();
280+ const indexOptions = this.#indexOptions(true);
281+ const log = this.#log;
282+ const previous = this.#state.read("host", "adoption-root") as
283+ | { source: WriterSource; next: number; digest: string }
284+ | undefined;
285+ if (
286+ (from === 0 && previous) ||
287+ (from > 0 && (!previous || previous.next !== from || !SqliteWriterHost.#same(previous.source, source)))
288+ )
289+ throw new Error("writer adoption root cursor is stale");
290+ let digest = previous?.digest ?? "";
291+ const frames = function* () {
292+ let bytes = 0;
293+ for (let seq = from; seq < source.logLength && seq < from + limits.maxEntries; seq++) {
294+ // Each frame is bounded before reading; the core also checks the
295+ // cumulative byte count before applying a frame.
296+ const json = log.boundedFrame(seq, limits.maxBytes);
297+ const next = new TextEncoder().encode(json).byteLength;
298+ if (bytes + next > limits.maxBytes && bytes > 0) return;
299+ bytes += next;
300+ digest = writerFrameDigest(digest, seq, json);
301+ yield { seq, json };
302+ }
303+ };
304+ const result = Project.adoptWriterPage(
305+ this.#state,
306+ {
307+ source,
308+ from,
309+ frames: frames(),
310+ ...limits,
311+ currentSource: () => this.source(),
312+ },
313+ indexOptions,
314+ );
315+ SqliteWriterHost.#sync(validateAuthority());
316+ this.#state.write("host", "adoption-root", { source, next: result.next, digest });
317+ if (result.ready) {
318+ this.#state.write("host", "canonical", source);
319+ this.#state.write("host", "canonical-root", { format: 1, ...source, digest } satisfies WriterRoot);
320+ }
321+ return result;
322+ });
323+ }
324+ /** Read through the existing call adapter with persistent mutations forbidden. */
325+ readCalls<T>(input: {
326+ expected: WriterSource;
327+ validateAuthority(): void;
328+ services?: Pick<ProjectOptions, "hasBlob" | "whole">;
329+ operation(calls: EngineProject): T;
330+ }): T {
331+ return this.#storage.transactionSync(() => {
332+ SqliteWriterHost.#sync(input.validateAuthority());
333+ const source = this.source();
334+ this.root();
335+ if (!SqliteWriterHost.#same(input.expected, source)) throw new Error("reader source is stale");
336+ const refuse = () => {
337+ throw new Error("indexed read attempted to mutate persistent state");
338+ };
339+ const readOnly: GraphStateStorage = {
340+ read: (collection, key) => this.#state.read(collection, key),
341+ entries: (collection) => this.#state.entries(collection),
342+ write: refuse,
343+ remove: refuse,
344+ transaction: (body) => this.#storage.transactionSync(body),
345+ };
346+ const projection = this.#projection?.open({ state: this.#state, log: this.#log, root: this.root() });
347+ try {
348+ const project = Project.openWriter({ append: refuse }, readOnly, source.logLength, {
349+ ...input.services,
350+ ...(input.services?.whole ? { whole: { read: input.services.whole.read, keep: refuse } } : {}),
351+ readViewProvider: projection?.readViewProvider,
352+ entryAt: (index) => this.#log.since(index, 1)[0]!,
353+ });
354+ const result = input.operation(new EngineProject(project));
355+ SqliteWriterHost.#sync(result);
356+ SqliteWriterHost.#sync(input.validateAuthority());
357+ if (!SqliteWriterHost.#same(source, this.source())) throw new Error("reader source changed");
358+ return result;
359+ } finally {
360+ SqliteWriterHost.#sync(projection?.close());
361+ }
362+ });
363+ }
365+ /** Reuse the existing call adapter within one fenced writer transaction. */
366+ runCalls<T>(input: {
367+ expected: WriterSource;
368+ validateAuthority(): void;
369+ checkerReady: boolean;
370+ services?: Pick<ProjectOptions, "hasBlob" | "whole">;
371+ operation(calls: EngineProject): T;
372+ commitReceipt(result: NoInfer<T>, source: WriterSource): void;
373+ }): T {
374+ return this.run({
375+ ...input,
376+ operation: (project) => {
377+ const calls = new EngineProject(project, (from, limit) => this.#log.since(from, limit), this.#log);
378+ calls.setCheckerReady(input.checkerReady);
379+ return input.operation(calls);
380+ },
381+ });
382+ }
383+ /** No asynchronous gap is permitted between authority validation and commit. */
384+ run<T>(input: {
385+ expected: WriterSource;
386+ validateAuthority(): void;
387+ operation(project: Project): T;
388+ services?: Pick<ProjectOptions, "hasBlob" | "whole">;
389+ commitReceipt(result: NoInfer<T>, source: WriterSource): void;
390+ }): T {
391+ try {
392+ return this.#storage.transactionSync(() => {
393+ SqliteWriterHost.#sync(input.validateAuthority());
394+ const source = this.source();
395+ const root = this.root();
396+ const bound = this.#state.read("host", "canonical") as WriterSource | undefined;
397+ if (!SqliteWriterHost.#same(input.expected, source) || !SqliteWriterHost.#same(bound, source))
398+ throw new Error("writer source or adopted generation is stale");
399+ const projection = this.#projection?.open({ state: this.#state, log: this.#log, root });
400+ try {
401+ const project = Project.openWriter(this.#log, this.#state, source.logLength, {
402+ ...input.services,
403+ ...this.#indexOptions(),
404+ readViewProvider: projection?.readViewProvider,
405+ shapes: this.#log.shapes(),
406+ now: () => Date.now(),
407+ });
408+ const result = input.operation(project);
409+ SqliteWriterHost.#sync(result);
410+ SqliteWriterHost.#sync(input.validateAuthority());
411+ const committed = this.source();
412+ this.#state.write("host", "canonical", committed);
413+ const committedRoot = advanceWriterRoot(this.#log, root, committed);
414+ this.#state.write("host", "canonical-root", committedRoot);
415+ SqliteWriterHost.#sync(projection?.commit(project, committedRoot));
416+ SqliteWriterHost.#sync(input.commitReceipt(result, committed));
417+ return result;
418+ } finally {
419+ SqliteWriterHost.#sync(projection?.close());
420+ }
421+ });
422+ } catch (error) {
423+ // The Project was scoped to the transaction and is discarded. Restore
424+ // SqliteLog's cached sequence after an enclosing rollback as well.
425+ this.#log.refreshSequence();
426+ throw error;
427+ }
428+ }
429+}
--- a/server/test/helpers.ts
+++ b/server/test/helpers.ts
@@ -5,8 +5,8 @@
55import { DatabaseSync } from "node:sqlite";
66import type { SqliteStorage } from "../src/engine-project.ts";
77
8−export function memoryStorage(): SqliteStorage & { db: DatabaseSync } {
9− const db = new DatabaseSync(":memory:");
8+export function memoryStorage(filename = ":memory:"): SqliteStorage & { db: DatabaseSync } {
9+ const db = new DatabaseSync(filename);
1010 let depth = 0;
1111 return {
1212 db,
--- /dev/null
+++ b/server/test/writer-host.test.ts
@@ -0,0 +1,136 @@
1+import assert from "node:assert/strict";
2+import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { test } from "node:test";
6+import { answer } from "../../worker/project/http.ts";
7+import { MemoryStore, Project } from "../../worker/project/project.ts";
8+import { SqliteLog } from "../src/engine-project.ts";
9+import { SqliteProjectionStore } from "../src/projection-store.ts";
10+import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts";
11+import { memoryStorage } from "./helpers.ts";
13+test("open server adopts and records through its call adapter without full-history loading", (t) => {
14+ const directory = mkdtempSync(join(tmpdir(), "abso-core-writer-"));
15+ const filename = join(directory, "state.sqlite");
16+ let storage = memoryStorage(filename);
17+ const reopen = () => {
18+ storage.db.close();
19+ storage = memoryStorage(filename);
20+ };
21+ t.after(() => {
22+ storage.db.close();
23+ unlinkSync(filename);
24+ rmdirSync(directory);
25+ });
26+ const memory = new MemoryStore();
27+ const oracle = new Project(memory);
28+ oracle.init({ "a.txt": "one\ntwo\n" }, 0);
29+ oracle.record("alice", { "a.txt": "ONE\ntwo\n" }, 1);
30+ oracle.publish("alice", "First", 2);
31+ oracle.move("alice", "a.txt", "b.txt", 3);
32+ oracle.publish("alice", "Move", 4);
33+ new SqliteLog(storage).append(memory.entries);
34+ SqliteWriterState.initialize(storage);
35+ const namespace = "open-server-capacity";
36+ const host = () => new SqliteWriterHost(storage, namespace, undefined, { indexProjectionAtoms: true });
37+ const expected = host().source();
38+ const canonicalBefore = storage.db.prepare("SELECT * FROM log ORDER BY seq, part").all();
39+ t.mock.method(Project, "load", () => {
40+ throw Error("full-history loading forbidden");
41+ });
42+ let from = 0,
43+ digest = "",
44+ ready = false;
45+ while (!ready) {
46+ const page = host().adoptVerifiedPage({ expected, from, digest, maxEntries: 2, maxBytes: 16384 }, () => {});
47+ assert.deepEqual(
48+ host().adoptVerifiedPage({ expected, from, digest, maxEntries: 2, maxBytes: 16384 }, () => {}),
49+ page,
50+ );
51+ from = page.next;
52+ digest = page.digest;
53+ ready = page.ready;
54+ reopen();
55+ }
56+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq, part").all(), canonicalBefore);
57+ let state = new SqliteWriterState(storage, namespace);
58+ const projection = new SqliteProjectionStore(
59+ { database: "project", namespace: "views", registry: "roots", defaultFile: "a.txt" },
60+ 1,
61+ { indexedAtoms: true },
62+ );
63+ let pages = 0;
64+ while (
65+ !projection.adopt({
66+ state,
67+ expected: host().root(),
68+ currentRoot: () => host().root(),
69+ maxAtoms: 1,
70+ maxVersions: 1,
71+ maxSteps: 2,
72+ }).ready
73+ )
74+ assert.ok(++pages < 1000);
75+ const writer = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true });
76+ const run = (operation: "record" | "publish", body: unknown, failReceipt = false) =>
77+ writer().runCalls({
78+ expected: writer().source(),
79+ validateAuthority: () => {},
80+ checkerReady: false,
81+ operation: (calls) => answer(calls, operation, "alice", body),
82+ commitReceipt: (result, source) => {
83+ state.write("receipts", operation, { result, source });
84+ if (failReceipt) throw Error("receipt failure");
85+ },
86+ });
87+ const rows = () => ({
88+ log: storage.db.prepare("SELECT * FROM log ORDER BY seq, part").all(),
89+ state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace, collection, key, part").all(),
90+ });
91+ const before = rows();
92+ assert.throws(() => run("record", { files: { "b.txt": "failed\n" } }, true), /receipt failure/);
93+ assert.deepEqual(rows(), before);
94+ assert.equal(run("record", { files: { "b.txt": "finished\n" } }).status, 200);
95+ const published = run("publish", { message: "Disk first" });
96+ assert.equal(published.status, 200);
97+ assert.equal((published.body as { ok: boolean }).ok, true);
98+ reopen();
99+ state = new SqliteWriterState(storage, namespace);
100+ const beforeRead = rows();
101+ assert.equal(
102+ writer().readCalls({
103+ expected: writer().source(),
104+ validateAuthority: () => {},
105+ operation: (calls) => calls.shared().files["b.txt"],
106+ }),
107+ "finished\n",
108+ );
109+ assert.deepEqual(rows(), beforeRead);
110+ assert.throws(
111+ () =>
112+ writer().runCalls({
113+ expected,
114+ validateAuthority: () => {},
115+ checkerReady: false,
116+ operation: () => undefined,
117+ commitReceipt: () => {},
118+ }),
119+ /stale/,
120+ );
121+ const committed = rows();
122+ assert.throws(
123+ () =>
124+ writer().runCalls({
125+ expected: writer().source(),
126+ validateAuthority: () => {
127+ throw Error("revoked authority");
128+ },
129+ checkerReady: false,
130+ operation: () => undefined,
131+ commitReceipt: () => {},
132+ }),
133+ /revoked authority/,
134+ );
135+ assert.deepEqual(rows(), committed);
136+});
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -1089,7 +1089,7 @@
10891089 // Accept.
10901090 const frozen = freezeAtom(
10911091 atom,
1092− (id) => this.#atoms[seqOf(id)]!.id,
1092+ (id) => this.idOfSeq(seqOf(id)),
10931093 (author) => {
10941094 if (this.#storage) return author;
10951095 let a = this.#authors.get(author);
--- a/src/engine/test/graph-metadata-indexed.test.ts
+++ b/src/engine/test/graph-metadata-indexed.test.ts
@@ -31,3 +31,28 @@
3131 db.db.close();
3232 }
3333});
35+test("accepting an edit does not decode historical atoms to canonicalize identities", () => {
36+ const db = new SqlState();
37+ try {
38+ const repo = Repo.init({ "a.txt": `first\n${"old\n".repeat(8191)}` });
39+ const graph = new Graph({ storage: db });
40+ graph.add(repo.graph.atom("a0"));
41+ const edit = repo.edit({ edits: [{ file: "a.txt", old: "first\n", new: "changed\n" }] });
42+ assert.ok(edit.deps.includes("a0"));
43+ const read = db.read.bind(db);
44+ db.read = (collection, key) => {
45+ if (collection === "atoms") throw Error("historical atom payload read forbidden");
46+ return read(collection, key);
47+ };
48+ graph.add(edit);
49+ assert.equal(graph.size, 2);
50+ assert.equal(graph.idOfSeq(1), edit.id);
51+ assert.equal(graph.lamport(edit.id), repo.graph.lamport(edit.id));
52+ assert.deepEqual(graph.filesOf(edit.id), repo.graph.filesOf(edit.id));
53+ db.read = read;
54+ assert.deepEqual(graph.atom(edit.id), repo.graph.atom(edit.id));
55+ } finally {
56+ db.db.close();
57+ }
58+});