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 } 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(), }); export type BenchmarkInput = z.infer; /** 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. */ export async function createBenchmark(input: BenchmarkInput) { const ab = !!input.deploymentBId; 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: ab ? "ab" : "run", deploymentId: a.id, deploymentBId: b?.id ?? null, modelId: a.modelId, label: input.label || null, description: input.description || null, settings: { 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, }) .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, sweepId: benchmarkRuns.sweepId, meta: benchmarkRuns.meta, metaB: benchmarkRuns.metaB, system: benchmarkRuns.system, description: benchmarkRuns.description, createdAt: benchmarkRuns.createdAt, }; export type BenchmarkRow = Awaited>[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 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, "queued"))); } 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 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 })); }