Joel Stevick

Eval harness · Eval runner · Ask, trace, score, spend · stage 3 of 5

Asking each case

The runner takes the selected cases in file order. For each case it resets the demo accounts' question counts and asks the question through the real POST /api/ask with its corpus's access key. It then reads the model calls the Worker traced, adds their cost to the ledger at once, fetches the chunks the answer model was given, and scores the case. After the last case it deletes each account's vectors from the shared eval index and stops the Worker.

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.mjs54 / 54 lines on this page explainedlines 177-230 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

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

evals/run.mjs The eval harness's runner.

The results and the ledger entry

segment · lines 177–185View on GitHub

The run's result list, its spend, and its entry in the ledger.

// One result per case, in case order; `spent` is this run's dollars so far.const results = []let spent = 0

Results and spend Eval run

Whatresults will hold one record per case, in case order. spent is the run's dollars so far.

WhyEvery case gets a record, either scored or not run, so the report's tally always sums to the number of selected cases.

// The ledger is written after every case, so a run that dies still counts what it spent.const runEntry = { id: runId, usd: 0 }ledger.runs.push(runEntry)const startTotal = ledger.total_usd

The run's ledger entry Eval run

WhatAppends { id: runId, usd: 0 } to ledger.runs before the first case and keeps the total at the start in startTotal.

WhyThe entry is added in memory before the first case, and saveLedger() writes the file after every case that runs, so a run that dies after its first case still has its line with the spend saved so far. In evals/JOURNAL.md, Round 2, the harness failed twice, and the second run died after spending about a cent that the ledger never recorded. The write after every case is the fix, and the lost spend of both starts is recorded as one estimate.

evals/runs/ledger.json: round2-crashes-unrecorded-estimate, $0.02 for both starts

The same idea, shown in the course's code: The ledger, rewritten after every case: a crashed run still counts From Prove it works, Ep 5: Caps, the ledger and comparing runs

saveLedger()

function · lines 186–193View on GitHub

Writes the run's spend so far and the new total to evals/runs/ledger.json.

Called by The case loop Provenance Writing the report

// Write this run's spend so far, and the new total, to the ledger file.const saveLedger = () => {  runEntry.usd = Number(spent.toFixed(4))  ledger.total_usd = Number((startTotal + spent).toFixed(4))  mkdirSync('evals/runs', { recursive: true })  writeFileSync(ledgerPath, JSON.stringify(ledger, null, 2) + '\n')}

Write the ledger Eval run

WhatSets the entry's usd to spent and total_usd to startTotal plus spent, each rounded to 4 decimal places, creates evals/runs if needed, and rewrites the whole file as indented JSON.

WhyThe total is recomputed from startTotal on every write instead of incremented, so writing after every case never double-counts. Two runs at once would overwrite each other's ledger, so the harness assumes one run at a time.

The case loop

segment · lines 194–225View on GitHub

One case at a time: reset, ask, trace, cost, chunks, score.

Calls saveLedger() call() One demo account per corpus cost() Caps, arguments and the Worker score() Scoring a case

// Run each case in turn.for (const c of cases) {  // Once either cap is reached, every remaining case is recorded as not run, never scored.  if (spent >= budget || startTotal + spent >= TOTAL_CAP) {    results.push({ id: c.id, status: 'not run', reason: 'budget' })    continue  }

Check the caps first Eval run

WhatBefore each case, if spent has reached budget or startTotal plus spent has reached TOTAL_CAP, the runner records the case as not run, with reason budget, and skips it.

WhyA capped case is never scored, so it cannot count as a pass or a fail, and the report shows exactly how much of the golden set ran. The check comes before each case, so the case that crosses a cap still completes and is paid for.

status: not run, reason: budget

The same idea, shown in the course's code: Not run: a case the budget stopped is never a pass or a fail From Prove it works, Ep 5: Caps, the ledger and comparing runs
  // Each case starts with the demo's question count at zero, so the ten-question limit never ends a run.  await call('/eval/reset', {})

Reset the question counts Eval run

WhatPOSTs /eval/reset, which sets asks_used to 0 for every demo account in the local D1.

WhyA demo account allows ten questions (LIMITS.asks), and one corpus's account serves up to 26 cases, so without the reset ASK 2 would refuse the eleventh. A reset before every case sends each question down the same path as a visitor's first question.

LIMITS.asks = 10

  // The question goes through the real ask route with its corpus's demo key, timed end to end.  const started = Date.now()  const asked = await call('/api/ask', { question: c.question }, demos[c.corpus].key)  const ms = Date.now() - started

Ask through the real route Eval run

