{"draft":null,"from":128,"to":318,"files":[{"path":"server/src/disk-first-runtime.ts","added":257,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/disk-first-runtime.ts\n@@ -0,0 +1,257 @@\n+import { createHash } from \"node:crypto\";\n+import { jsonValueChunks } from \"../../src/engine/json-value-chunks.ts\";\n+import { Project, type WriterSource } from \"../../worker/project/project.ts\";\n+import type { ProjectOptions } from \"../../worker/project/project-types.ts\";\n+import { EngineProject, SqliteLog, type SqliteStorage } from \"./engine-project.ts\";\n+import { SqliteHistoryHost } from \"./history-host.ts\";\n+import { SqliteProjectionStore } from \"./projection-store.ts\";\n+import { requestIdentityDigest } from \"./request-identity-digest.ts\";\n+import { SqliteWriterHost, SqliteWriterState } from \"./writer-host.ts\";\n+\n+type Services = Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n+type Progress = { ready: boolean; phase: \"empty\" | \"writer\" | \"projection\" | \"history\" | \"ready\"; next: number };\n+\n+/** One synchronous page or call per invocation. No object retains a loaded Project.\n+ * The owner schedules subsequent pages and supplies fresh authorization for every call. */\n+export class DiskFirstRuntime {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n+\treadonly #projection: SqliteProjectionStore;\n+\treadonly #services: Services;\n+\treadonly #history: SqliteHistoryHost;\n+\tconstructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {\n+\t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n+\t\tthis.#services = services;\n+\t\tthis.#history = new SqliteHistoryHost(storage, `${namespace}:history`);\n+\t\tthis.#projection = new SqliteProjectionStore(\n+\t\t\t{\n+\t\t\t\tdatabase,\n+\t\t\t\tnamespace: `${namespace}:views`,\n+\t\t\t\tregistry: `${namespace}:roots`,\n+\t\t\t\tdefaultFile: \"__abso_projection_default__\",\n+\t\t\t},\n+\t\t\t1,\n+\t\t\t{ indexedAtoms: true },\n+\t\t);\n+\t}\n+\t#host() {\n+\t\treturn new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, {\n+\t\t\tindexProjectionAtoms: true,\n+\t\t\thistory: this.#history,\n+\t\t});\n+\t}\n+\t#state() {\n+\t\treturn new SqliteWriterState(this.#storage, this.#namespace);\n+\t}\n+\t#saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) {\n+\t\t// Receipt payloads can exceed the graph-state value bound. Keep each stored\n+\t\t// piece small without increasing that bound for engine state.\n+\t\tconst characters = 64 * 1024;\n+\t\tconst digest = createHash(\"sha256\");\n+\t\tlet pending = \"\",\n+\t\t\tparts = 0,\n+\t\t\tlength = 0;\n+\t\tfor (const chunk of jsonValueChunks({ result }, { maxDepth: Infinity, unboxPrimitives: true })) {\n+\t\t\tdigest.update(chunk);\n+\t\t\tlength += chunk.length;\n+\t\t\tpending += chunk;\n+\t\t\twhile (pending.length >= characters) {\n+\t\t\t\tstate.write(`runtime:receipt:${id}`, String(parts++), pending.slice(0, characters));\n+\t\t\t\tpending = pending.slice(characters);\n+\t\t\t}\n+\t\t}\n+\t\tif (pending) state.write(`runtime:receipt:${id}`, String(parts++), pending);\n+\t\tstate.write(\"runtime:receipts\", id, {\n+\t\t\tformat: 3,\n+\t\t\tidentity,\n+\t\t\tparts,\n+\t\t\tcharacters: length,\n+\t\t\tdigest: digest.digest(\"hex\"),\n+\t\t});\n+\t}\n+\t#receiptResult<T>(\n+\t\tstate: SqliteWriterState,\n+\t\tid: string,\n+\t\treceipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string },\n+\t): T {\n+\t\tif (receipt.format === 2) return structuredClone(receipt.result) as T;\n+\t\tif (\n+\t\t\treceipt.format !== 3 ||\n+\t\t\t!Number.isSafeInteger(receipt.parts) ||\n+\t\t\treceipt.parts! < 1 ||\n+\t\t\t!Number.isSafeInteger(receipt.characters) ||\n+\t\t\treceipt.characters! < 1 ||\n+\t\t\treceipt.parts !== Math.ceil(receipt.characters! / (64 * 1024))\n+\t\t)\n+\t\t\tthrow Error(\"invalid receipt header\");\n+\t\tlet json = \"\";\n+\t\tfor (let part = 0; part < receipt.parts!; part++) {\n+\t\t\tconst chunk = state.read(`runtime:receipt:${id}`, String(part));\n+\t\t\tif (typeof chunk !== \"string\" || chunk.length !== Math.min(64 * 1024, receipt.characters! - part * 64 * 1024))\n+\t\t\t\tthrow Error(\"incomplete receipt payload\");\n+\t\t\tjson += chunk;\n+\t\t}\n+\t\tif (createHash(\"sha256\").update(json).digest(\"hex\") !== receipt.digest)\n+\t\t\tthrow Error(\"receipt payload digest mismatch\");\n+\t\treturn (JSON.parse(json) as { result: T }).result;\n+\t}\n+\n+\t#validate(validate: () => void) {\n+\t\tconst result: unknown = validate();\n+\t\tif (result && (typeof result === \"object\" || typeof result === \"function\") && \"then\" in result)\n+\t\t\tthrow Error(\"runtime authorization must be synchronous\");\n+\t}\n+\t#setup() {\n+\t\tSqliteWriterState.initialize(this.#storage);\n+\t\tconst state = this.#state();\n+\t\tconst format = state.read(\"runtime\", \"format\");\n+\t\tif (format !== undefined && format !== 1 && format !== 2 && format !== 3 && format !== 4 && format !== 5)\n+\t\t\tthrow Error(\"unsupported disk-first runtime format\");\n+\t\t// Format 5 additionally fences indexed insertion runs and lines from older readers.\n+\t\t// Never lower this marker in place.\n+\t\tif (format !== 5) state.write(\"runtime\", \"format\", 5);\n+\t\treturn state;\n+\t}\n+\t/** Initializes an empty canonical log without replay. Existing history must be adopted. */\n+\tinitialize<T>(\n+\t\toperation: (calls: EngineProject) => T,\n+\t\tvalidate: () => void,\n+\t\trequest?: { id: string; identity: unknown },\n+\t): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tconst log = new SqliteLog(this.#storage);\n+\t\t\tif (log.seq() !== 0) throw Error(\"disk-first initialization requires an empty log\");\n+\t\t\tif (request && (!request.id || request.id.length > 128)) throw Error(\"invalid disk-first request identity\");\n+\t\t\tconst project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });\n+\t\t\tconst result = structuredClone(operation(new EngineProject(project)));\n+\t\t\tthis.#validate(validate);\n+\t\t\tif (request && log.seq() > 0)\n+\t\t\t\tthis.#saveReceipt(this.#setup(), request.id, requestIdentityDigest(request.identity), result);\n+\t\t\treturn result;\n+\t\t});\n+\t}\n+\tpreparePage(validate: () => void): Progress {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tconst log = new SqliteLog(this.#storage);\n+\t\t\tif (log.seq() === 0) {\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: false, phase: \"empty\", next: 0 };\n+\t\t\t}\n+\t\t\tconst state = this.#setup();\n+\t\t\tconst host = this.#host();\n+\t\t\tconst ready = state.read(\"runtime\", \"ready\");\n+\t\t\tif (ready !== undefined && ready !== true) throw Error(\"invalid runtime readiness marker\");\n+\t\t\tif (ready === true) {\n+\t\t\t\tconst root = host.root();\n+\t\t\t\tconst history = this.#history.prepare(log, root, () => host.root(), validate);\n+\t\t\t\tif (!history.ready) {\n+\t\t\t\t\tstate.remove(\"runtime\", \"history-ready\");\n+\t\t\t\t\treturn { ready: false, phase: \"history\", next: history.next };\n+\t\t\t\t}\n+\t\t\t\tstate.write(\"runtime\", \"history-ready\", true);\n+\t\t\t\tconst scope = this.#projection.open({ state, log, root });\n+\t\t\t\tscope.close();\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: true, phase: \"ready\", next: root.logLength };\n+\t\t\t}\n+\t\t\tconst bound = state.read(\"host\", \"canonical-root\");\n+\t\t\tif (bound === undefined) {\n+\t\t\t\tconst cursor = state.read(\"host\", \"adoption-root\") as\n+\t\t\t\t\t| { source: WriterSource; next: number; digest: string }\n+\t\t\t\t\t| undefined;\n+\t\t\t\tconst page = host.adoptVerifiedPage(\n+\t\t\t\t\t{\n+\t\t\t\t\t\texpected: cursor?.source ?? host.source(),\n+\t\t\t\t\t\tfrom: cursor?.next ?? 0,\n+\t\t\t\t\t\tdigest: cursor?.digest ?? \"\",\n+\t\t\t\t\t\tmaxEntries: 32,\n+\t\t\t\t\t\tmaxBytes: log.adoptionPageBytes(cursor?.next ?? 0),\n+\t\t\t\t\t},\n+\t\t\t\t\tvalidate,\n+\t\t\t\t);\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: false, phase: \"writer\", next: page.next };\n+\t\t\t}\n+\t\t\tconst root = host.root();\n+\t\t\tconst page = this.#projection.adopt({\n+\t\t\t\tstate,\n+\t\t\t\texpected: root,\n+\t\t\t\tcurrentRoot: () => host.root(),\n+\t\t\t\tmaxAtoms: 32,\n+\t\t\t\tmaxVersions: 1,\n+\t\t\t\tmaxSteps: 32,\n+\t\t\t});\n+\t\t\tthis.#validate(validate);\n+\t\t\tif (!page.ready) return { ready: false, phase: \"projection\", next: root.logLength };\n+\t\t\tconst history = this.#history.prepare(log, root, () => host.root(), validate);\n+\t\t\tif (history.ready) {\n+\t\t\t\tstate.write(\"runtime\", \"ready\", true);\n+\t\t\t\tstate.write(\"runtime\", \"history-ready\", true);\n+\t\t\t}\n+\t\t\treturn { ready: history.ready, phase: history.ready ? \"ready\" : \"history\", next: history.next };\n+\t\t});\n+\t}\n+\t#requireReady() {\n+\t\tif (\n+\t\t\tthis.#storage.sql.exec(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'\").toArray()\n+\t\t\t\t.length === 0\n+\t\t)\n+\t\t\tthrow Error(\"disk-first adoption is not complete\");\n+\t\tif (\n+\t\t\tthis.#state().read(\"runtime\", \"format\") !== 5 ||\n+\t\t\tthis.#state().read(\"runtime\", \"ready\") !== true ||\n+\t\t\tthis.#state().read(\"runtime\", \"history-ready\") !== true\n+\t\t)\n+\t\t\tthrow Error(\"disk-first adoption is not complete\");\n+\t}\n+\tread<T>(operation: (calls: EngineProject) => T, validate: () => void): T {\n+\t\tthis.#requireReady();\n+\t\tconst host = this.#host();\n+\t\treturn host.readCalls({\n+\t\t\texpected: host.source(),\n+\t\t\tvalidateAuthority: validate,\n+\t\t\tservices: this.#services,\n+\t\t\toperation: (calls) => structuredClone(operation(calls)),\n+\t\t});\n+\t}\n+\twrite<T>(\n+\t\toperation: (calls: EngineProject) => T,\n+\t\tvalidate: () => void,\n+\t\trequest?: { id: string; identity: unknown },\n+\t): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tthis.#requireReady();\n+\t\t\tconst state = this.#state();\n+\t\t\tconst host = this.#host();\n+\t\t\thost.root();\n+\t\t\tif (request && (!request.id || request.id.length > 128)) throw Error(\"invalid disk-first request identity\");\n+\t\t\tconst identity = request ? requestIdentityDigest(request.identity) : undefined;\n+\t\t\tif (request) {\n+\t\t\t\tconst receipt = state.read(\"runtime:receipts\", request.id) as\n+\t\t\t\t\t| { format: number; identity: string; result: T }\n+\t\t\t\t\t| undefined;\n+\t\t\t\tif (receipt) {\n+\t\t\t\t\tif (receipt.format !== 2 && receipt.format !== 3) throw Error(\"unsupported disk-first receipt format\");\n+\t\t\t\t\tif (receipt.identity !== identity)\n+\t\t\t\t\t\tthrow Object.assign(Error(\"disk-first request identity was reused\"), { code: \"request-reused\" });\n+\t\t\t\t\tthis.#validate(validate);\n+\t\t\t\t\treturn this.#receiptResult<T>(state, request.id, receipt);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\treturn host.runCalls({\n+\t\t\t\texpected: host.source(),\n+\t\t\t\tvalidateAuthority: validate,\n+\t\t\t\tservices: this.#services,\n+\t\t\t\tcheckerReady: false,\n+\t\t\t\toperation: (calls) => structuredClone(operation(calls)),\n+\t\t\t\tcommitReceipt: (result) => {\n+\t\t\t\t\tif (request) this.#saveReceipt(state, request.id, identity!, result);\n+\t\t\t\t},\n+\t\t\t});\n+\t\t});\n+\t}\n+}"}],"unmatched":[]}