Release 0.14.0: quality eval
Release / release (push) Successful in 3m17s

A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-21 15:24:36 +02:00
1 parent 716bd8f2f0
commit 6b67c653b5
33 files changed
+3822 -79

No files matched your search

+37 -10
View File
@@ -6,7 +6,7 @@ import { gpuLoad } from "@/lib/agent-deployments";
import type { TokenIdentity } from "@/lib/api-tokens";
import { metaRows } from "@/lib/benchmark-meta";
import { headline } from "@/lib/benchmark-view";
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, type RunMeta } from "@/lib/db/schema";
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
import { db } from "@/lib/db/client";
import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
@@ -19,7 +19,8 @@ import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
export const AgentRunBody = z
.object({
kind: z.enum(["run", "ab"]).default("run"),
/** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
kind: z.enum(["run", "ab", "eval"]).default("run"),
deploymentId: z.string().min(1),
/** A/B: the second deployment (same model). */
deploymentBId: z.string().min(1).optional(),
@@ -31,6 +32,8 @@ export const AgentRunBody = z
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
mdePct: z.number().min(0.1).max(50).optional(),
maxPairs: z.number().int().min(12).max(2000).optional(),
/** eval: which sections (default all). */
sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
})
.strict();
@@ -46,6 +49,8 @@ export const AgentSweepBody = z
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant. */
quality: z.boolean().default(false),
})
.strict();
@@ -81,6 +86,8 @@ export async function requestRun(token: TokenIdentity, body: z.infer<typeof Agen
phases: body.phases,
mdePct: body.mdePct ?? null,
maxPairs: body.maxPairs ?? null,
kind: body.kind,
evalSections: body.sections,
}),
{ requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
);
@@ -103,7 +110,7 @@ export async function requestSweep(token: TokenIdentity, body: z.infer<typeof Ag
}
const pending = guard.approvalMode === "approve";
const row = await createSweep(
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases },
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
{
requestedBy: requested(token),
pendingApproval: pending,
@@ -132,10 +139,21 @@ export async function ownSweep(token: TokenIdentity, id: string) {
const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
/** The quality eval in short: overall score and per section. */
export function qualityView(q: QualityResult | null | undefined) {
if (!q) return null;
return {
evalSet: q.evalSet,
score: q.score,
sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
};
}
/** Headline numbers + the setup (section 1 metadata) as key/value. */
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null) {
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
const h = headline(summary);
return {
...(quality ? { quality: qualityView(quality) } : {}),
headline: {
decodeTps: r1(h.decode),
prefillTps: r1(h.prefill?.tps),
@@ -179,7 +197,8 @@ export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
...compact(r.summary, r.meta),
...compact(r.summary, r.meta, r.quality),
...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
...(r.kind === "ab" && r.ab
? {
ab: {
@@ -219,7 +238,16 @@ export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>
timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
variants: s.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId);
return { label: v.label, overrides: v.overrides, state: v.state, runId: v.runId ?? null, error: v.error ?? null, ...compact(run?.summary ?? null, run?.meta ?? null) };
const ev = data.runs.find((r) => r.id === v.evalRunId);
return {
label: v.label,
overrides: v.overrides,
state: v.state,
runId: v.runId ?? null,
evalRunId: v.evalRunId ?? null,
error: v.error ?? null,
...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
};
}),
startedAt: s.startedAt?.toISOString() ?? null,
finishedAt: s.finishedAt?.toISOString() ?? null,
@@ -228,16 +256,15 @@ export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>
}
/** Runs side by side: headline numbers and the setup keys whose values differ. */
export async function compareRuns(ids: string[], token: TokenIdentity) {
export async function compareRuns(ids: string[]) {
const runs = await getBenchmarks(ids);
const rows = runs.map((r) => ({ id: r.id, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta) }));
const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
return {
runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms. Differences under ~2 % between separate runs are noise; use an A/B for small effects.",
tokenName: token.name,
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
};
}
+46
View File
@@ -533,3 +533,49 @@ describe("the index", () => {
assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
});
});
describe("quality eval through the API", () => {
it("requests an eval run on the token's own deployment and reads its score", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
assert.equal(row?.kind, "eval");
assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
await M.db
.db()
.update(M.schema.benchmarkRuns)
.set({
state: "completed",
quality: {
evalSet: "kaname-eval-1",
score: 75,
sections: [
{ section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
],
items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
},
})
.where(eq(M.schema.benchmarkRuns.id, r.body.id));
const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
assert.equal(full.body.failed[0].id, "timer-12");
});
it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
assert.equal(bad.status, 400);
await setState(d.body.id, "stopped");
const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(s.status, 201);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
assert.equal(row?.settings.quality, true);
});
});
+2
View File
@@ -70,6 +70,8 @@ export function configChips(s: BenchmarkSnapshot): string[] {
}
export function describeSettings(st: BenchmarkSettings): string {
// A quality eval's settings carry its sections (empty: all).
if (st.evalSections) return `quality eval · ${st.evalSections.length ? st.evalSections.join(", ") : "all sections"}`;
const passes = st.passes ?? (st.quick ? 5 : 20);
const phases = st.phases.length ? st.phases.join(", ") : "all phases";
return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
+20 -10
View File
@@ -5,7 +5,7 @@ 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";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
@@ -35,6 +35,10 @@ export const BenchmarkBody = z.object({
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
/** Set by sweeps. */
sweepId: z.string().nullable().optional(),
/** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
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>;
@@ -54,7 +58,9 @@ async function snapshotOf(deploymentId: string, role: string) {
export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
const ab = !!input.deploymentBId;
const kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
const ab = kind === "ab";
if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
if (b) {
@@ -66,19 +72,22 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind: ab ? "ab" : "run",
kind,
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 } : {}),
},
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: a.snapshot,
snapshotB: b?.snapshot ?? null,
sweepId: input.sweepId ?? null,
@@ -116,6 +125,7 @@ const listColumns = {
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
quality: benchmarkRuns.quality,
sweepId: benchmarkRuns.sweepId,
requestedBy: benchmarkRuns.requestedBy,
requestedByTokenId: benchmarkRuns.requestedByTokenId,
+31 -2
View File
@@ -703,9 +703,34 @@ export type BenchmarkSettings = {
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
mdePct?: number | null;
maxPairs?: number | null;
/** eval: which sections (empty: all). Sweeps: also run the quality eval for each variant. */
evalSections?: QualitySection[];
quality?: boolean;
};
export const BENCHMARK_KINDS = ["run", "ab"] as const;
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
export type QualityResult = {
/** The eval set's version; only results of the same version are comparable. */
evalSet: string;
score: number | null;
sections: {
section: QualitySection;
passed: number;
total: number;
score: number | null;
/** Why the section couldn't run (e.g. the server doesn't do tool calls); then it doesn't count. */
unsupported?: string | null;
seconds: number;
}[];
items: { section: QualitySection; id: string; pass: boolean; detail?: string | null }[];
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
};
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
@@ -945,6 +970,8 @@ export const benchmarkRuns = sqliteTable(
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** kind "eval": the quality eval's result. */
quality: text("quality", { mode: "json" }).$type<QualityResult>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Requested through the API: the token and its name at the time. */
@@ -1026,9 +1053,11 @@ export type SweepVariant = {
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
overrides: Record<string, unknown>;
label: string;
state: "pending" | "deploying" | "benchmarking" | "done" | "failed" | "skipped";
state: "pending" | "deploying" | "benchmarking" | "evaluating" | "done" | "failed" | "skipped";
deploymentId?: string | null;
runId?: string | null;
/** The quality eval run of this variant (sweeps with quality: true). */
evalRunId?: string | null;
error?: string | null;
};
+12
View File
@@ -0,0 +1,12 @@
// Labels for the quality eval's sections. Pure and small: safe for client components (the eval set
// itself stays in src/lib/quality.ts).
import type { QualitySection } from "@/lib/db/schema";
export const SECTION_LABEL: Record<QualitySection, string> = { tools: "Tool calling", coding: "Coding", retrieval: "Long-context retrieval" };
export const SECTION_HINT: Record<QualitySection, string> = {
tools: "12 requests: valid JSON, the right function and arguments",
coding: "8 short Python functions, checked by unit tests in a sandbox",
retrieval: "a code hidden at 3 depths in 3 text lengths up to the context size",
};
+135
View File
@@ -0,0 +1,135 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { describe, it } from "node:test";
import { argMatches, buildHaystack, EVAL_SET, extractCode, prng, retrievalCases, scoreNeedle, scoreToolCall, summarize, testProgram, toolDefs } from "./quality";
describe("eval set", () => {
it("tool items only use defined tools and expect one of their own", () => {
for (const item of EVAL_SET.tools.items) {
for (const t of item.tools) assert.ok(EVAL_SET.tools.tools[t], `${item.id}: unknown tool ${t}`);
assert.ok(item.tools.includes(item.expect.name), `${item.id}: expects ${item.expect.name}, not offered`);
const params = EVAL_SET.tools.tools[item.expect.name].parameters as { properties: Record<string, unknown> };
for (const k of Object.keys(item.expect.args)) assert.ok(params.properties[k], `${item.id}: ${k} isn't a parameter`);
}
assert.equal(EVAL_SET.tools.items.length, 12);
assert.equal(toolDefs(EVAL_SET.tools.items[0])[0].type, "function");
});
it("has unique ids", () => {
const ids = [...EVAL_SET.tools.items, ...EVAL_SET.coding.items].map((i) => i.id);
assert.equal(new Set(ids).size, ids.length);
});
// Reference solutions: the eval's own tests must accept a correct answer.
const python = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).status === 0);
const REFERENCE: Record<string, string> = {
"is-palindrome": "def is_palindrome(s):\n t = [c.lower() for c in s if c.isalnum()]\n return t == t[::-1]",
fizzbuzz:
"def fizzbuzz(n):\n return ['FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, n + 1)]",
"merge-intervals":
"def merge_intervals(intervals):\n out = []\n for s, e in sorted(intervals):\n if out and s <= out[-1][1]:\n out[-1][1] = max(out[-1][1], e)\n else:\n out.append([s, e])\n return out",
"word-count":
"import re\ndef word_count(text):\n d = {}\n for w in re.findall('[A-Za-z]+', text):\n d[w.lower()] = d.get(w.lower(), 0) + 1\n return d",
"roman-to-int":
"def roman_to_int(s):\n v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n n = 0\n for i, c in enumerate(s):\n n += -v[c] if i + 1 < len(s) and v[s[i + 1]] > v[c] else v[c]\n return n",
flatten: "def flatten(nested):\n out = []\n for x in nested:\n out.extend(flatten(x) if isinstance(x, list) else [x])\n return out",
"second-largest": "def second_largest(nums):\n u = sorted(set(nums))\n return u[-2] if len(u) > 1 else None",
"rle-encode":
"from itertools import groupby\ndef rle_encode(s):\n return ''.join(f'{k}{len(list(g))}' for k, g in groupby(s))",
};
it("coding tests pass for a correct solution and fail for a wrong one", { skip: !python && "no python here" }, () => {
for (const item of EVAL_SET.coding.items) {
const ok = spawnSync(python!, ["-I", "-c", testProgram(REFERENCE[item.id], item.tests)], { encoding: "utf8" });
assert.equal(ok.status, 0, `${item.id}: ${ok.stderr}`);
assert.match(ok.stdout, /KANAME-OK/);
const fname = item.prompt.split("(")[0];
const bad = spawnSync(python!, ["-I", "-c", testProgram(`def ${fname}(*a, **k):\n return None`, item.tests)], { encoding: "utf8" });
assert.notEqual(bad.status, 0, `${item.id}: a wrong answer passed`);
}
});
});
describe("tool call scoring", () => {
const expect = EVAL_SET.tools.items.find((i) => i.id === "calendar-budget")!.expect;
const call = (args: unknown, name = "create_calendar_event") => [{ name, arguments: typeof args === "string" ? args : JSON.stringify(args) }];
it("accepts the right function with matching arguments (case-insensitive, extra ones fine)", () => {
const r = scoreToolCall(call({ title: "Budget Review", date: "2026-11-03", time: "14:30", duration_minutes: 45, location: "x" }), expect);
assert.equal(r.pass, true);
assert.equal(scoreToolCall(call({ title: "budget review meeting", date: "2026-11-03", time: "14:30", duration_minutes: "45" }), expect).pass, true);
});
it("refuses invalid JSON, the wrong function, wrong or missing arguments, several calls, none", () => {
assert.match(scoreToolCall(call("{title: 'x'"), expect).detail, /invalid JSON/);
assert.match(scoreToolCall(call("[1]"), expect).detail, /JSON object/);
assert.match(scoreToolCall(call({}, "set_timer"), expect).detail, /called set_timer/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-04", time: "14:30", duration_minutes: 45 }), expect).detail, /wrong date/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-03", time: "14:30" }), expect).detail, /wrong duration_minutes=undefined/);
assert.match(scoreToolCall([...call({}), ...call({})], expect).detail, /2 tool calls/);
assert.equal(scoreToolCall([], expect).pass, false);
assert.equal(scoreToolCall(null, expect).pass, false);
});
it("matches the argument rules", () => {
assert.ok(argMatches("PDF", { oneOf: ["pdf", ".pdf"] }));
assert.ok(argMatches(" 17 * 23 ", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(!argMatches("17+23", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(argMatches(250.0, 250));
assert.ok(!argMatches(null, "x"));
});
});
describe("code extraction", () => {
it("takes the last python block, or bare code", () => {
assert.equal(extractCode("Here:\n```python\ndef a(): pass\n```\nand\n```py\ndef b(): pass\n```"), "def b(): pass");
assert.equal(extractCode("```\ndef c(): pass\n```"), "def c(): pass");
assert.equal(extractCode("def d():\n return 1"), "def d():\n return 1");
assert.equal(extractCode("I can't do that."), null);
});
});
describe("long-context retrieval", () => {
it("plans lengths × positions within the context, deterministic codes", () => {
const c = retrievalCases(32768);
assert.equal(c.length, 9);
assert.ok(c.every((x) => x.targetTokens <= 32768 - EVAL_SET.retrieval.reserveTokens));
assert.deepEqual(retrievalCases(32768), c);
assert.ok(c.every((x) => /^\d{6}$/.test(x.code)));
assert.equal(retrievalCases(600).length, 0, "too short for any haystack");
assert.equal(retrievalCases(1200).length, 6, "the 25 % length is under 256 tokens");
});
it("puts the needle at its depth and the question at the end", () => {
const [first, , last] = retrievalCases(16384);
for (const c of [first, last]) {
const text = buildHaystack(c, 4);
const at = text.indexOf(c.code) / text.length;
assert.ok(Math.abs(at - c.position) < 0.05, `needle at ${at}, wanted ${c.position}`);
assert.ok(text.trimEnd().endsWith("only."));
assert.ok(Math.abs(text.length / 4 - c.targetTokens) / c.targetTokens < 0.06);
}
assert.equal(buildHaystack(first, 4), buildHaystack(first, 4));
});
it("scores the answer by the six digits", () => {
const c = retrievalCases(8192)[0];
assert.equal(scoreNeedle(`The code is ${c.code}.`, c).pass, true);
assert.equal(scoreNeedle("123456", { ...c, code: "654321" }).pass, false);
const r = prng(1);
assert.equal(prng(1)(), r());
});
});
describe("score", () => {
it("averages the sections that ran", () => {
const s = summarize([
{ section: "tools", passed: 9, total: 12, score: null, seconds: 10 },
{ section: "coding", passed: 4, total: 8, score: null, seconds: 30 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "context unknown", seconds: 0 },
]);
assert.equal(s.score, 62.5);
assert.deepEqual(s.sections.map((x) => x.score), [75, 50, null]);
assert.equal(summarize([]).score, null);
});
});
+175
View File
@@ -0,0 +1,175 @@
// The quality eval: a small, deterministic check of what a deployment produces (not how fast), so
// launch options that change the output (quant, KV cache type, context, sampling bugs in a build)
// show up next to the speed numbers. Pure: the eval set, prompt building and scoring; the worker
// (src/worker/quality.ts) talks to the server and the code sandbox.
import type { QualityResult } from "@/lib/db/schema";
import coding from "@/evals/v1/coding.json";
import retrieval from "@/evals/v1/retrieval.json";
import tools from "@/evals/v1/tools.json";
/** Bump with any change to the eval set or the scoring: results are only comparable within a version. */
export const EVAL_SET_VERSION = "kaname-eval-1";
export const EVAL_SEED = 1;
export type ArgRule = string | number | boolean | { contains: string } | { oneOf: (string | number)[] } | { matches: string };
export type ToolItem = { id: string; tools: string[]; prompt: string; expect: { name: string; args: Record<string, ArgRule> } };
export type CodingItem = { id: string; prompt: string; tests: string[] };
export const EVAL_SET = {
version: EVAL_SET_VERSION,
tools: tools as unknown as { tools: Record<string, { description: string; parameters: Record<string, unknown> }>; items: ToolItem[] },
coding: coding as { instructions: string; items: CodingItem[] },
retrieval: retrieval as {
lengths: number[];
positions: number[];
reserveTokens: number;
seed: number;
needle: string;
question: string;
colors: string[];
filler: string[];
},
};
// --- tool calling ---------------------------------------------------------------------------
/** The OpenAI `tools` array for an item. */
export function toolDefs(item: ToolItem) {
return item.tools.map((name) => ({ type: "function" as const, function: { name, ...EVAL_SET.tools.tools[name] } }));
}
const norm = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : v);
/** One argument against its rule: strings case-insensitively, numbers by value. */
export function argMatches(value: unknown, rule: ArgRule): boolean {
if (value === undefined || value === null) return false;
if (typeof rule === "object") {
if ("contains" in rule) return typeof value === "string" && value.toLowerCase().includes(rule.contains.toLowerCase());
if ("oneOf" in rule) return rule.oneOf.some((r) => argMatches(value, r));
if ("matches" in rule) return typeof value === "string" && new RegExp(rule.matches, "i").test(value);
}
if (typeof rule === "number") return Number(value) === rule;
return norm(value) === norm(rule);
}
export type ToolCall = { name: string; arguments: string };
/**
* A tool call is right when there is exactly one, its arguments are valid JSON, the function is the
* expected one and every expected argument matches (extra arguments are fine).
*/
export function scoreToolCall(calls: ToolCall[] | null | undefined, expect: ToolItem["expect"]): { pass: boolean; detail: string } {
if (!calls || calls.length === 0) return { pass: false, detail: "no tool call" };
if (calls.length > 1) return { pass: false, detail: `${calls.length} tool calls, expected one` };
const [c] = calls;
let args: Record<string, unknown>;
try {
const parsed = JSON.parse(c.arguments || "{}");
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { pass: false, detail: "arguments aren't a JSON object" };
args = parsed as Record<string, unknown>;
} catch {
return { pass: false, detail: `invalid JSON arguments: ${c.arguments.slice(0, 120)}` };
}
if (c.name !== expect.name) return { pass: false, detail: `called ${c.name}, expected ${expect.name}` };
const wrong = Object.entries(expect.args).filter(([k, rule]) => !argMatches(args[k], rule));
if (wrong.length) return { pass: false, detail: `wrong ${wrong.map(([k]) => `${k}=${JSON.stringify(args[k])}`).join(", ")}` };
return { pass: true, detail: `${c.name}(${JSON.stringify(args)})` };
}
// --- coding -------------------------------------------------------------------------------
/** The last ```python block of a reply (or the only fenced block); null without one. */
export function extractCode(reply: string): string | null {
const blocks = [...reply.matchAll(/```(?:python|py)?[ \t]*\r?\n([\s\S]*?)```/gi)].map((m) => m[1]);
if (blocks.length) return blocks[blocks.length - 1].trim() || null;
// Some models answer with bare code.
return /^\s*(def|import|from)\s/m.test(reply) ? reply.trim() : null;
}
/** The program the sandbox runs: the model's code, then the tests; prints OK when all pass. */
export function testProgram(code: string, tests: string[]): string {
return `${code}\n\n# --- tests ---\n${tests.join("\n")}\nprint("KANAME-OK")\n`;
}
// --- long-context retrieval ---------------------------------------------------------------
/** A small, seeded PRNG (mulberry32): the haystacks are the same every run. */
export function prng(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export type NeedleCase = { id: string; targetTokens: number; position: number; color: string; code: string };
/** The cases for a context of `contextTokens`: each length × each needle position, deduplicated. */
export function retrievalCases(contextTokens: number): NeedleCase[] {
const r = EVAL_SET.retrieval;
const usable = Math.max(0, contextTokens - r.reserveTokens);
const rand = prng(r.seed);
const out: NeedleCase[] = [];
const seen = new Set<number>();
let i = 0;
for (const len of r.lengths) {
const target = Math.floor(usable * len);
if (target < 256 || seen.has(target)) continue;
seen.add(target);
for (const position of r.positions) {
out.push({
id: `${Math.round(target / 100) / 10}k@${Math.round(position * 100)}%`,
targetTokens: target,
position,
color: r.colors[i++ % r.colors.length],
code: String(100000 + Math.floor(rand() * 900000)),
});
}
}
return out;
}
/**
* The haystack for a case: filler sentences in a seeded order up to about `targetTokens` (measured
* with the server's own tokenizer as characters per token), the needle at `position`, then the
* question.
*/
export function buildHaystack(c: NeedleCase, charsPerToken: number): string {
const r = EVAL_SET.retrieval;
const rand = prng(r.seed + c.targetTokens);
const targetChars = Math.floor(c.targetTokens * charsPerToken * 0.97);
const parts: string[] = [];
let len = 0;
while (len < targetChars) {
const s = r.filler[Math.floor(rand() * r.filler.length)];
parts.push(s);
len += s.length + 1;
}
const needle = r.needle.replace("{color}", c.color).replace("{code}", c.code);
parts.splice(Math.round(parts.length * c.position), 0, needle);
return `${parts.join(" ")}\n\n${r.question.replace("{color}", c.color)}`;
}
/** Did the answer give the code (the six digits, anywhere)? */
export function scoreNeedle(answer: string, c: NeedleCase): { pass: boolean; detail: string } {
const found: string[] = answer.match(/\d{6}/g) ?? [];
return found.includes(c.code) ? { pass: true, detail: c.code } : { pass: false, detail: `expected ${c.code}, got ${JSON.stringify(answer.trim().slice(0, 80))}` };
}
// --- score --------------------------------------------------------------------------------
/** Section pass rates and the overall score (mean of the sections that could run), 0–100. */
export function summarize(
sections: QualityResult["sections"],
): Pick<QualityResult, "score" | "sections"> {
const counted = sections.filter((s) => !s.unsupported && s.total > 0);
const withScore = sections.map((s) => ({ ...s, score: !s.unsupported && s.total > 0 ? Math.round((s.passed / s.total) * 1000) / 10 : null }));
const score = counted.length ? Math.round((counted.reduce((n, s) => n + s.passed / s.total, 0) / counted.length) * 1000) / 10 : null;
return { score, sections: withScore };
}
export { SECTION_LABEL } from "@/lib/quality-view";
+15 -4
View File
@@ -28,6 +28,8 @@ export const SweepBody = z.object({
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).nullable().optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant (after its speed run). */
quality: z.boolean().default(false),
});
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
@@ -76,7 +78,7 @@ export async function createSweep(input: z.infer<typeof SweepBody>, agent?: Agen
// The variants' deployments must not publish ports or require a second copy of the base's port.
base: { name: base.name, runtimeId: base.runtimeId, modelId: base.modelId, options: base.options, cpus: base.cpus, memoryMb: base.memoryMb },
params: input.params,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases, quality: input.quality },
variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })),
...(agent
? {
@@ -101,10 +103,19 @@ export async function listSweeps(): Promise<SweepRow[]> {
export async function getSweep(id: string) {
const sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!sweep) return null;
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = sweep.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error, meta: benchmarkRuns.meta })
.select({
id: benchmarkRuns.id,
state: benchmarkRuns.state,
summary: benchmarkRuns.summary,
resources: benchmarkRuns.resources,
phase: benchmarkRuns.phase,
error: benchmarkRuns.error,
meta: benchmarkRuns.meta,
quality: benchmarkRuns.quality,
})
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
@@ -136,7 +147,7 @@ export async function deleteSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "running" || s.state === "queued") throw new SweepRequestError("busy", "Cancel the sweep first.", 409);
const runIds = s.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = s.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
if (runIds.length) {
await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds));
await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds));