Eval harness · Eval runner · The PDFs uploaded · stage 2 of 5
One demo account per corpus
Before the first case, the runner creates one demo account for each corpus that the selected cases name: a row in the demos table, the same kind a visitor gets at sign-up, which owns the files, chunks and questions sent with its access key. It extracts each of the corpus's PDFs with pdf.js exactly as demo.html does in the browser, and posts the pages to the demo app's real upload route, which chunks, stores and embeds them (INGEST 1–7). It then polls until Vectorize returns a vector for every chunk, and empties the model-call trace so that the first case's trace holds only that case's calls.
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.mjs70 / 70 lines on this page explainedlines 74-104,138-176 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
/** A page's text as demo.html extracts it in the browser. */
Doc comment: text as demo.html extracts it Never runs
WhatStates the contract: each page's text, extracted as demo.html extracts it.
WhyThe demo Worker never receives a PDF, only the text the browser sends. The harness must send the same text, or it evaluates input that no visitor produces.
asyncfunctionpagesOf(file) {// Open the PDF from the corpus folder.const pdf = await pdfjs.getDocument({ data: newUint8Array(readFileSync(`evals/corpus/${file}`)), verbosity: 0 }).promise
Open the PDF Eval run
WhatReads evals/corpus/<file> into a Uint8Array and opens it with pdf.js's getDocument. verbosity 0 silences pdf.js's warnings.
WhyThe runner reads the PDF from disk, where the browser reads a File's arrayBuffer. From getDocument on, the calls are the same as demo.html's.
// Read each page's text in turn.const pages = []for (let n = 1; n <= pdf.numPages; n++) {const content = await (await pdf.getPage(n)).getTextContent()// pdf.js gives text runs with whether a line ends at each; joined as demo.html joins them, so the Worker sees what a browser would send.const text = content.items.map((item) => item.str + (item.hasEOL ? '\n' : ' ')).join('').replace(/[ \t]+/g, ' ').replace(/ *\n */g, '\n').trim() pages.push({ page: n, text }) }
Each page's text, joined as the browser joins it Eval run
WhatFor each page, getTextContent returns text items. Each item's str is followed by a newline when hasEOL is set and by a space otherwise. Then runs of spaces and tabs collapse to one space, spaces around newlines are removed, and the result is trimmed.
WhyThe expression is the same as the one in demo.html's pagesOf (the same map, join and two replace patterns, with the same pdf.js version), so line breaks reach the chunker where a visitor's would. The chunker depends on them, because it treats ".\n" as a sentence end (evals/JOURNAL.md, The failure: real PDFs were cut mid-sentence before it did).
// Blank pages are left out.return { page_count: pdf.numPages, pages: pages.filter((p) => p.text !== '') }}
Drop blank pages Eval run
WhatReturns page_count, the PDF's full page count, and pages, which keeps only the pages whose text is not empty, each with its 1-based page number.
WhyThis is the shape of the upload body. page_count counts against the demo account's 300-page limit (INGEST 3) even for pages with no text, and the page numbers stay true to the PDF, so citations name the right page.
asyncfunctioncall(path, body, key) {const headers = { 'Content-Type': 'application/json' }// The demo key picks the demo the request acts on, as the X-Demo-Key the site sets from the browser's cookie does.if (key) headers['X-Demo-Key'] = key
Headers and the access key Eval run
WhatAlways sends Content-Type: application/json, and sends X-Demo-Key when a key is given.
WhyOn the live site, the Pages Function reads the visitor's access key from the demo cookie and sends it as X-Demo-Key. The Worker hashes that key with SHA-256 and looks up the demo account by its key_hash. Sending the header directly reaches the same signedIn() lookup without the site in front.
// Send it, and read the reply as JSON when it is JSON.const response = awaitfetch(`${BASE}${path}`, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) })return { status: response.status, body: await response.json().catch(() =>null) }}
Send, and read the reply Eval run
WhatReturns { status, body }, with body parsed as JSON or null when parsing fails. The request does not ask for text/event-stream (Node's fetch sends Accept: */*), so /api/ask answers with one JSON body instead of server-sent events.
WhyThe status is returned with the body because scoring treats any ask that does not return 200 as an error. Because a JSON parse failure is caught, a non-JSON reply is reported through its status instead of crashing the runner.
// One demo per corpus, each with its PDFs uploaded through the real route.const demos = {}const corpusHash = {}
Two maps: each corpus's account, and PDF hashes Eval run
WhatThe map demos will hold each corpus's demo account as { key, id }, and corpusHash each PDF's short SHA-256 for the results.
WhyThe case loop reads the demos map to ask each question with its corpus's key. corpusHash goes into the meta of results.json, so a comparison of two runs shows whether the PDFs were the same.
for (const [name, files] ofObject.entries(CORPUS)) {// Only a corpus some selected case uses gets a demo, so an --only run uploads less.if (!cases.some((c) => c.corpus === name)) continue
Only the corpora in use Eval run
WhatWalks CORPUS in order (resume, book, both) and skips any corpus that no selected case names.
WhyUploading and embedding the book is the slow part of setup, so an --only run of résumé cases never uploads it.
// A fingerprint no card has: each run gets demos of its own, named after it.const { body } = awaitcall('/internal/demos', { fingerprint: `eval-${runId}-${name}` })// The reply holds the demo's id and key; the key authorises the uploads and, later, the questions. demos[name] = body
Create the corpus's demo account Eval run
WhatPOSTs /internal/demos with the fingerprint eval-<runId>-<corpus>. The Worker's createDemo inserts a demos row under a random id, stores only the SHA-256 of a fresh 32-byte key, and replies { key, id }.
Whycard_fingerprint is UNIQUE, and a known fingerprint only gives its existing demo account a new access key, so a fingerprint that carries the run id guarantees a new, empty demo account for each run. The reply is not checked. A reply without a key makes the upload go without X-Demo-Key, and the upload's 401 stops the run at the status check. A non-JSON reply makes body.key throw.
fingerprint: eval-<runId>-<corpus>key: 32 random bytes, base64url
for (const file of files) {// Each PDF is hashed once for the results, then extracted as a browser would and posted to the upload// route, which chunks, stores and embeds it. corpusHash[file] ??= sha(readFileSync(`evals/corpus/${file}`))const extracted = awaitpagesOf(file)
Hash once, extract Eval run
WhatFor each PDF of the corpus, the hash is computed only the first time (??=, because resume.pdf and book.pdf also appear in both), and the pages are extracted with pagesOf.
WhyExtraction is redone for each upload instead of cached. It runs locally, costs nothing, and keeps each upload independent.
// Upload it; a failed upload stops the run.const up = awaitcall('/api/files', { name: file, ...extracted }, body.key)if (up.status !== 200) thrownewError(`${file} did not upload to ${name}: ${JSON.stringify(up.body)}`)console.log(`${name}: ${file}, ${extracted.page_count} pages, ${up.body.chunks} chunks`) }
Upload through the real route Eval run
WhatPOSTs { name, page_count, pages } to /api/files with the account's access key. Any status other than 200 throws with the reply. On success the runner logs the corpus, file, page count and the chunk count from the reply.
Why/api/files is the route the browser uses, so validation, the limits, chunking, storage and embedding (INGEST 1–7) all run as they do for a visitor. A failed upload must stop the run, because questions over a missing document would score as retrieval failures.
// Poll every 2 seconds, for up to 3 minutes, until the index holds a vector for every chunk.for (let i = 0; ; i++) {// A transient failure of the check is a "not yet", never a crash.const indexed = (awaitcall('/eval/indexed', { demo_id: body.id }).catch(() => ({ body: null }))).body ?? { ready: -1, chunks: 0 }// Vectorize writes asynchronously: wait until every chunk's vector reads back, or the first cases would search a half-built index.if (indexed.ready >= indexed.chunks && indexed.chunks > 0) breakif (i > 90) thrownewError(`Vectorize had ${indexed.ready} of ${indexed.chunks} vectors for ${name} after 3 minutes`)awaitnewPromise((r) =>setTimeout(r, 2000)) }}
Wait until every vector reads back Eval run
WhatEvery 2 seconds, POSTs /eval/indexed with the account's id. That route counts the account's chunks in D1 and how many of their ids Vectorize's getByIds returns. The loop stops when ready ≥ chunks and chunks > 0, and throws on the 92nd check, after 91 two-second waits (about 3 minutes). A failed check reads as ready -1, chunks 0, which means not yet.
WhyVectorize applies upserts asynchronously, so a query right after an upload would search a partial index. The vector half of hybrid retrieval would miss the chunks not yet written, and the first cases would be scored on degraded retrieval. A failed check is retried because one repeat died when the readiness check answered empty once (evals/JOURNAL.md, Repeats of the final configuration).
// Read and discard the trace, so the first case's read holds only that case's model calls.awaitcall('/eval/trace')
Empty the trace Eval run
WhatGETs /eval/trace and ignores the reply. The eval Worker returns and clears every model call traced so far.
WhyEach read of the trace returns the calls since the last read. Uploads make no Claude calls (embedding goes to Workers AI, which is not traced), so this read is a guard: anything in the list now belongs to no case, and the first case's cost and pool must be its own.