"use client"; import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { toast } from "sonner"; import { BarChart } from "@/components/bar-chart"; import { BenchmarkStateBadge } from "@/components/benchmark-state"; import { Button, buttonVariants } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { AgentApprovalBar } from "@/components/approval-bar"; import { RequestedByBadge } from "@/components/requested-by-badge"; import { metaRows } from "@/lib/benchmark-meta"; import { describeSettings, headline } from "@/lib/benchmark-view"; import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema"; import { formatBytes } from "@/lib/format"; import { cn } from "@/lib/utils"; type Sweep = typeof benchmarkSweeps.$inferSelect; type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null; meta: RunMeta | null; quality: QualityResult | null; }; export type SweepData = { sweep: Sweep; runs: Run[] }; const VARIANT_STATE: Record = { pending: "Waiting", deploying: "Deploying", benchmarking: "Benchmarking", evaluating: "Quality eval", done: "Done", failed: "Failed", skipped: "Skipped", }; type Row = { v: SweepVariant; run: Run | null; decode: number | null; ttft: number | null; prefill: number | null; peak: number | null; cpu: number | null; ram: number | null; vram: number | null; power: number | null; temp: number | null; quality: number | null; }; function rowsOf(data: SweepData): Row[] { return data.sweep.variants.map((v) => { const run = data.runs.find((r) => r.id === v.runId) ?? null; const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null; const h = headline(run?.summary ?? null); const c = run?.resources?.containers.find((x) => x.side === "a"); const g = run?.resources?.gpus ?? []; return { v, run, decode: h.decode, ttft: h.ttftMs, prefill: h.prefill?.tps ?? null, peak: h.peak?.tps ?? null, cpu: c?.cpuAvg ?? null, ram: c?.memPeakBytes ?? null, vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null, power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null, temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null, quality: ev?.quality?.score ?? null, }; }); } /** * Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by * every variant go above the table, the ones that differ become columns. */ function setupOf(rows: Row[]) { const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null)); const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()]; const recorded = per.filter((x) => x != null); const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null; const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1); const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null })); return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value }; } /** Best value per column (higher or lower is better), to set it in bold. */ function best(rows: Row[], key: keyof Row, higher: boolean): number | null { const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number"); if (vals.length < 2) return null; return higher ? Math.max(...vals) : Math.min(...vals); } export function SweepDetail({ initial }: { initial: SweepData }) { const router = useRouter(); const [data, setData] = useState(initial); const [busy, setBusy] = useState(false); const { sweep } = data; const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running"; useEffect(() => { if (!active) return; const t = setInterval(async () => { const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null); if (res?.ok) setData(await res.json()); }, 3_000); return () => clearInterval(t); }, [sweep.id, active]); async function act(path: string, method: string, done: () => void) { setBusy(true); try { const res = await fetch(path, { method }); const json = await res.json().catch(() => ({})); if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`); done(); } finally { setBusy(false); } } const rows = rowsOf(data); const setup = setupOf(rows); const finished = rows.filter((r) => r.decode != null); const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed")); const bestOf = { decode: best(rows, "decode", true), ttft: best(rows, "ttft", false), prefill: best(rows, "prefill", true), peak: best(rows, "peak", true), cpu: best(rows, "cpu", false), ram: best(rows, "ram", false), vram: best(rows, "vram", false), power: best(rows, "power", false), temp: best(rows, "temp", false), quality: best(rows, "quality", true), }; const hasQuality = !!sweep.settings.quality; const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => ( {v != null ? fmt(v) : "—"} ); const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length; return (

{sweep.label ?? `Sweep of ${sweep.base.name}`}

{sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "} {sweep.baseDeploymentId ? ( {sweep.base.name} ) : ( sweep.base.name )}

{runIds.length >= 2 && ( Compare in detail )} {active ? ( ) : ( )}
{active && (

{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.

)} {sweep.state === "pending_approval" && ( `${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`} base={`/api/sweeps/${sweep.id}`} /> )} {sweep.error &&

{sweep.error}

} {finished.length > 0 && ( Generation speed by variant Single-stream decode, tokens per second (BetterBench combined score). Higher is better. ({ label: r.v.label, value: r.decode, valueLabel: r.decode!.toFixed(1), details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean), }))} /> )} Variants Best value per column in bold. Resource figures are averages/peaks over the run. {setup.shared.length > 0 && (

{setup.shared .filter((x) => x.value) .map((x) => `${x.label}: ${x.value}`) .join(" · ")}

)}
{setup.columns.map((c) => ( ))} {hasQuality && } {rows.map((r, i) => ( {setup.columns.map((c) => ( ))} {cell(r.decode, bestOf.decode, (x) => x.toFixed(1))} {hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)} {cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))} {cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))} {cell(r.peak, bestOf.peak, (x) => x.toFixed(1))} {cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))} {cell(r.ram, bestOf.ram, (x) => formatBytes(x))} {cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)} {cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)} {cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)} ))}
Variant State {c.label} Decode t/sQualityTTFT ms Prefill t/s Peak t/s CPU cores Peak RAM Peak VRAM GPU power Peak temp
{r.v.runId ? ( {r.v.label} ) : ( r.v.label )} {VARIANT_STATE[r.v.state]} {r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""} {(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""} {setup.value(i, c.key) ?? "–"}
); }