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