Files
Kaname/src/lib/benchmarks.ts
T
Pascal LinxweilerandClaude Opus 5.5 276108932d
Release / release (push) Successful in 12m32s
Release 0.15.0: endpoints instead of deployments
Kaname keeps two jobs: the model downloader and benchmarks. Benchmarks
now run against endpoints (any OpenAI-compatible server added by URL,
with an optional server-side API key and hand-written hardware notes)
instead of deployments Kaname started itself.

Removed: runtimes, deployments, sweeps, resource telemetry, hardware
detection, the /api/v1 API with tokens and guardrails, and all Docker
access. The quality eval's coding tests run in a network-less sandbox
container that shares only an exchange folder with the worker.

The previous state is kept in branch backup / tag backup-0.14.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 21:43:42 +01:00

195 lines
8.8 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 { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema";
import { probeEndpoint } from "@/lib/endpoint-probe";
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({
endpointId: z.string().min(1),
/** The model to request; default: the endpoint's (or the only one it serves). */
model: z.string().trim().max(300).nullable().optional(),
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 endpoint (B), the target minimum detectable effect in % and the pair ceiling. */
endpointBId: 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(),
/** "eval": the quality eval instead of BetterBench (default: run, or ab with endpointBId). */
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>;
/** The endpoint, asked right now: a run against a server that doesn't answer fails at once. */
async function endpointFor(id: string, role: string) {
const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
if (!e) throw new BenchmarkError("not_found", `${role} not found.`, 404);
const probe = await probeEndpoint({ baseUrl: e.baseUrl, apiKey: e.apiKey, engine: e.engine });
await db().update(endpoints).set({ probe }).where(eq(endpoints.id, e.id));
if (!probe.ok) throw new BenchmarkError("invalid", `${role} (${e.name}): ${probe.error}`, 409);
return { e, probe };
}
/**
* Queue a run against an endpoint, or a paired A/B between two endpoints serving the same model
* (BetterBench sends one model name to both). The worker runs one benchmark at a time.
*/
export async function createBenchmark(input: BenchmarkInput) {
const kind = input.kind ?? (input.endpointBId ? "ab" : "run");
const ab = kind === "ab";
if (ab && !input.endpointBId) throw new BenchmarkError("invalid", "An A/B needs a second endpoint.", 400);
if (ab && input.endpointBId === input.endpointId) throw new BenchmarkError("invalid", "Pick two different endpoints for an A/B.", 400);
const a = await endpointFor(input.endpointId, ab ? "Endpoint A" : "The endpoint");
const picked = modelFor(a.e, a.probe, input.model);
if ("error" in picked) throw new BenchmarkError("invalid", picked.error, 400);
const b = ab ? await endpointFor(input.endpointBId!, "Endpoint B") : null;
if (b && b.probe.models.length && !b.probe.models.includes(picked.model)) {
throw new BenchmarkError("invalid", `Endpoint B doesn't serve "${picked.model}". An A/B sends the same model name to both servers.`, 400);
}
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind,
endpointId: a.e.id,
endpointBId: b?.e.id ?? null,
modelId: await libraryModelId(picked.model),
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: snapshotOf(a.e, picked.model, a.probe),
snapshotB: b ? snapshotOf(b.e, picked.model, b.probe) : null,
})
.returning({ id: benchmarkRuns.id });
return row;
}
const listColumns = {
id: benchmarkRuns.id,
endpointId: benchmarkRuns.endpointId,
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,
endpointBId: benchmarkRuns.endpointBId,
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
quality: benchmarkRuns.quality,
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: { endpointId?: string; modelId?: string } = {}) {
return db()
.select(listColumns)
.from(benchmarkRuns)
.where(
and(
filter.endpointId ? or(eq(benchmarkRuns.endpointId, filter.endpointId), eq(benchmarkRuns.endpointBId, filter.endpointId)) : 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 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") {
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));
}
}
/** 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 }));
}