// Runs BetterBench against running deployments, one benchmark at a time (two at once would // measure each other). import { type ChildProcess, execFile, spawn } from "node:child_process"; import { access, mkdir, readFile } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; import { asc, eq } from "drizzle-orm"; import { overTime } from "@/lib/agent-tuning"; import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchmark-meta"; import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths"; import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot"; import { db } from "@/lib/db/client"; import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema"; import { ENGINE_PORT } from "@/lib/deploy-command"; import { coreEnv } from "@/lib/env"; import { abSummary } from "./ab-summary"; import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench"; import { sanitizeLine } from "./job-log"; import { log } from "./log"; import { normalizePciAddress } from "./hardware"; import { errorCauses } from "./log-causes"; import { type GpuTargets, ResourceSampler } from "./resources"; import { docker, workerImage } from "./runtimes"; type Current = { runId: string; kind: "run" | "ab"; deploymentIds: string[]; child: ChildProcess; sampler: ResourceSampler | null; /** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */ meta: RunMeta | null; metaB: RunMeta | null; maxPairs: number | null; cancelled: boolean; lost: string | null; secrets: string[]; }; let current: Current | null = null; let starting = false; const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = []; const partial = new Map(); const tails = new Map(); const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); function addLog(runId: string, stream: LogStream, line: string, secrets: string[] = []) { const clean = sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...secrets]).slice(0, 4000); pending.push({ runId, stream, line: clean, ts: new Date() }); const tail = tails.get(runId) ?? []; tail.push(clean); if (tail.length > 400) tail.shift(); tails.set(runId, tail); } /** Split a stream into lines (keeps the unfinished rest per run and stream). */ function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets: string[]) { const key = `${runId}:${stream}`; const parts = ((partial.get(key) ?? "") + data.toString("utf8")).split(/\r?\n|\r/); partial.set(key, parts.pop() ?? ""); for (const p of parts) { if (!p.trim()) continue; addLog(runId, stream, p, secrets); const step = stepOf(p); if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {}); } } /** BetterBench's progress lines ("[single] chat: …", "[prefill] depth ~2000 tok: …") as a short step label. */ export function stepOf(line: string): string | null { const m = line.match(/^\[(single|prefill|concurrency)\]\s*([^:]*)/); if (!m) return null; const what = m[2].trim(); const name = m[1] === "single" ? "Generation" : m[1] === "prefill" ? "Prompt processing" : "Parallel requests"; return what ? `${name}: ${what}` : name; } export async function flushBenchmarkLogs(): Promise { if (pending.length === 0) return; const batch = pending.splice(0, pending.length); for (let i = 0; i < batch.length; i += 500) await db().insert(benchmarkLogs).values(batch.slice(i, i + 500)); } async function finish(runId: string, set: Partial) { await db() .update(benchmarkRuns) .set({ finishedAt: new Date(), ...set }) .where(eq(benchmarkRuns.id, runId)); } /** Runs left "running" by a previous worker can't be resumed. */ export async function recoverBenchmarks(): Promise { const res = await db() .update(benchmarkRuns) .set({ state: "failed", error: "Interrupted: the worker restarted during the run.", finishedAt: new Date() }) .where(eq(benchmarkRuns.state, "running")) .returning({ id: benchmarkRuns.id }); if (res.length) log.info(`marked ${res.length} interrupted benchmark(s) as failed`); } async function exists(path: string) { return access(path).then( () => true, () => false, ); } /** Completed runs whose stored summary predates SUMMARY_VERSION: recompute from results.json. */ export async function refreshSummaries(): Promise { const rows = await db() .select({ id: benchmarkRuns.id, summary: benchmarkRuns.summary, settings: benchmarkRuns.settings }) .from(benchmarkRuns) .where(eq(benchmarkRuns.state, "completed")); let n = 0; for (const r of rows) { if (r.summary?.v === SUMMARY_VERSION) continue; const results = join(runDir(r.id), RESULTS_FILE); if (!(await exists(results))) continue; try { const summary = { ...(await summarize(results)), quick: !!r.settings.quick }; await db().update(benchmarkRuns).set({ summary }).where(eq(benchmarkRuns.id, r.id)); n++; } catch (err) { log.warn(`benchmark ${r.id}: summary refresh failed: ${message(err)}`); } } if (n) log.info(`refreshed ${n} benchmark summar${n === 1 ? "y" : "ies"}`); } async function summarize(results: string): Promise { const { stdout } = await promisify(execFile)(betterbenchPython(), ["-c", SUMMARY_SCRIPT, results], { timeout: 120_000, maxBuffer: 16 * 2 ** 20 }); return JSON.parse(stdout) as BenchmarkSummary; } type Target = { id: string; containerId: string; containerName: string; engine: "llama.cpp" | "vllm"; accelerator: string }; async function target(deploymentId: string | null): Promise { if (!deploymentId) return null; const [d] = await db() .select({ state: deployments.state, containerId: deployments.containerId, containerName: deployments.containerName, engine: runtimes.engine, accelerator: runtimes.accelerator }) .from(deployments) .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) .where(eq(deployments.id, deploymentId)); if (!d || d.state !== "running" || !d.containerName || !d.containerId) return null; return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator }; } /** * What the sampler watches for the GPUs a run uses: NVIDIA via nvidia-smi, Intel/AMD via sysfs (and * the fdinfo probe for Intel), and every GPU's link where sysfs shows it. Probes run from our own image. */ async function gpuTargets(metas: (RunMeta | null)[]): Promise { const addrs = [...new Set(metas.flatMap((m) => m?.gpus.map((g) => g.pciAddress) ?? []).filter((a): a is string => !!a))]; const { hardware, nvidia } = await effectiveHardware(); const image = workerImage(); const used = (hardware?.gpus ?? []).filter((g) => addrs.includes(g.pciAddress)); const pciByIndex: Record = {}; for (const g of nvidia) { const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`; if (addrs.includes(addr)) pciByIndex[g.index] = addr; } const others = used.filter((g) => g.vendor !== "nvidia"); return { nvidia: image && Object.keys(pciByIndex).length ? { image, pciByIndex } : null, sysfs: others.map((g, i) => ({ index: i, pciAddress: g.pciAddress, name: g.name ?? `${g.vendor} GPU`, vendor: g.vendor, vramTotalMb: g.vramMb })), intelProbeImage: image, linkAddresses: addrs.filter((a) => !a.startsWith("nvidia-")), }; } /** A/B notes: the shared host facts once, the engine and model per side. */ function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record): Record { const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"]; const out: Record = Object.fromEntries(Object.entries(shared).filter(([k]) => pick.includes(k))); for (const [side, m] of [["a", a], ["b", b]] as const) { if (!m) continue; out[`${side}_engine`] = engineLabel(m) || m.runtime.engine; out[`${side}_model`] = modelLabel(m); if (m.contextSize != null) out[`${side}_ctx`] = String(m.contextSize); if (m.concurrency != null) out[`${side}_concurrency`] = String(m.concurrency); } return out; } const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`; async function start(run: typeof benchmarkRuns.$inferSelect) { const fail = (error: string) => finish(run.id, { state: "failed", error }); const a = await target(run.deploymentId); if (!a) return fail(run.kind === "ab" ? "Deployment A isn't running anymore." : "The deployment isn't running anymore."); const b = run.kind === "ab" ? await target(run.deploymentBId) : null; if (run.kind === "ab" && !b) return fail("Deployment B isn't running anymore."); const dir = runDir(run.id); await mkdir(dir, { recursive: true }); const needsKey = run.snapshot.options.requireApiKey || run.snapshotB?.options.requireApiKey; // One key works for both: BETTERBENCH_API_KEY fills in every missing key flag. const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : []; const s = run.snapshot; const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS; // What runs on what, recorded now (the deployments are up, so the server's version is known). const setup = await runSetup([a.id, b?.id ?? null]); const [meta, metaB] = setup.metas; const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {}; const args = run.kind === "ab" && b ? abArgs({ endpointA: endpoint(a), endpointB: endpoint(b), model: s.repoId, out: join(dir, AB_FILE), mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT, maxPairs, notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}), ...abNotes(meta, metaB, metaNotesA), }, }) : runArgs({ endpoint: endpoint(a), model: s.repoId, out: join(dir, RESULTS_FILE), settings: run.settings, maxModelLen: s.options.contextSize ?? null, notes: { deployment: s.deploymentName, runtime: s.runtimeName, image: s.image, ...(s.options.modelFile ? { file: s.options.modelFile } : {}), ctx: String(s.options.contextSize), ...metaNotesA, ...(run.label ? { label: run.label } : {}), }, }); // Only what BetterBench needs: no HF_TOKEN or other worker secrets. const env: Record = { PATH: process.env.PATH, HOME: process.env.HOME, LANG: "C.UTF-8", PYTHONUNBUFFERED: "1", NO_COLOR: "1", BETTERBENCH_HOME: dir, BETTERBENCH_NO_UPDATE_CHECK: "1", ...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}), }; addLog( run.id, "system", run.kind === "ab" ? `Paired A/B: ${s.deploymentName} (A) vs ${run.snapshotB?.deploymentName} (B), ${s.repoId}, with BetterBench` : `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`, ); addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys); await db() .update(benchmarkRuns) .set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, metaB, system: setup.system }) .where(eq(benchmarkRuns.id, run.id)); // Resource use of the server(s) under test, and of the GPUs they use. const c = docker(); const sampler = c ? new ResourceSampler( c, [{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])], await gpuTargets([meta, metaB]), ) : null; await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`)); const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); const cur: Current = { runId: run.id, kind: run.kind, deploymentIds: [a.id, ...(b ? [b.id] : [])], child, sampler, meta, metaB, maxPairs: run.kind === "ab" ? maxPairs : null, cancelled: false, lost: null, secrets: keys, }; current = cur; child.stdout.on("data", (buf: Buffer) => chunk(run.id, "stdout", buf, keys)); child.stderr.on("data", (buf: Buffer) => chunk(run.id, "stderr", buf, keys)); child.on("error", (err: NodeJS.ErrnoException) => { addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`); }); child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err))); log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`); } async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) { const id = cur.runId; for (const stream of ["stdout", "stderr"] as const) { const rest = partial.get(`${id}:${stream}`); if (rest?.trim()) addLog(id, stream, rest, cur.secrets); partial.delete(`${id}:${stream}`); } const resources = (await cur.sampler?.stop().catch(() => null)) ?? null; if (current === cur) current = null; if (resources?.links) { const loaded = (m: RunMeta | null) => withLoadLinks(m, resources.links, !!m?.overridden.includes("pcie link")); await db() .update(benchmarkRuns) .set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) }) .where(eq(benchmarkRuns.id, id)) .catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`)); } const dir = runDir(id); const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE); const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE))); if (cur.cancelled) { addLog(id, "system", "Cancelled."); await finish(id, { state: "cancelled", hasReport, resources }); } else if (cur.lost) { addLog(id, "system", cur.lost); await finish(id, { state: "failed", error: cur.lost, hasReport, resources }); } else if (code === 0 && (await exists(results))) { try { if (cur.kind === "ab") { const ab = abSummary(await readFile(results, "utf8"), cur.maxPairs); addLog(id, "system", `Done: ${ab.decode_tps.verdict} (${ab.pairs} pairs).`); await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, resources, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." }); } else { const summary = { ...(await summarize(results)), quick: false }; const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) }); summary.quick = !!run?.settings.quick; addLog(id, "system", "Done."); await finish(id, { state: "completed", summary, hasReport, resources }); } } catch (err) { await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport, resources }); } } else { const lines = tails.get(id) ?? []; const causes = errorCauses(lines); const why = signal ? `stopped by ${signal}` : `exit code ${code ?? "?"}`; const last = lines.slice(-12).join("\n"); await finish(id, { state: "failed", error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"), hasReport, resources, }); } tails.delete(id); await flushBenchmarkLogs().catch(() => {}); log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost ? "failed (deployment gone)" : code === 0 ? "completed" : "failed"}`); } function stop(cur: Current) { if (cur.child.exitCode !== null) return; cur.child.kill("SIGTERM"); setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref(); } /** Start the next queued run, stop the current one on cancel or when its deployment goes away. */ export async function tickBenchmarks(): Promise { if (starting) return; if (current) { const cur = current; const [run] = await db() .select({ cancel: benchmarkRuns.cancelRequestedAt, startedAt: benchmarkRuns.startedAt, timeLimitS: benchmarkRuns.timeLimitS }) .from(benchmarkRuns) .where(eq(benchmarkRuns.id, cur.runId)); if (!run || run.cancel) { cur.cancelled = true; stop(cur); return; } // Agent runs have a time limit (Settings → API tokens). if (overTime(run.startedAt, run.timeLimitS)) { cur.lost = `Stopped: the run exceeded the time limit for agent runs (${Math.round((run.timeLimitS ?? 0) / 60)} min).`; stop(cur); return; } for (const depId of cur.deploymentIds) { const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId)); if (!d || d.state !== "running") { cur.lost = cur.deploymentIds.length > 1 ? "A deployment of the A/B stopped during the run." : "The deployment stopped during the run."; stop(cur); break; } } return; } starting = true; try { const next = await db().query.benchmarkRuns.findFirst({ where: eq(benchmarkRuns.state, "queued"), orderBy: asc(benchmarkRuns.createdAt) }); if (next) await start(next).catch((err) => finish(next.id, { state: "failed", error: `Could not start: ${message(err)}` })); } finally { starting = false; } } /** Worker shutdown: a run can't continue in another process. */ export async function stopBenchmarks(): Promise { const cur = current; if (!cur) return; cur.lost = "Interrupted: the worker stopped during the run."; stop(cur); const deadline = Date.now() + 5_000; while (current === cur && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100)); }