Eval harness · Eval runner · Before any case · stage 1 of 5
Caps, arguments and the Worker
Everything run.mjs does before it uploads a PDF or asks a question. It fixes the spend caps and token prices, and reads --label and --budget. It defines the helpers that later stages call (sha, the run id, text normalisation, cost). Then it wipes the local D1 state, applies demo/schema.sql, starts evals/worker.ts under wrangler dev and polls until the Worker answers.
Runs in: Your machine, the developer's machine: npm test (vitest, demo/tests/), npm run eval (Node and wrangler dev, evals/) and npm run search (Node, examples/). New to Cloudflare? How these fit together
evals/run.mjs100 / 100 lines on this page explainedlines 1-30,33-44,47-61,64-73,105-137 of 349; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
// The eval harness: runs evals/cases.jsonl through the demo's real routes and real models// (evals/worker.ts under `wrangler dev`), scores each case and writes evals/runs/<run>/.//// npm run eval -- --label baseline [--only resume-01,book-13] [--budget 2]//// Spend is capped: --budget dollars a run (at most 3), and $7.50 across every run in// evals/runs/ledger.json. A run that reaches either cap stops, and the cases not reached// are recorded as not run, never as passes. See evals/README.md.
What the harness is Never runs
WhatThe header states the design: the golden set goes through the demo app's real routes and real models, served by evals/worker.ts under wrangler dev, and each run writes evals/runs/<run>/. It also gives the command line and the two spend caps.
WhyAn end-to-end eval measures the pipeline a visitor gets, prompts, retrieval and checks included. The header's last sentence is the harness's main guarantee: cases that a cap stops are recorded as not run, so a short run can never show a better pass rate.
npm run eval -- --label baseline [--only resume-01,book-13] [--budget 2]
WhatNode's child_process runs wrangler, crypto computes SHA-256, fs reads and writes the files, and pdf.js's legacy build from pdfjs-dist extracts PDF text.
WhyThe legacy build runs in Node without a browser's DOM. package.json pins pdfjs-dist at 4.10.38, the version demo.html loads from cdnjs, so the runner extracts the same text a browser would.
// Spend caps in dollars: one run's ceiling (--budget may lower it, never raise it), and the ceiling// across every run in the ledger.constRUN_CAP = 3constTOTAL_CAP = 7.5
The spend caps Eval run
WhatOne run may spend at most $3, and all the runs recorded in the ledger together at most $7.50. --budget can lower the first cap, never raise it.
WhyAn eval calls paid models on every case, so the spend limit is enforced in code. The runner checks both caps before each case, never during one, so a run can exceed a cap by the cost of the case that crosses it.
RUN_CAP = 3TOTAL_CAP = 7.5evals/JOURNAL.md, The harness and Round 2: first $2 a run and $5 in all, then raised by 50%evals/runs/ledger.json at the pin: total_usd 6.518
The same idea, shown in the course's code: Spending caps: one run, every run, checked between cases From Prove it works, Ep 5: Caps, the ledger and comparing runs
Dollars per million tokens for the two Claude models the demo app calls.
// $ per million tokens (input, output), Anthropic first-party prices as of 2026-10-06.constPRICES = { 'claude-sonnet-5-5': [2, 10], 'claude-haiku-5-5': [0.1, 0.5] }
Token prices Eval run
WhatInput and output prices per million tokens: $2 and $10 for Claude Sonnet 5.5 (the answer model), $0.10 and $0.50 for Claude Haiku 5.5 (the reranker).
Whycost() multiplies each traced call's token counts by these prices, and both caps compare the resulting dollars. The comment dates the prices so that a stale table can be noticed. Workers AI embedding calls are not traced, so their cost is not counted.
claude-sonnet-5-5: $2 in, $10 out per millionclaude-haiku-5-5: $0.10 in, $0.50 out per million
Where the eval Worker listens and where wrangler keeps its local D1.
// The eval Worker's local port, and the folder where wrangler keeps its local D1 state, wiped at each run's start.constPORT = 8862constBASE = `http://localhost:${PORT}`constSTATE = '.wrangler/evals'
Port and local state Eval run
WhatBASE is the URL every call() goes to. STATE is the folder passed to wrangler as --persist-to, both when the schema is applied and when the dev server starts.
WhyWith a fixed port the runner reaches the Worker without parsing wrangler's output. A dedicated state folder, separate from wrangler's default, can be deleted at each start without touching any other local D1.
WhatEach argument that starts with -- becomes a key, and the argument after it becomes its value. label defaults to run.
WhyThree flags do not justify a parser dependency. The parse has no notion of a flag without a value: a flag given last gets undefined, and the defaults absorb it.
The harness run on three cases of the golden set. --label ends the name of the run's folder in evals/runs/, and --only selects the cases. All three cases use the book, so the harness uploads only the book's corpus. 2026-11-29, Terminal on macOS, in a checkout of the repository at the pinned commit
// --budget is clamped to RUN_CAP; anything but a positive number stops the run before any spend.const budget = Math.min(Number(args.budget ?? RUN_CAP), RUN_CAP)if (!(budget > 0)) {console.error(`--budget must be a number of dollars up to ${RUN_CAP}.`) process.exit(1)}
--budget, clamped Eval run
Whatbudget is the smaller of --budget (default RUN_CAP) and RUN_CAP. A value that is not a positive number (NaN, 0 or negative) prints an error and exits with status 1.
WhyMath.min with NaN returns NaN, and !(NaN > 0) is true, so a typo stops the run instead of running without a cap. Exiting at this point costs nothing, because no Worker has started and no model has been called.
The Anthropic key and the cap on all runs, checked before anything starts.
// The Worker reads the Anthropic key from evals/.dev.vars; without it every model call would fail, so stop here.if (!existsSync('evals/.dev.vars') || !/ANTHROPIC_API_KEY=\S+/.test(readFileSync('evals/.dev.vars', 'utf8'))) {console.error('evals/.dev.vars with ANTHROPIC_API_KEY=... is needed (git ignores it).') process.exit(1)}
The key, or stop Eval run
WhatExits unless evals/.dev.vars exists and sets ANTHROPIC_API_KEY to a non-blank value.
Whywrangler dev loads .dev.vars as the Worker's secrets. Without a key every Claude call would fail, the demo app would fall back on every case, and the run would score a broken setup as a page of fallbacks. git ignores the file, so the key stays out of the public repository.
// The ledger holds every run's spend; no run starts once the total cap is reached.const ledgerPath = 'evals/runs/ledger.json'const ledger = existsSync(ledgerPath) ? JSON.parse(readFileSync(ledgerPath, 'utf8')) : { total_usd: 0, runs: [] }if (ledger.total_usd >= TOTAL_CAP) {console.error(`The eval budget is spent: $${ledger.total_usd.toFixed(2)} of $${TOTAL_CAP}.`) process.exit(1)}
The ledger, or stop Eval run
WhatReads evals/runs/ledger.json ({ total_usd, runs }), or starts an empty ledger, and exits if total_usd has reached TOTAL_CAP.
WhyThe ledger is committed with the runs, so the total cap holds across machines and sessions, beyond one process. At the pin the total is $6.518, so the next run stops starting cases once it has spent the $0.982 that is left, which is below RUN_CAP.
evals/runs/ledger.json at the pin: total_usd 6.518 over 21 entries
// Short content hashes, recorded in the results so a run names the exact cases and corpus it scored.constsha = (data) => createHash('sha256').update(data).digest('hex').slice(0, 12)
Twelve hex characters of SHA-256 Eval run
WhatKeeps the first 12 hex digits (48 bits) of the SHA-256 digest.
WhyThe report records the hash of cases.jsonl and of each PDF, so a comparison of two runs shows whether the golden set or the corpus changed between them. 48 bits is ample to tell a handful of file versions apart.
// The run id sorts by time and carries the label: it names the run's folder and its demos.const runId = `${newDate().toISOString().replace(/[:.]/g, '-').slice(0, 19)}-${label}`
A sortable run id Eval run
WhatThe current UTC time in ISO 8601, with : and . replaced by -, cut to the second, then -<label>. For example: 2026-10-30T13-49-56-stream-final.
WhyLexical order is time order, so evals/runs/ lists the runs chronologically, and the label says what each run tested. toISOString returns UTC, so the folder names are four hours ahead of the US Eastern daylight times in evals/JOURNAL.md (the baseline at 13:35 is 2026-10-21T17-35-57-baseline). The run id is also part of the fingerprint of each of the run's demo accounts (eval-<runId>-<corpus>).
// Matching is on whitespace-collapsed, lower-cased text with curly single quotes straightened: the ways a PDF's text differs from a typed expectation.constflat = (text) => text.replace(/\s+/g, ' ').trim()constnorm = (text) => flat(text).toLowerCase().replace(/[’‘]/g, "'")
Normalise before matching Eval run
Whatflat collapses each run of whitespace to one space and trims. norm also lower-cases and replaces the curly single quotes ’ and ‘ with '.
WhyExpected evidence and match terms are typed by hand, while passages come from pdf.js with line breaks and typographic apostrophes, so a raw substring test would miss real matches (Howard’s against Howard's). Only the curly single quotes are straightened, so a curly double quote in a passage still fails to match a typed straight one.
// A case's cost in dollars from its traced token counts. A model missing from PRICES counts as free,// so a new model must be added there or its spend escapes both caps.constcost = (calls) => calls.reduce((sum, c) => {// The model's prices, or zero when it has none.const [input, output] = PRICES[c.model] ?? [0, 0]return sum + (c.input_tokens * input + c.output_tokens * output) / 1e6}, 0)
Tokens to dollars Eval run
WhatPrices each traced call's input and output tokens at the model's per-million-token rates and sums the dollars. A model missing from PRICES counts as $0.
WhyThe token counts are Anthropic's own usage fields, which the eval Worker's trace reads. The dollars multiply those counts by the hard-coded PRICES, so the ledger is a close estimate of the Anthropic bill. The comment names the risk of the $0 default: a new model must be added to PRICES, or its spend escapes both caps.
evals/runs/2026-10-30T13-49-56-stream-final: median $0.0185 a question
// A fresh local database, then the Worker.rmSync(STATE, { recursive: true, force: true })
Wipe the local state Eval run
WhatDeletes .wrangler/evals recursively.
WhyEvery run starts on empty tables, so no demo account, chunk or question count left by an earlier run can affect this one. Only D1 is local. Workers AI and the eval Vectorize index are remote and are not reset here, so the runner deletes each demo account's vectors after the last case.
// The demo's schema applied to the empty local D1, so the Worker starts on clean tables.execFileSync('npx', ['wrangler', 'd1', 'execute', 'joelstevick-com-demos-eval', '--local', '--persist-to', STATE, '-c', 'evals/wrangler.toml', '--file', 'demo/schema.sql'], { stdio: 'pipe' })
Apply the schema Eval run
WhatRuns wrangler d1 execute with demo/schema.sql against the local database joelstevick-com-demos-eval in STATE, synchronously, with its output captured.
WhyThe Worker gets the deployed demo app's own schema, so a schema change is evaluated together with the code that needs it. execFileSync throws on a non-zero exit, so a broken schema stops the run before any spend.
// wrangler dev serves evals/worker.ts on PORT against that same local state; its output is kept for the error below.const worker = spawn('npx', ['wrangler', 'dev', '-c', 'evals/wrangler.toml', '--port', String(PORT), '--persist-to', STATE, '--inspector-port', '9362'], { stdio: ['ignore', 'pipe', 'pipe'] })
Start wrangler dev Eval run
WhatSpawns wrangler dev with evals/wrangler.toml on PORT, persisting to the same STATE, with the inspector on port 9362, and pipes back its stdout and stderr.
Whyevals/wrangler.toml runs evals/worker.ts: the demo app's own code plus five /eval/ routes and a fetch trace. It binds AI and VECTORS remotely (bindings are properties of env: env.AI calls Workers AI and env.VECTORS the Vectorize index) and has no MAILER, so the run uses the real embedding model and a real Vectorize index and emails no one. The fixed inspector port avoids a clash with another wrangler dev on the default port.
// Keep the Worker's output, to show if it fails to start.const log = []worker.stdout.on('data', (d) => log.push(String(d)))worker.stderr.on('data', (d) => log.push(String(d)))
Keep the Worker's output Eval run
WhatAppends each chunk of the Worker's stdout and stderr to log.
WhyThe runner prints the log only if the Worker fails to start, so a normal run stays quiet and a broken one shows why.
// The Worker is killed whenever this process exits, a thrown error included.conststop = () => worker.kill('SIGTERM')process.on('exit', stop)
Kill it on exit Eval run
Whatstop sends SIGTERM to the Worker and is registered on the process's exit event.
WhyNode emits exit on process.exit and when an uncaught error ends the process, so a run that throws midway does not leave wrangler dev holding the port for the next run.
// Poll the trace route once a second for up to two minutes; the first OK reply means the Worker is serving.for (let i = 0; ; i++) {if (i > 120) thrownewError(`the eval Worker did not start:\n${log.join('')}`)const up = awaitfetch(`${BASE}/eval/trace`).then((r) => r.ok).catch(() =>false)if (up) breakawaitnewPromise((r) =>setTimeout(r, 1000))}
Wait until it serves Eval run
WhatGETs /eval/trace once a second until a reply is OK. A refused connection counts as not yet. After 121 attempts (about two minutes) it throws with the Worker's collected output.
Whywrangler dev takes seconds to bundle and start, and the first upload must not race it. At this point /eval/trace has no side effect, because the list of traced calls is still empty.