fix(experiment): align native reads with refreshed main

Retain inspection file owners before a target lease exists and gate replacement on cleanup. Reuse the streaming string inventory owner and the same installation adapter in native profiling.

Validate 80 related tests, real SSH value/source parity in both MCP adapters, injected descriptor/native cleanup retries, zlib SDK immutability and native profiling. Keep historical model costs pinned to their measured runtime.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
committed 2026-10-16 18:01:04 +00:00
1 parent 8e0aa73db2
commit 7a76e0b9ba
12 files changed
+332 -46

No files matched your search

+5
View File
@@ -6,6 +6,11 @@ This is an **in-progress experiment**, not an integrated provider release. Branc
prototype. Historical measurements in `../atomic-re-tools/` retain their original
baselines. No PR or merge is intended.
The branch was subsequently [refreshed from main `60bf10245`](main-refresh-study.md).
Shared installation/file cleanup and string parsing now follow that main's
owners. Historical model measurements retain their original frozen runtimes;
the refresh has separate real-provider verification and resource receipts.
The goal is a real model completing reverse-engineering questions through
composable facts, with Code Mode as the calling adapter. A configured feature flag,
a scripted verifier or a small response does not prove that goal.
+21 -1
View File
@@ -4,6 +4,8 @@ import { KunaFactOwner } from "./provider.mjs";
import { FactFailure } from "./fact-error.mjs";
import { MAX_BYTE_BATCH_BYTES } from "./limits.mjs";
import { createReference } from "./reference.mjs";
import { ArtifactResourceScope } from "../../dist/artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../../dist/artifacts/ArtifactReader.js";
const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u);
const snapshot = z.string().startsWith("snap_");
@@ -333,6 +335,7 @@ methods.references.input = methods.references.input.superRefine(
export class AtomicSession {
#owner;
#tail = Promise.resolve();
#files = new ArtifactResourceScope();
constructor(factory = KunaFactOwner.open) {
this.factory = factory;
}
@@ -347,11 +350,27 @@ export class AtomicSession {
abort() {
this.#owner?.cancel();
}
async #releaseFiles() {
try {
await this.#files.retryCleanup();
} catch (cause) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cause,
"Target session files",
);
throw new FactFailure("cleanup_incomplete", cleanup.reason, {
resources: cleanup.resources,
});
}
}
open(path) {
return this.#admit(async () => {
await this.#releaseFiles();
if (this.#owner) await this.#owner.close();
this.#owner = undefined;
this.#owner = await this.factory(path);
this.#owner = await this.factory(path, {
fileResources: this.#files,
});
return {
ok: true,
context: this.context,
@@ -363,6 +382,7 @@ export class AtomicSession {
close() {
return this.#admit(async () => {
if (this.#owner) await this.#owner.close();
await this.#releaseFiles();
this.#owner = undefined;
return { ok: true, closed: true };
});
+58
View File
@@ -130,6 +130,64 @@ test("close drains admitted reads and a failed cleanup retains ownership for ret
await session.close();
assert.equal(session.context, null);
});
for (const action of ["close", "replace"])
test(`failed open retains session file owners through ${action} and cleanup retry`, async () => {
let acquisitions = 0,
cleanupAttempts = 0,
releasable = false;
const primary = new Error(
"Engine inspection failed after acquiring a file",
);
const session = new AtomicSession(async (path, { fileResources }) => {
acquisitions++;
if (acquisitions === 1)
return fileResources.run(async () => {
fileResources.retain({
kind: "lease",
resource: "/selected/engine",
lease: {
release: async () => {
cleanupAttempts++;
if (!releasable) throw new Error("Descriptor remains open");
},
},
});
throw primary;
});
return {
context: { lease: "recovered", selected_path: path },
close: async () => {},
};
});
await assert.rejects(session.open("first"), (error) => error === primary);
assert.equal(session.context, null);
assert.equal(
(await session.call("strings", { query: "x" })).error.code,
"no_target",
);
const retry = () =>
action === "close" ? session.close() : session.open("second");
await assert.rejects(
retry(),
(error) =>
error.code === "cleanup_incomplete" &&
error.details.resources.length === 1 &&
error.details.resources[0] === "/selected/engine",
);
assert.equal(acquisitions, 1, "Unresolved owners block replacement");
assert.equal(cleanupAttempts, 1);
releasable = true;
assert.equal((await retry()).ok, true);
assert.equal(cleanupAttempts, 2);
if (action === "close") {
assert.equal(session.context, null);
assert.equal((await session.open("second")).ok, true);
}
assert.equal(acquisitions, 2);
assert.equal(session.context.lease, "recovered");
await session.close();
assert.equal(cleanupAttempts, 2, "Released owners are not retried");
});
test("cancellation before admission makes no provider query; advertised reference schemas compile", async () => {
const provider = factory();
const session = new AtomicSession(provider.create);
@@ -0,0 +1,102 @@
# Main refresh and shared-owner compatibility
The experiment was refreshed from main
`60bf1024592888b5efb78f9c9458b4633da298bd` at merge commit `8e0aa73db`.
This updates only the experimental branch; no PR or integration merge is intended.
The [OpenSSH model comparison](ssh-warning-study.md) remains a historical result
at frozen runtime `09677946c`. Its model runs were not repeated on this new
compiled runtime, and its costs must not be relabeled as current measurements.
## Producing boundaries
Main now requires caller-owned file resources when inspecting Kuna. The session
owns an `ArtifactResourceScope` before attempting an open, including when no
target lease is established. A failed descriptor close keeps its exact owner;
close retries it, and another open cannot acquire a replacement until cleanup
succeeds. The shared native-installation adapter reuses main's error projection
and cleanup leases. The diagnostic native profiler uses the same adapter and
retains its own file scope through final cleanup. No fallback installation
parser or parallel resource manager was added.
Main also replaced the whole-string inventory parser with
`KunaStringInventoryReader`. The experiment feeds its bounded retained source
through that owner and freezes the validated inventory once. The underlying
capture still retains complete source Evidence; this adapter update does not
establish streaming native capture or a new analysis speedup.
The initial source test invocation failed to load the removed string-parser
export. After updating that boundary, 65 Code Mode/API tests and the 15 shared
atomic-fact tests pass. The two new cases verify failed-open cleanup and
replacement admission. Focused lint reports no warnings, and formatting passes.
## Real artifact checks
The unchanged preserved `a9ca8a8a...` experimental engine is used throughout.
Both actual MCP adapters repeat the stripped OpenSSH value task, checking all
250 selected SSA versions and 369 operand occurrences against the earlier
complete native graph. Both caller/emitter function records equal the prior
goldens, including C, calls and graph fields. Each route executes fifteen MCP
requests; these are verification scripts, not new model trials.
A first Code Mode verifier attempt omitted its required evaluator Evidence
directory. Its reads succeeded but its later producer comparison failed. That
attempt remains recorded; the verifier now validates the required setting
before analysis, and both complete reruns pass with separate source directories.
Linux MCP failure injection rejects two close attempts for the actual engine
fingerprint descriptor. Procfs confirms the same descriptor remains open after
the failed initial open and blocked replacement, then disappears after the
successful close retry. The lease stays null until a later open succeeds.
Both adapters also repeat the existing native-close failure/retry scenario.
These failures are injected, not observed OS or engine cleanup incidents.
Real zlib SDK reads preserve cached strings, aliases and source metadata against
caller mutation and verify the complete Evidence digest. SDK cleanup/replacement
retry checks pass on SSH. The native profiler completes two zlib `inflateReset`
captures at `0xbf00` with equal function records; internal timing is disabled.
The generated traditional baseline still contains exactly the sixteen declared
native/session/view tools, matching the earlier corrected manifest. Declared
catalog coverage does not prove every operation's live behavior.
## Executed resource costs
| Scope | Family wall s | Family CPU s | Kernel peak MiB |
| ---------------------------------- | ------------: | -----------: | --------------: |
| Locked dependency install | 20.462 | 19.525 | 1,601.2 |
| Runtime and packaged-skill build | 85.441 | 84.797 | 2,730.4 |
| Code Mode/API tests, 65 | 4.447 | 4.234 | 87.5 |
| Shared atomic-fact tests, 15 | 0.623 | 0.439 | 43.9 |
| SSH value queries, Code Mode | 9.382 | 9.146 | 336.5 |
| SSH value queries, direct | 8.976 | 8.759 | 346.5 |
| Engine descriptor retry, Code Mode | 2.036 | 1.769 | 198.0 |
| Engine descriptor retry, direct | 1.935 | 1.728 | 184.8 |
| Native close retry, Code Mode | 1.831 | 1.650 | 188.9 |
| Native close retry, direct | 1.744 | 1.559 | 182.4 |
| SDK inventory immutability | 1.530 | 1.285 | 123.8 |
| SDK cleanup/replacement retry | 1.831 | 1.602 | 128.1 |
| Native profiler, two captures | 1.931 | 1.683 | 110.2 |
| Actual baseline catalog generation | 3.943 | 3.727 | 438.2 |
All use one CPU, 4 GiB hard / 3 GiB early-stop memory bounds, OOM/kill 0 and
verified payload cleanup. Kernel process-family peaks include charged file
cache, not RSS. Source receipts remain under `.cache/atomic-codemode/main-refresh-*`.
The unsuccessful initial test/load attempt costs 3.138 wall / 2.942 CPU seconds,
79.8 MiB; the incomplete verifier attempt costs 9.181 / 8.941 seconds, 353.2 MiB.
Both also have OOM 0 and verified cleanup.
The successful query verifiers retain separate fresh leases/native caches:
| Phase | Code Mode wall / CPU s | Direct wall / CPU s |
| ------------------------------------------- | ---------------------: | ------------------: |
| Two fresh native captures | 7.354 / 7.346 | 7.139 / 7.087 |
| First indexed task, all 250 values/369 uses | 0.233 / 0.234 | 0.167 / 0.168 |
| Same-lease selected one-value/use read | 0.008 / 0.009 | 0.008 / 0.006 |
The last two rows complete different tasks; they do not measure a warm-task
speedup. The native profiler's fresh/second-process captures take 643.1/453.9 ms,
with private native cache reuse, without separate CPU or peak measurements.
The family table includes startup, capture, reads and cleanup. Cumulative peaks
do not isolate warm memory; OS caches and host contention are uncontrolled.
No new real-agent token measurement was performed in this refresh. Full
repository/native test suites, other providers, and new real-agent comparisons
on this refreshed runtime remain unverified.
@@ -0,0 +1,38 @@
// Both the session and diagnostic profiler keep descriptor ownership on failed open.
import {
createKunaFileCloseScope,
inspectKunaInstallation,
} from "../../dist/kuna/KunaInstallation.js";
import { kunaFileCleanupError } from "../../dist/kuna/KunaCommand.js";
import { RegularFileCleanupFailure } from "../../dist/filesystem/OwnedRegularFile.js";
import { requireResult } from "./fact-error.mjs";
export const inspectNativeInstallation = async (
environment,
resources,
signal,
) => {
const files = createKunaFileCloseScope({
retain: (owner, resource) =>
resources.retain({
kind: "lease",
resource,
lease: { release: () => owner.close() },
}),
run: (operation) => resources.run(operation),
});
try {
return requireResult(
await inspectKunaInstallation(environment, {
signal,
fileCloseResources: files.owner,
}),
"provider_unavailable",
);
} catch (cause) {
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
const error = kunaFileCleanupError(cause, "experiment:atomic-open", signal);
files.bindFailure(cause, error);
return requireResult({ ok: false, error });
}
};
+16 -4
View File
@@ -5,7 +5,9 @@ import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { parseArgs } from "node:util";
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
import { inspectKunaInstallation } from "../../dist/kuna/KunaInstallation.js";
import { ArtifactResourceScope } from "../../dist/artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../../dist/artifacts/ArtifactReader.js";
import { inspectNativeInstallation } from "./native-installation.mjs";
import { KunaTargetCommands } from "../../dist/kuna/KunaTargetCommands.js";
import { PrivateRuntimeRoot } from "../../dist/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../dist/process/ProviderProcess.js";
@@ -51,15 +53,17 @@ const verifier = createVerifierRun(),
runs = [],
failures = [];
const root = await PrivateRuntimeRoot.create({ prefix: "rea-atomic-profile-" });
const files = new ArtifactResourceScope();
let commands, installation, target;
try {
target = requireResult(await parseBinaryTarget(binary));
installation = requireResult(
await inspectKunaInstallation({
installation = await inspectNativeInstallation(
{
...process.env,
REA_KUNA_COMMAND: engine,
REA_KUNA_CACHE_DIR: join(root.path, "engine-cache"),
}),
},
files,
);
commands = new KunaTargetCommands(target, {
signal: new AbortController().signal,
@@ -168,6 +172,14 @@ try {
stack: error.stack,
});
} finally {
try {
await files.close();
} catch (error) {
failures.push({
code: "cleanup_incomplete",
...ArtifactReaderFailure.cleanupObservation(error, engine),
});
}
let closed = true;
if (commands) {
const result = await commands.close();
+7 -6
View File
@@ -3,7 +3,7 @@ import { createHash, randomUUID } from "node:crypto";
import { writeFile, readFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
import { inspectKunaInstallation } from "../../dist/kuna/KunaInstallation.js";
import { inspectNativeInstallation } from "./native-installation.mjs";
import { KunaTargetCommands } from "../../dist/kuna/KunaTargetCommands.js";
import { referenceReader } from "./reference-reads.mjs";
import { PrivateRuntimeRoot } from "../../dist/process/PrivateRuntimeRoot.js";
@@ -49,15 +49,16 @@ export class KunaFactOwner {
}));
#nativeIR = false;
context;
static async open(path, environment = process.env) {
static async open(path, { environment = process.env, fileResources }) {
const owner = new KunaFactOwner();
owner.#target = requireResult(
await parseBinaryTarget(path),
"invalid_target",
);
owner.#installation = requireResult(
await inspectKunaInstallation(environment),
"provider_unavailable",
owner.#installation = await inspectNativeInstallation(
environment,
fileResources,
owner.#lifetime.signal,
);
const nativeIRHash = environment.REA_ATOMIC_NATIVE_IR_ENGINE_SHA256;
if (
@@ -204,7 +205,7 @@ export class KunaFactOwner {
],
signal,
);
this.#strings ??= parseStringFacts(
this.#strings ??= await parseStringFacts(
await this.#sourceText(capture.source.evidence_id),
capture.input,
);
@@ -7,6 +7,10 @@ starts from two formats, without addresses, and accepts machine-supported
answers without requiring native-only SSA identities. This tests a local
cross-function warning/guard path, not reverse engineering the whole application.
A later [main refresh](main-refresh-study.md) has its own compatibility checks.
The model costs below still refer to the original frozen runtime; they were not
remeasured on the refreshed compiled REA runtime.
## Correctness and coverage
All four complete answers pass the frozen oracle/source review: both format
+9 -7
View File
@@ -1,14 +1,16 @@
import { parseKunaStringInventory } from "../../dist/kuna/KunaStringInventory.js";
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 = (text, input) =>
freezeFacts(
requireResult(
parseKunaStringInventory(text, input),
"invalid_provider_output",
),
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"),
);
};
export const selectStringFacts = (inventory, input) => ({
...pageFacts(
@@ -1,6 +1,6 @@
// Real public MCP lifecycle, with one explicit test-only tagged failure.
// Real public MCP lifecycle, with explicitly injected cleanup failures.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { readFile, readlink, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { Client } from "@modelcontextprotocol/client";
@@ -12,8 +12,12 @@ import {
assertVerifierCleanupComplete,
} from "../../scripts/lib/verifier-run.mjs";
const [binary, output] = process.argv.slice(2);
assert.ok(binary && output, "Usage: verify-cleanup-mcp.mjs BINARY OUTPUT");
const [binary, output, scenario = "native-close"] = process.argv.slice(2);
assert.ok(
binary && output,
"Usage: verify-cleanup-mcp.mjs BINARY OUTPUT [native-close|installation-close]",
);
assert.ok(["native-close", "installation-close"].includes(scenario));
const run = createVerifierRun(),
calls = [],
failures = [],
@@ -22,15 +26,29 @@ const run = createVerifierRun(),
});
const url = (path) => JSON.stringify(pathToFileURL(resolve(path)).href);
const bootstrap = join(root.path, "injected-cleanup.mjs");
const audit = join(root.path, "injected-descriptor.json");
await writeFile(
bootstrap,
`import {KunaTargetCommands} from ${url("dist/kuna/KunaTargetCommands.js")};
scenario === "native-close"
? `import {KunaTargetCommands} from ${url("dist/kuna/KunaTargetCommands.js")};
import {ProviderCleanupError} from ${url("dist/domain/providerCleanupError.js")};
import {err} from ${url("dist/domain/result.js")};
const close=KunaTargetCommands.prototype.close;let injected=false;
KunaTargetCommands.prototype.close=async function(){
if(!injected){injected=true;return err(new ProviderCleanupError("kuna",["verifier-injected-cleanup-resource"],{reason:"Explicit verifier fault; not a real engine cleanup failure"}));}
return close.call(this);
};`
: `import {OwnedFileHandle} from ${url("dist/filesystem/OwnedFileHandle.js")};
import {readlink,realpath,writeFile} from "node:fs/promises";
const engine=await realpath(process.env.REA_KUNA_COMMAND);
const close=OwnedFileHandle.prototype.close;let selected,failures=0;
OwnedFileHandle.prototype.close=async function(){
if(selected===undefined && await readlink("/proc/self/fd/"+this.handle.fd).catch(()=>null)===engine){
selected=this;
await writeFile(${JSON.stringify(audit)},JSON.stringify({descriptor:"/proc/"+process.pid+"/fd/"+this.handle.fd,engine}),{flag:"wx"});
}
if(this===selected && failures++<2)throw new Error("Verifier-injected engine descriptor close failure; not an observed OS failure");
return close.call(this);
};`,
{ flag: "wx" },
);
@@ -53,6 +71,26 @@ const call = async (name, input) => {
};
try {
await client.connect(transport);
if (scenario === "installation-close") {
assert.equal(process.platform, "linux", "Descriptor probe requires procfs");
const failed = await call("open_binary", { path: binary });
assert.equal(failed.ok, false);
assert.equal(failed.context, null);
assert.equal(failed.error.code, "cleanup_incomplete");
const descriptor = JSON.parse(await readFile(audit, "utf8"));
assert.deepEqual(failed.error.details.failure.details.resources, [
descriptor.engine,
]);
assert.equal(await readlink(descriptor.descriptor), descriptor.engine);
const blocked = await call("open_binary", { path: binary });
assert.equal(blocked.ok, false);
assert.equal(blocked.context, null);
assert.equal(blocked.error.code, "cleanup_incomplete");
assert.deepEqual(blocked.error.details.resources, [descriptor.engine]);
assert.equal(await readlink(descriptor.descriptor), descriptor.engine);
assert.equal((await call("close_binary", {})).ok, true);
await assert.rejects(readlink(descriptor.descriptor), { code: "ENOENT" });
}
const opened = await call("open_binary", { path: binary });
assert.equal(opened.ok, true);
const direct = process.env.REA_ATOMIC_ADAPTER === "direct";
@@ -63,13 +101,15 @@ try {
});
assert.equal(read.ok, true);
if (!direct) assert.equal(read.value.ok, true);
const failed = await call("close_binary", {});
assert.equal(failed.ok, false);
assert.equal(failed.context.lease, opened.context.lease);
assert.equal(failed.error.code, "cleanup_incomplete");
assert.deepEqual(failed.error.details.failure.details.resources, [
"verifier-injected-cleanup-resource",
]);
if (scenario === "native-close") {
const failed = await call("close_binary", {});
assert.equal(failed.ok, false);
assert.equal(failed.context.lease, opened.context.lease);
assert.equal(failed.error.code, "cleanup_incomplete");
assert.deepEqual(failed.error.details.failure.details.resources, [
"verifier-injected-cleanup-resource",
]);
}
assert.equal((await call("close_binary", {})).ok, true);
} catch (error) {
failures.push(error.stack ?? String(error));
@@ -86,8 +126,12 @@ try {
}
const lifecycle = await completeVerifierRun(run);
assertVerifierCleanupComplete(lifecycle.process_lineage);
await writeFile(output, JSON.stringify({ calls, failures, lifecycle }), {
flag: "wx",
});
await writeFile(
output,
JSON.stringify({ scenario, calls, failures, lifecycle }),
{
flag: "wx",
},
);
console.log(JSON.stringify({ output, calls: calls.length, failures }));
if (failures.length) process.exitCode = 1;
@@ -22,8 +22,8 @@ const run = createVerifierRun(),
const owners = [];
try {
for (const action of ["close", "replace"]) {
const session = new AtomicSession(async (path) => {
const owner = await KunaFactOwner.open(path);
const session = new AtomicSession(async (path, options) => {
const owner = await KunaFactOwner.open(path, options);
owners.push(owner);
return owner;
});
@@ -14,6 +14,11 @@ import {
} from "../../scripts/lib/verifier-run.mjs";
const [binary, output, callerSource, emitterSource] = process.argv.slice(2);
const evidenceDirectory = process.env.REA_ATOMIC_EVIDENCE_DIR;
assert.ok(
evidenceDirectory,
"Set REA_ATOMIC_EVIDENCE_DIR for producer comparison",
);
assert.equal(process.versions.node, (await readFile(".nvmrc", "utf8")).trim());
const sources = await Promise.all(
[callerSource, emitterSource].map((path) => readFile(path, "utf8")),
@@ -33,13 +38,11 @@ const valuesByID = new Map(graph.values.map((v) => [v.id, v]));
for (const op of graph.operations)
for (const input of op.inputs)
if (byValue.has(input.value_id))
byValue
.get(input.value_id)
.push({
operation: op.id,
...input,
definition: valuesByID.get(input.value_id).definition,
});
byValue.get(input.value_id).push({
operation: op.id,
...input,
definition: valuesByID.get(input.value_id).definition,
});
assert.equal(expectedValues.length, 250);
assert.equal(
[...byValue.values()].reduce((n, rows) => n + rows.length, 0),
@@ -218,10 +221,7 @@ try {
[emitter, emitterGolden],
]) {
const text = await readFile(
join(
process.env.REA_ATOMIC_EVIDENCE_DIR,
`${capture.source.evidence_id}.txt`,
),
join(evidenceDirectory, `${capture.source.evidence_id}.txt`),
"utf8",
);
assert.deepEqual(JSON.parse(text).functions[0], golden);