import "server-only"; import { rm } from "node:fs/promises"; import { and, asc, desc, eq, gt, inArray, or, sql } from "drizzle-orm"; import { z } from "zod"; import { runDir } from "@/lib/benchmark-paths"; import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot"; import { headline } from "@/lib/benchmark-view"; 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; /** 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; } /** Everything about a run: the detail and compare pages, results downloads. */ const runColumns = { 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, }; /** * What lists show: no A/B series, eval items, hardware facts or descriptions (lists got all of it, * ~13× what they use, re-fetched every 3 s while a run was active). The summary is read only to * compute the headline numbers. */ const listColumns = { id: benchmarkRuns.id, endpointId: benchmarkRuns.endpointId, endpointBId: benchmarkRuns.endpointBId, modelId: benchmarkRuns.modelId, label: benchmarkRuns.label, kind: benchmarkRuns.kind, settings: benchmarkRuns.settings, snapshot: benchmarkRuns.snapshot, state: benchmarkRuns.state, phase: benchmarkRuns.phase, cancelRequestedAt: benchmarkRuns.cancelRequestedAt, startedAt: benchmarkRuns.startedAt, finishedAt: benchmarkRuns.finishedAt, hasReport: benchmarkRuns.hasReport, createdAt: benchmarkRuns.createdAt, summary: benchmarkRuns.summary, qualityScore: sql`json_extract(${benchmarkRuns.quality}, '$.score')`, }; export type BenchmarkRow = NonNullable>>; export type BenchmarkListRow = Awaited>[number]; /** Runs for lists, newest first; `endpointId` matches either side of an A/B. */ export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}, options: { limit?: number } = {}) { let query = 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)) .$dynamic(); if (options.limit) query = query.limit(options.limit); return (await query).map(({ summary, ...r }) => ({ ...r, headline: headline(summary) })); } export async function getBenchmark(id: string) { const [row] = await db().select(runColumns).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(runColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids)); const byId = new Map(rows.map((r) => [r.id, r])); return ids.map((id) => byId.get(id)).filter((r) => r != null); } async function runState(id: string) { return db().query.benchmarkRuns.findFirst({ columns: { id: true, state: true }, where: eq(benchmarkRuns.id, id) }); } /** Queued runs are cancelled right away; a running one is stopped by the worker. */ export async function cancelBenchmark(id: string) { const run = await runState(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 = {}; 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 runState(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 })); }