From 06ad98cf7c8f8f4cd13ee2c6c1ae273e5def6807 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 22:13:50 +0000 Subject: [PATCH 1/7] test(ui-server): qualify EDQUOT, cancellation, crash recovery and backend latency under the Git workload (#3513) Case 19 of the reference pool proof now also records per-step pool-device and process I/O and peak allocation around cold, warm and refresh reads, and exercises write-time EDQUOT in a managed worktree and inside a refresh fetch, cancellation mid-fetch, and a SIGKILLed app instance recovered by the next instance's startup recovery, all on the generated repository. The integrated cell's repository gains incompressible charts, its first turn ends with a warm source read, and the parent samples health, WebSocket ping/pong, pool peak and device I/O through every turn on both backends. The child times each reference tool call at the model boundary. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/README.md | 38 +++- scripts/native-proof/pool-io.ts | 39 ++++ .../reference-efficiency-crash-child.ts | 22 +++ scripts/native-proof/reference-efficiency.ts | 178 ++++++++++++++++-- .../reference-integration-child.ts | 21 ++- .../reference-integration-steps.ts | 2 + .../reference-integration.native.ts | 142 ++++++++++++-- scripts/native-proof/reference-pool.native.ts | 5 +- tests/native-pool-io.test.ts | 37 ++++ 9 files changed, 436 insertions(+), 48 deletions(-) create mode 100644 scripts/native-proof/pool-io.ts create mode 100644 scripts/native-proof/reference-efficiency-crash-child.ts create mode 100644 tests/native-pool-io.test.ts diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 09cff0defc..c8405e3820 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -383,7 +383,12 @@ are sealed, so their comparisons use the census's exclusive extents. `pendingBytes` and `availableBytes` are the admission reservations. A `btrfs filesystem du` census reports total, exclusive and shared extents per path. Git's `count-objects` is recorded as logical object size only; no -logical size or sum of `st_blocks` is reported as unique usage. The run checks: +logical size or sum of `st_blocks` is reported as unique usage. Every row also +carries `io`: the pool loop device's block reads and writes from +`/proc/diskstats`, and this process's own I/O with its reaped transport +workers from `/proc/self/io`, both since the previous row and after a `sync`. +Cold, warm and refresh rows add `peak`, the highest combined charge and +reservation sampled every 50 ms while the step ran. The run checks: - **Reuse.** A repeat read inside the refresh window, and an unchanged refresh after it, reuse the one source root and allocate at most 256 KiB. @@ -403,6 +408,20 @@ logical size or sum of `st_blocks` is reported as unique usage. The run checks: - **Sharing loss.** `git repack -a -d -f` in a worktree, or a linked `git worktree add` inside one, allocates its objects or checkout as new extents charged to that worktree alone. +- **Write-time EDQUOT.** A worktree writing past its allowance is refused by + `write()` with `EDQUOT`, charging neither its sibling nor its source. A + commit larger than one operation's allowance is refused inside the refresh + fetch: the previous root keeps serving, marked stale with Git's quota error, + and the staging root is released and reclaimed. +- **Cancellation.** A refresh whose only requester leaves once its staging + root is writable rejects as `cancelled`, publishes nothing, and its staging + root is released and reclaimed. +- **Crash and restart.** A second app instance on the same database + (`reference-efficiency-crash-child.ts`) is killed with `SIGKILL` while its + staging root is writable. The manager keeps that root writable and charged. + The next instance's startup `recover()` releases it, retains nothing and + keeps the previous source, and the space is observed reclaimed. The changed + refresh then runs on that restarted instance. Repository features, as the transport handles them: @@ -448,6 +467,23 @@ 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 charge and reservations every 100 ms, and 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/pool-io.ts b/scripts/native-proof/pool-io.ts new file mode 100644 index 0000000000..bf989c72dc --- /dev/null +++ b/scripts/native-proof/pool-io.ts @@ -0,0 +1,39 @@ +/** + * Block I/O counters for the reference pool proofs (#3513): the pool loop + * device's cumulative counters from /proc/diskstats (512-byte sectors), and + * this process's own from /proc/self/io, which include its reaped children. + * Callers sync before reading, so delayed Btrfs writeback is counted in the + * step that caused it. Null when a counter cannot be read. + */ +import { readFileSync, statSync } from "node:fs"; + +/** The fixture's pool loop device (reference-pool-fixture.py). */ +export const POOL_DEVICE = "/dev/brain-pool-loop"; +export interface PoolIo { device: { readOps: number; readBytes: number; writeOps: number; writeBytes: number }; process: { readBytes: number; writeBytes: number; rchar: number; wchar: number } } + +export function poolIo(device = POOL_DEVICE): PoolIo | null { + try { return parsePoolIo(statSync(device).rdev, readFileSync("/proc/diskstats", "utf8"), readFileSync("/proc/self/io", "utf8")); } + catch { return null; } +} + +/** Linux `dev_t` decoding, so a loop minor above 255 (the fixture's 2429) matches its diskstats row. */ +export function deviceNumbers(rdev: number): { major: number; minor: number } { + return { major: (rdev >> 8) & 0xfff, minor: (rdev & 0xff) | ((rdev >> 12) & 0xfff00) }; +} + +export function parsePoolIo(rdev: number, diskstats: string, selfIo: string): PoolIo | null { + const { major, minor } = deviceNumbers(rdev); + const fields = diskstats.split("\n").map(line => line.trim().split(/\s+/)).find(row => Number(row[0]) === major && Number(row[1]) === minor); + if (!fields || fields.length < 10) return null; + const own = Object.fromEntries(selfIo.trim().split("\n").map(line => line.split(": ")).map(([key, value]) => [key, Number(value)])); + const process = { readBytes: own.read_bytes, writeBytes: own.write_bytes, rchar: own.rchar, wchar: own.wchar }; + if (Object.values(process).some(value => !Number.isFinite(value))) return null; + return { device: { readOps: Number(fields[3]), readBytes: Number(fields[5]) * 512, writeOps: Number(fields[7]), writeBytes: Number(fields[9]) * 512 }, + process: process as PoolIo["process"] }; +} + +export function poolIoDelta(now: PoolIo | null, then: PoolIo | null): PoolIo | null { + if (!now || !then) return null; + const minus = (a: Record, b: Record) => Object.fromEntries(Object.keys(a).map(key => [key, a[key as K] - b[key as K]])) as Record; + return { device: minus(now.device, then.device), process: minus(now.process, then.process) }; +} diff --git a/scripts/native-proof/reference-efficiency-crash-child.ts b/scripts/native-proof/reference-efficiency-crash-child.ts new file mode 100644 index 0000000000..14229a4ddd --- /dev/null +++ b/scripts/native-proof/reference-efficiency-crash-child.ts @@ -0,0 +1,22 @@ +/** + * The crashed app instance of case 19 (#3513). It opens the case's database + * and the served pool, requests the pending changed refresh and is killed by + * the proof with SIGKILL once its staging root is writable, so no cleanup of + * its own runs. Arguments: database, manager socket, repository, principal and + * the case's fixed clock. + */ +import { createUiDb } from "../../packages/ui-server/src/db/client.js"; +import { createReferenceSources } from "../../packages/ui-server/src/brain/reference-source.js"; +import { createReferenceTransport } from "../../packages/ui-server/src/brain/reference-transport.js"; +import { referenceWorktreeDependents } from "../../packages/ui-server/src/brain/reference-worktrees.js"; +import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; + +const [dbPath, socketPath, repository, principalId, clock] = process.argv.slice(2) as [string, string, string, string, string]; +const db = createUiDb(dbPath); +const sources = createReferenceSources({ db, pool: createNativeBrainManagerClient({ socketPath, timeoutMs: 20_000 }), + transport: createReferenceTransport({ brainPath: "/brain-fixture/brain" }), brain: "ithaca", credentials: {}, now: () => Number(clock), + dependents: rootId => referenceWorktreeDependents(db, rootId) }); +console.log("requesting"); +const lease = await sources.request({ principalId, repository, revision: "main" }); +// Reached only if the proof was too late to kill this instance; the proof then fails on its own assertion. +console.log(`acquired ${lease.rootId}`); diff --git a/scripts/native-proof/reference-efficiency.ts b/scripts/native-proof/reference-efficiency.ts index 17eb5c94d5..790a1ee899 100644 --- a/scripts/native-proof/reference-efficiency.ts +++ b/scripts/native-proof/reference-efficiency.ts @@ -7,13 +7,19 @@ * refreshed unchanged and changed, refreshed under concurrent readers, and * checked out into two managed worktrees. A reflinked and a full copy of the * same checkout, and a copy onto another filesystem, compare the copy paths. + * Under the same workload, a worktree and a refresh each write past their + * allowance and are refused at write time with EDQUOT, a refresh is cancelled + * mid-fetch, and an app instance is killed mid-acquisition and recovered by the + * next instance's startup recovery. * * Every step records the pool's own accounting (`chargedBytes`: unique * physical allocation across data, metadata and system, profile replication * included; `ownerBytes`: simple-quota first-owner charge per root) and an * independent extent census (`btrfs filesystem du`). Neither logical size nor - * a sum of st_blocks is reported as unique usage. The report is - * `reference-efficiency.json` next to the other receipts. + * a sum of st_blocks is reported as unique usage. Every step also records the + * pool device's block I/O and this process's I/O (reaped children included) + * since the previous step. The report is `reference-efficiency.json` next to + * the other receipts. */ import { expect } from "bun:test"; import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, writeSync } from "node:fs"; @@ -23,6 +29,7 @@ import type { NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/s import type { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { createFixtureWorktrees } from "./reference-worktree-allocation.js"; import { settledWorktreeRelease } from "./reference-worktree-release.js"; +import { poolIo, poolIoDelta, type PoolIo } from "./pool-io.js"; const MIB = 1024 ** 2; /** Generated workload: 40 books of 50 short lines, three 2 MiB charts, then one changed commit. */ @@ -47,12 +54,17 @@ export const EFFICIENCY_TOLERANCES = Object.freeze({ reflinkBytes: 256 * 1024, /** Cold acquisition elapsed: measured 1,265 ms. Concurrent refresh: measured 4,688 ms. */ coldMs: 15_000, concurrentMs: 30_000, + /** A refused, cancelled or crashed acquisition, after observed reclamation, pool-wide: the case's final residual bound. */ + reclaimedBytes: 4 * MIB, }); + const T = EFFICIENCY_TOLERANCES; type Client = ReturnType; export interface EfficiencyContext { client: Client; + /** The served manager's socket, for the crashed app instance's own client. */ + socketPath: string; artifacts: string; note: (kind: string, facts: Record) => void; command: (argv: string[], permitFailure?: boolean) => string; @@ -63,11 +75,11 @@ interface Census { path: string; total: number; exclusive: number; shared: numbe interface Step { step: string; ms: number | null; chargedBytes: number; ownerBytes: number; globalBytes: number; pendingBytes: number; availableBytes: number; data: number; metadata: number; roots: { id: string; purpose: string; state: string; from: string | null; ownerBytes: number | null }[]; - census: Census[]; [extra: string]: unknown; + census: Census[]; io: PoolIo | null; [extra: string]: unknown; } export async function runReferenceEfficiency(context: EfficiencyContext): Promise { - const { client, artifacts, note, command, sync } = context; + const { client, socketPath, artifacts, note, command, sync } = context; const { createUiDb } = await import("../../packages/ui-server/src/db/client.js"); const { createPrincipal } = await import("../../packages/ui-server/src/db/principals.js"); const { createReferenceGrant } = await import("../../packages/ui-server/src/db/reference-grants.js"); @@ -98,7 +110,7 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis git(work, "add", ".gitmodules"); git(work, "commit", "-q", "-m", "Odysseus charts the Aegean"); command(["git", "clone", "-q", "--bare", work, join(srv, "aegean.git")]); - const push = () => git(work, "push", "-q", join(srv, "aegean.git"), "main"); + const push = (...flags: string[]) => git(work, "push", "-q", ...flags, join(srv, "aegean.git"), "main"); const db = createUiDb(join(state, "ui.db")); let clock = Date.now(); @@ -112,13 +124,15 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis return { path: name.join(" "), total: Number(total), exclusive: Number(exclusive), shared: Number(shared) }; }); const report: { schema: 1; basis: string; workload: typeof W; environment: Record; steps: Step[]; findings: Record } = { - schema: 1, basis: "chargedBytes: pool accounting basis (btrfs-space-info-disk-used+simple-quota-owner); ownerBytes: simple-quota first-owner charge per root; census: btrfs filesystem du extent sharing", + schema: 1, basis: "chargedBytes: pool accounting basis (btrfs-space-info-disk-used+simple-quota-owner); ownerBytes: simple-quota first-owner charge per root; census: btrfs filesystem du extent sharing; " + + "io: since the previous step, after sync: pool loop device block counters (/proc/diskstats) and this process with its reaped children (/proc/self/io); peak: pool status sampled every 50 ms", workload: W, 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", }, steps: [], findings: {}, }; const save = () => writeFileSync(join(artifacts, "reference-efficiency.json"), JSON.stringify(report, null, 2)); + let counters = poolIo(); async function measure(step: string, ms: number | null, paths: string[] = [], extra: Record = {}): Promise { sync(); const status: NativePoolStatus = await client.poolStatus(); @@ -126,32 +140,71 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis const a = status.accounting!; const roots = (await records()).filter(record => ["reserved", "writable", "sealed"].includes(record.state)) .map(record => ({ id: record.id, purpose: record.purpose, state: record.state, from: record.from, ownerBytes: record.ownerBytes })); + const read = poolIo(), io = poolIoDelta(read, counters); + counters = read; const row: Step = { step, ms, chargedBytes: a.chargedBytes, ownerBytes: a.ownerBytes, globalBytes: a.globalBytes, pendingBytes: a.pendingBytes, - availableBytes: a.availableBytes, data: a.spaces.data.bytesUsed, metadata: a.spaces.metadata.bytesUsed, roots, census: census(paths), ...extra }; + availableBytes: a.availableBytes, data: a.spaces.data.bytesUsed, metadata: a.spaces.metadata.bytesUsed, roots, census: census(paths), io, ...extra }; + expect(io, `REFERENCE_EFFICIENCY_IO_COUNTED_${step}`).not.toBeNull(); report.steps.push(row); save(); note("efficiency", { step, ms, chargedBytes: row.chargedBytes, pendingBytes: row.pendingBytes, roots: roots.length }); return row; } const timed = async (work: () => Promise): Promise<[T, number]> => { const began = performance.now(); const value = await work(); return [value, Math.round(performance.now() - began)]; }; + /** Timed work with the pool's peak combined charge and reservations sampled every 50 ms while it runs. */ + const sampled = async (work: () => Promise): Promise<[T, number, { chargedBytes: number; pendingBytes: number }]> => { + const peak = { chargedBytes: 0, pendingBytes: 0 }; + let running = true; + const sampling = (async () => { + while (running) { + const value = (await client.poolStatus().catch(() => null))?.accounting; + if (value) { peak.chargedBytes = Math.max(peak.chargedBytes, value.chargedBytes); peak.pendingBytes = Math.max(peak.pendingBytes, value.pendingBytes); } + await Bun.sleep(50); + } + })(); + try { const [value, ms] = await timed(work); return [value, ms, peak]; } finally { running = false; await sampling; } + }; const owner = (step: Step, id: string) => step.roots.find(root => root.id === id)?.ownerBytes ?? null; // Writable roots carry no owner charge until sealed, so worktrees compare on the census's exclusive extents. const exclusive = (step: Step, path: string) => { const entry = step.census.find(value => value.path === path); expect(entry, `REFERENCE_EFFICIENCY_CENSUS_${step.step}`).toBeDefined(); return entry!.exclusive; }; const pathOf = async (id: string) => (await records()).find(record => record.id === id)!.path!; const sourceRoots = async () => (await records()).filter(record => record.purpose === "source" && record.state === "sealed").map(record => record.id); + /** Source roots still reserved, writable or deleting: an acquisition whose staging was not released. */ + const unsettled = async () => (await records()).filter(record => record.purpose === "source" && ["reserved", "writable", "deleting"].includes(record.state)); + async function settledStaging(label: string) { + for (let attempt = 0; attempt < 400 && (await unsettled()).length; attempt++) await Bun.sleep(25); + expect((await unsettled()).map(record => ({ id: record.id, state: record.state })), `${label}_STAGING_RELEASED`).toEqual([]); + } + /** Measure again until the pool is back within the bound of `base`, crediting only observed reclamation. */ + async function reclaimed(step: string, base: Step, extra: Record = {}): Promise { + let row = await measure(step, null, [], extra); + for (let attempt = 0; attempt < 20 && row.chargedBytes - base.chargedBytes > T.reclaimedBytes; attempt++) { await Bun.sleep(250); row = await measure(step, null, [], extra); } + return row; + } + /** Wait for a source root not in `known` to reach `state`, polling the pool every 5 ms. */ + async function newSourceRoot(known: Set, state: string, stop: () => boolean = () => false): Promise { + for (let attempt = 0; attempt < 4_000 && !stop(); attempt++) { + const found = (await records()).find(record => record.purpose === "source" && !known.has(record.id) && record.state === state); + if (found) return found; + await Bun.sleep(5); + } + return undefined; + } try { const penelope = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 86_400 }); createReferenceGrant(db, { brain: "ithaca", principalId: penelope.id, repositoryPrefix: `file://${srv}`, credential: null, createdBy: penelope.id, now: clock }); - const sources = createReferenceSources({ db, pool: client, transport: createReferenceTransport({ brainPath: "/brain-fixture/brain" }), brain: "ithaca", credentials: {}, now, + // One app instance's services; the crash below replaces them with the next instance's. + const instance = () => createReferenceSources({ db, pool: client, transport: createReferenceTransport({ brainPath: "/brain-fixture/brain" }), brain: "ithaca", credentials: {}, now, dependents: rootId => referenceWorktreeDependents(db, rootId) }); - const worktrees = createFixtureWorktrees({ db, pool: client, sources, now }, note); - const repository = `file://${srv}/aegean.git`, request = () => sources.request({ principalId: penelope.id, repository, revision: "main" }); + let sources = instance(); + let worktrees = createFixtureWorktrees({ db, pool: client, sources, now }, note); + const repository = `file://${srv}/aegean.git`, request = (signal?: AbortSignal) => sources.request({ principalId: penelope.id, repository, revision: "main", ...(signal ? { signal } : {}) }); const baseline = await measure("baseline", null); // Cold acquisition: one new sealed source root holds Git objects and the checkout. - const [cold, coldMs] = await timed(request); + const [cold, coldMs, coldPeak] = await sampled(() => request()); const coldRoot = await pathOf(cold.rootId); const objects = (root: string) => Object.fromEntries(command(["git", "-c", "safe.directory=*", "--git-dir", join(root, ".git"), "count-objects", "-v"]).trim().split("\n").map(line => line.split(": ") as [string, string])); - const acquired = await measure("cold-acquisition", coldMs, [coldRoot, join(coldRoot, ".git"), join(coldRoot, "odyssey"), join(coldRoot, "charts")], { objects: objects(coldRoot) }); + const acquired = await measure("cold-acquisition", coldMs, [coldRoot, join(coldRoot, ".git"), join(coldRoot, "odyssey"), join(coldRoot, "charts")], { objects: objects(coldRoot), peak: coldPeak }); const coldOwner = owner(acquired, cold.rootId)!; expect(coldOwner, "REFERENCE_EFFICIENCY_COLD_HOLDS_OBJECTS_AND_CHECKOUT").toBeGreaterThanOrEqual(2 * W.charts * W.chartBytes); expect(await sourceRoots(), "REFERENCE_EFFICIENCY_COLD_ONE_ROOT").toEqual([cold.rootId]); @@ -161,8 +214,10 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis expect(features, "REFERENCE_EFFICIENCY_SUBMODULE_AND_LFS_NOT_FETCHED").toEqual({ submodule: "", lfs: "version https://git-lfs.github.com/spec/v1" }); // Repeat read inside the refresh window: the same root, no new checkout and no new allocation. - const [warm, warmMs] = await timed(request); - const reread = await measure("repeat-read", warmMs); + const [warm, warmMs, warmPeak] = await sampled(() => request()); + const reread = await measure("repeat-read", warmMs, [], { peak: warmPeak }); + // A warm read never reserves: its peak stays at the charge the cold acquisition left. + expect(warmPeak.pendingBytes, "REFERENCE_EFFICIENCY_REPEAT_READ_RESERVES_NOTHING").toBe(0); expect({ root: warm.rootId, roots: await sourceRoots() }, "REFERENCE_EFFICIENCY_REPEAT_READ_REUSES_ROOT").toEqual({ root: cold.rootId, roots: [cold.rootId] }); expect(warmMs, "REFERENCE_EFFICIENCY_REPEAT_READ_FASTER_THAN_COLD").toBeLessThan(coldMs); expect(coldMs, "REFERENCE_EFFICIENCY_COLD_ELAPSED").toBeLessThanOrEqual(T.coldMs); @@ -170,7 +225,7 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis // Unchanged refresh after the window: validated in place, no new root. advance(); - const [unchanged, unchangedMs] = await timed(request); + const [unchanged, unchangedMs] = await timed(() => request()); const validated = await measure("unchanged-refresh", unchangedMs); expect({ root: unchanged.rootId, roots: await sourceRoots(), refreshed: unchanged.refreshedAt > cold.refreshedAt }, "REFERENCE_EFFICIENCY_UNCHANGED_REFRESH_IN_PLACE") .toEqual({ root: cold.rootId, roots: [cold.rootId], refreshed: true }); @@ -215,6 +270,20 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis expect(repackLoss, "REFERENCE_EFFICIENCY_REPACK_LOSES_SHARING").toBeGreaterThanOrEqual(W.charts * W.chartBytes); expect(linkedGrowth, "REFERENCE_EFFICIENCY_LINKED_WORKTREE_CHECKS_OUT_NEW_EXTENTS").toBeGreaterThanOrEqual(W.charts * W.chartBytes); expect(owner(linked, cold.rootId), "REFERENCE_EFFICIENCY_SHARING_LOSS_STAYS_IN_ITS_WORKTREE").toBe(owner(allocated, cold.rootId)); + // Write-time EDQUOT: a worktree writing past its own allowance is refused by the kernel at write(), and charges nothing outside itself. + const allowance = (await client.poolStatus()).limits.operationBytes; + let overflowWritten = 0, overflowRefusal = ""; + const overflowFd = openSync(join(secondPath, "charts", "poseidon.bin"), "w"); + try { while (overflowWritten < 2 * allowance) overflowWritten += writeSync(overflowFd, randomBytes(MIB)); } + catch (error) { overflowRefusal = (error as NodeJS.ErrnoException).code ?? String(error); } + finally { closeSync(overflowFd); } + const refusedWrite = await measure("worktree-edquot", null, [firstPath, secondPath], { allowance, written: overflowWritten, refusal: overflowRefusal }); + report.findings.worktreeEdquot = { allowance, written: overflowWritten, refusal: overflowRefusal, exclusive: exclusive(refusedWrite, secondPath) }; + expect(overflowRefusal, "REFERENCE_EFFICIENCY_WORKTREE_EDQUOT_AT_WRITE").toBe("EDQUOT"); + expect(exclusive(refusedWrite, secondPath), "REFERENCE_EFFICIENCY_WORKTREE_EDQUOT_WITHIN_ALLOWANCE").toBeLessThanOrEqual(allowance); + expect(Math.abs(exclusive(refusedWrite, firstPath) - exclusive(edited, firstPath)), "REFERENCE_EFFICIENCY_WORKTREE_EDQUOT_LEAVES_SIBLING").toBeLessThanOrEqual(64 * 1024); + expect(owner(refusedWrite, cold.rootId), "REFERENCE_EFFICIENCY_WORKTREE_EDQUOT_LEAVES_SOURCE").toBe(owner(allocated, cold.rootId)); + rmSync(join(secondPath, "charts", "poseidon.bin")); // The managed release reads the commit as unpreserved work; this proof then releases both roots itself. const held = { record: (await records()).find(record => record.id === first.id)!, row: worktrees.inventory().find(entry => entry.row.id === first.id)!.row }; const retained = await settledWorktreeRelease({ db, worktrees, records, note }, held, @@ -226,22 +295,91 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis db.query("DELETE FROM reference_worktrees").run(); const parked = await measure("worktrees-released", null); - // Changed refresh: the staging root snapshots the previous one, so only new objects and changed files allocate. + // Write-time EDQUOT on a refresh: a commit larger than one operation's allowance is refused inside the fetch. + // The previous root keeps serving, marked stale, and the staging root is released. + const accepted = git(work, "rev-parse", "HEAD").trim(); + incompressible(join(work, "charts", "poseidon.bin"), allowance + 8 * MIB); + git(work, "add", "."); git(work, "commit", "-q", "-m", "Poseidon raises a storm"); push(); + advance(); + const [overflowed, overflowMs, overflowPeak] = await sampled(() => request()); + await settledStaging("REFERENCE_EFFICIENCY_EDQUOT_REFRESH"); + const refusedRefresh = await reclaimed("edquot-refresh", parked, { ms: overflowMs, peak: overflowPeak, error: overflowed.error }); + report.findings.refreshEdquot = { allowance, commitBytes: allowance + 8 * MIB, error: overflowed.error, peak: overflowPeak, residualBytes: refusedRefresh.chargedBytes - parked.chargedBytes }; + expect({ root: overflowed.rootId, stale: overflowed.stale, roots: await sourceRoots() }, "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_KEEPS_PREVIOUS") + .toEqual({ root: cold.rootId, stale: true, roots: [cold.rootId] }); + // The transport classifies the refusal by Git's own message (reference-transport.ts); the error carries it. + expect(overflowed.error ?? "", "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_REFUSED_AT_WRITE").toMatch(/quota/i); + expect(refusedRefresh.chargedBytes - parked.chargedBytes, "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_RECLAIMED").toBeLessThanOrEqual(T.reclaimedBytes); + overflowed.release(); + // The remote rewinds past the storm; the next refresh never fetches it. + git(work, "reset", "-q", "--hard", accepted); push("--force"); + + // The changed commit every following step acquires: a revised book and one new chart. for (let line = 0; line < W.changedLines; line++) writeFileSync(join(work, "odyssey", "book-1", `line-${line}.md`), `Ithaca log: book 1, line ${line}, revised.\n`); incompressible(join(work, "charts", "scheria.bin"), W.addedChartBytes); git(work, "add", "."); git(work, "commit", "-q", "-m", "Odysseus reaches Scheria"); push(); advance(); - const [changed, changedMs] = await timed(request); + + // Cancellation mid-fetch: the only requester leaves once the staging root is writable. The fetch stops, + // nothing is published, and the staging root is released. + { + const known = new Set((await records()).map(record => record.id)), controller = new AbortController(); + const outcome = request(controller.signal).then(lease => ({ lease, error: null }), (error: unknown) => ({ lease: null, error: error as { code?: string; message?: string } })); + const staged = await newSourceRoot(known, "writable"); + const [left, cancelMs] = await timed(async () => { controller.abort(); return outcome; }); + left.lease?.release(); + await settledStaging("REFERENCE_EFFICIENCY_CANCEL"); + const cancelled = await reclaimed("cancelled-refresh", parked, { ms: cancelMs, staged: staged?.id ?? null, error: left.error?.message ?? null }); + const stagedState = (await records()).find(record => record.id === staged?.id)?.state ?? null; + report.findings.cancellation = { staged: staged?.id ?? null, code: left.error?.code ?? null, stagedState, cancelMs, residualBytes: cancelled.chargedBytes - parked.chargedBytes }; + expect({ staged: Boolean(staged), code: left.error?.code ?? null }, "REFERENCE_EFFICIENCY_CANCEL_DURING_FETCH").toEqual({ staged: true, code: "cancelled" }); + expect({ roots: await sourceRoots(), stagedState: ["deleted", "reclaimed"].includes(stagedState ?? "") }, "REFERENCE_EFFICIENCY_CANCEL_PUBLISHES_NOTHING") + .toEqual({ roots: [cold.rootId], stagedState: true }); + expect(cancelled.chargedBytes - parked.chargedBytes, "REFERENCE_EFFICIENCY_CANCEL_RECLAIMED").toBeLessThanOrEqual(T.reclaimedBytes); + } + + // Crash mid-acquisition and restart: another app instance on this database is killed with SIGKILL while its + // staging root is writable, so none of its own cleanup runs. The next instance's startup recovery releases + // that root and serves the previous source again. + let rested: Step; + { + await worktrees.close(); await sources.close(); + const known = new Set((await records()).map(record => record.id)); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "reference-efficiency-crash-child.ts"), join(state, "ui.db"), socketPath, repository, penelope.id, String(clock)], + { cwd: "/repo", stdout: "pipe", stderr: "pipe" }); + let exited = false; void child.exited.then(() => { exited = true; }); + const stranded = await newSourceRoot(known, "writable", () => exited); + child.kill("SIGKILL"); + const [code, output, errors] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + const crashed = await measure("crashed-refresh", null, [], { stranded: stranded?.id ?? null, code, output: output.trim().slice(-500), errors: errors.trim().slice(-1000) }); + expect({ stranded: Boolean(stranded), signal: child.signalCode, acquired: output.includes("acquired") }, `REFERENCE_EFFICIENCY_CRASH_STRANDS_STAGING ${errors.slice(-1000)}`) + .toEqual({ stranded: true, signal: "SIGKILL", acquired: false }); + // The manager outlives its client: the stranded root stays writable and charged until someone releases it. + expect(crashed.roots.find(root => root.id === stranded!.id)?.state, "REFERENCE_EFFICIENCY_CRASH_LEAVES_STAGING_CHARGED").toBe("writable"); + sources = instance(); + const [recovered, recoverMs] = await timed(() => sources.recover()); + worktrees = createFixtureWorktrees({ db, pool: client, sources, now }, note); + await settledStaging("REFERENCE_EFFICIENCY_RESTART"); + rested = await reclaimed("restart-recovered", parked, { ms: recoverMs, released: recovered.released, retained: recovered.retained }); + report.findings.crashRecovery = { stranded: stranded!.id, recoverMs, released: recovered.released, retained: recovered.retained, residualBytes: rested.chargedBytes - parked.chargedBytes }; + expect({ released: recovered.released.includes(stranded!.id), retained: recovered.retained, roots: await sourceRoots() }, "REFERENCE_EFFICIENCY_RESTART_RELEASES_STAGING") + .toEqual({ released: true, retained: [], roots: [cold.rootId] }); + expect(rested.chargedBytes - parked.chargedBytes, "REFERENCE_EFFICIENCY_RESTART_RECLAIMED").toBeLessThanOrEqual(T.reclaimedBytes); + } + + // Changed refresh: the staging root snapshots the previous one, so only new objects and changed files allocate. + const [changed, changedMs, changedPeak] = await sampled(() => request()); const changedRoot = await pathOf(changed.rootId); // The superseded root has already left its view, so the census covers the new root only. - const refreshed = await measure("changed-refresh", changedMs, [changedRoot], { objects: objects(changedRoot) }); + const refreshed = await measure("changed-refresh", changedMs, [changedRoot], { objects: objects(changedRoot), peak: changedPeak }); expect(changed.rootId, "REFERENCE_EFFICIENCY_CHANGED_REFRESH_NEW_ROOT").not.toBe(cold.rootId); const refreshOwner = owner(refreshed, changed.rootId)!; report.findings.changedRefreshPerCold = refreshOwner / coldOwner; // The new chart is stored once as a Git object and once checked out; nothing inherited is copied. expect(refreshOwner, "REFERENCE_EFFICIENCY_CHANGED_REFRESH_CHARGES_NEW_DATA").toBeGreaterThanOrEqual(2 * W.addedChartBytes); expect(refreshOwner, "REFERENCE_EFFICIENCY_CHANGED_REFRESH_NOT_A_RECLONE").toBeLessThan(coldOwner / 2); - expect(refreshed.chargedBytes - parked.chargedBytes, "REFERENCE_EFFICIENCY_CHANGED_REFRESH_GROWTH_BOUNDED").toBeLessThanOrEqual(T.changedRefreshBytes); + // Measured from the restarted instance's recovered state: the refused, cancelled and crashed attempts left nothing behind it. + expect(refreshed.chargedBytes - rested.chargedBytes, "REFERENCE_EFFICIENCY_CHANGED_REFRESH_GROWTH_BOUNDED").toBeLessThanOrEqual(T.changedRefreshBytes); // Concurrent readers during one refresh join it: exactly one new root, every reader on it. writeFileSync(join(work, "odyssey", "book-2", "line-0.md"), "Ithaca log: book 2, line 0, the Phaeacians listen.\n"); @@ -249,7 +387,7 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis advance(); const before = await sourceRoots(); let peak = 0; const sample = setInterval(() => { client.poolStatus().then(value => { peak = Math.max(peak, value.accounting?.pendingBytes ?? 0); }, () => {}); }, 50); - const [readers, concurrentMs] = await timed(() => Promise.all(Array.from({ length: 4 }, request))); + const [readers, concurrentMs] = await timed(() => Promise.all(Array.from({ length: 4 }, () => request()))); clearInterval(sample); const joined = await measure("concurrent-refresh", concurrentMs, [], { peakPendingBytes: peak }); const added = (await sourceRoots()).filter(id => !before.includes(id)); 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..c1453446ed 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,35 @@ 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: pool status every 100 ms; 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 +95,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 +108,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"); @@ -100,6 +141,9 @@ 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 +178,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 +196,31 @@ 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, pendingBytes: 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); } })(), + (async () => { while (running) { const value = (await manager.poolStatus().catch(() => null))?.accounting; + if (value) { start.chargedBytes ??= value.chargedBytes; peak.chargedBytes = Math.max(peak.chargedBytes, value.chargedBytes); peak.pendingBytes = Math.max(peak.pendingBytes, value.pendingBytes); } + 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 +233,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(sampled.inspects!.io, `INTEGRATED_${tag}_IO_COUNTED`).not.toBeNull(); + 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/") }, diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index f6fb7d8f29..40ed77403b 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -820,13 +820,14 @@ const shapes = await create("staging", 32 * MIB); // 19. Repository efficiency (#3513): a generated repository acquired, read again, // refreshed unchanged, changed and concurrently, and checked out into managed -// worktrees, with the unique allocation of every step in reference-efficiency.json. +// worktrees; write-time EDQUOT, cancellation and crash recovery under the same +// workload; the unique allocation and I/O of every step in reference-efficiency.json. { const { runReferenceEfficiency } = await import("./reference-efficiency.js"); await manager.close(); const served = await serveNativeBrainManager(config); try { - await runReferenceEfficiency({ client: createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }), artifacts: ARTIFACTS, note, command, sync }); + await runReferenceEfficiency({ client: createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }), socketPath: config.socketPath, artifacts: ARTIFACTS, note, command, sync }); } finally { await served.close(); } manager = await createNativeBrainManager(config); } diff --git a/tests/native-pool-io.test.ts b/tests/native-pool-io.test.ts new file mode 100644 index 0000000000..4edbbc15c0 --- /dev/null +++ b/tests/native-pool-io.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from "bun:test"; +import { deviceNumbers, parsePoolIo, poolIoDelta } from "../scripts/native-proof/pool-io.ts"; + +// makedev(7, 2429): the reference pool fixture's loop device (scripts/native-proof/reference-pool-fixture.py). +const POOL_RDEV = (2429 & 0xff) | (7 << 8) | ((2429 & ~0xff) << 12); +const DISKSTATS = [ + " 7 125 loop125 1 0 8 0 2 0 16 0 0 0 0 0 0 0 0 0 0", + " 7 2429 loop2429 40 2 800 11 90 5 4096 30 0 41 41 0 0 0 0 7 3", + " 259 0 nvme0n1 5 0 10 1 6 0 12 1 0 2 2 0 0 0 0 0 0", +].join("\n"); +const SELF_IO = "rchar: 9000\nwchar: 7000\nsyscr: 30\nsyscw: 20\nread_bytes: 4096\nwrite_bytes: 8192\ncancelled_write_bytes: 0\n"; + +describe("pool I/O counters (#3513)", () => { + test("decodes a loop minor above 255 from its dev_t", () => { + expect(deviceNumbers(POOL_RDEV)).toEqual({ major: 7, minor: 2429 }); + expect(deviceNumbers((125 & 0xff) | (7 << 8))).toEqual({ major: 7, minor: 125 }); + }); + + test("reads the pool device's row, not a device sharing its low minor bits", () => { + expect(parsePoolIo(POOL_RDEV, DISKSTATS, SELF_IO)).toEqual({ + device: { readOps: 40, readBytes: 800 * 512, writeOps: 90, writeBytes: 4096 * 512 }, + process: { readBytes: 4096, writeBytes: 8192, rchar: 9000, wchar: 7000 }, + }); + }); + + test("is null rather than zero when a counter is missing", () => { + expect(parsePoolIo(POOL_RDEV, DISKSTATS.split("\n").filter(line => !line.includes("loop2429")).join("\n"), SELF_IO)).toBeNull(); + expect(parsePoolIo(POOL_RDEV, DISKSTATS, "rchar: 1\nwchar: 2\n")).toBeNull(); + }); + + test("reports each step's own I/O as the difference of two readings", () => { + const before = parsePoolIo(POOL_RDEV, DISKSTATS, SELF_IO)!; + const after = parsePoolIo(POOL_RDEV, DISKSTATS.replace("loop2429 40 2 800 11 90 5 4096", "loop2429 41 2 808 11 95 5 6144"), SELF_IO.replace("write_bytes: 8192", "write_bytes: 12288"))!; + expect(poolIoDelta(after, before)).toEqual({ device: { readOps: 1, readBytes: 8 * 512, writeOps: 5, writeBytes: 2048 * 512 }, process: { readBytes: 0, writeBytes: 4096, rchar: 0, wchar: 0 } }); + expect(poolIoDelta(after, null)).toBeNull(); + }); +}); From 381ee1de84df1e0012be61be352660b073f53761 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 22:14:07 +0000 Subject: [PATCH 2/7] chore(scripts): TEMPORARY hosted probe running the integrated reference cell (#3513) Reverted before the PR is ready. Co-Authored-By: Claude Opus 5.5 --- scripts/prove-reference-pool.ts | 37 ++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 54c9374880..34c5e98af8 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,19 +37,28 @@ 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, so run both cells here. + const cells = selected.length ? [integrated] : [undefined, { backends: ["claude", "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 4e63c998331a2cace174d978dd1013441f132da1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 05:00:17 +0000 Subject: [PATCH 3/7] test(ui-server): correct the refresh EDQUOT expectation and keep integrated receipts uploadable (#3513) The first hosted baseline showed Git's write-time quota error inside the refresh fetch, rejected as capacity: past the refresh window the previous commit's validation has lapsed too, so no stale copy may be served. Assert that rule instead of a stale fallback. The integrated cell left its UID 1000 app data owner-only in the artifact tree, so the whole runtime-host receipt upload failed. Make the tree readable on exit, print the app's warnings into the job log, and sample peak allocation from sysfs rather than polling the shared manager mid-turn. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/README.md | 10 +++++--- scripts/native-proof/reference-efficiency.ts | 21 +++++++++------- .../reference-integration.native.ts | 25 ++++++++++++++----- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index c8405e3820..e3add39531 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -411,7 +411,9 @@ reservation sampled every 50 ms while the step ran. The run checks: - **Write-time EDQUOT.** A worktree writing past its allowance is refused by `write()` with `EDQUOT`, charging neither its sibling nor its source. A commit larger than one operation's allowance is refused inside the refresh - fetch: the previous root keeps serving, marked stale with Git's quota error, + fetch, with Git's quota error. Past the refresh window the previous commit's + validation has also lapsed, so no stale copy may be served: the request + rejects as `capacity`, the previous root is neither served nor withdrawn, and the staging root is released and reclaimed. - **Cancellation.** A refresh whose only requester leaves once its staging root is writable rejects as `cancelled`, publishes nothing, and its staging @@ -473,8 +475,10 @@ Git objects and checkout both hold real data 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 charge and reservations every 100 ms, and reads the pool device's -block I/O per turn. The child times each reference tool call at the model +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, diff --git a/scripts/native-proof/reference-efficiency.ts b/scripts/native-proof/reference-efficiency.ts index 790a1ee899..15555f9efa 100644 --- a/scripts/native-proof/reference-efficiency.ts +++ b/scripts/native-proof/reference-efficiency.ts @@ -296,21 +296,24 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis const parked = await measure("worktrees-released", null); // Write-time EDQUOT on a refresh: a commit larger than one operation's allowance is refused inside the fetch. - // The previous root keeps serving, marked stale, and the staging root is released. + // The refresh window has passed and so has the previous commit's validation (both default to five minutes), + // so no stale copy may be served: the request rejects as capacity. The previous root is neither served nor + // withdrawn, and the staging root is released. const accepted = git(work, "rev-parse", "HEAD").trim(); incompressible(join(work, "charts", "poseidon.bin"), allowance + 8 * MIB); git(work, "add", "."); git(work, "commit", "-q", "-m", "Poseidon raises a storm"); push(); advance(); - const [overflowed, overflowMs, overflowPeak] = await sampled(() => request()); + const [overflowed, overflowMs, overflowPeak] = await sampled(() => request().then( + lease => { lease.release(); return { root: lease.rootId as string | null, code: null as string | null, message: lease.error }; }, + (error: { code?: string; message?: string }) => ({ root: null as string | null, code: error.code ?? null, message: error.message ?? String(error) }))); await settledStaging("REFERENCE_EFFICIENCY_EDQUOT_REFRESH"); - const refusedRefresh = await reclaimed("edquot-refresh", parked, { ms: overflowMs, peak: overflowPeak, error: overflowed.error }); - report.findings.refreshEdquot = { allowance, commitBytes: allowance + 8 * MIB, error: overflowed.error, peak: overflowPeak, residualBytes: refusedRefresh.chargedBytes - parked.chargedBytes }; - expect({ root: overflowed.rootId, stale: overflowed.stale, roots: await sourceRoots() }, "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_KEEPS_PREVIOUS") - .toEqual({ root: cold.rootId, stale: true, roots: [cold.rootId] }); - // The transport classifies the refusal by Git's own message (reference-transport.ts); the error carries it. - expect(overflowed.error ?? "", "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_REFUSED_AT_WRITE").toMatch(/quota/i); + const refusedRefresh = await reclaimed("edquot-refresh", parked, { ms: overflowMs, peak: overflowPeak, refusal: overflowed }); + report.findings.refreshEdquot = { allowance, commitBytes: allowance + 8 * MIB, refusal: overflowed, peak: overflowPeak, residualBytes: refusedRefresh.chargedBytes - parked.chargedBytes }; + expect({ root: overflowed.root, code: overflowed.code, roots: await sourceRoots() }, "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_REFUSED_AS_CAPACITY") + .toEqual({ root: null, code: "capacity", roots: [cold.rootId] }); + // The transport classifies the refusal by Git's own message (reference-transport.ts); the refusal carries it. + expect(overflowed.message ?? "", "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_REFUSED_AT_WRITE").toMatch(/quota/i); expect(refusedRefresh.chargedBytes - parked.chargedBytes, "REFERENCE_EFFICIENCY_EDQUOT_REFRESH_RECLAIMED").toBeLessThanOrEqual(T.reclaimedBytes); - overflowed.release(); // The remote rewinds past the storm; the next refresh never fetches it. git(work, "reset", "-q", "--hard", accepted); push("--force"); diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index c1453446ed..5ef854ab7e 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -51,7 +51,8 @@ const percentile = (values: number[], fraction: number) => { const sorted = [... 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: pool status every 100 ms; io: pool loop device block counters (/proc/diskstats) per turn, after sync", + + "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)); @@ -137,6 +138,12 @@ 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; } @@ -199,14 +206,15 @@ async function run(backend: "claude" | "pi") { /** 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, pendingBytes: 0 }, start: { chargedBytes: number | null } = { chargedBytes: null }; + 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); } })(), - (async () => { while (running) { const value = (await manager.poolStatus().catch(() => null))?.accounting; - if (value) { start.chargedBytes ??= value.chargedBytes; peak.chargedBytes = Math.max(peak.chargedBytes, value.chargedBytes); peak.pendingBytes = Math.max(peak.pendingBytes, value.pendingBytes); } + // 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 () => { @@ -280,7 +288,7 @@ async function run(backend: "claude" | "pi") { `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(sampled.inspects!.io, `INTEGRATED_${tag}_IO_COUNTED`).not.toBeNull(); + 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. @@ -381,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 }); } } @@ -410,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 36a9c8a27d2eefc728d8b386fca26b38b5dab404 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 07:45:29 +0000 Subject: [PATCH 4/7] Revert "chore(scripts): TEMPORARY hosted probe running the integrated reference cell (#3513)" This reverts commit 381ee1de84df1e0012be61be352660b073f53761. --- scripts/prove-reference-pool.ts | 37 +++++++++++++-------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 34c5e98af8..54c9374880 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,28 +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, so run both cells here. - const cells = selected.length ? [integrated] : [undefined, { backends: ["claude", "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 1e3f724a266676ada0af04e79e9036b725b22aab Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 07:45:38 +0000 Subject: [PATCH 5/7] test(scripts): keep the integrated latency instrument out until #4079 lets it run (#3513) Both hosted baselines stopped the integrated cell at its first reference_source call: the turn's own scratch check and the reference transport's Git command each need the whole default maintenance budget, and the second is refused (#4079). The cell's latency assertions were never measured, so they leave this change; the instrument is kept on its own branch for the follow-up. Case 19 passed in full on hosted runtime_host. 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, 26 insertions(+), 173 deletions(-) diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index e3add39531..a1cc582e30 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -469,25 +469,6 @@ 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 7129660079..ffd32a51d8 100644 --- a/scripts/native-proof/reference-integration-child.ts +++ b/scripts/native-proof/reference-integration-child.ts @@ -25,16 +25,11 @@ 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. - * `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. - */ +/** Every tool result and command output, keyed by step, feeds later steps and the parent's assertions. */ const state: IntegrationState = { repository, results: {} }; -function record(key: string, step: IntegrationStep, index: number, value: unknown, elapsedMs: number | null = null) { +function record(key: string, step: IntegrationStep, index: number, value: unknown) { state.results[stepKey(key, index)] = value; - event("integration_step", { backend: selectedBackend, turn: key, index, stepKind: step.kind, ...(step.kind === "tool" ? { tool: step.tool } : {}), elapsedMs, value }); + event("integration_step", { backend: selectedBackend, turn: key, index, stepKind: step.kind, ...(step.kind === "tool" ? { tool: step.tool } : {}), value }); } const turnKey = (text: string) => Object.keys(INTEGRATION_STEPS).find(key => text.includes(`Odysseus ${key}`)); @@ -43,8 +38,6 @@ 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 }); @@ -63,8 +56,7 @@ 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(""); - 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)); + record(key, steps[index]!, index, steps[index]!.kind === "tool" ? JSON.parse(text) : text); } appendFileSync(join(dir, "pi-requests.jsonl"), JSON.stringify({ turn: key, step: index, raw }) + "\n"); const step = steps[index]; @@ -76,7 +68,6 @@ 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. @@ -121,11 +112,9 @@ 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), elapsedMs); + record(key, step, index, JSON.parse(text)); } } 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 0914fff492..b0a0ffef20 100644 --- a/scripts/native-proof/reference-integration-steps.ts +++ b/scripts/native-proof/reference-integration-steps.ts @@ -42,7 +42,6 @@ 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` }, @@ -50,7 +49,6 @@ 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 5ef854ab7e..fd0a0aad7b 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -6,16 +6,9 @@ * 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, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs"; -import { randomBytes } from "node:crypto"; +import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { Database } from "bun:sqlite"; import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; @@ -26,36 +19,6 @@ 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"; @@ -96,7 +59,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 and three incompressible charts, served from a local path. +// The offline fictional repository: 24 books of 50 lines, 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`); @@ -109,11 +72,6 @@ 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"); @@ -138,19 +96,10 @@ 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") { @@ -185,16 +134,9 @@ 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 })); } @@ -203,32 +145,6 @@ 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. @@ -241,56 +157,30 @@ async function run(backend: "claude" | "pi") { advertise(UNDELIVERABLE); await Bun.sleep(2_500); } - // 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 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); } 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/") }, @@ -389,10 +279,7 @@ 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}`); - // 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 }); + note(`${backend}-app-exit`, { code }); } } @@ -421,6 +308,4 @@ 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 99e26925d12f41b17c064c0d39c62b21a19427ec Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 07:47:34 +0000 Subject: [PATCH 6/7] test(ui-server): MUTATION M1, reverted before ready: recovery skips a writable staging root (#3513) Expected to fail REFERENCE_EFFICIENCY_RESTART_RELEASES_STAGING in case 19. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/reference-source.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 63e0af6d2e..69fb091a71 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -707,6 +707,8 @@ export function createReferenceSources(options: { // A root a managed worktree (#2430) was snapshotted from stays: releasing it would free nothing. if (record.purpose !== "source" || record.state === "reclaimed" || keep.has(record.id)) continue; if (options.dependents?.(record.id)) { retained.push(record.id); continue; } + // MUTATION M1 (#3513), reverted before ready: startup recovery leaves an interrupted writable staging root behind. + if (record.state === "writable") continue; try { await pool.poolRelease(record.id); released.push(record.id); } catch { retained.push(record.id); } } From 39a1a431643f53e35ab317ba4726f77b092094c3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 10:32:27 +0000 Subject: [PATCH 7/7] Revert "test(ui-server): MUTATION M1, reverted before ready: recovery skips a writable staging root (#3513)" This reverts commit 99e26925d12f41b17c064c0d39c62b21a19427ec. --- packages/ui-server/src/brain/reference-source.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 69fb091a71..63e0af6d2e 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -707,8 +707,6 @@ export function createReferenceSources(options: { // A root a managed worktree (#2430) was snapshotted from stays: releasing it would free nothing. if (record.purpose !== "source" || record.state === "reclaimed" || keep.has(record.id)) continue; if (options.dependents?.(record.id)) { retained.push(record.id); continue; } - // MUTATION M1 (#3513), reverted before ready: startup recovery leaves an interrupted writable staging root behind. - if (record.state === "writable") continue; try { await pool.poolRelease(record.id); released.push(record.id); } catch { retained.push(record.id); } }