Benchmarks: lean list queries

listBenchmarks() selected every column of every run, including the raw A/B
series, all quality eval items, hardware facts and descriptions, while lists
show only the snapshot, settings, headline numbers and the quality score. With
200 runs /api/benchmarks returned 732 KB, re-fetched every 3 s while a run was
active; the table used about 55 KB of it.

- listBenchmarks() returns lean rows: the headline numbers are computed on the
  server from the summary, the quality score comes from json_extract().
- The model page asks for 5 runs (it shows 5), the ⌘K index for 300.
- getBenchmark()/getBenchmarks() keep the full rows for detail and compare;
  cancel and delete only read the state.
- ListRow (lists) and RunRow (detail) are separate types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
Claude committed 2026-11-01 20:52:12 +00:00
1 parent 7239ba2692
commit 2e56351e96
10 files changed
+111 -34

No files matched your search

+3
View File
@@ -19,6 +19,9 @@ step 1 (Hugging Face downloader) is released as a minor version.
- **Lighter library page**: folders found in the models folder no longer bring their whole file - **Lighter library page**: folders found in the models folder no longer bring their whole file
list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and
filter counts are computed once per change instead of on every progress update. filter counts are computed once per change instead of on every progress update.
- **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K
search load only what they show (headline numbers, the quality score), not every run's full
results; the list refreshed every 3 s during a run now sends a fraction of the data.
## [0.16.0] - 2026-10-30 ## [0.16.0] - 2026-10-30
+4 -4
View File
@@ -26,7 +26,7 @@ import { ModelStatusBadge } from "@/components/model-status-badge";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format"; import { formatBytes, shortSha } from "@/lib/format";
import { listBenchmarks } from "@/lib/benchmarks"; import { listBenchmarks } from "@/lib/benchmarks";
import { headline, targetName } from "@/lib/benchmark-view"; import { targetName } from "@/lib/benchmark-view";
import { fetchModelCard } from "@/lib/hub/client"; import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata"; import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs"; import { listModelJobs } from "@/lib/jobs";
@@ -107,7 +107,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined), tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(), getWorkerStatus(),
listModelJobs(model.id, 1), listModelJobs(model.id, 1),
listBenchmarks({ modelId: model.id }), listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all
]); ]);
const update = const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha !hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
@@ -306,13 +306,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<SideCard title="Benchmarks" icon={GaugeIcon}> <SideCard title="Benchmarks" icon={GaugeIcon}>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{runs.slice(0, 5).map((r) => { {runs.slice(0, 5).map((r) => {
const h = headline(r.summary); const h = r.headline;
return ( return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted"> <Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col"> <span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span> <span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
<span className="truncate text-xs text-muted-foreground"> <span className="truncate text-xs text-muted-foreground">
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"} {r.kind === "eval" ? (r.qualityScore != null ? `quality ${r.qualityScore}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
</span> </span>
</span> </span>
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} /> <BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
+2 -2
View File
@@ -3,7 +3,7 @@ import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib
import { CONFIG_ROWS, targetName } from "@/lib/benchmark-view"; import { CONFIG_ROWS, targetName } from "@/lib/benchmark-view";
import type { PairedResult } from "@/lib/db/schema"; import type { PairedResult } from "@/lib/db/schema";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list"; import type { RunRow } from "../benchmark-list";
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`; const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
@@ -56,7 +56,7 @@ function Side({ label, name, value, unit }: { label: string; name: string; value
); );
} }
export function AbReport({ run }: { run: ListRow }) { export function AbReport({ run }: { run: RunRow }) {
const ab = run.ab; const ab = run.ab;
const a = run.snapshot; const a = run.snapshot;
const b = run.snapshotB; const b = run.snapshotB;
@@ -39,7 +39,7 @@ import {
modelName, modelName,
targetName, targetName,
} from "@/lib/benchmark-view"; } from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list"; import type { RunRow } from "../benchmark-list";
import { PageHero } from "@/components/hero/page-hero"; import { PageHero } from "@/components/hero/page-hero";
import { RunMetaCard } from "@/components/run-meta"; import { RunMetaCard } from "@/components/run-meta";
import { import {
@@ -68,7 +68,7 @@ function duration(a: string | null, b: string | null, now: number) {
: `${Math.round(s)} s`; : `${Math.round(s)} s`;
} }
export function BenchmarkDetail({ initial }: { initial: ListRow }) { export function BenchmarkDetail({ initial }: { initial: RunRow }) {
const router = useRouter(); const router = useRouter();
const [r, setR] = useState(initial); const [r, setR] = useState(initial);
const [now, setNow] = useState(() => Date.now()); const [now, setNow] = useState(() => Date.now());
@@ -7,7 +7,7 @@ import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportS
import { configChips, engineName, modelName } from "@/lib/benchmark-view"; import { configChips, engineName, modelName } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema"; import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list"; import type { RunRow } from "../benchmark-list";
function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) { function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
return ( return (
@@ -54,7 +54,7 @@ const date = (iso: string | null | undefined) =>
: ""; : "";
/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */ /** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
export function BenchmarkReport({ run }: { run: ListRow }) { export function BenchmarkReport({ run }: { run: RunRow }) {
const sum = run.summary; const sum = run.summary;
if (!sum) return null; if (!sum) return null;
const s = run.snapshot; const s = run.snapshot;
+11 -8
View File
@@ -17,20 +17,23 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import type { BenchmarkRow } from "@/lib/benchmarks"; import type { BenchmarkListRow, BenchmarkRow } from "@/lib/benchmarks";
import { configChips, describeSettings, engineName, headline, modelName, targetName } from "@/lib/benchmark-view"; import { configChips, describeSettings, engineName, modelName, targetName } from "@/lib/benchmark-view";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export type ListRow = Omit< /** A row as it arrives in the browser (dates as ISO strings). */
BenchmarkRow, type Serialized<T> = Omit<T, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
> & {
createdAt: string; createdAt: string;
startedAt: string | null; startedAt: string | null;
finishedAt: string | null; finishedAt: string | null;
cancelRequestedAt: string | null; cancelRequestedAt: string | null;
}; };
/** A run in a list: headline numbers only. */
export type ListRow = Serialized<BenchmarkListRow>;
/** A run with everything (detail page). */
export type RunRow = Serialized<BenchmarkRow>;
const MAX_COMPARE = 16; const MAX_COMPARE = 16;
const fmt = (v: number | null | undefined, digits = 1) => const fmt = (v: number | null | undefined, digits = 1) =>
v == null ? "–" : v.toFixed(digits); v == null ? "–" : v.toFixed(digits);
@@ -165,7 +168,7 @@ export function BenchmarkList({
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{shown.map((r) => { {shown.map((r) => {
const h = headline(r.summary); const h = r.headline;
const s = r.snapshot; const s = r.snapshot;
return ( return (
<TableRow <TableRow
@@ -214,7 +217,7 @@ export function BenchmarkList({
</TableCell> </TableCell>
<TableCell className="text-right font-medium tabular-nums"> <TableCell className="text-right font-medium tabular-nums">
{r.kind === "eval" ? ( {r.kind === "eval" ? (
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span> <span title="Quality eval score">{r.qualityScore != null ? `${r.qualityScore}% quality` : "–"}</span>
) : ( ) : (
fmt(h.decode) fmt(h.decode)
)} )}
+2 -3
View File
@@ -5,7 +5,6 @@ import { buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ENGINE_LABEL } from "@/lib/benchmark-meta"; import { ENGINE_LABEL } from "@/lib/benchmark-meta";
import { headline } from "@/lib/benchmark-view";
import { listBenchmarks } from "@/lib/benchmarks"; import { listBenchmarks } from "@/lib/benchmarks";
import { listEndpoints } from "@/lib/endpoints"; import { listEndpoints } from "@/lib/endpoints";
import { PageHero } from "@/components/hero/page-hero"; import { PageHero } from "@/components/hero/page-hero";
@@ -21,8 +20,8 @@ export default async function EndpointsPage() {
for (const r of runs) { for (const r of runs) {
if (!r.endpointId || r.state !== "completed") continue; if (!r.endpointId || r.state !== "completed") continue;
const cur = latest.get(r.endpointId) ?? { decode: null, quality: null }; const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode; if (r.kind === "run" && cur.decode == null) cur.decode = r.headline.decode;
if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null; if (r.kind === "eval" && cur.quality == null) cur.quality = r.qualityScore;
latest.set(r.endpointId, cur); latest.set(r.endpointId, cur);
} }
+2 -2
View File
@@ -10,11 +10,11 @@ export const dynamic = "force-dynamic";
/** Everything the ⌘K palette can jump to, compact (it filters in the browser). */ /** Everything the ⌘K palette can jump to, compact (it filters in the browser). */
export const GET = withAuth(async () => { export const GET = withAuth(async () => {
const [models, endpoints, runs, tags] = await Promise.all([listLibrary(), listEndpoints(), listBenchmarks(), listTags()]); const [models, endpoints, runs, tags] = await Promise.all([listLibrary(), listEndpoints(), listBenchmarks({}, { limit: 300 }), listTags()]);
return NextResponse.json({ return NextResponse.json({
models: models.map((m) => ({ id: m.id, repoId: m.repoId, quants: m.quants, status: m.status, tags: m.tags.map((t) => t.name) })), models: models.map((m) => ({ id: m.id, repoId: m.repoId, quants: m.quants, status: m.status, tags: m.tags.map((t) => t.name) })),
endpoints: endpoints.map((e) => ({ id: e.id, name: e.name, model: e.model, engine: e.engine ?? e.probe?.engine ?? null })), endpoints: endpoints.map((e) => ({ id: e.id, name: e.name, model: e.model, engine: e.engine ?? e.probe?.engine ?? null })),
benchmarks: runs.slice(0, 300).map((r) => ({ benchmarks: runs.map((r) => ({
id: r.id, id: r.id,
label: r.label, label: r.label,
kind: r.kind, kind: r.kind,
+48 -11
View File
@@ -1,9 +1,10 @@
import "server-only"; import "server-only";
import { rm } from "node:fs/promises"; import { rm } from "node:fs/promises";
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm"; import { and, asc, desc, eq, gt, inArray, or, sql } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths"; import { runDir } from "@/lib/benchmark-paths";
import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot"; import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot";
import { headline } from "@/lib/benchmark-view";
import { db } from "@/lib/db/client"; import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema"; import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema";
import { probeEndpoint } from "@/lib/endpoint-probe"; import { probeEndpoint } from "@/lib/endpoint-probe";
@@ -95,7 +96,8 @@ export async function createBenchmark(input: BenchmarkInput) {
return row; return row;
} }
const listColumns = { /** Everything about a run: the detail and compare pages, results downloads. */
const runColumns = {
id: benchmarkRuns.id, id: benchmarkRuns.id,
endpointId: benchmarkRuns.endpointId, endpointId: benchmarkRuns.endpointId,
modelId: benchmarkRuns.modelId, modelId: benchmarkRuns.modelId,
@@ -123,10 +125,37 @@ const listColumns = {
createdAt: benchmarkRuns.createdAt, createdAt: benchmarkRuns.createdAt,
}; };
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number]; /**
* 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<number | null>`json_extract(${benchmarkRuns.quality}, '$.score')`,
};
export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}) { export type BenchmarkRow = NonNullable<Awaited<ReturnType<typeof getBenchmark>>>;
return db() export type BenchmarkListRow = Awaited<ReturnType<typeof listBenchmarks>>[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) .select(listColumns)
.from(benchmarkRuns) .from(benchmarkRuns)
.where( .where(
@@ -135,23 +164,31 @@ export async function listBenchmarks(filter: { endpointId?: string; modelId?: st
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined, filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
), ),
) )
.orderBy(desc(benchmarkRuns.createdAt)); .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) { export async function getBenchmark(id: string) {
const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id)); const [row] = await db().select(runColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
return row ?? null; return row ?? null;
} }
export async function getBenchmarks(ids: string[]) { export async function getBenchmarks(ids: string[]) {
if (ids.length === 0) return []; if (ids.length === 0) return [];
const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids)); const rows = await db().select(runColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null); 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. */ /** Queued runs are cancelled right away; a running one is stopped by the worker. */
export async function cancelBenchmark(id: string) { export async function cancelBenchmark(id: string) {
const run = await getBenchmark(id); const run = await runState(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404); if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "queued") { 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))); await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
@@ -172,7 +209,7 @@ export async function updateBenchmark(id: string, patch: { label?: string | null
/** Deletes the run, its log and its files. Cancel a running one first. */ /** Deletes the run, its log and its files. Cancel a running one first. */
export async function deleteBenchmark(id: string) { export async function deleteBenchmark(id: string) {
const run = await getBenchmark(id); const run = await runState(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404); 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); 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(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
+35
View File
@@ -129,3 +129,38 @@ describe("queuing runs", () => {
assert.equal(run!.snapshotB && "model" in run!.snapshotB ? run!.snapshotB.model : null, "Qwen/Qwen3-8B"); assert.equal(run!.snapshotB && "model" in run!.snapshotB ? run!.snapshotB.model : null, "Qwen/Qwen3-8B");
}); });
}); });
describe("listing runs", () => {
it("lists headline numbers and the quality score, not the heavy results", async () => {
const { benchmarkRuns } = M.schema;
const snapshot = { type: "endpoint" as const, endpointName: "x", model: "m", engine: null, engineVersion: null, contextSize: null, hardware: {} };
const settings = { quick: false, passes: null, warmup: null, phases: [] };
const summary = {
v: 2,
combined: { decode: 42.5, ttft_p50: 120, itl_low1: null, update_p50: null, update_p99: null },
single: [],
prefill: [{ target_depth: 4000, skipped: false, pp_med: 900 }],
concurrency: [{ level: 4, ok: 4, requests: 4, aggregate_tps: 150, ttft_p50: null, ttft_p99: null, decode_med: null }],
phases: [],
cacheHits: 0,
betterbenchVersion: "0.6.1",
corpusVersion: "v1",
passes: null,
quick: false,
};
const quality = { evalSet: "v1", score: 71, sections: [], items: [{ section: "tools" as const, id: "t1", pass: true }], config: { temperature: 0, seed: 1, thinking: false, contextTokens: null } };
await M.db.db().insert(benchmarkRuns).values([
{ kind: "run", state: "completed", settings, snapshot, summary, createdAt: new Date(Date.now() + 1000) },
{ kind: "eval", state: "completed", settings, snapshot, quality, createdAt: new Date(Date.now() + 2000) },
]);
const rows = await M.benchmarks.listBenchmarks();
const evalRow = rows.find((r) => r.kind === "eval")!;
const runRow = rows.find((r) => r.kind === "run" && r.headline.decode != null)!;
assert.equal(evalRow.qualityScore, 71);
assert.deepEqual(runRow.headline, { decode: 42.5, ttftMs: 120, prefill: { tps: 900, depth: 4000 }, peak: { tps: 150, level: 4 } });
for (const r of rows) for (const k of ["summary", "quality", "ab", "meta", "metaB", "system", "description", "snapshotB"]) assert.ok(!(k in r), k);
const [newest] = await M.benchmarks.listBenchmarks({}, { limit: 1 });
assert.equal(newest.id, evalRow.id, "newest first, limited");
assert.equal((await M.benchmarks.getBenchmark(evalRow.id))!.quality?.items.length, 1, "the detail still has everything");
});
});