From ededbd7f247380a8f9f2a8eba4a3ec6603e7a741 Mon Sep 17 00:00:00 2001 From: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 17 Oct 2026 02:51:37 +0000 Subject: [PATCH] perf(experiment): reuse proven native source refusals Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --- experiments/atomic-codemode/README.md | 5 + .../atomic-codemode/capacity-refusal-study.md | 132 ++++++++++++ experiments/atomic-codemode/limits.mjs | 1 + .../atomic-codemode/native-capture-cache.mjs | 99 +++++++++ .../native-capture-cache.test.mjs | 193 ++++++++++++++++++ .../atomic-codemode/native-source-store.mjs | 4 +- experiments/atomic-codemode/provider.mjs | 17 +- .../atomic-codemode/verify-capacity-reuse.mjs | 184 +++++++++++++++++ 8 files changed, 622 insertions(+), 13 deletions(-) create mode 100644 experiments/atomic-codemode/capacity-refusal-study.md create mode 100644 experiments/atomic-codemode/native-capture-cache.mjs create mode 100644 experiments/atomic-codemode/native-capture-cache.test.mjs create mode 100644 experiments/atomic-codemode/verify-capacity-reuse.mjs diff --git a/experiments/atomic-codemode/README.md b/experiments/atomic-codemode/README.md index 8b9bab93671..51016a54ad2 100644 --- a/experiments/atomic-codemode/README.md +++ b/experiments/atomic-codemode/README.md @@ -59,6 +59,11 @@ Both real models now complete the FFmpeg task with all cited raw captures verified. Code Mode uses less cumulative input but more uncached input and time. The study also retains two evaluator namespace failures and their full costs; the corrected pair uses actual registered tool discovery. +The [refusal-cache study](capacity-refusal-study.md) then avoids repeated native +work for proven immutable source-budget failures. Real SDK and both MCP adapters +verify reuse and readable partial Evidence; cancellation/cleanup uncertainty +remain uncached. The first Code Mode precondition failure and its cost remain in +the record. Larger-target inventory coverage is still unresolved. The [AArch64 reference study](aarch64-xref-study.md) finds and fixes missing ADRP-based string and memory references before the next model comparison. diff --git a/experiments/atomic-codemode/capacity-refusal-study.md b/experiments/atomic-codemode/capacity-refusal-study.md new file mode 100644 index 00000000000..d4031c296e7 --- /dev/null +++ b/experiments/atomic-codemode/capacity-refusal-study.md @@ -0,0 +1,132 @@ +# Reuse proven native source refusals + +After the streamed-inventory model pair, main was fetched again and remained +`150e996a8`. Baseline runtime is `b88c75df8`. Native engine remains +`2e398e7229e30b6d2387a802db8a0050764119a6b457020d334855e36e69d6c5`. +This is an experimental follow-up, with no PR or integration into main. + +## Observed redundant work + +Two identical real LLVM string queries in one target lease first hit the 64 MiB +source ceiling after 8.363 seconds. The second still runs native analysis for +3.024 seconds / 3.021736 CPU seconds, retaining another partial prefix and +reporting cleanup uncertainty. The provider discarded every failed work entry, +even a proven output-size refusal for the identical immutable native capture. +The source budget cannot grow within that lease. Neither query produces valid +string facts; absence must remain unknown. + +The same two-request probe after the change takes 7.603 seconds for the first +refusal and 1.528 ms / 0.001567 CPU seconds for reuse. Only one partial source is +captured, with the same readable Evidence handle on both errors. The added +`cached_observation:{kind:"source_budget_refusal",scope:"target_lease"}` labels +the original observation being reused; it does not report a fresh native run or +current process status. Cold-time variation is not a causal speed claim. + +| Same two-request diagnostic probe | Wall s | Local family CPU s | Kernel family peak MiB | +| --------------------------------- | -----: | -----------------: | ---------------------: | +| Before | 12.406 | 12.192070 | 1,745.6 | +| After | 8.579 | 8.364375 | 1,492.5 | + +This compares the same diagnostic intent, not successful LLVM analysis. The +second original attempt adds a cleanup-uncertainty failure, whereas reuse keeps +the original proven resource refusal without starting another process. Different +cold costs and transient ownership observations prevent a pure latency ratio or +general memory/speedup claim. The decisive signal is avoided native work. + +## Cache ownership and invalidation + +`NativeCaptureCache` owns pending/completed native work in one provider lease. +It replaces the old map wrapper. It retains a refusal only for the understood +`FactFailure` resource code, native-source scope, positive safe byte limit and +observed lower bound above that limit, with a retained partial source ID and +only the six understood refusal fields. Secondary file-cleanup uncertainty and +unexamined metadata also prevent reuse. Classification copies own data properties without +invoking getters; unknown/primitive failures retain their original identity. + +Cancellation, I/O, cleanup uncertainty, other resources and unproven constraints +remain uncached. The cache never turns an unknown primary cleanup outcome into +resource success. Error views are separate from the immutable retained refusal, +so editing an SDK error cannot alter later Evidence IDs or limits. At most the +existing 128-source policy's number of work entries is memoized. When that table +is full, new producer results still return without adding retention; the shared +application owner continues to bound native admission. This also bounds any future source/key aliases. No additional source budget is introduced. + +Keys keep the existing native request inputs, with target/engine/profile fixed +by the owner instance. Catalog selectors do not change native capture arguments. +Cache validity follows the immutable artifact capture and nonincreasing source +budget, not live state. Successful captures retain the previous reuse semantics; +close clears the cache after confirmed resource cleanup. A new lease gets a new +owner. No cross-session negative cache is claimed. + +## Actual adapters, failures and verification scope + +Real LLVM SDK and Direct MCP checks pass refusal reuse, unchanged target/lease, +identical refusal details except the explicit reuse label, one raw source, +readable partial Evidence and exact full raw digest. SDK warm latency is 2.282 ms +/ 0.001675 CPU seconds; Direct is 6.412 ms / 0.005566 CPU seconds. Their fresh +first calls take 7.350 / 7.756 seconds respectively. + +The first scripted Code Mode check fails its cache-hit precondition because the +first call reports `cleanup_incomplete`. It correctly does not reuse that +uncertain failure, and the second native attempt takes about 2.905 seconds. +Both partial raw captures independently validate target/engine/hash/length. The +original verifier recorded phases/stack but placed the complete API observation +after its assertions, so the failed API payload is not fully auditable. Preserve +that limitation and the original failed receipt; do not relabel it a pass. + +The verifier now records replies before assertions and stops if cleanup is +uncertain. One fresh scripted coverage repeat then reaches the proven-refusal +path. In one actual MCP execution, the guest calls strings twice and Evidence +once: the second call is 3 ms by guest `Date.now` (millisecond precision, separate +warm CPU unmeasured), with the same handle and exactly one raw source. The full +8.126-second program uses 8.119767 local CPU seconds. The two error results remain +errors; successful composition does not establish successful LLVM analysis. +This is a scripted coverage repeat after a verifier correction, not another +model answer or a replacement for the failed observation. + +| Whole verifier | Wall s | Local family CPU s | Kernel family peak MiB | Result | +| ---------------------------------------- | -----: | -----------------: | ---------------------: | ---------------------------------- | +| SDK refusal + reuse + Evidence | 9.092 | 8.908659 | 1,516.8 | pass | +| Direct MCP same task | 9.886 | 9.666791 | 1,635.9 | pass | +| First Code Mode attempt | 12.909 | 12.680445 | 1,939.9 | cache-hit precondition unavailable | +| Corrected Code Mode coverage repeat | 10.088 | 9.885309 | 1,698.8 | pass | +| Capacity + partial source + cancellation | 9.885 | 9.632806 | 1,487.4 | pass | + +Both Code Mode attempts cost 22.997 family-wall seconds / 22.565754 CPU seconds; +peak across them is 1,939.9 MiB, not the sum of peaks. These receipts are not a +matched adapter performance ranking: verifier work and failure paths differ. +All are one-CPU, 3 GiB early-stop / 4 GiB hard-limit, no-swap runs; payload-exit +observers verify cleanup and OOM=0, including the failed attempt. Final exited- +cgroup counters are unavailable. Kernel family memory includes file cache. + +All 116 experimental JS tests pass, including in-flight reuse, invalidation, +mutable caller views, zero/false/null/unknown errors, noncacheable cleanup, +accessor avoidance and bounded memo admission. Real FFmpeg selected facts, +Evidence, bytes and stale-handle checks pass in SDK/Direct/Code Mode after the +cache change. Cancellation/owned cleanup checks pass. Changed-file lint and +format checks pass. After tightening the sealed-source/secondary-cleanup eligibility guard, the full +116-test suite passes again, and captured SDK/Direct/Code Mode refusal DTOs all +pass through that sealed contract in replay. That replay is a production-boundary +check, not another live-provider or model run. Existing full-suite/resource-gate +limitations from the +[streaming study](streamed-inventory-study.md) remain. No new model trial was +performed for this cache change; the earlier fixed-runtime model costs remain +attached to that earlier runtime. Scripted probes consume no model tokens. + +LLVM and Node inventories still exceed the source budget. This optimization +makes known refusal cheap; producer-side selective computation remains the next +coverage/computation question. It does not improve provider parity or prove +complex reverse-engineering superiority. + +Local artifact SHA-256 (raw documents remain uncommitted): + +- `capacity-cache-before.json`: `68fbd4444c81b4a4435a8d300f8b1ea7365f140078ab3cc322bde140be74db24` +- `capacity-cache-after.json`: `66491d37d85c3748578022e0f7e0f8013c2bf19ecec6d0c73db33d2246c7485e` +- `capacity-cache-before.log`: `d57684ede8f9d01bf9750b78f400b4bb529e2d7a23b84195d79d6d729cba6190` +- `capacity-cache-after.log`: `30039f832930680a8cc128c8a372c0018be08c88ac84e4db03d2cc15e4623b38` +- `capacity-cache-final-sdk.json`: `95326d584a88ca5130e79e116b5c0a14bdbaa0a6016342d58010515e8a6c22f9` +- `capacity-cache-final-direct.json`: `ead7e2c5976e13876d1d34cd336e88f62a2e9bba4b3812bc012efbc64d272473` +- `capacity-cache-final-codemode.json`: `8bb64217d52bdbd1771968b9274d6ae04a6ea3b0ae1e5a09d0510bf180320e7b` +- `capacity-cache-final2-codemode.json`: `4ccf81f282a2f62db00638b6a94feaf80992aacc8096ea15d3fc419f0d2789a3` +- `capacity-cache-js-precommit.log`: `d22b3e948baf2a36ae262786d470af0fc3d631ddd79d88a879ac9f2103352792` +- `capacity-cache-js-sealed.log`: `004ffeac2994612f1608fd5904eff15c41ea059d4ad91644abce8532669a5ea0` diff --git a/experiments/atomic-codemode/limits.mjs b/experiments/atomic-codemode/limits.mjs index 1fce9f8eb35..827f138852f 100644 --- a/experiments/atomic-codemode/limits.mjs +++ b/experiments/atomic-codemode/limits.mjs @@ -1,4 +1,5 @@ // Shared application resource policy, independent of native wire formats. +export const MAX_NATIVE_SOURCES = 128; export const MAX_RETAINED_SOURCE_BYTES = 64 * 1024 * 1024; export const NATIVE_OUTPUT_BYTES = 8 * 1024 * 1024; export const MAX_BRIDGE_BYTES = 2 * 1024 * 1024; diff --git a/experiments/atomic-codemode/native-capture-cache.mjs b/experiments/atomic-codemode/native-capture-cache.mjs new file mode 100644 index 00000000000..66f3d262913 --- /dev/null +++ b/experiments/atomic-codemode/native-capture-cache.mjs @@ -0,0 +1,99 @@ +// Per-lease native work. A proven byte refusal remains valid as storage only shrinks. +import { FactFailure } from "./fact-error.mjs"; +import { MAX_NATIVE_SOURCES } from "./limits.mjs"; + +const reuse = Object.freeze({ + kind: "source_budget_refusal", + scope: "target_lease", +}); +const refusalFields = new Set([ + "scope", + "limit_bytes", + "observed_bytes_at_least", + "evidence_id", + "source_retained", + "source_complete", +]); +const retainRefusal = (error) => { + try { + if (!(error instanceof FactFailure)) return; + const own = Object.getOwnPropertyDescriptors(error); + if ( + own.code?.value !== "resource_constraint" || + typeof own.message?.value !== "string" + ) + return; + const fields = Object.getOwnPropertyDescriptors(own.details?.value); + if ( + Object.keys(fields).some((key) => !refusalFields.has(key)) || + Object.values(fields).some( + (field) => + !Object.hasOwn(field, "value") || + (field.value !== null && + !["string", "number", "boolean"].includes(typeof field.value)), + ) + ) + return; + const details = Object.fromEntries( + Object.entries(fields).map(([key, field]) => [key, field.value]), + ); + if ( + details.scope !== "native_source" || + details.source_retained !== true || + details.source_complete !== false || + typeof details.evidence_id !== "string" || + !details.evidence_id || + !Number.isSafeInteger(details.limit_bytes) || + details.limit_bytes < 1 || + !Number.isSafeInteger(details.observed_bytes_at_least) || + details.observed_bytes_at_least <= details.limit_bytes + ) + return; + return new FactFailure( + own.code.value, + own.message.value, + Object.freeze(details), + ); + } catch { + // Unknown host failures retain their original identity and remain uncached. + return; + } +}; + +export class NativeCaptureCache { + #entries = new Map(); + clear() { + this.#entries.clear(); + } + async read(key, load) { + let pending = this.#entries.get(key); + const reused = pending !== undefined; + if (!pending) { + pending = Promise.resolve() + .then(load) + .then( + (value) => ({ ok: true, value }), + (error) => { + const refusal = retainRefusal(error); + return { + ok: false, + error: refusal ?? error, + reusable: refusal !== undefined, + }; + }, + ); + if (this.#entries.size < MAX_NATIVE_SOURCES) + this.#entries.set(key, pending); + } + const result = await pending; + if (result.ok) return result.value; + if (!result.reusable) { + if (this.#entries.get(key) === pending) this.#entries.delete(key); + throw result.error; + } + throw new FactFailure(result.error.code, result.error.message, { + ...result.error.details, + ...(reused ? { cached_observation: reuse } : {}), + }); + } +} diff --git a/experiments/atomic-codemode/native-capture-cache.test.mjs b/experiments/atomic-codemode/native-capture-cache.test.mjs new file mode 100644 index 00000000000..11c9c8e6eec --- /dev/null +++ b/experiments/atomic-codemode/native-capture-cache.test.mjs @@ -0,0 +1,193 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { NativeCaptureCache } from "./native-capture-cache.mjs"; +import { FactFailure } from "./fact-error.mjs"; +import { MAX_NATIVE_SOURCES } from "./limits.mjs"; + +const refusal = () => + new FactFailure("resource_constraint", "native source cannot fit", { + scope: "native_source", + limit_bytes: 8, + observed_bytes_at_least: 9, + evidence_id: "ev_owned", + source_retained: true, + source_complete: false, + }); + +test("capacity reuse preserves observed facts, reports reuse and isolates mutable SDK error views", async () => { + const cache = new NativeCaptureCache(); + let runs = 0, + first; + const load = async () => { + runs++; + throw refusal(); + }; + await assert.rejects(cache.read("strings", load), (error) => { + first = error; + assert.equal(error.details.cached_observation, undefined); + return true; + }); + first.details.evidence_id = "caller edit"; + first.details.limit_bytes = 999; + await assert.rejects(cache.read("strings", load), (error) => { + assert.equal(error.code, "resource_constraint"); + assert.equal(error.details.evidence_id, "ev_owned"); + assert.equal(error.details.limit_bytes, 8); + assert.deepEqual(error.details.cached_observation, { + kind: "source_budget_refusal", + scope: "target_lease", + }); + return true; + }); + assert.equal(runs, 1); + cache.clear(); + await assert.rejects(cache.read("strings", load)); + assert.equal(runs, 2); +}); + +test("concurrent reads share one capture and capture keys remain independent", async () => { + const cache = new NativeCaptureCache(); + let finish, + runs = 0; + const load = () => { + runs++; + return new Promise((resolve) => { + finish = resolve; + }); + }; + const a = cache.read("one", load), + b = cache.read("one", load); + await Promise.resolve(); + assert.equal(runs, 1); + const value = Object.freeze({ source: { evidence_id: "ev_one" } }); + finish(value); + assert.strictEqual(await a, value); + assert.strictEqual(await b, value); + assert.strictEqual( + await cache.read("one", () => { + throw new Error("must reuse"); + }), + value, + ); + assert.equal(await cache.read("two", async () => 2), 2); +}); + +test("cancelled, cleanup, IO, unknown and unproven capacity failures stay retryable observations", async () => { + const base = refusal(); + for (const failure of [ + undefined, + null, + false, + 0, + "failure", + new FactFailure("cancelled", "cancelled"), + new FactFailure("cleanup_incomplete", "unknown process ownership", { + source_capture_failure: base, + }), + new FactFailure("source_write_failed", "disk full"), + { code: base.code, details: base.details }, + new FactFailure("resource_constraint", "other resource", { + scope: "memory", + }), + new FactFailure(base.code, base.message, { + ...base.details, + observed_bytes_at_least: 8, + }), + new FactFailure(base.code, base.message, { + ...base.details, + source_complete: true, + }), + new FactFailure(base.code, base.message, { + ...base.details, + unknown: { state: "live" }, + }), + new FactFailure(base.code, base.message, { + ...base.details, + cleanup_incomplete: "unconfirmed descriptor close", + }), + new FactFailure(base.code, base.message, { + ...base.details, + unknown: "live state", + }), + new FactFailure(base.code, base.message, { + ...base.details, + source_retained: false, + }), + new FactFailure(base.code, base.message, { + ...base.details, + evidence_id: undefined, + }), + ]) { + const cache = new NativeCaptureCache(); + let runs = 0; + for (let i = 0; i < 2; i++) { + let rejected = false; + try { + await cache.read("key", async () => { + runs++; + throw failure; + }); + } catch (error) { + rejected = true; + assert.strictEqual(error, failure); + } + assert(rejected); + } + assert.equal(runs, 2); + } +}); + +test("failure classification never invokes accessors or substitutes an inspection error", async () => { + let reads = 0, + runs = 0; + const details = Object.defineProperty({}, "scope", { + enumerable: true, + get() { + reads++; + throw new Error("must not inspect"); + }, + }); + const original = new FactFailure( + "resource_constraint", + "unknown source failure", + details, + ), + cache = new NativeCaptureCache(); + for (let i = 0; i < 2; i++) + await assert.rejects( + cache.read("key", async () => { + runs++; + throw original; + }), + (error) => error === original, + ); + assert.equal(reads, 0); + assert.equal(runs, 2); +}); + +test("memo retention stays within the source-count policy without refusing uncached results", async () => { + const cache = new NativeCaptureCache(); + for (let i = 0; i < MAX_NATIVE_SOURCES; i++) + await assert.rejects( + cache.read(String(i), async () => { + throw refusal(); + }), + ); + let runs = 0; + for (let i = 0; i < 2; i++) + assert.equal( + await cache.read("beyond memo capacity", async () => { + runs++; + return "still delivered"; + }), + "still delivered", + ); + assert.equal(runs, 2); + await assert.rejects( + cache.read("0", async () => { + throw new Error("existing memo lost"); + }), + (error) => + error.details.cached_observation.kind === "source_budget_refusal", + ); +}); diff --git a/experiments/atomic-codemode/native-source-store.mjs b/experiments/atomic-codemode/native-source-store.mjs index 3c2ce54a5fa..ac137481fa0 100644 --- a/experiments/atomic-codemode/native-source-store.mjs +++ b/experiments/atomic-codemode/native-source-store.mjs @@ -2,13 +2,13 @@ import { createHash, randomUUID } from "node:crypto"; import { open, rm, writeFile, copyFile, mkdir, stat } from "node:fs/promises"; import { constants } from "node:fs"; -import { MAX_RETAINED_SOURCE_BYTES } from "./limits.mjs"; import { join } from "node:path"; import { Writable } from "node:stream"; import { StringDecoder } from "node:string_decoder"; import { ArtifactResourceScope } from "../../dist/artifacts/ArtifactResourceScope.js"; import { OwnedFileHandle } from "../../dist/filesystem/OwnedFileHandle.js"; import { FactFailure, projectFactFailure } from "./fact-error.mjs"; +import { MAX_RETAINED_SOURCE_BYTES, MAX_NATIVE_SOURCES } from "./limits.mjs"; const cleanupFailure = (cause, primary) => { const failure = projectFactFailure( @@ -129,7 +129,7 @@ export class NativeSourceStore { } async spool(limit, reader) { if (this.#copyFailure) throw this.#copyFailure; - if (this.size >= 128) + if (this.size >= MAX_NATIVE_SOURCES) throw new FactFailure( "capacity", "Session source capacity reached; close and reopen the target", diff --git a/experiments/atomic-codemode/provider.mjs b/experiments/atomic-codemode/provider.mjs index a007b4eae25..d43daa8d754 100644 --- a/experiments/atomic-codemode/provider.mjs +++ b/experiments/atomic-codemode/provider.mjs @@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import { join } from "node:path"; import { NativeSourceStore } from "./native-source-store.mjs"; +import { NativeCaptureCache } from "./native-capture-cache.mjs"; import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js"; import { inspectNativeInstallation } from "./native-installation.mjs"; import { KunaTargetCommands } from "../../dist/kuna/KunaTargetCommands.js"; @@ -35,7 +36,7 @@ const missingNativeFacet = () => ({ export class KunaFactOwner { #lifetime = new AbortController(); #snapshots = new Map(); - #work = new Map(); + #work = new NativeCaptureCache(); #loaded = new Map(); #root; #sourceFiles; @@ -122,16 +123,10 @@ export class KunaFactOwner { }); return owner; } - async #native(key, arguments_, signal, readerFactory) { - if (this.#work.has(key)) return this.#work.get(key); - const work = this.#capture(arguments_, signal, readerFactory); - this.#work.set(key, work); - try { - return await work; - } catch (error) { - this.#work.delete(key); - throw error; - } + #native(key, arguments_, signal, readerFactory) { + return this.#work.read(key, () => + this.#capture(arguments_, signal, readerFactory), + ); } async #capture(arguments_, signal, readerFactory) { const start = performance.now(); diff --git a/experiments/atomic-codemode/verify-capacity-reuse.mjs b/experiments/atomic-codemode/verify-capacity-reuse.mjs new file mode 100644 index 00000000000..3749424c27c --- /dev/null +++ b/experiments/atomic-codemode/verify-capacity-reuse.mjs @@ -0,0 +1,184 @@ +// Actual immutable-target refusal reuse through SDK and both MCP transports. +import assert from "node:assert/strict"; +import { readFile, writeFile, readdir } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { join, resolve } from "node:path"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { AtomicSession } from "./session.mjs"; +import { familyCounters } from "./family-counters.mjs"; +import { + createVerifierRun, + completeVerifierRun, + assertVerifierCleanupComplete, +} from "../../scripts/lib/verifier-run.mjs"; +const [output, adapter = "sdk"] = process.argv.slice(2); +assert( + output && + ["sdk", "direct", "codemode"].includes(adapter) && + process.env.REA_ATOMIC_EVIDENCE_DIR, +); +const target = "/usr/lib/x86_64-linux-gnu/libLLVM-16.so.1", + digest = "f62d254b7f2bf42df8c8b07d46ee3bb4c2cafeca436b2e6bc6ccbe4581f58f40"; +const sha = (value) => createHash("sha256").update(value).digest("hex"); +assert.equal(sha(await readFile(target)), digest); +const run = createVerifierRun(), + observations = [], + phases = [], + failures = []; +const session = adapter === "sdk" ? new AtomicSession() : null; +const client = session + ? null + : new Client({ name: "capacity-reuse-verifier", version: "0.1.0" }); +const transport = session + ? null + : new StdioClientTransport({ + command: process.execPath, + args: [resolve("experiments/atomic-codemode/server.mjs")], + env: { ...process.env, REA_ATOMIC_ADAPTER: adapter }, + stderr: "pipe", + }); +const invoke = async (name, input) => { + const reply = await client.callTool( + { name, arguments: input }, + { timeout: 180000 }, + ); + assert(!reply.isError); + return JSON.parse(reply.content[0].text); +}; +const read = async (name, input) => + session ? session.call(name, input) : invoke("facts_" + name, input); +const query = { query: "undefined symbol", fields: [], limit: 2 }; +const measure = async (name, work) => { + const start = performance.now(), + before = await familyCounters(); + const result = await work(), + after = await familyCounters(); + phases.push({ + name, + elapsed_ms: performance.now() - start, + cpu_seconds: (after.cpu - before.cpu) / 1e6, + }); + return result; +}; +let source; +try { + if (session) await session.open(target); + else { + await client.connect(transport); + await invoke("open_binary", { path: target }); + } + let first, second, evidence; + if (adapter === "codemode") { + const program = await measure("in_program_cold_and_reuse", () => + invoke("execute_javascript", { + code: ` + const first=await rea.strings(${JSON.stringify(query)}); + if(first.ok || first.error?.code!=="resource_constraint") + return {first,second:null,evidence:null,warm_ms:null}; + const started=Date.now(); + const second=await rea.strings(${JSON.stringify(query)}); + const warm_ms=Date.now()-started; + const id=first.error?.details?.evidence_id; + const evidence=id?await rea.evidence({evidence_id:id,limit:64}):null; + return {first,second,warm_ms,evidence}; + `, + }), + ); + observations.push({ phase: "code_program", response: program }); + assert(program.ok); + assert.equal( + program.execution.host_calls, + program.value.first.error?.code === "resource_constraint" ? 3 : 1, + ); + ({ first, second, evidence } = program.value); + phases.push({ + name: "guest_wall_reuse", + elapsed_ms: program.value.warm_ms, + precision: "guest Date.now milliseconds; CPU unmeasured separately", + }); + } else { + first = await measure("cold_refusal", () => read("strings", query)); + observations.push({ phase: "first_refusal", response: first }); + assert.equal( + first.error?.code, + "resource_constraint", + "cache-hit verification requires confirmed cleanup of the first refusal", + ); + second = await measure("warm_refusal", () => read("strings", query)); + evidence = await read("evidence", { + evidence_id: first.error?.details?.evidence_id, + limit: 64, + }); + } + observations.push({ first, second, evidence }); + assert.equal(first.ok, false); + assert.equal( + first.error.code, + "resource_constraint", + "cleanup uncertainty is not proof of a cacheable refusal", + ); + assert.equal(second.ok, false); + assert.equal(second.error.code, first.error.code); + assert.equal(second.context.lease, first.context.lease); + assert(!Object.hasOwn(first, "data") && !Object.hasOwn(second, "data")); + assert.equal(first.error.details.cached_observation, undefined); + assert.deepEqual(second.error.details.cached_observation, { + kind: "source_budget_refusal", + scope: "target_lease", + }); + const { cached_observation: _cachedObservation, ...original } = + second.error.details; + assert.deepEqual(original, first.error.details); + assert(evidence?.ok); + source = evidence.data.source; + assert.equal(source.evidence_id, first.error.details.evidence_id); + assert.equal(source.capture_complete, false); + const files = (await readdir(process.env.REA_ATOMIC_EVIDENCE_DIR)).filter( + (name) => name.endsWith(".json"), + ); + assert.equal(files.length, 1, "reuse must not capture another source prefix"); + const raw = await readFile( + join(process.env.REA_ATOMIC_EVIDENCE_DIR, source.evidence_id + ".txt"), + ); + assert.equal(raw.length, source.bytes); + assert.equal(sha(raw), source.sha256); + assert.equal(evidence.data.text, raw.toString().slice(0, 64)); +} catch (error) { + failures.push(error.stack ?? String(error)); +} finally { + if (session) { + session.abort(); + await session.close(); + } else { + try { + await invoke("close_binary", {}); + } finally { + await client.close(); + await transport.close(); + } + } +} +const lifecycle = await completeVerifierRun(run); +assertVerifierCleanupComplete(lifecycle.process_lineage); +assert.equal(sha(await readFile(target)), digest); +await writeFile( + output, + JSON.stringify( + { + adapter, + target, + digest, + phases, + source, + observations, + failures, + lifecycle, + }, + null, + 2, + ), + { flag: "wx" }, +); +console.log(JSON.stringify({ adapter, phases, failures })); +assert.deepEqual(failures, []);