From 901de218f555f7be74edea0612d04de6a6b04272 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 20:47:57 +0000 Subject: [PATCH 1/6] test(ui-server): sample health, WebSocket and tool latency in the integrated reference cell (#3513) The integrated cell's repository gains three incompressible charts, its first turn ends with a warm read of the same source, and the parent samples /api/health, WebSocket ping/pong, the pool's sysfs peak allocation and the pool device's block I/O through every turn on both backends. The child times each reference tool call at the model boundary. The measurements land in reference-integration-latency.json and are held to INTEGRATED_TOLERANCES. The cell also makes its artifact tree readable on exit, so the receipt upload survives the app's owner-only data, and prints the app's warnings into the job log. Ported from the instrument branch onto main after #4072 and #4079. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/README.md | 19 +++ .../reference-integration-child.ts | 21 ++- .../reference-integration-steps.ts | 2 + .../reference-integration.native.ts | 157 +++++++++++++++--- 4 files changed, 173 insertions(+), 26 deletions(-) diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 843b76e29d..f04ef091ea 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -485,6 +485,25 @@ and earlier messages byte-identical. For Claude it holds the system-prompt option and the assembled MCP roster. It is not part of the default runtime cell. +The repository carries three incompressible 2 MiB charts beside its books, so +Git objects and checkout both hold real data +([#3513](https://github.com/schlessera/brain-kit/issues/3513)). The first turn +ends with a warm read of the same source. Throughout every turn, from its +message to its settled idle status, the parent samples `GET /api/health` +every 100 ms and a WebSocket `ping`/`pong` every 200 ms. It also samples the +pool's peak physical allocation every 100 ms, from the data, metadata and +system `disk_used` in `/sys/fs/btrfs//allocation` rather than through the +manager, so the sampling never queues behind the app's own pool calls. It +reads the pool device's block I/O per turn. The child times each reference tool call at the model +boundary: one in-process MCP call for Claude, and for Pi the span from the +scripted answer naming the step to the request carrying its result. +`reference-integration-latency.json` records the samples' p50, p95 and maximum, +the elapsed times and the kernel, btrfs-progs, Git, Bun and candidate +identities. Every health probe must answer and every ping must return its +pong. The warm read must add no source root and be faster than the cold one. +Latencies, elapsed times and the first turn's peak are held to +`INTEGRATED_TOLERANCES` in `reference-integration.native.ts`. + The container has no network, `no-new-privileges` and only `SYS_ADMIN`, `MKNOD`, `DAC_OVERRIDE`, `FOWNER`, `CHOWN`, `KILL`, `SETUID`, `SETGID` and `SETFCAP`. It deliberately omits diff --git a/scripts/native-proof/reference-integration-child.ts b/scripts/native-proof/reference-integration-child.ts index ffd32a51d8..7129660079 100644 --- a/scripts/native-proof/reference-integration-child.ts +++ b/scripts/native-proof/reference-integration-child.ts @@ -25,11 +25,16 @@ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js"); const { InMemoryTransport } = await import("@modelcontextprotocol/sdk/inMemory.js"); const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex"); -/** Every tool result and command output, keyed by step, feeds later steps and the parent's assertions. */ +/** + * Every tool result and command output, keyed by step, feeds later steps and the parent's assertions. + * `elapsedMs` (#3513) is the step's time at the model boundary: for Claude, one in-process MCP tool call; + * for Pi, from the scripted answer naming the step to the next provider request carrying its result. + * Claude's commands share one worker and carry none. + */ const state: IntegrationState = { repository, results: {} }; -function record(key: string, step: IntegrationStep, index: number, value: unknown) { +function record(key: string, step: IntegrationStep, index: number, value: unknown, elapsedMs: number | null = null) { state.results[stepKey(key, index)] = value; - event("integration_step", { backend: selectedBackend, turn: key, index, stepKind: step.kind, ...(step.kind === "tool" ? { tool: step.tool } : {}), value }); + event("integration_step", { backend: selectedBackend, turn: key, index, stepKind: step.kind, ...(step.kind === "tool" ? { tool: step.tool } : {}), elapsedMs, value }); } const turnKey = (text: string) => Object.keys(INTEGRATION_STEPS).find(key => text.includes(`Odysseus ${key}`)); @@ -38,6 +43,8 @@ const turnKey = (text: string) => Object.keys(INTEGRATION_STEPS).find(key => tex // the provider-facing history. const HOST_KEY = "odysseus-offline-host-key", MODEL = "claude-sonnet-4-6"; let piInference: { origin: string; close(): void } | undefined; +/** When the scripted Pi answer naming each step was sent. */ +const issued = new Map(); if (selectedBackend === "pi") { const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 16 * 1024 ** 2, async fetch(request) { if (request.method !== "POST" || new URL(request.url).pathname !== "/v1/messages") return new Response("unexpected offline inference route", { status: 404 }); @@ -56,7 +63,8 @@ if (selectedBackend === "pi") { if (state.results[stepKey(key, index)] !== undefined) continue; const content = results.get(`toolu_${key}_${index}`); const text = typeof content === "string" ? content : (content as { type: string; text?: string }[]).filter(part => part.type === "text").map(part => part.text).join(""); - record(key, steps[index]!, index, steps[index]!.kind === "tool" ? JSON.parse(text) : text); + const sent = issued.get(stepKey(key, index)); + record(key, steps[index]!, index, steps[index]!.kind === "tool" ? JSON.parse(text) : text, sent === undefined ? null : Math.round(performance.now() - sent)); } appendFileSync(join(dir, "pi-requests.jsonl"), JSON.stringify({ turn: key, step: index, raw }) + "\n"); const step = steps[index]; @@ -68,6 +76,7 @@ if (selectedBackend === "pi") { : [{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: (block as { text: string }).text } }], { type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 1 } }, { type: "message_stop" }].flat(); appendFileSync(join(dir, "pi-answers.jsonl"), JSON.stringify({ turn: key, step: index, answer: { role: "assistant", content: [block] } }) + "\n"); + if (step) issued.set(stepKey(key, index), performance.now()); return new Response(frames.map(frame => `event: ${(frame as { type: string }).type}\ndata: ${JSON.stringify(frame)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); // A fictional host-held key, sent only to this offline loopback fixture. @@ -112,9 +121,11 @@ const backend = selectedBackend === "pi" names: listed.tools.map((tool: { name: string }) => tool.name), allowedTools: params.options.allowedTools }); for (const [index, step] of INTEGRATION_STEPS[key]!.entries()) { if (step.kind === "bash") { commands.push(`printf '@@${index}@@\\n'; ${step.command(state)}`); continue; } + const began = performance.now(); const result = await client.callTool({ name: step.tool, arguments: step.input(state) }); + const elapsedMs = Math.round(performance.now() - began); const text = (result.content as { type: string; text: string }[]).map(part => part.text).join(""); - record(key, step, index, JSON.parse(text)); + record(key, step, index, JSON.parse(text), elapsedMs); } } finally { await client.close(); } const child = params.options.spawnClaudeCodeProcess({ command: "/bin/sh", args: ["-c", commands.join("\n") || "true"], diff --git a/scripts/native-proof/reference-integration-steps.ts b/scripts/native-proof/reference-integration-steps.ts index b0a0ffef20..0914fff492 100644 --- a/scripts/native-proof/reference-integration-steps.ts +++ b/scripts/native-proof/reference-integration-steps.ts @@ -42,6 +42,7 @@ const request: IntegrationStep = { kind: "tool", tool: "reference_worktree", inp /** Turn prompts carry `Odysseus `. */ export const INTEGRATION_STEPS: Record = { // Acquire and inspect shared source, then request two worktrees; the second is released unused. + // A last, warm read of the same source (#3513) reuses its root inside the refresh window or validates it in place. inspects: [ source(), { kind: "bash", command: state => `find ${sourcePath(state, "inspects", 0)}/odyssey -type f | wc -l; cat ${sourcePath(state, "inspects", 0)}/odyssey/book-23/line-49.md` }, @@ -49,6 +50,7 @@ export const INTEGRATION_STEPS: Record = { request, { kind: "bash", command: state => `find ${held(state, "inspects", 2)}/odyssey -type f | wc -l; cat ${held(state, "inspects", 2)}/odyssey/book-1/line-1.md` }, action("release", "inspects", 3), + source(), ], // Source has moved to a newer commit; the worktree has not. Edit it and renew it. corrects: [ diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index fd0a0aad7b..5ef854ab7e 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -6,9 +6,16 @@ * reference tool, a production worker inspects it, and a managed worktree is * requested, edited, renewed and released; its retained work reaches the * host-only hygiene review and the owner removes it there. + * + * Under that Git workload (#3513), the parent samples `/api/health` and the + * WebSocket `ping`/`pong` round trip throughout every turn, the pool's peak + * charge and reservations, and the pool device's block I/O per turn. The + * child times every reference tool call; cold and warm source reads are held + * to `INTEGRATED_TOLERANCES`. The report is `reference-integration-latency.json`. */ import { expect } from "bun:test"; -import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { appendFileSync, chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs"; +import { randomBytes } from "node:crypto"; import { join } from "node:path"; import { Database } from "bun:sqlite"; import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; @@ -19,6 +26,36 @@ import { journalDatabasePath } from "../../packages/ui-server/src/db/journal-dat import { referenceWorktreeJournalPath } from "../../packages/ui-server/src/brain/reference-worktree-journal.js"; import { bytes } from "../../tests/helpers/provider-history.js"; import { INTEGRATION_STEPS, INTEGRATION_TURNS, stepKey } from "./reference-integration-steps.js"; +import { poolIo, poolIoDelta, type PoolIo } from "./pool-io.js"; + +/** + * Latency and elapsed bounds of the integrated cell (#3513). PROVISIONAL until + * the first hosted baseline: each is replaced by its measured value with + * headroom, recorded beside it. Health and WebSocket samples cover every turn + * from its message to its settled idle status. + */ +export const INTEGRATED_TOLERANCES = Object.freeze({ + healthP95Ms: 500, healthMaxMs: 2_000, + wsP95Ms: 500, wsMaxMs: 2_000, + /** The first reference_source call of a backend: a cold acquisition of the 1,203-file repository with its charts. */ + coldSourceMs: 30_000, + /** The last call of the first turn: the same source again, reused or validated in place. */ + warmSourceMs: 5_000, + /** Peak pool charge above the turn's start during the first turn: one source and two worktree snapshots. */ + inspectsPeakBytes: 64 * 1024 ** 2, +}); +const IT = INTEGRATED_TOLERANCES; +/** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ +const CHARTS = 3, CHART_BYTES = 2 * 1024 ** 2; +const percentile = (values: number[], fraction: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1)]! : null; }; +const summary = (values: number[]) => ({ count: values.length, p50: percentile(values, 0.5), p95: percentile(values, 0.95), max: values.length ? Math.max(...values) : null }); +const latency: { schema: 1; basis: string; environment: Record; tolerances: typeof IT; backends: Record } = { + schema: 1, basis: "health: GET /api/health every 100 ms, sequential, 10 s timeout; ws: ping every 200 ms, pong receipt; tool elapsed: the child's model-boundary time per reference tool call; " + + "peak: the pool's data, metadata and system disk_used from /sys/fs/btrfs//allocation every 100 ms (the space-info term of chargedBytes, without simple-quota owner charge); " + + "io: pool loop device block counters (/proc/diskstats) per turn, after sync", + environment: {}, tolerances: IT, backends: {}, +}; +const saveLatency = () => writeFileSync(join(ARTIFACTS, "reference-integration-latency.json"), JSON.stringify(latency, null, 2)); const SOURCE = "/repo", MIB = 1024 ** 2, APP_UID = 1000, POOL = "/reference-pool"; const ARTIFACTS = process.env.BRAIN_REFERENCE_POOL_ARTIFACTS ?? "/proof"; @@ -59,7 +96,7 @@ command(["git", "init", "--quiet", "-b", "main", workspace]); writeFileSync(join(workspace, "log.md"), "Argo log: the crew rows past Scylla.\n"); const workspaceLog = () => existsSync(join(workspace, "log.md")) ? readFileSync(join(workspace, "log.md"), "utf8") : null; -// The offline fictional repository: 24 books of 50 lines, served from a local path. +// The offline fictional repository: 24 books of 50 lines and three incompressible charts, served from a local path. const srv = "/native-runtime/srv", work = "/native-runtime/ithaca-work", bare = join(srv, "ithaca.git"); /** A loose ref overrides the packed one: point the remote's main at a commit, or at one it cannot deliver. */ const advertise = (commit: string) => writeFileSync(join(bare, "refs/heads/main"), `${commit}\n`); @@ -72,6 +109,11 @@ for (let book = 0; book < 24; book++) { mkdirSync(join(work, "odyssey", `book-${book}`), { recursive: true }); for (let line = 0; line < 50; line++) writeFileSync(join(work, "odyssey", `book-${book}`, `line-${line}.md`), `Ithaca chart: book ${book}, line ${line}.\n`); } +mkdirSync(join(work, "charts")); +for (let chart = 0; chart < CHARTS; chart++) { + const fd = openSync(join(work, "charts", `aegean-${chart}.bin`), "w"); + try { writeSync(fd, randomBytes(CHART_BYTES)); } finally { closeSync(fd); } +} gitIn(work, "add", "."); gitIn(work, "commit", "-q", "-m", "Odysseus charts the way home"); const first = gitIn(work, "rev-parse", "HEAD").trim(); writeFileSync(join(work, "odyssey", "harbour.md"), "Phorcys harbour, charted after the landing.\n"); @@ -96,10 +138,19 @@ note("native-ready", { ready }); const qualified = await manager.poolStatus(); note("pool-qualified", { status: qualified }); expect(qualified.qualified, "INTEGRATED_POOL_QUALIFIED").toBe(true); +/** Physical allocation of the pool, read from sysfs without the manager; null if unreadable. */ +const POOL_FSID = fsid(POOL); +function poolDiskUsed(): number | null { + try { return ["data", "metadata", "system"].reduce((sum, kind) => sum + Number(readFileSync(`/sys/fs/btrfs/${POOL_FSID}/allocation/${kind}/disk_used`, "utf8").trim()), 0); } + catch { return null; } +} const records = async () => { const all: NativePoolRecord[] = []; for (let after: string | null = null; ;) { const page = await manager.listPoolRecovery(after); all.push(...page.records); if (!page.next) return all; after = page.next; } }; +latency.environment = { kernel: command(["uname", "-r"]).trim(), btrfsProgs: command(["btrfs", "--version"]).split("\n")[0]!.trim(), git: command(["git", "--version"]).trim(), + bun: Bun.version, candidate: process.env.BRAIN_PROOF_CANDIDATE ?? "unrecorded" }; +saveLatency(); const { serializeSigned } = await import(join(SOURCE, "node_modules/hono/dist/utils/cookie.js")); async function run(backend: "claude" | "pi") { @@ -134,9 +185,16 @@ async function run(backend: "claude" | "pi") { expect(granted.status, `INTEGRATED_${tag}_OWNER_GRANT_CREATED`).toBe(201); const frames: any[] = [], approvals: any[] = []; + // Liveness and health samples (#3513), each tagged with the turn it ran in. + const pings = new Map(), pongs: { turn: string; ms: number }[] = [], health: { turn: string; ms: number; status: number }[] = []; ws = new (WebSocket as any)(origin.replace("http", "ws") + "/ws", { headers: { cookie, origin } }) as WebSocket; ws.addEventListener("message", message => { const frame = { ...JSON.parse(String(message.data)), receiptAt: performance.now() }; + if (frame.type === "pong") { + const ping = pings.get(frame.probeId); + if (ping) { pongs.push({ turn: ping.turn, ms: frame.receiptAt - ping.sent }); pings.delete(frame.probeId); } + return; + } frames.push(frame); appendFileSync(join(ARTIFACTS, `frames-${backend}.jsonl`), JSON.stringify(frame) + "\n"); // A gated tool waits for the user's card: the user approves it once, per use. if (frame.type === "tool_approval_request") { approvals.push({ toolName: frame.toolName, kind: frame.kind ?? "tool" }); ws!.send(JSON.stringify({ type: "tool_approval", toolUseId: frame.toolUseId, turnId: frame.turnId })); } @@ -145,6 +203,32 @@ async function run(backend: "claude" | "pi") { ws.send(JSON.stringify({ type: "client_hello", protocolRev: 3, capabilities: { followUpQueue: true } })); let sessionId: string | undefined; const turns: Record = {}; + /** Health, liveness and pool sampling for one turn; the returned stop waits for its loops and its outstanding pongs. */ + function sampling(turn: string) { + let running = true, probes = 0; + const peak = { chargedBytes: 0 }, start: { chargedBytes: number | null } = { chargedBytes: null }; + Bun.spawnSync(["sync"]); + const before = poolIo(), began = performance.now(); + const loops = [ + (async () => { while (running) { const at = performance.now(); const status = await fetch(origin + "/api/health", { signal: AbortSignal.timeout(10_000) }).then(response => response.status, () => 0); health.push({ turn, ms: performance.now() - at, status }); await Bun.sleep(100); } })(), + (async () => { while (running) { const probeId = `odysseus-${backend}-${turn}-${probes++}`; pings.set(probeId, { turn, sent: performance.now() }); ws!.send(JSON.stringify({ type: "ping", probeId })); await Bun.sleep(200); } })(), + // Read-only sysfs, never the manager: a second client polling it mid-turn would queue behind, and perturb, the app's own pool calls. + (async () => { while (running) { const value = poolDiskUsed(); + if (value !== null) { start.chargedBytes ??= value; peak.chargedBytes = Math.max(peak.chargedBytes, value); } + await Bun.sleep(100); } })(), + ]; + return async () => { + const elapsedMs = Math.round(performance.now() - began); + running = false; await Promise.all(loops); + const outstanding = () => [...pings.values()].filter(ping => ping.turn === turn).length; + await until(() => outstanding() === 0, `${turn} pongs`, 5_000).catch(() => {}); + Bun.spawnSync(["sync"]); + return { elapsedMs, startChargedBytes: start.chargedBytes, peak, lostPongs: outstanding(), io: poolIoDelta(poolIo(), before) as PoolIo | null }; + }; + } + const sampled: Record>>> = {}; + const knownRoots = new Set((await records()).map(record => record.id)); + let inspectsSourceRoots = 0; for (const key of INTEGRATION_TURNS) { if (key === "corrects") { // Source moves on: the remote's main gains a commit, past the refresh cooldown. @@ -157,30 +241,56 @@ async function run(backend: "claude" | "pi") { advertise(UNDELIVERABLE); await Bun.sleep(2_500); } - const requestId = `odysseus-${backend}-${key}`, begin = performance.now(); - ws.send(JSON.stringify({ type: "chat_message", text: `Odysseus ${key} the Ithaca chart on 2026-07-12.`, requestId, sessionId })); - await until(() => frames.some(frame => frame.type === "session_info" && frame.requestId === requestId) || frames.some(frame => frame.type === "error" && frame.requestId === requestId), `${key} ack`); - const ack = frames.find(frame => frame.type === "session_info" && frame.requestId === requestId); - if (!ack) throw Error(`INTEGRATED_${tag}_${key.toUpperCase()}_ADMITTED: ${JSON.stringify(frames.filter(frame => frame.requestId === requestId))}`); - expect(ack.workerProfile?.actualProfile, `INTEGRATED_${tag}_GOVERNED_PROFILE`).toBe("governed"); - sessionId = ack.sessionId; - await until(() => frames.some(frame => (frame.type === "result" || frame.type === "error") && frame.receiptAt >= begin && (frame.sessionId ?? sessionId) === sessionId), `${key} result`, 120_000); - await until(() => frames.some(frame => frame.type === "turn_journal" && frame.turnId === ack.turnId && frame.journal?.state === "complete"), `${key} journal complete`, 30_000); - // The next turn starts only after this one settled: no follow-up queue in between. - await until(() => frames.some(frame => frame.type === "status" && frame.status === "idle" && frame.turnId === ack.turnId - && frame.receiptAt >= frames.find(other => other.type === "turn_journal" && other.turnId === ack.turnId && other.journal?.state === "complete")!.receiptAt), `${key} settled`, 30_000); - const terminal = frames.findLast(frame => (frame.type === "result" || frame.type === "error") && frame.receiptAt >= begin); - expect(frames.filter(frame => frame.type === "text_delta" && frame.turnId === ack.turnId && /stopped|froze|freeze/.test(frame.text)), `INTEGRATED_${tag}_${key.toUpperCase()}_NOT_STOPPED_BY_SCOPE`).toEqual([]); - const journal = frames.findLast(frame => frame.type === "turn_journal" && frame.turnId === ack.turnId)!.journal; - turns[key] = { turnId: ack.turnId, journal }; - note(`${backend}-turn`, { key, turnId: ack.turnId, outcome: terminal?.outcome ?? terminal?.type, journal }); - expect(terminal?.type === "result" && terminal.outcome !== "error", `INTEGRATED_${tag}_${key.toUpperCase()}_SUCCEEDED ${JSON.stringify(terminal)}`).toBe(true); + // Samples cover the turn itself, from its message to its settled idle status. + const stop = sampling(key); + try { + const requestId = `odysseus-${backend}-${key}`, begin = performance.now(); + ws.send(JSON.stringify({ type: "chat_message", text: `Odysseus ${key} the Ithaca chart on 2026-07-12.`, requestId, sessionId })); + await until(() => frames.some(frame => frame.type === "session_info" && frame.requestId === requestId) || frames.some(frame => frame.type === "error" && frame.requestId === requestId), `${key} ack`); + const ack = frames.find(frame => frame.type === "session_info" && frame.requestId === requestId); + if (!ack) throw Error(`INTEGRATED_${tag}_${key.toUpperCase()}_ADMITTED: ${JSON.stringify(frames.filter(frame => frame.requestId === requestId))}`); + expect(ack.workerProfile?.actualProfile, `INTEGRATED_${tag}_GOVERNED_PROFILE`).toBe("governed"); + sessionId = ack.sessionId; + await until(() => frames.some(frame => (frame.type === "result" || frame.type === "error") && frame.receiptAt >= begin && (frame.sessionId ?? sessionId) === sessionId), `${key} result`, 120_000); + await until(() => frames.some(frame => frame.type === "turn_journal" && frame.turnId === ack.turnId && frame.journal?.state === "complete"), `${key} journal complete`, 30_000); + // The next turn starts only after this one settled: no follow-up queue in between. + await until(() => frames.some(frame => frame.type === "status" && frame.status === "idle" && frame.turnId === ack.turnId + && frame.receiptAt >= frames.find(other => other.type === "turn_journal" && other.turnId === ack.turnId && other.journal?.state === "complete")!.receiptAt), `${key} settled`, 30_000); + const terminal = frames.findLast(frame => (frame.type === "result" || frame.type === "error") && frame.receiptAt >= begin); + expect(frames.filter(frame => frame.type === "text_delta" && frame.turnId === ack.turnId && /stopped|froze|freeze/.test(frame.text)), `INTEGRATED_${tag}_${key.toUpperCase()}_NOT_STOPPED_BY_SCOPE`).toEqual([]); + const journal = frames.findLast(frame => frame.type === "turn_journal" && frame.turnId === ack.turnId)!.journal; + turns[key] = { turnId: ack.turnId, journal }; + note(`${backend}-turn`, { key, turnId: ack.turnId, outcome: terminal?.outcome ?? terminal?.type, journal }); + expect(terminal?.type === "result" && terminal.outcome !== "error", `INTEGRATED_${tag}_${key.toUpperCase()}_SUCCEEDED ${JSON.stringify(terminal)}`).toBe(true); + } finally { sampled[key] = await stop(); } + if (key === "inspects") inspectsSourceRoots = (await records()).filter(record => record.purpose === "source" && !knownRoots.has(record.id)).length; } const steps = Object.fromEntries(events().filter(row => row.kind === "integration_step").map(row => [stepKey(row.turn, row.index), row.value])); note(`${backend}-steps`, { steps, approvals }); for (const key of INTEGRATION_TURNS) for (const index of INTEGRATION_STEPS[key]!.keys()) expect(steps[stepKey(key, index)], `INTEGRATED_${tag}_STEP_RECORDED ${stepKey(key, index)}`).toBeDefined(); + // Latency, elapsed time, peak allocation and I/O under the Git workload (#3513), recorded before they are judged. + const elapsed: Record = Object.fromEntries(events().filter(row => row.kind === "integration_step" && typeof row.elapsedMs === "number").map(row => [stepKey(row.turn, row.index), row.elapsedMs])); + const measured = { health: summary(health.map(sample => sample.ms)), healthFailures: health.filter(sample => sample.status !== 200).length, + ws: summary(pongs.map(sample => sample.ms)), lostPongs: pings.size, tools: elapsed, turns: sampled, inspectsSourceRoots, + perTurn: Object.fromEntries(INTEGRATION_TURNS.map(key => [key, { health: summary(health.filter(sample => sample.turn === key).map(sample => sample.ms)), ws: summary(pongs.filter(sample => sample.turn === key).map(sample => sample.ms)) }])) }; + latency.backends[backend] = measured; saveLatency(); + note(`${backend}-latency`, measured); + expect({ ok: steps["inspects#6"].ok, commit: steps["inspects#6"].source?.commit, freshness: steps["inspects#6"].source?.freshness }, `INTEGRATED_${tag}_WARM_SOURCE_READ`) + .toEqual({ ok: true, commit: first, freshness: "fresh" }); + expect(inspectsSourceRoots, `INTEGRATED_${tag}_WARM_READ_ADDS_NO_ROOT`).toBe(1); + expect({ cold: typeof elapsed["inspects#0"], warm: typeof elapsed["inspects#6"] }, `INTEGRATED_${tag}_SOURCE_ELAPSED_RECORDED`).toEqual({ cold: "number", warm: "number" }); + expect(elapsed["inspects#0"]!, `INTEGRATED_${tag}_COLD_SOURCE_ELAPSED`).toBeLessThanOrEqual(IT.coldSourceMs); + expect(elapsed["inspects#6"]!, `INTEGRATED_${tag}_WARM_SOURCE_ELAPSED`).toBeLessThanOrEqual(IT.warmSourceMs); + expect(elapsed["inspects#6"]! < elapsed["inspects#0"]!, `INTEGRATED_${tag}_WARM_FASTER_THAN_COLD`).toBe(true); + expect({ health: measured.health.count > 0, ws: measured.ws.count > 0, healthFailures: measured.healthFailures, lostPongs: measured.lostPongs }, + `INTEGRATED_${tag}_HEALTH_AND_LIVENESS_ANSWERED`).toEqual({ health: true, ws: true, healthFailures: 0, lostPongs: 0 }); + expect({ p95: measured.health.p95! <= IT.healthP95Ms, max: measured.health.max! <= IT.healthMaxMs }, `INTEGRATED_${tag}_HEALTH_LATENCY ${JSON.stringify(measured.health)}`).toEqual({ p95: true, max: true }); + expect({ p95: measured.ws.p95! <= IT.wsP95Ms, max: measured.ws.max! <= IT.wsMaxMs }, `INTEGRATED_${tag}_WS_LATENCY ${JSON.stringify(measured.ws)}`).toEqual({ p95: true, max: true }); + expect({ io: sampled.inspects!.io !== null, peak: sampled.inspects!.startChargedBytes !== null }, `INTEGRATED_${tag}_IO_AND_PEAK_SAMPLED`).toEqual({ io: true, peak: true }); + expect(sampled.inspects!.peak.chargedBytes - (sampled.inspects!.startChargedBytes ?? 0), `INTEGRATED_${tag}_INSPECTS_PEAK_BOUNDED`).toBeLessThanOrEqual(IT.inspectsPeakBytes); + // Acquisition and inspection: a private source at the first commit, read by a worker, charging no changed path. const acquired = steps["inspects#0"]; expect({ ok: acquired.ok, domain: acquired.source?.domain, commit: acquired.source?.commit, freshness: acquired.source?.freshness, worker: acquired.source?.path?.startsWith("/tmp/brain-reference/private/") }, @@ -279,7 +389,10 @@ async function run(backend: "claude" | "pi") { if (!exited) child.kill("SIGTERM"); const code = await child.exited; writeFileSync(join(ARTIFACTS, `app-${backend}.log`), `exit ${code}\n--- stdout\n${await output}\n--- stderr\n${await errors}`); - note(`${backend}-app-exit`, { code }); + // The app's own warnings, so a failed run's cause is in the job log even if no artifact survives. + const warnings = events().filter(row => row.kind === "fixture_logs").flatMap(row => row.records).filter((log: { severity: string }) => log.severity !== "INFO" && log.severity !== "DEBUG") + .map((log: { severity: string; body: unknown }) => `${log.severity}: ${String(log.body).slice(0, 400)}`).slice(-12); + note(`${backend}-app-exit`, { code, warnings }); } } @@ -308,4 +421,6 @@ try { expect(left, "INTEGRATED_NO_WORKTREE_LEFT").toEqual([]); } finally { await service.close(); + // The app wrote its data as UID 1000, some of it owner-only; the receipt upload reads the whole artifact tree. + Bun.spawnSync(["chmod", "-R", "a+rX", ARTIFACTS]); } From ea71984c3a0e1af5db59ba8cf76eccb8185b93be Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 20:49:19 +0000 Subject: [PATCH 2/6] chore(scripts): TEMPORARY hosted probe measuring the integrated reference cell's baseline (#3513) Reverted before the PR is ready. Co-Authored-By: Claude Opus 5.5 --- .../reference-integration.native.ts | 3 +- scripts/prove-reference-pool.ts | 38 ++++++++++++------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 5ef854ab7e..9fc8213b36 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -44,7 +44,8 @@ export const INTEGRATED_TOLERANCES = Object.freeze({ /** Peak pool charge above the turn's start during the first turn: one source and two worktree snapshots. */ inspectsPeakBytes: 64 * 1024 ** 2, }); -const IT = INTEGRATED_TOLERANCES; +// TEMPORARY (#3513) baseline probe: every bound open, so each backend records all its measurements. +const IT = Object.freeze(Object.fromEntries(Object.keys(INTEGRATED_TOLERANCES).map(key => [key, Number.MAX_SAFE_INTEGER]))) as typeof INTEGRATED_TOLERANCES; /** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ const CHARTS = 3, CHART_BYTES = 2 * 1024 ** 2; const percentile = (values: number[], fraction: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1)]! : null; }; diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 54c9374880..cabb27eda9 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,19 +37,29 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + // TEMPORARY (#3513) hosted feedback probe, reverted before the PR is ready: the hosted runtime_host cell runs this + // script without arguments, and the integrated cell has no hosted cell of its own. Run each backend's integrated + // cell twice, each in its own container, so one backend's failure does not hide the other's measurements. + const cells = selected.length ? [integrated] : [{ backends: ["claude"] }, { backends: ["pi"] }, { backends: ["claude"] }, { backends: ["pi"] }]; + const failures: string[] = []; + for (const integrated of cells) { + try { + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } + } + if (failures.length) throw Error(failures.join("\n")); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } } From 3e26c0070425612fca5228ef4b0bc7d18008defb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:28:15 +0000 Subject: [PATCH 3/6] Revert "chore(scripts): TEMPORARY hosted probe measuring the integrated reference cell's baseline (#3513)" This reverts commit ea71984c3a0e1af5db59ba8cf76eccb8185b93be. --- .../reference-integration.native.ts | 3 +- scripts/prove-reference-pool.ts | 38 +++++++------------ 2 files changed, 15 insertions(+), 26 deletions(-) diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 9fc8213b36..5ef854ab7e 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -44,8 +44,7 @@ export const INTEGRATED_TOLERANCES = Object.freeze({ /** Peak pool charge above the turn's start during the first turn: one source and two worktree snapshots. */ inspectsPeakBytes: 64 * 1024 ** 2, }); -// TEMPORARY (#3513) baseline probe: every bound open, so each backend records all its measurements. -const IT = Object.freeze(Object.fromEntries(Object.keys(INTEGRATED_TOLERANCES).map(key => [key, Number.MAX_SAFE_INTEGER]))) as typeof INTEGRATED_TOLERANCES; +const IT = INTEGRATED_TOLERANCES; /** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ const CHARTS = 3, CHART_BYTES = 2 * 1024 ** 2; const percentile = (values: number[], fraction: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1)]! : null; }; diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index cabb27eda9..54c9374880 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,29 +37,19 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - // TEMPORARY (#3513) hosted feedback probe, reverted before the PR is ready: the hosted runtime_host cell runs this - // script without arguments, and the integrated cell has no hosted cell of its own. Run each backend's integrated - // cell twice, each in its own container, so one backend's failure does not hide the other's measurements. - const cells = selected.length ? [integrated] : [{ backends: ["claude"] }, { backends: ["pi"] }, { backends: ["claude"] }, { backends: ["pi"] }]; - const failures: string[] = []; - for (const integrated of cells) { - try { - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); - } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } - } - if (failures.length) throw Error(failures.join("\n")); + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } } From 98b530d75c5aac9f916747b07b57ad868a393d26 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:28:39 +0000 Subject: [PATCH 4/6] test(ui-server): hold the integrated reference cell to its measured hosted baseline (#3513) INTEGRATED_TOLERANCES now comes from the hosted runtime_host baseline: two integrated cells per backend at ea71984c3 (draft heavy feedback run 43969834503). Each bound records the worst measured value beside it. The warm source bound is per backend, because Pi's model-boundary time includes its agent loop's round trip through the offline provider. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/README.md | 6 +++- .../reference-integration.native.ts | 33 +++++++++++-------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index f04ef091ea..b6fe7bc88f 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -502,7 +502,11 @@ the elapsed times and the kernel, btrfs-progs, Git, Bun and candidate identities. Every health probe must answer and every ping must return its pong. The warm read must add no source root and be faster than the cold one. Latencies, elapsed times and the first turn's peak are held to -`INTEGRATED_TOLERANCES` in `reference-integration.native.ts`. +`INTEGRATED_TOLERANCES` in `reference-integration.native.ts`. Those bounds +come from a hosted `runtime_host` baseline of two cells per backend, and the +worst measured value is recorded beside each bound. Pi's warm-read bound is +wider than Claude's. Pi's time includes its agent loop's round trip through +the offline provider, while Claude's is the MCP call alone. The container has no network, `no-new-privileges` and only `SYS_ADMIN`, `MKNOD`, `DAC_OVERRIDE`, `FOWNER`, `CHOWN`, `KILL`, `SETUID`, `SETGID` and diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 5ef854ab7e..9e8742de6f 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -29,20 +29,27 @@ import { INTEGRATION_STEPS, INTEGRATION_TURNS, stepKey } from "./reference-integ import { poolIo, poolIoDelta, type PoolIo } from "./pool-io.js"; /** - * Latency and elapsed bounds of the integrated cell (#3513). PROVISIONAL until - * the first hosted baseline: each is replaced by its measured value with - * headroom, recorded beside it. Health and WebSocket samples cover every turn - * from its message to its settled idle status. + * Latency, elapsed and allocation bounds of the integrated cell (#3513), set from the hosted + * `runtime_host` baseline: draft heavy feedback run 43969834503 at `ea71984c3`, two cells per + * backend (kernel 7.0.0-1017-azure, btrfs-progs v6.6.3, Git 2.43.0, Bun 1.4.2). Each bound + * names the worst of the four measurements beside it. Health and WebSocket samples cover every + * turn from its message to its settled idle status. */ export const INTEGRATED_TOLERANCES = Object.freeze({ - healthP95Ms: 500, healthMaxMs: 2_000, - wsP95Ms: 500, wsMaxMs: 2_000, - /** The first reference_source call of a backend: a cold acquisition of the 1,203-file repository with its charts. */ - coldSourceMs: 30_000, - /** The last call of the first turn: the same source again, reused or validated in place. */ - warmSourceMs: 5_000, - /** Peak pool charge above the turn's start during the first turn: one source and two worktree snapshots. */ - inspectsPeakBytes: 64 * 1024 ** 2, + /** Measured p95 2.3–6.1 ms, max 9.7–86.4 ms. */ + healthP95Ms: 50, healthMaxMs: 500, + /** Measured p95 2.9–6.3 ms, max 12.2–14.7 ms. */ + wsP95Ms: 50, wsMaxMs: 250, + /** The first reference_source call of a backend: a cold acquisition of the 1,203-file repository with its charts. Measured 1,183–1,264 ms. */ + coldSourceMs: 4_000, + /** + * The last call of the first turn: the same source again, reused or validated in place. Claude's + * time is the MCP call alone (measured 2 ms); Pi's spans its agent loop's round trip through the + * offline provider, about 0.7 s on any step (measured 735–744 ms). + */ + warmSourceMs: Object.freeze({ claude: 250, pi: 2_000 }), + /** Peak pool allocation above the turn's start during the first turn: one source and two worktree snapshots. Measured 14.7 MiB. */ + inspectsPeakBytes: 20 * 1024 ** 2, }); const IT = INTEGRATED_TOLERANCES; /** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ @@ -282,7 +289,7 @@ async function run(backend: "claude" | "pi") { expect(inspectsSourceRoots, `INTEGRATED_${tag}_WARM_READ_ADDS_NO_ROOT`).toBe(1); expect({ cold: typeof elapsed["inspects#0"], warm: typeof elapsed["inspects#6"] }, `INTEGRATED_${tag}_SOURCE_ELAPSED_RECORDED`).toEqual({ cold: "number", warm: "number" }); expect(elapsed["inspects#0"]!, `INTEGRATED_${tag}_COLD_SOURCE_ELAPSED`).toBeLessThanOrEqual(IT.coldSourceMs); - expect(elapsed["inspects#6"]!, `INTEGRATED_${tag}_WARM_SOURCE_ELAPSED`).toBeLessThanOrEqual(IT.warmSourceMs); + expect(elapsed["inspects#6"]!, `INTEGRATED_${tag}_WARM_SOURCE_ELAPSED`).toBeLessThanOrEqual(IT.warmSourceMs[backend]); expect(elapsed["inspects#6"]! < elapsed["inspects#0"]!, `INTEGRATED_${tag}_WARM_FASTER_THAN_COLD`).toBe(true); expect({ health: measured.health.count > 0, ws: measured.ws.count > 0, healthFailures: measured.healthFailures, lostPongs: measured.lostPongs }, `INTEGRATED_${tag}_HEALTH_AND_LIVENESS_ANSWERED`).toEqual({ health: true, ws: true, healthFailures: 0, lostPongs: 0 }); From 639585b873614c7f54e576c727214223e274713f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:30:21 +0000 Subject: [PATCH 5/6] chore(scripts): TEMPORARY hosted mutation round for the integrated cell's tolerances (#3513) Each backend's integrated cell runs once with the measured bounds, which must pass, and once with one bound set below its measured value, which must fail first on that bound's named assertion. Reverted before the PR is ready. Co-Authored-By: Claude Opus 5.5 --- .../reference-integration.native.ts | 3 +- scripts/prove-reference-pool.ts | 61 ++++++++++++++----- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 9e8742de6f..c9a1803f9c 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -51,7 +51,8 @@ export const INTEGRATED_TOLERANCES = Object.freeze({ /** Peak pool allocation above the turn's start during the first turn: one source and two worktree snapshots. Measured 14.7 MiB. */ inspectsPeakBytes: 20 * 1024 ** 2, }); -const IT = INTEGRATED_TOLERANCES; +// TEMPORARY (#3513) mutation round: the probe may replace named bounds with values below their measurements. +const IT = Object.freeze({ ...INTEGRATED_TOLERANCES, ...JSON.parse(process.env.BRAIN_INTEGRATED_TOLERANCE_BREACH ?? "{}") }) as typeof INTEGRATED_TOLERANCES; /** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ const CHARTS = 3, CHART_BYTES = 2 * 1024 ** 2; const percentile = (values: number[], fraction: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1)]! : null; }; diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 54c9374880..ea6abfcd58 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -4,8 +4,10 @@ import { basename, dirname, join, resolve } from "node:path"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; /** `integrated` runs the app-level proof of #2751 on the same owned volumes, for the named backends. */ -export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string): string[] { +export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string, breach?: string): string[] { return ["docker", "run", "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", + // TEMPORARY (#3513) mutation round: a breach override for the integrated cell's tolerances. + ...(breach ? [`--env=BRAIN_INTEGRATED_TOLERANCE_BREACH=${breach}`] : []), // The efficiency report (#3513) names the exact candidate it measured. ...(candidate ? [`--env=BRAIN_PROOF_CANDIDATE=${candidate}`] : []), ...(integrated ? [`--env=BRAIN_REFERENCE_INTEGRATION_BACKENDS=${integrated.backends.join(",")}`] : []), @@ -37,19 +39,48 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + // TEMPORARY (#3513) hosted mutation round, reverted before the PR is ready: the hosted runtime_host cell runs this + // script without arguments, and the integrated cell has no hosted cell of its own. Each backend's integrated cell runs + // once with its measured INTEGRATED_TOLERANCES, which must pass, and once with one bound set below its measured value, + // which must fail on that bound's named assertion and on nothing earlier. + type Cell = { integrated?: { backends: string[] }; breach?: { bounds: Record; fails: string } }; + const cells: Cell[] = selected.length ? [{ integrated }] : [ + { integrated: { backends: ["claude"] } }, { integrated: { backends: ["pi"] } }, + { integrated: { backends: ["claude"] }, breach: { bounds: { coldSourceMs: 100 }, fails: "INTEGRATED_CLAUDE_COLD_SOURCE_ELAPSED" } }, + { integrated: { backends: ["pi"] }, breach: { bounds: { wsP95Ms: 0.1 }, fails: "INTEGRATED_PI_WS_LATENCY" } }, + ]; + const failures: string[] = []; + for (const { integrated, breach } of cells) { + try { + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? (breach ? "run-breach-" : "run-integrated-") : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate, breach ? JSON.stringify(breach.bounds) : undefined), + { stdin: "ignore", stdout: breach ? "pipe" : "inherit", stderr: breach ? "pipe" : "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const captured = breach ? await Promise.all([new Response(child.stdout as ReadableStream).text(), new Response(child.stderr as ReadableStream).text()]) : []; + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (breach) { + const text = captured.join("\n"); + process.stdout.write(text); + // The fixture prints the cell's output tail as JSON, so its newlines may be escaped. + const first = /error: (INTEGRATED_[A-Z_]+)/.exec(text)?.[1]; + const receipt = { breach: breach.bounds, expected: breach.fails, exit: code, firstFailure: first ?? null }; + console.log(`MUTATION RECEIPT ${JSON.stringify(receipt)}`); + if (code === 0 || first !== breach.fails) throw Error(`Tolerance breach ${JSON.stringify(breach.bounds)} did not fail ${breach.fails} first: ${JSON.stringify(receipt)}`); + console.log(`Tolerance breach failed ${breach.fails} as intended.`); + continue; + } + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } + } + if (failures.length) throw Error(failures.join("\n")); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } } From 3587bbbffb2ad08a8ac6cb88ef01cd1e15ec67cb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:16:36 +0000 Subject: [PATCH 6/6] Revert "chore(scripts): TEMPORARY hosted mutation round for the integrated cell's tolerances (#3513)" This reverts commit 639585b873614c7f54e576c727214223e274713f. --- .../reference-integration.native.ts | 3 +- scripts/prove-reference-pool.ts | 61 +++++-------------- 2 files changed, 16 insertions(+), 48 deletions(-) diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index c9a1803f9c..9e8742de6f 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -51,8 +51,7 @@ export const INTEGRATED_TOLERANCES = Object.freeze({ /** Peak pool allocation above the turn's start during the first turn: one source and two worktree snapshots. Measured 14.7 MiB. */ inspectsPeakBytes: 20 * 1024 ** 2, }); -// TEMPORARY (#3513) mutation round: the probe may replace named bounds with values below their measurements. -const IT = Object.freeze({ ...INTEGRATED_TOLERANCES, ...JSON.parse(process.env.BRAIN_INTEGRATED_TOLERANCE_BREACH ?? "{}") }) as typeof INTEGRATED_TOLERANCES; +const IT = INTEGRATED_TOLERANCES; /** Three incompressible 2 MiB charts beside the books: Git objects and checkout both hold them. */ const CHARTS = 3, CHART_BYTES = 2 * 1024 ** 2; const percentile = (values: number[], fraction: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1)]! : null; }; diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index ea6abfcd58..54c9374880 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -4,10 +4,8 @@ import { basename, dirname, join, resolve } from "node:path"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; /** `integrated` runs the app-level proof of #2751 on the same owned volumes, for the named backends. */ -export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string, breach?: string): string[] { +export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string): string[] { return ["docker", "run", "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", - // TEMPORARY (#3513) mutation round: a breach override for the integrated cell's tolerances. - ...(breach ? [`--env=BRAIN_INTEGRATED_TOLERANCE_BREACH=${breach}`] : []), // The efficiency report (#3513) names the exact candidate it measured. ...(candidate ? [`--env=BRAIN_PROOF_CANDIDATE=${candidate}`] : []), ...(integrated ? [`--env=BRAIN_REFERENCE_INTEGRATION_BACKENDS=${integrated.backends.join(",")}`] : []), @@ -39,48 +37,19 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - // TEMPORARY (#3513) hosted mutation round, reverted before the PR is ready: the hosted runtime_host cell runs this - // script without arguments, and the integrated cell has no hosted cell of its own. Each backend's integrated cell runs - // once with its measured INTEGRATED_TOLERANCES, which must pass, and once with one bound set below its measured value, - // which must fail on that bound's named assertion and on nothing earlier. - type Cell = { integrated?: { backends: string[] }; breach?: { bounds: Record; fails: string } }; - const cells: Cell[] = selected.length ? [{ integrated }] : [ - { integrated: { backends: ["claude"] } }, { integrated: { backends: ["pi"] } }, - { integrated: { backends: ["claude"] }, breach: { bounds: { coldSourceMs: 100 }, fails: "INTEGRATED_CLAUDE_COLD_SOURCE_ELAPSED" } }, - { integrated: { backends: ["pi"] }, breach: { bounds: { wsP95Ms: 0.1 }, fails: "INTEGRATED_PI_WS_LATENCY" } }, - ]; - const failures: string[] = []; - for (const { integrated, breach } of cells) { - try { - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? (breach ? "run-breach-" : "run-integrated-") : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate, breach ? JSON.stringify(breach.bounds) : undefined), - { stdin: "ignore", stdout: breach ? "pipe" : "inherit", stderr: breach ? "pipe" : "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const captured = breach ? await Promise.all([new Response(child.stdout as ReadableStream).text(), new Response(child.stderr as ReadableStream).text()]) : []; - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (breach) { - const text = captured.join("\n"); - process.stdout.write(text); - // The fixture prints the cell's output tail as JSON, so its newlines may be escaped. - const first = /error: (INTEGRATED_[A-Z_]+)/.exec(text)?.[1]; - const receipt = { breach: breach.bounds, expected: breach.fails, exit: code, firstFailure: first ?? null }; - console.log(`MUTATION RECEIPT ${JSON.stringify(receipt)}`); - if (code === 0 || first !== breach.fails) throw Error(`Tolerance breach ${JSON.stringify(breach.bounds)} did not fail ${breach.fails} first: ${JSON.stringify(receipt)}`); - console.log(`Tolerance breach failed ${breach.fails} as intended.`); - continue; - } - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); - } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } - } - if (failures.length) throw Error(failures.join("\n")); + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } }