Files
Kaname/src/lib/endpoints.test.ts
T
Claude 2e56351e96 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
2026-11-01 20:52:12 +00:00

167 lines
8.8 KiB
TypeScript

// Endpoints and queuing runs against them, on a temporary SQLite database with a fake server.
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import { eq } from "drizzle-orm";
const dir = mkdtempSync(join(tmpdir(), "kaname-endpoints-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.MODELS_DIR = join(dir, "models");
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
endpoints: typeof import("./endpoints");
benchmarks: typeof import("./benchmarks");
};
let M: Mods;
let server: Server;
let base = "";
const auth: (string | undefined)[] = [];
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
endpoints: await import("./endpoints"),
benchmarks: await import("./benchmarks"),
};
server = createServer((req, res) => {
auth.push(req.headers.authorization);
res.writeHead(req.url === "/v1/models" ? 200 : 404, { "Content-Type": "application/json" });
res.end(JSON.stringify(req.url === "/v1/models" ? { data: [{ id: "Qwen/Qwen3-8B", owned_by: "vllm" }, { id: "Qwen/Qwen3-0.6B", owned_by: "vllm" }] } : {}));
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => {
server.close();
// Windows keeps the open database file locked; the temp folder is cleaned up eventually anyway.
try {
rmSync(dir, { recursive: true, force: true });
} catch {}
});
describe("endpoints", () => {
it("never hands out the API key; edits keep, replace or remove it", async () => {
const e = await M.endpoints.createEndpoint({ name: "box", baseUrl: `${base}/v1/`, apiKey: "sk-secret", hardware: { gpuName: "RTX 4090", gpuCount: 1, vramGb: 24, cpu: "" } });
assert.equal(e.baseUrl, base);
assert.equal(e.hasApiKey, true);
assert.ok(!JSON.stringify(e).includes("sk-secret"));
assert.deepEqual(e.hardware, { gpuName: "RTX 4090", gpuCount: 1, vramGb: 24 }, "empty fields aren't stored");
assert.ok(!JSON.stringify(await M.endpoints.listEndpoints()).includes("sk-secret"));
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, hardware: {} });
const row = await M.db.db().query.endpoints.findFirst({ where: eq(M.schema.endpoints.id, e.id) });
assert.equal(row!.apiKey, "sk-secret", "left out: kept");
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, apiKey: "" });
assert.equal((await M.endpoints.getEndpoint(e.id))!.hasApiKey, false, '"": removed');
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, apiKey: "sk-secret" });
});
it("validates names, URLs and hardware notes", async () => {
await assert.rejects(M.endpoints.createEndpoint({ name: "box", baseUrl: base }), /already exists/);
await assert.rejects(M.endpoints.createEndpoint({ name: "x", baseUrl: "file:///etc" }), /http/);
await assert.rejects(M.endpoints.createEndpoint({ name: "y", baseUrl: base, hardware: { gpuCount: 0 } }), /gpuCount/);
await assert.rejects(M.endpoints.createEndpoint({ name: "z", baseUrl: base, hardware: { pcie: "very fast" } }), /Gen4 x16/);
});
it("tests a form's values without sending the stored key to another URL", async () => {
const [e] = await M.endpoints.listEndpoints();
auth.length = 0;
const p = await M.endpoints.testEndpoint(e.id);
assert.equal(p.ok, true);
assert.deepEqual(p.models, ["Qwen/Qwen3-8B", "Qwen/Qwen3-0.6B"]);
assert.equal(p.engine, "vllm");
assert.ok(auth.every((a) => a === "Bearer sk-secret"));
auth.length = 0;
await M.endpoints.testEndpoint(e.id, { name: "box", baseUrl: base.replace("127.0.0.1", "localhost") });
assert.ok(auth.length > 0 && auth.every((a) => a === undefined), "another URL doesn't get the stored key");
});
});
describe("queuing runs", () => {
it("needs a model when the server serves several, and records no URL or key", async () => {
const [e] = await M.endpoints.listEndpoints();
const body = { endpointId: e.id, quick: true, phases: [] };
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse(body)), /several models/);
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ ...body, model: "nope" })), /doesn't list "nope"/);
const { id } = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ ...body, model: "Qwen/Qwen3-8B" }));
const run = await M.benchmarks.getBenchmark(id);
assert.equal(run!.state, "queued");
assert.equal(run!.endpointId, e.id);
assert.deepEqual(run!.snapshot, {
type: "endpoint",
endpointName: "box",
model: "Qwen/Qwen3-8B",
engine: "vllm",
engineVersion: null,
contextSize: null,
slots: null,
hardware: {},
});
assert.ok(!JSON.stringify(run).includes(base) && !JSON.stringify(run).includes("sk-secret"));
await assert.rejects(M.endpoints.deleteEndpoint(e.id), /queued or running/);
await M.benchmarks.cancelBenchmark(id);
await M.endpoints.deleteEndpoint(e.id);
assert.equal((await M.benchmarks.getBenchmark(id))!.endpointId, null, "the run stays, unlinked");
});
it("refuses a run against a server that doesn't answer, and A/B between different models", async () => {
const down = await M.endpoints.createEndpoint({ name: "down", baseUrl: "http://127.0.0.1:9" });
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: down.id })), /Couldn't reach/);
const a = await M.endpoints.createEndpoint({ name: "a", baseUrl: base, model: "Qwen/Qwen3-8B" });
const b = await M.endpoints.createEndpoint({ name: "b", baseUrl: base });
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, endpointBId: a.id })), /two different/);
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, model: "other" })), /doesn't list/);
const ab = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, endpointBId: b.id }));
const run = await M.benchmarks.getBenchmark(ab.id);
assert.equal(run!.kind, "ab");
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");
});
});