#!/usr/bin/env node // BudgetBench RUNNER: one interface for every system. For each case it asks the turns in order on a fresh // conversation, and when a turn asks a choice it answers EVERY option on a copy of the conversation; the TAP picks // the option the ANSWER KEY marks right (grader/score.mjs rightFor), the same way for every system, and the // conversation goes on from it. Each row holds the full transcript; the label is computed by grader/score.mjs and // can be recomputed from the row at any time (stats/report.mjs --regrade). // // node budgetbench/runner/run.mjs --system pulse-local --variant rules --split public [--run-id ID] // [--household p-amex] [--only id,id] [--limit N] [--timeout-s 900] // BB_BASE=http://127.0.0.1:8080/v1 BB_MODEL=local BB_NO_THINK=1 \ // node budgetbench/runner/run.mjs --system openai-compat --variant qwen3-8b --split public // // The SEALED splits (v1 "sealed", v2 "sealed-v2", v3 "sealed-v3") run only with --sealed (the release gate's call, never a // development run). // Infra failures (a crash, a timeout, a served-model mismatch) go to errors.jsonl, never into results.jsonl. import {createHash} from "node:crypto"; import {execSync, spawnSync} from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import {fileURLToPath, pathToFileURL} from "node:url"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const BB = path.resolve(HERE, ".."); const argv = process.argv.slice(2); const flag = (n, d = null) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : d; }; const has = (n) => argv.includes(n); const SYSTEM = flag("--system"), VARIANT = flag("--variant", "default"), SPLIT = flag("--split", "public"); const ONLY = flag("--only") ? new Set(flag("--only").split(",")) : null; const HOUSEHOLD = flag("--household"), LIMIT = Number(flag("--limit", "0")), TIMEOUT_S = Number(flag("--timeout-s", "900")); const RUN_ID = flag("--run-id", new Date().toISOString().slice(0, 10)); if (!SYSTEM) { console.error("usage: run.mjs --system --variant --split public [--run-id ID]"); process.exit(2); } const SPLITS = {public: ["cases/public", "households/public"], sealed: ["sealed/cases", "sealed/households"], "sealed-v2": ["sealed-v2/cases", "sealed-v2/households"], "sealed-v3": ["sealed-v3/cases", "sealed-v3/households"]}; const SEALED = SPLIT.startsWith("sealed"); if (SEALED && !has("--sealed")) { console.error("a sealed split runs only with --sealed (release gate; see CONTAMINATION.md)"); process.exit(2); } if (!SPLITS[SPLIT]) { console.error(`--split ${Object.keys(SPLITS).join("|")}`); process.exit(2); } const CASES_DIR = path.join(BB, SPLITS[SPLIT][0]); const HH_DIR = path.join(BB, SPLITS[SPLIT][1]); const OUT = path.join(BB, "results", `${SYSTEM}-${VARIANT}`, SPLIT, RUN_ID); fs.mkdirSync(OUT, {recursive: true}); const sha = (buf) => createHash("sha256").update(buf).digest("hex"); const fileSha = (f) => sha(fs.readFileSync(f)); function dirSha(dir, filter = () => true) { const h = createHash("sha256"); const walk = (d) => { for (const e of fs.readdirSync(d, {withFileTypes: true}).sort((a, b) => a.name.localeCompare(b.name))) { const p = path.join(d, e.name); if (e.isDirectory()) walk(p); else if (filter(p)) h.update(path.relative(dir, p)).update("\0").update(fs.readFileSync(p)).update("\0"); } }; walk(dir); return h.digest("hex"); } function loadCases() { const all = []; for (const f of fs.readdirSync(CASES_DIR).filter((x) => x.endsWith(".jsonl")).sort()) for (const l of fs.readFileSync(path.join(CASES_DIR, f), "utf8").split("\n").filter((x) => x.trim())) all.push(JSON.parse(l)); return all.filter((c) => (!ONLY || ONLY.has(c.id)) && (!HOUSEHOLD || c.household === HOUSEHOLD)); } const sys = await import(pathToFileURL(path.join(BB, "systems", `${SYSTEM}.mjs`)).href); async function inputs() { const appSource = SYSTEM === "pulse-local" ? (() => { const app = path.join(BB, "../app"); const files = execSync("git ls-files -c -o --exclude-standard electron src", {cwd: app, encoding: "utf8"}).split("\n").filter((f) => f && !f.includes("node_modules")).sort(); const h = createHash("sha256"); for (const f of files) { try { h.update(f).update("\0").update(fs.readFileSync(path.join(app, f))).update("\0"); } catch { /* deleted */ } } return h.digest("hex"); })() : null; let head = null; try { head = execSync("git rev-parse HEAD", {cwd: BB, encoding: "utf8"}).trim(); } catch { /* not a checkout */ } return {split: SPLIT, run_id: RUN_ID, system: await sys.describe(VARIANT), variant: VARIANT, git_head: head, app_source_sha256: appSource, cases_sha256: dirSha(CASES_DIR), households_sha256: dirSha(HH_DIR), grader_sha256: dirSha(path.join(BB, "grader")), oracle_sha256: dirSha(path.join(BB, "oracle")), runner_sha256: fileSha(fileURLToPath(import.meta.url)), system_sha256: fileSha(path.join(BB, "systems", `${SYSTEM}.mjs`)), tools_sha256: fileSha(path.join(BB, "systems/tools.mjs"))}; } // ---- the parent: one child per household when the system needs a process of its own ---------------------------- if (!has("--child")) { const ins = await inputs(); const insPath = path.join(OUT, "inputs.json"); if (fs.existsSync(insPath)) { const old = JSON.parse(fs.readFileSync(insPath, "utf8")); const same = (k) => JSON.stringify(old[k]) === JSON.stringify(ins[k]); const changed = ["cases_sha256", "households_sha256", "grader_sha256", "oracle_sha256", "runner_sha256", "system_sha256", "tools_sha256", "app_source_sha256", "system"].filter((k) => !same(k)); if (changed.length) { console.error(`inputs changed since this run started (${changed.join(", ")}): use a new --run-id`); process.exit(2); } } else fs.writeFileSync(insPath, JSON.stringify({...ins, started: new Date().toISOString()}, null, 1) + "\n"); const cases = loadCases(); const households = [...new Set(cases.map((c) => c.household))].sort(); const t0 = Date.now(); if (sys.processPerHousehold) { for (const hh of households) { const args = [fileURLToPath(import.meta.url), ...argv.filter((a, i) => !["--household"].includes(a) && argv[i - 1] !== "--household"), "--household", hh, "--child", "--run-id", RUN_ID]; const setup = JSON.parse(fs.readFileSync(path.join(HH_DIR, hh, "truth/setup.json"), "utf8")); const r = spawnSync(process.execPath, ["--experimental-strip-types", "--no-warnings", ...args], {stdio: "inherit", env: {...process.env, PULSE_TODAY: setup.today}}); if (r.status !== 0) console.error(`household ${hh}: child exited ${r.status}`); } } else await runHouseholds(households, cases); const meta = JSON.parse(fs.readFileSync(insPath, "utf8")); meta.finished = new Date().toISOString(); meta.wall_s = Math.round((Date.now() - t0) / 1000); fs.writeFileSync(insPath, JSON.stringify(meta, null, 1) + "\n"); console.log(`done: ${OUT}`); process.exit(0); } // ---- the child (or a single process): ask the cases ---------------------------------------------------------------- await runHouseholds([HOUSEHOLD], loadCases()); process.exit(0); async function runHouseholds(households, cases) { const {loadHousehold} = await import(pathToFileURL(path.join(BB, "oracle/oracle.mjs")).href); const {expectationsOf, rightFor, scoreCase} = await import(pathToFileURL(path.join(BB, "grader/score.mjs")).href); const {effectiveMonths} = await import(pathToFileURL(path.join(BB, "grader/judge.mjs")).href); const resultsPath = path.join(OUT, "results.jsonl"), errorsPath = path.join(OUT, "errors.jsonl"); const done = new Set(fs.existsSync(resultsPath) ? fs.readFileSync(resultsPath, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l).id) : []); for (const hhId of households) { const dir = path.join(HH_DIR, hhId); const setup = JSON.parse(fs.readFileSync(path.join(dir, "truth/setup.json"), "utf8")); const hh = loadHousehold(dir); let todo = cases.filter((c) => c.household === hhId && !done.has(c.id)); if (LIMIT > 0) todo = todo.slice(0, LIMIT); if (!todo.length) continue; const session = await sys.open(dir, setup, VARIANT); console.error(`[${hhId}] ${session.loaded} rows loaded; ${todo.length} cases`); let shown = 0; for (const c of todo) { const t0 = Date.now(); try { const turns = await withCeiling(runCase(session, hh, c, {expectationsOf, rightFor, effectiveMonths}), TIMEOUT_S * 1000); const score = scoreCase(hh, c, turns); const row = {id: c.id, household: c.household, category: c.category, source: c.source ?? (c.id.startsWith("pub-classic") ? "eval-v0" : "writer"), model: session.model, label: score.label, taps: score.taps, outcomes: score.turns.map((t) => ({outcome: t.outcome, class: t.class ?? null, reason: t.reason})), turns, wall_s: (Date.now() - t0) / 1000, ...(session.usage ? {usage_so_far: {...session.usage}} : {})}; fs.appendFileSync(resultsPath, JSON.stringify(row) + "\n"); // (a sealed run prints no case id and no label: its log may be read by anyone, or by a hosted assistant) console.error(SEALED ? ` case ${++shown} of ${todo.length} done` : ` ${c.id} ${score.label}`); } catch (e) { fs.appendFileSync(errorsPath, JSON.stringify({id: c.id, household: c.household, failure_class: e.failure_class ?? (/ceiling/.test(e.message) ? "timeout" : "harness_error"), error: String(e.stack ?? e).slice(0, 2000), at: new Date().toISOString()}) + "\n"); console.error(SEALED ? " a case failed: see errors.jsonl" : ` ${c.id} ERROR ${e.message}`); } } } } function withCeiling(p, ms) { if (!ms) return p; let t; return Promise.race([p, new Promise((_, rej) => { t = setTimeout(() => { const e = new Error("wall-clock ceiling exceeded"); e.failure_class = "timeout"; rej(e); }, ms); })]).finally(() => clearTimeout(t)); } async function runCase(session, hh, c, {expectationsOf, rightFor, effectiveMonths}) { const exps = expectationsOf(hh, c); let history = [], prev = null; const turns = []; for (const [i, t] of c.turns.entries()) { const r = await session.ask(history, t.q); const rec = {q: t.q, text: r.text, meta: r.meta ?? null}; let next = r.history; if (r.choice?.labels?.length) { const answers = [], hist = []; for (const label of r.choice.labels) { const a = await session.ask(r.history, label); answers.push({label, text: a.text, meta: a.meta ?? null}); hist.push(a.history); } rec.choice = {labels: r.choice.labels, answers}; // THE TAP: the option the answer key marks right, applied the same way to every system const k = answers.findIndex((a) => rightFor(hh, exps[i], a.text, prev)); if (k >= 0) { rec.tapped = k; next = hist[k]; } } turns.push(rec); prev = {...exps[i], months: effectiveMonths(exps[i], prev), turnRecord: rec}; history = next; } return turns; }