Files
Kaname/src/worker/benchmarks.ts
T
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5
Release / release (push) Successful in 3m17s
Release 0.14.0: quality eval
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00

503 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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,
type BenchmarkKind,
benchmarkLogs,
benchmarkRuns,
type BenchmarkSummary,
deployments,
type LogStream,
QUALITY_SECTIONS,
type QualityResult,
type QualitySection,
type RunMeta,
runtimes,
type SystemSummary,
} from "@/lib/db/schema";
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
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 { runQualityEval } from "./quality";
import { docker, workerImage } from "./runtimes";
type Current = {
runId: string;
kind: BenchmarkKind;
deploymentIds: string[];
/** BetterBench (runs, A/B); null for a quality eval, which runs in-process and stops via `abort`. */
child: ChildProcess | null;
abort: AbortController | null;
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<string, string>();
const tails = new Map<string, string[]>();
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<void> {
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<typeof benchmarkRuns.$inferInsert>) {
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<void> {
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<void> {
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<BenchmarkSummary> {
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<Target | null> {
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<GpuTargets> {
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<number, string> = {};
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<string, string>): Record<string, string> {
const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"];
const out: Record<string, string> = 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) : {};
if (run.kind === "eval") return startEval(run, a, keys, meta, setup.system);
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<string, string | undefined> = {
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,
abort: null,
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}`);
}
/** Stop the resource sampler; record the PCIe links seen under load in the run's meta. */
async function stopSampling(cur: Current) {
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, cur.runId))
.catch((err) => log.warn(`benchmark ${cur.runId}: link update failed: ${message(err)}`));
}
return resources;
}
/** Kaname's quality eval: in-process against the deployment, coding answers in the sandbox. */
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys: string[], meta: RunMeta | null, system: SystemSummary) {
const s = run.snapshot;
const sections = run.settings.evalSections?.length ? run.settings.evalSections : [...QUALITY_SECTIONS];
const dep = await db().query.deployments.findFirst({ columns: { engineInfo: true, options: true }, where: eq(deployments.id, a.id) });
const contextTokens = dep?.engineInfo?.contextSize ?? dep?.options.contextSize ?? s.options.contextSize ?? null;
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${s.deploymentName} (${s.repoId} on ${s.runtimeName}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, system }).where(eq(benchmarkRuns.id, run.id));
const c = docker();
const sampler = c ? new ResourceSampler(c, [{ side: "a" as const, containerId: a.containerId }], await gpuTargets([meta, null])) : null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const cur: Current = {
runId: run.id,
kind: "eval",
deploymentIds: [a.id],
child: null,
abort: new AbortController(),
sampler,
meta,
metaB: null,
maxPairs: null,
cancelled: false,
lost: null,
secrets: keys,
};
current = cur;
log.info(`benchmark ${run.id}: quality eval started for ${s.deploymentName}`);
const onLine = (line: string) => {
addLog(run.id, "stdout", line, keys);
const m = line.match(/^(tools|coding|retrieval): starting$/);
if (m) void db().update(benchmarkRuns).set({ phase: `Quality: ${SECTION_LABEL[m[1] as QualitySection]}` }).where(eq(benchmarkRuns.id, run.id)).then(() => {}, () => {});
};
runQualityEval(
{ base: `http://${a.containerName}:${ENGINE_PORT[a.engine]}`, model: s.repoId, engine: a.engine, apiKey: keys[0] ?? null, contextTokens },
{ sections, signal: cur.abort!.signal, log: onLine, docker: c, sandboxImage: workerImage() },
).then(
(q) => doneEval(cur, q, null),
(err) => doneEval(cur, null, err),
);
}
async function doneEval(cur: Current, quality: QualityResult | null, err: unknown) {
const id = cur.runId;
const resources = await stopSampling(cur);
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", quality, resources });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, quality, resources });
} else if (err || !quality) {
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}`, resources });
} else {
addLog(id, "system", `Done: score ${quality.score ?? "–"} (${quality.sections.map((x) => `${x.section} ${x.unsupported ? "n/a" : `${x.passed}/${x.total}`}`).join(", ")}).`);
await finish(id, { state: "completed", quality, resources });
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: quality eval ${cur.cancelled ? "cancelled" : cur.lost || err ? "failed" : `done, score ${quality?.score}`}`);
}
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 stopSampling(cur);
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) {
const child = cur.child;
if (!child) return void cur.abort?.abort();
if (child.exitCode !== null) return;
child.kill("SIGTERM");
setTimeout(() => child.exitCode === null && 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<void> {
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<void> {
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));
}