WhatPOSTs { question } to /api/ask with the corpus's access key and times the request from send to parsed reply. call() does not ask for text/event-stream, so the route drains the answering generator and replies with one JSON body: answer, items (for a list), sources, found, left, first_ms and, on an answer, the Worker's own ms. The body adds refused on a refused fallback, or stopped when the answer stopped partway. Failures return other statuses: 400 for an invalid question, 429 at the question limit, and 503 with { error, left } when the answer model fails before anything is shown. An exception out of the ask (D1 down, a bug) reaches createApp, which answers 500.

WhyThe whole ask runs as it does for a visitor: validation, the question reservation, retrieval, rerank, widening, the streamed answer and the check of each sentence. The recorded ms is the runner's own measurement, so it is end-to-end latency, and the body's ms is ignored. first_ms comes from the Worker: the time from the start of the ask, after the reservation, to the first checked sentence or list item released.

evals/runs/2026-10-30T13-49-56-stream-final: median 5426 ms, first sentence 4614 ms

  // The trace now holds this case's model calls (a cancelled stream's may land in the next read); their cost goes into the ledger at once.  const calls = (await call('/eval/trace')).body  const usd = cost(calls)  spent += usd  saveLedger()

Read the trace, count the spend Eval run

WhatGETs /eval/trace, the Claude calls the Worker traced since the last read (normally the rerank call and the answer call), prices them with cost(), adds the result to spent and saves the ledger.

WhyThe spend is written before scoring, so a crash in score() or later loses no record of money spent. The comment warns that a cancelled stream's call may land in the next read. When the demo app cancels a streamed answer (after a sentence fails its check), the Worker traces the call only after it has read the rest of Anthropic's stream, which can happen after this read. That call's tokens then count with the next case.

  // The answer call's trace names the chunk ids it was given; their text is read back to score what the answer saw.  const answerCall = calls.find((x) => x.given)  const given = answerCall ? (await call('/eval/chunks', { ids: answerCall.given })).body : []  results.push(score(c, asked, given, calls, ms, usd))

What the answer saw, then score Eval run

WhatFinds the traced call that has given (the answer call, whose [id] labels the Worker reads out of its prompt) and POSTs those ids to /eval/chunks, which returns each stored chunk's id, file, page and text. With no answer call (a fallback before ASK 6), given is empty. score() then builds the case's record.

WhyScoring "in context" against the ids the prompt carried separates a rerank loss from a generation loss. The chunks come back as stored, one chunk per id. A widened passage carries the id of the chosen chunk it was built around, but its text joins that chunk and its neighbours. So a source found only in a neighbour counts as missing from context here, while its citation (the joined passage) still supports it. If the answer call was traced late, after this case's read of the trace, this case has no given, and the next case's find picks the stale answer call first, so both cases' in-context counts are wrong.

evals/runs/2026-10-30T13-49-56-stream-final, boundary-01: in context 0/2, cited 2/2

  // One line per case on the console as the run goes: status, the score's summary and the cost.  const r = results.at(-1)  console.log(`${c.id.padEnd(10)} ${r.status.padEnd(7)} ${r.summary}  $${usd.toFixed(4)}`)}

One line per case Eval run

WhatPrints the case id padded to 10 characters, the status padded to 7, the score's summary and the case's cost to 4 decimal places.

WhyA run takes about ten minutes (evals/JOURNAL.md, For the story), so progress and early failures show while the run goes, before the report is written.

resume-01 pass answered; facts 7/7; in pool 7/7; in context 7/7; cited 7/7 $0.0125 (evals/runs/2026-10-30T13-49-56-stream-final)

The run's output: book.pdf uploaded as 267 pages and 501 chunks, one line per case with its status, facts, pool, context, citations and cost, then pass 2, review 1 of 3, the median cost and time, this run's spend against the ledger, and the path of results.md.
The run's output. The harness uploads the corpus through the real upload route and prints one line per case as it scores it. Then it prints the tally, the median cost and time, the spend against the ledger's cap and the path of results.md. 2026-11-29, Terminal on macOS, in a checkout of the repository at the pinned commit

Cleanup

segment · lines 226–230View on GitHub

The demo accounts' vectors deleted, then the Worker stopped.

Calls call() One demo account per corpus Starting the Worker Caps, arguments and the Worker

// Each demo's vectors are deleted from the shared eval index, then the Worker stops; the local D1 goes at the next run's start.for (const demo of Object.values(demos)) await call('/eval/forget', { demo_id: demo.id })stop()

Forget the vectors, stop the Worker Eval run

WhatFor each demo account, POSTs /eval/forget, which reads the account's chunk ids from D1 and deletes their vectors from Vectorize, 500 ids per call. Then the runner sends the Worker SIGTERM.

WhyThe eval Vectorize index is remote and shared by every run, while the local D1 is wiped at the next start, so the vectors are the only state that would outlive the run. A run that throws before this point leaves its vectors in the index. Each run's demo accounts have their own Vectorize namespaces (the partition of the index each account's searches are limited to, named by its id), so a later run never searches them.

index: joelstevick-com-demo-eval (remote)500 ids per deleteByIds