import "server-only"; import { and, desc, eq, or } from "drizzle-orm"; import { z } from "zod"; import { checkRun, TuningError, type TuningGuardrails } from "@/lib/agent-tuning"; 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 { db } from "@/lib/db/client"; import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks"; import { getDeployment } from "@/lib/deployments"; import { getTuning } from "@/lib/settings"; import { MAX_SWEEP_PARAMS, splitValues } from "@/lib/sweep"; import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps"; // Benchmark runs, A/B runs and sweeps through the API: on the token's own deployments only, one at a // time across all agents, with time limits and (by default) the user's approval. export const AgentRunBody = z .object({ kind: z.enum(["run", "ab"]).default("run"), deploymentId: z.string().min(1), /** A/B: the second deployment (same model). */ deploymentBId: z.string().min(1).optional(), label: z.string().trim().max(120).optional(), description: z.string().trim().max(4000).optional(), /** quick: 5 passes, a smoke check; full (default): 20 passes, comparable. */ quick: z.boolean().default(false), passes: z.number().int().min(1).max(200).optional(), 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(), }) .strict(); export const AgentSweepBody = z .object({ baseDeploymentId: z.string().min(1), label: z.string().trim().max(80).optional(), /** One or two settings with their values, e.g. [{ key: "kvCache", values: ["f16", "q8_0"] }]. */ params: z .array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }).strict()) .min(1) .max(MAX_SWEEP_PARAMS), quick: z.boolean().default(true), passes: z.number().int().min(1).max(200).optional(), phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]), }) .strict(); /** A deployment this token may benchmark: its own, not protected, running. */ async function benchmarkable(token: TokenIdentity, id: string, role: string) { const d = await getDeployment(id); if (!d) throw new TuningError("not_owner", `${role} not found.`, 404); if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't benchmark it.`, 403); if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only benchmark their own deployments. Deploy the model yourself (POST /api/v1/deployments).`, 403); return d; } const requested = (token: TokenIdentity) => ({ tokenId: token.id, name: token.name }); /** Queue a run or A/B against the token's own running deployment(s). */ export async function requestRun(token: TokenIdentity, body: z.infer, g?: TuningGuardrails) { const guard = g ?? (await getTuning()); await benchmarkable(token, body.deploymentId, body.kind === "ab" ? "Deployment A" : "The deployment"); if (body.kind === "ab") { if (!body.deploymentBId) throw new TuningError("not_owner", "An A/B needs deploymentBId (your second deployment of the same model).", 400); await benchmarkable(token, body.deploymentBId, "Deployment B"); } checkRun(await gpuLoad()); const pending = guard.approvalMode === "approve"; const row = await createBenchmark( BenchmarkBody.parse({ deploymentId: body.deploymentId, deploymentBId: body.kind === "ab" ? body.deploymentBId : null, label: body.label ?? null, description: body.description ?? null, quick: body.quick, passes: body.passes ?? null, phases: body.phases, mdePct: body.mdePct ?? null, maxPairs: body.maxPairs ?? null, }), { requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 }, ); return { id: row.id, state: pending ? "pending_approval" : "queued", timeLimitMinutes: guard.maxRunMinutes }; } /** Queue a sweep from the token's own base deployment (each variant deploys and is removed again). */ export async function requestSweep(token: TokenIdentity, body: z.infer, g?: TuningGuardrails) { const guard = g ?? (await getTuning()); const base = await benchmarkable(token, body.baseDeploymentId, "The base deployment"); const load = await gpuLoad(); checkRun(load); // Each variant starts its own deployment; an agent deployment still running would share the GPU. if (load.agentDeployments > 0) { throw new TuningError("gpu_busy", "an agent deployment is still running or waiting to start; a sweep deploys each variant itself. Stop yours first (POST /api/v1/deployments/{id}/stop).", 429); } const count = body.params.reduce((n, p) => n * splitValues(p.values.join(",")).length, 1); if (count > guard.maxSweepVariants) { throw new TuningError("too_many_variants", `That's ${count} variants; agents may run at most ${guard.maxSweepVariants} per sweep. Vary fewer values.`); } 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 }, { requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxSweepMinutes * 60, runTimeLimitS: guard.maxRunMinutes * 60, maxVariants: guard.maxSweepVariants, }, ); return { id: row.id, state: pending ? "pending_approval" : "queued", variants: count, timeLimitMinutes: guard.maxSweepMinutes }; } /** Cancel a run or sweep this token asked for. */ export async function ownRun(token: TokenIdentity, id: string) { const run = await getBenchmark(id); if (!run) throw new TuningError("not_owner", "No benchmark run with this id.", 404); if (run.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This run wasn't started by this token; agents only cancel their own runs.", 403); return run; } export async function ownSweep(token: TokenIdentity, id: string) { const s = await getSweep(id); if (!s) throw new TuningError("not_owner", "No sweep with this id.", 404); if (s.sweep.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This sweep wasn't started by this token; agents only cancel their own sweeps.", 403); return s; } const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10); /** Headline numbers + the setup (section 1 metadata) as key/value. */ function compact(summary: BenchmarkSummary | null, meta: RunMeta | null) { const h = headline(summary); return { headline: { decodeTps: r1(h.decode), prefillTps: r1(h.prefill?.tps), prefillDepth: h.prefill?.depth ?? null, ttftMs: r1(h.ttftMs), peakParallelTps: r1(h.peak?.tps), peakParallelLevel: h.peak?.level ?? null, }, setup: meta ? Object.fromEntries(metaRows(meta).map((r) => [r.key, r.value])) : null, }; } const RUN_NEXT: Record = { pending_approval: "Waiting for the user's approval in Kaname. Don't retry or poll; tell the user and stop.", queued: "Queued (one benchmark at a time). GET it with ?wait=900 instead of polling.", running: "Running. GET it with ?wait=900 instead of polling.", completed: "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…", failed: "Failed; see error. Fix the cause before trying again.", cancelled: "Cancelled or rejected by the user (or by you).", }; export const runSettled = (state: string) => state !== "queued" && state !== "running"; /** Compact run state: headline numbers, setup, resources; the full summary with `full`. */ export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) { const res = r.resources; return { id: r.id, kind: r.kind, state: r.state, label: r.label, description: r.description, deploymentId: r.deploymentId, deploymentBId: r.deploymentBId, deployment: r.snapshot.deploymentName, requestedBy: r.requestedBy, mine: r.requestedByTokenId === token.id, settings: r.settings, phase: r.phase, error: r.error, 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), ...(r.kind === "ab" && r.ab ? { ab: { pairs: r.ab.pairs, verdict: r.ab.decode_tps.verdict, decodeDiffPct: r1(r.ab.decode_tps.pct_diff), ciPct: [r1(r.ab.decode_tps.ci_low_pct), r1(r.ab.decode_tps.ci_high_pct)], significant: r.ab.decode_tps.significant, setupB: r.metaB ? Object.fromEntries(metaRows(r.metaB).map((x) => [x.key, x.value])) : null, }, } : {}), resources: res ? { cpuAvgCores: r1(res.containers[0]?.cpuAvg), ramPeakBytes: res.containers[0]?.memPeakBytes ?? null, gpus: res.gpus.map((g) => ({ name: g.name, vramPeakMb: g.vramPeakMb, vramTotalMb: g.vramTotalMb, utilAvg: r1(g.utilAvg), powerAvgW: r1(g.powerAvgW), tempPeakC: r1(g.tempPeakC) })), } : null, next: RUN_NEXT[r.state] ?? null, ...(full ? { summary: r.summary } : {}), }; } export function sweepView(data: NonNullable>>, token: TokenIdentity) { const s: SweepRow = data.sweep; return { id: s.id, state: s.state, label: s.label, baseDeploymentId: s.baseDeploymentId, params: s.params, settings: s.settings, requestedBy: s.requestedBy, mine: s.requestedByTokenId === token.id, error: s.error, 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) }; }), startedAt: s.startedAt?.toISOString() ?? null, finishedAt: s.finishedAt?.toISOString() ?? null, next: s.state === "pending_approval" ? RUN_NEXT.pending_approval : s.state === "queued" || s.state === "running" ? "Running variant by variant. GET it with ?wait=900 instead of polling." : null, }; } /** Runs side by side: headline numbers and the setup keys whose values differ. */ export async function compareRuns(ids: string[], token: TokenIdentity) { 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 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, }; } /** Recent runs, newest first, optionally of one deployment or token. */ export async function listRunsFor(filter: { deploymentId?: string; requestedBy?: string; limit: number }) { const rows = await db() .select({ id: benchmarkRuns.id }) .from(benchmarkRuns) .where( and( filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined, filter.requestedBy ? eq(benchmarkRuns.requestedBy, filter.requestedBy.toLowerCase()) : undefined, ), ) .orderBy(desc(benchmarkRuns.createdAt)) .limit(filter.limit); return getBenchmarks(rows.map((r) => r.id)); }