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"); 55+ for (const chunk of jsonValueChunks({ result }, { maxDepth: Infinity, unboxPrimitives: true })) { 56+ digest.update(chunk); 57+ length += chunk.length; 59+ while (pending.length >= characters) { 60+ state.write(`runtime:receipt:${id}`, String(parts++), pending.slice(0, characters)); 61+ pending = pending.slice(characters); 64+ if (pending) state.write(`runtime:receipt:${id}`, String(parts++), pending); 5465 state.write("runtime:receipts", id, { 58− characters: json.length,
59− digest: createHash("sha256").update(json).digest("hex"),
70+ digest: digest.digest("hex"), @@ -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); @@ -223,7 +229,7 @@
223229 const host = this.#host(); 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; 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"; 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"); 15+ if (Array.isArray(input)) { 17+ const length = input.length; 18+ for (let i = 0; i < length; i++) { 20+ if (i in input) yield* chunks(input[i], ""); 26+ for (const key of Object.keys(input).sort()) { 27+ if (!first) yield ","; 29+ yield* jsonValueChunks(key); 31+ yield* chunks((input as Record<string, unknown>)[key], "undefined"); 36+ active.delete(input); 39+ const encoded = JSON.stringify(input); 40+ if (encoded === undefined && absent === undefined) throw new TypeError("unsupported request identity"); 41+ yield encoded ?? absent!; 44+ for (const chunk of chunks(value)) hash.update(chunk); 45+ return hash.digest("hex"); --- 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 @@
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( @@ -368,6 +369,16 @@
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++) 379+ state.read(`runtime:receipt:${request.id}`, String(part)), 380+ expected.slice(part * 65536, (part + 1) * 65536), 371382 const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 372383 const replay = runtime().write( --- /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 [ 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)}` } } }, 28+ assert.equal(requestIdentityDigest(value), createHash("sha256").update(canonicalJson(value)).digest("hex")); 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); 41+ assert.equal(requestIdentityDigest(value), expected); 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[] = []; 48+ assert.throws(() => requestIdentityDigest(cyclic), /cyclic/); 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" } }), 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", { 72+ characters: json.length, 73+ digest: createHash("sha256").update(json).digest("hex"), 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"]) { 81+ throw Error("legacy operation executed twice"); 93+ { id, identity: { changed: true } }, 102+ throw Error("revoked"); 109+ assert.equal(new SqliteLog(storage).seq(), before); 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" } }), 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(); 129+ const result = answer(calls, "record", "fixture", { files: { "a.txt": "value-" + i } }); 130+ assert.equal(result.status, 200); 136+ assert.ok(new SqliteLog(storage).seq() > before); 140+ throw Error("retry executed"); 145+ JSON.parse(JSON.stringify(values[i])), --- 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. 21−export function* jsonValueChunks(input: unknown): IterableIterator<string> {
21+export function* jsonValueChunks( 23+ options: { maxDepth?: number; unboxPrimitives?: boolean } = {}, 24+): IterableIterator<string> { 2225 const active = new Set<object>(); 2326 function* string(value: string): IterableIterator<string> { @@ -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); 46+ if (options.unboxPrimitives && (value instanceof String || value instanceof Number || value instanceof Boolean)) 47+ return value.valueOf(); 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"); 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"); 6974 if (Array.isArray(value)) {