Skip to content

abso-core

Public

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

Check passed
MCP
show on this site's /mcp
CLI
abso show 158 --json
JSON
/christopher/abso-core/versions/158?format=json

Integrate opt-in disk-first project runtime with cold-object transactions

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

Version 157 · Files at version 158

12 files, 814 lines added, 51 removed.

--- /dev/null
+++ b/server/src/disk-first-runtime.ts
@@ -0,0 +1,167 @@
1+import { canonicalJson } from "../../worker/project/operation-protocol.ts";
2+import { Project, type WriterSource } from "../../worker/project/project.ts";
3+import type { ProjectOptions } from "../../worker/project/project-types.ts";
4+import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts";
5+import { SqliteProjectionStore } from "./projection-store.ts";
6+import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts";
7+
8+type Services = Pick<ProjectOptions, "hasBlob" | "whole">;
9+type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "ready"; next: number };
11+/** One synchronous page or call per invocation. No object retains a loaded Project.
12+ * The owner schedules subsequent pages and supplies fresh authorization for every call. */
13+export class DiskFirstRuntime {
14+ readonly #storage: SqliteStorage;
15+ readonly #namespace: string;
16+ readonly #projection: SqliteProjectionStore;
17+ readonly #services: Services;
18+ constructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {
19+ this.#storage = storage;
20+ this.#namespace = namespace;
21+ this.#services = services;
22+ this.#projection = new SqliteProjectionStore(
23+ {
24+ database,
25+ namespace: `${namespace}:views`,
26+ registry: `${namespace}:roots`,
27+ defaultFile: "__abso_projection_default__",
28+ },
29+ 1,
30+ { indexedAtoms: true },
31+ );
32+ }
33+ #host() {
34+ return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { indexProjectionAtoms: true });
35+ }
36+ #state() {
37+ return new SqliteWriterState(this.#storage, this.#namespace);
38+ }
39+ #validate(validate: () => void) {
40+ const result: unknown = validate();
41+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
42+ throw Error("runtime authorization must be synchronous");
43+ }
44+ #setup() {
45+ SqliteWriterState.initialize(this.#storage);
46+ const state = this.#state();
47+ 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);
50+ return state;
51+ }
52+ /** Initializes an empty canonical log without replay. Existing history must be adopted. */
53+ initialize<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
54+ return this.#storage.transactionSync(() => {
55+ this.#validate(validate);
56+ const log = new SqliteLog(this.#storage);
57+ if (log.seq() !== 0) throw Error("disk-first initialization requires an empty log");
58+ const project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });
59+ const result = structuredClone(operation(new EngineProject(project)));
60+ this.#validate(validate);
61+ return result;
62+ });
63+ }
64+ preparePage(validate: () => void): Progress {
65+ return this.#storage.transactionSync(() => {
66+ this.#validate(validate);
67+ const log = new SqliteLog(this.#storage);
68+ if (log.seq() === 0) {
69+ this.#validate(validate);
70+ return { ready: false, phase: "empty", next: 0 };
71+ }
72+ const state = this.#setup();
73+ const host = this.#host();
74+ const ready = state.read("runtime", "ready");
75+ if (ready !== undefined && ready !== true) throw Error("invalid runtime readiness marker");
76+ if (ready === true) {
77+ const root = host.root();
78+ const scope = this.#projection.open({ state, log, root });
79+ scope.close();
80+ this.#validate(validate);
81+ return { ready: true, phase: "ready", next: root.logLength };
82+ }
83+ const bound = state.read("host", "canonical-root");
84+ if (bound === undefined) {
85+ const cursor = state.read("host", "adoption-root") as
86+ | { source: WriterSource; next: number; digest: string }
87+ | undefined;
88+ const page = host.adoptVerifiedPage(
89+ {
90+ expected: cursor?.source ?? host.source(),
91+ from: cursor?.next ?? 0,
92+ digest: cursor?.digest ?? "",
93+ maxEntries: 32,
94+ maxBytes: 1_048_576,
95+ },
96+ validate,
97+ );
98+ this.#validate(validate);
99+ return { ready: false, phase: "writer", next: page.next };
100+ }
101+ const root = host.root();
102+ const page = this.#projection.adopt({
103+ state,
104+ expected: root,
105+ currentRoot: () => host.root(),
106+ maxAtoms: 32,
107+ maxVersions: 1,
108+ maxSteps: 32,
109+ });
110+ 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 };
113+ });
114+ }
115+ #requireReady() {
116+ if (
117+ this.#storage.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'").toArray()
118+ .length === 0
119+ )
120+ throw Error("disk-first adoption is not complete");
121+ if (this.#state().read("runtime", "format") !== 1 || this.#state().read("runtime", "ready") !== true)
122+ throw Error("disk-first adoption is not complete");
123+ }
124+ read<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
125+ this.#requireReady();
126+ const host = this.#host();
127+ return host.readCalls({
128+ expected: host.source(),
129+ validateAuthority: validate,
130+ services: this.#services,
131+ operation: (calls) => structuredClone(operation(calls)),
132+ });
133+ }
134+ write<T>(
135+ operation: (calls: EngineProject) => T,
136+ validate: () => void,
137+ request?: { id: string; identity: unknown },
138+ ): T {
139+ return this.#storage.transactionSync(() => {
140+ this.#validate(validate);
141+ this.#requireReady();
142+ const state = this.#state();
143+ const host = this.#host();
144+ host.root();
145+ if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity");
146+ const identity = request ? canonicalJson(request.identity) : undefined;
147+ if (request) {
148+ const receipt = state.read("runtime:receipts", request.id) as { identity: string; result: T } | undefined;
149+ if (receipt) {
150+ if (receipt.identity !== identity) throw Error("disk-first request identity was reused");
151+ this.#validate(validate);
152+ return structuredClone(receipt.result);
153+ }
154+ }
155+ return host.runCalls({
156+ expected: host.source(),
157+ validateAuthority: validate,
158+ services: this.#services,
159+ checkerReady: false,
160+ operation: (calls) => structuredClone(operation(calls)),
161+ commitReceipt: (result) => {
162+ if (request) state.write("runtime:receipts", request.id, { identity, result });
163+ },
164+ });
165+ });
166+ }
167+}
--- a/server/src/engine-project.ts
+++ b/server/src/engine-project.ts
@@ -536,14 +536,23 @@
536536 if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" });
537537 const end = this.project.logLength;
538538 const start = Math.max(0, Math.min(from, end));
539− const entries = start < end ? this.read(start, Math.min(limit, end - start)) : [];
539+ // Discard each canonical payload after extracting its event. A feed page must
540+ // not retain every historical file payload in the requested range.
541+ const events = [];
542+ let next = start;
543+ while (next < end && next - start < limit) {
544+ const entries = this.read(next, 1);
545+ if (entries.length === 0) break;
546+ events.push(...feedEvents(entries, next));
547+ next += entries.length;
548+ }
540549 // A drop event names the files it took out (#41), so a timeline needs no read per drop.
541− const events = feedEvents(entries, start).map((e) => {
550+ const enriched = events.map((e) => {
542551 if (e.type !== "drop" || e.version === undefined) return e;
543552 const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];
544553 return v && v.version === e.version ? { ...e, dropped: v.files } : e;
545554 });
546− return { next: start + entries.length, end, events };
555+ return { next, end, events: enriched };
547556 }
548557
549558 /** The log position for a time (ms since 1970) or a version of shared (#41). */
--- a/server/src/env.ts
+++ b/server/src/env.ts
@@ -4,6 +4,8 @@
44import type { ProjectObject } from "./project-object.ts";
55
66export interface Env {
7+ /** Explicit development opt-in while disk-first server acceptance is in progress. */
8+ ABSO_DISK_FIRST?: string;
79 /** One Durable Object per project, named by the project's name. */
810 PROJECT: DurableObjectNamespace<ProjectObject>;
911 /** Issues, asks and news: one Durable Object per project, named by the project's name. */
--- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -7,6 +7,7 @@
77import { type Answer, answer, type Readers } from "../../worker/project/http.ts";
88import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
99import { BLOB_MAX, BlobStore } from "./blobs.ts";
10+import { DiskFirstRuntime } from "./disk-first-runtime.ts";
1011import { EngineProject, SqliteLog } from "./engine-project.ts";
1112import { artifactsOf, type Env } from "./env.ts";
1213import { pushedSince, remoteHead } from "./ingest.ts";
@@ -23,7 +24,34 @@
2324 revokeKey,
2425} from "./keys.ts";
2526import { type PushResult, pushShared, repoName } from "./push.ts";
27+import { SqliteWriterState } from "./writer-host.ts";
2628
29+const READ_OPS = new Set([
30+ "status",
31+ "blame",
32+ "why",
33+ "tree",
34+ "path",
35+ "follow",
36+ "collisions",
37+ "draft-state",
38+ "refusals",
39+ "labels",
40+ "log",
41+ "show",
42+ "file",
43+ "files",
44+ "compare",
45+ "where",
46+ "feed",
47+ "drafts",
48+ "diff",
49+ "ribbon",
50+ "position",
51+ "changes",
52+ "notes",
53+]);
2755/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */
2856export const PUSH_EVERY_MS = 60_000;
2957/** While agents are working, how often a call looks for plain-git pushes to the repo. */
@@ -78,6 +106,7 @@
78106 /** Why the log didn't load, if it didn't. */
79107 private loadError: unknown;
80108 private tried = false;
109+ private authorityRevision = 0;
81110 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */
82111 private waiting: (() => void)[] = [];
83112 /** When this object last asked the repo for pushes made with plain git. */
@@ -94,8 +123,109 @@
94123 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };
95124 }
96125
126+ private diskRuntime(): DiskFirstRuntime | undefined {
127+ return this.env.ABSO_DISK_FIRST === "on"
128+ ? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), "server-disk-v1", {
129+ hasBlob: (sha) => this.blobs.has(sha),
130+ whole: this.wholeFiles(),
131+ })
132+ : undefined;
133+ }
134+ private async prepareDisk(validate: () => void = () => {}) {
135+ const runtime = this.diskRuntime();
136+ if (!runtime) return undefined;
137+ const progress = runtime.preparePage(validate);
138+ if (!progress.ready && progress.phase !== "empty") await this.soon(Date.now() + 100);
139+ return progress;
140+ }
141+ /** Once indexing starts, legacy writes would invalidate the persistent root. */
142+ private legacyWritesHeld(): boolean {
143+ if (this.env.ABSO_DISK_FIRST === "on") return false;
144+ const tables = this.ctx.storage.sql
145+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'")
146+ .toArray();
147+ return (
148+ tables.length > 0 &&
149+ new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "format") !== undefined
150+ );
151+ }
152+ private useProject<T>(operation: (calls: EngineProject) => T, write = false): T {
153+ const runtime = this.diskRuntime();
154+ if (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {});
155+ if (write && this.legacyWritesHeld())
156+ throw Error("disk-first indexes exist; enable ABSO_DISK_FIRST before writing");
157+ return operation(this.project as EngineProject);
158+ }
159+ private async diskCall(
160+ name: string,
161+ op: string,
162+ agent: string | undefined,
163+ body: unknown,
164+ how: string | undefined,
165+ revision: number,
166+ ): Promise<Answer> {
167+ const runtime = this.diskRuntime()!;
168+ const validate = () => {
169+ if (revision !== this.authorityRevision)
170+ throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" });
171+ };
172+ const progress = await this.prepareDisk(validate);
173+ const known = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
174+ validate();
175+ let readersChanged = false;
176+ const readers: Readers = {
177+ has: (a) => known.has(a),
178+ list: () => [...known].sort(),
179+ set: (a, on) => {
180+ if (on === known.has(a)) return;
181+ if (on) known.add(a);
182+ else known.delete(a);
183+ readersChanged = true;
184+ },
185+ };
186+ if (progress?.phase === "empty" && op !== "init")
187+ return { status: 404, body: { error: "no such project; run init first" } };
188+ if (!progress?.ready && !(progress?.phase === "empty" && op === "init"))
189+ return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } };
190+ const before = new SqliteLog(this.ctx.storage).seq();
191+ const action = (calls: EngineProject) => {
192+ const result = answer(calls, op, agent, body, readers, how);
193+ if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`);
194+ return result;
195+ };
197+ const result =
198+ progress.phase === "empty"
199+ ? runtime.initialize(action, validate)
200+ : READ_OPS.has(op) || op.startsWith("change/")
201+ ? runtime.read(action, validate)
202+ : runtime.write(action, validate);
203+ if (readersChanged) {
204+ this.authorityRevision++;
205+ await this.ctx.storage.put("readers", readers.list());
206+ }
207+ const log = new SqliteLog(this.ctx.storage);
208+ if (log.seq() !== before) {
209+ this.wake();
210+ await this.ctx.storage.put("name", name);
211+ await this.soon(Date.now() + 100);
212+ }
213+ if (
214+ result.status === 200 &&
215+ artifactsOf(this.env) &&
216+ Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
217+ (await this.ctx.storage.get("name")) !== undefined &&
218+ (await this.ctx.storage.getAlarm()) === null
219+ )
220+ await this.ctx.storage.setAlarm(Date.now());
221+ if (result.status === 200 && op === "starting") result.body = await this.startingHooks(name, result.body);
222+ if (result.status === 200) result.body = this.withBlobSizes(op, result.body);
223+ return result;
224+ }
97226 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */
98227 private ensure(): ProjectCalls | undefined {
228+ if (this.diskRuntime()) throw Error("legacy project load forbidden in disk-first mode");
99229 if (this.loaded || this.tried) return this.loaded;
100230 this.tried = true;
101231 try {
@@ -216,6 +346,7 @@
216346 how?: string,
217347 key?: KeyForCall,
218348 ): Promise<Answer> {
349+ const revision = this.authorityRevision;
219350 if (key) {
220351 const decided = await this.checkAgentKey(key.presented, agent, key.address);
221352 if (!decided.ok) return { status: decided.status, body: { error: decided.error } };
@@ -224,6 +355,17 @@
224355 how = decided.as;
225356 }
226357 if (op === "feed" && !inFeed) return this.feed(name, body);
358+ if (this.diskRuntime()) {
359+ try {
360+ return await this.diskCall(name, op, agent, body, how, revision);
361+ } catch (error) {
362+ if ((error as { code?: string })?.code === "authority-changed")
363+ return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } };
364+ throw error;
365+ }
366+ }
367+ if (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith("change/"))
368+ return { status: 409, body: { error: "disk-first indexes exist; enable ABSO_DISK_FIRST before writing" } };
227369 if (SOFT_HELD_OPS.has(op)) {
228370 const held = this.softHeld();
229371 if (held) return { status: 507, body: { error: held } };
@@ -332,16 +474,20 @@
332474 }
333475
334476 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {
477+ if (this.legacyWritesHeld()) return null;
335478 const artifacts = artifactsOf(this.env);
336479 if (!artifacts) return null;
337480 this.gitCheckedAt = Date.now();
338481 const name = await this.ctx.storage.get<string>("name");
339− if (!name || !this.project.exists()) return null;
482+ if (!name) return null;
483+ const progress = await this.prepareDisk();
484+ if (progress && !progress.ready) return null;
485+ if (!this.useProject((p) => p.exists())) return null;
340486 const seen = await this.ctx.storage.get<string>("git:head");
341487 const pushed = await this.ctx.storage.get<PushResult>("pushed");
342488 const head = await remoteHead(artifacts, name);
343489 if (!head || head === seen || head === pushed?.commit) return null;
344− const sharedBlobs = this.project.shared().blobs ?? {};
490+ const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});
345491 const found = await pushedSince(
346492 artifacts,
347493 name,
@@ -355,7 +501,10 @@
355501 }
356502 let result: unknown;
357503 try {
358− result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
504+ result = this.useProject(
505+ (p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()),
506+ true,
507+ );
359508 } catch (e) {
360509 result = { error: e instanceof Error ? e.message : String(e) };
361510 }
@@ -383,10 +532,14 @@
383532 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.
384533 */
385534 async alarm(): Promise<void> {
535+ if (!this.diskRuntime() && !artifactsOf(this.env)) return;
536+ if (!this.diskRuntime() && !this.ensure()) return;
537+ const progress = await this.prepareDisk();
538+ if (progress && !progress.ready) return;
386539 const artifacts = artifactsOf(this.env);
387540 if (!artifacts) return;
388541 const name = await this.ctx.storage.get<string>("name");
389− if (!name || !this.ensure()?.exists()) return;
542+ if (!name || !this.useProject((p) => p.exists())) return;
390543 await this.gitSync().then(
391544 () => this.ctx.storage.delete("git:error"),
392545 (e) =>
@@ -395,7 +548,7 @@
395548 error: e instanceof Error ? e.message : String(e),
396549 }),
397550 );
398− const shared = this.project.shared();
551+ const shared = this.useProject((p) => p.shared());
399552 const done = await this.ctx.storage.get<PushResult>("pushed");
400553 if (done && done.version >= shared.version) return;
401554 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0;
@@ -422,17 +575,16 @@
422575 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() });
423576 await this.ctx.storage.delete("pushError");
424577 // Another publish may have landed while this push ran.
425− if (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
578+ if (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
426579 }
427580
428581 /** The push out: the repo, the last version pushed, and plain-git intake. */
429582 async out() {
430583 const name = await this.ctx.storage.get<string>("name");
431− const p = this.ensure();
432584 return {
433585 repo: name ? repoName(name) : null,
434586 artifacts: artifactsOf(this.env) ? "bound" : "unbound",
435− version: p?.exists() ? p.shared().version : null,
587+ version: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null,
436588 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null,
437589 error: (await this.ctx.storage.get("pushError")) ?? null,
438590 git: {
@@ -471,6 +623,7 @@
471623 if (typeof when !== "number") return { error: when.error };
472624 const state = await this.keyState();
473625 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role);
626+ this.authorityRevision++;
474627 await this.ctx.storage.put("agent-keys", state);
475628 return issued;
476629 }
@@ -480,6 +633,7 @@
480633 if (!secret) return { revoked: false };
481634 const state = await this.keyState();
482635 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));
636+ this.authorityRevision++;
483637 await this.ctx.storage.put("agent-keys", state);
484638 return { revoked };
485639 }
@@ -492,9 +646,11 @@
492646
493647 /** The project's agent names, for the ask seat check. None when there's no project. */
494648 async agents(_project: string): Promise<string[]> {
495− const p = this.ensure();
496− if (!p?.exists()) return [];
497− return p.status().agents.map((a) => a.agent);
649+ if (!this.diskRuntime() && !this.ensure()) return [];
650+ const progress = await this.prepareDisk();
651+ if (progress?.phase === "empty") return [];
652+ if (progress && !progress.ready) throw Error("project indexes are being prepared");
653+ return this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : []));
498654 }
499655
500656 /**
@@ -502,33 +658,41 @@
502658 * its issue and to the known agents in `to`, never back to its writer.
503659 */
504660 async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {
505− const p = this.ensure();
506− if (!p?.exists()) return items.map(() => ({ to: [] }));
507− const engine = p as ProjectCalls & ProjectHistory;
508− const out: { to: string[] }[] = [];
509− for (const item of items) {
510− const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
511− const known = new Set(status.agents.map((a) => a.agent));
512− const to = new Set([
513− ...(item.issue !== null
514− ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
515− : []),
516− ...(item.to ?? []).filter((t) => known.has(t)),
517− ]);
518− to.delete(item.from);
519− if (to.size === 0) {
520− out.push({ to: [] });
521− continue;
661+ if (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] }));
662+ const progress = await this.prepareDisk();
663+ if (progress?.phase === "empty") return items.map(() => ({ to: [] }));
664+ if (progress && !progress.ready) throw Error("project indexes are being prepared");
665+ return this.useProject((p) => {
666+ if (!p.exists()) return items.map(() => ({ to: [] }));
667+ const engine = p as ProjectCalls & ProjectHistory;
668+ const out: { to: string[] }[] = [];
669+ for (const item of items) {
670+ const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
671+ const known = new Set(status.agents.map((a) => a.agent));
672+ const to = new Set([
673+ ...(item.issue !== null
674+ ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
675+ : []),
676+ ...(item.to ?? []).filter((t) => known.has(t)),
677+ ]);
678+ to.delete(item.from);
679+ if (to.size === 0) {
680+ out.push({ to: [] });
681+ continue;
682+ }
683+ try {
684+ engine.announce(item.from, item.text, [...to]);
685+ out.push({ to: [...to] });
686+ } catch (e) {
687+ // Persistent writer state may already have changed. Let the outer
688+ // transaction undo the whole batch before reporting a failure.
689+ if (this.env.ABSO_DISK_FIRST === "on") throw e;
690+ console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
691+ out.push({ to: [] });
692+ }
522693 }
523− try {
524− engine.announce(item.from, item.text, [...to]);
525− out.push({ to: [...to] });
526− } catch (e) {
527− console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
528− out.push({ to: [] });
529− }
530− }
531− this.wake();
532− return out;
694+ this.wake();
695+ return out;
696+ }, true);
533697 }
534698}
--- a/server/src/writer-host.ts
+++ b/server/src/writer-host.ts
@@ -351,7 +351,7 @@
351351 readViewProvider: projection?.readViewProvider,
352352 entryAt: (index) => this.#log.since(index, 1)[0]!,
353353 });
354− const result = input.operation(new EngineProject(project));
354+ const result = input.operation(new EngineProject(project, (from, limit) => this.#log.since(from, limit)));
355355 SqliteWriterHost.#sync(result);
356356 SqliteWriterHost.#sync(input.validateAuthority());
357357 if (!SqliteWriterHost.#same(source, this.source())) throw new Error("reader source changed");
--- /dev/null
+++ b/server/test/disk-first-runtime.test.ts
@@ -0,0 +1,132 @@
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 { Project } from "../../worker/project/project.ts";
8+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
9+import { SqliteLog } from "../src/engine-project.ts";
10+import { memoryStorage } from "./helpers.ts";
12+test("runtime resumes from disk and detaches reads, with exact authorized retries", (t) => {
13+ const directory = mkdtempSync(join(tmpdir(), "abso-runtime-"));
14+ const filename = join(directory, "state.sqlite");
15+ let storage = memoryStorage(filename);
16+ t.after(() => {
17+ storage.db.close();
18+ unlinkSync(filename);
19+ rmdirSync(directory);
20+ });
21+ const runtime = () => new DiskFirstRuntime(storage, "project-1", "disk-v1");
22+ const validate = () => {};
23+ t.mock.method(Project, "load", () => {
24+ throw Error("full-history load forbidden");
25+ });
26+ assert.equal(runtime().preparePage(validate).phase, "empty");
27+ assert.equal(
28+ storage.db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'writer_state'").get()!.n,
29+ 0,
30+ "an empty lookup must not install the legacy-write fence",
31+ );
32+ assert.equal(
33+ runtime().initialize((calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }), validate)
34+ .status,
35+ 200,
36+ );
37+ assert.throws(() => runtime().write(() => undefined, validate), /not complete/);
38+ let pages = 0;
39+ while (!runtime().preparePage(validate).ready) {
40+ assert.ok(++pages < 100);
41+ storage.db.close();
42+ storage = memoryStorage(filename);
43+ }
44+ assert.ok(pages > 0);
45+ const req = { id: "record-1", identity: { agent: "alice", operation: "record", files: { "a.txt": "changed\n" } } };
46+ const operation = (calls: Parameters<Parameters<DiskFirstRuntime["write"]>[0]>[0]) =>
47+ answer(calls, "record", "alice", { files: req.identity.files });
48+ const first = runtime().write(operation, validate, req);
49+ assert.equal(first.status, 200);
50+ const length = new SqliteLog(storage).seq();
51+ storage.db.close();
52+ storage = memoryStorage(filename);
53+ assert.deepEqual(
54+ runtime().write(
55+ () => {
56+ throw Error("retry executed");
57+ },
58+ validate,
59+ req,
60+ ),
61+ first,
62+ );
63+ assert.equal(new SqliteLog(storage).seq(), length);
64+ assert.throws(() => runtime().write(operation, validate, { ...req, identity: { agent: "bob" } }), /reused/);
65+ assert.throws(
66+ () =>
67+ runtime().write(
68+ operation,
69+ () => {
70+ throw Error("revoked");
71+ },
72+ req,
73+ ),
74+ /revoked/,
75+ );
76+ assert.equal(
77+ runtime().write((calls) => answer(calls, "publish", "alice", { message: "Publish" }), validate).status,
78+ 200,
79+ );
80+ const shared = runtime().read((calls) => calls.shared(), validate);
81+ assert.equal(Object.getOwnPropertyDescriptor(shared, "files")?.get, undefined);
82+ assert.equal(shared.files["a.txt"], "changed\n");
83+ storage.db.close();
84+ storage = memoryStorage(filename);
85+ assert.equal(runtime().preparePage(validate).ready, true);
86+ assert.equal(
87+ runtime().read((calls) => calls.shared().files["a.txt"], validate),
88+ "changed\n",
89+ );
90+});
92+test("runtime page and write authority failures leave no partial state", (t) => {
93+ const storage = memoryStorage();
94+ t.after(() => storage.db.close());
95+ const runtime = new DiskFirstRuntime(storage, "project", "disk-v1");
96+ runtime.initialize(
97+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
98+ () => {},
99+ );
100+ const rows = () => {
101+ const tables = storage.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all();
102+ return tables.map((row) => [
103+ row.name,
104+ storage.db.prepare(`SELECT * FROM "${String(row.name).replaceAll('"', '""')}" ORDER BY rowid`).all(),
105+ ]);
106+ };
107+ const before = rows();
108+ let checks = 0;
109+ assert.throws(
110+ () =>
111+ runtime.preparePage(() => {
112+ if (++checks === 3) throw Error("authority changed");
113+ }),
114+ /authority changed/,
115+ );
116+ assert.deepEqual(rows(), before);
117+ while (!runtime.preparePage(() => {}).ready) {}
118+ const adopted = rows();
119+ checks = 0;
120+ assert.throws(
121+ () =>
122+ runtime.write(
123+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }),
124+ () => {
125+ if (++checks === 3) throw Error("authority changed");
126+ },
127+ { id: "failed", identity: "record" },
128+ ),
129+ /authority changed/,
130+ );
131+ assert.deepEqual(rows(), adopted);
132+});
--- a/server/test/engine-project.test.ts
+++ b/server/test/engine-project.test.ts
@@ -5,6 +5,26 @@
55import { memoryStorage } from "./helpers.ts";
66
77describe("the engine over the object's SQLite log", () => {
8+ it("extracts feed events without retaining a page of canonical payloads", (t) => {
9+ const storage = memoryStorage();
10+ t.after(() => storage.db.close());
11+ const project = EngineProject.open(storage);
12+ answer(project, "init", undefined, { files: { "a.txt": "one\n" } });
13+ answer(project, "sync", "alice", {});
14+ answer(project, "record", "alice", { files: { "a.txt": "two\n" } });
15+ answer(project, "publish", "alice", { message: "Changed" });
16+ const expected = project.feed(0, 500);
17+ const original = SqliteLog.prototype.since;
18+ let reads = 0;
19+ t.mock.method(SqliteLog.prototype, "since", function (this: SqliteLog, from: number, limit: number) {
20+ assert.equal(limit, 1, "feed must release each canonical payload before reading another");
21+ reads++;
22+ return original.call(this, from, limit);
23+ });
24+ assert.deepEqual(project.feed(0, 500), expected);
25+ assert.equal(reads, expected.next);
26+ assert.deepEqual(project.feed(1, 2).events, expected.events.slice(1, 3));
27+ });
828 it("serves init, records and pushes through answer(), and holds a collision", () => {
929 const storage = memoryStorage();
1030 const p = EngineProject.open(storage);
--- /dev/null
+++ b/server/test/project-object-disk-first.test.ts
@@ -0,0 +1,168 @@
1+import assert from "node:assert/strict";
2+import { registerHooks } from "node:module";
3+import { test } from "node:test";
4+import { Project } from "../../worker/project/project.ts";
5+import { EngineProject } from "../src/engine-project.ts";
6+import { memoryStorage } from "./helpers.ts";
7+
8+const hooks = registerHooks({
9+ resolve(specifier, context, next) {
10+ if (specifier === "cloudflare:workers")
11+ return {
12+ url: `data:text/javascript,${encodeURIComponent("export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }")}`,
13+ shortCircuit: true,
14+ };
15+ return next(specifier, context);
16+ },
17+});
18+const { ProjectObject } = await import("../src/project-object.ts");
19+hooks.deregister();
21+test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => {
22+ const storage = memoryStorage();
23+ t.after(() => storage.db.close());
24+ const context = { id: { toString: () => "empty" }, storage: { ...storage, get: async () => undefined } };
25+ const disk = new ProjectObject(context as never, { ABSO_DISK_FIRST: "on" } as never);
26+ assert.deepEqual(await disk.call("empty", "status", undefined, {}), {
27+ status: 404,
28+ body: { error: "no such project; run init first" },
29+ });
30+ assert.deepEqual(await disk.agents("empty"), []);
31+ assert.deepEqual(await disk.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
32+ await disk.alarm();
33+ t.mock.method(EngineProject, "open", () => {
34+ throw Error("unloadable legacy log");
35+ });
36+ const legacy = new ProjectObject(context as never, {} as never);
37+ assert.deepEqual(await legacy.agents("empty"), []);
38+ assert.deepEqual(await legacy.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
39+ await legacy.alarm();
40+});
42+test("ProjectObject disk-first calls survive cold objects without replay", async (t) => {
43+ const storage = memoryStorage();
44+ t.after(() => storage.db.close());
45+ const values = new Map<string, unknown>();
46+ let alarm: number | null = null;
47+ let onReaders: (() => Promise<void>) | undefined;
48+ const context = {
49+ id: { toString: () => "project-1" },
50+ storage: {
51+ ...storage,
52+ get: async (key: string) => {
53+ if (key === "readers" && onReaders) {
54+ const action = onReaders;
55+ onReaders = undefined;
56+ await action();
57+ }
58+ return values.get(key);
59+ },
60+ put: async (key: string | Record<string, unknown>, value?: unknown) => {
61+ if (typeof key === "string") values.set(key, value);
62+ else for (const [name, v] of Object.entries(key)) values.set(name, v);
63+ },
64+ delete: async (key: string) => values.delete(key),
65+ getAlarm: async () => alarm,
66+ setAlarm: async (value: number) => {
67+ alarm = value;
68+ },
69+ },
70+ };
71+ const object = () =>
72+ new ProjectObject(
73+ context as never,
74+ { ABSO_DISK_FIRST: "on", ABSO_ARTIFACTS: "off", KEY_HMAC_SECRET: "invented-test-secret" } as never,
75+ );
76+ t.mock.method(Project, "load", () => {
77+ throw Error("full history replay forbidden");
78+ });
79+ const call = async (op: string, agent: string | undefined, body: unknown) => {
80+ for (let page = 0; page < 100; page++) {
81+ const result = await object().call("project", op, agent, body);
82+ if (result.status !== 503) {
83+ assert.notEqual(result.status, 500, JSON.stringify({ op, result }));
84+ return result;
85+ }
86+ assert.notEqual(alarm, null);
87+ await object().alarm();
88+ }
89+ throw Error("adoption did not finish");
90+ };
91+ assert.equal((await call("init", undefined, { files: { "a.txt": "one\ntwo\n" } })).status, 200);
92+ assert.equal((await call("sync", "alice", {})).status, 200);
93+ assert.equal((await call("record", "alice", { files: { "a.txt": "changed\n" } })).status, 200);
94+ const published = await call("publish", "alice", { message: "Disk first" });
95+ assert.equal(published.status, 200);
96+ assert.equal((published.body as { ok: boolean }).ok, true);
97+ const file = await call("file", undefined, { path: "a.txt", version: "1" });
98+ assert.equal(file.status, 200);
99+ assert.match(JSON.stringify(file.body), /changed/);
100+ const feed = await call("feed", undefined, { from: "0", limit: "2" });
101+ assert.equal(feed.status, 200);
102+ assert.ok((feed.body as { next: number }).next > 0);
103+ assert.deepEqual(await object().agents("project"), ["alice"]);
104+ assert.equal((await object().out()).version, 1);
105+ assert.deepEqual(await object().news("project", [{ from: "bob", issue: null, text: "Hello", to: ["alice"] }]), [
106+ { to: ["alice"] },
107+ ]);
108+ assert.equal((await call("status", undefined, {})).status, 200);
109+ for (const agent of ["alice", "bob"]) assert.equal((await call("sync", agent, {})).status, 200);
110+ assert.equal((await call("record", "alice", { files: { "a.txt": "Alice's change\n" } })).status, 200);
111+ assert.equal((await call("record", "bob", { files: { "a.txt": "Bob's change\n" } })).status, 200);
112+ assert.equal((await call("publish", "alice", { message: "Alice wins first" })).status, 200);
113+ const collision = await call("publish", "bob", { message: "Bob conflicts" });
114+ assert.equal((collision.body as { ok: boolean }).ok, false);
115+ assert.equal((collision.body as { collisions: unknown[] }).collisions.length, 1);
116+ const historical = await call("file", undefined, { path: "a.txt", version: "1" });
117+ assert.equal(historical.status, 200);
118+ assert.match(JSON.stringify(historical.body), /changed/);
119+ const rows = () => ({
120+ log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(),
121+ state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
122+ });
123+ const stable = rows();
124+ const disabled = new ProjectObject(context as never, { ABSO_DISK_FIRST: "off" } as never);
125+ const held = await disabled.call("project", "record", "alice", { files: { "a.txt": "legacy write\n" } });
126+ assert.equal(held.status, 409);
127+ assert.match(JSON.stringify(held.body), /enable ABSO_DISK_FIRST/);
128+ assert.equal(await disabled.gitSync(), null);
129+ assert.deepEqual(rows(), stable);
130+ assert.equal((await call("status", undefined, {})).status, 200, "re-enabling disk mode preserves the valid root");
131+ const originalAnnounce = EngineProject.prototype.announce;
132+ const failingAnnounce = t.mock.method(
133+ EngineProject.prototype,
134+ "announce",
135+ function (this: EngineProject, ...args: Parameters<EngineProject["announce"]>) {
136+ originalAnnounce.apply(this, args);
137+ throw Error("injected after announce");
138+ },
139+ );
140+ await assert.rejects(
141+ () => object().news("project", [{ from: "bob", issue: null, text: "Must roll back", to: ["alice"] }]),
142+ /injected after announce/,
143+ );
144+ assert.deepEqual(rows(), stable);
145+ failingAnnounce.mock.restore();
146+ const current = object();
147+ onReaders = async () => {
148+ await current.revokeAgentKey("missing-test-key", "127.0.0.1");
149+ };
150+ const revoked = await current.call("project", "record", "alice", { files: { "a.txt": "unauthorized\n" } });
151+ assert.equal(revoked.status, 409);
152+ assert.equal((revoked.body as { retryable: boolean }).retryable, true);
153+ assert.deepEqual(rows(), stable);
154+ const original = EngineProject.prototype.record;
155+ t.mock.method(
156+ EngineProject.prototype,
157+ "record",
158+ function (this: EngineProject, ...args: Parameters<EngineProject["record"]>) {
159+ original.apply(this, args);
160+ throw Error("injected after record");
161+ },
162+ );
163+ await assert.rejects(
164+ () => object().call("project", "record", "alice", { files: { "a.txt": "failed\n" } }),
165+ /injected after record/,
166+ );
167+ assert.deepEqual(rows(), stable);
168+});
--- a/src/engine/experimental/projection-locator.ts
+++ b/src/engine/experimental/projection-locator.ts
@@ -120,6 +120,24 @@
120120 }
121121 return undefined;
122122 }
123+ /** Stream immutable leaves in numeric key order, retaining at most eight branch levels. */
124+ *entries(root: Page): IterableIterator<readonly [number, T]> {
125+ page(root);
126+ const index = this;
127+ function* visit(current: Page, parent?: string, digit?: string, depth = 0): IterableIterator<readonly [number, T]> {
128+ if (depth > 8) throw Error("invalid locator depth");
129+ if (current === null) return;
130+ const node = index.#read(current, parent, digit);
131+ if (node.kind === "leaf") {
132+ yield [Number.parseInt(node.prefix, 16), index.#decode(structuredClone(node.value))];
133+ return;
134+ }
135+ for (const digit of Object.keys(node.children).sort())
136+ yield* visit(node.children[digit]!, node.prefix, digit, depth + 1);
137+ }
138+ yield* visit(root);
139+ }
123141 set(root: Page, id: number, value: T): number {
124142 page(root);
125143 const key = keyOf(id),
--- a/src/engine/experimental/projection-reader.ts
+++ b/src/engine/experimental/projection-reader.ts
@@ -23,18 +23,31 @@
2323 get set(): ReadonlySet<string> {
2424 this.#assertLive();
2525 const has = (id: string) =>
26− this.graph.has(id) &&
27− (this.#adapter.members.get(this.#state.membership, this.graph.atom(id).seq)?.present ?? false);
26+ this.graph.has(id) && (this.#adapter.members.get(this.#state.membership, Number(id.slice(1)))?.present ?? false);
2827 const assertLive = this.#assertLive;
28+ const members = this.#adapter.members;
29+ const root = this.#state.membership;
30+ const graph = this.graph;
2931 return new (class extends StableSet<string> {
3032 readonly retainedBytes = 64;
3133 has(id: string): boolean {
3234 assertLive();
3335 return has(id);
3436 }
35− values(): SetIterator<string> {
37+ *values(): SetIterator<string> {
3638 assertLive();
37− throw Error("unsupported projected membership enumeration");
39+ const iterator = members.entries(root);
40+ try {
41+ for (;;) {
42+ assertLive();
43+ const item = iterator.next();
44+ if (item.done) return;
45+ const [seq, member] = item.value;
46+ if (member.present) yield graph.idOfSeq(seq);
47+ }
48+ } finally {
49+ iterator.return?.();
50+ }
3851 }
3952 })();
4053 }
--- /dev/null
+++ b/src/engine/test/projection-membership-iterator.test.ts
@@ -0,0 +1,71 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { ProjectionLocator } from "../experimental/projection-locator.ts";
4+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts";
5+import { ProjectionReader } from "../experimental/projection-reader.ts";
6+import { Graph } from "../graph.ts";
7+import { Repo } from "./helpers.ts";
8+import { SqlState } from "./storage-helper.ts";
9+
10+test("locator streams ordered immutable leaves with bounded first-result reads", () => {
11+ const db = new SqlState();
12+ try {
13+ const index = new ProjectionLocator(db, "iterate", (v) => {
14+ if (typeof v !== "number") throw Error("invalid value");
15+ return v;
16+ });
17+ let root: number | null = null;
18+ for (let id = 511; id >= 0; id--) root = index.set(root, id, id);
19+ const previous = root;
20+ root = index.set(root, 256, -1);
21+ const before = db.reads;
22+ const iterator = index.entries(root);
23+ assert.deepEqual(iterator.next().value, [0, 0]);
24+ assert.ok(db.reads - before <= 9);
25+ iterator.return?.();
26+ assert.deepEqual(
27+ [...index.entries(previous)],
28+ Array.from({ length: 512 }, (_, id) => [id, id]),
29+ );
30+ assert.equal([...index.entries(root)][256]?.[1], -1);
31+ db.write('experimental-locator:"iterate"', String(root), {
32+ format: 1,
33+ kind: "branch",
34+ prefix: "",
35+ children: { 0: root, 1: root },
36+ });
37+ assert.throws(() => index.entries(root).next(), /invalid locator child/);
38+ } finally {
39+ db.db.close();
40+ }
41+});
43+test("projected membership streams without atom payload reads and expires with its scope", () => {
44+ const db = new SqlState();
45+ try {
46+ const repo = Repo.init({ "a.txt": "one\n" });
47+ const atoms = [repo.graph.atom("a0"), repo.edit({ edits: [{ file: "a.txt", old: "one\n", new: "two\n" }] })];
48+ const graph = new Graph({ storage: db });
49+ for (const atom of atoms) graph.add(atom);
50+ const adapter = new ExperimentalMarkerProjection(db, graph, "a.txt", "membership");
51+ let state = adapter.empty();
52+ for (const atom of atoms) state = adapter.apply(state, atom);
53+ let live = true;
54+ const reader = new ProjectionReader(adapter, state, () => {
55+ if (!live) throw Error("expired");
56+ });
57+ const read = db.read.bind(db);
58+ db.read = (collection, key) => {
59+ if (collection === "atoms") throw Error("atom payload read forbidden");
60+ return read(collection, key);
61+ };
62+ assert.deepEqual([...reader.set], ["a0", "a1"]);
63+ assert.equal(reader.set.has("a1"), true);
64+ const iterator = reader.set.values();
65+ assert.equal(iterator.next().value, "a0");
66+ live = false;
67+ assert.throws(() => iterator.next(), /expired/);
68+ } finally {
69+ db.db.close();
70+ }
71+});
--- a/worker/project/changes-since.ts
+++ b/worker/project/changes-since.ts
@@ -26,11 +26,10 @@
2626 [before.set, after.set],
2727 [after.set, before.set],
2828 ] as const) {
29− for (const file of host.touchedFiles(
30− [...a].filter((id) => !b.has(id)),
31− [before, after],
32− ))
33− touched.add(file);
29+ const changed = function* () {
30+ for (const id of a) if (!b.has(id)) yield id;
31+ };
32+ for (const file of host.touchedFiles(changed(), [before, after])) touched.add(file);
3433 }
3534 const files: Files = {};
3635 const modes: Modes = {};