Files
Kaname/src/lib/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

229 lines
10 KiB
TypeScript

import "server-only";
import { rm } from "node:fs/promises";
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm";
import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
export const DESCRIPTION_MAX = 4000;
export const BenchmarkBody = z.object({
deploymentId: z.string().min(1),
label: z.string().trim().max(120).nullable().optional(),
/** Free text: what this run tries out. Passed to BetterBench and launch80 with the system summary. */
description: z.string().trim().max(DESCRIPTION_MAX).nullable().optional(),
quick: z.boolean().default(false),
passes: z.number().int().min(1).max(200).nullable().optional(),
warmup: z.number().int().min(0).max(50).nullable().optional(),
/** Empty: all phases. */
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** A/B: the second deployment (B), the target minimum detectable effect in % and the pair ceiling. */
deploymentBId: z.string().min(1).nullable().optional(),
mdePct: z.number().min(0.1).max(50).nullable().optional(),
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
/** Set by sweeps. */
sweepId: z.string().nullable().optional(),
/** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
kind: z.enum(["run", "ab", "eval"]).optional(),
/** eval: which sections (empty: all). */
evalSections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
});
export type BenchmarkInput = z.infer<typeof BenchmarkBody>;
/** A running deployment as it is now: what a run measures and records. */
async function snapshotOf(deploymentId: string, role: string) {
const d = await deploymentSnapshot(deploymentId);
if (!d) throw new BenchmarkError("not_found", `${role} not found.`, 404);
if (d.state !== "running") throw new BenchmarkError("invalid", `Start ${role.toLowerCase()} first; benchmarks run against a running server.`, 409);
return d;
}
/**
* Queue a run against a running deployment, or a paired A/B between two running deployments of the
* same model (BetterBench sends one model name to both). The worker runs one benchmark at a time.
*/
/** Requested through the API: who asked, whether it waits for approval, and its time limit. */
export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
const kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
const ab = kind === "ab";
if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
if (b) {
if (b.id === a.id) throw new BenchmarkError("invalid", "Pick two different deployments for an A/B.", 400);
if (b.snapshot.repoId !== a.snapshot.repoId) {
throw new BenchmarkError("invalid", "An A/B compares two deployments of the same model (BetterBench requests one model name from both).", 400);
}
}
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind,
deploymentId: a.id,
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings:
kind === "eval"
? { quick: false, passes: null, warmup: null, phases: [], evalSections: input.evalSections ?? [] }
: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
snapshot: a.snapshot,
snapshotB: b?.snapshot ?? null,
sweepId: input.sweepId ?? null,
...(agent
? {
requestedByTokenId: agent.requestedBy.tokenId,
requestedBy: agent.requestedBy.name,
timeLimitS: agent.timeLimitS,
state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
}
: {}),
})
.returning({ id: benchmarkRuns.id });
return row;
}
const listColumns = {
id: benchmarkRuns.id,
deploymentId: benchmarkRuns.deploymentId,
modelId: benchmarkRuns.modelId,
tool: benchmarkRuns.tool,
label: benchmarkRuns.label,
settings: benchmarkRuns.settings,
snapshot: benchmarkRuns.snapshot,
state: benchmarkRuns.state,
phase: benchmarkRuns.phase,
cancelRequestedAt: benchmarkRuns.cancelRequestedAt,
startedAt: benchmarkRuns.startedAt,
finishedAt: benchmarkRuns.finishedAt,
error: benchmarkRuns.error,
summary: benchmarkRuns.summary,
hasReport: benchmarkRuns.hasReport,
kind: benchmarkRuns.kind,
deploymentBId: benchmarkRuns.deploymentBId,
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
quality: benchmarkRuns.quality,
sweepId: benchmarkRuns.sweepId,
requestedBy: benchmarkRuns.requestedBy,
requestedByTokenId: benchmarkRuns.requestedByTokenId,
timeLimitS: benchmarkRuns.timeLimitS,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
description: benchmarkRuns.description,
createdAt: benchmarkRuns.createdAt,
};
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
return db()
.select(listColumns)
.from(benchmarkRuns)
.where(
and(
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
),
)
.orderBy(desc(benchmarkRuns.createdAt));
}
export async function getBenchmark(id: string) {
const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
return row ?? null;
}
export async function getBenchmarks(ids: string[]) {
if (ids.length === 0) return [];
const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
}
/** Queued (or still unapproved) runs are cancelled right away; a running one is stopped by the worker. */
export async function cancelBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "queued" || run.state === "pending_approval") {
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
} else if (run.state === "running") {
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
}
}
/** Let a run an agent asked for start (it joins the queue). */
export async function approveBenchmark(id: string) {
const res = await db()
.update(benchmarkRuns)
.set({ state: "queued" })
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
.returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
}
/** Turn down a run an agent asked for. */
export async function rejectBenchmark(id: string) {
const res = await db()
.update(benchmarkRuns)
.set({ state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
.returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
}
/** Rename a run (label) and/or change its description; fields left out stay as they are. */
export async function updateBenchmark(id: string, patch: { label?: string | null; description?: string | null }) {
const set: Partial<typeof benchmarkRuns.$inferInsert> = {};
if (patch.label !== undefined) set.label = patch.label?.trim() || null;
if (patch.description !== undefined) set.description = patch.description?.trim() || null;
if (Object.keys(set).length === 0) return;
const res = await db().update(benchmarkRuns).set(set).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
}
/** Deletes the run, its log and its files. Cancel a running one first. */
export async function deleteBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "running") throw new BenchmarkError("busy", "Cancel the run before deleting it.", 409);
await db().delete(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
await db().delete(benchmarkRuns).where(eq(benchmarkRuns.id, id));
await rm(runDir(id), { recursive: true, force: true });
}
export async function listBenchmarkLogs(id: string, afterId: number, tail = 500) {
const rows =
afterId > 0
? await db()
.select()
.from(benchmarkLogs)
.where(and(eq(benchmarkLogs.runId, id), gt(benchmarkLogs.id, afterId)))
.orderBy(asc(benchmarkLogs.id))
.limit(2000)
: (await db().select().from(benchmarkLogs).where(eq(benchmarkLogs.runId, id)).orderBy(desc(benchmarkLogs.id)).limit(tail)).reverse();
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
}