75 files, 5552 lines added, 433 removed.
--- a/client/src/api.ts
+++ b/client/src/api.ts
@@ -2,6 +2,7 @@
22// except `run`, which sends a tar.gz and reads the answer as a stream of JSON 5+import { randomUUID } from "node:crypto"; 56import { setDefaultResultOrder } from "node:dns"; @@ -201,6 +202,7 @@
201202 if (this.config.visitor && method !== "GET") 202203 throw new ApiError(`${path}: a folder that reads signed out sends only reads`); 203204 const sent = body === undefined ? undefined : JSON.stringify(body); 205+ const requestId = method === "POST" ? randomUUID() : undefined; 204206 const timeoutMs = Math.max(atLeastMs, timeoutFor(this.timeoutMs, sent)); 205207 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6 206208 // address timed out, and the same command went through seconds later). Nothing went out, so @@ -209,7 +211,10 @@
210212 res = await this.send(this.url(path, server), { 212− headers: this.headers(sent === undefined ? undefined : "application/json"),
215+ ...this.headers(sent === undefined ? undefined : "application/json"), 216+ ...(requestId ? { "Idempotency-Key": requestId } : {}), 213218 ...(sent === undefined ? {} : { body: sent }), 214219 signal: AbortSignal.timeout(timeoutMs), --- /dev/null
+++ b/client/test/api-request-id.test.ts
@@ -0,0 +1,20 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { Api } from "../src/api.ts"; 5+test("a logical JSON write retains its UUID across connection retry and later writes get new IDs", async (t) => { 6+ const api = new Api({ server: "https://example.invalid", project: "test", agent: "alice" } as never); 7+ const ids: (string | null)[] = []; 8+ t.mock.method(api, "send", async (_url: string, init: RequestInit) => { 9+ ids.push(new Headers(init.headers).get("Idempotency-Key")); 10+ if (ids.length === 1) throw Object.assign(Error("not connected"), { cause: { code: "ECONNREFUSED" } }); 11+ return Response.json({ ok: true }); 13+ await api.json("POST", "/a/alice/record", { files: {} }); 14+ await api.json("POST", "/a/alice/record", { files: {} }); 15+ await api.json("GET", "/status"); 16+ assert.match(ids[0]!, /^[0-9a-f-]{36}$/); 17+ assert.equal(ids[1], ids[0]); 18+ assert.notEqual(ids[2], ids[0]); 19+ assert.equal(ids[3], null); --- a/server/README.md
+++ b/server/README.md
@@ -101,3 +101,16 @@
101101 oversized projects, and runs the alarm that pushes out to Artifacts and takes plain git pushes in. 102102- `src/issues/`: issues, asks and news. 103103- The engine itself is `src/engine/` at the repository's root, the same one the client uses. 105+### Experimental disk-first rollback floor 107+Disk-first runtime format 4 is required before compressed projection-priority pages, chunked retry receipts chunked atom-text references or indexed atom-list references are written. Preparation upgrades a format-1, format-2 or format-3 namespace atomically. Older runtimes refuse that namespace before reading or writing; rolling back the executable does not make its derived data readable. 109+To return to an older runtime, keep writes disabled and rebuild its derived writer, projection and historical namespaces from the canonical log using a compatible implementation. Do not lower the format marker in place. Preserve retry receipts or explicitly resolve outstanding retries before changing their storage format. This is an activation boundary, not authorization to delete project data. The canonical log is unchanged by the format upgrade. 112+Runtime format 3 also fences chunked atom-text references. Runtimes that only understand format 2 must refuse these derived namespaces. Do not lower the marker to roll back; rebuild compatible derived state while preserving canonical history and retry receipts. 114+Format 4 additionally fences atom-list references. A format-3 executable must refuse a format-4 namespace; it cannot safely interpret the placeholder arrays. 116+Format 5 additionally fences indexed insertion runs and lines. Preparation accepts recognized formats 1 through 4 and upgrades atomically. Older executables must refuse format 5. Never lower the marker to roll back. --- /dev/null
+++ b/server/src/decoded-frames.ts
@@ -0,0 +1,68 @@
1+import { CachedStateStorage } from "../../src/engine/state-source.ts"; 2+import type { WriterAdoptionFrame } from "../../worker/project/project.ts"; 3+import type { Entry } from "../../worker/project/project-types.ts"; 4+import type { SqliteLog, SqliteStorage } from "./engine-project.ts"; 5+import { StoredJson, storeJson } from "./stored-json.ts"; 6+import { storedJsonView } from "./stored-json-view.ts"; 7+import { SqliteWriterState, writerFrameChunksDigest } from "./writer-host.ts"; 9+/** Keep decoded views alive through the complete page checkpoint, then remove their rows. */ 10+export function withDecodedFrames<T>( 11+ storage: SqliteStorage, 14+ input: { from: number; to: number; maxEntries: number; maxBytes: number; digest: string }, 15+ consume: (frames: Iterable<WriterAdoptionFrame>) => T, 16+): { result: T; digest: string } { 18+ ![input.from, input.to, input.maxEntries, input.maxBytes].every(Number.isSafeInteger) || 20+ input.to < input.from || 21+ input.maxEntries < 1 || 22+ input.maxEntries > 256 || 25+ throw Error("invalid decoded frame page bounds"); 26+ return storage.transactionSync(() => { 27+ SqliteWriterState.initialize(storage); 28+ const state = new SqliteWriterState(storage, namespace); 29+ // Temporary nodes are immutable after parsing; cap retained reads for the whole page. 30+ const reads = new CachedStateStorage(state, 64 * 1024, 256); 32+ storage.sql.exec("SELECT 1 AS present FROM writer_state WHERE namespace = ? LIMIT 1", namespace).toArray().length 34+ throw Error("decoded frame namespace is occupied"); 35+ let digest = input.digest; 37+ const frames = function* (): IterableIterator<WriterAdoptionFrame> { 39+ for (let seq = input.from; seq < input.to && seq < input.from + input.maxEntries; seq++) { 40+ if (!active) throw Error("decoded frame page has ended"); 41+ const size = log.frameBytes(seq); 42+ if (size > input.maxBytes - bytes) { 44+ throw Error("decoded frame exceeds page byte bound"); 46+ digest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq)); 47+ storeJson(state, String(seq), log.frameChunks(seq)); 49+ yield { seq, bytes: size, entry: storedJsonView(new StoredJson(reads, String(seq))) as Entry }; 53+ const result = consume(frames()); 56+ typeof result === "object" && 57+ (typeof (result as { then?: unknown }).then === "function" || 58+ typeof (result as { next?: unknown }).next === "function") 60+ throw Error("decoded frame consumption must finish synchronously"); 61+ return { result: structuredClone(result), digest }; 65+ storage.sql.exec("DELETE FROM writer_state WHERE namespace = ?", namespace); --- a/server/src/disk-first-runtime.ts
+++ b/server/src/disk-first-runtime.ts
@@ -1,12 +1,14 @@
1+import { createHash } from "node:crypto"; 12import { canonicalJson } from "../../worker/project/operation-protocol.ts"; 23import { Project, type WriterSource } from "../../worker/project/project.ts"; 34import type { ProjectOptions } from "../../worker/project/project-types.ts"; 45import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts"; 6+import { SqliteHistoryHost } from "./history-host.ts"; 57import { SqliteProjectionStore } from "./projection-store.ts"; 68import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts"; 810type Services = Pick<ProjectOptions, "hasBlob" | "whole">; 9−type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "ready"; next: number };
11+type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "history" | "ready"; next: number }; 1113/** One synchronous page or call per invocation. No object retains a loaded Project. 1214 * The owner schedules subsequent pages and supplies fresh authorization for every call. */ @@ -15,10 +17,12 @@
1517 readonly #namespace: string; 1618 readonly #projection: SqliteProjectionStore; 1719 readonly #services: Services; 20+ readonly #history: SqliteHistoryHost; 1821 constructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) { 1922 this.#storage = storage; 2023 this.#namespace = namespace; 2124 this.#services = services; 25+ this.#history = new SqliteHistoryHost(storage, `${namespace}:history`); 2226 this.#projection = new SqliteProjectionStore( @@ -31,11 +35,57 @@
34− return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { indexProjectionAtoms: true });
38+ return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { 39+ indexProjectionAtoms: true, 40+ history: this.#history, 3744 return new SqliteWriterState(this.#storage, this.#namespace); 46+ #saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) { 47+ // Receipt payloads can exceed the graph-state value bound. Keep each stored 48+ // piece small without increasing that bound for engine state. 49+ const json = JSON.stringify({ result }); 50+ const characters = 64 * 1024; 51+ const parts = Math.ceil(json.length / characters); 52+ for (let part = 0; part < parts; part++) 53+ state.write(`runtime:receipt:${id}`, String(part), json.slice(part * characters, (part + 1) * characters)); 54+ state.write("runtime:receipts", id, { 58+ characters: json.length, 59+ digest: createHash("sha256").update(json).digest("hex"), 63+ state: SqliteWriterState, 65+ receipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string }, 67+ if (receipt.format === 2) return structuredClone(receipt.result) as T; 69+ receipt.format !== 3 || 70+ !Number.isSafeInteger(receipt.parts) || 71+ receipt.parts! < 1 || 72+ !Number.isSafeInteger(receipt.characters) || 73+ receipt.characters! < 1 || 74+ receipt.parts !== Math.ceil(receipt.characters! / (64 * 1024)) 76+ throw Error("invalid receipt header"); 78+ for (let part = 0; part < receipt.parts!; part++) { 79+ const chunk = state.read(`runtime:receipt:${id}`, String(part)); 80+ if (typeof chunk !== "string" || chunk.length !== Math.min(64 * 1024, receipt.characters! - part * 64 * 1024)) 81+ throw Error("incomplete receipt payload"); 84+ if (createHash("sha256").update(json).digest("hex") !== receipt.digest) 85+ throw Error("receipt payload digest mismatch"); 86+ return (JSON.parse(json) as { result: T }).result; 3989 #validate(validate: () => void) { 4090 const result: unknown = validate(); 4191 if (result && (typeof result === "object" || typeof result === "function") && "then" in result) @@ -45,19 +95,34 @@
4595 SqliteWriterState.initialize(this.#storage); 4696 const state = this.#state(); 4797 const format = state.read("runtime", "format"); 48− if (format !== undefined && format !== 1) throw Error("unsupported disk-first runtime format");
49− if (format === undefined) state.write("runtime", "format", 1);
98+ if (format !== undefined && format !== 1 && format !== 2 && format !== 3 && format !== 4 && format !== 5) 99+ throw Error("unsupported disk-first runtime format"); 100+ // Format 5 additionally fences indexed insertion runs and lines from older readers. 101+ // Never lower this marker in place. 102+ if (format !== 5) state.write("runtime", "format", 5); 52105 /** Initializes an empty canonical log without replay. Existing history must be adopted. */ 53− initialize<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
107+ operation: (calls: EngineProject) => T, 108+ validate: () => void, 109+ request?: { id: string; identity: unknown }, 54111 return this.#storage.transactionSync(() => { 55112 this.#validate(validate); 56113 const log = new SqliteLog(this.#storage); 57114 if (log.seq() !== 0) throw Error("disk-first initialization requires an empty log"); 115+ if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity"); 58116 const project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() }); 59117 const result = structuredClone(operation(new EngineProject(project))); 60118 this.#validate(validate); 119+ if (request && log.seq() > 0) 123+ createHash("sha256").update(canonicalJson(request.identity)).digest("hex"), @@ -75,6 +140,12 @@
75140 if (ready !== undefined && ready !== true) throw Error("invalid runtime readiness marker"); 76141 if (ready === true) { 77142 const root = host.root(); 143+ const history = this.#history.prepare(log, root, () => host.root(), validate); 144+ if (!history.ready) { 145+ state.remove("runtime", "history-ready"); 146+ return { ready: false, phase: "history", next: history.next }; 148+ state.write("runtime", "history-ready", true); 78149 const scope = this.#projection.open({ state, log, root }); 80151 this.#validate(validate); @@ -91,7 +162,7 @@
91162 from: cursor?.next ?? 0, 92163 digest: cursor?.digest ?? "", 94− maxBytes: 1_048_576,
165+ maxBytes: log.adoptionPageBytes(cursor?.next ?? 0), @@ -108,8 +179,13 @@
110181 this.#validate(validate); 111− if (page.ready) state.write("runtime", "ready", true);
112− return { ready: page.ready, phase: page.ready ? "ready" : "projection", next: root.logLength };
182+ if (!page.ready) return { ready: false, phase: "projection", next: root.logLength }; 183+ const history = this.#history.prepare(log, root, () => host.root(), validate); 184+ if (history.ready) { 185+ state.write("runtime", "ready", true); 186+ state.write("runtime", "history-ready", true); 188+ return { ready: history.ready, phase: history.ready ? "ready" : "history", next: history.next }; @@ -118,7 +194,11 @@
120196 throw Error("disk-first adoption is not complete"); 121− if (this.#state().read("runtime", "format") !== 1 || this.#state().read("runtime", "ready") !== true)
198+ this.#state().read("runtime", "format") !== 5 || 199+ this.#state().read("runtime", "ready") !== true || 200+ this.#state().read("runtime", "history-ready") !== true 122202 throw Error("disk-first adoption is not complete"); 124204 read<T>(operation: (calls: EngineProject) => T, validate: () => void): T { @@ -143,13 +223,17 @@
143223 const host = this.#host(); 145225 if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity"); 146− const identity = request ? canonicalJson(request.identity) : undefined;
226+ const identity = request ? createHash("sha256").update(canonicalJson(request.identity)).digest("hex") : undefined; 148− const receipt = state.read("runtime:receipts", request.id) as { identity: string; result: T } | undefined;
228+ const receipt = state.read("runtime:receipts", request.id) as 229+ | { format: number; identity: string; result: T } 150− if (receipt.identity !== identity) throw Error("disk-first request identity was reused");
232+ if (receipt.format !== 2 && receipt.format !== 3) throw Error("unsupported disk-first receipt format"); 233+ if (receipt.identity !== identity) 234+ throw Object.assign(Error("disk-first request identity was reused"), { code: "request-reused" }); 151235 this.#validate(validate); 152− return structuredClone(receipt.result);
236+ return this.#receiptResult<T>(state, request.id, receipt); 155239 return host.runCalls({ @@ -159,7 +243,7 @@
159243 checkerReady: false, 160244 operation: (calls) => structuredClone(operation(calls)), 161245 commitReceipt: (result) => { 162− if (request) state.write("runtime:receipts", request.id, { identity, result });
246+ if (request) this.#saveReceipt(state, request.id, identity!, result); --- a/server/src/engine-project.ts
+++ b/server/src/engine-project.ts
@@ -96,6 +96,23 @@
9898 /** Reject an oversized canonical frame before loading its text into JavaScript. */ 99+ frameBytes(seq: number): number { 100+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position"); 101+ const size = this.storage.sql 103+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?", 106+ .toArray()[0] as { parts: number; bytes: number }; 107+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes < 1 || !Number.isSafeInteger(size.bytes)) 108+ throw Error("canonical frame exceeds hard decoding bound or is missing"); 111+ /** A larger first frame gets its own budget; later frames are deferred. */ 112+ adoptionPageBytes(from: number): number { 113+ return Math.max(1_048_576, this.frameBytes(from)); 99116 boundedFrame(seq: number, maxBytes: number): string { 101118 !Number.isSafeInteger(seq) || @@ -122,6 +139,26 @@
122139 return rows.map((row) => row.text).join(""); 142+ /** Stream one canonical frame without retaining its complete JSON text. */ 143+ *frameChunks(seq: number): IterableIterator<string> { 144+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position"); 147+ const rows = this.storage.sql 148+ .exec("SELECT part, text FROM log WHERE seq = ? AND part >= ? ORDER BY part LIMIT 1", seq, expected) 149+ .toArray() as { part: number; text: string }[]; 151+ if (!expected) throw Error("canonical frame is missing"); 154+ const row = rows[0]!; 155+ if (row.part !== expected || row.text.length > LOG_PART_CHARACTERS) 156+ throw Error("canonical frame parts are incomplete or oversized"); 125162 /** Refreshes the in-memory cursor after an enclosing transaction rolls back. */ 126163 refreshSequence(): void { 127164 const rows = this.storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as { @@ -524,11 +561,18 @@
524561 /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */ 525562 private readonly read: ((from: number, limit: number) => Entry[]) | undefined; 526563 private readonly store: SqliteLog | undefined; 564+ private readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined; 528− constructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {
568+ read?: (from: number, limit: number) => Entry[], 570+ historical?: <T>(at: number, operation: (project: Project) => T) => T, 529572 this.project = project; 531574 this.store = store; 575+ this.historical = historical; 534578 /** The project's events from log position `from` (#41): reading consumes nothing. */ @@ -638,6 +682,11 @@
638682 return this.replica; 640684 statusAt(at: number) { 685+ if (this.historical) 686+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({ 687+ at: Math.min(at, this.project.logLength), 688+ ...(p.initialized ? p.status() : { version: -1, agents: [] }), 641690 const p = this.at(at); 643692 at: Math.min(at, this.project.logLength), @@ -647,6 +696,11 @@
649698 whereAt(at: number) { 699+ if (this.historical) 700+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({ 701+ at: Math.min(at, this.project.logLength), 702+ ...(p.initialized ? where(p) : { version: -1, files: {} }), 650704 const p = this.at(at); 652706 at: Math.min(at, this.project.logLength), --- /dev/null
+++ b/server/src/history-host.ts
@@ -0,0 +1,247 @@
1+import { MemoryStore, Project } from "../../worker/project/project.ts"; 2+import { withDecodedFrames } from "./decoded-frames.ts"; 3+import type { SqliteLog, SqliteStorage } from "./engine-project.ts"; 4+import { SqliteHistoryState } from "./history-state.ts"; 5+import type { WriterProjectionSession } from "./writer-host.ts"; 6+import { SqliteWriterState, type WriterRoot, writerFrameChunksDigest } from "./writer-host.ts"; 8+type Cursor = { root: WriterRoot; next: number; digest: string }; 9+const same = (a: WriterRoot, b: WriterRoot) => 10+ a.format === b.format && 11+ a.generation === b.generation && 12+ a.logLength === b.logLength && 13+ a.sharedVersion === b.sharedVersion && 14+ a.digest === b.digest; 16+/** Derived historical state, bound to the host's exact canonical root. */ 17+export class SqliteHistoryHost { 18+ readonly #storage: SqliteStorage; 19+ readonly #namespace: string; 20+ readonly #meta: SqliteWriterState; 21+ constructor(storage: SqliteStorage, namespace: string) { 22+ if (!namespace || namespace.length > 80) throw Error("invalid historical host namespace"); 23+ this.#storage = storage; 24+ this.#namespace = namespace; 25+ this.#meta = new SqliteWriterState(storage, `${namespace}:control`); 27+ #validate(root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) { 28+ const result: unknown = authority(); 29+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result) 30+ throw Error("historical authority must be synchronous"); 31+ if (!same(root, currentRoot())) throw Error("historical canonical root changed"); 34+ this.#meta.remove("history", "cursor"); 35+ this.#meta.remove("history", "verification"); 36+ this.#meta.write("history", "reset", true); 37+ return { ready: false, next: 0 }; 40+ const sql = this.#storage.sql; 41+ const clauses: [string, string, (string | number)[]][] = [ 42+ ["writer_state", "namespace = ?", [this.#namespace]], 45+ "namespace >= ? AND namespace < ?", 46+ [`${this.#namespace}:history:`, `${this.#namespace}:history;`], 48+ ["writer_history_keys", "namespace = ?", [this.#namespace]], 49+ ["writer_history_heads", "namespace = ?", [this.#namespace]], 51+ for (const [table, condition, bindings] of clauses) { 52+ const rows = sql.exec(`SELECT rowid AS id FROM ${table} WHERE ${condition} LIMIT 256`, ...bindings).toArray() as { 55+ if (!rows.length) continue; 56+ sql.exec(`DELETE FROM ${table} WHERE rowid IN (${rows.map(() => "?").join(",")})`, ...rows.map((row) => row.id)); 57+ return { ready: false, next: 0 }; 59+ this.#meta.remove("history", "reset"); 60+ return { ready: false, next: 0 }; 63+ prepare(log: SqliteLog, root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) { 64+ return this.#storage.transactionSync(() => { 65+ this.#validate(root, currentRoot, authority); 66+ SqliteHistoryState.initialize(this.#storage); 67+ if (this.#meta.read("history", "reset") === true) { 68+ const result = this.#resetPage(); 69+ this.#validate(root, currentRoot, authority); 72+ let cursor = this.#meta.read("history", "cursor") as Cursor | undefined; 73+ if (cursor && !same(cursor.root, root)) { 74+ if (cursor.next > root.logLength) return this.#beginReset(); 75+ const saved = this.#meta.read("history", "verification") as Cursor | undefined; 76+ const verification = saved && same(saved.root, root) ? saved : { root, next: 0, digest: "" }; 77+ const budget = log.adoptionPageBytes(verification.next); 80+ while (verification.next < cursor.next && count < 32) { 81+ const size = log.frameBytes(verification.next); 82+ if (bytes && size > budget - bytes) break; 83+ verification.digest = writerFrameChunksDigest( 86+ log.frameChunks(verification.next), 92+ this.#validate(root, currentRoot, authority); 93+ if (verification.next < cursor.next) { 94+ this.#meta.write("history", "verification", verification); 95+ return { ready: false, next: cursor.next }; 97+ if (verification.digest !== cursor.digest) return this.#beginReset(); 98+ cursor = { ...cursor, root }; 99+ this.#meta.write("history", "cursor", cursor); 100+ this.#meta.remove("history", "verification"); 102+ if (cursor?.next === root.logLength) return { ready: true, next: cursor.next }; 103+ const from = cursor?.next ?? 0; 104+ const state = new SqliteHistoryState(this.#storage, this.#namespace, from); 105+ let digest = cursor?.digest ?? ""; 106+ const budget = log.adoptionPageBytes(from); 107+ const decoded = withDecodedFrames( 109+ `${this.#namespace}:decoded`, 111+ { from, to: root.logLength, maxEntries: 32, maxBytes: budget, digest }, 116+ const extended = Project.extendHistoricalPage(state, { 121+ decodedFrames: true, 122+ beginRevision: (revision) => state.beginRevision(revision), 123+ validateAuthority: () => this.#validate(root, currentRoot, authority), 125+ return { ...extended, ready: extended.next === root.logLength }; 127+ : Project.adoptWriterPage(state, { 133+ decodedFrames: true, 134+ currentSource: () => currentRoot(), 135+ beginRevision: (revision) => state.beginRevision(revision), 140+ const page = decoded.result; 141+ digest = decoded.digest; 142+ if (page.ready && digest !== root.digest) throw Error("historical canonical digest mismatch"); 143+ this.#validate(root, currentRoot, authority); 145+ this.#meta.write("history", "cursor", { root, next: page.next, digest } satisfies Cursor); 146+ return { ready: page.ready, next: page.next }; 149+ /** Called inside the canonical writer transaction, before its receipt commits. */ 152+ previous: WriterRoot, 153+ committed: WriterRoot, 154+ currentRoot: () => WriterRoot, 155+ authority: () => void, 157+ this.#storage.transactionSync(() => { 158+ const validate = () => this.#validate(committed, currentRoot, authority); 160+ const cursor = this.#meta.read("history", "cursor") as Cursor | undefined; 163+ !same(cursor.root, previous) || 164+ cursor.next !== previous.logLength || 165+ cursor.digest !== previous.digest 167+ throw Error("historical committed prefix is stale"); 168+ if (committed.logLength < previous.logLength || committed.generation < previous.generation) 169+ throw Error("historical root cannot move backwards"); 170+ let from = previous.logLength, 171+ digest = previous.digest; 172+ while (from < committed.logLength) { 173+ const budget = log.adoptionPageBytes(from); 174+ const state = new SqliteHistoryState(this.#storage, this.#namespace, from); 175+ const decoded = withDecodedFrames( 177+ `${this.#namespace}:decoded`, 179+ { from, to: committed.logLength, maxEntries: 32, maxBytes: budget, digest }, 181+ const page = Project.extendHistoricalPage(state, { 186+ decodedFrames: true, 187+ beginRevision: (revision) => state.beginRevision(revision), 188+ validateAuthority: validate, 193+ const page = decoded.result; 194+ digest = decoded.digest; 198+ if (digest !== committed.digest) throw Error("historical canonical tail digest mismatch"); 200+ this.#meta.write("history", "cursor", { root: committed, next: from, digest } satisfies Cursor); 205+ currentRoot: () => WriterRoot, 206+ authority: () => void, 208+ operation: (project: Project) => T, 209+ viewProvider?: WriterProjectionSession["historicalReadViewProvider"], 211+ return this.#storage.transactionSync(() => { 213+ const assertScope = () => { 214+ if (!active) throw Error("historical scope ended"); 216+ const validate = () => { 218+ this.#validate(root, currentRoot, authority); 222+ const cursor = this.#meta.read("history", "cursor") as Cursor | undefined; 223+ if (!cursor || !same(cursor.root, root) || cursor.next !== root.logLength || cursor.digest !== root.digest) 224+ throw Error("historical state is not ready for canonical root"); 225+ if (!Number.isSafeInteger(at) || at < 0 || at > root.logLength) 226+ throw Error("historical position outside authority"); 227+ const state = new SqliteHistoryState(this.#storage, this.#namespace, root.logLength); 228+ const historical = state.at(at, assertScope); 231+ ? new Project(new MemoryStore()) 232+ : Project.openHistorical( 235+ new SqliteWriterState(this.#storage, `${this.#namespace}:scratch`), 237+ viewProvider?.(historical), 239+ const result = structuredClone(operation(project)); --- /dev/null
+++ b/server/src/history-state.ts
@@ -0,0 +1,180 @@
1+import type { GraphStateStorage } from "../../src/engine/state-source.ts"; 2+import type { SqliteStorage } from "./engine-project.ts"; 3+import { SqliteWriterState } from "./writer-host.ts"; 5+/** Derived history for a freshly adopted writer namespace. The host supplies 6+ * canonical log positions and commits this state with the canonical transaction. */ 7+export class SqliteHistoryState implements GraphStateStorage { 8+ readonly #storage: SqliteStorage; 9+ readonly #namespace: string; 10+ readonly #current: SqliteWriterState; 13+ static initialize(storage: SqliteStorage): void { 14+ SqliteWriterState.initialize(storage); 16+ "CREATE TABLE IF NOT EXISTS writer_history_keys (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, revision INTEGER NOT NULL, deleted INTEGER NOT NULL, PRIMARY KEY(namespace, collection, key, revision))", 19+ "CREATE TABLE IF NOT EXISTS writer_history_heads (namespace TEXT PRIMARY KEY, sealed INTEGER NOT NULL)", 22+ constructor(storage: SqliteStorage, namespace: string, revision = 0) { 23+ if (!namespace || namespace.length > 80) throw Error("invalid history namespace"); 24+ if (!Number.isSafeInteger(revision) || revision < 0) throw Error("invalid history revision"); 25+ this.#storage = storage; 26+ this.#namespace = namespace; 27+ this.#current = new SqliteWriterState(storage, namespace); 28+ this.#revision = revision; 30+ beginRevision(revision: number): void { 31+ if (!Number.isSafeInteger(revision) || revision < this.#revision) 32+ throw Error("history revision must not go backwards"); 33+ if (revision > this.#revision) this.seal(); 34+ this.#revision = revision; 40+ .exec("SELECT sealed FROM writer_history_heads WHERE namespace = ?", this.#namespace) 41+ .toArray()[0] as { sealed: number } | undefined 46+ this.#storage.sql.exec( 47+ "INSERT INTO writer_history_heads VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET sealed = MAX(sealed, excluded.sealed)", 51+ this.#sealedThrough = this.#revision; 53+ #savedNamespace(revision: number): string { 54+ return `${this.#namespace}:history:${revision}`; 56+ read(collection: string, key: string): unknown { 57+ return this.#current.read(collection, key); 59+ entries(collection: string): Iterable<readonly [string, unknown]> { 60+ return this.#current.entries(collection); 62+ write(collection: string, key: string, value: unknown): void { 63+ if (this.#revision <= Math.max(this.#sealedThrough, this.#sealed())) throw Error("historical revision is sealed"); 64+ this.transaction(() => { 65+ this.#current.write(collection, key, value); 66+ const saved = this.#savedNamespace(this.#revision); 67+ this.#storage.sql.exec( 68+ "DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?", 73+ this.#storage.sql.exec( 74+ "INSERT INTO writer_state SELECT ?, collection, key, part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?", 80+ this.#storage.sql.exec( 81+ "INSERT OR REPLACE INTO writer_history_keys VALUES (?, ?, ?, ?, 0)", 89+ remove(collection: string, key: string): void { 90+ if (this.#revision <= Math.max(this.#sealedThrough, this.#sealed())) throw Error("historical revision is sealed"); 91+ this.transaction(() => { 92+ this.#current.remove(collection, key); 93+ new SqliteWriterState(this.#storage, this.#savedNamespace(this.#revision)).remove(collection, key); 94+ this.#storage.sql.exec( 95+ "INSERT OR REPLACE INTO writer_history_keys VALUES (?, ?, ?, ?, 1)", 103+ transaction<T>(body: () => T): T { 104+ const revision = this.#revision; 105+ const sealed = this.#sealedThrough; 107+ return this.#storage.transactionSync(body); 109+ this.#revision = revision; 110+ this.#sealedThrough = sealed; 114+ /** Read-only historical values, with bounded key pages and value decoding. */ 115+ at(revision: number, assertAuthority: () => void = () => {}): GraphStateStorage { 117+ if (!Number.isSafeInteger(revision) || revision < 0 || revision > this.#revision) 118+ throw Error("history position outside authority"); 119+ if (revision > this.#sealed()) throw Error("historical revision is not sealed"); 120+ const storage = this.#storage, 121+ namespace = this.#namespace; 122+ const read = (collection: string, key: string): unknown => { 124+ const row = storage.sql 126+ "SELECT revision, deleted FROM writer_history_keys WHERE namespace = ? AND collection = ? AND key = ? AND revision <= ? ORDER BY revision DESC LIMIT 1", 132+ .toArray()[0] as { revision: number; deleted: number } | undefined; 133+ if (!row || row.deleted) return undefined; 134+ return new SqliteWriterState(storage, this.#savedNamespace(row.revision)).read(collection, key); 136+ const refuse = (): never => { 137+ throw Error("historical state is read-only"); 141+ *entries(collection) { 142+ let after: string | undefined; 145+ const rows = storage.sql 147+ `SELECT key FROM writer_history_keys WHERE namespace = ? AND collection = ? AND revision <= ? ${after === undefined ? "" : "AND key > ?"} GROUP BY key ORDER BY key LIMIT 64`, 151+ ...(after === undefined ? [] : [after]), 153+ .toArray() as { key: string }[]; 154+ if (!rows.length) return; 155+ for (const row of rows) { 156+ const value = read(collection, row.key); 157+ // Stored undefined is a value; deletion is determined by the ledger. 158+ const latest = storage.sql 160+ "SELECT deleted FROM writer_history_keys WHERE namespace = ? AND collection = ? AND key = ? AND revision <= ? ORDER BY revision DESC LIMIT 1", 166+ .toArray()[0] as { deleted: number }; 167+ if (!latest.deleted) yield [row.key, value] as const; 169+ after = rows.at(-1)!.key; 174+ transaction: (body) => { 176+ return storage.transactionSync(body); --- /dev/null
+++ b/server/src/json-chunk-cursor.ts
@@ -0,0 +1,68 @@
1+/** Incremental UTF-16 cursor over canonical log chunks. */ 2+export class JsonChunkCursor { 3+ readonly #input: Iterator<string>; 6+ constructor(chunks: Iterable<string>) { 7+ this.#input = chunks[Symbol.iterator](); 9+ peek(): string | undefined { 10+ while (this.#offset === this.#chunk.length) { 11+ const next = this.#input.next(); 12+ if (next.done) return undefined; 13+ if (typeof next.value !== "string" || next.value.length > 600000) throw Error("invalid JSON input chunk"); 14+ this.#chunk = next.value; 17+ return this.#chunk[this.#offset]; 20+ const char = this.peek(); 21+ if (char === undefined) throw Error("truncated JSON input"); 25+ /** Consume one quoted JSON string, yielding bounded decoded text. */ 26+ *stringChunks(): IterableIterator<string> { 27+ if (this.take() !== '"') throw Error("expected JSON string"); 30+ let char = this.take(); 32+ if (buffer) yield buffer; 35+ if (char.charCodeAt(0) < 32) throw Error("unescaped JSON control character"); 37+ const escape = this.take(); 38+ const simple: Record<string, string> = { 48+ if (escape === "u") { 50+ for (let i = 0; i < 4; i++) hex += this.take(); 51+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw Error("invalid JSON Unicode escape"); 52+ char = String.fromCharCode(Number.parseInt(hex, 16)); 54+ if (!Object.hasOwn(simple, escape)) throw Error("invalid JSON escape"); 55+ char = simple[escape]!; 59+ if (buffer.length === 16384) { 66+ this.#input.return?.(); --- /dev/null
+++ b/server/src/json-events.ts
@@ -0,0 +1,74 @@
1+import { JsonChunkCursor } from "./json-chunk-cursor.ts"; 3+export type JsonEvent = 4+ | { kind: "object" | "array" | "end" | "string" | "string-end" } 5+ | { kind: "key" | "text"; value: string } 6+ | { kind: "value"; value: number | boolean | null }; 8+/** Structural JSON decoding. Retains nesting and one bounded string fragment, not a decoded tree. */ 9+export function* jsonEvents(chunks: Iterable<string>): IterableIterator<JsonEvent> { 10+ const cursor = new JsonChunkCursor(chunks); 11+ const whitespace = () => { 12+ while (cursor.peek() !== undefined && /[ \t\n\r]/.test(cursor.peek()!)) cursor.take(); 14+ function* value(depth: number): IterableIterator<JsonEvent> { 15+ if (depth > 128) throw Error("JSON nesting exceeds bound"); 17+ const first = cursor.peek(); 19+ yield { kind: "string" }; 20+ for (const text of cursor.stringChunks()) yield { kind: "text", value: text }; 21+ yield { kind: "string-end" }; 24+ if (first === "{" || first === "[") { 25+ const object = cursor.take() === "{"; 26+ const close = object ? "}" : "]"; 27+ yield { kind: object ? "object" : "array" }; 29+ if (cursor.peek() === close) { 31+ yield { kind: "end" }; 38+ for (const text of cursor.stringChunks()) { 40+ if (key.length > 4096) throw Error("JSON key exceeds bound"); 42+ yield { kind: "key", value: key }; 44+ if (cursor.take() !== ":") throw Error("expected JSON colon"); 46+ yield* value(depth + 1); 48+ const separator = cursor.take(); 49+ if (separator === close) break; 50+ if (separator !== ",") throw Error("expected JSON separator"); 52+ yield { kind: "end" }; 56+ while (cursor.peek() !== undefined && !/[ \t\n\r,\]}]/.test(cursor.peek()!)) { 57+ token += cursor.take(); 58+ if (token.length > 256) throw Error("JSON scalar exceeds bound"); 60+ if (token === "true" || token === "false" || token === "null") { 61+ yield { kind: "value", value: token === "null" ? null : token === "true" }; 63+ if (!/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw Error("invalid JSON scalar"); 64+ yield { kind: "value", value: Number(token) }; 70+ if (cursor.peek() !== undefined) throw Error("trailing JSON input"); --- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -4,8 +4,10 @@
44// R2 copies, edge cache, probes or disk-first writer. 66import { DurableObject } from "cloudflare:workers"; 7−import { type Answer, answer, type Readers } from "../../worker/project/http.ts";
7+import { createHash } from "node:crypto"; 8+import { type Answer, answer, type Readers, readerAnswer } from "../../worker/project/http.ts"; 89import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 10+import { ProjectError } from "../../worker/project/project-error.ts"; 911import { BLOB_MAX, BlobStore } from "./blobs.ts"; 1012import { DiskFirstRuntime } from "./disk-first-runtime.ts"; 1113import { EngineProject, SqliteLog } from "./engine-project.ts"; @@ -163,6 +165,7 @@
164166 how: string | undefined, 168+ request?: { id: string; principal: string }, 166169 ): Promise<Answer> { 167170 const runtime = this.diskRuntime()!; 168171 const validate = () => { @@ -170,7 +173,11 @@
170173 throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" }); 172175 const progress = await this.prepareDisk(validate); 173− const known = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
176+ const legacyReaders = (await this.ctx.storage.get<string[]>("readers")) ?? []; 177+ const storedReaders = progress?.ready 178+ ? (new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "readers") as string[] | undefined) 180+ const known = new Set(storedReaders ?? legacyReaders); 175182 let readersChanged = false; 176183 const readers: Readers = { @@ -187,25 +194,44 @@
187194 return { status: 404, body: { error: "no such project; run init first" } }; 188195 if (!progress?.ready && !(progress?.phase === "empty" && op === "init")) 189196 return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } }; 197+ if (agent && op !== "reader") { 198+ const refused = readerAnswer({ status: () => undefined }, op, agent, body, readers); 199+ if (refused) return refused; 190201 const before = new SqliteLog(this.ctx.storage).seq(); 191202 const action = (calls: EngineProject) => { 192203 const result = answer(calls, op, agent, body, readers, how); 193204 if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`); 206+ new SqliteWriterState(this.ctx.storage, "server-disk-v1").write("runtime", "readers", readers.list()); 210+ const receipt = request 212+ id: `http:${createHash("sha256").update(request.principal).digest("hex")}:${request.id}`, 215+ principal: request.principal, 216+ agent: agent ?? null, 198224 progress.phase === "empty" 199− ? runtime.initialize(action, validate)
225+ ? runtime.initialize(action, validate, receipt) 200226 : READ_OPS.has(op) || op.startsWith("change/") 201227 ? runtime.read(action, validate) 202− : runtime.write(action, validate);
228+ : runtime.write(action, validate, receipt); 203230 if (readersChanged) { 204231 this.authorityRevision++; 205− await this.ctx.storage.put("readers", readers.list());
207233 const log = new SqliteLog(this.ctx.storage); 208− if (log.seq() !== before) {
234+ if (log.seq() !== before || (request && !READ_OPS.has(op))) { 210236 await this.ctx.storage.put("name", name); 211237 await this.soon(Date.now() + 100); @@ -345,20 +371,38 @@
348375 ): Promise<Answer> { 349376 const revision = this.authorityRevision; 377+ let principal = "shared-token"; 379+ requestId !== undefined && 380+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(requestId) 382+ return { status: 400, body: { error: "Idempotency-Key must be a UUID" } }; 351384 const decided = await this.checkAgentKey(key.presented, agent, key.address); 352385 if (!decided.ok) return { status: decided.status, body: { error: decided.error } }; 353386 const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route }); 354387 if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } }; 389+ principal = `key:${decided.id}`; 357391 if (op === "feed" && !inFeed) return this.feed(name, body); 358392 if (this.diskRuntime()) { 360− return await this.diskCall(name, op, agent, body, how, revision);
394+ return await this.diskCall( 401+ requestId ? { id: requestId, principal } : undefined, 404+ if ((error as { code?: string })?.code === "request-reused") 405+ return { status: 409, body: { error: "Idempotency-Key was reused for a different request" } }; 362406 if ((error as { code?: string })?.code === "authority-changed") 363407 return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } }; @@ -499,14 +543,27 @@
499543 if (found) await this.ctx.storage.put("git:head", found.head); 546+ // Unexpected failures leave the cursor unacknowledged for retry. Engine 547+ // refusals are recorded and acknowledged so a later fixing commit can advance. 548+ const ingest = (p: EngineProject) => 549+ p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()); 550+ const runtime = this.diskRuntime(); 502551 let result: unknown; 504− result = this.useProject(
505− (p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()),
506− true,
507− );
508− } catch (e) {
509− result = { error: e instanceof Error ? e.message : String(e) };
554+ ? runtime.write(ingest, () => {}, { 555+ id: `git:${found.head}`, 560+ commits: found.commits.map((commit) => commit.sha), 563+ : this.useProject(ingest, true); 565+ if (!(error instanceof ProjectError)) throw error; 566+ result = { error: error.message }; 512569 at: new Date().toISOString(), --- a/server/src/projection-store.ts
+++ b/server/src/projection-store.ts
@@ -10,7 +10,7 @@
1010} from "../../src/engine/experimental/projection-root.ts"; 1111import { ProjectionSnapshots } from "../../src/engine/experimental/projection-snapshots.ts"; 1212import { Graph } from "../../src/engine/graph.ts"; 13−import { CachedStateStorage } from "../../src/engine/state-source.ts";
13+import { CachedStateStorage, type GraphStateStorage } from "../../src/engine/state-source.ts"; 1414import { canonicalJson } from "../../worker/project/operation-protocol.ts"; 1515import { projectedReader } from "../../worker/project/projection-provider.ts"; 1616import { Membership, type Published } from "../../worker/project/spaces.ts"; @@ -326,7 +326,8 @@
327327 const overlays: ProjectionOverlayStorage[] = []; 328328 const scopes: ProjectionReadScope[] = []; 329− const versions = new Membership(state).shared.versions;
329+ const membership = new Membership(state); 330+ const versions = membership.shared.versions; 330331 const current = (): WriterRoot => { 331332 if (!live) throw Error("closed projection writer"); 332333 if (log.seq() === observed.logLength && log.generation() !== observed.generation) @@ -339,45 +340,98 @@
342− return {
343− readViewProvider: (graph) => {
344+ (membershipState: GraphStateStorage): WriterProjectionSession["readViewProvider"] => 346+ const membership = new Membership(membershipState); 347+ const versions = membership.shared.versions; 344348 const scope = new ProjectionReadScope(graph, () => (live ? token : undefined)); 345349 scopes.push(scope); 350+ const readers = new Map<string, ReturnType<typeof projectedReader>>(); 352+ const reuse = (key: string, build: () => ReturnType<typeof projectedReader>) => { 353+ const source = current(); 354+ const next = JSON.stringify([ 361+ if (next !== identity) { 365+ const cacheable = key.length <= 8192 && /^(?:v|a) @/.test(key); 366+ const cached = cacheable ? readers.get(key) : undefined; 368+ scope.guard(graph)(); 371+ const reader = build(); 373+ if (readers.size >= 32) readers.delete(readers.keys().next().value!); 374+ readers.set(key, reader); 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);
384+ context: this.#context, 385+ sourceGeneration: this.#generation, 386+ sourceLength: () => current().logLength, 387+ prefixDigest: (length) => 388+ length === current().logLength 390+ : (state.read(`${this.#meta}:prefixes`, String(length)) as string | undefined), 391+ version: () => versions.length - 1, 392+ committed: () => head, 394+ state.read(`${this.#meta}:versions`, String(version)) as ProjectionHandle | undefined, 395+ delta: (version) => versions[version], 396+ namedVersion: (name, version) => { 397+ const space = membership.spaces.get(name); 398+ const selected = space?.versions[version]; 399+ if (!space || selected?.sharedBase === undefined) return undefined; 401+ sharedBase: selected.sharedBase, 402+ atoms: (function* () { 403+ for (let at = 0; at <= version; at++) { 404+ const delta = space.versions[at]!; 405+ if (delta.dropped?.length) throw Error("unexpected named draft removal"); 411+ guard: () => scope.guard(graph), 413+ const overlay = new ProjectionOverlayStorage( 415+ `${this.#context.namespace}:${this.#nextOverlay++}`, 416+ (collection) => state.clearProjectionOverlay(collection), 418+ overlays.push(overlay); 419+ return new CachedStateStorage(overlay, overlays.length <= 32 ? 65_536 : 0, 256); 372− },
373− key,
376− },
428+ readViewProvider: provider(state), 429+ historicalReadViewProvider: provider, 377430 commit: (project, committed) => { 378431 if (canonicalJson(current()) !== canonicalJson(committed)) throw Error("projection commit source mismatch"); 432+ const commitState = new CachedStateStorage(state, 65_536, 256); 379433 const adapter = new ExperimentalMarkerProjection( 380− state,
382436 this.#context.defaultFile, 383437 this.#context.namespace, --- a/server/src/router.ts
+++ b/server/src/router.ts
@@ -257,7 +257,16 @@
257257 body = { ...rest, ...(/^[\w.+-]{1,20}\/[\w.+-]{1,40}$/.test(client) ? { client } : {}) }; 260− const a = (await obj.call(project, (op ?? top)!, agent, body, false, how, keyForCall)) as unknown as Answer;
260+ const a = (await obj.call( 268+ request.headers.get("Idempotency-Key") ?? undefined, 269+ )) as unknown as Answer; 261270 return json(a.status, a.body); 263272 const error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`; --- /dev/null
+++ b/server/src/stored-json-view.ts
@@ -0,0 +1,56 @@
1+import type { StoredJson } from "./stored-json.ts"; 3+/** Read-only JSON view. Containers stay on disk; a requested string is materialized explicitly. */ 4+export function storedJsonView(node: StoredJson): unknown { 5+ const kind = node.kind; 6+ if (kind === "value") return node.scalar(); 7+ if (kind === "string") return [...node.textChunks()].join(""); 8+ const array = kind === "array"; 9+ const target = array ? [] : Object.create(null); 10+ const index = (key: PropertyKey): number | undefined => { 11+ if (typeof key !== "string" || !/^(0|[1-9][0-9]*)$/.test(key)) return undefined; 12+ const value = Number(key); 13+ return Number.isSafeInteger(value) ? value : undefined; 15+ const child = (key: PropertyKey) => { 16+ if (typeof key !== "string") return undefined; 17+ if (!array) return node.child(key); 18+ const position = index(key); 19+ return position === undefined ? undefined : node.child(position); 21+ return new Proxy(target, { 22+ get(target, key, receiver) { 23+ if (array && key === "length") return node.length; 24+ const value = child(key); 25+ if (value) return storedJsonView(value); 26+ return array ? Reflect.get(target, key, receiver) : undefined; 29+ return !!child(key) || (array && Reflect.has(target, key)); 33+ ? [...Array.from({ length: node.length }, (_, i) => String(i)), "length"] 34+ : [...node.properties()].map(([key]) => key); 36+ getOwnPropertyDescriptor(target, key) { 37+ if (array && key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: node.length }; 38+ const value = child(key); 40+ ? { configurable: true, enumerable: true, writable: false, value: storedJsonView(value) } 44+ throw Error("stored JSON view is read-only"); 47+ throw Error("stored JSON view is read-only"); 50+ throw Error("stored JSON view is read-only"); 52+ preventExtensions() { 53+ throw Error("stored JSON view is read-only"); --- /dev/null
+++ b/server/src/stored-json.ts
@@ -0,0 +1,150 @@
1+import type { GraphStateStorage } from "../../src/engine/state-source.ts"; 2+import { StoredText } from "../../src/engine/stored-text.ts"; 3+import { type JsonEvent, jsonEvents } from "./json-events.ts"; 5+/** Temporary decoded JSON on disk. A root is published only after complete parsing. */ 6+export function storeJson(storage: GraphStateStorage, namespace: string, chunks: Iterable<string>): number { 7+ return storage.transaction(() => { 8+ if (storage.read(namespace, "root") !== undefined) throw Error("decoded JSON already exists"); 9+ const events = jsonEvents(chunks); 11+ const take = (): JsonEvent => { 12+ const event = events.next(); 13+ if (event.done) throw Error("truncated JSON events"); 16+ const text = new StoredText(storage, `${namespace}:text`); 17+ const value = (event = take()): number => { 19+ if (!Number.isSafeInteger(nextId)) throw Error("decoded JSON identity overflow"); 20+ if (event.kind === "value") 21+ storage.write(namespace, String(id), { 23+ value: typeof event.value === "number" ? String(event.value) : event.value, 24+ number: typeof event.value === "number", 25+ negativeZero: Object.is(event.value, -0), 27+ else if (event.kind === "string") { 33+ if (part.kind === "string-end") return; 34+ if (part.kind !== "text") throw Error("invalid JSON string events"); 39+ storage.write(namespace, String(id), { kind: "string" }); 40+ } else if (event.kind === "array" || event.kind === "object") { 43+ const child = take(); 44+ if (child.kind === "end") break; 45+ if (event.kind === "object" && child.kind !== "key") throw Error("invalid JSON object events"); 46+ const key = child.kind === "key" ? child.value : String(count); 47+ const childId = value(event.kind === "object" ? take() : child); 48+ const edge = JSON.stringify([id, key]); 49+ if (event.kind === "object" && storage.read(`${namespace}:edges`, edge) === undefined) { 50+ storage.write(`${namespace}:keys`, JSON.stringify([id, count]), key); 53+ storage.write(`${namespace}:edges`, edge, childId); 54+ if (event.kind === "array") count++; 56+ storage.write(namespace, String(id), { kind: event.kind, count }); 57+ } else throw Error("invalid JSON value event"); 61+ const root = value(); 62+ if (!events.next().done) throw Error("trailing JSON events"); 63+ storage.write(namespace, "root", { format: 1, id: root, nodes: nextId }); 71+/** A disk-backed JSON node. Child lookup does not decode siblings or string payloads. */ 72+export class StoredJson { 73+ readonly storage: GraphStateStorage; 74+ readonly namespace: string; 76+ readonly nodes: number; 77+ constructor(storage: GraphStateStorage, namespace: string, id?: number) { 78+ this.storage = storage; 79+ this.namespace = namespace; 80+ const root = storage.read(namespace, "root") as { format: number; id: number; nodes: number } | undefined; 81+ if (root?.format !== 1 || !Number.isSafeInteger(root.nodes) || root.nodes < 1 || root.id !== 0) 82+ throw Error("invalid stored JSON root"); 83+ this.nodes = root.nodes; 84+ this.id = id ?? root.id; 85+ if (!Number.isSafeInteger(this.id) || this.id < 0 || this.id >= this.nodes) 86+ throw Error("invalid stored JSON identity"); 88+ private node(): { kind: string; count?: number; value?: unknown; number?: boolean; negativeZero?: boolean } { 89+ const node = this.storage.read(this.namespace, String(this.id)) as 90+ | { kind: string; count?: number; value?: unknown; number?: boolean; negativeZero?: boolean } 92+ if (!node || !["array", "object", "string", "value"].includes(node.kind)) throw Error("invalid stored JSON node"); 96+ return this.node().kind; 98+ get length(): number { 99+ const node = this.node(); 100+ if (node.kind !== "array" || !Number.isSafeInteger(node.count) || node.count! < 0) 101+ throw Error("invalid stored JSON array"); 104+ child(key: string | number): StoredJson | undefined { 105+ const node = this.node(); 106+ if (node.kind !== "object" && node.kind !== "array") throw Error("stored JSON node is not a container"); 108+ node.kind === "array" && 109+ (typeof key !== "number" || !Number.isSafeInteger(key) || key < 0 || key >= this.length) 112+ const id = this.storage.read(`${this.namespace}:edges`, JSON.stringify([this.id, String(key)])); 113+ if (id === undefined) { 114+ if (node.kind === "array") throw Error("missing stored JSON array element"); 117+ if (typeof id !== "number") throw Error("invalid stored JSON edge"); 118+ return new StoredJson(this.storage, this.namespace, id); 120+ *elements(): IterableIterator<StoredJson> { 121+ const length = this.length; 122+ for (let index = 0; index < length; index++) yield this.child(index)!; 124+ *properties(): IterableIterator<[string, StoredJson]> { 125+ const node = this.node(); 126+ if (node.kind !== "object" || !Number.isSafeInteger(node.count) || node.count! < 0) 127+ throw Error("invalid stored JSON object"); 128+ for (let index = 0; index < node.count!; index++) { 129+ const key = this.storage.read(`${this.namespace}:keys`, JSON.stringify([this.id, index])); 130+ if (typeof key !== "string") throw Error("missing stored JSON object key"); 131+ const child = this.child(key); 132+ if (!child) throw Error("missing stored JSON object member"); 136+ *textChunks(): IterableIterator<string> { 137+ if (this.kind !== "string") throw Error("stored JSON node is not text"); 138+ yield* new StoredText(this.storage, `${this.namespace}:text`).chunks(String(this.id)); 140+ scalar(): number | boolean | null { 141+ const node = this.node(); 142+ if (node.kind !== "value") throw Error("stored JSON node is not a scalar"); 144+ if (typeof node.value !== "string" || Number.isNaN(Number(node.value))) throw Error("invalid stored JSON number"); 145+ return node.negativeZero ? -0 : Number(node.value); 147+ if (node.value === null || typeof node.value === "boolean" || typeof node.value === "number") return node.value; 148+ throw Error("invalid stored JSON scalar"); --- a/server/src/writer-host.ts
+++ b/server/src/writer-host.ts
@@ -5,6 +5,7 @@
55import type { GraphStateStorage } from "../../src/engine/state-source.ts"; 66import { Project, type WriterSource } from "../../worker/project/project.ts"; 77import type { ProjectOptions } from "../../worker/project/project-types.ts"; 8+import { withDecodedFrames } from "./decoded-frames.ts"; @@ -12,6 +13,7 @@
1415} from "./engine-project.ts"; 16+import type { SqliteHistoryHost } from "./history-host.ts"; 1618export class SqliteWriterState implements GraphStateStorage { 1719 readonly #storage: SqliteStorage; @@ -145,25 +147,39 @@
146148/** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */ 147149export function writerFrameDigest(previous: string, seq: number, json: string): string { 148− return createHash("sha256")
150+ return writerFrameChunksDigest(previous, seq, [json]); 153+/** Same canonical digest without retaining the complete frame. */ 154+export function writerFrameChunksDigest(previous: string, seq: number, chunks: Iterable<string>): string { 155+ const hash = createHash("sha256") 149156 .update("abso-writer-log-v1\n") 150157 .update(JSON.stringify([previous, seq])) 151− .update("\n")
152− .update(json, "utf8")
153− .digest("hex");
160+ for (const chunk of chunks) { 161+ const text = carry + chunk; 162+ const last = text.charCodeAt(text.length - 1); 163+ const split = last >= 0xd800 && last <= 0xdbff; 164+ carry = split ? text.slice(-1) : ""; 165+ hash.update(split ? text.slice(0, -1) : text, "utf8"); 167+ if (carry) hash.update(carry, "utf8"); 168+ return hash.digest("hex"); 156171export function advanceWriterRoot(log: SqliteLog, previous: WriterRoot, source: WriterSource): WriterRoot { 157172 let digest = previous.digest; 158173 if (source.logLength < previous.logLength) throw new Error("writer root cannot move backwards"); 159174 for (let seq = previous.logLength; seq < source.logLength; seq++) 160− digest = writerFrameDigest(digest, seq, log.boundedFrame(seq, 8_000_000));
175+ digest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq)); 161176 return { format: 1, ...source, digest }; 164179/** Inactive host for explicit adoption and synchronous fenced writer operations. */ 165180export interface WriterProjectionSession { 166181 readonly readViewProvider: NonNullable<ProjectOptions["readViewProvider"]>; 182+ historicalReadViewProvider?(state: GraphStateStorage): NonNullable<ProjectOptions["readViewProvider"]>; 167183 commit(project: Project, root: WriterRoot): void; 168184 /** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */ @@ -176,21 +192,25 @@
177193export class SqliteWriterHost { 178194 readonly #storage: SqliteStorage; 195+ readonly #namespace: string; 179196 readonly #state: SqliteWriterState; 180197 readonly #log: SqliteLog; 181198 readonly #projection?: WriterProjectionHost; 182199 readonly #indexProjectionAtoms: boolean; 200+ readonly #history?: SqliteHistoryHost; 184202 storage: SqliteStorage, 185203 namespace: string, 186204 projection?: WriterProjectionHost, 187− options: { indexProjectionAtoms?: boolean } = {},
205+ options: { indexProjectionAtoms?: boolean; history?: SqliteHistoryHost } = {}, 189207 this.#storage = storage; 208+ this.#namespace = namespace; 190209 this.#state = new SqliteWriterState(storage, namespace); 191210 this.#log = new SqliteLog(storage); 192211 this.#projection = projection; 193212 this.#indexProjectionAtoms = options.indexProjectionAtoms ?? false; 213+ this.#history = options.history; 195215 #indexOptions(adopting = false) { 196216 const mode = this.#state.read("host", "projection-atom-index-mode"); @@ -246,7 +266,6 @@
246266 input.maxEntries > 256 || 247267 !Number.isSafeInteger(input.maxBytes) || 248268 input.maxBytes < 1 || 249− input.maxBytes > 8_000_000 ||
250269 !(input.digest === "" || /^[a-f0-9]{64}$/.test(input.digest)) 252271 throw new Error("invalid bounded adoption request"); @@ -288,30 +307,29 @@
289308 throw new Error("writer adoption root cursor is stale"); 290309 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(),
310+ const decoded = withDecodedFrames( 312+ `${this.#namespace}:decoded`, 314+ { from, to: source.logLength, ...limits, digest }, 316+ const result = Project.adoptWriterPage( 323+ decodedFrames: true, 324+ currentSource: () => this.source(), 313− indexOptions,
331+ const result = decoded.result; 332+ digest = decoded.digest; 315333 SqliteWriterHost.#sync(validateAuthority()); 316334 this.#state.write("host", "adoption-root", { source, next: result.next, digest }); 317335 if (result.ready) { @@ -351,7 +369,25 @@
351369 readViewProvider: projection?.readViewProvider, 352370 entryAt: (index) => this.#log.since(index, 1)[0]!, 354− const result = input.operation(new EngineProject(project, (from, limit) => this.#log.since(from, limit)));
372+ const root = this.root(); 373+ const result = input.operation( 376+ (from, limit) => this.#log.since(from, limit), 379+ ? (at, operation) => 380+ this.#history!.read( 383+ input.validateAuthority, 386+ projection?.historicalReadViewProvider, 355391 SqliteWriterHost.#sync(result); 356392 SqliteWriterHost.#sync(input.validateAuthority()); 357393 if (!SqliteWriterHost.#same(source, this.source())) throw new Error("reader source changed"); @@ -374,7 +410,15 @@
376412 operation: (project) => { 377− const calls = new EngineProject(project, (from, limit) => this.#log.since(from, limit), this.#log);
413+ const root = this.root(); 414+ const calls = new EngineProject( 416+ (from, limit) => this.#log.since(from, limit), 419+ ? (at, operation) => this.#history!.read(root, () => this.root(), input.validateAuthority, at, operation) 378422 calls.setCheckerReady(input.checkerReady); 379423 return input.operation(calls); @@ -413,6 +457,7 @@
413457 const committedRoot = advanceWriterRoot(this.#log, root, committed); 414458 this.#state.write("host", "canonical-root", committedRoot); 415459 SqliteWriterHost.#sync(projection?.commit(project, committedRoot)); 460+ this.#history?.advance(this.#log, root, committedRoot, () => this.root(), input.validateAuthority); 416461 SqliteWriterHost.#sync(input.commitReceipt(result, committed)); --- /dev/null
+++ b/server/test/atom-list-history.test.ts
@@ -0,0 +1,65 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { Graph } from "../../src/engine/graph.ts"; 4+import { answer } from "../../worker/project/http.ts"; 5+import { Project } from "../../worker/project/project.ts"; 6+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 7+import { SqliteLog } from "../src/engine-project.ts"; 8+import { SqliteHistoryState } from "../src/history-state.ts"; 9+import { memoryStorage } from "./helpers.ts"; 11+test("large atom lists preserve historical reads after later writes", (t) => { 12+ const storage = memoryStorage(); 13+ t.after(() => storage.db.close()); 14+ const runtime = () => new DiskFirstRuntime(storage, "list-history", "list-history"); 15+ const old = Array.from({ length: 300 }, (_, i) => `old line ${i}`).join("\n") + "\n"; 16+ const current = Array.from({ length: 300 }, (_, i) => `new line ${i}`).join("\n") + "\n"; 17+ runtime().initialize( 18+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": old } }), 21+ while (!runtime().preparePage(() => {}).ready) {} 22+ const before = runtime().read( 23+ (calls) => calls.fileAt("a.txt", 0, null), 28+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": current } }), 35+ (calls) => answer(calls, "publish", "alice", { message: "Replace all lines" }), 40+ t.mock.method(Project, "load", () => { 41+ throw Error("full history replay forbidden"); 45+ (calls) => calls.fileAt("a.txt", 0, null), 52+ (calls) => calls.shared().files["a.txt"], 58+ (storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE collection LIKE 'atom-list:%'").get()! 61+ const history = new SqliteHistoryState(storage, "list-history:history", new SqliteLog(storage).seq()); 62+ const graph = new Graph({ storage: history.at(1, () => {}) }); 63+ assert.equal(graph.lineText("a0.0"), "old line 0"); 64+ assert.equal(graph.atom("a0").inserts[0]!.lines[0], "old line 0"); --- /dev/null
+++ b/server/test/decoded-adoption-bounds.test.ts
@@ -0,0 +1,31 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { SqlState } from "../../src/engine/test/storage-helper.ts"; 4+import { MemoryStore, Project } from "../../worker/project/project.ts"; 6+test("large adoption budgets require decoded frames and refuse JSON without mutation", (t) => { 7+ const storage = new SqlState(); 8+ t.after(() => storage.db.close()); 9+ const log = new MemoryStore(); 10+ new Project(log).init({ "a.txt": "small\n" }, 0); 11+ const source = { generation: 1, logLength: 1, sharedVersion: 0 }; 12+ const frames = [{ seq: 0, json: JSON.stringify(log.entries[0]) }]; 13+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 14+ const input = { source, from: 0, frames, maxEntries: 1, maxBytes: 8100000, currentSource: () => source }; 15+ assert.throws(() => Project.adoptWriterPage(storage, input), /invalid writer adoption bounds/); 16+ assert.throws(() => Project.adoptWriterPage(storage, { ...input, decodedFrames: true }), /requires decoded frames/); 17+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 20+ Project.extendHistoricalPage(storage, { 26+ validateAuthority() {}, 28+ /invalid historical extension bounds/, 30+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); --- /dev/null
+++ b/server/test/decoded-entry-adoption.test.ts
@@ -0,0 +1,62 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { SqlState } from "../../src/engine/test/storage-helper.ts"; 4+import { MemoryStore, Project } from "../../worker/project/project.ts"; 5+import type { Entry } from "../../worker/project/project-types.ts"; 6+import { StoredJson, storeJson } from "../src/stored-json.ts"; 7+import { storedJsonView } from "../src/stored-json-view.ts"; 9+test("Project adopts disk-backed decoded entries with replay parity and source fencing", (t) => { 10+ const storage = new SqlState(); 11+ t.after(() => storage.db.close()); 12+ const log = new MemoryStore(); 13+ const oracle = new Project(log); 14+ oracle.init({ "a.txt": "old\n" }, 0); 15+ oracle.record("alice", { "a.txt": "new\n" }, 1); 16+ oracle.publish("alice", "edit", 2); 17+ const source = { generation: 1, logLength: log.entries.length, sharedVersion: oracle.version }; 18+ const frames = log.entries.map((entry, seq) => { 19+ const json = JSON.stringify(entry); 20+ const namespace = `decoded:${seq}`; 25+ for (let i = 0; i < json.length; i += 11) yield json.slice(i, i + 11); 28+ return { seq, bytes: Buffer.byteLength(json), entry: storedJsonView(new StoredJson(storage, namespace)) as Entry }; 30+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 34+ Project.adoptWriterPage(storage, { 40+ currentSource: () => (++checks === 1 ? source : { ...source, generation: 2 }), 42+ /source changed during/, 44+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 45+ t.mock.method(Project, "load", () => { 46+ throw Error("full history load forbidden"); 49+ Project.adoptWriterPage(storage, { 55+ currentSource: () => source, 59+ const reopened = Project.openWriter(log, storage, log.entries.length); 60+ assert.deepEqual(reopened.files(), oracle.files()); 61+ assert.deepEqual(reopened.status(), oracle.status()); --- /dev/null
+++ b/server/test/decoded-frames.test.ts
@@ -0,0 +1,36 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { withDecodedFrames } from "../src/decoded-frames.ts"; 4+import { logParts, SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteWriterState, writerFrameDigest } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("decoded frame pages retain views through consumption and remove scratch on all exits", (t) => { 9+ const storage = memoryStorage(); 10+ t.after(() => storage.db.close()); 11+ const log = new SqliteLog(storage); 12+ const json = JSON.stringify({ type: "join", agent: "alice", version: 0 }); 13+ for (const [part, text] of logParts(json).entries()) 14+ storage.sql.exec("INSERT INTO log(seq,part,text) VALUES(?,?,?)", 0, part, text); 15+ SqliteWriterState.initialize(storage); 16+ const before = storage.db.prepare("SELECT * FROM writer_state").all(); 17+ const input = { from: 0, to: 1, maxEntries: 1, maxBytes: 1000, digest: "" }; 18+ const result = withDecodedFrames(storage, "decoded-page", log, input, (frames) => { 19+ const frame = [...frames][0]!; 20+ assert.ok("entry" in frame); 21+ assert.equal(frame.entry.type, "join"); 22+ return frame.entry.type; 24+ assert.equal(result.result, "join"); 25+ assert.equal(result.digest, writerFrameDigest("", 0, json)); 26+ assert.deepEqual(storage.db.prepare("SELECT * FROM writer_state").all(), before); 29+ withDecodedFrames(storage, "decoded-page", log, input, (frames) => { 31+ throw Error("consumer failure"); 35+ assert.deepEqual(storage.db.prepare("SELECT * FROM writer_state").all(), before); --- a/server/test/disk-first-runtime.test.ts
+++ b/server/test/disk-first-runtime.test.ts
@@ -4,11 +4,96 @@
44import { join } from "node:path"; 55import { test } from "node:test"; 66import { answer } from "../../worker/project/http.ts"; 7−import { Project } from "../../worker/project/project.ts";
7+import { MemoryStore, Project } from "../../worker/project/project.ts"; 8+import { where } from "../../worker/project/where.ts"; 89import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 9−import { SqliteLog } from "../src/engine-project.ts";
10+import { type EngineProject, SqliteLog } from "../src/engine-project.ts"; 11+import { SqliteProjectionStore } from "../src/projection-store.ts"; 12+import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 1013import { memoryStorage } from "./helpers.ts"; 15+test("runtime defers a large later frame and adopts it on its own page", (t) => { 16+ const storage = memoryStorage(); 17+ t.after(() => storage.db.close()); 18+ const memory = new MemoryStore(); 19+ const project = new Project(memory); 20+ project.init({ "a.txt": "small\n" }, 0); 21+ project.record("alice", { "a.txt": `${"x".repeat(1_100_000)}\n` }, 1); 22+ project.publish("alice", "Large entry", 2); 23+ const log = new SqliteLog(storage); 24+ log.append(memory.entries); 25+ const large = memory.entries.findIndex((entry) => Buffer.byteLength(JSON.stringify(entry)) > 1_048_576); 26+ assert.ok(large > 0); 27+ const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 28+ t.mock.method(Project, "load", () => { 29+ throw Error("full-history replay forbidden"); 31+ const runtime = () => new DiskFirstRuntime(storage, "large-later", "large-later"); 32+ const first = runtime().preparePage(() => {}); 33+ assert.equal(first.phase, "writer"); 34+ assert.equal(first.next, large); 36+ while (!runtime().preparePage(() => {}).ready) assert.ok(++pages < 100); 39+ (calls) => calls.statusAt(log.seq()).version, 46+ (calls) => calls.shared().files["a.txt"]?.length, 51+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before); 54+test("historical runtime preserves named draft bases and intermediate states after landing", (t) => { 55+ const storage = memoryStorage(); 56+ t.after(() => storage.db.close()); 57+ const memory = new MemoryStore(); 58+ const project = new Project(memory); 59+ project.init({ "a.txt": "one\ntwo\n", "b.txt": "other\n" }, 0); 60+ project.switchTo("alice", "rewrite", 1); 61+ project.record("alice", { "a.txt": "ONE\ntwo\n" }, 2); 62+ project.publish("alice", "First draft version", 3); 63+ project.switchTo("bob", "rewrite", 4); 64+ project.record("bob", { "b.txt": "OTHER\n" }, 5); 65+ project.publish("bob", "Second draft version", 6); 66+ assert.equal(project.land("bob", "Land rewrite", 7).ok, true); 67+ const expected = memory.entries.map((_, i) => { 68+ const prefix = Project.load(memory.entries.slice(0, i + 1), new MemoryStore()); 69+ return { status: prefix.status(), where: where(prefix) }; 71+ new SqliteLog(storage).append(memory.entries); 72+ t.mock.method(Project, "load", () => { 73+ throw Error("full-history replay forbidden"); 75+ const runtime = () => new DiskFirstRuntime(storage, "named-history", "named-history"); 76+ while (!runtime().preparePage(() => {}).ready) {} 77+ for (let at = 1; at <= expected.length; at++) { 80+ (calls) => calls.statusAt(at), 83+ { at, ...expected[at - 1]!.status }, 88+ (calls) => calls.whereAt(at), 91+ { at, ...expected[at - 1]!.where }, 1297test("runtime resumes from disk and detaches reads, with exact authorized retries", (t) => { 1398 const directory = mkdtempSync(join(tmpdir(), "abso-runtime-")); 1499 const filename = join(directory, "state.sqlite"); @@ -42,12 +127,29 @@
42127 storage = memoryStorage(filename); 44129 assert.ok(pages > 0); 130+ const initialLength = new SqliteLog(storage).seq(); 131+ const initialStatus = runtime().read((calls) => calls.statusAt(initialLength), validate); 132+ const initialWhere = runtime().read((calls) => calls.whereAt(initialLength), validate); 133+ // Reproduce the published runtime's ready state before historical indexing existed. 134+ new SqliteWriterState(storage, "disk-v1").remove("runtime", "history-ready"); 136+ "DELETE FROM writer_state WHERE namespace LIKE 'disk-v1:history%'; DROP TABLE writer_history_keys; DROP TABLE writer_history_heads;", 138+ assert.throws(() => runtime().read((calls) => calls.status(), validate), /not complete/); 139+ assert.throws(() => runtime().write(() => undefined, validate), /not complete/); 140+ while (!runtime().preparePage(validate).ready) {} 142+ runtime().read((calls) => calls.statusAt(initialLength), validate), 45145 const req = { id: "record-1", identity: { agent: "alice", operation: "record", files: { "a.txt": "changed\n" } } }; 46146 const operation = (calls: Parameters<Parameters<DiskFirstRuntime["write"]>[0]>[0]) => 47147 answer(calls, "record", "alice", { files: req.identity.files }); 48148 const first = runtime().write(operation, validate, req); 49149 assert.equal(first.status, 200); 50150 const length = new SqliteLog(storage).seq(); 151+ const draftStatus = runtime().read((calls) => calls.statusAt(length), validate); 152+ const draftWhere = runtime().read((calls) => calls.whereAt(length), validate); 51153 storage.db.close(); 52154 storage = memoryStorage(filename); @@ -83,7 +185,32 @@
83185 storage.db.close(); 84186 storage = memoryStorage(filename); 85187 assert.equal(runtime().preparePage(validate).ready, true); 189+ runtime().read((calls) => calls.statusAt(initialLength), validate), 193+ runtime().read((calls) => calls.whereAt(initialLength), validate), 196+ const end = new SqliteLog(storage).seq(); 198+ runtime().read((calls) => calls.statusAt(length), validate), 202+ runtime().read((calls) => calls.whereAt(length), validate), 206+ runtime().read((calls) => calls.statusAt(end).version, validate), 210+ runtime().read((calls) => calls.whereAt(end).version, validate), 87214 runtime().read((calls) => calls.shared().files["a.txt"], validate), @@ -129,4 +256,233 @@
129256 /authority changed/, 131258 assert.deepEqual(rows(), adopted); 259+ const originalWrite = SqliteWriterState.prototype.write; 260+ const failure = t.mock.method( 261+ SqliteWriterState.prototype, 263+ function (this: SqliteWriterState, collection: string, key: string, value: unknown) { 264+ if (collection === "runtime:receipts") throw Error("receipt persistence failed"); 265+ return originalWrite.call(this, collection, key, value); 271+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }), 273+ { id: "receipt-failed", identity: "record" }, 275+ /receipt persistence failed/, 277+ assert.deepEqual(rows(), adopted, "receipt failure must roll back canonical state, history and its cursor"); 278+ failure.mock.restore(); 281+test("runtime recovers after a writer without historical support commits", (t) => { 282+ const storage = memoryStorage(); 283+ t.after(() => storage.db.close()); 284+ const namespace = "old-writer"; 285+ const runtime = () => new DiskFirstRuntime(storage, "recovery", namespace); 286+ runtime().initialize( 287+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 290+ while (!runtime().preparePage(() => {}).ready) {} 291+ const historical = runtime().read( 292+ (calls) => calls.statusAt(1), 295+ const projection = new SqliteProjectionStore( 297+ database: "recovery", 298+ namespace: `${namespace}:views`, 299+ registry: `${namespace}:roots`, 300+ defaultFile: "__abso_projection_default__", 303+ { indexedAtoms: true }, 305+ const oldWriter = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true }); 306+ for (const [op, body] of [ 307+ ["record", { files: { "a.txt": "two\n" } }], 308+ ["publish", { message: "Old writer" }], 311+ oldWriter().runCalls({ 312+ expected: oldWriter().source(), 313+ validateAuthority: () => {}, 314+ checkerReady: false, 315+ commitReceipt: () => {}, 316+ operation: (calls) => answer(calls, op, "alice", body), 321+ t.mock.method(Project, "load", () => { 322+ throw Error("full-history load forbidden"); 325+ for (let page = 0; page < 100 && !ready; page++) ready = runtime().preparePage(() => {}).ready; 326+ assert.equal(ready, true); 329+ (calls) => calls.statusAt(1), 336+ (calls) => calls.shared().files["a.txt"], 343+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "three\n" } }), 350+test("a large retry response must not roll back an otherwise successful write", (t) => { 351+ const storage = memoryStorage(); 352+ t.after(() => storage.db.close()); 353+ const runtime = () => new DiskFirstRuntime(storage, "large-receipt", "large-receipt"); 354+ runtime().initialize( 355+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 358+ while (!runtime().preparePage(() => {}).ready) {} 359+ const large = "x".repeat(8_100_000); 360+ const request = { id: "large-response", identity: { agent: "alice", operation: "large-fixture" } }; 361+ const result = runtime().write( 363+ const recorded = answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }); 364+ assert.equal(recorded.status, 200); 365+ return { status: 200, body: large }; 370+ assert.equal(result.body.length, large.length); 371+ const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 372+ const replay = runtime().write( 374+ throw Error("receipt replay must not execute twice"); 379+ assert.deepEqual(replay, result); 380+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before); 383+test("chunked receipts roll back failures and reject damaged replay", (t) => { 384+ const storage = memoryStorage(); 385+ t.after(() => storage.db.close()); 386+ const runtime = () => new DiskFirstRuntime(storage, "receipt-failure", "receipt-failure"); 387+ runtime().initialize( 388+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 391+ while (!runtime().preparePage(() => {}).ready) {} 392+ const rows = () => ({ 393+ log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), 394+ state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 395+ history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 396+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 398+ const before = rows(); 399+ const original = SqliteWriterState.prototype.write; 400+ const failure = t.mock.method( 401+ SqliteWriterState.prototype, 403+ function (this: SqliteWriterState, collection: string, key: string, value: unknown) { 404+ original.call(this, collection, key, value); 405+ if (collection === "runtime:receipt:chunk-failure" && key === "1") throw Error("injected receipt chunk failure"); 408+ const request = { id: "chunk-failure", identity: { operation: "fixture" } }; 409+ const operation = (calls: EngineProject) => { 410+ assert.equal(answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }).status, 200); 411+ return { body: "x".repeat(140000) }; 413+ assert.throws(() => runtime().write(operation, () => {}, request), /injected receipt chunk failure/); 414+ assert.deepEqual(rows(), before); 415+ failure.mock.restore(); 416+ const result = runtime().write(operation, () => {}, request); 417+ const committed = rows(); 421+ throw Error("must not execute"); 428+ assert.deepEqual(rows(), committed); 429+ const state = new SqliteWriterState(storage, "receipt-failure"); 430+ const chunk = state.read("runtime:receipt:chunk-failure", "1") as string; 431+ state.write("runtime:receipt:chunk-failure", "1", "y" + chunk.slice(1)); 436+ throw Error("must not execute"); 443+ state.remove("runtime:receipt:chunk-failure", "1"); 448+ throw Error("must not execute"); 453+ /incomplete receipt/, 455+ assert.deepEqual(rows().log, committed.log); 458+test("runtime format upgrade is authorized, atomic, and rejects unknown formats", (t) => { 459+ const storage = memoryStorage(); 460+ t.after(() => storage.db.close()); 461+ const runtime = () => new DiskFirstRuntime(storage, "format-test", "format-test"); 462+ runtime().initialize( 463+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 466+ while (!runtime().preparePage(() => {}).ready) {} 467+ const state = new SqliteWriterState(storage, "format-test"); 468+ assert.equal(state.read("runtime", "format"), 5); 469+ state.write("runtime", "format", 3); 470+ const before = storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(); 471+ let validations = 0; 474+ runtime().preparePage(() => { 475+ if (++validations === 2) throw Error("revoked during upgrade"); 480+ storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 483+ assert.equal(runtime().preparePage(() => {}).ready, true); 484+ assert.equal(state.read("runtime", "format"), 5); 485+ state.write("runtime", "format", 999); 486+ assert.throws(() => runtime().preparePage(() => {}), /unsupported disk-first runtime format/); 487+ assert.equal(state.read("runtime", "format"), 999); --- /dev/null
+++ b/server/test/frame-chunks.test.ts
@@ -0,0 +1,35 @@
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { test } from "node:test"; 4+import { logParts, SqliteLog } from "../src/engine-project.ts"; 5+import { writerFrameChunksDigest, writerFrameDigest } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("canonical chunks stream oversized frames and reject missing parts", (t) => { 9+ const storage = memoryStorage(); 10+ t.after(() => storage.db.close()); 11+ const log = new SqliteLog(storage); 12+ const json = JSON.stringify({ value: "x".repeat(8_100_000) }); 13+ for (const [part, text] of logParts(json).entries()) 14+ storage.sql.exec("INSERT INTO log (seq,part,text) VALUES (?, ?, ?)", 0, part, text); 15+ assert.equal(writerFrameChunksDigest("", 0, log.frameChunks(0)), writerFrameDigest("", 0, json)); 16+ storage.sql.exec("DELETE FROM log WHERE seq = 0 AND part = 1"); 17+ assert.throws(() => { 18+ for (const _ of log.frameChunks(0)) { 21+ assert.throws(() => log.frameChunks(1).next(), /missing/); 23+test("chunked writer digests preserve Unicode across every split", () => { 24+ const text = '{"value":"a\u{1f600}b\u{1d11e}c"}'.replace(/\\u\{([0-9a-f]+)\}/g, (_, hex) => 25+ String.fromCodePoint(Number.parseInt(hex, 16)), 27+ const reference = createHash("sha256") 28+ .update("abso-writer-log-v1\n") 29+ .update(JSON.stringify(["prior", 7])) 31+ .update(text, "utf8") 33+ for (let at = 0; at <= text.length; at++) 34+ assert.equal(writerFrameChunksDigest("prior", 7, [text.slice(0, at), "", text.slice(at)]), reference); --- /dev/null
+++ b/server/test/history-host.test.ts
@@ -0,0 +1,180 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteHistoryHost } from "../src/history-host.ts"; 6+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("historical host binds paged snapshots to the verified canonical root", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const memory = new MemoryStore(); 13+ const project = new Project(memory); 14+ project.init({ "a.txt": "one\n" }, 0); 15+ for (let i = 1; i <= 18; i++) { 16+ project.record("alice", { "a.txt": `${i}\n` }, i * 2); 17+ project.publish("alice", `Change ${i}`, i * 2 + 1); 19+ const expected = memory.entries.map((_, index) => 20+ Project.load(memory.entries.slice(0, index + 1), new MemoryStore()).status(), 22+ const log = new SqliteLog(storage); 23+ log.append(memory.entries); 24+ SqliteWriterState.initialize(storage); 25+ const writer = new SqliteWriterHost(storage, "writer"); 28+ const page = writer.adoptPage(from, { maxEntries: 32, maxBytes: 1_048_576 }, () => {}); 30+ if (page.ready) break; 32+ const root = writer.root(); 33+ t.mock.method(Project, "load", () => { 34+ throw Error("full-history replay forbidden"); 36+ const history = () => new SqliteHistoryHost(storage, "history"); 59+ assert.ok(pages > 0); 60+ let authorized = true; 67+ if (!authorized) throw Error("authority expired during read"); 71+ const result = p.status(); 76+ /authority expired during read/, 78+ let observedRoot = root; 87+ const result = p.status(); 88+ observedRoot = { ...root, generation: root.generation + 1 }; 94+ for (let at = 1; at <= root.logLength; at++) { 110+ () => ({ ...root, generation: root.generation + 1 }), 123+ throw Error("revoked"); 130+ const rows = () => ({ 131+ values: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 132+ history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 133+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 135+ const before = rows(); 136+ project.record("alice", { "a.txt": "tail\n" }, 100); 137+ project.publish("alice", "Tail", 101); 138+ log.append(memory.entries.slice(root.logLength)); 139+ const committed = advanceWriterRoot(log, root, writer.source()); 140+ const wrong = { ...committed, digest: "0".repeat(64) }; 150+ /tail digest mismatch/, 152+ assert.deepEqual(rows(), before); 165+ committed.logLength, --- /dev/null
+++ b/server/test/history-recovery.test.ts
@@ -0,0 +1,189 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteHistoryHost } from "../src/history-host.ts"; 6+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("historical preparation recovers after a writer without history appends", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const memory = new MemoryStore(); 13+ const project = new Project(memory); 14+ project.init({ "a.txt": "one\n" }, 0); 15+ for (let i = 1; i <= 20; i++) { 16+ project.record("alice", { "a.txt": `before ${i}\n` }, i * 2); 17+ project.publish("alice", `Before ${i}`, i * 2 + 1); 19+ const log = new SqliteLog(storage); 20+ log.append(memory.entries); 21+ SqliteWriterState.initialize(storage); 22+ const writer = new SqliteWriterHost(storage, "writer"); 25+ const page = writer.adoptPage(from, { maxEntries: 32, maxBytes: 1048576 }, () => {}); 27+ if (page.ready) break; 29+ const previous = writer.root(); 30+ const history = () => new SqliteHistoryHost(storage, "history"); 39+ const oldStatus = project.status(); 40+ project.record("alice", { "a.txt": "two\n" }, 1); 41+ project.publish("alice", "Second", 2); 42+ log.append(memory.entries.slice(previous.logLength)); 43+ const current = advanceWriterRoot(log, previous, writer.source()); 44+ // The previous runtime commits canonical history but does not advance historical indexes. 55+ for (let page = 0; page < 20 && !ready; page++) { 56+ ready = history().prepare( 63+ assert.equal(ready, true); 86+for (const shortened of [false, true]) { 87+ test(`historical recovery rebuilds ${shortened ? "shortened" : "replaced"} canonical history`, (t) => { 88+ const storage = memoryStorage(); 89+ t.after(() => storage.db.close()); 90+ const memory = new MemoryStore(); 91+ const project = new Project(memory); 92+ project.init({ "old.txt": "old\n" }, 0); 93+ project.record("alice", { "old.txt": "changed\n" }, 1); 94+ project.publish("alice", "Old", 2); 95+ const log = new SqliteLog(storage); 96+ log.append(memory.entries); 97+ SqliteWriterState.initialize(storage); 98+ const empty = { format: 1 as const, generation: 0, logLength: 0, sharedVersion: 0, digest: "" }; 99+ const oldRoot = advanceWriterRoot(log, empty, { 100+ generation: log.generation(), 101+ logLength: log.seq(), 102+ sharedVersion: project.version, 104+ const history = () => new SqliteHistoryHost(storage, "history"); 113+ const replacement = new MemoryStore(); 114+ const current = new Project(replacement); 115+ current.init({ "new.txt": "new\n" }, 0); 117+ current.record("bob", { "new.txt": "different\n" }, 1); 118+ current.publish("bob", "New", 2); 121+ log.append(replacement.entries); 122+ const root = advanceWriterRoot(log, empty, { 123+ generation: log.generation(), 124+ logLength: log.seq(), 125+ sharedVersion: current.version, 127+ const canonical = JSON.stringify(log.since(0, 100)); 148+ const rows = () => ({ 149+ state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 150+ keys: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 151+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 153+ const beforeCleanup = rows(); 154+ let validations = 0; 162+ if (++validations === 2) throw Error("authority revoked during cleanup"); 165+ /authority revoked/, 167+ assert.deepEqual(rows(), beforeCleanup); 169+ for (let page = 0; page < 100 && !ready; page++) 170+ ready = history().prepare( 176+ assert.equal(ready, true); 187+ assert.equal(JSON.stringify(log.since(0, 100)), canonical); --- /dev/null
+++ b/server/test/history-state.test.ts
@@ -0,0 +1,254 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { where } from "../../worker/project/where.ts"; 5+import { EngineProject } from "../src/engine-project.ts"; 6+import { SqliteHistoryState } from "../src/history-state.ts"; 7+import { SqliteWriterState } from "../src/writer-host.ts"; 8+import { memoryStorage } from "./helpers.ts"; 10+test("bounded adoption checkpoints reopen every historical Project prefix without replay", (t) => { 11+ const storage = memoryStorage(); 12+ t.after(() => storage.db.close()); 13+ SqliteHistoryState.initialize(storage); 14+ const log = new MemoryStore(); 15+ const project = new Project(log); 16+ project.init({ "a.txt": "one\ntwo\n" }, 0); 17+ project.record("alice", { "a.txt": "ONE\ntwo\n" }, 1); 18+ project.publish("alice", "First", 2); 19+ project.move("alice", "a.txt", "b.txt", 3); 20+ project.publish("alice", "Move", 4); 21+ const expected = log.entries.map((_, i) => { 22+ const prefix = Project.load(log.entries.slice(0, i + 1), new MemoryStore()); 23+ return { status: prefix.status(), where: where(prefix) }; 25+ t.mock.method(Project, "load", () => { 26+ throw Error("full-history replay forbidden"); 28+ const source = { generation: 1, logLength: log.entries.length, sharedVersion: project.version }; 30+ while (from < log.entries.length) { 31+ const state = new SqliteHistoryState(storage, "project-history", from); 32+ const frames = log.entries 33+ .slice(from, from + 2) 34+ .map((entry, i) => ({ seq: from + i, json: JSON.stringify(entry) })); 35+ const page = Project.adoptWriterPage(state, { 41+ currentSource: () => source, 42+ beginRevision: (revision) => state.beginRevision(revision), 46+ const state = new SqliteHistoryState(storage, "project-history", from); 49+ const calls = new EngineProject(project, undefined, undefined, (at, operation) => { 50+ const validate = () => { 51+ if (!active) throw Error("historical scope expired"); 56+ ? new Project(new MemoryStore()) 57+ : Project.openHistorical(state.at(at, validate), at, new SqliteWriterState(storage, "history-scratch")), 60+ assert.deepEqual(calls.statusAt(0), { at: 0, version: -1, agents: [] }); 61+ assert.deepEqual(calls.whereAt(0), { at: 0, version: -1, files: {} }); 62+ for (let at = 1; at <= from; at++) { 63+ const historical = Project.openHistorical(state.at(at), at, new SqliteWriterState(storage, "history-scratch")); 64+ assert.deepEqual(historical.status(), expected[at - 1]!.status, `status at ${at}`); 65+ assert.deepEqual(where(historical), expected[at - 1]!.where, `where at ${at}`); 66+ assert.deepEqual(calls.statusAt(at), { at, ...expected[at - 1]!.status }); 67+ assert.deepEqual(calls.whereAt(at), { at, ...expected[at - 1]!.where }); 69+ assert.deepEqual(calls.statusAt(from + 10), { at: from, ...expected[from - 1]!.status }); 71+ assert.throws(() => calls.statusAt(1), /scope expired/); 72+ assert.throws(() => calls.whereAt(1), /scope expired/); 74+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'history-scratch'").get()!.n, 79+test("historical state preserves old values, deletions and undefined across reopen", (t) => { 80+ const storage = memoryStorage(); 81+ t.after(() => storage.db.close()); 82+ SqliteHistoryState.initialize(storage); 83+ let state = new SqliteHistoryState(storage, "history"); 84+ state.beginRevision(1); 85+ state.write("values", "", "empty key"); 86+ for (let i = 0; i < 150; i++) state.write("values", `key-${i.toString().padStart(3, "0")}`, { value: i }); 87+ state.write("values", "undefined", undefined); 88+ state.beginRevision(2); 89+ state.write("values", "key-000", { value: "changed" }); 90+ state.remove("values", "key-001"); 91+ state.remove("values", "undefined"); 93+ state = new SqliteHistoryState(storage, "history", 2); 94+ assert.deepEqual(state.at(1).read("values", "key-000"), { value: 0 }); 95+ assert.deepEqual(state.at(2).read("values", "key-000"), { value: "changed" }); 96+ const old = new Map(state.at(1).entries("values")); 97+ const current = new Map(state.at(2).entries("values")); 98+ assert.equal(old.size, 152); 99+ assert.equal(current.size, 150); 100+ assert.equal(old.has("undefined"), true); 101+ assert.equal(current.has("undefined"), false); 102+ assert.equal(current.has("key-001"), false); 103+ assert.equal(current.get(""), "empty key"); 104+ assert.throws(() => state.at(3), /outside authority/); 105+ assert.throws(() => state.at(1).write("values", "bad", 1), /read-only/); 106+ assert.throws(() => state.write("values", "bad", 1), /sealed/); 107+ const reopened = new SqliteHistoryState(storage, "history", 2); 108+ assert.throws(() => reopened.write("values", "key-000", "overwrite"), /sealed/); 109+ reopened.beginRevision(3); 110+ reopened.write("values", "key-000", "new revision"); 112+ assert.deepEqual(reopened.at(2).read("values", "key-000"), { value: "changed" }); 115+test("new canonical tails extend historical snapshots atomically without replaying old entries", (t) => { 116+ const storage = memoryStorage(); 117+ t.after(() => storage.db.close()); 118+ SqliteHistoryState.initialize(storage); 119+ const log = new MemoryStore(); 120+ const live = new Project(log); 121+ live.init({ "a.txt": "one\ntwo\n" }, 0); 122+ const initialLength = log.entries.length; 123+ const initial = live.status(); 124+ const state = new SqliteHistoryState(storage, "tail"); 125+ const source = { generation: 1, logLength: initialLength, sharedVersion: live.version }; 126+ Project.adoptWriterPage(state, { 131+ frames: log.entries.map((entry, seq) => ({ seq, json: JSON.stringify(entry) })), 132+ currentSource: () => source, 133+ beginRevision: (revision) => state.beginRevision(revision), 136+ live.record("alice", { "a.txt": "ONE\ntwo\n" }, 1); 137+ live.publish("alice", "First", 2); 138+ const expected = log.entries.map((_, i) => { 139+ const p = Project.load(log.entries.slice(0, i + 1), new MemoryStore()); 140+ return { status: p.status(), where: where(p) }; 142+ t.mock.method(Project, "load", () => { 143+ throw Error("full-history replay forbidden"); 145+ const rows = () => ({ 146+ values: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 147+ history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 148+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 150+ const before = rows(); 151+ const frames = log.entries 152+ .slice(initialLength) 153+ .map((entry, i) => ({ seq: initialLength + i, json: JSON.stringify(entry) })); 154+ let validations = 0; 157+ Project.extendHistoricalPage(state, { 158+ from: initialLength, 162+ beginRevision: (revision) => state.beginRevision(revision), 163+ validateAuthority: () => { 164+ if (++validations === 2) throw Error("canonical tail changed"); 167+ /canonical tail changed/, 169+ assert.deepEqual(rows(), before); 170+ let from = initialLength; 171+ while (from < log.entries.length) { 172+ const reopened = new SqliteHistoryState(storage, "tail", from); 173+ const page = Project.extendHistoricalPage(reopened, { 175+ frames: frames.filter((frame) => frame.seq >= from).slice(0, 2), 178+ beginRevision: (revision) => reopened.beginRevision(revision), 179+ validateAuthority: () => {}, 184+ const reopened = new SqliteHistoryState(storage, "tail", from); 185+ const scratch = new SqliteWriterState(storage, "tail-scratch"); 186+ assert.deepEqual(Project.openHistorical(reopened.at(initialLength), initialLength, scratch).status(), initial); 187+ for (let at = initialLength + 1; at <= from; at++) { 188+ const historical = Project.openHistorical(reopened.at(at), at, scratch); 189+ assert.deepEqual(historical.status(), expected[at - 1]!.status); 190+ assert.deepEqual(where(historical), expected[at - 1]!.where); 194+test("current state and its history roll back together", (t) => { 195+ const storage = memoryStorage(); 196+ t.after(() => storage.db.close()); 197+ SqliteHistoryState.initialize(storage); 198+ const state = new SqliteHistoryState(storage, "rollback"); 199+ state.beginRevision(1); 200+ state.write("values", "a", { before: true }); 202+ const rows = () => ({ 203+ values: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 204+ history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 205+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 207+ const before = rows(); 210+ state.transaction(() => { 211+ state.beginRevision(2); 212+ state.write("values", "a", { after: true }); 213+ state.remove("values", "a"); 215+ throw Error("injected failure"); 219+ assert.deepEqual(rows(), before); 220+ assert.throws(() => state.at(2), /outside authority/); 221+ assert.deepEqual(state.read("values", "a"), { before: true }); 224+test("historical readers recheck canonical authority after creation and between yielded keys", (t) => { 225+ const storage = memoryStorage(); 226+ t.after(() => storage.db.close()); 227+ SqliteHistoryState.initialize(storage); 228+ const state = new SqliteHistoryState(storage, "authority"); 229+ state.beginRevision(1); 230+ state.write("values", "a", 1); 231+ state.write("values", "b", 2); 234+ const guard = () => { 235+ if (!valid) throw Error("canonical authority expired"); 237+ const historical = state.at(1, guard); 238+ const iterator = historical.entries("values")[Symbol.iterator](); 239+ assert.deepEqual(iterator.next().value, ["a", 1]); 241+ assert.throws(() => iterator.next(), /authority expired/); 242+ assert.throws(() => historical.read("values", "a"), /authority expired/); 243+ assert.throws(() => historical.entries("values")[Symbol.iterator]().next(), /authority expired/); 247+ historical.transaction(() => { 250+ /authority expired/, 252+ assert.equal(called, false); 253+ assert.throws(() => state.at(1, guard), /authority expired/); --- /dev/null
+++ b/server/test/json-chunk-cursor.test.ts
@@ -0,0 +1,43 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { JsonChunkCursor } from "../src/json-chunk-cursor.ts"; 5+test("JSON strings decode exactly across every input boundary", () => { 6+ const values = ["", "plain", 'quotes" and slash\\', "\n\r\t\b\f", "\uD83D\uDE00", "\uD800", "\uDC00"]; 7+ const encoded = values.map((value) => JSON.stringify(value)); 8+ encoded.push('"\\uD83D\\uDE00\\u0000\\/"'); 9+ for (const json of encoded) 10+ for (let split = 0; split <= json.length; split++) { 11+ const cursor = new JsonChunkCursor([json.slice(0, split), "", json.slice(split), ","]); 12+ assert.equal([...cursor.stringChunks()].join(""), JSON.parse(json)); 13+ assert.equal(cursor.take(), ","); 14+ assert.equal(cursor.peek(), undefined); 16+ for (const invalid of ['"unterminated', '"\\x"', '"\\u12xz"', '"\\u123', '"raw\ncontrol"']) { 17+ const cursor = new JsonChunkCursor(invalid.split("")); 18+ assert.throws(() => [...cursor.stringChunks()], /JSON/); 22+test("long JSON strings decode in fixed-size output chunks", () => { 24+ const cursor = new JsonChunkCursor( 28+ for (let i = 0; i < 500; i++) yield "x".repeat(16384); 36+ for (const chunk of cursor.stringChunks()) { 37+ assert.ok(chunk.length <= 16384); 38+ count += chunk.length; 40+ assert.equal(count, 8192000); 42+ assert.equal(closed, true); --- /dev/null
+++ b/server/test/json-events.test.ts
@@ -0,0 +1,148 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { jsonEvents } from "../src/json-events.ts"; 5+test("structural JSON decoding is invariant at every chunk boundary", () => { 7+ '{"type":"init","atom":{"lines":["a\\n","\\uD83D\\uDE00"],"seq":0}}', 8+ "[true,false,null,-0,1.2e-3,{},[]]", 11+ for (const document of documents) { 12+ const expected = [...jsonEvents([document])]; 13+ for (let split = 0; split <= document.length; split++) 14+ assert.deepEqual([...jsonEvents([document.slice(0, split), document.slice(split)])], expected); 16+ for (const invalid of [ 29+ assert.throws(() => [...jsonEvents([invalid])], /JSON/); 30+ assert.throws(() => [...jsonEvents(["[".repeat(130) + "0" + "]".repeat(130)])], /nesting/); 33+test("structural JSON decoding streams large arrays and closes early input", () => { 35+ const source = function* () { 38+ for (let i = 0; i < 100000; i++) yield `${i ? "," : ""}${i}`; 45+ for (const event of jsonEvents(source())) 46+ if (event.kind === "value") { 47+ assert.equal(event.value, count); 50+ assert.equal(count, 100000); 51+ assert.equal(closed, true); 53+ for (const event of jsonEvents(source())) { 54+ assert.equal(event.kind, "array"); 57+ assert.equal(closed, true); 60+function materialize(document: string): unknown { 61+ const events = jsonEvents(document.split("")); 63+ const event = events.next(); 64+ if (event.done) throw Error("missing event"); 67+ const value = (event = next()): unknown => { 68+ if (event.kind === "value") return event.value; 69+ if (event.kind === "string") { 72+ const fragment = next(); 73+ if (fragment.kind === "string-end") return text; 74+ if (fragment.kind !== "text") throw Error("bad string event"); 75+ text += fragment.value; 78+ if (event.kind === "array") { 79+ const result: unknown[] = []; 81+ const child = next(); 82+ if (child.kind === "end") return result; 83+ result.push(value(child)); 86+ if (event.kind === "object") { 87+ const result: Record<string, unknown> = {}; 90+ if (key.kind === "end") return result; 91+ if (key.kind !== "key") throw Error("bad key event"); 92+ Object.defineProperty(result, key.value, { 100+ throw Error("unexpected event"); 102+ const result = value(); 103+ assert.equal(events.next().done, true); 107+test("streamed JSON agrees with JSON.parse on generated and adversarial documents", () => { 109+ const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0); 110+ const generate = (depth: number): unknown => { 111+ const choice = random() % (depth ? 6 : 4); 112+ if (choice === 0) return null; 113+ if (choice === 1) return random() % 2 === 0; 114+ if (choice === 2) return (random() - 0x80000000) / 17; 115+ if (choice === 3) return `quotes"\\\n${String.fromCharCode(random() % 65536)}\uD83D\uDE00`; 116+ if (choice === 4) return Array.from({ length: random() % 5 }, () => generate(depth - 1)); 117+ return Object.fromEntries(Array.from({ length: random() % 5 }, (_, i) => [`key${i}`, generate(depth - 1)])); 119+ for (let i = 0; i < 200; i++) { 120+ const document = JSON.stringify(generate(4)); 121+ assert.deepEqual(materialize(document), JSON.parse(document)); 123+ for (const document of [ 124+ '{"__proto__":{"polluted":true},"constructor":0,"a":1,"a":2}', 125+ "[-0,1e999,-1e999,1e-999]", 126+ '{"\\u0061":"\\uD800\\uDC00"}', 128+ assert.deepEqual(materialize(document), JSON.parse(document)); 131+import { MemoryStore, Project } from "../../worker/project/project.ts"; 133+test("streamed JSON preserves real canonical project entries", () => { 134+ const memory = new MemoryStore(); 135+ const project = new Project(memory); 136+ project.init({ "a.txt": "one\ntwo\n" }, 0); 137+ project.record("alice", { "a.txt": "ONE\ntwo\n" }, 1); 138+ project.publish("alice", "Publish", 2); 139+ project.switchTo("alice", "draft", 3); 140+ project.record("alice", { "a.txt": "ONE\nTWO\n" }, 4); 141+ project.publish("alice", "Draft publish", 5); 142+ project.land("alice", "Land", 6); 143+ for (const entry of memory.entries) { 144+ const document = JSON.stringify(entry); 145+ assert.deepEqual(materialize(document), JSON.parse(document)); 147+ assert.ok(memory.entries.length > 5); --- /dev/null
+++ b/server/test/long-text-history.test.ts
@@ -0,0 +1,61 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { Graph } from "../../src/engine/graph.ts"; 4+import { answer } from "../../worker/project/http.ts"; 5+import { Project } from "../../worker/project/project.ts"; 6+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 7+import { SqliteLog } from "../src/engine-project.ts"; 8+import { SqliteHistoryState } from "../src/history-state.ts"; 9+import { memoryStorage } from "./helpers.ts"; 11+test("long text remains exact in current and historical storage after later writes", (t) => { 12+ const storage = memoryStorage(); 13+ t.after(() => storage.db.close()); 14+ const runtime = () => new DiskFirstRuntime(storage, "long-history", "long-history"); 15+ const old = `${"old".repeat(20000)}\uD83D\uDE00\n`; 16+ const current = `${"new".repeat(20000)}\uD834\uDD1E\n`; 17+ runtime().initialize( 18+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": old } }), 21+ while (!runtime().preparePage(() => {}).ready) {} 22+ const before = runtime().read( 23+ (calls) => calls.fileAt("a.txt", 0, null), 28+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": current } }), 35+ (calls) => answer(calls, "publish", "alice", { message: "Replace long line" }), 40+ t.mock.method(Project, "load", () => { 41+ throw Error("full history replay forbidden"); 45+ (calls) => calls.fileAt("a.txt", 0, null), 52+ (calls) => calls.shared().files["a.txt"], 57+ const history = new SqliteHistoryState(storage, "long-history:history", new SqliteLog(storage).seq()); 58+ const graph = new Graph({ storage: history.at(1, () => {}) }); 59+ assert.equal(graph.lineText("a0.0"), old.slice(0, -1)); 60+ assert.equal(graph.atom("a0").inserts[0]!.lines[0], old.slice(0, -1)); --- a/server/test/project-object-disk-first.test.ts
+++ b/server/test/project-object-disk-first.test.ts
@@ -1,8 +1,10 @@
11import assert from "node:assert/strict"; 22import { registerHooks } from "node:module"; 33import { test } from "node:test"; 4+import git from "isomorphic-git"; 45import { Project } from "../../worker/project/project.ts"; 56import { EngineProject } from "../src/engine-project.ts"; 7+import { MemoryFS } from "../src/memory-fs.ts"; 68import { memoryStorage } from "./helpers.ts"; 810const hooks = registerHooks({ @@ -45,6 +47,8 @@
4547 const values = new Map<string, unknown>(); 4648 let alarm: number | null = null; 4749 let onReaders: (() => Promise<void>) | undefined; 50+ let failGitAcknowledgement = false; 51+ let failNamePersistence = false; 4953 id: { toString: () => "project-1" }, @@ -58,6 +62,14 @@
5862 return values.get(key); 6064 put: async (key: string | Record<string, unknown>, value?: unknown) => { 65+ if (key === "name" && failNamePersistence) { 66+ failNamePersistence = false; 67+ throw Error("injected name persistence failure"); 69+ if (failGitAcknowledgement && typeof key === "object" && "git:head" in key) { 70+ failGitAcknowledgement = false; 71+ throw Error("injected Git cursor persistence failure"); 6173 if (typeof key === "string") values.set(key, value); 6274 else for (const [name, v] of Object.entries(key)) values.set(name, v); @@ -76,9 +88,9 @@
7688 t.mock.method(Project, "load", () => { 7789 throw Error("full history replay forbidden"); 79− const call = async (op: string, agent: string | undefined, body: unknown) => {
91+ const call = async (op: string, agent: string | undefined, body: unknown, requestId?: string) => { 8092 for (let page = 0; page < 100; page++) { 81− const result = await object().call("project", op, agent, body);
93+ const result = await object().call("project", op, agent, body, false, undefined, undefined, requestId); 8294 if (result.status !== 503) { 8395 assert.notEqual(result.status, 500, JSON.stringify({ op, result })); @@ -88,12 +100,114 @@
89101 throw Error("adoption did not finish"); 91− assert.equal((await call("init", undefined, { files: { "a.txt": "one\ntwo\n" } })).status, 200);
103+ const initId = "00000000-0000-4000-8000-000000000008"; 104+ const initBody = { files: { "a.txt": "one\ntwo\n" } }; 105+ failNamePersistence = true; 106+ await assert.rejects( 107+ () => object().call("project", "init", undefined, initBody, false, undefined, undefined, initId), 108+ /name persistence failure/, 110+ const initializedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 111+ assert.equal((await call("init", undefined, initBody, initId)).status, 200); 112+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), initializedLog); 92113 assert.equal((await call("sync", "alice", {})).status, 200); 93− assert.equal((await call("record", "alice", { files: { "a.txt": "changed\n" } })).status, 200);
114+ const requestId = "00000000-0000-4000-8000-000000000007"; 115+ const recordBody = { files: { "a.txt": "changed\n" } }; 116+ failNamePersistence = true; 117+ await assert.rejects( 118+ () => object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId), 119+ /name persistence failure/, 121+ const recordedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 123+ (await object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId)).status, 126+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), recordedLog); 129+ await object().call( 133+ { files: { "a.txt": "different\n" } }, 94142 const published = await call("publish", "alice", { message: "Disk first" }); 95143 assert.equal(published.status, 200); 96144 assert.equal((published.body as { ok: boolean }).ok, true); 145+ const issued = await object().issueAgentKey("alice", "test-address", null, "writer"); 146+ assert.ok("key" in issued); 147+ const keyCall = { presented: issued.key, address: "test-address", write: true, route: "record" }; 148+ const crossPrincipal = await object().call( 158+ assert.equal(crossPrincipal.status, 200, "each checked principal owns its own request ID namespace"); 159+ const principalReceipts = storage.db 160+ .prepare("SELECT DISTINCT key FROM writer_state WHERE collection = 'runtime:receipts' AND key LIKE ?") 161+ .all(`http:%:${requestId}`); 162+ assert.equal(principalReceipts.length, 2); 163+ const beforeSharedReplay = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 164+ assert.equal((await call("record", "alice", recordBody, requestId)).status, 200); 165+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeSharedReplay); 166+ const keyRequestId = "00000000-0000-4000-8000-000000000010"; 168+ (await object().call("project", "record", "alice", recordBody, false, undefined, keyCall, keyRequestId)).status, 171+ await object().revokeAgentKey(issued.id, "test-address"); 172+ const beforeRevokedRetry = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 173+ const revokedRetry = await object().call( 183+ assert.equal(revokedRetry.status, 403); 184+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeRevokedRetry); 185+ const readerId = "00000000-0000-4000-8000-000000000009"; 186+ failNamePersistence = true; 187+ await assert.rejects( 188+ () => object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId), 189+ /name persistence failure/, 191+ const nowRefused = await object().call( 202+ (nowRefused.body as { ok: boolean }).ok, 204+ "current reader authority overrides an earlier successful receipt", 207+ (await object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId)).status, 210+ assert.equal((await call("reader", "alice", { reader: false })).status, 200); 97211 const file = await call("file", undefined, { path: "a.txt", version: "1" }); 98212 assert.equal(file.status, 200); 99213 assert.match(JSON.stringify(file.body), /changed/); @@ -165,4 +279,171 @@
165279 /injected after record/, 167281 assert.deepEqual(rows(), stable); 282+ // Exercise the real alarm and commit builder; only remote transport is mocked. 283+ t.mock.method(git, "listServerRefs", async () => []); 284+ t.mock.method(git, "clone", async () => { 285+ throw Error("empty test repository"); 288+ let remoteFiles: MemoryFS | undefined; 289+ t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => { 290+ const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" }); 291+ const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid }); 292+ assert.match(commit.commit.message, /abso-version: 2/); 293+ const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" }); 294+ assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n"); 296+ remoteFiles = options.fs as MemoryFS; 297+ return { ok: true }; 301+ info: async () => ({ remote: "https://artifacts.invalid/test" }), 302+ createToken: async () => ({ plaintext: "invented-test-token" }), 303+ [Symbol.dispose]() {}, 306+ const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never); 307+ await bound().alarm(); 308+ assert.equal(pushed, 1); 309+ assert.equal((await bound().out()).pushed?.version, 2); 310+ assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state"); 311+ await bound().alarm(); 312+ assert.equal(pushed, 1, "a cold alarm does not push the same version again"); 313+ assert.ok(remoteFiles); 314+ const remote = remoteFiles; 315+ const parent = await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }); 316+ const blob = await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode("From Git\n") }); 317+ const tree = await git.writeTree({ 320+ tree: [{ mode: "100644", path: "a.txt", oid: blob, type: "blob" }], 322+ const incoming = await git.commit({ 327+ message: "Plain Git edit", 328+ author: { name: "Git writer", email: "test@example.invalid" }, 330+ await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true }); 331+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]); 332+ t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 333+ (options.fs as MemoryFS).entries = structuredClone(remote.entries); 335+ const beforeIntake = rows(); 336+ const originalIngest = EngineProject.prototype.ingest; 337+ const failedIngest = t.mock.method( 338+ EngineProject.prototype, 340+ function (this: EngineProject, ...args: Parameters<EngineProject["ingest"]>) { 341+ originalIngest.apply(this, args); 342+ throw Error("injected after Git intake"); 345+ await assert.rejects(() => bound().gitSync(), /injected after Git intake/); 346+ assert.deepEqual(rows(), beforeIntake); 347+ assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head"); 348+ failedIngest.mock.restore(); 349+ failGitAcknowledgement = true; 350+ await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/); 351+ const committedIntake = rows(); 352+ assert.equal((await bound().out()).version, 3); 353+ assert.equal((await bound().out()).git.head, parent); 354+ const intake = await bound().gitSync(); 355+ assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt"); 357+ assert.equal(intake?.head, incoming); 358+ assert.equal(intake?.commits, 1); 359+ assert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake)); 360+ const imported = await call("file", undefined, { path: "a.txt", version: "3" }); 361+ assert.equal(imported.status, 200); 362+ assert.match(JSON.stringify(imported.body), /From Git/); 363+ const afterIntake = rows(); 364+ assert.equal(await bound().gitSync(), null); 365+ assert.deepEqual(rows(), afterIntake, "cold intake does not apply the same commit twice"); 368+for (const disk of [false, true]) { 369+ test(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => { 370+ const storage = memoryStorage(); 371+ t.after(() => storage.db.close()); 372+ const values = new Map<string, unknown>(); 374+ id: { toString: () => "refusal" }, 377+ get: async (key: string) => values.get(key), 378+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 379+ if (typeof key === "string") values.set(key, value); 380+ else for (const [k, v] of Object.entries(key)) values.set(k, v); 382+ getAlarm: async () => null, 383+ setAlarm: async () => {}, 388+ info: async () => ({ remote: "https://artifacts.invalid/refusal" }), 389+ createToken: async () => ({ plaintext: "invented-test-token" }), 390+ [Symbol.dispose]() {}, 393+ const object = () => 394+ new ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? "on" : "off", ARTIFACTS: artifacts } as never); 395+ const call = async (op: string, body: unknown) => { 396+ for (let page = 0; page < 100; page++) { 397+ const result = await object().call("refusal", op, undefined, body); 398+ if (result.status !== 503) return result; 400+ throw Error("preparation did not finish"); 402+ assert.equal((await call("init", { files: { "a.txt": "original\n" } })).status, 200); 403+ assert.equal((await call("status", {})).status, 200); 404+ const remote = new MemoryFS(); 405+ await git.init({ fs: remote, dir: "/repo", defaultBranch: "main" }); 406+ const commit = async (files: Record<string, string>, message: string, parent: string[]) => { 408+ for (const [path, text] of Object.entries(files)) 412+ type: "blob" as const, 413+ oid: await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode(text) }), 415+ const tree = await git.writeTree({ fs: remote, dir: "/repo", tree: entries }); 416+ const oid = await git.commit({ 422+ author: { name: "Git writer", email: "test@example.invalid" }, 424+ await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: oid, force: true }); 427+ const base = await commit({ "a.txt": "original\n" }, "Initial\n\nabso-version: 0", []); 428+ values.set("git:head", base); 429+ let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]); 430+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]); 431+ t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 432+ (options.fs as MemoryFS).entries = structuredClone(remote.entries); 434+ const refused = await object().gitSync(); 436+ assert.match(JSON.stringify(refused.answer), /one file|clash/i); 437+ assert.equal(values.get("git:head"), head); 438+ assert.equal(await object().gitSync(), null); 439+ head = await commit({ "a.txt": "fixed\n" }, "Fixed", [head]); 440+ const fixed = await object().gitSync(); 442+ assert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed)); 443+ assert.equal(values.get("git:head"), head); 445+ JSON.stringify((await call("file", { path: "a.txt", version: String((await object().out()).version) })).body), --- a/server/test/router.test.ts
+++ b/server/test/router.test.ts
@@ -45,6 +45,23 @@
4747describe("routes", () => { 48+ it("forwards request identity separately from untrusted JSON body", async () => { 49+ const { env, calls } = fakeEnv(); 50+ const id = "00000000-0000-4000-8000-000000000007"; 51+ const response = await handle( 52+ request("/p/game/a/alice/record", { 54+ headers: { "content-type": "application/json", "Idempotency-Key": id }, 55+ body: JSON.stringify({ files: {}, principal: "forged" }), 61+ assert.equal(response.status, 200); 62+ assert.equal(calls[0]!.args[7], id); 63+ assert.equal(calls[0]!.args[6], undefined); 4865 it("matches the project's top routes and an agent's ops", () => { 4966 assert.deepEqual(PROJECT_ROUTE.exec("/p/game/status")?.slice(1, 3), ["game", "status"]); 5067 assert.deepEqual(PROJECT_ROUTE.exec("/p/game/a/alice/publish")?.slice(1), [ --- /dev/null
+++ b/server/test/stored-json-view.test.ts
@@ -0,0 +1,35 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { StoredJson, storeJson } from "../src/stored-json.ts"; 4+import { storedJsonView } from "../src/stored-json-view.ts"; 5+import { SqliteWriterState } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("stored JSON views expose array operations without decoding unrelated payloads", (t) => { 9+ const database = memoryStorage(); 10+ t.after(() => database.db.close()); 11+ SqliteWriterState.initialize(database); 12+ const state = new SqliteWriterState(database, "view"); 13+ const input = { type: "draft", atom: { deps: ["a0", "a1"], message: "x".repeat(50000) } }; 14+ storeJson(state, "entry", [JSON.stringify(input)]); 15+ const read = state.read.bind(state); 17+ state.read = (collection, key) => { 18+ if (collection.endsWith(":text:chunks")) chunks++; 19+ return read(collection, key); 21+ const value = storedJsonView(new StoredJson(state, "entry")) as typeof input; 22+ assert.equal(chunks, 0); 23+ assert.equal(value.atom.deps.length, 2); 24+ assert.equal(chunks, 0); 26+ value.atom.deps.map((x) => x), 29+ assert.equal(chunks, 2); 30+ assert.equal("message" in value.atom, true); 31+ assert.throws(() => { 32+ value.atom.deps[0] = "changed"; 34+ assert.deepEqual(JSON.parse(JSON.stringify(value)), input); --- /dev/null
+++ b/server/test/stored-json.test.ts
@@ -0,0 +1,94 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { StoredText } from "../../src/engine/stored-text.ts"; 4+import { StoredJson, storeJson } from "../src/stored-json.ts"; 5+import { SqliteWriterState } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("large JSON text streams into bounded SQLite values", (t) => { 9+ const database = memoryStorage(); 10+ t.after(() => database.db.close()); 11+ SqliteWriterState.initialize(database); 12+ const state = new SqliteWriterState(database, "decoded"); 13+ const root = storeJson( 18+ for (let i = 0; i < 500; i++) yield "x".repeat(16384); 19+ yield '","sequence":0}'; 22+ assert.deepEqual(state.read("entry", String(root)), { kind: "object", count: 2 }); 23+ const line = state.read("entry:edges", JSON.stringify([root, "line"])) as number; 25+ for (const chunk of new StoredText(state, "entry:text").chunks(String(line))) length += chunk.length; 26+ assert.equal(length, 8192000); 27+ assert.ok((database.db.prepare("SELECT MAX(length(value)) AS n FROM writer_state").get()!.n as number) < 100000); 28+ const before = database.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(); 29+ assert.throws(() => storeJson(state, "failed", ['{"line":"', "x".repeat(50000), '",oops}']), /JSON/); 31+ database.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 34+ assert.equal(state.read("failed", "root"), undefined); 37+test("disk JSON reads selected children without reading unrelated text", (t) => { 38+ const database = memoryStorage(); 39+ t.after(() => database.db.close()); 40+ SqliteWriterState.initialize(database); 41+ const state = new SqliteWriterState(database, "decoded"); 42+ storeJson(state, "entry", [ 45+ '","items":[true,null,42],"duplicate":1,"duplicate":2}', 47+ const originalRead = state.read.bind(state); 48+ state.read = (collection, key) => { 49+ assert.ok(!collection.includes(":text"), "metadata lookup read text payload"); 50+ return originalRead(collection, key); 52+ const root = new StoredJson(state, "entry"); 53+ assert.equal(root.kind, "object"); 54+ assert.equal(root.child("missing"), undefined); 55+ assert.equal(root.child("duplicate")!.scalar(), 2); 57+ [...root.child("items")!.elements()].map((node) => node.scalar()), 60+ assert.equal(root.child("items")!.child(3), undefined); 61+ state.write("entry:edges", JSON.stringify([root.child("items")!.id, "1"]), 999999); 62+ assert.throws(() => root.child("items")!.child(1), /identity/); 65+test("disk JSON preserves JSON numeric overflow and negative zero", (t) => { 66+ const database = memoryStorage(); 67+ t.after(() => database.db.close()); 68+ SqliteWriterState.initialize(database); 69+ const state = new SqliteWriterState(database, "decoded"); 70+ storeJson(state, "numbers", ["[1e400,-1e400,-0,1.25]"]); 72+ [...new StoredJson(state, "numbers").elements()].map((node) => node.scalar()), 73+ JSON.parse("[1e400,-1e400,-0,1.25]"), 77+test("disk JSON object traversal preserves unique keys and last duplicate values", (t) => { 78+ const database = memoryStorage(); 79+ t.after(() => database.db.close()); 80+ SqliteWriterState.initialize(database); 81+ const state = new SqliteWriterState(database, "decoded"); 82+ storeJson(state, "object", ['{"__proto__":1,"a":2,"__proto__":3,"constructor":4}']); 83+ const object = new StoredJson(state, "object"); 85+ [...object.properties()].map(([key, node]) => [key, node.scalar()]), 92+ state.remove("object:keys", JSON.stringify([object.id, 1])); 93+ assert.throws(() => [...object.properties()], /missing stored JSON object key/); --- /dev/null
+++ b/server/test/streamed-history-host.test.ts
@@ -0,0 +1,71 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteHistoryHost } from "../src/history-host.ts"; 6+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("history preparation and advancement never reconstruct a canonical frame string", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const memory = new MemoryStore(); 13+ const oracle = new Project(memory); 14+ oracle.init({ "a.txt": "before\n" }, 0); 15+ const log = new SqliteLog(storage); 16+ log.append(memory.entries); 17+ SqliteWriterState.initialize(storage); 18+ const writer = new SqliteWriterHost(storage, "writer"); 19+ writer.adoptPage(0, { maxEntries: 32, maxBytes: 100000 }, () => {}); 20+ const root = writer.root(); 21+ t.mock.method(log, "boundedFrame", () => { 22+ throw Error("whole canonical frame forbidden"); 24+ t.mock.method(Project, "load", () => { 25+ throw Error("whole history forbidden"); 27+ const history = new SqliteHistoryHost(storage, "streamed-history"); 36+ oracle.record("alice", { "a.txt": "after\n" }, 1); 37+ oracle.publish("alice", "change", 2); 38+ log.append(memory.entries.slice(root.logLength)); 39+ const committed = advanceWriterRoot(log, root, writer.source()); 68+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-history:decoded'").get()!.n, --- /dev/null
+++ b/server/test/streamed-large-frame.test.ts
@@ -0,0 +1,34 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("streamed writer adoption accepts a canonical frame above the full-decoder ceiling", (t) => { 9+ const storage = memoryStorage(); 10+ t.after(() => storage.db.close()); 11+ const memory = new MemoryStore(); 12+ new Project(memory).init({ "large.txt": "x".repeat(8100000) }, 0); 13+ const log = new SqliteLog(storage); 14+ log.append(memory.entries); 15+ SqliteWriterState.initialize(storage); 16+ const host = new SqliteWriterHost(storage, "large-stream"); 17+ const expected = host.source(); 18+ t.mock.method(SqliteLog.prototype, "boundedFrame", () => { 19+ throw Error("whole frame forbidden"); 21+ t.mock.method(Project, "load", () => { 22+ throw Error("whole history forbidden"); 24+ const maxBytes = log.adoptionPageBytes(0); 25+ assert.ok(maxBytes > 8000000); 26+ const page = host.adoptVerifiedPage({ expected, from: 0, digest: "", maxEntries: 1, maxBytes }, () => {}); 27+ assert.equal(page.ready, true); 28+ assert.equal(host.root().logLength, 1); 29+ assert.ok(JSON.stringify(new SqliteWriterState(storage, "large-stream").read("atoms", "0")).length < 4096); 31+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace='large-stream:decoded'").get()!.n, --- /dev/null
+++ b/server/test/streamed-large-history.test.ts
@@ -0,0 +1,72 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteHistoryHost } from "../src/history-host.ts"; 6+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("history prepares an oversized entry and preserves it after later publication", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const memory = new MemoryStore(); 13+ const oracle = new Project(memory); 14+ oracle.init({ "a.txt": "x".repeat(8100000) }, 0); 15+ const initialText = oracle.files()["a.txt"]; 16+ const log = new SqliteLog(storage); 17+ log.append(memory.entries); 18+ SqliteWriterState.initialize(storage); 19+ const writer = new SqliteWriterHost(storage, "writer"); 20+ writer.adoptPage(0, { maxEntries: 32, maxBytes: log.adoptionPageBytes(0) }, () => {}); 21+ const root = writer.root(); 22+ t.mock.method(log, "boundedFrame", () => { 23+ throw Error("whole canonical frame forbidden"); 25+ t.mock.method(Project, "load", () => { 26+ throw Error("whole history forbidden"); 28+ const history = new SqliteHistoryHost(storage, "streamed-history"); 37+ oracle.record("alice", { "b.txt": "after\n" }, 1); 38+ oracle.publish("alice", "change", 2); 39+ log.append(memory.entries.slice(root.logLength)); 40+ const committed = advanceWriterRoot(log, root, writer.source()); 69+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-history:decoded'").get()!.n, --- /dev/null
+++ b/server/test/streamed-writer-adoption.test.ts
@@ -0,0 +1,48 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("writer adoption streams canonical frames and preserves exact page retries", (t) => { 9+ const storage = memoryStorage(); 10+ t.after(() => storage.db.close()); 11+ const memory = new MemoryStore(); 12+ const oracle = new Project(memory); 13+ oracle.init({ "a.txt": "one\n" }, 0); 14+ oracle.record("alice", { "a.txt": "two\n" }, 1); 15+ oracle.publish("alice", "change", 2); 16+ new SqliteLog(storage).append(memory.entries); 17+ SqliteWriterState.initialize(storage); 18+ const host = () => new SqliteWriterHost(storage, "streamed-writer"); 19+ const expected = host().source(); 20+ const canonical = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 21+ t.mock.method(SqliteLog.prototype, "boundedFrame", () => { 22+ throw Error("whole frame reconstruction forbidden"); 24+ t.mock.method(Project, "load", () => { 25+ throw Error("full history forbidden"); 29+ while (from < expected.logLength) { 30+ const input = { expected, from, digest, maxEntries: 2, maxBytes: 100000 }; 31+ const page = host().adoptVerifiedPage(input, () => {}); 33+ host().adoptVerifiedPage(input, () => {}), 37+ digest = page.digest; 40+ host().readCalls({ expected, validateAuthority: () => {}, operation: (calls) => calls.shared().files }), 43+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), canonical); 45+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-writer:decoded'").get()!.n, --- a/server/test/writer-host.test.ts
+++ b/server/test/writer-host.test.ts
@@ -72,6 +72,37 @@
7474 assert.ok(++pages < 1000); 75+ // Repeated anonymous views share one reader only inside their verified session. 76+ const session = projection.open({ state, log: new SqliteLog(storage), root: host().root() }); 77+ const views = session.readViewProvider(oracle.graph); 78+ const first = views.keyed!("v @0"); 79+ assert.equal(views.keyed!("v @0"), first); 80+ assert.deepEqual(first.files(), { "a.txt": "one\ntwo\n" }); 81+ const seq = oracle.graph.size; 86+ message: "Advance graph", 98+ assert.throws(() => first.files(), /stale/); 99+ const refreshed = views.keyed!("v @0"); 100+ assert.notEqual(refreshed, first); 101+ assert.deepEqual(refreshed.files(), { "a.txt": "one\ntwo\n" }); 103+ assert.throws(() => refreshed.files(), /expired|closed/); 104+ assert.throws(() => first.files(), /expired|closed/); 105+ assert.throws(() => views.keyed!("v @0"), /expired|closed/); 75106 const writer = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true }); 76107 const run = (operation: "record" | "publish", body: unknown, failReceipt = false) => 77108 writer().runCalls({ @@ -92,6 +123,9 @@
92123 assert.throws(() => run("record", { files: { "b.txt": "failed\n" } }, true), /receipt failure/); 93124 assert.deepEqual(rows(), before); 94125 assert.equal(run("record", { files: { "b.txt": "finished\n" } }).status, 200); 126+ const beforePublish = rows(); 127+ assert.throws(() => run("publish", { message: "Disk first" }, true), /receipt failure/); 128+ assert.deepEqual(rows(), beforePublish); 95129 const published = run("publish", { message: "Disk first" }); 96130 assert.equal(published.status, 200); 97131 assert.equal((published.body as { ok: boolean }).ok, true); --- a/src/engine/experimental/projection-atom-index.ts
+++ b/src/engine/experimental/projection-atom-index.ts
@@ -61,7 +61,8 @@
6262 throw Error("invalid projection atom attribute"); 64− return structuredClone(value);
64+ // Every validated record field is scalar; detach proxy-backed records without cloning a container graph. 65+ return value && typeof value === "object" ? { ...value } : value; 6768/** Derived index only. The caller supplies an already validated canonical atom and --- a/src/engine/experimental/projection-locator.ts
+++ b/src/engine/experimental/projection-locator.ts
@@ -63,42 +63,52 @@
6363 this.#storage.write(this.#collection, "next", next + 1); 66− /** Persist only pages reachable from the final root of a bounded update batch. */
66+ /** Update each touched branch once, retaining at most 256 decoded values. */ 6767 setMany(root: Page, values: ReadonlyArray<readonly [number, T]>): Page { 6969 if (values.length > 256) throw Error("locator batch limit"); 7070 return this.#storage.transaction(() => { 71− const staged = new Map<string, unknown>();
72− const storage: GraphStateStorage = {
73− read: (collection, key) =>
74− collection === this.#collection && staged.has(key) ? staged.get(key) : this.#storage.read(collection, key),
75− write: (collection, key, value) => {
76− if (collection !== this.#collection) throw Error("unexpected batch collection");
77− staged.set(key, value);
78− },
79− remove: () => {
80− throw Error("unexpected batch removal");
81− },
82− entries: () => {
83− throw Error("unexpected batch scan");
84− },
85− transaction: (body) => body(),
71+ if (!values.length) return root; 72+ let next = this.#storage.read(this.#collection, "next") ?? 0; 73+ if (!safe(next)) throw Error("invalid locator allocation"); 74+ const write = (node: Node): number => { 75+ if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid locator allocation"); 76+ if (this.#storage.read(this.#collection, String(next)) !== undefined) 77+ throw Error("locator allocation collision"); 79+ this.#storage.write(this.#collection, String(id), node); 87− // The namespace is encoded into the collection at construction.
88− const namespace = JSON.parse(this.#collection.slice("experimental-locator:".length)) as string;
89− const index = new ProjectionLocator<T>(storage, namespace, this.#decode);
90− let result = root;
91− for (const [id, value] of values) result = index.set(result, id, value);
92− const retained = new Set<number>();
93− const visit = (id: Page): void => {
94− if (id === null || retained.has(id) || !staged.has(String(id))) return;
95− retained.add(id);
96− const node = staged.get(String(id)) as Node;
97− if (node.kind === "branch") for (const child of Object.values(node.children)) visit(child);
82+ const checked = new Map<string, T>(); 83+ for (const [id, value] of values) checked.set(keyOf(id), structuredClone(this.#decode(structuredClone(value)))); 84+ const updates = [...checked].sort(([a], [b]) => a.localeCompare(b)); 85+ const visit = (current: Page, edits: [string, T][], parent?: string, digit?: string, depth = 0): Page => { 86+ if (!edits.length) return current; 87+ if (depth > 8) throw Error("invalid locator depth"); 88+ const node = current === null ? undefined : this.#read(current, parent, digit); 89+ let prefix = node?.prefix ?? edits[0]![0]; 90+ for (const [key] of edits) { 92+ while (common < prefix.length && prefix[common] === key[common]) common++; 93+ prefix = prefix.slice(0, common); 95+ if (prefix.length === 8) return write({ format: 1, kind: "leaf", prefix, value: edits[edits.length - 1]![1] }); 96+ const children: Record<string, number> = 97+ node?.kind === "branch" && node.prefix === prefix ? { ...node.children } : {}; 98+ if (node && node.prefix !== prefix) children[node.prefix[prefix.length]!] = current!; 99+ const groups = new Map<string, [string, T][]>(); 100+ for (const edit of edits) { 101+ const edge = edit[0][prefix.length]!; 102+ const group = groups.get(edge) ?? []; 104+ groups.set(edge, group); 106+ for (const [edge, group] of groups) 107+ children[edge] = visit(children[edge] ?? null, group, prefix, edge, depth + 1)!; 108+ return write({ format: 1, kind: "branch", prefix, children }); 99− visit(result);
100− for (const id of retained) this.#storage.write(this.#collection, String(id), staged.get(String(id)));
101− if (staged.has("next")) this.#storage.write(this.#collection, "next", staged.get("next"));
110+ const result = visit(root, updates); 111+ this.#storage.write(this.#collection, "next", next); --- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -118,16 +118,21 @@
118118 if (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error("missing dependency"); 119119 return this.storage.transaction(() => { 120120 const state = { ...previous }; 121− const sequence = this.sequence;
122121 this.ensureFile(state, this.path); 123122 for (const run of atom.inserts) this.ensureFile(state, run.file); 125124 for (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`); 125+ let visibility: Array<{ kind: "visibility"; id: number; delta: number }> = []; 126126 for (const line of atom.deletes) { 127127 const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); 128128 if (!marker) throw Error("missing deleted marker"); 129− state.sequence = sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
129+ visibility.push({ kind: "visibility", id: marker.enter, delta: 1 }); 130+ if (visibility.length === 16) { 131+ state.sequence = this.sequence.updateMany(state.sequence, visibility); 135+ if (visibility.length) state.sequence = this.sequence.updateMany(state.sequence, visibility); 131136 for (const id of atom.deps) { 132137 const seq = this.graph.atom(id).seq, 133138 member = required(this.members.get(state.membership, seq)); @@ -143,12 +148,6 @@
143148 insertLine(state: MarkerState, line: string): void { 144149 this.assertContext(state); 145150 const sequence = this.sequence; 146− const insert = (rank: number, text: string, hidden = false): number => {
147− const id = state.sequence.next;
148− state.sequence = sequence.update(state.sequence, { kind: "insert", rank, text });
149− if (hidden) state.sequence = sequence.update(state.sequence, { kind: "visibility", id, delta: 1 });
150− return id;
151− };
152151 const n = this.graph.lineN(line), 153152 parent = this.graph.parentCodeOf(n); 154153 if (n + 1 >= 0x80000000) throw Error("prototype line identity limit"); @@ -175,8 +174,12 @@
175174 preceding === undefined ? parentMarker.enter : required(this.markers.get(state.locator, preceding + 1)).exit; 176175 state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) }); 177176 const at = sequence.rank(state.sequence, anchor) + 1; 178− const enter = insert(at, line),
179− exit = insert(at + 1, `${line}:end`, true);
177+ const enter = state.sequence.next, 179+ state.sequence = sequence.updateMany(state.sequence, [ 180+ { kind: "insert", rank: at, text: line }, 181+ { kind: "insert", rank: at + 1, text: `${line}:end`, hidden: true }, 180183 state.locator = this.markers.set(state.locator, n + 1, { kind: "line", enter, exit, parentKey, key }); 182185 removeDeleter(previous: MarkerState, atom: Atom): MarkerState { --- a/src/engine/experimental/projection-priority.ts
+++ b/src/engine/experimental/projection-priority.ts
@@ -1,26 +1,15 @@
11import type { GraphStateStorage } from "../state-source.ts"; 33type Page = number | null; 4−interface Leaf {
5− format: 1;
6− kind: "leaf";
7− depth: 57;
8− value: unknown;
9−}
10−interface Branch {
11− format: 1;
12− kind: "branch";
13− depth: number;
14− children: Record<string, number>;
15−}
16−type Node = Leaf | Branch;
17−const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
18−const object = (value: unknown): value is Record<string, unknown> =>
19− value !== null && typeof value === "object" && !Array.isArray(value);
5+ | { format: 2; kind: "leaf"; prefix: string; value: unknown } 6+ | { format: 2; kind: "branch"; prefix: string; children: Record<string, number> }; 7+const safe = (v: unknown): v is number => Number.isSafeInteger(v) && Number(v) >= 0; 8+const object = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v); 209function check(root: Page, key: string): void { 2110 if ((root !== null && !safe(root)) || !/^[0-9a-f]{57}$/.test(key)) throw Error("invalid priority lookup"); 23−/** Internal immutable priority experiment. At most 57 levels and 16 children. */
12+/** Immutable compressed priority paths. Reads legacy depth pages; writes format 2. */ 2413export class ProjectionPriority<T> { 2514 readonly #storage: GraphStateStorage; 2615 readonly #collection: string; @@ -31,85 +20,131 @@
3120 this.#collection = `experimental-priority:${JSON.stringify(namespace)}`; 3221 this.#decode = decode; 34− #read(id: number, depth: number): Node {
35− if (!safe(id) || !safe(depth) || depth > 57) throw Error("invalid priority reference");
23+ #read(id: number, expected: string): Node { 24+ if (!safe(id) || expected.length > 57) throw Error("invalid priority reference"); 3625 const row = this.#storage.read(this.#collection, String(id)); 37− if (!object(row) || row.format !== 1 || row.depth !== depth || Object.keys(row).length !== 4)
38− throw Error("invalid priority node");
39− if (depth === 57) {
40− if (row.kind !== "leaf" || !("value" in row)) throw Error("invalid priority leaf");
41− return row as unknown as Leaf;
26+ if (!object(row) || Object.keys(row).length !== 4) throw Error("invalid priority node"); 27+ const legacy = row.format === 1; 28+ const prefix = legacy ? expected : row.prefix; 30+ (legacy ? row.depth !== expected.length : row.format !== 2) || 31+ typeof prefix !== "string" || 32+ !/^[0-9a-f]{0,57}$/.test(prefix) || 33+ !prefix.startsWith(expected) 35+ throw Error("invalid priority prefix"); 36+ if (row.kind === "leaf") { 37+ if (prefix.length !== 57 || !("value" in row)) throw Error("invalid priority leaf"); 38+ return { format: 2, kind: "leaf", prefix, value: row.value }; 43− if (row.kind !== "branch" || !object(row.children)) throw Error("invalid priority branch");
40+ if (row.kind !== "branch" || prefix.length >= 57 || !object(row.children)) throw Error("invalid priority branch"); 4441 const entries = Object.entries(row.children); 45− if (!entries.length || entries.length > 16) throw Error("invalid priority fanout");
42+ if (entries.length < (legacy ? 1 : 2) || entries.length > 16) throw Error("invalid priority fanout"); 4643 for (const [digit, child] of entries) 4744 if (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error("invalid priority child"); 48− return row as unknown as Branch;
45+ return { format: 2, kind: "branch", prefix, children: row.children as Record<string, number> }; 50− #write(node: Node): number {
51− const next = this.#storage.read(this.#collection, "next") ?? 0;
52− if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid priority allocation");
53− if (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error("priority allocation collision");
54− this.#storage.write(this.#collection, String(next), node);
55− this.#storage.write(this.#collection, "next", next + 1);
56− return next;
47+ #allocate<R>(body: (write: (node: Node) => number) => R): R { 48+ return this.#storage.transaction(() => { 49+ let next = this.#storage.read(this.#collection, "next") ?? 0; 50+ if (!safe(next)) throw Error("invalid priority allocation"); 51+ const initial = next; 52+ const result = body((node) => { 53+ // Collapse legacy singleton paths before storing a compressed page. 54+ while (node.kind === "branch" && Object.keys(node.children).length === 1) { 55+ const [digit, child] = Object.entries(node.children)[0]!; 56+ node = this.#read(child, node.prefix + digit); 58+ if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid priority allocation"); 59+ if (this.#storage.read(this.#collection, String(next)) !== undefined) 60+ throw Error("priority allocation collision"); 62+ this.#storage.write(this.#collection, String(id), node); 65+ if (next !== initial) this.#storage.write(this.#collection, "next", next); 5870 insert(root: Page, key: string, value: T): number { 6072 const checked = structuredClone(this.#decode(structuredClone(value))); 61− return this.#storage.transaction(() => {
62− const visit = (id: Page, depth: number): number => {
63− const node = id === null ? undefined : this.#read(id, depth);
64− if (depth === 57) return this.#write({ format: 1, kind: "leaf", depth: 57, value: checked });
65− if (node?.kind === "leaf") throw Error("invalid priority depth");
66− const children = node?.children ?? {},
67− digit = key[depth]!;
68− const child = visit(children[digit] ?? null, depth + 1);
69− return this.#write({ format: 1, kind: "branch", depth, children: { ...children, [digit]: child } });
73+ return this.#allocate((write) => { 74+ const leaf = () => write({ format: 2, kind: "leaf", prefix: key, value: checked }); 75+ const visit = (id: Page, expected: string): number => { 76+ if (id === null) return leaf(); 77+ const node = this.#read(id, expected); 79+ while (common < node.prefix.length && node.prefix[common] === key[common]) common++; 80+ if (common < node.prefix.length) { 81+ // Legacy pages need their inferred prefix persisted when moved below a new branch. 82+ const old = write(node), 87+ prefix: key.slice(0, common), 88+ children: { [node.prefix[common]!]: old, [key[common]!]: added }, 91+ if (node.kind === "leaf") return leaf(); 92+ const digit = key[node.prefix.length]!; 93+ const child = visit(node.children[digit] ?? null, node.prefix + digit); 94+ return write({ ...node, children: { ...node.children, [digit]: child } }); 71− return visit(root, 0);
96+ return visit(root, ""); 7499 remove(root: Page, key: string): Page { 76− return this.#storage.transaction(() => {
77− const visit = (id: Page, depth: number): Page => {
101+ return this.#allocate((write) => { 102+ const visit = (id: Page, expected: string): Page => { 78103 if (id === null) throw Error("missing priority key"); 79− const node = this.#read(id, depth);
104+ const node = this.#read(id, expected); 105+ if (!key.startsWith(node.prefix)) throw Error("missing priority key"); 80106 if (node.kind === "leaf") return null; 81− const digit = key[depth]!,
82− child = visit(node.children[digit] ?? null, depth + 1),
107+ const digit = key[node.prefix.length]!, 108+ child = visit(node.children[digit] ?? null, node.prefix + digit), 83109 children = { ...node.children }; 84110 if (child === null) delete children[digit]; 85111 else children[digit] = child; 86− return Object.keys(children).length ? this.#write({ ...node, children }) : null;
112+ const entries = Object.entries(children); 113+ if (!entries.length) return null; 114+ if (entries.length === 1) { 115+ const [d, c] = entries[0]!; 116+ return write(this.#read(c, node.prefix + d)); 118+ return write({ ...node, children }); 88− return visit(root, 0);
120+ return visit(root, ""); 91123 before(root: Page, key: string): T | undefined { 93− let current = root;
94− let candidate: { id: number; depth: number } | undefined;
95− for (let depth = 0; current !== null && depth < 57; depth++) {
96− const node = this.#read(current, depth);
97− if (node.kind !== "branch") throw Error("invalid priority depth");
98− const digit = key[depth]!,
99− lower = Object.keys(node.children)
100− .filter((item) => item < digit)
101− .sort()
102− .at(-1);
103− if (lower !== undefined) candidate = { id: node.children[lower]!, depth: depth + 1 };
104− current = node.children[digit] ?? null;
105− }
106− if (!candidate) return undefined;
107− let { id, depth } = candidate;
108− for (; depth <= 57; depth++) {
109− const node = this.#read(id, depth);
125+ const maximum = (id: number, expected: string): T => { 126+ const node = this.#read(id, expected); 110127 if (node.kind === "leaf") return this.#decode(structuredClone(node.value)); 111− id = node.children[Object.keys(node.children).sort().at(-1)!]!;
112− }
113− throw Error("invalid priority depth");
128+ const digit = Object.keys(node.children).sort().at(-1)!; 129+ return maximum(node.children[digit]!, node.prefix + digit); 131+ const visit = (id: Page, expected: string): T | undefined => { 132+ if (id === null) return undefined; 133+ const node = this.#read(id, expected); 134+ if (!key.startsWith(node.prefix)) return node.prefix < key ? maximum(id, expected) : undefined; 135+ if (node.kind === "leaf") return undefined; 136+ const digit = key[node.prefix.length]!; 137+ const same = node.children[digit]; 138+ if (same !== undefined) { 139+ const found = visit(same, node.prefix + digit); 140+ if (found !== undefined) return found; 142+ const lower = Object.keys(node.children) 143+ .filter((d) => d < digit) 146+ return lower === undefined ? undefined : maximum(node.children[lower]!, node.prefix + lower); 148+ return visit(root, ""); --- a/src/engine/experimental/projection-sequence.ts
+++ b/src/engine/experimental/projection-sequence.ts
@@ -20,7 +20,7 @@
2020 readonly next: number; 2222export type SequenceOperation = 23− | { kind: "insert"; rank: number; text: string }
23+ | { kind: "insert"; rank: number; text: string; hidden?: boolean } 2424 | { kind: "visibility"; id: number; delta: number } 2525 | { kind: "move"; from: number; length: number; to: number }; 2626const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; @@ -132,6 +132,11 @@
134134 update(state: SequenceState, operation: SequenceOperation): SequenceState { 135+ return this.updateMany(state, [operation]); 137+ /** A small bounded group shares changed AVL nodes and one locator flush. */ 138+ updateMany(state: SequenceState, operations: readonly SequenceOperation[]): SequenceState { 139+ if (operations.length < 1 || operations.length > 16) throw Error("invalid sequence operation batch"); 135140 this.#state(state); 136141 return this.storage.transaction(() => { 137142 let map = state.map; @@ -192,114 +197,117 @@
193198 let root = state.root, 194199 next = state.next; 195− if (operation.kind === "insert") {
196− const { rank, text } = operation;
197− if (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32) throw Error("invalid insert");
198− const added = next++;
199− const insert = (id: Page, at: number, p: Page): number => {
200− if (id === null)
201− return put({
202− id: added,
203− parent: p,
204− left: null,
205− right: null,
206− text,
207− deletions: 0,
208− height: 1,
209− count: 1,
210− visible: 1,
211− fileStarts: text.startsWith("root:") ? 1 : 0,
212− });
213− const node = get(id),
214− leftCount = count(node.left);
215− if (at <= leftCount) save({ ...node, left: insert(node.left, at, id) });
216− else save({ ...node, right: insert(node.right, at - leftCount - 1, id) });
217− return balance(id);
218− };
219− root = insert(root, rank, null);
220− parent(root, null);
221− } else if (operation.kind === "move") {
222− const { from, length, to } = operation;
223− const total = count(root);
224− if (
225− ![from, length, to].every(Number.isSafeInteger) ||
226− from < 0 ||
227− length < 0 ||
228− from + length > total ||
229− to < 0 ||
230− to > total - length
231− )
232− throw Error("invalid move range");
233− // Join two AVL trees around one existing stable marker.
234− const join = (left: Page, pivot: number, right: Page): number => {
235− if (height(left) > height(right) + 1) {
236− const node = get(left!);
237− save({ ...node, right: join(node.right, pivot, right) });
238− const result = balance(left!);
239− parent(result, null);
240− return result;
241− }
242− if (height(right) > height(left) + 1) {
243− const node = get(right!);
244− save({ ...node, left: join(left, pivot, node.left) });
245− const result = balance(right!);
246− parent(result, null);
247− return result;
248− }
249− return save({ ...get(pivot), left, right, parent: null });
250− };
251− const split = (id: Page, at: number): [Page, Page] => {
252− if (id === null) return [null, null];
253− const node = get(id),
254− size = count(node.left);
255− if (at <= size) {
256− const [left, middle] = split(node.left, at);
257− const right = join(middle, id, node.right);
200+ for (const operation of operations) { 201+ if (operation.kind === "insert") { 202+ const { rank, text } = operation; 203+ if (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32) 204+ throw Error("invalid insert"); 205+ const added = next++; 206+ const insert = (id: Page, at: number, p: Page): number => { 214+ deletions: operation.hidden ? 1 : 0, 217+ visible: operation.hidden ? 0 : 1, 218+ fileStarts: text.startsWith("root:") ? 1 : 0, 220+ const node = get(id), 221+ leftCount = count(node.left); 222+ if (at <= leftCount) save({ ...node, left: insert(node.left, at, id) }); 223+ else save({ ...node, right: insert(node.right, at - leftCount - 1, id) }); 226+ root = insert(root, rank, null); 228+ } else if (operation.kind === "move") { 229+ const { from, length, to } = operation; 230+ const total = count(root); 232+ ![from, length, to].every(Number.isSafeInteger) || 235+ from + length > total || 239+ throw Error("invalid move range"); 240+ // Join two AVL trees around one existing stable marker. 241+ const join = (left: Page, pivot: number, right: Page): number => { 242+ if (height(left) > height(right) + 1) { 243+ const node = get(left!); 244+ save({ ...node, right: join(node.right, pivot, right) }); 245+ const result = balance(left!); 246+ parent(result, null); 249+ if (height(right) > height(left) + 1) { 250+ const node = get(right!); 251+ save({ ...node, left: join(left, pivot, node.left) }); 252+ const result = balance(right!); 253+ parent(result, null); 256+ return save({ ...get(pivot), left, right, parent: null }); 258+ const split = (id: Page, at: number): [Page, Page] => { 259+ if (id === null) return [null, null]; 260+ const node = get(id), 261+ size = count(node.left); 263+ const [left, middle] = split(node.left, at); 264+ const right = join(middle, id, node.right); 266+ parent(right, null); 267+ return [left, right]; 269+ const [middle, right] = split(node.right, at - size - 1); 270+ const left = join(node.left, id, middle); 258271 parent(left, null); 259272 parent(right, null); 260273 return [left, right]; 275+ const merge = (left: Page, right: Page): Page => { 276+ if (left === null) { 277+ parent(right, null); 280+ if (right === null) { 284+ const [pivot, rest] = split(right, 1); 285+ return join(left, pivot!, rest); 287+ if (length && from !== to) { 288+ const [left, tail] = split(root, from); 289+ const [moved, right] = split(tail, length); 290+ const remaining = merge(left, right); 291+ const [before, after] = split(remaining, to); 292+ root = merge(merge(before, moved), after); 262− const [middle, right] = split(node.right, at - size - 1);
263− const left = join(node.left, id, middle);
264− parent(left, null);
265− parent(right, null);
266− return [left, right];
267− };
268− const merge = (left: Page, right: Page): Page => {
269− if (left === null) {
270− parent(right, null);
271− return right;
295+ } else if (operation.kind === "visibility") { 296+ let node = get(operation.id); 299+ !Number.isInteger(operation.delta) || 300+ Math.abs(operation.delta) !== 1 || 301+ node.deletions + operation.delta < 0 303+ throw Error("invalid visibility"); 304+ save({ ...node, deletions: node.deletions + operation.delta }); 305+ while (node.parent !== null) { 306+ node = get(node.parent); 273− if (right === null) {
274− parent(left, null);
275− return left;
276− }
277− const [pivot, rest] = split(right, 1);
278− return join(left, pivot!, rest);
279− };
280− if (length && from !== to) {
281− const [left, tail] = split(root, from);
282− const [moved, right] = split(tail, length);
283− const remaining = merge(left, right);
284− const [before, after] = split(remaining, to);
285− root = merge(merge(before, moved), after);
286− parent(root, null);
287− }
288− } else if (operation.kind === "visibility") {
289− let node = get(operation.id);
290− if (
291− !node ||
292− !Number.isInteger(operation.delta) ||
293− Math.abs(operation.delta) !== 1 ||
294− node.deletions + operation.delta < 0
295− )
296− throw Error("invalid visibility");
297− save({ ...node, deletions: node.deletions + operation.delta });
298− while (node.parent !== null) {
299− node = get(node.parent);
300− save(node);
301− }
302− } else throw Error("unknown operation");
309+ } else throw Error("unknown operation"); 303311 // Keep locator staging bounded even if a valid split/merge changes more 304312 // than one batch. The enclosing transaction commits all batches together. 305313 let batch: Array<readonly [number, SequenceNode]> = []; --- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -20,12 +20,14 @@
2020import { withProjectionScratch } from "./projection-scratch.ts"; 2222 type GraphStateStorage, 2829} from "./state-source.ts"; 30+import { StoredText } from "./stored-text.ts"; @@ -306,12 +308,169 @@
306308 if (options.storage) { 307309 const storage = options.storage; 308310 const numbers = (name: string): NumberIndex => storedNumbers(storage, name); 309− this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
310− freezeAtom(
311− atom,
312− (id) => id,
313− (author) => author,
314− ),
311+ const atomText = new StoredText(storage, "atom-text:long"); 312+ type TextReference = { text: string }; 313+ const listFields = [ 325+ type EncodedAtom = { 326+ insertionFormat?: 1; 327+ insertionRuns?: string; 331+ lists?: Partial<Record<(typeof listFields)[number], string>>; 334+ this.#atoms = storedArray<Atom>( 338+ const encoded = value as unknown as Partial<EncodedAtom>; 339+ if (encoded.textFormat !== undefined && encoded.textFormat !== 1) 340+ throw Error("invalid stored atom text format"); 341+ if (encoded.listFormat !== undefined && encoded.listFormat !== 1) 342+ throw Error("invalid stored atom list format"); 343+ if (encoded.listFormat === 1) { 346+ typeof encoded.lists !== "object" || 347+ Array.isArray(encoded.lists) || 348+ !Number.isSafeInteger(encoded.listCount) || 349+ encoded.listCount! < 1 || 350+ Object.keys(encoded.lists).length !== encoded.listCount || 351+ Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number])) 353+ throw Error("invalid stored atom list references"); 355+ if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1) 356+ throw Error("invalid stored insertion format"); 358+ encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1 362+ encoded.textFormat === 1 363+ ? (start: number, length: number): readonly string[] => { 364+ const result: string[] = []; 366+ for (const run of atom.inserts) 367+ for (const raw of run.lines) { 368+ if (index >= start && index < start + length) { 369+ const reference = raw as unknown as TextReference; 370+ if (typeof raw === "string") result.push(raw); 371+ else if (reference && typeof reference.text === "string") 372+ result.push(atomText.read(reference.text)); 373+ else throw Error("invalid stored atom text reference"); 375+ if (++index >= start + length) return result; 377+ throw Error("stored atom text range missing"); 380+ const frozen = freezeAtom( 386+ if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen; 387+ const result = { ...frozen }; 388+ if (encoded.insertionFormat === 1) { 389+ const collection = `atom-inserts:${atom.seq}`; 390+ if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference"); 391+ const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => { 392+ const run = raw as { file: string; parent: InsertRun["parent"]; lines: string }; 393+ const lines = `${collection}:lines:${index}`; 394+ if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string") 395+ throw Error("invalid stored insertion run"); 396+ return Object.freeze({ 399+ lines: readonlyStoredArray<string>(storage, lines, (rawLine) => { 400+ if (typeof rawLine === "string") return rawLine; 401+ const ref = rawLine as TextReference; 402+ if (!ref || typeof ref.text !== "string") throw Error("invalid stored insertion text"); 403+ return atomText.read(ref.text); 407+ Object.defineProperty(result, "inserts", { value: inserts, enumerable: true }); 409+ for (const field of listFields) { 410+ const collection = encoded.lists?.[field]; 411+ if (collection === undefined) continue; 412+ if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`) 413+ throw Error("invalid stored atom list reference"); 414+ Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true }); 416+ return Object.freeze(result); 419+ const atom = { ...input }; 420+ const lists: Partial<Record<(typeof listFields)[number], string>> = {}; 421+ for (const field of listFields) { 422+ const values = input[field]; 423+ if (!values || values.length <= 256) continue; 424+ const collection = `atom-list:${input.seq}:${field}`; 425+ const saved = storedArray<unknown>(storage, collection); 426+ for (const value of values) saved.push(value); 427+ lists[field] = collection; 428+ Object.defineProperty(atom, field, { value: [], enumerable: true }); 430+ const listCount = Object.keys(lists).length; 431+ const hasLists = listCount > 0; 432+ if (atom.inserts.length > 256 || atom.inserts.some((run) => run.lines.length > 256)) { 433+ const collection = `atom-inserts:${input.seq}`; 434+ const runs = storedArray<unknown>(storage, collection); 437+ for (const run of atom.inserts) { 438+ const lineCollection = `${collection}:lines:${runIndex++}`; 439+ const lines = storedArray<unknown>(storage, lineCollection); 440+ for (const line of run.lines) { 441+ const text = JSON.stringify([key, lineIndex++]); 442+ if (line.length > StoredText.chunkCharacters) { 443+ atomText.write(text, line); 444+ lines.push({ text }); 445+ } else lines.push(line); 447+ runs.push({ file: run.file, parent: run.parent, lines: lineCollection }); 451+ insertionRuns: collection, 452+ ...(hasLists ? { listFormat: 1, listCount, lists } : {}), 453+ atom: { ...atom, inserts: [] }, 456+ if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters))) 457+ return hasLists ? { listFormat: 1, listCount, lists, atom } : atom; 459+ const inserts = atom.inserts.map((run) => ({ 461+ lines: run.lines.map((line) => { 462+ const text = JSON.stringify([key, index++]); 463+ if (line.length <= StoredText.chunkCharacters) return line; 464+ atomText.write(text, line); 470+ ...(hasLists ? { listFormat: 1, listCount, lists } : {}), 471+ atom: { ...atom, inserts }, 316475 this.#lamport = storedArray(storage, "lamport"); 317476 this.#lineBase = storedArray(storage, "line-base"); @@ -324,7 +483,26 @@
324483 this.#lineParent = numbers("line-parent"); 325484 this.#deleter = numbers("deleter"); 326485 this.#replacing = numbers("replacing"); 327− this.#lineText = storedArray(storage, "line-text");
486+ const longText = atomText; 487+ this.#lineText = storedArray<string>( 491+ if (typeof value === "string") return value; 492+ const reference = value as unknown as { format: number; text: string }; 493+ if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference"); 494+ return longText.read(reference.text); 497+ if (value.length <= StoredText.chunkCharacters) return value; 498+ const number = Number(key); 499+ const seq = this.#lineAtom.at(number); 500+ const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]); 501+ const header = storage.read("atom-text:long", text) as { characters?: number } | undefined; 502+ if (header?.characters !== value.length) throw Error("long line atom text is missing"); 503+ return { format: 1, text }; 328506 this.#pathIndex = storedMap(storage, "path-index"); 329507 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) => 330508 JSON.stringify(["number", Number(key)]), @@ -565,6 +743,15 @@
566744 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */ 567745 deletedLines(id: AtomId): readonly LineId[] { 746+ const seq = this.#seq(id); 747+ const count = this.#storage?.read("atom-delete-counts", String(seq)); 748+ if (count !== undefined) { 749+ const out: LineId[] = []; 750+ for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq))) 751+ out.push(this.#lineName(n)); 752+ if (out.length !== count) throw Error("incomplete atom deletion index"); 568755 const ns = this.#atomDeletes[this.#seq(id)]; 569756 if (!ns) return EMPTY; 570757 const out: LineId[] = new Array(ns.length); @@ -574,7 +761,13 @@
575762 /** How many lines an atom deletes, without reading its lists. */ 576763 deleteCount(id: AtomId): number { 577− return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
764+ const seq = this.#seq(id); 765+ const count = this.#storage?.read("atom-delete-counts", String(seq)); 766+ if (count !== undefined) { 767+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count"); 768+ return count as number; 770+ return this.#atomDeletes[seq]?.length ?? 0; 580773 textOf(n: number): string { @@ -957,10 +1150,6 @@
9571150 #reaches(from: Iterable<AtomId>, target: AtomId): boolean { 9581151 const floor = this.#lamport[this.#seq(target)]!; 9591152 if (this.#storage) { 960− // Roots belong to the current atom's dependency list, not its history.
961− const roots = [...from];
962− if (roots.includes(target)) return true;
963− if (roots.every((id) => this.#lamport[this.#seq(id)]! <= floor)) return false;
9641153 return this.withProjectionScratch((scratch) => { 9661155 const push = (id: AtomId): void => { @@ -968,7 +1157,10 @@
9681157 scratch.write("seen", id, true); 9691158 scratch.write("stack", String(length++), id); 971− for (const id of roots) push(id);
1160+ for (const id of from) { 1161+ if (id === target) return true; 1162+ if (this.#lamport[this.#seq(id)]! > floor) push(id); 9721164 while (length > 0) { 9731165 const key = String(--length); 9741166 const current = scratch.read("stack", key) as AtomId; @@ -1011,12 +1203,11 @@
10111203 else this.#add(atom); 1014− #add(atom: Atom): void {
1015− if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1016− if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1017− this.#storage.write("ordered-children", "format", 2);
1018− }
1019−
1206+ #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void { 1207+ const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => { 1208+ if (!scratch) return new Set<T>(); 1209+ return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) }; 10201211 validateShape(atom); 10211212 const seq = this.#atoms.length; 10221213 const bad = (why: string): never => { @@ -1024,24 +1215,32 @@
10251216 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`); 1027− const deps = new Set<AtomId>();
1218+ const deps = membership<AtomId>("deps"); 10281219 for (const d of atom.deps) { 10291220 if (!this.has(d)) bad(`dependency ${d} is not in the graph`); 10301221 if (deps.has(d)) bad(`dependency ${d} listed twice`); 1033− for (const d of [...atom.needs, ...atom.resolves]) {
1034− if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1035− }
1224+ for (const list of [atom.needs, atom.resolves]) 1225+ for (const d of list) { 1226+ if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`); 10361228 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`); 10381230 // Everything it touches must come from its closure. Derived deps name the 10391231 // writers directly, so this is usually one lookup per writer. 1040− const below = new Map<AtomId, boolean>();
1232+ const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>(); 1234+ get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)), 1235+ set: (key: AtomId, value: boolean) => { 1236+ if (scratch) scratch.write("below", key, value); 1237+ else memoryBelow!.set(key, value); 10411240 const inClosure = (writer: AtomId): boolean => { 10421241 let hit = below.get(writer); 10431242 if (hit === undefined) { 1044− hit = deps.has(writer) || this.#reaches(deps, writer);
1243+ hit = deps.has(writer) || this.#reaches(atom.deps, writer); 10451244 below.set(writer, hit); @@ -1060,45 +1259,65 @@
10601259 checkLine(run.parent, "an insert"); 1063− const moved = new Set<LineId>();
1262+ const writes = membership<Key>("writes"); 1263+ for (const key of atom.writes) writes.add(key); 1264+ const moved = membership<LineId>("moved"); 10641265 for (const m of atom.moves ?? []) { 10651266 checkLine(m.line, "a move"); 10661267 if (!isStartNode(m.parent)) checkLine(m.parent, "a move"); 10671268 if (m.line === m.parent) bad(`moves ${m.line} after itself`); 10681269 if (moved.has(m.line)) bad(`moves ${m.line} twice`); 10691270 moved.add(m.line); 1070− if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
1271+ if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) { 10711272 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`); 1074− const deleted = new Set<LineId>();
1275+ const deleted = membership<LineId>("deleted"); 10751276 for (const line of atom.deletes) { 10761277 checkLine(line, "a delete"); 10771278 if (deleted.has(line)) bad(`deletes ${line} twice`); 10781279 deleted.add(line); 1080− const writes = new Set(atom.writes);
1081− for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1082− for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
1083− const parsed = parseKey(key);
1084− if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1085− else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1086− checkLine(parsed.node, `key ${key}`);
1281+ for (const line of atom.deletes) 1282+ if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`); 1283+ for (const list of [atom.writes, atom.reads, atom.holds]) 1284+ for (const key of list) { 1285+ const parsed = parseKey(key); 1286+ if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`); 1287+ else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)) 1288+ checkLine(parsed.node, `key ${key}`); 1292+ #add(atom: Atom): void { 1293+ if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) { 1294+ if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption"); 1295+ this.#storage.write("ordered-children", "format", 2); 1298+ if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch)); 1299+ else this.#validateAcceptedAtom(atom); 1300+ const seq = this.#atoms.length; 1301+ const deps = atom.deps; 1302+ const deleted = this.#storage ? undefined : new Set(atom.deletes); 1303+ const writes = this.#storage ? atom.writes : new Set(atom.writes); 1090− const frozen = freezeAtom(
1091− atom,
1092− (id) => this.idOfSeq(seqOf(id)),
1093− (author) => {
1094− if (this.#storage) return author;
1095− let a = this.#authors.get(author);
1096− if (a === undefined) this.#authors.set(author, (a = author));
1097− return a;
1098− },
1099− this.#texts ? this.#reader(seq) : undefined,
1100− this.#lists ? this.#listReader(seq) : undefined,
1101− );
1306+ // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists. 1307+ const frozen = this.#storage 1311+ (id) => this.idOfSeq(seqOf(id)), 1313+ if (this.#storage) return author; 1314+ let a = this.#authors.get(author); 1315+ if (a === undefined) this.#authors.set(author, (a = author)); 1318+ this.#texts ? this.#reader(seq) : undefined, 1319+ this.#lists ? this.#listReader(seq) : undefined, 11021321 this.#atoms.push(this.#storage ? atom : frozen); 11041323 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1); @@ -1106,9 +1325,28 @@
11071326 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist. 11081327 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log. 1109− const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
1110− const deletedN = atom.deletes.map((line) => this.#lineN(line));
1111− this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
1328+ const deletes = (line: LineId | NodeId): boolean => { 1329+ if (isStartNode(line)) return false; 1330+ if (deleted) return deleted.has(line); 1331+ const n = this.#lineN(line); 1332+ return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq; 1334+ const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line)); 1335+ this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined); 1336+ if (this.#storage) { 1337+ const pages = storedLists<number>(this.#storage, "atom-deletes"); 1338+ for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line)); 1339+ this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length); 1341+ const deletedNumbers = function* (graph: Graph) { 1342+ if (deletedN) yield* deletedN; 1343+ else for (const line of atom.deletes) yield graph.#lineN(line); 1345+ for (const n of deletedNumbers(this)) { 1346+ if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq); 1347+ else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq); 1348+ else pushIndex(this.#moreDeleters, n, seq); 11121350 this.#lineBase.push(this.#lineTotal); 11131351 for (const run of atom.inserts) { 11141352 const file = this.#pathOf(run.file); @@ -1119,7 +1357,7 @@
11191357 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert( 11201358 orderedChildKey({ 1122− replaces: deletes?.has(run.parent) ? 1 : 0,
1360+ replaces: deletes(run.parent) ? 1 : 0, 11251363 k: first - this.#lineBase[seq]!, @@ -1137,7 +1375,7 @@
11371375 this.#lineParent.push(parent); 11381376 this.#lineText?.push(run.lines[i]!); 11391377 this.#deleter.push(-1); 1140− this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1378+ this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0); @@ -1152,37 +1390,39 @@
11521390 else pushIndex(this.#relocatedToCode, parentCode, info); 11541392 if (frozen.moves) this.#movers.push(frozen.id); 1155− for (const n of deletedN) {
1156− if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1157− else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1158− else pushIndex(this.#moreDeleters, n, seq);
1159− }
1160− for (const key of new Set(atom.writes)) {
1393+ for (const key of writes) { 11611394 const code = this.#code(key); 1162− if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1163− else pushOne(this.#writers, code, frozen.id);
1395+ if (this.#writersPages) { 1396+ const key = JSON.stringify([typeof code, code]); 1397+ if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id); 1398+ } else pushOne(this.#writers, code, frozen.id); 1165− for (const key of new Set(atom.reads)) {
1400+ for (const key of this.#storage ? atom.reads : new Set(atom.reads)) { 11661401 const code = this.#code(key); 1167− if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1168− else pushOne(this.#readers, code, frozen.id);
1402+ if (this.#readersPages) { 1403+ const key = JSON.stringify([typeof code, code]); 1404+ if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id); 1405+ } else pushOne(this.#readers, code, frozen.id); 1170− for (const key of new Set(atom.holds)) {
1407+ for (const key of this.#storage ? atom.holds : new Set(atom.holds)) { 11711408 const code = this.#code(key); 1172− if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1173− else pushOne(this.#holders, code, frozen.id);
1409+ if (this.#holdersPages) { 1410+ const key = JSON.stringify([typeof code, code]); 1411+ if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id); 1412+ } else pushOne(this.#holders, code, frozen.id); 11751414 for (const d of deps) { 11761415 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id); 11771416 else pushOne(this.#dependents, d, frozen.id); 1179− for (const r of new Set(frozen.resolves)) {
1180− if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1181− else pushOne(this.#resolvers, r, frozen.id);
1418+ for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) { 1419+ if (this.#resolversPages) { 1420+ if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id); 1421+ } else pushOne(this.#resolvers, r, frozen.id); 11831423 const files = new Set<string>(); 11841424 for (const run of atom.inserts) files.add(run.file); 1185− for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1425+ for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!); 11861426 for (const a of frozen.attrs ?? []) files.add(a.file); 11871427 for (const m of frozen.moves ?? []) { 11881428 files.add(this.lineFile(m.line)!); --- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -282,7 +282,12 @@
284284/** Array-shaped access without retaining its historical values in memory. */ 285−export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
285+export function storedArray<T>( 286+ storage: GraphStateStorage, 288+ decode?: (value: T) => T, 289+ encode?: (value: T, key: string) => unknown, 286291 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0; 287292 const read = (key: string) => { 288293 const value = storage.read(name, key) as T; @@ -303,7 +308,7 @@
303308 const index = Number(key); 304309 const size = length(); 305310 if (index > size) throw new Error("stored graph arrays cannot contain gaps"); 306− storage.write(name, key, value);
311+ storage.write(name, key, encode ? encode(value, key) : value); 307312 if (index === size) storage.write(`${name}:meta`, "length", size + 1); @@ -371,6 +376,14 @@
379+ last(key: string): V | undefined { 380+ const count = length(key); 381+ if (count === 0) return undefined; 382+ const values = page(key, Math.floor((count - 1) / pageSize)); 383+ const expected = ((count - 1) % pageSize) + 1; 384+ if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`); 385+ return values[expected - 1]; 374387 append(key: string, value: V): void { 375388 const count = length(key); 376389 const offset = count % pageSize; @@ -532,3 +545,63 @@
532545 for (const key of this.values()) callback.call(thisArg, key, key, this); 549+/** Read-only array access to individually stored values, without copying the list. */ 550+export function readonlyStoredArray<T>( 551+ storage: GraphStateStorage, 553+ decode?: (value: unknown, index: number) => T, 555+ const length = () => { 556+ const count = storage.read(`${name}:meta`, "length"); 557+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length"); 558+ return count as number; 561+ return new Proxy([] as T[], { 562+ get(target, key, receiver) { 563+ if (key === "length") return length(); 564+ if (indexKey(key)) { 565+ if (Number(key) >= length()) return undefined; 566+ const raw = storage.read(name, key); 567+ const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T); 568+ if (value === undefined) throw Error("missing stored list element"); 569+ return value && typeof value === "object" ? Object.freeze(value) : value; 571+ return Reflect.get(target, key, receiver); 574+ return indexKey(key) ? Number(key) < length() : Reflect.has(target, key); 577+ return [...Array.from({ length: length() }, (_, index) => String(index)), "length"]; 579+ getOwnPropertyDescriptor(target, key) { 580+ if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() }; 581+ if (indexKey(key) && Number(key) < length()) { 582+ const raw = storage.read(name, key); 583+ const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T); 584+ if (value === undefined) throw Error("missing stored list element"); 589+ value: value && typeof value === "object" ? Object.freeze(value) : value, 592+ return Reflect.getOwnPropertyDescriptor(target, key); 594+ preventExtensions() { 595+ throw Error("stored list is read-only"); 598+ throw Error("stored list is read-only"); 601+ throw Error("stored list is read-only"); 604+ throw Error("stored list is read-only"); --- /dev/null
+++ b/src/engine/stored-text.ts
@@ -0,0 +1,70 @@
1+import type { GraphStateStorage } from "./state-source.ts"; 3+/** Exact UTF-16 text storage with bounded values; callers choose streaming or full reads. */ 4+export class StoredText { 5+ static readonly chunkCharacters = 16384; 6+ readonly storage: GraphStateStorage; 7+ readonly collection: string; 8+ constructor(storage: GraphStateStorage, collection: string) { 9+ this.storage = storage; 10+ this.collection = collection; 12+ write(key: string, text: string): void { 16+ for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters) 17+ yield text.slice(offset, offset + StoredText.chunkCharacters); 21+ /** Input pieces and the retained buffer are bounded independently of total text length. */ 22+ writeChunks(key: string, chunks: Iterable<string>): void { 23+ this.storage.transaction(() => { 24+ if (this.storage.read(this.collection, key) !== undefined) throw Error("stored text already exists"); 28+ const persist = (chunk: string) => 29+ this.storage.write(`${this.collection}:chunks`, JSON.stringify([key, parts++]), chunk); 30+ for (const chunk of chunks) { 31+ if (typeof chunk !== "string" || chunk.length > StoredText.chunkCharacters) 32+ throw Error("stored text input chunk exceeds bound"); 33+ characters += chunk.length; 34+ if (!Number.isSafeInteger(characters)) throw Error("stored text length overflow"); 36+ if (pending.length >= StoredText.chunkCharacters) { 37+ persist(pending.slice(0, StoredText.chunkCharacters)); 38+ pending = pending.slice(StoredText.chunkCharacters); 41+ if (pending) persist(pending); 42+ this.storage.write(this.collection, key, { format: 1, characters, parts }); 46+ *chunks(key: string): IterableIterator<string> { 47+ const header = this.storage.read(this.collection, key) as 48+ | { format: number; characters: number; parts: number } 51+ header?.format !== 1 || 52+ !Number.isSafeInteger(header.characters) || 53+ header.characters < 0 || 54+ header.parts !== Math.ceil(header.characters / StoredText.chunkCharacters) 56+ throw Error("invalid stored text header"); 57+ for (let part = 0; part < header.parts; part++) { 58+ const chunk = this.storage.read(`${this.collection}:chunks`, JSON.stringify([key, part])); 60+ typeof chunk !== "string" || 61+ chunk.length !== Math.min(StoredText.chunkCharacters, header.characters - part * StoredText.chunkCharacters) 63+ throw Error("incomplete stored text"); 67+ read(key: string): string { 68+ return [...this.chunks(key)].join(""); --- /dev/null
+++ b/src/engine/test/graph-atom-list-integrity.test.ts
@@ -0,0 +1,40 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("stored atom list metadata refuses missing or substituted references", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 12+ graph.add(buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 })); 13+ const keys = Array.from({ length: 513 }, () => lineKey("a0.0")); 32+ const stored = storage.read("atoms", "1") as Record<string, unknown>; 33+ for (const lists of [undefined, {}, { writes: "atom-list:1:reads" }]) { 34+ storage.write("atoms", "1", { ...stored, lists }); 35+ assert.throws(() => new Graph({ storage }).atom("a1"), /stored atom list/); --- /dev/null
+++ b/src/engine/test/graph-atom-list-rollback.test.ts
@@ -0,0 +1,45 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("partial atom-list persistence rolls back and retries on the same graph", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 12+ graph.add(buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 })); 13+ const keys = Array.from({ length: 257 }, () => lineKey("a0.0")); 30+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 31+ const write = storage.write.bind(storage); 32+ storage.write = (collection, key, value) => { 33+ write(collection, key, value); 34+ if (collection === "atom-list:1:writes" && key === "128") throw Error("injected list persistence failure"); 36+ assert.throws(() => graph.add(atom), /injected list persistence failure/); 37+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 38+ assert.equal(graph.size, 1); 39+ storage.write = write; 41+ assert.deepEqual([...new Graph({ storage }).atom("a1").writes], keys); --- /dev/null
+++ b/src/engine/test/graph-atom-lists.test.ts
@@ -0,0 +1,51 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("large persisted atom lists stay out of metadata and read incrementally", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 12+ graph.add(buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 })); 13+ const keys = Array.from({ length: 513 }, () => lineKey("a0.0")); 31+ assert.ok(JSON.stringify(storage.read("atoms", "1")).length < 2048); 33+ const read = storage.read.bind(storage); 34+ storage.read = (collection, key) => { 35+ if (collection.startsWith("atom-list:") && !collection.endsWith(":meta")) items++; 36+ return read(collection, key); 38+ const saved = new Graph({ storage }).atom("a1"); 39+ assert.equal(items, 0); 40+ assert.equal(saved.writes.length, 513); 41+ assert.equal(items, 0); 42+ assert.equal(saved.writes[512], keys[512]); 43+ assert.equal(items, 1); 44+ assert.throws(() => { 45+ (saved.writes as string[])[0] = "changed"; 47+ assert.deepEqual([...saved.writes], keys); --- /dev/null
+++ b/src/engine/test/graph-deletion-pages.test.ts
@@ -0,0 +1,49 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom, LineId } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("persistent delete counts do not load the atom's deleted-line payload", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 14+ { "a.txt": Array.from({ length: 300 }, (_, i) => `line ${i}`).join("\n") }, 15+ { author: "fixture", message: "base", time: 0 }, 18+ const deletes = Array.from({ length: 300 }, (_, i) => `a0.${i}` as LineId); 27+ writes: deletes.map(lineKey), 36+ const reopened = new Graph({ storage }); 37+ const read = storage.read.bind(storage); 38+ storage.read = (collection, key) => { 39+ assert.notEqual(collection, "atom-deletes", "count decoded the full deletion list"); 40+ assert.notEqual(collection, "atom-deletes:pages", "count read deletion payload pages"); 41+ return read(collection, key); 43+ assert.equal(reopened.deleteCount("a1"), 300); 45+ assert.deepEqual(reopened.deletedLines("a1"), deletes); --- /dev/null
+++ b/src/engine/test/graph-deletion-rollback.test.ts
@@ -0,0 +1,54 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom, LineId } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("deletion page failure rolls back acceptance and missing pages fail after reopen", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 14+ { "a.txt": Array.from({ length: 300 }, (_, i) => `line ${i}`).join("\n") }, 15+ { author: "fixture", message: "base", time: 0 }, 18+ const deletes = Array.from({ length: 300 }, (_, i) => `a0.${i}` as LineId); 27+ writes: deletes.map(lineKey), 35+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 36+ const write = storage.write.bind(storage); 37+ storage.write = (collection, key, value) => { 38+ write(collection, key, value); 39+ if (collection === "atom-deletes:pages" && key === JSON.stringify(["1", 1])) 40+ throw Error("injected deletion page failure"); 42+ assert.throws(() => graph.add(atom), /injected deletion page failure/); 43+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 44+ assert.equal(graph.size, 1); 45+ storage.write = write; 47+ assert.equal(new Graph({ storage }).deleteCount("a1"), 300); 48+ assert.deepEqual(new Graph({ storage }).deletedLines("a1"), deletes); 49+ storage.remove("atom-deletes:pages", JSON.stringify(["1", 1])); 50+ assert.throws(() => new Graph({ storage }).deletedLines("a1"), /missing or invalid writer list page/); --- /dev/null
+++ b/src/engine/test/graph-index-dedup.test.ts
@@ -0,0 +1,64 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import { storedLists } from "../state-source.ts"; 6+import type { Atom } from "../types.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("persistent key indexes deduplicate repeated keys without per-atom key sets", () => { 10+ const storage = new SqlState(); 12+ const graph = new Graph({ storage }); 13+ graph.add(buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 })); 14+ const keys = Array.from({ length: 513 }, () => lineKey("a0.0")); 27+ resolves: ["a0", "a0"], 32+ for (const collection of ["writers", "readers", "holders", "resolvers"]) { 33+ const index = storedLists<string>(storage, collection, (key) => key); 35+ for (const key of index.keys()) { 36+ const values = [...index.values(key)]; 37+ const count = values.filter((value) => value === "a1").length; 38+ assert.ok(count <= 1); 41+ assert.equal(matches, 1, collection); 48+test("last list entry reads only its final page and rejects truncated pages", () => { 49+ const storage = new SqlState(); 51+ const list = storedLists<number>(storage, "items"); 52+ for (let i = 0; i < 513; i++) list.append("key", i); 53+ const read = storage.read.bind(storage); 54+ storage.read = (collection, key) => { 55+ if (collection === "items:pages") assert.equal(key, JSON.stringify(["key", 2])); 56+ return read(collection, key); 58+ assert.equal(list.last("key"), 512); 59+ storage.write("items:pages", JSON.stringify(["key", 2]), [512, 513]); 60+ assert.throws(() => list.last("key"), /incomplete writer list page/); --- /dev/null
+++ b/src/engine/test/graph-insertion-integrity.test.ts
@@ -0,0 +1,18 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("stored insertion reads reject missing lines and substituted run references", (t) => { 7+ const storage = new SqlState(); 8+ t.after(() => storage.db.close()); 9+ const lines = Array.from({ length: 257 }, (_, i) => (i === 128 ? "x".repeat(40000) : `line ${i}`)); 10+ const atom = buildBase({ "a.txt": lines.join("\n") }, { author: "fixture", message: "base", time: 0 }); 11+ new Graph({ storage }).add(atom); 12+ assert.equal(new Graph({ storage }).atom("a0").inserts[0]!.lines[128], lines[128]); 13+ storage.remove("atom-inserts:0:lines:0", "12"); 14+ assert.throws(() => new Graph({ storage }).atom("a0").inserts[0]!.lines[12], /missing stored list element/); 15+ const run = storage.read("atom-inserts:0", "0") as Record<string, unknown>; 16+ storage.write("atom-inserts:0", "0", { ...run, lines: "unrelated" }); 17+ assert.throws(() => new Graph({ storage }).atom("a0").inserts[0], /invalid stored insertion run/); --- /dev/null
+++ b/src/engine/test/graph-insertion-runs.test.ts
@@ -0,0 +1,24 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("many insertion runs reopen without fetching every run", (t) => { 7+ const storage = new SqlState(); 8+ t.after(() => storage.db.close()); 9+ const files = Object.fromEntries(Array.from({ length: 257 }, (_, i) => [`file-${i}.txt`, `value ${i}`])); 10+ const atom = buildBase(files, { author: "fixture", message: "many files", time: 0 }); 11+ new Graph({ storage }).add(atom); 12+ assert.ok(JSON.stringify(storage.read("atoms", "0")).length < 2048); 13+ const read = storage.read.bind(storage); 15+ storage.read = (collection, key) => { 16+ if (collection === "atom-inserts:0") runs++; 17+ return read(collection, key); 19+ const saved = new Graph({ storage }).atom("a0"); 20+ assert.equal(saved.inserts.length, atom.inserts.length); 21+ assert.equal(runs, 0); 22+ assert.deepEqual([...saved.inserts[256]!.lines], atom.inserts[256]!.lines); 23+ assert.equal(runs, 1); --- /dev/null
+++ b/src/engine/test/graph-insertion-storage.test.ts
@@ -0,0 +1,52 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("persisted insertion lines stay out of atom metadata", (t) => { 7+ const storage = new SqlState(); 8+ t.after(() => storage.db.close()); 9+ const text = Array.from({ length: 513 }, (_, i) => `line ${i}\n`).join(""); 10+ const graph = new Graph({ storage }); 11+ const atom = buildBase({ "a.txt": text }, { author: "fixture", message: "base", time: 0 }); 12+ const oracle = new Graph(); 15+ const bytes = Buffer.byteLength(JSON.stringify(storage.read("atoms", "0"))); 16+ assert.ok(bytes < 2048, `atom metadata retained ${bytes} bytes for 513 insertion lines`); 17+ assert.deepEqual([...new Graph({ storage }).atom("a0").inserts[0]!.lines], oracle.atom("a0").inserts[0]!.lines); 18+ const read = storage.read.bind(storage); 20+ storage.read = (collection, key) => { 21+ if (collection === "atom-inserts:0:lines:0") lineReads++; 22+ return read(collection, key); 24+ const saved = new Graph({ storage }).atom("a0"); 25+ assert.equal(lineReads, 0); 26+ assert.equal(saved.inserts[0]!.lines.length, 513); 27+ assert.equal(lineReads, 0); 28+ assert.equal(saved.inserts[0]!.lines[512], oracle.atom("a0").inserts[0]!.lines[512]); 29+ assert.equal(lineReads, 1); 32+test("partial insertion persistence rolls back and retries on the same graph", (t) => { 33+ const storage = new SqlState(); 34+ t.after(() => storage.db.close()); 35+ const graph = new Graph({ storage }); 36+ const atom = buildBase( 37+ { "a.txt": Array.from({ length: 513 }, (_, i) => `line ${i}\n`).join("") }, 38+ { author: "fixture", message: "base", time: 0 }, 40+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 41+ const write = storage.write.bind(storage); 42+ storage.write = (collection, key, value) => { 43+ write(collection, key, value); 44+ if (collection === "atom-inserts:0:lines:0" && key === "128") throw Error("injected insertion failure"); 46+ assert.throws(() => graph.add(atom), /injected insertion failure/); 47+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 48+ assert.equal(graph.size, 0); 49+ storage.write = write; 51+ assert.deepEqual([...new Graph({ storage }).atom("a0").inserts[0]!.lines], atom.inserts[0]!.lines); --- /dev/null
+++ b/src/engine/test/graph-long-text.test.ts
@@ -0,0 +1,123 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../../worker/project/project.ts"; 4+import { Graph } from "../graph.ts"; 5+import { SqlState } from "./storage-helper.ts"; 7+test("persistent graph stores long lines in chunks and reopens exact text", () => { 8+ const storage = new SqlState(); 10+ const memory = new MemoryStore(); 11+ const value = `${"x".repeat(100000)}\uD83D\uDE00`; 12+ new Project(memory).init({ "a.txt": value }, 0); 13+ const entry = memory.entries[0]!; 14+ assert.equal(entry.type, "init"); 15+ if (entry.type !== "init") throw Error("expected init"); 16+ new Graph({ storage }).add(entry.atom); 17+ assert.deepEqual(storage.read("line-text", "0"), { format: 1, text: JSON.stringify(["0", 0]) }); 18+ assert.equal(new Graph({ storage }).lineText("a0.0"), value); 20+ (storage.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection = 'atom-text:long:chunks'").get()! 28+import { SqliteWriterState } from "../../../server/src/writer-host.ts"; 29+import { memoryStorage } from "../../../server/test/helpers.ts"; 31+test("persistent atom metadata accepts text beyond the generic state limit", (t) => { 32+ const database = memoryStorage(); 33+ t.after(() => database.db.close()); 34+ SqliteWriterState.initialize(database); 35+ const storage = new SqliteWriterState(database, "long-atom"); 36+ const memory = new MemoryStore(); 37+ const value = "x".repeat(8100000); 38+ new Project(memory).init({ "large.txt": value }, 0); 39+ const entry = memory.entries[0]!; 40+ if (entry.type !== "init") throw Error("expected init"); 41+ new Graph({ storage }).add(entry.atom); 42+ assert.ok(JSON.stringify(storage.read("atoms", "0")).length < 4096); 43+ const read = storage.read.bind(storage); 45+ t.mock.method(storage, "read", (collection: string, key: string) => { 46+ if (collection === "atom-text:long:chunks") textReads++; 47+ return read(collection, key); 49+ const graph = new Graph({ storage }); 50+ const atom = graph.atom("a0"); 51+ assert.equal(textReads, 0, "reading atom metadata must not load long text"); 52+ assert.equal(atom.inserts[0]!.lines[0], value); 53+ assert.ok(textReads > 0); 54+ assert.equal(graph.lineText("a0.0"), value); 58+ "SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'long-atom' AND collection = 'atom-text:long:chunks' AND part = -1", 61+ Math.ceil(value.length / 16384), 66+ "SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'long-atom' AND collection = 'line-text:long:chunks'", 73+test("long atom acceptance rolls back partial chunks and detects missing text", (t) => { 74+ const storage = new SqlState(); 75+ t.after(() => storage.db.close()); 76+ const memory = new MemoryStore(); 77+ const value = "z".repeat(100000); 78+ new Project(memory).init({ "a.txt": value }, 0); 79+ const entry = memory.entries[0]!; 80+ if (entry.type !== "init") throw Error("expected init"); 81+ const graph = new Graph({ storage }); 82+ const rows = () => storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 83+ const before = rows(); 84+ const write = storage.write.bind(storage); 86+ const failure = t.mock.method(storage, "write", (collection: string, key: string, value: unknown) => { 87+ write(collection, key, value); 88+ if (collection === "atom-text:long:chunks" && ++chunks === 2) throw Error("injected partial atom text"); 90+ assert.throws(() => graph.add(entry.atom), /partial atom text/); 91+ assert.deepEqual(rows(), before); 92+ assert.equal(graph.size, 0); 93+ failure.mock.restore(); 94+ graph.add(entry.atom); 95+ assert.equal(graph.lineText("a0.0"), value); 96+ const textKey = JSON.stringify(["0", 0]); 97+ storage.remove("atom-text:long:chunks", JSON.stringify([textKey, 1])); 98+ const reopened = new Graph({ storage }); 99+ assert.throws(() => reopened.lineText("a0.0"), /incomplete stored text/); 100+ assert.throws(() => reopened.atom("a0").inserts[0]!.lines[0], /incomplete stored text/); 103+test("persistent graph detaches accepted lists without freezing a second input copy", () => { 104+ const storage = new SqlState(); 106+ const memory = new MemoryStore(); 107+ new Project(memory).init({ "a.txt": "before\nsecond" }, 0); 108+ const entry = memory.entries[0]!; 109+ if (entry.type !== "init") throw Error("expected init"); 110+ const atom = structuredClone(entry.atom); 111+ const expected = structuredClone(atom); 112+ const graph = new Graph({ storage }); 114+ (atom.inserts[0]!.lines as string[])[0] = "changed"; 115+ (atom.writes as string[]).length = 0; 116+ for (const loaded of [graph, new Graph({ storage })]) { 117+ assert.deepEqual(JSON.parse(JSON.stringify(loaded.atom("a0"))), expected); 118+ assert.equal(loaded.lineText("a0.0"), expected.inserts[0]!.lines[0]); --- /dev/null
+++ b/src/engine/test/graph-move-write-membership.test.ts
@@ -0,0 +1,41 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { gapKey, posKey } from "../keys.ts"; 5+import type { Atom } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("move validation uses indexed write membership without rescanning the write list", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 12+ graph.add(buildBase({ "a.txt": "one\ntwo" }, { author: "fixture", message: "base", time: 0 })); 13+ const writes = [posKey("a0.1"), gapKey("a0.0")]; 14+ writes.includes = () => { 15+ throw Error("whole write list scan forbidden"); 32+ moves: [{ line: "a0.1", parent: "a0.0" }], 35+ assert.equal(new Graph({ storage }).size, 2); 36+ assert.throws(() => graph.add({ ...atom, id: "a2", seq: 2, writes: [posKey("a0.1")] }), /without writing/); 37+ assert.equal(graph.size, 2); --- /dev/null
+++ b/src/engine/test/graph-replacement-membership.test.ts
@@ -0,0 +1,42 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import { lineKey } from "../keys.ts"; 5+import type { Atom } from "../types.ts"; 6+import { SqlState } from "./storage-helper.ts"; 8+test("replacement membership distinguishes first, repeated and previous deletions", () => { 9+ const storage = new SqlState(); 11+ const graph = new Graph({ storage }); 12+ const oracle = new Graph(); 13+ const base = buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 }); 16+ for (let seq = 1; seq <= 3; seq++) { 17+ const deleting = seq < 3; 22+ message: "replacement", 24+ inserts: [{ file: "a.txt", parent: "a0.0", lines: [`new ${seq}`] }], 25+ deletes: deleting ? ["a0.0"] : [], 26+ writes: deleting ? [lineKey("a0.0")] : [], 32+ deps: [`a${seq - 1}`], 36+ assert.equal(graph.replaces(`a${seq}.0`), deleting); 37+ assert.equal(new Graph({ storage }).replaces(`a${seq}.0`), oracle.replaces(`a${seq}.0`)); --- /dev/null
+++ b/src/engine/test/graph-validation-scratch.test.ts
@@ -0,0 +1,47 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph } from "../index.ts"; 4+import type { Atom } from "../types.ts"; 5+import { SqlState } from "./storage-helper.ts"; 7+test("persistent atom validation uses rollback scratch for memberships", () => { 8+ const storage = new SqlState(); 10+ const graph = new Graph({ storage }); 11+ graph.add(buildBase({ "a.txt": "base" }, { author: "fixture", message: "base", time: 0 })); 28+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 29+ assert.throws(() => graph.add({ ...atom, deps: ["a0", "a0"] }), /listed twice/); 30+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 31+ let scratchWrites = 0; 32+ const write = storage.write.bind(storage); 33+ storage.write = (collection, key, value) => { 34+ if (collection.startsWith("projection-scratch:") && collection.endsWith(":deps")) scratchWrites++; 35+ write(collection, key, value); 38+ assert.ok(scratchWrites > 0); 40+ storage.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection-scratch:%'").get()!.n, 43+ assert.equal(new Graph({ storage }).size, 2); --- a/src/engine/test/projection-locator.test.ts
+++ b/src/engine/test/projection-locator.test.ts
@@ -103,3 +103,30 @@
107+test("multi-key locator updates match sequential sparse edits and retain previous roots", () => { 108+ const db = new SqlState(); 110+ const batched = new ProjectionLocator(db, "multi", decode); 111+ const sequential = new ProjectionLocator(db, "oracle", decode); 112+ let left: number | null = null, 113+ right: number | null = null; 115+ const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0); 116+ const keys = [0, 0xffffffff, 1, 16, 255, 256, ...Array.from({ length: 60 }, random)]; 117+ for (let round = 0; round < 8; round++) { 118+ const edits: [number, number][] = Array.from({ length: 64 }, (_, i) => [ 119+ keys[random() % keys.length]!, 122+ const prior: number | null = left; 123+ const oldEntries: (readonly [number, number])[] = [...batched.entries(prior)]; 124+ left = batched.setMany(left, edits); 125+ for (const [key, value] of edits) right = sequential.set(right, key, value); 126+ assert.deepEqual([...batched.entries(left)], [...sequential.entries(right)]); 127+ assert.deepEqual([...batched.entries(prior)], oldEntries); --- a/src/engine/test/projection-marker.test.ts
+++ b/src/engine/test/projection-marker.test.ts
@@ -118,3 +118,50 @@
118118 storage.db.close(); 122+test("visibility batches roll back earlier batches and retry with exact line parity", (t) => { 123+ const db = new SqlState(); 124+ t.after(() => db.db.close()); 125+ const text = Array.from({ length: 35 }, (_, n) => `line ${n}\n`).join(""); 126+ const repo = Repo.init({ "f.txt": text }); 127+ const graph = new Graph({ storage: new CachedStateStorage(db) }); 128+ graph.add(repo.graph.atom("a0")); 129+ const p = new MarkerProjection(db, graph, "f.txt", "batch-failure"); 130+ const initial = p.apply(p.empty(), repo.graph.atom("a0")); 131+ const originalLines = p.lines(initial, "f.txt"); 132+ const atom = repo.edit({ edits: [{ file: "f.txt", old: text, new: "" }] }); 134+ const rows = () => db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 135+ const before = rows(); 136+ const original = p.sequence.updateMany.bind(p.sequence); 137+ const sizes: number[] = []; 142+ (state: Parameters<typeof original>[0], operations: Parameters<typeof original>[1]) => { 143+ const next = original(state, operations); 144+ if (operations.every((op) => op.kind === "visibility")) { 145+ sizes.push(operations.length); 146+ if (fail && sizes.length === 2) throw Error("second visibility batch failure"); 151+ assert.throws(() => p.apply(initial, atom), /second visibility batch/); 152+ assert.deepEqual(sizes, [16, 16]); 153+ assert.deepEqual(rows(), before); 154+ assert.deepEqual(p.lines(initial, "f.txt"), originalLines); 157+ const next = p.apply(initial, atom); 158+ assert.deepEqual(sizes, [16, 16, 3]); 160+ p.lines(next, "f.txt"), 164+ .map((line) => line.id), 166+ assert.deepEqual(p.lines(initial, "f.txt"), originalLines); --- a/src/engine/test/projection-priority.test.ts
+++ b/src/engine/test/projection-priority.test.ts
@@ -51,3 +51,127 @@
55+test("priority allocation rolls back a failed final counter and retries without collisions", (t) => { 56+ const storage = new SqlState(); 57+ t.after(() => storage.db.close()); 58+ const index = new ProjectionPriority(storage, "counter-retry", decode); 59+ const key = "1".repeat(57); 60+ const root = index.insert(null, key, 1); 61+ const rows = () => storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 62+ const before = rows(); 63+ const original = storage.write.bind(storage); 65+ t.mock.method(storage, "write", (collection: string, key: string, value: unknown) => { 66+ original(collection, key, value); 67+ if (key === "next" && fail) throw Error("final allocation counter failure"); 69+ assert.throws(() => index.insert(root, "2".repeat(57), 2), /final allocation counter/); 70+ assert.deepEqual(rows(), before); 71+ assert.equal(index.before(root, "f".repeat(57)), 1); 73+ const next = index.insert(root, "2".repeat(57), 2); 74+ assert.equal(index.before(next, "f".repeat(57)), 2); 75+ assert.equal(index.before(root, "f".repeat(57)), 1); 76+ const beforeRemove = rows(); 78+ assert.throws(() => index.remove(next, "2".repeat(57)), /final allocation counter/); 79+ assert.deepEqual(rows(), beforeRemove); 81+ const removed = index.remove(next, "2".repeat(57)); 82+ assert.equal(index.before(removed, "f".repeat(57)), 1); 85+test("compressed priority updates legacy depth paths without changing old roots", (t) => { 86+ const storage = new SqlState(); 87+ t.after(() => storage.db.close()); 88+ const collection = 'experimental-priority:"legacy"'; 89+ const key = "1".repeat(57); 90+ storage.write(collection, "57", { format: 1, kind: "leaf", depth: 57, value: 1 }); 91+ for (let depth = 56; depth >= 0; depth--) 92+ storage.write(collection, String(depth), { 96+ children: { [key[depth]!]: depth + 1 }, 98+ storage.write(collection, "next", 58); 99+ const index = new ProjectionPriority(storage, "legacy", decode); 100+ assert.equal(index.before(0, "f".repeat(57)), 1); 101+ const mixed = index.insert(0, "1".repeat(56) + "2", 2); 102+ assert.equal(index.before(mixed, "f".repeat(57)), 2); 103+ assert.equal(index.before(mixed, "1".repeat(56) + "2"), 1); 104+ assert.equal(index.before(0, "f".repeat(57)), 1); 105+ const removed = index.remove(mixed, key); 106+ assert.equal(index.before(removed, "f".repeat(57)), 2); 107+ assert.equal(index.remove(removed, "1".repeat(56) + "2"), null); 108+ assert.equal(index.before(0, "f".repeat(57)), 1); 111+test("compressed priority matches a sorted oracle across varied prefixes and removals", (t) => { 112+ const storage = new SqlState(); 113+ t.after(() => storage.db.close()); 114+ const index = new ProjectionPriority(storage, "varied", decode); 115+ const oracle = new Map<string, number>(); 116+ let root: number | null = null; 118+ const randomKey = () => 119+ Array.from({ length: 57 }, () => { 120+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; 121+ return (seed >>> 28).toString(16); 126+ ...Array.from({ length: 128 }, randomKey), 127+ ...Array.from({ length: 32 }, (_, n) => "a".repeat(55) + n.toString(16).padStart(2, "0")), 129+ const verify = () => { 130+ const sorted = [...oracle.keys()].sort(); 131+ for (const key of [...keys, randomKey()]) { 132+ const before = sorted.filter((candidate) => candidate < key).at(-1); 133+ assert.equal(index.before(root, key), before === undefined ? undefined : oracle.get(before)); 136+ for (const [n, key] of keys.entries()) { 137+ root = index.insert(root, key, n); 139+ if (n % 23 === 0) verify(); 142+ for (const [n, key] of keys.entries()) { 143+ root = index.remove(root, key); 145+ if (n % 19 === 0) verify(); 147+ assert.equal(root, null); 151+test("compressed priority rejects malformed prefixes and cyclic child edges", (t) => { 152+ const storage = new SqlState(); 153+ t.after(() => storage.db.close()); 154+ const collection = 'experimental-priority:"corrupt"'; 155+ const index = new ProjectionPriority(storage, "corrupt", decode); 156+ const first = index.insert(null, "1".repeat(57), 1); 157+ const root = index.insert(first, "2".repeat(57), 2); 158+ const saved = storage.read(collection, String(root)); 159+ for (const node of [ 160+ { format: 2, kind: "branch", prefix: "", children: { "1": root, "2": first } }, 161+ { format: 2, kind: "branch", prefix: "x", children: { "1": first, "2": first } }, 162+ { format: 2, kind: "branch", prefix: "", children: { "1": first } }, 163+ { format: 2, kind: "leaf", prefix: "1", value: 1 }, 164+ { format: 3, kind: "leaf", prefix: "1".repeat(57), value: 1 }, 166+ storage.write(collection, String(root), node); 167+ assert.throws(() => index.before(root, "f".repeat(57)), /invalid priority/); 169+ storage.write(collection, String(root), saved); 170+ const branch = saved as { children: Record<string, number> }; 171+ const child = branch.children["2"]!; 172+ const leaf = storage.read(collection, String(child)); 173+ storage.write(collection, String(child), { format: 2, kind: "leaf", prefix: "3".repeat(57), value: 2 }); 174+ assert.throws(() => index.before(root, "f".repeat(57)), /invalid priority/); 175+ storage.write(collection, String(child), leaf); 176+ assert.equal(index.before(root, "f".repeat(57)), 2); --- /dev/null
+++ b/src/engine/test/stored-list-array.test.ts
@@ -0,0 +1,24 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { readonlyStoredArray, storedArray } from "../state-source.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("readonly stored lists preserve array traversal and explicit enumeration", () => { 7+ const storage = new SqlState(); 9+ storedArray<number>(storage, "numbers").push(10, 20, 30); 10+ const values = readonlyStoredArray<number>(storage, "numbers"); 11+ assert.equal(Array.isArray(values), true); 13+ values.map((value) => value + 1), 16+ assert.deepEqual([...values], [10, 20, 30]); 17+ assert.equal(JSON.stringify(values), "[10,20,30]"); 18+ assert.deepEqual(Object.keys(values), ["0", "1", "2"]); 19+ assert.equal(Object.getOwnPropertyDescriptor(values, "1")?.value, 20); 20+ assert.throws(() => Object.defineProperty(values, "0", { value: 99 }), /read-only/); --- /dev/null
+++ b/src/engine/test/stored-list-integrity.test.ts
@@ -0,0 +1,21 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { readonlyStoredArray, storedArray } from "../state-source.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("referenced stored lists reject missing metadata and missing elements", () => { 7+ const storage = new SqlState(); 9+ assert.throws(() => readonlyStoredArray(storage, "missing"), /stored list/); 10+ const values = storedArray<number>(storage, "values"); 11+ values.push(1, 2, 3); 12+ const readonly = readonlyStoredArray<number>(storage, "values"); 13+ assert.equal(readonly.length, 3); 14+ storage.remove("values", "1"); 15+ assert.throws(() => readonly[1], /stored list/); 16+ storage.remove("values:meta", "length"); 17+ assert.throws(() => readonly.length, /stored list/); --- /dev/null
+++ b/src/engine/test/stored-text.test.ts
@@ -0,0 +1,68 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { StoredText } from "../stored-text.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("stored text preserves long lines and split surrogate pairs with bounded values", () => { 7+ const state = new SqlState(); 9+ const text = new StoredText(state, "text"); 10+ const value = "x".repeat(StoredText.chunkCharacters - 1) + "\uD83D\uDE00" + "y".repeat(8100000); 11+ text.write("line", value); 13+ for (const chunk of text.chunks("line")) { 14+ assert.ok(chunk.length <= StoredText.chunkCharacters); 15+ count += chunk.length; 17+ assert.equal(count, value.length); 18+ assert.equal(text.read("line"), value); 19+ assert.throws(() => text.write("line", "overwrite"), /already exists/); 20+ text.write("empty", ""); 21+ assert.equal(text.read("empty"), ""); 22+ const before = state.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 23+ state.failWrite = state.writes + 2; 24+ assert.throws(() => text.write("failure", value), /injected/); 25+ assert.deepEqual(state.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 26+ state.failWrite = Infinity; 27+ state.remove("text:chunks", JSON.stringify(["line", 1])); 28+ assert.throws(() => text.read("line"), /incomplete/); 34+test("streamed text repacks small chunks and rolls back interrupted input", () => { 35+ const state = new SqlState(); 37+ const text = new StoredText(state, "stream"); 38+ const value = `${"a".repeat(20000)}\uD83D\uDE00${"b".repeat(20000)}`; 42+ for (const unit of value.split("")) yield unit; 45+ assert.equal(text.read("unicode"), value); 46+ const rows = () => state.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 47+ const before = rows(); 53+ yield "x".repeat(StoredText.chunkCharacters); 55+ throw Error("input interrupted"); 60+ assert.deepEqual(rows(), before); 61+ assert.throws(() => text.writeChunks("oversized", ["x".repeat(StoredText.chunkCharacters + 1)]), /exceeds bound/); 62+ assert.deepEqual(rows(), before); 63+ text.writeChunks("interrupted", ["retry"]); 64+ assert.equal(text.read("interrupted"), "retry"); --- a/worker/project/collisions.ts
+++ b/worker/project/collisions.ts
@@ -68,26 +68,44 @@
6868 * atom key, retaining no candidate set proportional to historical claims. */ 6969function* orderedClaimants(g: Graph, streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> { 71− const heads = streams.map((stream) => stream.next());
71+ type Head = { id: AtomId; seq: number; stream: number }; 72+ const heap: Head[] = []; 73+ const less = (a: Head, b: Head) => a.seq < b.seq || (a.seq === b.seq && a.stream < b.stream); 74+ const push = (head: Head) => { 75+ let at = heap.length; 78+ const parent = (at - 1) >>> 1; 79+ if (!less(head, heap[parent]!)) break; 80+ heap[at] = heap[parent]!; 85+ const advance = (stream: number) => { 86+ const next = streams[stream]!.next(); 87+ if (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream }); 89+ for (let stream = 0; stream < streams.length; stream++) advance(stream); 73− for (;;) {
74− let best = -1;
75− let seq = Infinity;
76− for (let i = 0; i < heads.length; i++) {
77− const head = heads[i]!;
78− if (head.done) continue;
79− const current = g.atom(head.value).seq;
80− if (current < seq) {
81− best = i;
82− seq = current;
91+ while (heap.length) { 92+ const head = heap[0]!; 93+ const tail = heap.pop()!; 96+ while (at * 2 + 1 < heap.length) { 97+ let child = at * 2 + 1; 98+ if (child + 1 < heap.length && less(heap[child + 1]!, heap[child]!)) child++; 99+ if (!less(heap[child]!, tail)) break; 100+ heap[at] = heap[child]!; 85− if (best < 0) return;
86− const id = heads[best]!.value!;
87− heads[best] = streams[best]!.next();
88− if (seq === previous) continue;
89− previous = seq;
90− yield id;
105+ advance(head.stream); 106+ if (head.seq === previous) continue; 107+ previous = head.seq; 93111 for (const stream of streams) stream.return?.(); --- a/worker/project/land.ts
+++ b/worker/project/land.ts
@@ -2,11 +2,12 @@
22// the host is Project. Ingest and pluck call landDraft, the inner step. 44import { type AtomId, buildAtom, type Graph, type ReadView } from "../../src/engine/index.ts"; 5+import { differenceSet, StableOverlaySet, unionOverlay } from "../../src/engine/state-source.ts"; 56import type { Pair } from "./collisions.ts"; 67import type { DefinitionRule } from "./definition-rule.ts"; 78import { ProjectError } from "./project-error.ts"; 89import type { AgentState, Collision, Entry, LandAnswer } from "./project-types.ts"; 9−import { SHARED, type Space, sharedBaseOf } from "./spaces.ts";
10+import { SHARED, SharedAdditions, type Space, sharedBaseOf } from "./spaces.ts"; 1112/** What landing a named draft needs from a project. */ 1213export interface LandHost { @@ -23,6 +24,7 @@
2324 setOf(space: Space): ReadonlySet<AtomId>; 2425 at(space: Space, version: number): ReadonlySet<AtomId>; 2526 view(set: ReadonlySet<AtomId>): ReadView; 27+ viewAt(space: Space, version: number, changes?: readonly AtomId[]): ReadView; 2628 sharedView(): ReadView; 2729 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[]; 2830 describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision; @@ -70,21 +72,32 @@
73−): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
75+): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } { 7476 const shared = host.shared(); 7577 const base = host.at(shared, sharedBaseOf(space)); 76− const own = new Set(changes);
77− const union = new Set([...shared.own, ...changes]);
78+ const own = new StableOverlaySet(changes); 79+ const current = host.at(shared, host.version()); 80+ const union = unionOverlay(current, changes); 7881 // The draft's own changes (some already plucked into shared) are never newer work to it. 79− const newer = new Set([...shared.own].filter((id) => !base.has(id) && !own.has(id) && !space.own.has(id)));
82+ const newer = differenceSet( 84+ shared.membershipVersion 85+ ? new SharedAdditions(shared, sharedBaseOf(space), base, current) 86+ : differenceSet(current, base), 8091 // A pluck is checked as the draft's base plus only the plucked changes. 81− const draftView = host.view(pick ? new Set([...base, ...changes]) : host.setOf(space));
92+ const draftView = pick 93+ ? host.viewAt(shared, sharedBaseOf(space), changes) 94+ : host.viewAt(space, space.versions.length - 1); 8295 const describeLand = (p: Pair): Collision => host.describe(p, draftView, host.sharedView(), SHARED); 8396 const collisions = [ 8497 ...host.pairs(changes, newer, union).map(describeLand), 87− .collisions(own, draftView, host.view(base), host.sharedView(), newer, SHARED)
100+ .collisions(own, draftView, host.viewAt(shared, sharedBaseOf(space)), host.sharedView(), newer, SHARED) 88101 .map((d) => d.collision), 90103 return { collisions, newer, union }; @@ -107,9 +120,15 @@
107120 if (changes.length === 0) return { ok: true, version: host.version(), changes: 0 }; 108121 const { collisions, newer, union } = landCollisions(host, space, changes, !!pick); 109122 if (collisions.length > 0) return host.refuse(agent, space, "land", time, collisions, entries); 110− const seen = host.pairs(changes, new Set([...shared.own].filter((id) => !newer.has(id))), union);
123+ const seen = host.pairs(changes, differenceSet(host.at(shared, host.version()), newer), union); 111124 const resolves = [...new Set(seen.flatMap((p) => [p.yours, p.theirs]))]; 112− const tie = buildAtom(host.view(union), { author: agent.name, message, time, needs: changes, resolves });
125+ const tie = buildAtom(host.viewAt(shared, host.version(), changes), { 113132 host.requireClosed(tie, union); 114133 const version = host.version() + 1; 115134 // A pluck leaves the draft where it is: the rest of it lands later. --- a/worker/project/news.ts
+++ b/worker/project/news.ts
@@ -280,18 +280,22 @@
282282 const just = new Set(space.versions[version]!.atoms); 283− // Most publishes change no definition; then only the same-lines rule can bring news.
284− const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]);
285− const before = definitionsIn(host.viewAt(space, version - 1), touched);
286− const after = definitionsIn(host.viewAt(space, last(space)), touched);
287− const changedDefinitions = [...new Set([...before.keys(), ...after.keys()])].some(
288− (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),
289− );
283+ let changedDefinitions: boolean | undefined; 284+ const compareDefinitions = () => { 285+ // Most publishes change no definition; then only the same-lines rule can bring news. 286+ const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]); 287+ const before = definitionsIn(host.viewAt(space, version - 1), touched); 288+ const after = definitionsIn(host.viewAt(space, last(space)), touched); 289+ return [...new Set([...before.keys(), ...after.keys()])].some( 290+ (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []), 290293 for (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) { 291294 if (agent === publisher || agent.space !== space.name) continue; 292295 const draft = host.draft(agent); 293296 if (draft.length === 0) continue; 294297 const lines = pairsIn(host.graph, draft, just, unionOverlay(host.setOf(space), draft)); 298+ changedDefinitions ??= compareDefinitions(); 295299 const defs = changedDefinitions 296300 ? host.definitionCollisions(agent, host.newerFor(agent)).filter((d) => just.has(d.by)) --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -228,6 +228,19 @@
231+/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */ 232+export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry }; 233+function adoptionFrameBytes(frame: WriterAdoptionFrame): number { 234+ return "json" in frame 235+ ? typeof frame.json === "string" 236+ ? new TextEncoder().encode(frame.json).byteLength 240+function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry { 241+ return "json" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry; 231244export class Project { 232245 readonly #store: ProjectStore; 233246 readonly #writerStorage?: GraphStateStorage; @@ -480,6 +493,46 @@
480493 return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN); 496+ /** Open a host-verified historical prefix. Its state must be immutable and 497+ * scoped to canonical authority; adoption readiness describes the live writer, 498+ * not whether this individual prefix has a complete checkpoint. */ 499+ static openHistorical( 500+ storage: GraphStateStorage, 502+ scratch: GraphStateStorage, 503+ assertScope: () => void = () => { 504+ storage.read("project:meta", "checkpoint"); 506+ readViewProvider?: ProjectOptions["readViewProvider"], 508+ const refuse = (): never => { 509+ throw new Error("historical project is read-only"); 511+ const selected = (collection: string) => { 512+ // Revalidate the historical scope even when accessing derived scratch. 514+ return collection.startsWith("projection-scratch:") ? scratch : storage; 516+ return Project.#openWriter( 519+ read: (collection, key) => selected(collection).read(collection, key), 520+ entries: (collection) => selected(collection).entries(collection), 521+ write: (collection, key, value) => { 522+ if (selected(collection) !== scratch) refuse(); 523+ scratch.write(collection, key, value); 525+ remove: (collection, key) => { 526+ if (selected(collection) !== scratch) refuse(); 527+ scratch.remove(collection, key); 529+ transaction: (body) => storage.transaction(() => scratch.transaction(body)), 532+ { readViewProvider }, 484537 * Derive one bounded page from the host's canonical frames. The host reads 485538 * those frames from its own log and revalidates the source inside this same @@ -490,10 +543,15 @@
491544 source: WriterSource; 493− frames: Iterable<{ seq: number; json: string }>;
546+ frames: Iterable<WriterAdoptionFrame>; 494547 maxEntries: number; 549+ /** The host supplies disk-backed decoded entries and verified byte counts. */ 550+ decodedFrames?: boolean; 496551 currentSource(): WriterSource; 552+ /** Select the host's derived historical revision before applying a frame. 553+ * Each selected revision receives a complete Project checkpoint. */ 554+ beginRevision?(logLength: number): void; 498556 options: Omit<ProjectOptions, "writerStorage"> = {}, 499557 ): { next: number; ready: boolean; entries: number; bytes: number } { @@ -509,7 +567,7 @@
509567 input.maxEntries > 256 || 510568 !Number.isSafeInteger(input.maxBytes) || 511569 input.maxBytes < 1 || 512− input.maxBytes > 8_000_000
570+ (input.maxBytes > 8_000_000 && input.decodedFrames !== true) 514572 throw new Error("invalid writer adoption bounds or source"); 515573 return storage.transaction(() => { @@ -533,19 +591,24 @@
535593 for (const frame of input.frames) { 594+ if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames"); 595+ const size = adoptionFrameBytes(frame); 537597 count >= input.maxEntries || 538598 frame.seq !== input.from + count || 539599 frame.seq >= input.source.logLength || 540− typeof frame.json !== "string" ||
541− frame.json.length > input.maxBytes - bytes
600+ !Number.isSafeInteger(size) || 602+ size > input.maxBytes - bytes 543604 throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame"); 544− bytes += new TextEncoder().encode(frame.json).byteLength;
545606 if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound"); 546− project.#apply(JSON.parse(frame.json) as Entry);
607+ input.beginRevision?.(frame.seq + 1); 608+ project.#apply(adoptionFrameEntry(frame)); 547609 project.#stored++; 548610 project.#persistMutable(); 611+ if (input.beginRevision) project.#writeCheckpoint(); 551614 if (count === 0) throw new Error("writer adoption page must advance"); @@ -563,9 +626,81 @@
566− * Apply more stored entries to a copy loaded for reading (#41, replay):
567− * scrubbing forward applies only what's new. Never for the live project.
629+ * Extend derived historical indexes from an already checkpointed prefix. 630+ * The host supplies only new canonical frames inside its commit transaction. 632+ static extendHistoricalPage( 633+ storage: GraphStateStorage, 636+ frames: Iterable<WriterAdoptionFrame>; 639+ /** The host supplies disk-backed decoded entries and verified byte counts. */ 640+ decodedFrames?: boolean; 641+ beginRevision(logLength: number): void; 642+ /** Verify both the saved prefix and the new frames against canonical authority. */ 643+ validateAuthority(): void; 645+ ): { next: number; entries: number; bytes: number } { 647+ !Number.isSafeInteger(input.from) || 649+ !Number.isSafeInteger(input.maxEntries) || 650+ input.maxEntries < 1 || 651+ input.maxEntries > 256 || 652+ !Number.isSafeInteger(input.maxBytes) || 653+ input.maxBytes < 1 || 654+ (input.maxBytes > 8_000_000 && input.decodedFrames !== true) 656+ throw new Error("invalid historical extension bounds"); 657+ const validate = () => { 658+ const result: unknown = input.validateAuthority(); 659+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result) 660+ throw new Error("historical authority must be synchronous"); 662+ return storage.transaction(() => { 664+ const project = Project.#openWriter( 667+ throw new Error("history derivation cannot append canonical entries"); 674+ project.#loading = true; 677+ for (const frame of input.frames) { 678+ if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames"); 679+ const size = adoptionFrameBytes(frame); 681+ entries >= input.maxEntries || 682+ frame.seq !== input.from + entries || 683+ !Number.isSafeInteger(size) || 685+ size > input.maxBytes - bytes 687+ throw new Error("historical extension exceeds bounds or is not contiguous"); 689+ if (bytes > input.maxBytes) throw new Error("historical extension exceeds byte bound"); 690+ input.beginRevision(frame.seq + 1); 691+ project.#apply(adoptionFrameEntry(frame)); 693+ project.#persistMutable(); 694+ project.#writeCheckpoint(); 697+ if (!entries) throw new Error("historical extension must advance"); 699+ return { next: input.from + entries, entries, bytes }; 703+ /** Apply more entries to a replay copy. Never for the live project. */ 569704 catchUp(entries: Iterable<Entry>): void { 570705 this.#loading = true; @@ -896,6 +1031,7 @@
8971032 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */ 8981033 #reviewRules(): ReviewRule[] { 1034+ if (["abso.json", "avcs.json"].every((path) => this.#graph.startCodeOf(path) === undefined)) return []; 8991035 return reviewRulesIn(projectFileIn(this.#sharedView())?.text); @@ -1325,7 +1461,7 @@
13261462 changes: AtomId[], 1328− ): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
1464+ ): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } { 13291465 return hostedLandCollisions(this.#landHost, space, changes, pick); @@ -2043,6 +2179,12 @@
20432179 #landers?: LandHost; 20442180 get #landHost(): LandHost { 20452181 this.#landers ??= { 2182+ viewAt: (space, version, changes) => 2184+ ? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(",")}`, () => 2185+ unionOverlay(this.#at(space, version), changes), 2187+ : this.#viewAt(space, version), 20462188 agents: this.#agents, 20472189 graph: this.#graph, 20482190 spaces: this.#spaces, --- a/worker/project/projection-provider.ts
+++ b/worker/project/projection-provider.ts
@@ -17,6 +17,7 @@
1717 committed(): { version: number; handle: ProjectionHandle }; 1818 at(version: number): ProjectionHandle | undefined; 1919 delta(version: number): Published | undefined; 20+ namedVersion?(name: string, version: number): { sharedBase: number; atoms: Iterable<string> } | undefined; 2021 /** Read-through overlay owned and cleaned by the current transaction. */ 2122 allocate(): GraphStateStorage; 2223 /** Checks this exact transaction, graph revision and verified source binding. */ @@ -41,9 +42,13 @@
4142 throw Error("expired projection source binding"); 44− const match = /^(v|a) @(0|[1-9]\d*)(?:\+(.+))?$/.exec(key);
45− if (!match || (match[1] === "v" && match[3])) throw Error(`unsupported projection key: ${key}`);
46− const version = Number(match[2]);
45+ const match = /^(v|a) (.*)@(0|[1-9]\d*)(?:\+(.+))?$/.exec(key); 46+ if (!match || (match[1] === "v" && match[4])) throw Error(`unsupported projection key: ${key}`); 47+ const requested = Number(match[3]); 48+ if (!Number.isSafeInteger(requested)) throw Error("projection version outside authority"); 49+ const named = match[2] ? binding.namedVersion?.(match[2], requested) : undefined; 50+ if (match[2] && !named) throw Error("named projection version outside authority"); 51+ const version = named?.sharedBase ?? requested; 4752 if (!Number.isSafeInteger(version) || version > binding.version()) 4853 throw Error("projection version outside authority"); 4954 const exact = binding.at(version); @@ -74,7 +79,8 @@
7479 for (const atom of delta.atoms.map((id) => binding.graph.atom(id)).sort((a, b) => a.seq - b.seq)) 7580 state = adapter.apply(state, atom); 77− for (const id of match[3]?.split(",") ?? []) state = adapter.apply(state, binding.graph.atom(id));
82+ for (const id of named?.atoms ?? []) state = adapter.apply(state, binding.graph.atom(id)); 83+ for (const id of match[4]?.split(",") ?? []) state = adapter.apply(state, binding.graph.atom(id)); 7985 return new ProjectionReader(adapter, state, assertLive); --- a/worker/project/test/collision-streaming.test.ts
+++ b/worker/project/test/collision-streaming.test.ts
@@ -107,3 +107,51 @@
107107 source.db.close(); 111+test("wide claim merging reads each stream head once and closes streams on failure", () => { 119+ writes: Array.from({ length: count }, (_, n) => `L:a0.${n}`), 129+ const stream = function* () { 134+ if (fail) throw Error("claim stream failure"); 141+ atom: (id: string) => { 143+ return id === "a3" ? draft : { seq: Number(id.slice(1)) }; 145+ eachWriterOf: stream, 146+ eachReaderOf: stream, 147+ eachHolderOf: stream, 148+ } as unknown as Graph; 149+ assert.deepEqual(pairsIn(graph, ["a3"], new Set(), new Set()), []); 150+ assert.ok(reads <= count * 12 + 1, `Unexpected repeated head reads: ${reads}`); 151+ assert.equal(closed, opened); 155+ assert.throws(() => pairsIn(graph, ["a3"], new Set(), new Set()), /claim stream failure/); 156+ assert.equal(closed, opened); --- /dev/null
+++ b/worker/project/test/land-streaming.test.ts
@@ -0,0 +1,83 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { StableOverlaySet, StableSet } from "../../../src/engine/state-source.ts"; 4+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 5+import { type LandHost, landCollisions } from "../land.ts"; 6+import { addVersion, Membership, type Space } from "../spaces.ts"; 8+test("landing collision setup does not enumerate shared history", () => { 9+ class History extends StableSet<string> { 10+ readonly retainedBytes = 0; 11+ readonly end: number; 12+ constructor(end: number) { 17+ return /^a\d+$/.test(id) && Number(id.slice(1)) < this.end; 19+ values(): SetIterator<string> { 20+ throw Error("shared history enumeration forbidden during setup"); 23+ for (const size of [32, 8192, 1_000_000]) { 24+ const shared = { name: "", own: new History(size) } as unknown as Space; 27+ own: new StableOverlaySet(["draft-change"]), 28+ versions: [{ sharedBase: 0 }], 29+ } as unknown as Space; 31+ shared: () => shared, 33+ at: (_space: Space, version: number) => new History(version === 0 ? size - 1 : size), 35+ sharedView: () => ({}), 36+ pairs: (_changes: string[], newer: ReadonlySet<string>, union: ReadonlySet<string>) => { 37+ assert.equal(newer.has(`a${size - 1}`), true); 38+ assert.equal(newer.has("a0"), false); 39+ assert.equal(union.has("a0"), true); 40+ assert.equal(union.has("draft-change"), true); 43+ definitionRule: () => ({ collisions: () => [] }), 44+ } as unknown as LandHost; 45+ assert.deepEqual(landCollisions(host, draft, ["draft-change"], false).collisions, []); 49+test("landing uses real stored membership without enumerating shared ownership", (t) => { 50+ const storage = new SqlState(); 52+ const membership = new Membership(storage); 53+ const shared = membership.shared; 54+ for (let version = 0; version < 40; version++) { 55+ addVersion(shared, { version, agent: "test", message: "version", time: 0, atoms: [`a${version}`] }); 57+ t.mock.method(shared.own, "values", () => { 58+ throw Error("stored shared history enumeration forbidden"); 62+ own: new StableOverlaySet(["draft-change"]), 63+ versions: [{ sharedBase: 38 }], 64+ } as unknown as Space; 66+ shared: () => shared, 68+ at: (space: Space, version: number) => membership.at(space, version), 70+ sharedView: () => ({}), 71+ pairs: (_changes: string[], newer: ReadonlySet<string>, union: ReadonlySet<string>) => { 72+ assert.deepEqual([...newer], ["a39"]); 73+ assert.equal(union.has("a0"), true); 74+ assert.equal(union.has("draft-change"), true); 77+ definitionRule: () => ({ collisions: () => [] }), 78+ } as unknown as LandHost; 79+ assert.deepEqual(landCollisions(host, draft, ["draft-change"], false).collisions, []); --- /dev/null
+++ b/worker/project/test/news-lazy.test.ts
@@ -0,0 +1,35 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { type NewsHost, newsForOthers } from "../news.ts"; 4+import type { AgentState } from "../project-types.ts"; 5+import type { Space } from "../spaces.ts"; 7+test("news skips historical views when no other agent has a draft in the space", () => { 8+ const publisher = { name: "alice", space: "" } as AgentState; 9+ const idle = { name: "bob", space: "" } as AgentState; 10+ const elsewhere = { name: "carol", space: "branch" } as AgentState; 11+ const space = { name: "", versions: [{ atoms: [] }] } as unknown as Space; 13+ const host = new Proxy( 16+ ["alice", publisher], 18+ ["carol", elsewhere], 20+ draft: (agent: AgentState) => { 21+ assert.equal(agent, idle); 28+ if (key in target) return Reflect.get(target, key); 29+ throw Error(`Unexpected news work: ${String(key)}`); 32+ ) as unknown as NewsHost; 33+ newsForOthers(host, publisher, space, 0, []); 34+ assert.equal(draftReads, 1); --- a/worker/project/test/reviewers.test.ts
+++ b/worker/project/test/reviewers.test.ts
@@ -92,3 +92,25 @@
9292 plain.publish("b", "x", 2); 9393 assert.equal(plain.news("c").news.length, 0); 96+test("review rules added after an absent configuration are honored and removal clears them", () => { 97+ for (const name of ["abso.json", "avcs.json"]) { 98+ const project = new Project(new MemoryStore()); 99+ project.init({ "a.txt": "one\n" }, 0); 100+ project.sync("builder"); 101+ project.sync("reviewer"); 102+ project.record("builder", { "a.txt": "two\n" }, 1); 103+ project.publish("builder", "No configuration", 2); 104+ assert.equal(project.news("reviewer").news.length, 0); 107+ { [name]: JSON.stringify({ review: [{ paths: ["a.txt"], reviewer: "reviewer" }] }), "a.txt": "three\n" }, 110+ project.publish("builder", "Add rules", 4); 111+ assert.ok(project.news("reviewer").news.some((text) => text.includes("in your review area"))); 112+ project.record("builder", { [name]: null, "a.txt": "four\n" }, 5); 113+ project.publish("builder", "Remove rules", 6); 114+ assert.equal(project.news("reviewer").news.length, 0); --- a/worker/project/test/where-many-agents.test.ts
+++ b/worker/project/test/where-many-agents.test.ts
@@ -7,6 +7,16 @@
77import { MemoryStore, Project } from "../project.ts"; 88import { where } from "../where.ts"; 10+test("where does not construct shared history when every draft is empty", (t) => { 11+ const project = new Project(new MemoryStore()); 12+ project.init({ "a.txt": "one\n" }, 0); 13+ project.sync("idle"); 14+ t.mock.method(project, "sharedView", () => { 15+ throw Error("unnecessary shared history construction"); 17+ assert.deepEqual(where(project), { version: 0, files: {}, starting: [] }); 1020test("where answers right with more agents than the view cache holds, and lays out no view for an empty draft", () => { 1121 const store = new MemoryStore(); 1222 const project = new Project(store); --- a/worker/project/where.ts
+++ b/worker/project/where.ts
@@ -30,8 +30,9 @@
3131export function where(project: Project) { 3232 const graph = project.graph; 33− const shared = project.sharedView();
33+ let shared: ReturnType<Project["sharedView"]> | undefined; 3434 const sharedNumber = (file: string, id: LineId): number | undefined => { 35+ shared ??= project.sharedView(); 3536 if (!shared.hasFile(file)) return undefined; 3637 const i = shared.lines(file).findIndex((l) => l.id === id); 3738 return i >= 0 ? i + 1 : undefined;