Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/server/src/writer-host.ts?version=161&format=json
429 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 158, 2 versions changed it

You're reading version 161. The newest is 318, and 1 version since then changed this file. Go to the newestCompare with 318

1// Shared SQLite writer host.
2// Callers provide current authority and own activation; this module adds no route.
3import { createHash } from "node:crypto";
4import { indexAcceptedProjectionAtom } from "../../src/engine/experimental/projection-atom-index.ts";
5import type { GraphStateStorage } from "../../src/engine/state-source.ts";
6import { Project, type WriterSource } from "../../worker/project/project.ts";
7import type { ProjectOptions } from "../../worker/project/project-types.ts";
8import {
9 EngineProject,
10 logParts,
11 LOG_PART_CHARACTERS as PART,
12 SqliteLog,
13 type SqliteStorage,
14} from "./engine-project.ts";
16export class SqliteWriterState implements GraphStateStorage {
17 readonly #storage: SqliteStorage;
18 readonly #namespace: string;
19 static readonly maxValueBytes = 8_000_000;
20 constructor(storage: SqliteStorage, namespace: string) {
21 if (!namespace || namespace.length > 128) throw new Error("invalid writer-state namespace");
22 this.#storage = storage;
23 this.#namespace = namespace;
24 }
25 /** Explicit schema setup, reserved for an authorized adoption host. */
26 static initialize(storage: SqliteStorage): void {
27 storage.sql.exec(
28 "CREATE TABLE IF NOT EXISTS writer_state (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, part INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, collection, key, part))",
29 );
30 }
31 read(collection: string, key: string): unknown {
32 const header = this.#storage.sql
33 .exec(
34 "SELECT value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part = -1",
35 this.#namespace,
36 collection,
37 key,
38 )
39 .toArray() as { value: string }[];
40 if (!header.length) return undefined;
41 const meta = JSON.parse(header[0]!.value) as { parts: number; characters: number; bytes: number };
42 if (
43 !Number.isSafeInteger(meta.parts) ||
44 meta.parts < 1 ||
45 meta.parts > Math.ceil(SqliteWriterState.maxValueBytes / (PART - 1)) ||
46 !Number.isSafeInteger(meta.characters) ||
47 meta.characters < 1 ||
48 meta.characters > SqliteWriterState.maxValueBytes ||
49 !Number.isSafeInteger(meta.bytes) ||
50 meta.bytes < 1 ||
51 meta.bytes > SqliteWriterState.maxValueBytes
52 )
53 throw new Error("invalid writer-state value header");
54 const rows = this.#storage.sql
55 .exec(
56 "SELECT part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part >= 0 ORDER BY part LIMIT ?",
57 this.#namespace,
58 collection,
59 key,
60 meta.parts + 1,
61 )
62 .toArray() as { part: number; value: string }[];
63 if (rows.length !== meta.parts || rows.some((row, index) => row.part !== index || row.value.length > PART))
64 throw new Error("incomplete writer-state value");
65 const json = rows.map((row) => row.value).join("");
66 if (json.length !== meta.characters || new TextEncoder().encode(json).byteLength !== meta.bytes)
67 throw new Error("writer-state value length mismatch");
68 return (JSON.parse(json) as { value?: unknown }).value;
69 }
70 write(collection: string, key: string, value: unknown): void {
71 const json = JSON.stringify({ value });
72 if (json.length > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
73 const bytes = new TextEncoder().encode(json).byteLength;
74 if (bytes > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
75 const parts = logParts(json);
76 this.transaction(() => {
77 this.remove(collection, key);
78 this.#storage.sql.exec(
79 "INSERT INTO writer_state VALUES (?, ?, ?, -1, ?)",
80 this.#namespace,
81 collection,
82 key,
83 JSON.stringify({ parts: parts.length, characters: json.length, bytes }),
84 );
85 for (const [part, text] of parts.entries())
86 this.#storage.sql.exec(
87 "INSERT INTO writer_state VALUES (?, ?, ?, ?, ?)",
88 this.#namespace,
89 collection,
90 key,
91 part,
92 text,
93 );
94 });
95 }
96 remove(collection: string, key: string): void {
97 this.#storage.sql.exec(
98 "DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?",
99 this.#namespace,
100 collection,
101 key,
102 );
103 }
104 /** Delete one owned temporary projection collection without reading its values. */
105 clearProjectionOverlay(collection: string): void {
106 if (!collection.startsWith("projection:temporary:") || collection === "projection:temporary:")
107 throw Error("invalid temporary projection collection");
108 this.#storage.sql.exec(
109 "DELETE FROM writer_state WHERE namespace = ? AND collection = ?",
110 this.#namespace,
111 collection,
112 );
113 }
114 *entries(collection: string): Iterable<readonly [string, unknown]> {
115 let after: string | undefined;
116 for (;;) {
117 const rows = (
118 after === undefined
119 ? this.#storage.sql.exec(
120 "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 ORDER BY key LIMIT 1",
121 this.#namespace,
122 collection,
123 )
124 : this.#storage.sql.exec(
125 "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 AND key > ? ORDER BY key LIMIT 1",
126 this.#namespace,
127 collection,
128 after,
129 )
130 ).toArray() as { key: string }[];
131 if (!rows.length) return;
132 after = rows[0]!.key;
133 yield [after, this.read(collection, after)];
134 }
135 }
136 transaction<T>(body: () => T): T {
137 return this.#storage.transactionSync(body);
138 }
141export interface WriterRoot extends WriterSource {
142 readonly format: 1;
143 readonly digest: string;
146/** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */
147export function writerFrameDigest(previous: string, seq: number, json: string): string {
148 return createHash("sha256")
149 .update("abso-writer-log-v1\n")
150 .update(JSON.stringify([previous, seq]))
151 .update("\n")
152 .update(json, "utf8")
153 .digest("hex");
156export 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. */
165export interface WriterProjectionSession {
166 readonly readViewProvider: NonNullable<ProjectOptions["readViewProvider"]>;
167 commit(project: Project, root: WriterRoot): void;
168 /** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */
169 close(): void;
172/** Private integration hook. No endpoint or persisted setting enables it. */
173export interface WriterProjectionHost {
174 open(input: { state: SqliteWriterState; log: SqliteLog; root: WriterRoot }): WriterProjectionSession;
177export class SqliteWriterHost {
178 readonly #storage: SqliteStorage;
179 readonly #state: SqliteWriterState;
180 readonly #log: SqliteLog;
181 readonly #projection?: WriterProjectionHost;
182 readonly #indexProjectionAtoms: boolean;
183 constructor(
184 storage: SqliteStorage,
185 namespace: string,
186 projection?: WriterProjectionHost,
187 options: { indexProjectionAtoms?: boolean } = {},
188 ) {
189 this.#storage = storage;
190 this.#state = new SqliteWriterState(storage, namespace);
191 this.#log = new SqliteLog(storage);
192 this.#projection = projection;
193 this.#indexProjectionAtoms = options.indexProjectionAtoms ?? false;
194 }
195 #indexOptions(adopting = false) {
196 const mode = this.#state.read("host", "projection-atom-index-mode");
197 const expected = this.#indexProjectionAtoms ? 1 : 0;
198 if (mode !== undefined && mode !== expected) throw Error("writer atom indexing mode mismatch");
199 if (mode === undefined && this.#indexProjectionAtoms && (!adopting || this.#state.read("atoms:meta", "length")))
200 throw Error("writer atom indexing requires fresh adoption");
201 if (mode === undefined && adopting) this.#state.write("host", "projection-atom-index-mode", expected);
202 return { indexAcceptedAtom: this.#indexProjectionAtoms ? indexAcceptedProjectionAtom : undefined };
203 }
205 source(): WriterSource {
206 this.#log.refreshSequence();
207 const shared = this.#storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
208 value: number;
209 }[];
210 if (!Number.isSafeInteger(shared[0]?.value) || shared[0]!.value < 0)
211 throw new Error("canonical shared head must be established before writer adoption");
212 return { generation: this.#log.generation(), logLength: this.#log.seq(), sharedVersion: shared[0]!.value };
213 }
214 static #same(a: WriterSource | undefined, b: WriterSource): boolean {
215 return a?.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
216 }
217 root(): WriterRoot {
218 const root = this.#state.read("host", "canonical-root") as WriterRoot | undefined;
219 if (root?.format !== 1 || !/^[a-f0-9]{64}$/.test(root.digest) || !SqliteWriterHost.#same(root, this.source()))
220 throw new Error("writer canonical root is missing or stale");
221 return root;
222 }
223 static #sync(value: unknown): void {
224 if (value && (typeof value === "object" || typeof value === "function") && "then" in value)
225 throw new Error("writer transaction callbacks must be synchronous");
226 }
227 /** Resume one bounded adoption page against an exact source and prior digest. */
228 adoptVerifiedPage(
229 input: {
230 expected: WriterSource;
231 from: number;
232 digest: string;
233 maxEntries: number;
234 maxBytes: number;
235 },
236 validateAuthority: () => void,
237 ) {
238 return this.#storage.transactionSync(() => {
239 SqliteWriterHost.#sync(validateAuthority());
240 if (!SqliteWriterHost.#same(input.expected, this.source())) throw new Error("adoption source changed");
241 if (
242 !Number.isSafeInteger(input.from) ||
243 input.from < 0 ||
244 !Number.isSafeInteger(input.maxEntries) ||
245 input.maxEntries < 1 ||
246 input.maxEntries > 256 ||
247 !Number.isSafeInteger(input.maxBytes) ||
248 input.maxBytes < 1 ||
249 input.maxBytes > 8_000_000 ||
250 !(input.digest === "" || /^[a-f0-9]{64}$/.test(input.digest))
251 )
252 throw new Error("invalid bounded adoption request");
253 const request = JSON.stringify([
254 input.expected.generation,
255 input.expected.logLength,
256 input.expected.sharedVersion,
257 input.from,
258 input.digest,
259 input.maxEntries,
260 input.maxBytes,
261 ]);
262 const previous = this.#state.read("host", "adoption-page-receipt") as
263 | { request: string; result: { next: number; ready: boolean; digest: string } }
264 | undefined;
265 if (previous?.request === request) return previous.result;
266 const cursor = this.#state.read("host", "adoption-root") as { next: number; digest: string } | undefined;
267 if ((cursor?.next ?? 0) !== input.from || (cursor?.digest ?? "") !== input.digest)
268 throw new Error("adoption cursor or digest changed");
269 const page = this.adoptPage(input.from, input, validateAuthority);
270 const root = this.#state.read("host", "adoption-root") as { digest: string };
271 const result = { next: page.next, ready: page.ready, digest: root.digest };
272 this.#state.write("host", "adoption-page-receipt", { request, result });
273 return result;
274 });
275 }
276 adoptPage(from: number, limits: { maxEntries: number; maxBytes: number }, validateAuthority: () => void) {
277 return this.#storage.transactionSync(() => {
278 SqliteWriterHost.#sync(validateAuthority());
279 const source = this.source();
280 const indexOptions = this.#indexOptions(true);
281 const log = this.#log;
282 const previous = this.#state.read("host", "adoption-root") as
283 | { source: WriterSource; next: number; digest: string }
284 | undefined;
285 if (
286 (from === 0 && previous) ||
287 (from > 0 && (!previous || previous.next !== from || !SqliteWriterHost.#same(previous.source, source)))
288 )
289 throw new Error("writer adoption root cursor is stale");
290 let digest = previous?.digest ?? "";
291 const frames = function* () {
292 let bytes = 0;
293 for (let seq = from; seq < source.logLength && seq < from + limits.maxEntries; seq++) {
294 // Each frame is bounded before reading; the core also checks the
295 // cumulative byte count before applying a frame.
296 const json = log.boundedFrame(seq, limits.maxBytes);
297 const next = new TextEncoder().encode(json).byteLength;
298 if (bytes + next > limits.maxBytes && bytes > 0) return;
299 bytes += next;
300 digest = writerFrameDigest(digest, seq, json);
301 yield { seq, json };
302 }
303 };
304 const result = Project.adoptWriterPage(
305 this.#state,
306 {
307 source,
308 from,
309 frames: frames(),
310 ...limits,
311 currentSource: () => this.source(),
312 },
313 indexOptions,
314 );
315 SqliteWriterHost.#sync(validateAuthority());
316 this.#state.write("host", "adoption-root", { source, next: result.next, digest });
317 if (result.ready) {
318 this.#state.write("host", "canonical", source);
319 this.#state.write("host", "canonical-root", { format: 1, ...source, digest } satisfies WriterRoot);
320 }
321 return result;
322 });
323 }
324 /** Read through the existing call adapter with persistent mutations forbidden. */
325 readCalls<T>(input: {
326 expected: WriterSource;
327 validateAuthority(): void;
328 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
329 operation(calls: EngineProject): T;
330 }): T {
331 return this.#storage.transactionSync(() => {
332 SqliteWriterHost.#sync(input.validateAuthority());
333 const source = this.source();
334 this.root();
335 if (!SqliteWriterHost.#same(input.expected, source)) throw new Error("reader source is stale");
336 const refuse = () => {
337 throw new Error("indexed read attempted to mutate persistent state");
338 };
339 const readOnly: GraphStateStorage = {
340 read: (collection, key) => this.#state.read(collection, key),
341 entries: (collection) => this.#state.entries(collection),
342 write: refuse,
343 remove: refuse,
344 transaction: (body) => this.#storage.transactionSync(body),
345 };
346 const projection = this.#projection?.open({ state: this.#state, log: this.#log, root: this.root() });
347 try {
348 const project = Project.openWriter({ append: refuse }, readOnly, source.logLength, {
349 ...input.services,
350 ...(input.services?.whole ? { whole: { read: input.services.whole.read, keep: refuse } } : {}),
351 readViewProvider: projection?.readViewProvider,
352 entryAt: (index) => this.#log.since(index, 1)[0]!,
353 });
354 const result = input.operation(new EngineProject(project, (from, limit) => this.#log.since(from, limit)));
355 SqliteWriterHost.#sync(result);
356 SqliteWriterHost.#sync(input.validateAuthority());
357 if (!SqliteWriterHost.#same(source, this.source())) throw new Error("reader source changed");
358 return result;
359 } finally {
360 SqliteWriterHost.#sync(projection?.close());
361 }
362 });
363 }
365 /** Reuse the existing call adapter within one fenced writer transaction. */
366 runCalls<T>(input: {
367 expected: WriterSource;
368 validateAuthority(): void;
369 checkerReady: boolean;
370 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
371 operation(calls: EngineProject): T;
372 commitReceipt(result: NoInfer<T>, source: WriterSource): void;
373 }): T {
374 return this.run({
375 ...input,
376 operation: (project) => {
377 const calls = new EngineProject(project, (from, limit) => this.#log.since(from, limit), this.#log);
378 calls.setCheckerReady(input.checkerReady);
379 return input.operation(calls);
380 },
381 });
382 }
383 /** No asynchronous gap is permitted between authority validation and commit. */
384 run<T>(input: {
385 expected: WriterSource;
386 validateAuthority(): void;
387 operation(project: Project): T;
388 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
389 commitReceipt(result: NoInfer<T>, source: WriterSource): void;
390 }): T {
391 try {
392 return this.#storage.transactionSync(() => {
393 SqliteWriterHost.#sync(input.validateAuthority());
394 const source = this.source();
395 const root = this.root();
396 const bound = this.#state.read("host", "canonical") as WriterSource | undefined;
397 if (!SqliteWriterHost.#same(input.expected, source) || !SqliteWriterHost.#same(bound, source))
398 throw new Error("writer source or adopted generation is stale");
399 const projection = this.#projection?.open({ state: this.#state, log: this.#log, root });
400 try {
401 const project = Project.openWriter(this.#log, this.#state, source.logLength, {
402 ...input.services,
403 ...this.#indexOptions(),
404 readViewProvider: projection?.readViewProvider,
405 shapes: this.#log.shapes(),
406 now: () => Date.now(),
407 });
408 const result = input.operation(project);
409 SqliteWriterHost.#sync(result);
410 SqliteWriterHost.#sync(input.validateAuthority());
411 const committed = this.source();
412 this.#state.write("host", "canonical", committed);
413 const committedRoot = advanceWriterRoot(this.#log, root, committed);
414 this.#state.write("host", "canonical-root", committedRoot);
415 SqliteWriterHost.#sync(projection?.commit(project, committedRoot));
416 SqliteWriterHost.#sync(input.commitReceipt(result, committed));
417 return result;
418 } finally {
419 SqliteWriterHost.#sync(projection?.close());
420 }
421 });
422 } catch (error) {
423 // The Project was scoped to the transaction and is discarded. Restore
424 // SqliteLog's cached sequence after an enclosing rollback as well.
425 this.#log.refreshSequence();
426 throw error;
427 }
428 }