import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { CHANNELS } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; import { enqueueVerdictBench, parseBenchVerdictsBody } from "yt-dlp-transcript-common/controller/benchVerdicts"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import { readBenchRun } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_benchVerdicts.test.ts" // // The `bench-verdicts` job (release 28 M7) end to end in this process: the // controller the route adapts, the ruled synthetic fact-check in a temp // article store, the synthetic recordings' cues on disk, the fake Anthropic // and ollama servers, a temp jobs dir, usage ledger and runs root. const RULED = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft/reports/ruled.report.json"); let tmp: string; let api: FakeAnthropic; let ol: FakeOllama; let paths: Paths; let gen: GenerationSettings; let root: string; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "bench-verdicts-")); api = await startFakeAnthropic(); ol = await startFakeOllama(); const keyFile = path.join(tmp, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); const report = JSON.parse(await readFile(RULED, "utf8")); await mkdir(path.join(tmp, "reports", report.id), { recursive: true }); await writeFile(path.join(tmp, "reports", report.id, "report.json"), JSON.stringify(report)); for (const ch of CHANNELS) { for (const r of ch.records) { const rec = path.join(tmp, "channels", ch.slug, "data", r.id); await mkdir(rec, { recursive: true }); await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues })); } } paths = { jobsDir: path.join(tmp, ".jobs"), articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, ".export-index"), channelsDir: path.join(tmp, "channels"), generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), ollamaUrl: ol.url, } as Paths; root = path.join(tmp, ".generation", "bench", "verdicts"); gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20 } }); }); after(async () => { await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const deps = (g: Partial = {}) => ({ paths, root, settings: () => ({ generation: { ...gen, ...g } }) }); test("the body: models required, the run id and reports checked, numbers as numbers", () => { assert.throws(() => parseBenchVerdictsBody({}), /"models" is a list/); assert.throws(() => parseBenchVerdictsBody({ models: [] }), /at least one model/); assert.throws(() => parseBenchVerdictsBody({ models: ["m"], run: "../x" }), /"run" is a run id/); assert.throws(() => parseBenchVerdictsBody({ models: ["m"], reports: ["Bad Id"] }), /"reports" is a list of article ids/); assert.throws(() => parseBenchVerdictsBody({ models: ["m"], window: "60" }), /"window" is a number/); assert.deepEqual(parseBenchVerdictsBody({ models: "a, b", maxUsd: 2, limit: 3 }), { models: ["a", "b"], maxUsd: 2, limit: 3 }); // Release 29 V1: the window mode and items-from. assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], windowMode: "turn" }), { models: ["q"], windowMode: "turn" }); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], windowMode: "line" }), /"windowMode" is "seconds" or "turn"/); assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28" }), { models: ["q"], itemsFrom: "vb-r28" }); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "../x" }), /"itemsFrom" is a run id/); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28", window: 30 }), /drop the window/); // Release 32 R8: dedupe is a boolean, off unless asked, never with items-from. assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], dedupe: true }), { models: ["q"], dedupe: true }); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], dedupe: "yes" }), /"dedupe" is true or false/); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28", dedupe: true }), /drop the dedupe/); }); test("an API and a local model: a bench-verdicts job on draft:local, every answer on disk, the API spend in the ledger, ollama unloaded", async () => { for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { parts: [{ part: "she said it", finding: "shown" }], checkable: true, reason: "she says so" })); for (let i = 0; i < 7; i++) ol.push(jsonReply({ parts: [{ part: "she said it", finding: "not shown" }], checkable: true, reason: "not in the window" })); const out = await enqueueVerdictBench({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-editor" }, deps()); assert.ok(out.result.ok && "run" in out, (out.result as { error?: string }).error); assert.equal(out.run, "vb-editor"); const job = getRegistry().get(out.result.jobId)!; assert.equal(job.kind, "bench-verdicts"); assert.equal(job.queueKey, "draft:local"); void out.result.stream.cancel(); const done = await out.result.done; const log = await readFile(job.logPath, "utf8"); assert.equal(done.status, "done", log); assert.match(log, /@@bench-verdicts \{"run":"vb-editor","status":"done","items":7,"skipped":1/); assert.match(log, /unloaded qwen3:8b from ollama/); assert.ok(!log.includes(FAKE_KEY), "the key is never in the log"); assert.deepEqual(ol.unloads, ["qwen3:8b"]); const run = (await readBenchRun(root, "vb-editor"))!; assert.equal(run.results.length, 14); const [sonnet, qwen] = run.summary.score.models; assert.equal(sonnet!.agreed, 2); // the two CORROBORATED assert.equal(qwen!.agreed, 1); // the one NOT_FOUND const all = await readGenerationUsage(paths.generationUsageFile); const rows = all.filter((r) => !isLocalUsage(r)); assert.deepEqual(rows.map((r) => [r.model, r.task, r.jobId]), [["claude-sonnet-5-5", "bench-verdicts", out.result.jobId]]); // The local model's calls: in the ledger at no cost (demo epic D3). assert.deepEqual(all.filter(isLocalUsage).map((r) => [r.model, r.task, r.jobId, r.usd]), [["qwen3:8b", "bench-verdicts", out.result.jobId, 0]]); assert.ok(rows[0]!.usd > 0); assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); }); test("API models only run on draft:api; past the day's cap an API run is refused, a local one is not", async () => { api.push(toolTurn("answer", { parts: [{ part: "it", finding: "shown" }], checkable: true, reason: "ok" })); const one = await enqueueVerdictBench({ models: ["claude-haiku-4-5"], run: "vb-api", limit: 1 }, deps()); assert.ok(one.result.ok && "run" in one); assert.equal(getRegistry().get(one.result.jobId)!.queueKey, "draft:api"); void one.result.stream.cancel(); assert.equal((await one.result.done).status, "done"); await appendGenerationUsage(paths.generationUsageFile, [ { at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }, ]); const refused = await enqueueVerdictBench({ models: ["claude-sonnet-5-5"], run: "vb-late" }, deps()); assert.equal(refused.result.ok, false); assert.match((refused.result as { error: string }).error, /daily cap/); ol.push(jsonReply({ parts: [{ part: "it", finding: "shown" }], checkable: true, reason: "ok" })); const local = await enqueueVerdictBench({ models: ["qwen3:8b"], run: "vb-local", limit: 1 }, deps()); assert.ok(local.result.ok && "run" in local); void local.result.stream.cancel(); assert.equal((await local.result.done).status, "done"); });