{"version":184,"agent":"codex-capacity-chair","message":"Stream retry receipt persistence and request identity hashing while preserving existing receipt bytes and replay behavior","time":1791978764980,"timeIso":"2026-10-14T11:52:44.980Z","changes":6,"change":2992,"files":["server/src/disk-first-runtime.ts","server/src/request-identity-digest.ts","server/test/disk-first-runtime.test.ts","server/test/request-identity-digest.test.ts","src/engine/json-value-chunks.ts"],"draft":null,"diff":[{"path":"server/src/disk-first-runtime.ts","added":20,"removed":14,"diff":"--- a/server/src/disk-first-runtime.ts\n+++ b/server/src/disk-first-runtime.ts\n@@ -1,10 +1,11 @@\n import { createHash } from \"node:crypto\";\n-import { canonicalJson } from \"../../worker/project/operation-protocol.ts\";\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@@ -46,17 +47,27 @@\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 json = JSON.stringify({ result });\n \t\tconst characters = 64 * 1024;\n-\t\tconst parts = Math.ceil(json.length / characters);\n-\t\tfor (let part = 0; part < parts; part++)\n-\t\t\tstate.write(`runtime:receipt:${id}`, String(part), json.slice(part * characters, (part + 1) * characters));\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: json.length,\n-\t\t\tdigest: createHash(\"sha256\").update(json).digest(\"hex\"),\n+\t\t\tcharacters: length,\n+\t\t\tdigest: digest.digest(\"hex\"),\n \t\t});\n \t}\n \t#receiptResult<T>(\n@@ -117,12 +128,7 @@\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(\n-\t\t\t\t\tthis.#setup(),\n-\t\t\t\t\trequest.id,\n-\t\t\t\t\tcreateHash(\"sha256\").update(canonicalJson(request.identity)).digest(\"hex\"),\n-\t\t\t\t\tresult,\n-\t\t\t\t);\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@@ -223,7 +229,7 @@\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 ? createHash(\"sha256\").update(canonicalJson(request.identity)).digest(\"hex\") : undefined;\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 }"},{"path":"server/src/request-identity-digest.ts","added":46,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/request-identity-digest.ts\n@@ -0,0 +1,46 @@\n+import { createHash } from \"node:crypto\";\n+import { jsonValueChunks } from \"../../src/engine/json-value-chunks.ts\";\n+\n+/** Preserve canonicalJson identity bytes without retaining the complete encoded request. */\n+export function requestIdentityDigest(value: unknown): string {\n+\tconst hash = createHash(\"sha256\");\n+\tconst active = new Set<object>();\n+\tfunction* chunks(input: unknown, absent?: string): Generator<string> {\n+\t\tif (typeof input === \"string\") {\n+\t\t\tyield* jsonValueChunks(input);\n+\t\t} else if (input && typeof input === \"object\") {\n+\t\t\tif (active.has(input)) throw new TypeError(\"cyclic request identity\");\n+\t\t\tactive.add(input);\n+\t\t\ttry {\n+\t\t\t\tif (Array.isArray(input)) {\n+\t\t\t\t\tyield \"[\";\n+\t\t\t\t\tconst length = input.length;\n+\t\t\t\t\tfor (let i = 0; i < length; i++) {\n+\t\t\t\t\t\tif (i) yield \",\";\n+\t\t\t\t\t\tif (i in input) yield* chunks(input[i], \"\");\n+\t\t\t\t\t}\n+\t\t\t\t\tyield \"]\";\n+\t\t\t\t} else {\n+\t\t\t\t\tyield \"{\";\n+\t\t\t\t\tlet first = true;\n+\t\t\t\t\tfor (const key of Object.keys(input).sort()) {\n+\t\t\t\t\t\tif (!first) yield \",\";\n+\t\t\t\t\t\tfirst = false;\n+\t\t\t\t\t\tyield* jsonValueChunks(key);\n+\t\t\t\t\t\tyield \":\";\n+\t\t\t\t\t\tyield* chunks((input as Record<string, unknown>)[key], \"undefined\");\n+\t\t\t\t\t}\n+\t\t\t\t\tyield \"}\";\n+\t\t\t\t}\n+\t\t\t} finally {\n+\t\t\t\tactive.delete(input);\n+\t\t\t}\n+\t\t} else {\n+\t\t\tconst encoded = JSON.stringify(input);\n+\t\t\tif (encoded === undefined && absent === undefined) throw new TypeError(\"unsupported request identity\");\n+\t\t\tyield encoded ?? absent!;\n+\t\t}\n+\t}\n+\tfor (const chunk of chunks(value)) hash.update(chunk);\n+\treturn hash.digest(\"hex\");\n+}"},{"path":"server/test/disk-first-runtime.test.ts","added":12,"removed":1,"diff":"--- a/server/test/disk-first-runtime.test.ts\n+++ b/server/test/disk-first-runtime.test.ts\n@@ -1,4 +1,5 @@\n import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n import { mkdtempSync, rmdirSync, unlinkSync } from \"node:fs\";\n import { tmpdir } from \"node:os\";\n import { join } from \"node:path\";\n@@ -356,7 +357,7 @@\n \t\t() => {},\n \t);\n \twhile (!runtime().preparePage(() => {}).ready) {}\n-\tconst large = \"x\".repeat(8_100_000);\n+\tconst large = \"x\".repeat(65503) + \"🚀\" + '\\u0000\\n\"\\\\é中\\ud800'.repeat(1_000_000);\n \tconst request = { id: \"large-response\", identity: { agent: \"alice\", operation: \"large-fixture\" } };\n \tconst result = runtime().write(\n \t\t(calls) => {\n@@ -368,6 +369,16 @@\n \t\trequest,\n \t);\n \tassert.equal(result.body.length, large.length);\n+\tconst state = new SqliteWriterState(storage, \"large-receipt\");\n+\tconst header = state.read(\"runtime:receipts\", request.id) as { parts: number; characters: number; digest: string };\n+\tconst expected = JSON.stringify({ result });\n+\tassert.equal(header.characters, expected.length);\n+\tassert.equal(header.digest, createHash(\"sha256\").update(expected).digest(\"hex\"));\n+\tfor (let part = 0; part < header.parts; part++)\n+\t\tassert.equal(\n+\t\t\tstate.read(`runtime:receipt:${request.id}`, String(part)),\n+\t\t\texpected.slice(part * 65536, (part + 1) * 65536),\n+\t\t);\n \tconst before = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n \tconst replay = runtime().write(\n \t\t() => {"},{"path":"server/test/request-identity-digest.test.ts","added":148,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/request-identity-digest.test.ts\n@@ -0,0 +1,148 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { canonicalJson } from \"../../worker/project/operation-protocol.ts\";\n+import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { requestIdentityDigest } from \"../src/request-identity-digest.ts\";\n+import { SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"request identity hashes preserve canonical bytes and legacy omission semantics\", () => {\n+\tconst shared = { z: 1, a: \"same\" };\n+\tfor (const value of [\n+\t\tnull,\n+\t\ttrue,\n+\t\tfalse,\n+\t\t0,\n+\t\t-0,\n+\t\t1e30,\n+\t\tNaN,\n+\t\tInfinity,\n+\t\t{ z: [shared, shared], a: { \"10\": 10, \"2\": 2, b: undefined, c: Symbol(\"x\"), d: () => 1 } },\n+\t\tObject.assign(new Array(5), { 0: undefined, 2: null, 3: Symbol(\"x\"), 4: () => 1 }),\n+\t\t{ toJSON: () => \"ignored by canonicalJson\", value: \"original\" },\n+\t\t{ body: { files: { \"large.txt\": `${\"x\".repeat(16383)}🚀${'\\u0000\\n\"\\\\é中\\ud800'.repeat(100000)}` } } },\n+\t]) {\n+\t\tassert.equal(requestIdentityDigest(value), createHash(\"sha256\").update(canonicalJson(value)).digest(\"hex\"));\n+\t}\n+});\n+\n+test(\"large request strings never reach a whole-string JSON encoder\", (t) => {\n+\tconst value = { body: { files: { \"a.txt\": \"🚀abc\\n\".repeat(500000) } } };\n+\tconst expected = createHash(\"sha256\").update(canonicalJson(value)).digest(\"hex\");\n+\tconst stringify = JSON.stringify;\n+\tt.mock.method(JSON, \"stringify\", (input: unknown) => {\n+\t\tif (typeof input === \"string\") assert.ok(input.length <= 16384);\n+\t\telse assert.ok(input === null || typeof input !== \"object\", \"whole request serialization forbidden\");\n+\t\treturn stringify(input);\n+\t});\n+\tassert.equal(requestIdentityDigest(value), expected);\n+});\n+\n+test(\"invalid identities fail instead of hashing a different value\", () => {\n+\tfor (const value of [undefined, Symbol(\"x\"), () => 1, 1n]) assert.throws(() => requestIdentityDigest(value));\n+\tconst cyclic: unknown[] = [];\n+\tcyclic.push(cyclic);\n+\tassert.throws(() => requestIdentityDigest(cyclic), /cyclic/);\n+});\n+\n+test(\"a reopened runtime replays legacy receipts without executing the operation\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"legacy-identity\", \"legacy-identity\");\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst state = new SqliteWriterState(storage, \"legacy-identity\");\n+\tconst identity = { z: \"last\", body: { files: { \"a.txt\": \"new\\n\" } }, a: \"first\" };\n+\tconst digest = createHash(\"sha256\").update(canonicalJson(identity)).digest(\"hex\");\n+\tconst result = { status: 200, body: \"🚀\\n\".repeat(40000) };\n+\tconst json = JSON.stringify({ result });\n+\tconst parts = Math.ceil(json.length / 65536);\n+\tfor (let part = 0; part < parts; part++)\n+\t\tstate.write(\"runtime:receipt:legacy-3\", String(part), json.slice(part * 65536, (part + 1) * 65536));\n+\tstate.write(\"runtime:receipts\", \"legacy-3\", {\n+\t\tformat: 3,\n+\t\tidentity: digest,\n+\t\tparts,\n+\t\tcharacters: json.length,\n+\t\tdigest: createHash(\"sha256\").update(json).digest(\"hex\"),\n+\t});\n+\tstate.write(\"runtime:receipts\", \"legacy-2\", { format: 2, identity: digest, result });\n+\tconst before = new SqliteLog(storage).seq();\n+\tfor (const id of [\"legacy-2\", \"legacy-3\"]) {\n+\t\tassert.deepEqual(\n+\t\t\truntime().write(\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"legacy operation executed twice\");\n+\t\t\t\t},\n+\t\t\t\t() => {},\n+\t\t\t\t{ id, identity },\n+\t\t\t),\n+\t\t\tresult,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\truntime().write(\n+\t\t\t\t\t() => result,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t{ id, identity: { changed: true } },\n+\t\t\t\t),\n+\t\t\t/reused/,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\truntime().write(\n+\t\t\t\t\t() => result,\n+\t\t\t\t\t() => {\n+\t\t\t\t\t\tthrow Error(\"revoked\");\n+\t\t\t\t\t},\n+\t\t\t\t\t{ id, identity },\n+\t\t\t\t),\n+\t\t\t/revoked/,\n+\t\t);\n+\t}\n+\tassert.equal(new SqliteLog(storage).seq(), before);\n+});\n+\n+test(\"receipt streaming preserves deep results and boxed primitive JSON behavior\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"receipt-compat\", \"receipt-compat\");\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tlet deep: unknown = \"leaf\";\n+\tfor (let i = 0; i < 200; i++) deep = { child: deep };\n+\tconst values = [deep, new String(\"boxed\"), new Number(42), new Boolean(false)];\n+\tfor (let i = 0; i < values.length; i++) {\n+\t\tconst request = { id: \"compat-\" + i, identity: { i } };\n+\t\tconst before = new SqliteLog(storage).seq();\n+\t\truntime().write(\n+\t\t\t(calls) => {\n+\t\t\t\tconst result = answer(calls, \"record\", \"fixture\", { files: { \"a.txt\": \"value-\" + i } });\n+\t\t\t\tassert.equal(result.status, 200);\n+\t\t\t\treturn values[i];\n+\t\t\t},\n+\t\t\t() => {},\n+\t\t\trequest,\n+\t\t);\n+\t\tassert.ok(new SqliteLog(storage).seq() > before);\n+\t\tassert.deepEqual(\n+\t\t\truntime().write(\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"retry executed\");\n+\t\t\t\t},\n+\t\t\t\t() => {},\n+\t\t\t\trequest,\n+\t\t\t),\n+\t\t\tJSON.parse(JSON.stringify(values[i])),\n+\t\t);\n+\t}\n+});"},{"path":"src/engine/json-value-chunks.ts","added":8,"removed":3,"diff":"--- a/src/engine/json-value-chunks.ts\n+++ b/src/engine/json-value-chunks.ts\n@@ -18,7 +18,10 @@\n /** JSON.stringify-compatible chunks for canonical data, without a whole-value string.\n  * Individual input strings and object key lists still belong to the caller.\n  */\n-export function* jsonValueChunks(input: unknown): IterableIterator<string> {\n+export function* jsonValueChunks(\n+\tinput: unknown,\n+\toptions: { maxDepth?: number; unboxPrimitives?: boolean } = {},\n+): IterableIterator<string> {\n \tconst active = new Set<object>();\n \tfunction* string(value: string): IterableIterator<string> {\n \t\tyield '\"';\n@@ -38,8 +41,10 @@\n \t\t\tconst streaming = streamingValues.get(value);\n \t\t\tif (streaming) return streaming();\n \t\t\tconst toJSON = (value as { toJSON?: unknown }).toJSON;\n-\t\t\tif (typeof toJSON === \"function\") return toJSON.call(value, key);\n+\t\t\tif (typeof toJSON === \"function\") value = toJSON.call(value, key);\n \t\t}\n+\t\tif (options.unboxPrimitives && (value instanceof String || value instanceof Number || value instanceof Boolean))\n+\t\t\treturn value.valueOf();\n \t\treturn value;\n \t};\n \tconst omitted = (value: unknown) => value === undefined || typeof value === \"function\" || typeof value === \"symbol\";\n@@ -63,7 +68,7 @@\n \t\telse if (typeof value !== \"object\" || value === null) throw Error(\"unsupported canonical JSON value\");\n \t\telse {\n \t\t\tif (active.has(value)) throw Error(\"cyclic canonical JSON value\");\n-\t\t\tif (active.size >= 128) throw Error(\"canonical JSON depth exceeds bound\");\n+\t\t\tif (active.size >= (options.maxDepth ?? 128)) throw Error(\"canonical JSON depth exceeds bound\");\n \t\t\tactive.add(value);\n \t\t\ttry {\n \t\t\t\tif (Array.isArray(value)) {"}],"ci":null}