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 184 --json
JSON
/christopher/abso-core/versions/184?format=json

Stream retry receipt persistence and request identity hashing while preserving existing receipt bytes and replay behavior

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

Version 183 · Files at version 184

5 files, 234 lines added, 18 removed.

--- a/server/src/disk-first-runtime.ts
+++ b/server/src/disk-first-runtime.ts
@@ -1,10 +1,11 @@
11import { createHash } from "node:crypto";
2−import { canonicalJson } from "../../worker/project/operation-protocol.ts";
2+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts";
33import { Project, type WriterSource } from "../../worker/project/project.ts";
44import type { ProjectOptions } from "../../worker/project/project-types.ts";
55import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts";
66import { SqliteHistoryHost } from "./history-host.ts";
77import { SqliteProjectionStore } from "./projection-store.ts";
8+import { requestIdentityDigest } from "./request-identity-digest.ts";
89import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts";
1011type Services = Pick<ProjectOptions, "hasBlob" | "whole">;
@@ -46,17 +47,27 @@
4647 #saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) {
4748 // Receipt payloads can exceed the graph-state value bound. Keep each stored
4849 // piece small without increasing that bound for engine state.
49− const json = JSON.stringify({ result });
5050 const characters = 64 * 1024;
51− const parts = Math.ceil(json.length / characters);
52− for (let part = 0; part < parts; part++)
53− state.write(`runtime:receipt:${id}`, String(part), json.slice(part * characters, (part + 1) * characters));
51+ const digest = createHash("sha256");
52+ let pending = "",
53+ parts = 0,
54+ length = 0;
55+ for (const chunk of jsonValueChunks({ result }, { maxDepth: Infinity, unboxPrimitives: true })) {
56+ digest.update(chunk);
57+ length += chunk.length;
58+ pending += chunk;
59+ while (pending.length >= characters) {
60+ state.write(`runtime:receipt:${id}`, String(parts++), pending.slice(0, characters));
61+ pending = pending.slice(characters);
62+ }
63+ }
64+ if (pending) state.write(`runtime:receipt:${id}`, String(parts++), pending);
5465 state.write("runtime:receipts", id, {
5566 format: 3,
5667 identity,
5768 parts,
58− characters: json.length,
59− digest: createHash("sha256").update(json).digest("hex"),
69+ characters: length,
70+ digest: digest.digest("hex"),
6071 });
6172 }
6273 #receiptResult<T>(
@@ -117,12 +128,7 @@
117128 const result = structuredClone(operation(new EngineProject(project)));
118129 this.#validate(validate);
119130 if (request && log.seq() > 0)
120− this.#saveReceipt(
121− this.#setup(),
122− request.id,
123− createHash("sha256").update(canonicalJson(request.identity)).digest("hex"),
124− result,
125− );
131+ this.#saveReceipt(this.#setup(), request.id, requestIdentityDigest(request.identity), result);
126132 return result;
127133 });
128134 }
@@ -223,7 +229,7 @@
223229 const host = this.#host();
224230 host.root();
225231 if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity");
226− const identity = request ? createHash("sha256").update(canonicalJson(request.identity)).digest("hex") : undefined;
232+ const identity = request ? requestIdentityDigest(request.identity) : undefined;
227233 if (request) {
228234 const receipt = state.read("runtime:receipts", request.id) as
229235 | { format: number; identity: string; result: T }
--- /dev/null
+++ b/server/src/request-identity-digest.ts
@@ -0,0 +1,46 @@
1+import { createHash } from "node:crypto";
2+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts";
3+
4+/** Preserve canonicalJson identity bytes without retaining the complete encoded request. */
5+export function requestIdentityDigest(value: unknown): string {
6+ const hash = createHash("sha256");
7+ const active = new Set<object>();
8+ function* chunks(input: unknown, absent?: string): Generator<string> {
9+ if (typeof input === "string") {
10+ yield* jsonValueChunks(input);
11+ } else if (input && typeof input === "object") {
12+ if (active.has(input)) throw new TypeError("cyclic request identity");
13+ active.add(input);
14+ try {
15+ if (Array.isArray(input)) {
16+ yield "[";
17+ const length = input.length;
18+ for (let i = 0; i < length; i++) {
19+ if (i) yield ",";
20+ if (i in input) yield* chunks(input[i], "");
21+ }
22+ yield "]";
23+ } else {
24+ yield "{";
25+ let first = true;
26+ for (const key of Object.keys(input).sort()) {
27+ if (!first) yield ",";
28+ first = false;
29+ yield* jsonValueChunks(key);
30+ yield ":";
31+ yield* chunks((input as Record<string, unknown>)[key], "undefined");
32+ }
33+ yield "}";
34+ }
35+ } finally {
36+ active.delete(input);
37+ }
38+ } else {
39+ const encoded = JSON.stringify(input);
40+ if (encoded === undefined && absent === undefined) throw new TypeError("unsupported request identity");
41+ yield encoded ?? absent!;
42+ }
43+ }
44+ for (const chunk of chunks(value)) hash.update(chunk);
45+ return hash.digest("hex");
46+}
--- a/server/test/disk-first-runtime.test.ts
+++ b/server/test/disk-first-runtime.test.ts
@@ -1,4 +1,5 @@
11import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
23import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
34import { tmpdir } from "node:os";
45import { join } from "node:path";
@@ -356,7 +357,7 @@
356357 () => {},
357358 );
358359 while (!runtime().preparePage(() => {}).ready) {}
359− const large = "x".repeat(8_100_000);
360+ const large = "x".repeat(65503) + "🚀" + '\u0000\n"\\é中\ud800'.repeat(1_000_000);
360361 const request = { id: "large-response", identity: { agent: "alice", operation: "large-fixture" } };
361362 const result = runtime().write(
362363 (calls) => {
@@ -368,6 +369,16 @@
368369 request,
369370 );
370371 assert.equal(result.body.length, large.length);
372+ const state = new SqliteWriterState(storage, "large-receipt");
373+ const header = state.read("runtime:receipts", request.id) as { parts: number; characters: number; digest: string };
374+ const expected = JSON.stringify({ result });
375+ assert.equal(header.characters, expected.length);
376+ assert.equal(header.digest, createHash("sha256").update(expected).digest("hex"));
377+ for (let part = 0; part < header.parts; part++)
378+ assert.equal(
379+ state.read(`runtime:receipt:${request.id}`, String(part)),
380+ expected.slice(part * 65536, (part + 1) * 65536),
381+ );
371382 const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
372383 const replay = runtime().write(
373384 () => {
--- /dev/null
+++ b/server/test/request-identity-digest.test.ts
@@ -0,0 +1,148 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { test } from "node:test";
4+import { answer } from "../../worker/project/http.ts";
5+import { canonicalJson } from "../../worker/project/operation-protocol.ts";
6+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
7+import { SqliteLog } from "../src/engine-project.ts";
8+import { requestIdentityDigest } from "../src/request-identity-digest.ts";
9+import { SqliteWriterState } from "../src/writer-host.ts";
10+import { memoryStorage } from "./helpers.ts";
12+test("request identity hashes preserve canonical bytes and legacy omission semantics", () => {
13+ const shared = { z: 1, a: "same" };
14+ for (const value of [
15+ null,
16+ true,
17+ false,
18+ 0,
19+ -0,
20+ 1e30,
21+ NaN,
22+ Infinity,
23+ { z: [shared, shared], a: { "10": 10, "2": 2, b: undefined, c: Symbol("x"), d: () => 1 } },
24+ Object.assign(new Array(5), { 0: undefined, 2: null, 3: Symbol("x"), 4: () => 1 }),
25+ { toJSON: () => "ignored by canonicalJson", value: "original" },
26+ { body: { files: { "large.txt": `${"x".repeat(16383)}🚀${'\u0000\n"\\é中\ud800'.repeat(100000)}` } } },
27+ ]) {
28+ assert.equal(requestIdentityDigest(value), createHash("sha256").update(canonicalJson(value)).digest("hex"));
29+ }
30+});
32+test("large request strings never reach a whole-string JSON encoder", (t) => {
33+ const value = { body: { files: { "a.txt": "🚀abc\n".repeat(500000) } } };
34+ const expected = createHash("sha256").update(canonicalJson(value)).digest("hex");
35+ const stringify = JSON.stringify;
36+ t.mock.method(JSON, "stringify", (input: unknown) => {
37+ if (typeof input === "string") assert.ok(input.length <= 16384);
38+ else assert.ok(input === null || typeof input !== "object", "whole request serialization forbidden");
39+ return stringify(input);
40+ });
41+ assert.equal(requestIdentityDigest(value), expected);
42+});
44+test("invalid identities fail instead of hashing a different value", () => {
45+ for (const value of [undefined, Symbol("x"), () => 1, 1n]) assert.throws(() => requestIdentityDigest(value));
46+ const cyclic: unknown[] = [];
47+ cyclic.push(cyclic);
48+ assert.throws(() => requestIdentityDigest(cyclic), /cyclic/);
49+});
51+test("a reopened runtime replays legacy receipts without executing the operation", (t) => {
52+ const storage = memoryStorage();
53+ t.after(() => storage.db.close());
54+ const runtime = () => new DiskFirstRuntime(storage, "legacy-identity", "legacy-identity");
55+ runtime().initialize(
56+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
57+ () => {},
58+ );
59+ while (!runtime().preparePage(() => {}).ready) {}
60+ const state = new SqliteWriterState(storage, "legacy-identity");
61+ const identity = { z: "last", body: { files: { "a.txt": "new\n" } }, a: "first" };
62+ const digest = createHash("sha256").update(canonicalJson(identity)).digest("hex");
63+ const result = { status: 200, body: "🚀\n".repeat(40000) };
64+ const json = JSON.stringify({ result });
65+ const parts = Math.ceil(json.length / 65536);
66+ for (let part = 0; part < parts; part++)
67+ state.write("runtime:receipt:legacy-3", String(part), json.slice(part * 65536, (part + 1) * 65536));
68+ state.write("runtime:receipts", "legacy-3", {
69+ format: 3,
70+ identity: digest,
71+ parts,
72+ characters: json.length,
73+ digest: createHash("sha256").update(json).digest("hex"),
74+ });
75+ state.write("runtime:receipts", "legacy-2", { format: 2, identity: digest, result });
76+ const before = new SqliteLog(storage).seq();
77+ for (const id of ["legacy-2", "legacy-3"]) {
78+ assert.deepEqual(
79+ runtime().write(
80+ () => {
81+ throw Error("legacy operation executed twice");
82+ },
83+ () => {},
84+ { id, identity },
85+ ),
86+ result,
87+ );
88+ assert.throws(
89+ () =>
90+ runtime().write(
91+ () => result,
92+ () => {},
93+ { id, identity: { changed: true } },
94+ ),
95+ /reused/,
96+ );
97+ assert.throws(
98+ () =>
99+ runtime().write(
100+ () => result,
101+ () => {
102+ throw Error("revoked");
103+ },
104+ { id, identity },
105+ ),
106+ /revoked/,
107+ );
108+ }
109+ assert.equal(new SqliteLog(storage).seq(), before);
110+});
112+test("receipt streaming preserves deep results and boxed primitive JSON behavior", (t) => {
113+ const storage = memoryStorage();
114+ t.after(() => storage.db.close());
115+ const runtime = () => new DiskFirstRuntime(storage, "receipt-compat", "receipt-compat");
116+ runtime().initialize(
117+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
118+ () => {},
119+ );
120+ while (!runtime().preparePage(() => {}).ready) {}
121+ let deep: unknown = "leaf";
122+ for (let i = 0; i < 200; i++) deep = { child: deep };
123+ const values = [deep, new String("boxed"), new Number(42), new Boolean(false)];
124+ for (let i = 0; i < values.length; i++) {
125+ const request = { id: "compat-" + i, identity: { i } };
126+ const before = new SqliteLog(storage).seq();
127+ runtime().write(
128+ (calls) => {
129+ const result = answer(calls, "record", "fixture", { files: { "a.txt": "value-" + i } });
130+ assert.equal(result.status, 200);
131+ return values[i];
132+ },
133+ () => {},
134+ request,
135+ );
136+ assert.ok(new SqliteLog(storage).seq() > before);
137+ assert.deepEqual(
138+ runtime().write(
139+ () => {
140+ throw Error("retry executed");
141+ },
142+ () => {},
143+ request,
144+ ),
145+ JSON.parse(JSON.stringify(values[i])),
146+ );
147+ }
148+});
--- a/src/engine/json-value-chunks.ts
+++ b/src/engine/json-value-chunks.ts
@@ -18,7 +18,10 @@
1818/** JSON.stringify-compatible chunks for canonical data, without a whole-value string.
1919 * Individual input strings and object key lists still belong to the caller.
2020 */
21−export function* jsonValueChunks(input: unknown): IterableIterator<string> {
21+export function* jsonValueChunks(
22+ input: unknown,
23+ options: { maxDepth?: number; unboxPrimitives?: boolean } = {},
24+): IterableIterator<string> {
2225 const active = new Set<object>();
2326 function* string(value: string): IterableIterator<string> {
2427 yield '"';
@@ -38,8 +41,10 @@
3841 const streaming = streamingValues.get(value);
3942 if (streaming) return streaming();
4043 const toJSON = (value as { toJSON?: unknown }).toJSON;
41− if (typeof toJSON === "function") return toJSON.call(value, key);
44+ if (typeof toJSON === "function") value = toJSON.call(value, key);
4245 }
46+ if (options.unboxPrimitives && (value instanceof String || value instanceof Number || value instanceof Boolean))
47+ return value.valueOf();
4348 return value;
4449 };
4550 const omitted = (value: unknown) => value === undefined || typeof value === "function" || typeof value === "symbol";
@@ -63,7 +68,7 @@
6368 else if (typeof value !== "object" || value === null) throw Error("unsupported canonical JSON value");
6469 else {
6570 if (active.has(value)) throw Error("cyclic canonical JSON value");
66− if (active.size >= 128) throw Error("canonical JSON depth exceeds bound");
71+ if (active.size >= (options.maxDepth ?? 128)) throw Error("canonical JSON depth exceeds bound");
6772 active.add(value);
6873 try {
6974 if (Array.isArray(value)) {