// `bench-verdicts` — the verdict bench (release 28, M7) as an editor job: // `archilyzer reports bench-verdicts` → `pnpm ops bench-verdicts` → // POST /api/ops/bench-verdicts → here. // // run the run's id: a new one, or one to continue (default vb-) // reports the fact-check articles to read (default: every one) // models the models to ask (required) // window seconds of transcript either side of each cited span (default 60) // windowMode "seconds" (the default) or "turn": the cited speaker's turn, // bounded by the window (release 29 V1) // maxUsd the whole run's API cap (default 5, at most 50) // limit a stratified sample of n items, by the operator's verdict (V1) // itemsFrom the exact items of an earlier run (V1; no reports, window, // windowMode or limit with it) // // WHY A JOB IN THE EDITOR, NOT A `report-draft`: a bench writes no iteration // and is no task of an article, so `report-draft`'s machinery (an iteration // created queued, the task registry) would be bent to fit it. What it needs // of release 27 is the GPU path, which is the editor's alone (the arbiter's // holds are in-process): a run with any LOCAL model goes on `draft:local`, // every ollama call through `gpuGatedFetch` (it waits for transcription and // for a synthesis, and holds the card while it runs), and ollama is unloaded // when the job ends, however it ends — exactly as a `report-draft` on // `draft:local`. A run of API models only goes on `draft:api`. // // An API run is refused past the day's cap (settings.generation.caps.daily), // and its spend is appended to the usage ledger (task `bench-verdicts`, no // article) so the day's total counts it. The cues are the local corpus's // (`diskCuesOf`): a fact-check may cite channels no build carries. The log // ends `@@bench-verdicts {json}` with the run's id, status and spend. import { modelLogged } from "./jobModelLog"; import { getSettings } from "../lib/settings"; import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { providerOf, unloadOllama } from "../lib/llm"; import { diskCuesOf } from "../lib/report/convert-server"; import { BenchInputError, DEFAULT_BENCH_MAX_USD, isBenchRunId, isWindowMode, newBenchRunId, runVerdictBench, validateBenchOptions, type BenchOptions, type WindowMode, } from "../lib/report/draft/bench/index"; import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk"; import { isReportId } from "../lib/report/schema"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { llmConfigOf } from "./reportDraft"; export const BENCH_VERDICTS_JOB_KIND = "bench-verdicts"; export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "windowMode", "maxUsd", "limit", "itemsFrom", "dedupe"] as const; const fail = (msg: string): never => { throw new BenchInputError(msg); }; // The body, judged without touching the disk. export function parseBenchVerdictsBody(b: Record): BenchOptions { const out: BenchOptions = { models: [] }; if (b.run !== undefined) { if (!isBenchRunId(b.run)) fail(`"run" is a run id: lowercase letters, digits and dashes`); out.runId = b.run as string; } if (b.reports !== undefined) { if (!Array.isArray(b.reports) || !b.reports.every((r) => isReportId(r))) fail(`"reports" is a list of article ids`); out.reports = b.reports as string[]; } const models = typeof b.models === "string" ? b.models.split(",") : b.models; if (!Array.isArray(models) || !models.every((m) => typeof m === "string")) fail(`"models" is a list of model names`); out.models = (models as string[]).map((m) => m.trim()).filter(Boolean); if (b.window !== undefined) { if (typeof b.window !== "number") fail(`"window" is a number of seconds`); out.windowS = b.window as number; } if (b.maxUsd !== undefined) { if (typeof b.maxUsd !== "number") fail(`"maxUsd" is a number of dollars`); out.maxUsd = b.maxUsd as number; } if (b.limit !== undefined) { if (typeof b.limit !== "number") fail(`"limit" is a number of items`); out.limit = b.limit as number; } if (b.windowMode !== undefined) { if (!isWindowMode(b.windowMode)) fail(`"windowMode" is "seconds" or "turn"`); out.windowMode = b.windowMode as WindowMode; } if (b.itemsFrom !== undefined) { if (!isBenchRunId(b.itemsFrom)) fail(`"itemsFrom" is a run id: lowercase letters, digits and dashes`); out.itemsFrom = b.itemsFrom as string; } if (b.dedupe !== undefined) { if (typeof b.dedupe !== "boolean") fail(`"dedupe" is true or false`); out.dedupe = b.dedupe as boolean; } validateBenchOptions(out); return out; } export type BenchVerdictsDeps = { paths: Paths; settings?: () => { generation: GenerationSettings }; now?: () => Date; // Where runs live (tests); default `.generation/bench/verdicts/`. root?: string; }; export type BenchVerdictsEnqueued = { result: StreamActionResult; run: string }; // One run with the settings' providers: the job's body, and `archilyzer // reports bench-verdicts --here` (API models only: no GPU arbiter outside the // editor, so a local model there is refused). The ledger gets this run's API // spend; a local model is unloaded at the end. Answers the outcome. export async function runBenchWithSettings( opts: BenchOptions & { runId: string }, o: { paths: Paths; gen: GenerationSettings; onLog: (line: string) => void; signal?: AbortSignal; jobId: string; // In the editor: every ollama call through the GPU arbiter. gpu: boolean; now?: () => Date; root?: string; }, ): Promise>> { const { paths, gen: g, onLog } = o; const locals = opts.models.filter((m) => providerOf(m) === "local"); if (locals.length && !o.gpu) { throw new BenchInputError(`${locals.join(", ")} run${locals.length === 1 ? "s" : ""} on the GPU, which only the editor arbitrates: run the bench through the editor (pnpm ops bench-verdicts)`); } let spent: Awaited>["spent"] | null = null; try { const out = await runVerdictBench(opts, { paths, ...(o.root ? { root: o.root } : {}), cuesOf: diskCuesOf(paths.channelsDir), turnsOf: diskTurnsOf(paths.channelsDir), dateOf: diskDateOf(paths.channelsDir), llm: llmConfigOf(g, paths, locals.length ? { onLog, ...(o.signal ? { signal: o.signal } : {}) } : undefined), log: onLog, ...(o.signal ? { signal: o.signal } : {}), ...(o.now ? { now: o.now } : {}), }); spent = out.spent; const s = out.summary; onLog( `${BENCH_VERDICTS_RESULT_MARKER}${JSON.stringify({ run: s.id, status: s.status, items: s.items, skipped: s.skipped.length, spentUsd: s.spentUsd, ...(s.stopped ? { stopped: s.stopped } : {}), })}`, ); return out; } finally { for (const m of locals) { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, m).then( () => onLog(`unloaded ${m} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } if (spent) { const now = o.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(spent.byModel) .filter(([m, t]) => providerOf(m) === "api" && (t.usd > 0 || t.calls > 0)) .map(([m, t]) => ({ at: now.toISOString(), day: utcDay(now), jobId: o.jobId, article: "", iteration: 0, task: BENCH_VERDICTS_JOB_KIND, model: m, inputTokens: t.input, outputTokens: t.output, cacheReadTokens: t.cacheRead, cacheWriteTokens: t.cacheWrite, usd: Math.round(t.usd * 10_000) / 10_000, })); await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } } } // The day's cap, for a run with an API model: the refusal, or null. export async function benchDailyCapRefusal(opts: BenchOptions, paths: Pick, gen: GenerationSettings, now?: Date): Promise { if (!opts.models.some((m) => providerOf(m) === "api")) return null; return dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(now)), gen.caps.daily); } export async function enqueueVerdictBench( raw: Record, deps: BenchVerdictsDeps, ): Promise { const refuse = (error: string) => ({ result: { ok: false as const, error } }); let opts: BenchOptions; try { opts = parseBenchVerdictsBody(raw); } catch (e) { return refuse((e as Error).message); } const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; const anyLocal = opts.models.some((m) => providerOf(m) === "local"); const refusal = await benchDailyCapRefusal(opts, paths, gen, deps.now?.()); if (refusal) return refuse(refusal); const run = opts.runId ?? newBenchRunId(deps.now?.() ?? new Date()); const result = await runManagedFunction({ kind: BENCH_VERDICTS_JOB_KIND, queueKey: anyLocal ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, fn: modelLogged({ paths, task: "bench-verdicts" }, async (onLog, signal, _progress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await benchDailyCapRefusal(opts, paths, g, deps.now?.()); if (late) throw new Error(late); onLog(`verdict bench ${run}: ${opts.models.join(", ")} (API cap $${opts.maxUsd ?? DEFAULT_BENCH_MAX_USD})`); const out = await runBenchWithSettings( { ...opts, runId: run }, { paths, gen: g, onLog, signal, jobId: ctx.jobId, gpu: true, ...(deps.now ? { now: deps.now } : {}), ...(deps.root ? { root: deps.root } : {}) }, ); if (out.summary.status === "cancelled" || signal.aborted) throw new Error("cancelled"); }), }); if (!result.ok) return { result }; return { result, run }; }