Joel Stevick

Eval harness · Eval runner · Facts, sources, status · stage 4 of 5

Scoring a case

score() turns one ask into one result record, in code, with no model as judge. It checks each required fact by its match terms in the answer. It follows each expected source through three stages (the reranker's candidate pool, meaning the passages retrieval handed it to choose from; the answer's context; the cited passages), so a miss names the stage that lost the source. It lists model errors and sets the status: pass, fail, review or error. The case loop pushes the record into results, and the report renders it.

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.mjs63 / 63 lines on this page explainedlines 235-297 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.

score()

function · lines 235–297View on GitHub

One case's result: status, facts met, how far each expected source got, citations, errors and cost.

Called by The case loop Asking each caseCalls fileOf() Reading the cases flat(), norm() Caps, arguments and the Worker

/** One case's result: its status, which facts the answer met, where each expected source got to, the citations, errors and cost. */

Doc comment: what a result holds Never runs

WhatLists what the record holds: the status, the facts met, how far each expected source got, the citations, errors and cost.

WhyRuns are compared record by record, so each field answers one diagnostic question about the case.

The same idea, shown in the course's code: Scoring: the source check, required facts, forbidden claims, citations From Prove it works, Ep 4: Scoring
function score(c, asked, given, calls, ms, usd) {  const body = asked.body ?? {}

score()'s inputs Eval run

WhatTakes the case, the ask's { status, body }, the given chunks read back from D1, the traced calls, the runner's ms and the case's dollars. A null body (from a non-JSON reply) becomes {}.

WhyWith the body defaulted, every later field can be read without null checks, and the HTTP status alone decides the error case.

  // A list answer's items are part of what it says: a fact named only in a bullet is still met.  const answer = [typeof body.answer === 'string' ? body.answer : '', ...(Array.isArray(body.items) ? body.items : [])].join('\n')

The answer text, items included Eval run

WhatJoins the prose answer and every list item with newlines into the one string that facts are matched against.

WhyA list answer puts each job or chapter in items instead of answer. Joining them means a fact named only in a bullet is still met.

  // `found` is the demo's own claim to have answered; the cited sources keep their passage text for the support check.  const found = asked.status === 200 && body.found === true  const cited = (body.sources ?? []).map((s) => ({ id: s.id, file: s.file, page: s.page, passage: s.passage }))

found, and the citations Eval run

Whatfound is true only for HTTP 200 with found: true in the body, which is the demo app's own claim that it answered. cited keeps each source's id, file, page and passage. The passage is the text the answer was given under that id: the chunk's stored text or, for a widened passage, the stored texts of the chunk and its neighbours joined.

WhyThe passage is what the citation points at, so support is judged on stored text, never on the model's words. A stopped answer has found: true, so what was shown counts as answered.

  // A quote a chunk boundary splits (book-07) counts when either half is in one passage.  const halves = (evidence) => {    // The evidence split in two by word count; a half under 30 characters is dropped, since it could match by chance.    const words = norm(evidence).split(' ')    const middle = Math.floor(words.length / 2)    return [norm(evidence), words.slice(0, middle).join(' '), words.slice(middle).join(' ')].filter((part) => part.length >= 30 || part === norm(evidence))  }

Evidence, or either half of it Eval run

Whathalves returns the normalised evidence plus its first and second halves, split by word count. A half shorter than 30 characters is dropped, and the whole quote is always kept.

WhyA chunk boundary can split a quote, so that no single passage holds it whole. In evals/JOURNAL.md, Round 2, book-07's quote was split this way and "in pool" under-counted it. The 30-character floor keeps a short half from matching by chance.

minimum half: 30 characters

  // A passage holds an expected source when it is from the same file and contains the evidence, or a half of it.  const holds = (passages, s) => passages.some((p) => p.file === s.file && halves(s.evidence).some((part) => norm(p.text ?? p.passage).includes(part)))

Does a passage hold a source? Eval run

Whatholds is true when some passage has the source's file and its normalised text (text, or passage for a citation) contains the evidence or one of its halves.

WhyA substring test on normalised text is deterministic and free, and the verbatim evidence quote that the README requires for each source makes it precise. The test locates one known passage, so an answer drawn correctly from another passage that says the same thing scores as a miss here (evals/JOURNAL.md, Round 2: book-05 and book-06).

  // A fact is met when any of its match terms appears in the answer: proof of the term, not of the answer (the README's caveat).  const facts = c.required_facts.map((f) => ({ fact: f.fact, met: f.match.some((m) => norm(answer).includes(norm(m))) }))

Required facts Eval run

WhatA fact is met when any of its normalised match terms is a substring of the normalised answer.

WhyThe match terms list spellings (Howard's Lantern, Howards Lantern, Howard’s Lantern), so different phrasing does not fail a right answer. As the comment says, a term's presence proves the term and says nothing about whether the answer is right. A sentence that names the term to deny it still meets the fact, which is why a person reads surprising passes.

  // Where each expected source got to: the reranker's pool, the answer's context, the citations. A miss names the stage that lost it.  const retrieved = c.sources.map((s) => holds(given, s))

In context Eval run

WhatFor each expected source, whether one of the chunks given to the answer prompt holds it.

WhyThe "Read a result" section of evals/README.md sets the diagnostic order: a source missing from the pool is a retrieval loss, one in the pool but not in context is a rerank loss, and one in context but not in the answer is a generation loss. Widening blurs that order. The given chunks are the stored chunks by id, so a source that reached the answer only through a widened neighbour counts as missing here although the answer saw it.

Explained in Ep 1: Where each passage got to: in the pool, in the context, cited From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
  // The rerank call's trace has the pool's texts but no files, so each is given the case's file for `holds`.  const pool = (calls.find((x) => x.pool)?.pool ?? []).map((text) => ({ file: fileOf(c), text }))  const pooled = c.sources.map((s) => holds(pool, s))

In the pool Eval run

WhatTakes the pool texts from the traced rerank call (the passages read back out of its prompt), labels each with the case's file from fileOf(), and checks each expected source against them. Every pool passage gets the same label, so the label never tells them apart and they are matched on text alone. For resume-02 (corpus both), book passages are labelled resume.pdf too.

WhyThe pool is what retrieval passed to the reranker (up to POOL = 48 passages, or every chunk when the account's documents are read whole), so a source missing from the pool was lost by retrieval. Round 2 in evals/JOURNAL.md added this measure to separate retrieval misses from rerank misses.

evals/runs/2026-10-30T13-49-56-stream-final, resume-02: 7/7 of 48 in pool, 3/7 in context, cited 7/7 (the other 4 were in widened neighbours, which in context does not count)

  // Whether a cited passage backs each expected source.  const supported = c.sources.map((s) => holds(cited, s))

Cited support Eval run

WhatFor each expected source, whether a cited passage holds it.

WhyThis measure tests the citations: when a cited passage holds the evidence, a reader who follows the citation can verify the fact. Cited passages carry the joined text of a widened passage, so this count can exceed the in-context count.

  // Model errors, answers cut off at max_tokens and refusals are listed on the result, whatever its status.  const errors = calls.filter((x) => x.error || x.stop_reason === 'max_tokens' || x.stop_reason === 'refusal').map((x) => `${x.model}: ${x.error ?? x.stop_reason}`)

Model errors Eval run

WhatLists every traced call that has an error or a stop_reason of max_tokens or refusal, as model: reason.

WhyThese failures often leave no trace in the answer, because the demo app falls back or recovers. In evals/JOURNAL.md, Baseline, the reranker hit its 256-token cap on 4 of 25 questions, and each ranking was discarded without a sign. Listing the errors on every result, whatever its status, keeps a pass that hid a failure from looking clean.

  // An answer call with no traced rerank pool means the reranker failed before a reply came back.  if (asked.status === 200 && calls.some((x) => x.given) && !calls.some((x) => x.pool)) errors.push('no rerank call')

No rerank call Eval run

WhatIf the ask returned 200 and an answer call was traced but no rerank call with a pool was, adds the error no rerank call.

WhyThe demo app reranks before every answer. An answer without a rerank call that carries a pool means the reranker threw before its request was sent, or its request failed outright: the eval Worker traces a timeout or a dropped connection with an error and no pool, because it reads the pool back only once a reply arrives. In both cases the demo app falls back to fusion order, and nothing in the answer shows it.

  let status  // An answer case passes on found and every fact; a fallback case passes on a fallback, and an answer there is `review`: a person reads it.  if (asked.status !== 200) status = 'error'  else if (c.expected_behavior === 'answer') status = found && facts.every((f) => f.met) ? 'pass' : 'fail'  else if (c.expected_behavior === 'fallback') status = found ? 'review' : 'pass'  else status = found ? 'review' : 'pass'

The status Eval run

WhatA status other than 200 is error. An answer case passes when found is true and every fact is met, and fails otherwise. Every other case (fallback, and correct_or_fallback through the last else) passes on a fallback and is marked review when the demo app answered.

WhyWhether an answer about an absent topic or a false premise is right needs a reader, so code never passes or fails it. review sends it to a person (evals/JOURNAL.md, Baseline: the three false-premise answers were reviewed by hand). The fallback branch and the final else are identical, so correct_or_fallback differs from fallback only in name.

evals/runs/2026-10-30T13-49-56-stream-final: pass 24, fail 1, review 5, error 0 of 30

  // `n/m` counts for the summary and the table: how many of the expected items were met.  const count = (xs) => `${xs.filter(Boolean).length}/${xs.length}`

n/m counts Eval run

Whatcount formats a list of booleans as the number true over the length, for example 7/7.

Whycount produces the counts in the summary line and the record's sources_in_pool, sources_in_context and sources_supported strings, which the report's table prints unchanged.

  // The full record goes into results.json; `summary` is the one line printed per case.  return {    id: c.id, corpus: c.corpus, category: c.category, question: c.question, expected: c.expected_behavior, status,

The record: the case Eval run

WhatThe returned object starts with the case's id, corpus, category, question and expected behaviour, and the status.

WhyEach result carries its case's question and expected behaviour (and, in facts, its fact names), so results.json can be read on its own. It does not carry the match terms or the evidence quotes. The cases_hash in the run's meta identifies the version of cases.jsonl that held them.

    // A stopped answer was answered: what was shown counts, with the reason it stopped.    found, answer, refused: body.refused ?? null, stopped: body.stopped ?? null, first_ms: body.first_ms ?? null, http: asked.status,

The record: the reply Eval run

Whatfound, the answer text, refused and stopped (null when absent), first_ms and the HTTP status.

Whyrefused carries the check's reason for a fallback (for example empty), and stopped carries the reason an answer stopped partway (for example overlong), so the report can say why a case fell back or stopped.

evals/runs/2026-10-30T13-49-56-stream-final: book-20 stopped overlong, book-18 refused empty

    facts, retrieval: { pool: pool.length, sources_in_pool: count(pooled), k: given.length, sources_in_context: count(retrieved), per_source: retrieved },    citations: { cited: cited.length, sources_supported: count(supported), pages: [...new Set(cited.map((s) => `${s.file} p${s.page}`))] },

The record: retrieval and citations Eval run

Whatfacts; retrieval, with the pool size, sources in pool, k, sources in context and the per-source booleans; citations, with the number cited, the sources supported and the distinct file-and-page pairs cited. k is the number of passages in the answer prompt (a widened passage counts once), read back by id. k is 0 when no answer call was traced.

WhyThe pool size and k next to the counts show how much each stage had to choose from: 7/7 in a pool of 9 (a résumé read whole) is a different result from 7/7 in a pool of 48.

evals/runs/2026-10-30T13-49-56-stream-final, resume-01: 7/7 of 9 in poolevals/runs/2026-10-30T13-49-56-stream-final, book-20: k=0, a stopped answer whose answer call was not in its trace, $0.0012

    forbidden_claims: c.forbidden_claims, model_calls: calls, errors, ms, usd,    summary: `${found ? 'answered' : 'fallback'}; facts ${count(facts.map((f) => f.met))}; in pool ${count(pooled)}; in context ${count(retrieved)}; cited ${count(supported)}${errors.length ? `; ${errors.join(', ')}` : ''}`,  }}

The record: the rest, and the summary Eval run

Whatforbidden_claims copied from the case, every traced model call, the errors, ms and usd, and summary: answered or fallback, then the facts, in-pool, in-context and cited counts, then any errors.

Whyforbidden_claims are recorded and never checked. No code tests the answer against them, so the person reading the answers applies them. The full model calls (tokens, stop reasons, the reranker's reply) let a case be diagnosed later without running it again.