diff --git a/experiments/atomic-codemode/README.md b/experiments/atomic-codemode/README.md index 59f8a20034a..76657b7bff8 100644 --- a/experiments/atomic-codemode/README.md +++ b/experiments/atomic-codemode/README.md @@ -51,6 +51,10 @@ retrieves correct data but labels two 17-byte prefixes as 16, failing the exact reporting criterion. Both use metadata selection without sending full blobs. Code Mode uses less input but more wall time; the differing correctness and byte window choices prevent a matched-quality efficiency ranking. All runs remain. +The [streamed inventory study](streamed-inventory-study.md) then restores real +FFmpeg queries whose complete native source exceeds 8 MiB, using the production +streaming parser and bounded retained files. Real SDK/MCP lanes pass; LLVM and +Node still exceed the existing 64 MiB budget. Those failures remain explicit. The [AArch64 reference study](aarch64-xref-study.md) finds and fixes missing ADRP-based string and memory references before the next model comparison. @@ -166,10 +170,12 @@ and complete sources outside the model workspace when explicitly selected by the evaluator. The ambient environment and credentials are not logged. Current bounds: 64 MiB guest heap, 32 KiB code and script value/error payloads, 64 host calls per execution, -120 seconds wall deadline and 2 seconds of guest synchronous execution; native requests have existing supervision, an 8 MiB -capture budget and 1 GiB function-memory limit. Retained source storage is 64 MiB -per target, with two resident indexes (each derived from at most 2 MiB diagnostic -or 8 MiB native wire source). Compressed native graphs admit at most 32 MiB decoded +120 seconds wall deadline and 2 seconds of guest synchronous execution. Native +requests use existing supervision and a 1 GiB function-memory limit. Buffered +formats and diagnostics keep an 8 MiB bound; string inventories stream through +the production reader into the existing 64 MiB per-target source budget, without +an aggregate stdout string. Two resident function indexes each derive from at +most 2 MiB diagnostic or 8 MiB native wire source. Compressed native graphs admit at most 32 MiB decoded JSON plus independent row/text/relationship bounds. One decoded Evidence text view up to 32 MiB is also retained per lease; these source bounds are not parsed-heap size guarantees. Sources are diff --git a/experiments/atomic-codemode/fact-reads.mjs b/experiments/atomic-codemode/fact-reads.mjs index 936b030bd61..cf980e2bb42 100644 --- a/experiments/atomic-codemode/fact-reads.mjs +++ b/experiments/atomic-codemode/fact-reads.mjs @@ -9,11 +9,18 @@ export function freezeFacts(value) { return value; } -export const sourceSummary = ({ evidence_id, sha256, bytes, elapsed_ms }) => ({ +export const sourceSummary = ({ evidence_id, sha256, bytes, elapsed_ms, + capture_complete, +}) => ({ + evidence_id, + sha256, + bytes, + elapsed_ms, + ...(capture_complete === undefined ? {} : { capture_complete }), }); export const projectFact = (row, fields, identity) => diff --git a/experiments/atomic-codemode/limits.mjs b/experiments/atomic-codemode/limits.mjs index cdce65bed26..1fce9f8eb35 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_RETAINED_SOURCE_BYTES = 64 * 1024 * 1024; export const NATIVE_OUTPUT_BYTES = 8 * 1024 * 1024; export const MAX_BRIDGE_BYTES = 2 * 1024 * 1024; // The observed client clips oversized MCP results. Bound this profile's tool diff --git a/experiments/atomic-codemode/native-catalog-reads.mjs b/experiments/atomic-codemode/native-catalog-reads.mjs index 25b08fe3825..6b0cd597e79 100644 --- a/experiments/atomic-codemode/native-catalog-reads.mjs +++ b/experiments/atomic-codemode/native-catalog-reads.mjs @@ -1,9 +1,10 @@ // Fixed per-lease catalogs share source admission; queries do not create cache keys. import { parseFunctionFacts, selectFunctionFacts } from "./function-facts.mjs"; -import { parseStringFacts, selectStringFacts } from "./string-facts.mjs"; +import { selectStringFacts } from "./string-facts.mjs"; import { parseNativeStorageMap } from "./native-storage-map.mjs"; -import { sourceSummary } from "./fact-reads.mjs"; -import { FactFailure } from "./fact-error.mjs"; +import { freezeFacts, sourceSummary } from "./fact-reads.mjs"; +import { FactFailure, requireResult } from "./fact-error.mjs"; +import { KunaStringInventoryReader } from "../../dist/kuna/KunaStringInventory.js"; const catalogs = { functions: { @@ -23,7 +24,7 @@ const catalogs = { "any", "--no-xrefs", ], - parse: parseStringFacts, + reader: () => new KunaStringInventoryReader(), }, storage: { arguments: (path) => ["storage-map", path, "--json"], @@ -41,12 +42,30 @@ export class NativeCatalogReads { if (name === "storage") this.requireStorage(); if (!this.#loaded.has(name)) { const definition = catalogs[name], - capture = await this.capture(name, definition.arguments, signal); - try { - const facts = await definition.parse( - await this.readSource(capture.source.evidence_id), - capture.input, + capture = await this.capture( + name, + definition.arguments, + signal, + definition.reader, ); + try { + const facts = definition.reader + ? freezeFacts( + requireResult(capture.parsed, "invalid_provider_output"), + ) + : await definition.parse( + await this.readSource(capture.source.evidence_id), + capture.input, + ); + if ( + definition.reader && + (facts.sha256 !== capture.source.sha256 || + facts.bytes !== capture.source.bytes) + ) + throw new FactFailure( + "invalid_provider_output", + "Parsed inventory and retained source identities disagree", + ); this.#loaded.set(name, { facts, source: Object.freeze(sourceSummary(capture.source)), diff --git a/experiments/atomic-codemode/native-evidence-reads.mjs b/experiments/atomic-codemode/native-evidence-reads.mjs index d91854e0b90..599066f6ad6 100644 --- a/experiments/atomic-codemode/native-evidence-reads.mjs +++ b/experiments/atomic-codemode/native-evidence-reads.mjs @@ -4,43 +4,44 @@ import { readNativeGraphEvidence } from "./native-ir-contract.mjs"; export class NativeEvidenceReads { #graph; - constructor(readSource) { - this.readSource = readSource; + constructor({ readText, readWindow }) { + Object.assign(this, { readText, readWindow }); } clear() { this.#graph = undefined; } async read(input) { - const { text: original, source } = await this.readSource(input.evidence_id); - let text = original, - view; - if (input.component === "recovered_ir") { - const key = `${input.evidence_id}:${source.sha256}`; - if (this.#graph?.key !== key) { - const decoded = readNativeGraphEvidence(text); - this.#graph = { - key, - ...decoded, - sha256: createHash("sha256").update(decoded.text).digest("hex"), - bytes: Buffer.byteLength(decoded.text), - }; - } - const decoded = this.#graph; - text = decoded.text; - view = { - component: "recovered_ir", - encoding: decoded.encoding, - sha256: decoded.sha256, - bytes: decoded.bytes, - authority: - "uninterpreted retained graph source; fact validity is separate", + if (input.component !== "recovered_ir") + return this.readWindow(input.evidence_id, { + offset: input.offset ?? 0, + limit: input.limit ?? 4096, + }); + const { text: original, source } = await this.readText(input.evidence_id); + const key = `${input.evidence_id}:${source.sha256}`; + if (this.#graph?.key !== key) { + const decoded = readNativeGraphEvidence(original); + this.#graph = { + key, + ...decoded, + sha256: createHash("sha256").update(decoded.text).digest("hex"), + bytes: Buffer.byteLength(decoded.text), }; } + const decoded = this.#graph, + text = decoded.text; + const view = { + component: "recovered_ir", + encoding: decoded.encoding, + sha256: decoded.sha256, + bytes: decoded.bytes, + authority: + "uninterpreted retained graph source; fact validity is separate", + }; const offset = input.offset ?? 0, limit = input.limit ?? 4096; return { source, - ...(view ? { view } : {}), + view, text: text.slice(offset, offset + limit), total_code_units: text.length, next_offset: offset + limit < text.length ? offset + limit : null, diff --git a/experiments/atomic-codemode/native-evidence-reads.test.mjs b/experiments/atomic-codemode/native-evidence-reads.test.mjs index 974d20097a5..e35f23f0dfe 100644 --- a/experiments/atomic-codemode/native-evidence-reads.test.mjs +++ b/experiments/atomic-codemode/native-evidence-reads.test.mjs @@ -38,7 +38,13 @@ function captured(text) { test("decoded Evidence pages preserve their own byte identity and raw source provenance", async () => { const logical = "{malformed JSON with 中文 and 😀", source = captured(logical); - const reader = new NativeEvidenceReads(async () => source); + const reader = new NativeEvidenceReads({ + readText: async () => source, + readWindow: async (_id, { offset, limit }) => ({ + source: source.source, + text: source.text.slice(offset, offset + limit), + }), + }); const raw = await reader.read({ evidence_id: "ev_owned", limit: 1e5 }); assert.equal(raw.text, source.text); assert.equal(raw.view, undefined); @@ -62,10 +68,12 @@ test("decoded view reuse still requires source-owner validation and follows cont let source = captured('{"schema_version":3}'), failure = false, reads = 0; - const reader = new NativeEvidenceReads(async () => { - reads++; - if (failure) throw new Error("source_changed"); - return source; + const reader = new NativeEvidenceReads({ + readText: async () => { + reads++; + if (failure) throw new Error("source_changed"); + return source; + }, }); const query = { evidence_id: "ev_owned", component: "recovered_ir" }; await reader.read(query); diff --git a/experiments/atomic-codemode/native-source-store.mjs b/experiments/atomic-codemode/native-source-store.mjs new file mode 100644 index 00000000000..3c2ce54a5fa --- /dev/null +++ b/experiments/atomic-codemode/native-source-store.mjs @@ -0,0 +1,315 @@ +// Raw native Evidence has one file/hash owner; reads verify before returning facts. +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"; + +const cleanupFailure = (cause, primary) => { + const failure = projectFactFailure( + primary === undefined ? cause : primary, + primary === undefined ? "cleanup_incomplete" : "analysis_failed", + ); + return new FactFailure(failure.code, failure.message, { + ...failure.details, + cleanup_incomplete: String(cause?.message ?? cause), + }); +}; + +export class NativeSourceStore { + #records = new Map(); + #retainedBytes = 0; + #copyFailure; + #resources = new ArtifactResourceScope(); + constructor({ root, context, captureDirectory }) { + Object.assign(this, { root, context, captureDirectory }); + } + get size() { + return this.#records.size; + } + get remainingBytes() { + return MAX_RETAINED_SOURCE_BYTES - this.#retainedBytes; + } + source(id) { + return this.#record(id).source; + } + #record(id) { + const record = this.#records.get(id); + if (!record) + throw new FactFailure( + "unknown_evidence", + "Evidence is not owned by this target lease", + ); + return record; + } + async retain( + spool, + { arguments: actualArguments, input, started, complete }, + ) { + const size = (await stat(spool.path)).size; + if (size !== spool.bytes) { + await spool.discard(); + throw new FactFailure( + "invalid_source", + "Native source size disagrees with acknowledged writes", + { + expected_bytes: spool.bytes, + actual_bytes: size, + source_retained: false, + }, + ); + } + const id = `ev_${sha256(JSON.stringify([this.context.lease, actualArguments, spool.sha256, complete]))}`; + if (this.#records.has(id)) { + await spool.discard(); + return this.#records.get(id).source; + } + const source = Object.freeze({ + evidence_id: id, + sha256: spool.sha256, + bytes: spool.bytes, + capture_complete: complete, + arguments: Object.freeze(actualArguments), + display_arguments: Object.freeze( + actualArguments.map((s) => (s === input ? this.context.path : s)), + ), + elapsed_ms: performance.now() - started, + }); + this.#records.set(id, { source, file: spool.path }); + this.#retainedBytes += spool.bytes; + try { + if (this.captureDirectory) { + await mkdir(this.captureDirectory, { recursive: true, mode: 0o700 }); + await copyFile( + spool.path, + join(this.captureDirectory, `${id}.txt`), + constants.COPYFILE_EXCL, + ); + await writeFile( + join(this.captureDirectory, `${id}.json`), + JSON.stringify({ context: this.context, source }), + { flag: "wx", mode: 0o600 }, + ); + } + } catch (cause) { + this.#copyFailure = new FactFailure( + "evidence_copy_failed", + "Native Evidence is retained but the requested external copy failed", + { + evidence_id: id, + source_retained: true, + copy_directory: this.captureDirectory, + reason: String(cause?.message ?? cause), + filesystem_code: cause?.code ?? null, + copy_retry: "new_target_lease", + }, + ); + throw this.#copyFailure; + } + return source; + } + + async #open(path, flags) { + await this.#resources.retryCleanup(); + const handle = new OwnedFileHandle(await open(path, flags, 0o600)); + const owner = { kind: "file-handle", resource: path, handle }; + return { + handle: handle.handle, + close: async (primary) => { + const result = await this.#resources.release(owner); + if (result.kind === "failed") + throw cleanupFailure(result.cause, primary); + }, + }; + } + async spool(limit, reader) { + if (this.#copyFailure) throw this.#copyFailure; + if (this.size >= 128) + throw new FactFailure( + "capacity", + "Session source capacity reached; close and reopen the target", + ); + limit = Math.min(limit, this.remainingBytes); + if (!Number.isSafeInteger(limit) || limit < 1) + throw new FactFailure("capacity", "Retained-source budget is exhausted"); + const path = join(this.root, `source-${randomUUID()}`); + return new NativeSourceSpool({ + path, + file: await this.#open(path, "wx"), + limit, + reader, + discard: async () => { + const result = await this.#resources.release({ + kind: "lease", + resource: path, + lease: { release: () => rm(path, { force: true }) }, + }); + if (result.kind === "failed") throw cleanupFailure(result.cause); + }, + }); + } + async read(id, window) { + const record = this.#record(id); + const file = await this.#open(record.file, "r"); + let primary; + try { + return await readVerified(file.handle, record.source, window); + } catch (error) { + primary = error; + throw error; + } finally { + await file.close(primary); + } + } + async close() { + await this.#resources.close(); + } +} + +class NativeSourceSpool extends Writable { + #hash = createHash("sha256"); + #digest; + #pending = Promise.resolve(); + #rejected = new AbortController(); + bytes = 0; + failure; + constructor({ path, file, limit, reader, discard }) { + super(); + Object.assign(this, { path, file, limit, reader, discard }); + // The command owns stream failure reporting; never leave a rejected sink unobserved. + reader?.on("error", () => {}); + } + get rejected() { + return this.#rejected.signal; + } + get sha256() { + return (this.#digest ??= this.#hash.digest("hex")); + } + _write(chunk, _encoding, callback) { + this.#pending = this.#write(chunk); + this.#pending.then( + () => callback(), + (error) => { + this.failure = + error instanceof FactFailure + ? error + : new FactFailure( + "source_write_failed", + "Native Evidence could not be written", + { + reason: String(error?.message ?? error), + filesystem_code: error?.code ?? null, + }, + ); + this.#rejected.abort(this.failure); + callback(this.failure); + }, + ); + } + async #write(chunk) { + if (this.bytes + chunk.byteLength > this.limit) + throw new FactFailure( + "resource_constraint", + "Native Evidence exceeds its retained-source budget", + { + scope: "native_source", + limit_bytes: this.limit, + observed_bytes_at_least: this.bytes + chunk.byteLength, + }, + ); + for (let offset = 0; offset < chunk.byteLength;) { + const written = await this.file.handle.write( + chunk, + offset, + chunk.byteLength - offset, + ); + if (written.bytesWritten === 0) + throw new FactFailure( + "source_write_failed", + "Native source write made no progress", + ); + this.#hash.update(chunk.subarray(offset, offset + written.bytesWritten)); + this.bytes += written.bytesWritten; + offset += written.bytesWritten; + } + if (this.reader) + await new Promise((resolve, reject) => + this.reader.write(chunk, (error) => + error ? reject(error) : resolve(), + ), + ); + } + _final(callback) { + if (this.reader) this.reader.end(callback); + else callback(); + } + _destroy(error, callback) { + if (!this.reader?.writableFinished) this.reader?.destroy(); + this.#pending.then( + () => callback(error), + () => callback(error), + ); + } + async close(primary) { + if (!this.destroyed) this.destroy(); + await this.#pending.catch(() => {}); + try { + await this.file.close(primary); + } catch (error) { + // Unpublished failed captures must not accumulate outside the source ledger. + try { + await this.discard(); + } catch (cause) { + throw cleanupFailure(cause, error); + } + throw error; + } + } +} + +async function readVerified(handle, source, window) { + const hash = createHash("sha256"), + decoder = new StringDecoder("utf8"), + chunks = []; + const buffer = Buffer.allocUnsafe(64 * 1024); + let bytes = 0, + units = 0; + const collect = (text) => { + if (window) { + const start = Math.max(0, window.offset - units); + const end = Math.min(text.length, window.offset + window.limit - units); + if (end > start) chunks.push(text.slice(start, end)); + } else chunks.push(text); + units += text.length; + }; + while (true) { + const { bytesRead } = await handle.read(buffer, 0, buffer.length); + if (!bytesRead) break; + bytes += bytesRead; + if (bytes > source.bytes) throw changed(); + const chunk = buffer.subarray(0, bytesRead); + hash.update(chunk); + collect(decoder.write(chunk)); + } + collect(decoder.end()); + if (bytes !== source.bytes || hash.digest("hex") !== source.sha256) + throw changed(); + return { + source, + text: chunks.join(""), + total_code_units: units, + next_offset: + window && window.offset + window.limit < units + ? window.offset + window.limit + : null, + }; +} +const changed = () => + new FactFailure("evidence_changed", "Retained source changed"); + +const sha256 = (text) => createHash("sha256").update(text).digest("hex"); diff --git a/experiments/atomic-codemode/native-source-store.test.mjs b/experiments/atomic-codemode/native-source-store.test.mjs new file mode 100644 index 00000000000..65f9744703f --- /dev/null +++ b/experiments/atomic-codemode/native-source-store.test.mjs @@ -0,0 +1,310 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createHash } from "node:crypto"; +import { readFile, writeFile, stat } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { PrivateRuntimeRoot } from "../../dist/process/PrivateRuntimeRoot.js"; +import { KunaStringInventoryReader } from "../../dist/kuna/KunaStringInventory.js"; +import { NativeSourceStore } from "./native-source-store.mjs"; + +const hash = (bytes) => createHash("sha256").update(bytes).digest("hex"); +async function withFiles(work) { + const root = await PrivateRuntimeRoot.create({ prefix: "rea-source-test-" }); + const files = new NativeSourceStore({ + root: root.path, + context: { lease: "test", path: "/input" }, + }); + try { + await work(files); + } finally { + await files.close(); + await root.close(); + } +} +const retain = (files, spool) => + files.retain(spool, { + arguments: ["strings", "/input"], + input: "/input", + started: performance.now(), + complete: true, + }); + +// UTF-8 byte boundaries, UTF-16 unit boundaries and the selected window differ. +test("raw windows preserve slice semantics, exact hashes and complete source lengths", () => + withFiles(async (files) => { + const text = "x".repeat(65535) + "中文😀" + "y".repeat(65537), + bytes = Buffer.from(text); + const spool = await files.spool(bytes.length); + await pipeline( + Readable.from([bytes.subarray(0, 65536), bytes.subarray(65536)]), + spool, + ); + await spool.close(); + assert.equal((await stat(spool.path)).mode & 0o777, 0o600); + const source = await retain(files, spool); + assert.equal(source.sha256, hash(bytes)); + for (const [offset, limit] of [ + [0, 0], + [65534, 2], + [65538, 1], + [65539, 1], + [65540, 3], + [text.length, 5], + [text.length + 9, 2], + ]) { + const page = await files.read(source.evidence_id, { offset, limit }); + assert.equal(page.text, text.slice(offset, offset + limit)); + assert.equal(page.total_code_units, text.length); + assert.equal( + page.next_offset, + offset + limit < text.length ? offset + limit : null, + ); + } + assert.equal((await files.read(source.evidence_id)).text, text); + })); + +test("a mutation outside the selected window cannot pass source validation", () => + withFiles(async (files) => { + const spool = await files.spool(32); + await pipeline(Readable.from(["retained evidence"]), spool); + await spool.close(); + const source = await retain(files, spool); + for (const value of [ + "retained evidencE", + "retained evidenc", + "retained evidence!", + ]) { + await writeFile(spool.path, value); + await assert.rejects( + files.read(source.evidence_id, { offset: 0, limit: 1 }), + { code: "evidence_changed" }, + ); + } + })); + +test("source limits admit the exact boundary and reject before writing an over-budget chunk", () => + withFiles(async (files) => { + const exact = await files.spool(4); + await pipeline(Readable.from(["abcd"]), exact); + await exact.close(); + assert.equal(exact.bytes, 4); + assert.equal(exact.rejected.aborted, false); + const partial = await files.spool(4); + await assert.rejects(pipeline(Readable.from(["abc", "de"]), partial), { + code: "resource_constraint", + }); + await partial.close(); + assert.equal(partial.bytes, 3); + assert.equal(partial.failure.details.observed_bytes_at_least, 5); + assert.equal(partial.rejected.aborted, true); + assert.equal((await readFile(partial.path)).toString(), "abc"); + await partial.discard(); + await assert.rejects(stat(partial.path), { code: "ENOENT" }); + await assert.rejects(files.spool(0), { code: "capacity" }); + })); + +const inventory = (overrides = {}) => + JSON.stringify({ + binary: "/input", + encoding: "all", + min_length: 5, + filter: null, + section: null, + termination: "any", + scanned: "sections", + xrefs: false, + count: 1, + strings: [ + { + address: 4096, + address_hex: "0x1000", + text: "hello中文", + length: 7, + byte_length: 12, + nul_terminated: true, + encoding: "utf8", + section: ".rodata", + xrefs_count: 0, + functions: [], + }, + ], + ...overrides, + }); + +test("the production string reader validates streamed rows while original Evidence stays byte-exact", () => + withFiles(async (files) => { + for (const valid of [true, false]) { + const bytes = Buffer.from(inventory(valid ? {} : { count: 2 })), + reader = new KunaStringInventoryReader(); + const spool = await files.spool(bytes.length, reader); + await pipeline( + Readable.from([...bytes].map((byte) => Buffer.from([byte]))), + spool, + ); + await spool.close(); + const result = reader.finish("/input"); + assert.equal(result.ok, valid); + if (result.ok) { + assert.equal(result.value.items[0].string.nul_terminated, true); + assert.equal(result.value.items[0].value, "hello中文"); + assert.equal(result.value.sha256, spool.sha256); + } else assert.match(result.error.message, /count/); + assert.deepEqual(await readFile(spool.path), bytes); + } + })); + +test("failed descriptor cleanup retains the same owner and preserves the primary failure", () => + withFiles(async (files) => { + const spool = await files.spool(4), + handle = spool.file.handle, + close = handle.close.bind(handle); + await pipeline(Readable.from(["a"]), spool); + let attempts = 0; + handle.close = async () => { + attempts++; + if (attempts === 1) throw new Error("injected close failure"); + return close(); + }; + await assert.rejects( + spool.close( + Object.assign(new Error("cancelled request"), { code: "cancelled" }), + ), + (error) => + error.code === "cancelled" && + error.details.cleanup_incomplete === "injected close failure", + ); + assert(handle.fd >= 0); + await assert.rejects(stat(spool.path), { code: "ENOENT" }); + await files.close(); + assert.equal(handle.fd, -1); + assert.equal(attempts, 2); + })); + +// This is the existing per-lease retained-source ceiling, independent of paging. +test("the aggregate source budget remains readable at exhaustion without admitting more captures", () => + withFiles(async (files) => { + const chunk = Buffer.alloc(1024 * 1024, 0x61), + budget = files.remainingBytes; + const spool = await files.spool(budget + 1); + await pipeline( + Readable.from( + (function* () { + for (let i = 0; i < budget / chunk.length; i++) yield chunk; + })(), + ), + spool, + ); + await spool.close(); + const source = await retain(files, spool); + assert.equal(files.remainingBytes, 0); + await assert.rejects(files.spool(1), { code: "capacity" }); + const page = await files.read(source.evidence_id, { + offset: source.bytes - 3, + limit: 3, + }); + assert.equal(page.text, "aaa"); + assert.equal(page.next_offset, null); + assert.equal(page.total_code_units, budget); + })); + +test("content deduplication and partial-capture identity preserve the one source owner", () => + withFiles(async (files) => { + const sources = []; + for (const complete of [true, true, false]) { + const spool = await files.spool(8); + await pipeline(Readable.from(["source"]), spool); + await spool.close(); + sources.push( + await files.retain(spool, { + arguments: ["strings", "/input"], + input: "/input", + started: performance.now(), + complete, + }), + ); + if (sources.length === 2) + await assert.rejects(stat(spool.path), { code: "ENOENT" }); + } + assert.strictEqual(sources[0], sources[1]); + assert.notEqual(sources[0].evidence_id, sources[2].evidence_id); + assert.equal(sources[2].capture_complete, false); + assert.equal(files.size, 2); + assert.equal(files.remainingBytes, 64 * 1024 * 1024 - 12); + await assert.rejects(files.read("foreign", { offset: 0, limit: 1 }), { + code: "unknown_evidence", + }); + })); + +test("partial writes make progress and a zero-progress write fails explicitly", () => + withFiles(async (files) => { + const spool = await files.spool(8), + handle = spool.file.handle, + write = handle.write.bind(handle); + handle.write = (buffer, offset, length) => + write(buffer, offset, Math.min(length, 1)); + await pipeline(Readable.from(["source"]), spool); + await spool.close(); + assert.equal((await readFile(spool.path)).toString(), "source"); + const stuck = await files.spool(8); + stuck.file.handle.write = async () => ({ bytesWritten: 0 }); + await assert.rejects(pipeline(Readable.from(["x"]), stuck), { + code: "source_write_failed", + }); + await stuck.close(); + await stuck.discard(); + })); + +test("external copy failures preserve the retained observation and caller-selected destination", () => + withFiles(async (files) => { + const destination = files.root + "/not-a-directory"; + await writeFile(destination, "owned test file"); + files.captureDirectory = destination; + const spool = await files.spool(8); + await pipeline(Readable.from(["source"]), spool); + await spool.close(); + let id; + await assert.rejects(retain(files, spool), (error) => { + id = error.details.evidence_id; + return ( + error.code === "evidence_copy_failed" && + error.details.copy_directory === destination && + error.details.source_retained + ); + }); + assert.equal((await files.read(id, { offset: 0, limit: 3 })).text, "sou"); + assert.equal(files.size, 1); + await assert.rejects(files.spool(8), { code: "evidence_copy_failed" }); + })); + +test("a write failure after an acknowledged prefix retains exact partial Evidence", () => + withFiles(async (files) => { + const spool = await files.spool(8), + handle = spool.file.handle, + write = handle.write.bind(handle); + let calls = 0; + handle.write = (buffer, offset, length) => { + if (calls++) + throw Object.assign(new Error("injected disk failure"), { + code: "ENOSPC", + }); + return write(buffer, offset, Math.min(3, length)); + }; + await assert.rejects(pipeline(Readable.from(["abcdef"]), spool), { + code: "source_write_failed", + }); + await spool.close(); + assert.equal(spool.bytes, 3); + const source = await files.retain(spool, { + arguments: ["strings", "/input"], + input: "/input", + started: performance.now(), + complete: false, + }); + assert.equal(source.sha256, hash("abc")); + assert.equal(source.capture_complete, false); + assert.equal( + (await files.read(source.evidence_id, { offset: 0, limit: 8 })).text, + "abc", + ); + })); diff --git a/experiments/atomic-codemode/provider.mjs b/experiments/atomic-codemode/provider.mjs index 3f17c6b8c44..a007b4eae25 100644 --- a/experiments/atomic-codemode/provider.mjs +++ b/experiments/atomic-codemode/provider.mjs @@ -1,7 +1,7 @@ // Native protocols stay here. API and execution adapters consume parsed facts. import { createHash, randomUUID } from "node:crypto"; -import { writeFile, readFile, mkdir } from "node:fs/promises"; import { join } from "node:path"; +import { NativeSourceStore } from "./native-source-store.mjs"; import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js"; import { inspectNativeInstallation } from "./native-installation.mjs"; import { KunaTargetCommands } from "../../dist/kuna/KunaTargetCommands.js"; @@ -11,7 +11,11 @@ import { parseNativeIR } from "./native-ir.mjs"; import { NativeEvidenceReads } from "./native-evidence-reads.mjs"; import { NativeCatalogReads } from "./native-catalog-reads.mjs"; import { DEFAULT_NATIVE_OPERATION_FIELDS } from "./native-operation-views.mjs"; -import { FactFailure, requireResult } from "./fact-error.mjs"; +import { + FactFailure, + requireResult, + projectFactFailure, +} from "./fact-error.mjs"; import { windowReaders } from "./window-readers.mjs"; import { NATIVE_OUTPUT_BYTES } from "./limits.mjs"; import { sourceSummary, projectFact, readFactBatch } from "./fact-reads.mjs"; @@ -30,15 +34,14 @@ const missingNativeFacet = () => ({ }); export class KunaFactOwner { #lifetime = new AbortController(); - #sources = new Map(); #snapshots = new Map(); #work = new Map(); #loaded = new Map(); #root; + #sourceFiles; #commands; #target; #installation; - #retainedBytes = 0; #catalogs = new NativeCatalogReads( (...args) => this.#native(...args), (id) => this.#sourceText(id), @@ -49,11 +52,10 @@ export class KunaFactOwner { (id) => this.#sourceText(id), () => this.#requireNativeIR(), ); - #captureDirectory; - #evidence = new NativeEvidenceReads(async (id) => ({ - text: await this.#sourceText(id), - source: this.#sources.get(id).source, - })); + #evidence = new NativeEvidenceReads({ + readText: async (id) => this.#sourceFiles.read(id), + readWindow: async (id, window) => this.#sourceFiles.read(id, window), + }); #nativeIR = false; context; static async open(path, { environment = process.env, fileResources }) { @@ -97,7 +99,6 @@ export class KunaFactOwner { owner.#commands = new KunaTargetCommands(owner.#target, { signal: owner.#lifetime.signal, }); - owner.#captureDirectory = environment.REA_ATOMIC_EVIDENCE_DIR; owner.context = Object.freeze({ lease: randomUUID(), artifact_sha256: owner.#target.sha256, @@ -114,16 +115,16 @@ export class KunaFactOwner { ? "pinned engine with embedded specs; fresh private engine cache per lease; byte/storage metadata reads suppress global discovery; other native CLI defaults; no annotations" : "byte reads suppress global discovery; other native CLI defaults, no annotations; external spec cache freshness is not fingerprinted", }); + owner.#sourceFiles = new NativeSourceStore({ + root: owner.#root.path, + context: owner.context, + captureDirectory: environment.REA_ATOMIC_EVIDENCE_DIR, + }); return owner; } - async #native(key, arguments_, signal) { + async #native(key, arguments_, signal, readerFactory) { if (this.#work.has(key)) return this.#work.get(key); - if (this.#sources.size >= 128) - throw new FactFailure( - "capacity", - "Session source capacity reached; close and reopen the target", - ); - const work = this.#capture(arguments_, signal); + const work = this.#capture(arguments_, signal, readerFactory); this.#work.set(key, work); try { return await work; @@ -132,68 +133,80 @@ export class KunaFactOwner { throw error; } } - async #capture(arguments_, signal) { + async #capture(arguments_, signal, readerFactory) { const start = performance.now(); - const snapshot = requireResult( - await this.#commands.run({ - installation: this.#installation, - operation: "experiment:atomic-facts", - arguments: arguments_, - outputBytes: NATIVE_OUTPUT_BYTES, - timeoutMs: 120000, - signal: AbortSignal.any([signal, this.#lifetime.signal]), - }), + const reader = readerFactory?.(); + const remaining = this.#sourceFiles.remainingBytes; + const spool = await this.#sourceFiles.spool( + reader ? remaining : Math.min(remaining, NATIVE_OUTPUT_BYTES), + reader, ); - const actualArguments = arguments_(snapshot.input); - const id = `ev_${sha256(JSON.stringify([this.context.lease, actualArguments, sha256(snapshot.stdout.text)]))}`; - const bytes = Buffer.byteLength(snapshot.stdout.text); - if (this.#retainedBytes + bytes > 64 * 1024 * 1024) - throw new FactFailure( - "capacity", - "64 MiB retained-source budget reached; close and reopen", - ); - const file = join(this.#root.path, id); - await writeFile(file, snapshot.stdout.text, { flag: "wx" }); - const source = Object.freeze({ - evidence_id: id, - sha256: sha256(snapshot.stdout.text), - bytes: Buffer.byteLength(snapshot.stdout.text), - arguments: Object.freeze(actualArguments), - display_arguments: Object.freeze( - actualArguments.map((s) => - s === snapshot.input ? this.#target.path : s, - ), - ), - elapsed_ms: performance.now() - start, - }); - this.#sources.set(id, { source, file }); - this.#retainedBytes += bytes; - if (this.#captureDirectory) { - await mkdir(this.#captureDirectory, { recursive: true, mode: 0o700 }); - await writeFile( - join(this.#captureDirectory, `${id}.txt`), - snapshot.stdout.text, - { flag: "wx", mode: 0o600 }, - ); - await writeFile( - join(this.#captureDirectory, `${id}.json`), - JSON.stringify({ context: this.context, source }), - { flag: "wx", mode: 0o600 }, + let snapshot, actualArguments, captureInput, primary; + try { + snapshot = requireResult( + await this.#commands.run({ + installation: this.#installation, + operation: "experiment:atomic-facts", + arguments: (input) => { + captureInput = input; + return (actualArguments = arguments_(input)); + }, + outputBytes: NATIVE_OUTPUT_BYTES, + stdout: spool, + timeoutMs: 120000, + signal: AbortSignal.any([ + signal, + this.#lifetime.signal, + spool.rejected, + ]), + }), ); + } catch (error) { + const failure = projectFactFailure(error); + primary = new FactFailure(failure.code, failure.message, failure.details); + if (spool.failure) { + primary = new FactFailure(failure.code, failure.message, { + ...failure.details, + source_capture_failure: projectFactFailure(spool.failure), + }); + } + if ( + spool.failure && + failure.code === "cancelled" && + !signal.aborted && + !this.#lifetime.signal.aborted + ) + primary = spool.failure; + } finally { + await spool.close(primary); } - return { source, input: snapshot.input }; + if (primary && !spool.bytes) { + await spool.discard(); + throw primary; + } + const source = await this.#sourceFiles.retain(spool, { + arguments: actualArguments, + input: captureInput, + started: start, + complete: !primary, + }); + if (primary) { + const failure = projectFactFailure(primary); + throw new FactFailure(failure.code, failure.message, { + ...failure.details, + evidence_id: source.evidence_id, + source_retained: true, + source_complete: false, + }); + } + return { + source, + input: snapshot.input, + ...(reader ? { parsed: reader.finish(snapshot.input) } : {}), + }; } async #sourceText(id) { - const record = this.#sources.get(id); - if (!record) - throw new FactFailure( - "unknown_evidence", - "Evidence is not owned by this target lease", - ); - const text = await readFile(record.file, "utf8"); - if (sha256(text) !== record.source.sha256) - throw new FactFailure("evidence_changed", "Retained source changed"); - return text; + return (await this.#sourceFiles.read(id)).text; } async strings(input, signal) { return this.#catalogs.strings(input, signal); @@ -295,7 +308,7 @@ export class KunaFactOwner { "Snapshot is not owned by the current target lease", ); if (!this.#loaded.has(id)) { - const { source } = this.#sources.get(descriptor.evidence_id); + const source = this.#sourceFiles.source(descriptor.evidence_id); if ( source.bytes > (this.#nativeIR ? NATIVE_OUTPUT_BYTES : 2 * 1024 * 1024) ) @@ -452,9 +465,9 @@ export class KunaFactOwner { this.#lifetime.abort(); // A failed Result retains native cleanup owners; leave this lease retryable. requireResult(await this.#commands.close()); + await this.#sourceFiles.close(); await this.#root.close(); this.#loaded.clear(); - this.#sources.clear(); this.#work.clear(); this.#snapshots.clear(); this.#catalogs.clear(); diff --git a/experiments/atomic-codemode/reference.mjs b/experiments/atomic-codemode/reference.mjs index 5f09c286c3c..274841c6e8f 100644 --- a/experiments/atomic-codemode/reference.mjs +++ b/experiments/atomic-codemode/reference.mjs @@ -46,7 +46,7 @@ const returns = { "data:{operations:[operation rows as above],coverage:{status,boundaries:[{id,reason}],missing,missing_reasons?,source_scope?,source_issues,runtime_reachability,memory_alias_dependencies},value_frontier?:[{value_id?|operation?,input_index?,reason}],evidence_id}", code: "data:{evidence_id,start_line,language:string|null,text,total_lines,next_offset,coverage}; language is native-reported or unknown. Read/filter full reconstructed text within Code Mode without returning it all.", evidence: - "data:{source:{evidence_id,sha256,bytes,arguments},view?:{component,encoding,sha256,bytes,authority},text,total_code_units,next_offset}. Default component:source preserves exact native wire output. component:recovered_ir exposes complete decoded graph JSON with a separate view hash, including compressed graphs; source hash still identifies the original wire capture. This source view preserves malformed logical facts without asserting their validity. One decoded Evidence view up to 32 MiB is cached per lease and source freshness is checked on reads.", + "data:{source:{evidence_id,sha256,bytes,capture_complete,arguments},view?:{component,encoding,sha256,bytes,authority},text,total_code_units,next_offset}. Default component:source pages retained native output with full-file hash validation; capture_complete:false marks a partial capture, not empty facts. component:recovered_ir exposes complete decoded graph JSON with a separate view hash, including compressed graphs; source hash still identifies the original wire capture. This source view preserves malformed logical facts without asserting their validity. One decoded Evidence view up to 32 MiB is cached per lease and source freshness is checked on reads.", }; const referenceSchemas = new WeakMap(); const schemaFor = (input) => { diff --git a/experiments/atomic-codemode/streamed-inventory-oracle.md b/experiments/atomic-codemode/streamed-inventory-oracle.md new file mode 100644 index 00000000000..bd1115e0cd6 --- /dev/null +++ b/experiments/atomic-codemode/streamed-inventory-oracle.md @@ -0,0 +1,39 @@ +# Frozen real FFmpeg inventory task + +Target: Linux `/usr/lib/x86_64-linux-gnu/libavcodec.so.59.37.100`, 14,955,104 +bytes, SHA-256 `28c258cc42cbaf9813bf91b41666d2b8063d10aa77aaaf424fac0079f6497b7e`. +It is read statically and never executed. Native engine remains pinned to +`2e398e7229e30b6d2387a802db8a0050764119a6b457020d334855e36e69d6c5`. + +Independent ELF PT_LOAD/file reads establish the two selected encoded byte runs. +The preceding byte and each final byte are NUL. Each display text ends with LF; +there are 27 text bytes and 28 encoded bytes including NUL. Each query matches +one retained ASCII object, `nul_terminated:true`, in the pinned native inventory. + +| Text query | Address | Inclusive end | First 16 bytes | Final 8 bytes | +| -------------------------- | -------- | ------------- | -------------------------------- | ---------------- | +| Invalid extradata size: %d | 0xb52f2e | 0xb52f49 | 496e76616c6964206578747261646174 | 7a653a2025640a00 | +| Unsupported codec version! | 0xba3ed1 | 0xba3eec | 556e737570706f7274656420636f6465 | 7273696f6e210a00 | + +Both queries share one captured inventory in one lease. Its raw JSON is +16,810,900 bytes and contains 60,601 validated rows. These size/count facts are +producer fidelity, not an independent proof of complete artifact-wide string +recognition. Exact raw hashes include the private input pathname, so source IDs +and hashes differ by lease. Source metadata must say `capture_complete:true`; +that means the stdout capture completed, not that every possible string was +recognized. A bounded source window must actually be read and match that source. + +Grade full original answers against this oracle, actual selected-byte replies, +all cited IDs and complete retained raw captures. Preserve false/unknown coverage, +failures and exact window lengths. Do not repair or rerun a model answer to pick +a winner. Direct and Code Mode share the same 19 fact methods; both clients have +common JavaScript orchestration. Code Mode must actually call its isolated MCP +execution tool. Record all schemas/help, responses, calls/retries, input including +cached and uncached input, output including reasoning, wall, local CPU and kernel +process-family peak. Unknown remote costs remain unknown. + +The old experimental interface cannot answer this task: it refuses the complete +native inventory at its 8 MiB buffer limit before selecting rows. That original +failure is separate from successful completed-task adapter costs. No successful +historical workflow timing, complex-program reasoning superiority, broad provider +parity, cross-session caching or stable Code Mode speedup is implied. diff --git a/experiments/atomic-codemode/streamed-inventory-question.txt b/experiments/atomic-codemode/streamed-inventory-question.txt new file mode 100644 index 00000000000..bf26c3d2a79 --- /dev/null +++ b/experiments/atomic-codemode/streamed-inventory-question.txt @@ -0,0 +1,14 @@ +Analyze {{artifact_path}} statically. Find the retained encoded strings containing +these exact texts: "Invalid extradata size: %d" and "Unsupported codec version!". + +For each match establish the address, encoding, encoded byte length, inclusive +end and provider-reported NUL termination. Corroborate exactly the first 16 and +final 8 bytes with focused loaded-image windows; preserve the returned byte +counts when reporting hex. Establish whether both queries share one complete +retained source, its byte size, and verify a small readable Evidence window. +Cite real Evidence IDs and the target/engine identity. + +Keep unknown discovery and ambiguous matches explicit. Use compact selections; +do not fetch the full string inventory into model context. Distinguish encoded +spans from original source objects, reference/runtime use and live memory. +No target execution. Close the target lease. diff --git a/experiments/atomic-codemode/streamed-inventory-study.md b/experiments/atomic-codemode/streamed-inventory-study.md new file mode 100644 index 00000000000..bddd6512911 --- /dev/null +++ b/experiments/atomic-codemode/streamed-inventory-study.md @@ -0,0 +1,128 @@ +# Streamed native string Evidence + +This work refreshed main to `150e996a8` in `8488f8236`. It remains an experiment: +no PR and no merge into main. Native engine `2e398e7229e30b6d2387a802db8a0050764119a6b457020d334855e36e69d6c5` +is unchanged. Source retrieval through LeanToken returned internal/not-indexed +errors; scoped working-tree reads were used instead. + +## Reproduced coverage gap + +`strings({query,fields:[],limit:1})` still captured a complete stdout string before +selecting rows. In the frozen historical runtime at `8488f8236`, real Linux +FFmpeg `libavcodec.so.59.37.100` fails at the 8 MiB buffered-output ceiling before +answering the selected metadata question. Its complete native inventory is +16,810,900 bytes / 60,601 rows. The earlier LLVM query fails at that same ceiling. +These are real SDK/provider observations, not simulated large responses. + +The FFmpeg ELF is 14,955,104 bytes, SHA-256 +`28c258cc42cbaf9813bf91b41666d2b8063d10aa77aaaf424fac0079f6497b7e`. +Independent ELF PT_LOAD/file reads verify the two selected ASCII runs, preceding +NULs, LF endings, encoded lengths and exact head/tail bytes in the +[frozen oracle](streamed-inventory-oracle.md). The 60,601-row count is native +producer fidelity, not independent proof of complete recognition. + +## One source owner and the existing streaming parser + +The experimental provider now pipes native stdout to a bounded source spool. +Strings additionally feed the production `KunaStringInventoryReader` as bytes +arrive; its validated count/identity/hash/byte size must agree with retained +Evidence. The old whole-string parse wrapper is removed. No native CLI, detection +algorithm, public method count or query/filter semantics changed. + +`NativeSourceStore` owns source metadata, aggregate accounting, raw files and +hash validation. Existing process supervision still owns command cancellation +and cleanup. File descriptors use `OwnedFileHandle` and `ArtifactResourceScope`; +failed closes retain the same owner. Unpublished failed files are removed rather +than accumulating outside accounting. Partial writes update committed prefix +bytes/hash as they succeed. Disk and external-copy failures remain typed; a +failed requested copy keeps a readable source ID and blocks new captures until a +new lease, avoiding silent omission or repeated native work. + +A string capture may use the remaining **existing 64 MiB per-lease source budget**; +there is no aggregate stdout string in the host. Other native formats keep their +8 MiB source bound and stderr retains the 8 MiB diagnostic bound. The production +reader independently bounds retained heap. This does not bound native scan or +renderer allocation: the native command still inventories and renders the whole +target before selection. Per-lease parsed reuse is not cross-session caching. + +Native failures may retain an exact partial prefix. `source.capture_complete:false` +and typed failure details distinguish this from a valid empty result. A complete +capture can still contain invalid facts, which the parser rejects with Evidence +retained. Raw Evidence windows use a UTF-8 streaming decoder and retain only the +requested UTF-16 code units, while hashing the entire source on every read before +return. This preserves freshness and slice semantics across split multibyte or +surrogate boundaries; small replies do not make hash validation sublinear. + +## Executed checks and costs + +Real SDK, Direct MCP and Code Mode FFmpeg verifiers all pass selected metadata, +default text, cache/source identity, exact loaded bytes, raw windows, all five +retained raw digests and stale-handle rejection after reopen. The actual CLI also +returns the selected metadata. Native strings scan once per lease; four selected +byte windows have their own captures. All facts remain available through the same +shared session, with nineteen methods / twenty-two Direct tools / four Code tools. + +The first FFmpeg verifier failed because it expected byte coverage `complete` +instead of the existing `complete-for-requested-range`. That was corrected in +the verifier; the original log is retained. SQLite reference/NUL/span checks pass +in all three lanes, as do real x86 SSH complete-function/prototype fidelity and +actual converted catalog/schema checks. All 111 experimental JS tests pass, +including Unicode slices, out-of-window mutation, exact/aggregate capacity, +malformed provider facts, deduplication, partial-write failure, external-copy +failure and retained descriptor cleanup. Changed-file lint/format checks pass. +The latest-main runtime build passes. No full `check:pr`, new Ghidra/IDA lane, +exhaustive corpus or CPU-time speedup is claimed. The earlier bounded +`check:fast` refusal is not a pass and was not retried. + +| Whole verifier/probe | Wall s | Local family CPU s | Kernel family peak MiB | +| --------------------------------------------- | -----: | -----------------: | ---------------------: | +| Latest-main runtime build | 33.644 | 33.444422 | 3,047.6 | +| Old FFmpeg SDK probe, fails before selection | 1.631 | 1.423863 | 212.4 | +| New FFmpeg SDK verifier | 6.866 | 6.680577 | 348.8 | +| New FFmpeg Direct verifier | 7.369 | 7.125644 | 435.8 | +| New FFmpeg Code Mode verifier | 7.571 | 7.280821 | 431.8 | +| LLVM capacity + partial source + cancellation | 10.187 | 9.915344 | 1,489.5 | +| SSH fidelity | 8.681 | 8.427966 | 323.3 | +| Converted catalog/schema checks | 2.033 | 1.806248 | 141.0 | +| 111 JS tests | 6.563 | 6.307038 | 127.8 | + +The old probe aborts early and does less work than the completed new verifiers; +these costs cannot rank equivalent completed workflows. New cold metadata calls +are 2.29 / 2.31 / 2.41 seconds in SDK / Direct / Code Mode; warm metadata is +5.1 / 7.5 / 13.9 ms. Second-query reuse is 5.5 / 9.2 / 12.6 ms. Raw Evidence +windows take 82–96 ms in this sample, including full-file validation. These are +single fresh-lease observations, not cold kernel-cache or warm-model repeats. +Scripted probes have no model tokens. + +Every successful resource receipt above verifies OOM=0 and owned payload cleanup +at payload exit while the observer remains alive. Final exited-cgroup counters +are unavailable; kernel family memory includes file cache, not just RSS. Runs +are serial on one CPU with 3 GiB early stop / 4 GiB hard cap / no swap; builds +use 3.25 GiB early stop. Inherited ambient processes are outside the measurement. +The evaluator's explicitly retained raw copies are separate from lease handles. + +## Larger targets remain blocked + +Real `libLLVM-16.so.1`, `/usr/bin/node` and pinned Node 24 all exceed 64 MiB of +raw native inventory. The first streamed LLVM probe returns explicit capacity +with a retained partial prefix. Initial Node probes additionally report command +identity/cleanup uncertainty (`observed=[kuna]`) while stopping at that ceiling; +subsequent session close and payload cleanup are verified. Those original primary +failures are preserved, not converted into successful analysis. Current errors +also retain the source-budget failure when cleanup uncertainty remains primary. +The final LLVM verifier passes rejection, partial-prefix hash/readability, +500 ms request cancellation and owned cleanup checks; it does **not** successfully +analyze LLVM strings. Peaks across these probes are about 1.46–1.64 GiB, OOM=0. + +Do not increase the source budget merely to call these targets supported. A +producer-side literal/metadata selection or reusable compact index needs another +measured experiment. Stock regex filtering is not a correctness substitute for +literal search: its backtracking budget can classify an unexamined suffix as +nonmatching. This is a source-derived concern, not a newly reproduced runtime +regex false-negative claim. Whole-inventory native computation and these larger +coverage failures remain unresolved. + +The [model question](streamed-inventory-question.txt) and oracle are frozen before +actual isolated Direct/Code Mode trials. Record their original full answers and +whole-task costs separately; this prerequisite repair is not itself evidence +that Code Mode improves complex reverse-engineering reasoning. diff --git a/experiments/atomic-codemode/string-facts.mjs b/experiments/atomic-codemode/string-facts.mjs index f3e1d34a47b..76d886c5a96 100644 --- a/experiments/atomic-codemode/string-facts.mjs +++ b/experiments/atomic-codemode/string-facts.mjs @@ -1,16 +1,4 @@ -import { Readable } from "node:stream"; -import { pipeline } from "node:stream/promises"; -import { KunaStringInventoryReader } from "../../dist/kuna/KunaStringInventory.js"; -import { requireResult } from "./fact-error.mjs"; -import { freezeFacts, pageFacts } from "./fact-reads.mjs"; - -export const parseStringFacts = async (text, input) => { - const reader = new KunaStringInventoryReader(); - await pipeline(Readable.from([text]), reader); - return freezeFacts( - requireResult(reader.finish(input), "invalid_provider_output"), - ); -}; +import { pageFacts } from "./fact-reads.mjs"; export const selectStringFacts = (inventory, input) => ({ ...pageFacts( diff --git a/experiments/atomic-codemode/verify-source-capacity.mjs b/experiments/atomic-codemode/verify-source-capacity.mjs new file mode 100644 index 00000000000..3886f28724e --- /dev/null +++ b/experiments/atomic-codemode/verify-source-capacity.mjs @@ -0,0 +1,118 @@ +// Real LLVM capacity and native-command cancellation; never execute the target. +import assert from "node:assert/strict"; +import { readFile, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { AtomicSession } from "./session.mjs"; +import { + createVerifierRun, + completeVerifierRun, + assertVerifierCleanupComplete, +} from "../../scripts/lib/verifier-run.mjs"; + +const [target, output] = process.argv.slice(2); +assert(target && output && process.env.REA_ATOMIC_EVIDENCE_DIR); +const hash = (b) => createHash("sha256").update(b).digest("hex"); +const digest = hash(await readFile(target)); +assert.equal( + digest, + "f62d254b7f2bf42df8c8b07d46ee3bb4c2cafeca436b2e6bc6ccbe4581f58f40", +); +const run = createVerifierRun(), + session = new AtomicSession(), + observations = [], + failures = []; +try { + await session.open(target); + const start = performance.now(), + response = await session.call("strings", { + query: "undefined symbol", + fields: [], + limit: 2, + }); + assert.equal(response.ok, false); + assert(!Object.hasOwn(response, "data")); + assert( + ["resource_constraint", "cleanup_incomplete"].includes(response.error.code), + ); + const details = response.error.details, + capacity = + response.error.code === "resource_constraint" + ? details + : details.source_capture_failure?.details; + assert.equal(capacity.scope, "native_source"); + assert.equal(capacity.limit_bytes, 64 * 1024 * 1024); + assert(capacity.observed_bytes_at_least > capacity.limit_bytes); + assert.equal(details.source_retained, true); + assert.equal(details.source_complete, false); + observations.push({ + phase: "capacity", + elapsed_ms: performance.now() - start, + response, + }); + const evidence = await session.call("evidence", { + evidence_id: details.evidence_id, + offset: 0, + limit: 128, + }); + assert(evidence.ok); + assert.equal(evidence.data.source.capture_complete, false); + assert.equal(evidence.data.text.length, 128); + const raw = await readFile( + join(process.env.REA_ATOMIC_EVIDENCE_DIR, details.evidence_id + ".txt"), + ); + assert.equal(hash(raw), evidence.data.source.sha256); + assert.equal(raw.length, evidence.data.source.bytes); + assert(raw.length <= capacity.limit_bytes); + assert.equal(evidence.data.text, raw.toString().slice(0, 128)); + observations.push({ phase: "partial_evidence", response: evidence }); + await session.close(); + await session.open(target); + const cancellation = new AbortController(), + timer = setTimeout( + () => cancellation.abort("source verifier cancellation"), + 500, + ); + let cancelled; + try { + cancelled = await session.call( + "strings", + { query: "undefined symbol", fields: [], limit: 2 }, + cancellation.signal, + ); + } finally { + clearTimeout(timer); + } + assert.equal(cancelled.ok, false); + assert.equal(cancelled.error.code, "cancelled"); + observations.push({ phase: "cancellation", response: cancelled }); +} catch (error) { + failures.push(error.stack ?? String(error)); +} finally { + session.abort(); + await session.close(); +} +const lifecycle = await completeVerifierRun(run); +assertVerifierCleanupComplete(lifecycle.process_lineage); +assert.equal(hash(await readFile(target)), digest); +await writeFile( + output, + JSON.stringify( + { target, digest, observations, failures, lifecycle }, + null, + 2, + ), + { flag: "wx" }, +); +console.log( + JSON.stringify({ + phases: observations.map(({ phase, response, ...rest }) => ({ + phase, + ok: response.ok, + code: response.error?.code ?? null, + ...rest, + })), + failures, + }), +); +assert.deepEqual(failures, []); diff --git a/experiments/atomic-codemode/verify-streamed-inventory.mjs b/experiments/atomic-codemode/verify-streamed-inventory.mjs new file mode 100644 index 00000000000..ff481ce4a15 --- /dev/null +++ b/experiments/atomic-codemode/verify-streamed-inventory.mjs @@ -0,0 +1,257 @@ +// Real Linux FFmpeg inventory beyond the buffered wire cap, through public adapters. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile, writeFile, readdir } from "node:fs/promises"; +import { resolve, join } 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 { MAX_MCP_RESULT_BYTES, NATIVE_OUTPUT_BYTES } from "./limits.mjs"; +import { + createVerifierRun, + completeVerifierRun, + assertVerifierCleanupComplete, +} from "../../scripts/lib/verifier-run.mjs"; + +const [target, output, adapter = "sdk"] = process.argv.slice(2); +assert(target && output && ["sdk", "direct", "codemode"].includes(adapter)); +assert(process.env.REA_ATOMIC_EVIDENCE_DIR); +const sha = (value) => createHash("sha256").update(value).digest("hex"); +const bytes = await readFile(target), + digest = sha(bytes); +assert.equal( + digest, + "28c258cc42cbaf9813bf91b41666d2b8063d10aa77aaaf424fac0079f6497b7e", +); +// File offsets and target coordinates independently checked against ELF PT_LOAD. +const cases = [ + { + query: "Invalid extradata size: %d", + address: "0xb52f2e", + file_offset: 0xb52f2e, + }, + { + query: "Unsupported codec version!", + address: "0xba3ed1", + file_offset: 0xba3ed1, + }, +]; +const run = createVerifierRun(), + observations = [], + phases = [], + failures = []; +const session = adapter === "sdk" ? new AtomicSession() : null; +const client = session + ? null + : new Client({ name: "streamed-inventory-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); + assert(Buffer.byteLength(JSON.stringify(reply)) <= MAX_MCP_RESULT_BYTES); + return JSON.parse(reply.content[0].text); +}; +const read = async (name, input) => { + const wrapper = session + ? await session.call(name, input) + : adapter === "direct" + ? await invoke("facts_" + name, input) + : await invoke("execute_javascript", { + code: `return await rea.${name}(${JSON.stringify(input)});`, + }); + const response = session || adapter === "direct" ? wrapper : wrapper.value; + assert(response); + observations.push({ + name, + input, + response_bytes: Buffer.byteLength(JSON.stringify(response)), + ok: response.ok, + error: response.error ?? null, + }); + return response; +}; +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, + family_cpu_seconds: (after.cpu - before.cpu) / 1e6, + }); + return result; +}; +let context, + source, + rawBytes, + rawRows, + checked = 0; +try { + if (session) context = (await session.open(target)).context; + else { + await client.connect(transport); + context = (await invoke("open_binary", { path: target })).context; + } + for (const [index, fixture] of cases.entries()) { + const r = await measure( + index ? "same_inventory_second_query" : "cold_metadata", + () => read("strings", { query: fixture.query, fields: [], limit: 1 }), + ); + assert(r.ok); + assert.equal(r.context.lease, context.lease); + assert.equal(r.data.total, 1); + assert.equal(r.data.items.length, 1); + const row = r.data.items[0]; + assert.equal(row.address, fixture.address); + assert.equal(row.string.encoding, "ascii"); + assert.equal(row.string.nul_terminated, true); + assert.equal(row.string.byte_length, 28); + assert(!Object.hasOwn(row, "value")); + if (source) assert.equal(r.data.source.evidence_id, source.evidence_id); + else source = r.data.source; + assert.equal(source.capture_complete, true); + assert(source.bytes > NATIVE_OUTPUT_BYTES); + const value = await read("strings", { + query: fixture.query, + fields: ["value"], + limit: 1, + }); + assert(value.ok); + assert.equal( + value.data.items[0].value, + bytes.subarray(fixture.file_offset, fixture.file_offset + 27).toString(), + ); + assert.equal(bytes[fixture.file_offset - 1], 0); + assert.equal(bytes[fixture.file_offset + 27], 0); + } + await measure("warm_metadata", () => + read("strings", { query: cases[0].query, fields: [], limit: 1 }), + ); + const raw = await readFile( + join(process.env.REA_ATOMIC_EVIDENCE_DIR, source.evidence_id + ".txt"), + ); + assert.equal(sha(raw), source.sha256); + assert.equal(raw.length, source.bytes); + rawBytes = raw.length; + const inventory = JSON.parse(raw.toString()); + assert.equal(inventory.count, 60601); + assert.equal(inventory.strings.length, inventory.count); + rawRows = inventory.count; + const offset = raw.toString().indexOf(cases[1].query); + for (const name of ["raw_evidence_first", "raw_evidence_repeat"]) { + const evidence = await measure(name, () => + read("evidence", { evidence_id: source.evidence_id, offset, limit: 32 }), + ); + assert(evidence.ok); + assert.equal(evidence.data.source.evidence_id, source.evidence_id); + assert.equal(evidence.data.text, raw.toString().slice(offset, offset + 32)); + assert.equal(evidence.data.total_code_units, raw.toString().length); + } + const windows = cases.flatMap((row) => [ + { address: row.address, length: 16 }, + { address: "0x" + (BigInt(row.address) + 20n).toString(16), length: 8 }, + ]); + const selected = await read("bytes", { windows }); + assert(selected.ok); + assert.equal(selected.data.results.length, 4); + for (const [i, row] of selected.data.results.entries()) { + assert(row.ok); + const fixture = cases[Math.floor(i / 2)], + length = i % 2 ? 8 : 16, + offset = fixture.file_offset + (i % 2 ? 20 : 0); + assert.equal( + row.hex, + bytes.subarray(offset, offset + length).toString("hex"), + ); + assert.equal(row.returned_bytes, length); + assert.equal(row.coverage.status, "complete-for-requested-range"); + } + for (const file of await readdir(process.env.REA_ATOMIC_EVIDENCE_DIR)) { + if (!file.endsWith(".json")) continue; + const record = JSON.parse( + await readFile(join(process.env.REA_ATOMIC_EVIDENCE_DIR, file), "utf8"), + ), + payload = await readFile( + join( + process.env.REA_ATOMIC_EVIDENCE_DIR, + file.replace(/\.json$/u, ".txt"), + ), + ); + assert.equal(record.context.artifact_sha256, digest); + assert.equal(record.context.engine_sha256, context.engine_sha256); + assert.equal(sha(payload), record.source.sha256); + assert.equal(payload.length, record.source.bytes); + assert.equal(record.source.capture_complete, true); + checked++; + } + assert.equal(checked, 5); + if (session) { + await session.close(); + await session.open(target); + } else { + await invoke("close_binary", {}); + await invoke("open_binary", { path: target }); + } + const stale = await read("evidence", { + evidence_id: source.evidence_id, + limit: 1, + }); + assert.equal(stale.ok, false); + assert.equal(stale.error.code, "unknown_evidence"); + assert.notEqual(stale.context.lease, context.lease); +} 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, + context, + source, + raw_bytes: rawBytes, + raw_rows: rawRows, + raw_sources_verified: checked, + observations, + phases, + failures, + lifecycle, + }, + null, + 2, + ), + { flag: "wx" }, +); +console.log( + JSON.stringify({ adapter, source, rawRows, checked, phases, failures }), +); +assert.deepEqual(failures, []);