retrieval() runs on every question and on every search_documents call from the MCP server, and returns up to 48 candidate chunks. It runs two searches over the same chunks, keyword search (BM25) and vector search (bge-m3 embeddings in Vectorize), and merges their rankings by reciprocal rank fusion. For a question, the candidates go on to the reranker at ASK 5.
demo/src/app.ts41 / 41 lines on this page explainedlines 52-53,470-504,682-685 of 1124; the rest are on other stage pages
demo/src/retrieval.ts154 / 154 lines on this page explainedevery line of the file
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
/** How many chunks the reranker reads: 24 missed passages a book's answer sat in (evals/runs). */constPOOL = 48
The candidate pool size Module load
WhatRetrieval returns at most 48 chunks, and the reranker (Claude Haiku, ASK 5) reads all of them.
WhyIn evals/JOURNAL.md round 2, one book case (book-03) failed because its answering passage was not in a pool of 24 (the evals' book then had 501 chunks). Round 3 measured a pool of 48: two cases began to pass and one began to fail, a net gain of one. The reranker still passes at most 12 chunks (ANSWER_CHUNKS) to the answer model.
POOL = 48vector topK = 48BM25 limit = 96 when vector ids are present; 48 when keyword search answers alone
Explained in Ep 1: A retrieval miss: the passage outside a pool of 24, fixed by 48 From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
/** * ASK 3-4 · retrieval: the chunks a question is answered from, with every chunk of the demo. * * Reads the demo's chunks from D1, runs the vector search, and hands both to `fuseKeywordAndVector` * (retrieval.ts), which runs the keyword search (BM25) and merges the two rankings. The stage is * split this way on purpose, for testability. Everything that reaches a service and can be * missing or fail (D1, the embedding model, Vectorize) is here, with its fallbacks, so that * `fuseKeywordAndVector` stays a pure function of plain values (chunks, question, ids in; chunks out) that * can be exercised with arrays alone, no bindings, no fakes. `all` is returned too: the caller * reads documents whole when they fit and widens the chosen chunks by their neighbours in it. */
Why the stage is split in two Never runs
WhatThe doc comment names the stage (ASK 3–4) and explains the split. retrieval() does the I/O, and fuseKeywordAndVector does the ranking.
WhyEvery call that can be missing or fail (D1, the embedding model, Vectorize) is in retrieval(), with its fallback. The ranking is then a pure function of arrays, which tests can call with plain data and no bindings.
WhatTakes the visitor's question, the Worker's bindings (env), the model clients (models) and the demo account's row. Returns all, every chunk of the account, and retrieved, the fused candidates.
Whyall is returned too because answering() needs it twice: it reads an account of 12 chunks or fewer (ANSWER_CHUNKS) whole, and widen() looks up neighbours in it. The MCP tool search_documents also calls retrieval() (mcp.ts:271) and skips the rerank.
// `all`: every chunk of this demo's documents, from D1, for keyword search.const all = (await env.DB.prepare('SELECT id, file, page, text, seq FROM chunks WHERE demo_id = ? ORDER BY rowid').bind(demo.id).all<Chunk>()).results
Every chunk, from D1 Query time
WhatOne query reads every chunk of this demo account (id, file, page, text, seq) in insertion order (rowid).
WhyKeyword search has no stored inverted index. BM25 scores every chunk on every question, so it needs them all. The cost stays low because the upload limits (INGEST 3) cap a demo account at 300 pages and 500,000 characters. With chunks of at most 900 characters (CHUNK_CHARS, chunks.ts), an account at the 500,000-character limit holds at least 556 chunks, and more when its pages are short, since no chunk crosses a page.
// `near`: vector search. The question is embedded (Workers AI) and Vectorize returns the ids of// the chunks closest in meaning, best first. If either is missing or fails, `near` stays empty// and retrieval falls back to keyword search alone.letnear: string[] = []
near starts empty Query time
Whatnear will hold the vector search's chunk ids, best first.
WhyThe empty array is the fallback. If a binding is missing or a call throws, near stays empty, fusion returns keyword search alone, and the demo app still answers.
WhatWhen the Worker has both the AI and the VECTORS bindings (embedFor and vectorsFor return undefined without them), the question is embedded with bge-m3 on Workers AI. models.embed takes a list of texts and returns one vector per text, and [values] keeps the first.
WhyThe question must be in the same embedding space as the chunks, so the model that embedded them at INGEST 6 embeds it too.
// The namespace is `demo.id`: the demo's own row id in D1, 16 lowercase letters, digits and x// made in `createDemo` (`upload` stored each chunk's vector under it). So only this// demo's vectors are searched, for the POOL (48) closest to the question's vector; the// result is their chunk ids, best first. near = await models.vectors.query(demo.id, values, POOL)
Query this account's namespace Query time
WhatVectorize searches only the demo account's namespace (its own partition of the vector index, named by the account's id), where INGEST 6 stored the account's chunk vectors, and returns the ids of the 48 chunks nearest the question's vector.
WhyThe namespace is the isolation boundary, so one visitor's question never searches another visitor's documents. The index was created with the cosine metric (README, Run it), so Vectorize returns the approximate nearest neighbours by cosine similarity. The account's id is 16 characters long: createDemo encodes 12 random bytes as unpadded base64url, lower-cases the result and replaces - and _ with x.
namespace = demo.id (16 characters: 12 random bytes, base64url, lower-cased, - and _ → x)topK = POOL = 48metric: cosine (set at index creation)
Explained in Ep 2: ANN indexes (HNSW, IVF) and the account's Vectorize namespace From RAG deep dive, Ep 2: RAG Embeddings Explained: BM25, Vector Search and Cosine Similarity
The same idea, shown with HNSW, one kind of ANN index: Greedy descent through the layers, then a search of width ef From RAG deep dive, Ep 3: HNSW Algorithm Explained: Hierarchical Navigable Small World Graph for ANN Search
} catch (error) {console.error('demo ask: the vector index did not answer; BM25 alone', error) } }
Fall back, don't fail Query time
WhatAn error from the embedding model or Vectorize is logged and caught, and near stays empty.
WhyA vector outage degrades search to BM25 alone instead of failing the question. The log line records the outage, so a drop in answer quality can be traced to it later.
Explained in Ep 1: Hybrid search: BM25, vector search and reciprocal rank fusion From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
// ASK 3-4 · retrieval: every chunk (D1) and the vector search (Vectorize), merged with keyword// search (BM25) into the candidate pool. `retrieval` above says why it is split from `fuseKeywordAndVector`.yield { type: 'stage', stage: 'retrieving' }const { all, retrieved } = awaitretrieval(question, env, models, demo)
Where answering() calls retrieval() Query time
Whatanswering() yields a stage event, which the demo page shows as "Searching your documents…", then awaits retrieval().
WhyASK 1 (validate) and ASK 2 (reserve one of the account's ten questions) have already run. Before ASK 5 (rerank and widen), the result goes through the whole-document check and the empty-pool fallback (lines 686–703).
The status line during retrieval. The page shows "Searching your documents…" when it sends the question, and again when the retrieving stage event arrives. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
demo/src/retrieval.ts The ranking, written as pure functions of arrays that call no service.
/** * Which chunks a question is answered from: BM25 over the demo's own chunks, * fused by reciprocal rank with the vector index's nearest. * * Ported from Howard's Lantern's worker/src/law-retrieval.ts * (`words`, `bm25`, `retrieve`): the same tokens, the same BM25 constants and * the same RRF k. The law-specific steps (scope, rephrase, widen, nationwide, * spelling repair) are left out. */
What this module does, and where it came from Never runs
WhatThe module comment: keyword search (BM25) over the account's chunks, fused by reciprocal rank with the vector index's nearest chunks.
WhyThe module is ported from Howard's Lantern's law retrieval (law-retrieval.ts), with the same tokens, BM25 constants and RRF k. The law-specific steps, its widen among them, were left out. The neighbour widening at ASK 5 (widen.ts) is adapted separately, from wholeSections in learner-ask.ts.
exportinterfaceChunk {id: stringfile: stringpage: numbertext: string/** Its place in its file's order of chunks; null for chunks stored before the order was. */seq?: number | null/** The last page of a widened passage that runs past `page`. */lastPage?: number}
The Chunk shape Type only
Whatid, file, page and text, plus seq (the chunk's position in its file) and lastPage (set when a widened passage runs onto a later page).
WhyChunks are made at INGEST 4 (chunks.ts) and stored at INGEST 5. widen() uses seq to find a chunk's neighbours. Chunks stored before seq existed have null there.
/** The usual constant for reciprocal-rank fusion: it keeps one list's first place from swamping the other's. */exportconstRRF_K = 60
RRF_K = 60 Module load
WhatThe k of reciprocal rank fusion. Each ranked list adds 1 / (k + rank) to the score of every chunk it ranks.
Why60 is the value from the RRF paper (Cormack, Clarke and Büttcher, 2009). A large k flattens the curve, so first place is worth little more than tenth (1/61 against 1/70), and a chunk ranked well by both searches beats one ranked first by only one.
/** Words too common to tell chunks apart, dropped from the question and the chunks alike so they neither match nor score. */constSTOP = newSet('a an and are as at be by can could do does for from how i if in is it its me my of on or should so that the their them there this to was what when where which who why will with would you your'.split(' '),)
The stop words Module load
What47 common English words in a Set, built once when the Worker loads the module.
WhyThese words appear in nearly every chunk, so they cannot tell chunks apart. Dropping them from both the question and the chunks means they never match and never score.
/** A text as the tokens BM25 compares: lower-cased runs of letters and digits, stop words out, a plain plural's "s" off. */exportfunctionwords(text: string): string[] {// Anything but a letter or digit separates tokens, so punctuation and case never stop a match.return (text.toLowerCase().match(/[a-z0-9]+/g) ?? [])
Lower-case, split on anything else Query time
WhatThe text is lower-cased, and every run of a–z or 0–9 becomes a token. Every other character separates tokens.
WhyCase and punctuation never block a match: "BM25," and "bm25" are the same token. The pattern is ASCII only, so an accented letter splits a word ("café" becomes "caf"), the same way on both sides.
.filter((word) => !STOP.has(word))// "invoices" must find "invoice"; "bus" must not become "bu". .map((word) => (word.length > 3 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word))}
Drop stop words, strip a plain plural Query time
WhatStop words are filtered out. A token longer than three letters that ends in s, but not ss, loses the s.
WhyThis is a light stemmer. "invoices" finds "invoice", while "bus" (too short) and "class" (ss) are left alone. It is applied identically to questions and chunks, so "analysis" → "analysi" still matches itself. Its limit shows on irregular plurals: "policies" becomes "policie", which does not match "policy".
Explained in Ep 2: BM25 tokens: lower-case, stop words dropped, a plural stripped From RAG deep dive, Ep 2: RAG Embeddings Explained: BM25, Vector Search and Cosine Similarity
/** The chunks sharing words with `question`, best first. A chunk with no word of the question is never returned. */exportfunctionbm25(chunks: Chunk[], question: string, limit: number): Chunk[] {// No chunks, nothing to rank.if (chunks.length === 0) return []
Signature and the empty case Query time
WhatTakes the chunks, the question and a limit, and returns chunks best first. With no chunks it returns an empty list at once.
// Document frequency: for each word, how many chunks contain it (the n of the idf below).const frequency = newMap<string, number>()// Each chunk reduced once to its length in tokens and its count of each word (its tf), so scoring never re-reads the text.const docs = chunks.map((chunk) => {const counts = newMap<string, number>()const tokens = words(chunk.text)for (const word of tokens) counts.set(word, (counts.get(word) ?? 0) + 1)// Once per chunk, not per occurrence: idf asks how many chunks hold the word, not how often it is written.for (const word of counts.keys()) frequency.set(word, (frequency.get(word) ?? 0) + 1)return { length: tokens.length, counts } })
Term frequencies and document frequencies Query time
WhatEach chunk is tokenised once into its length and a count of each token (tf). frequency counts, for each token, how many chunks contain it (n), adding 1 per chunk and never per occurrence.
WhyThis is the index BM25 needs. It is built fresh on every question because nothing is stored between asks. Counting once per chunk is what makes n a document frequency.
book: 629 chunksbook: "agentic" n = 3book: "model" n = 230
// The average chunk length, which each chunk's length is measured against; `|| 1` avoids dividing by zero when no chunk has a word.const average = docs.reduce((sum, doc) => sum + doc.length, 0) / docs.length || 1
Average chunk length Query time
WhatThe mean token count across all chunks. || 1 replaces a zero average with 1.
WhyLength normalisation compares each chunk's length with this average. The fallback covers an account where no chunk has any token (every chunk is only stop words or punctuation), which would make the average 0.
// The usual BM25 constants. k1 sets how fast repeats of a word stop adding score (the second occurrence adds far more// than the tenth); b sets how much a chunk's length counts against it (0 not at all, 1 in full proportion).const k1 = 1.2const b = 0.75
// Score every chunk against the question's words, then keep the best.return docs .map((doc, index) => {let score = 0for (const word of asked) {// n: how many chunks hold the word; tf: how often this chunk does. A word this chunk lacks adds nothing.const n = frequency.get(word)const tf = doc.counts.get(word) ?? 0if (n === undefined || tf === 0) continue
For each chunk, for each asked word Query time
WhatEach chunk's score starts at 0. For each asked token, the loop looks up n (how many chunks hold the token) and tf (how often this chunk holds it). A token that no chunk holds, or that this chunk lacks, is skipped.
WhyOnly shared tokens can add score, which is why keyword search never returns a chunk with no word of the question.
// idf: a word held by few chunks says more about a chunk than one held by most, so it weighs more. The + 0.5s keep// the ratio finite when a word is in every chunk, and the 1 + keeps idf positive, so a common word adds a little, never less than nothing.const idf = Math.log(1 + (chunks.length - n + 0.5) / (n + 0.5))
Inverse document frequency Query time
Whatidf = ln(1 + (N − n + 0.5) / (n + 0.5)), where N is the number of chunks.
WhyA rare token says more about a chunk than a common one. The classic Robertson–Spärck Jones idf, ln((N − n + 0.5) / (n + 0.5)), is negative for any token in more than half the chunks; the 1 + (Lucene's form) keeps every idf positive.
// tf saturates through k1, and is divided by the chunk's length relative to the average, so a long chunk does not// outscore a short one just by holding more words. score += (idf * tf * (k1 + 1)) / (tf + k1 * (1 - b + (b * doc.length) / average))
Saturated, length-normalised term frequency Query time
WhatAdds idf × tf × (k1 + 1) / (tf + k1 × (1 − b + b × length / average)) to the chunk's score.
WhyEach repeat of a word adds less than the one before, and a long chunk cannot win only by holding more words. At average length the tf part is 1.0 for one occurrence, 1.57 for three and 1.96 for ten, and never exceeds 2.2 (k1 + 1).
Explained in Ep 2: BM25 scoring: IDF, saturated term frequency (k1), length (b) From RAG deep dive, Ep 2: RAG Embeddings Explained: BM25, Vector Search and Cosine Similarity
// A chunk with no word of the question scores 0 and is dropped, so keyword search names only real matches and// fusion never gives a non-match a rank. .filter((scored) => scored.score > 0)
Drop non-matches Query time
WhatChunks that scored 0 are removed.
WhyKeyword search names only real matches, so fusion never gives a chunk a keyword rank it did not earn.
/** * Picks the chunks a question should be answered from, best first, by combining * two rankings of the same chunks. * * Inputs: * - `chunks`: every chunk of the demo's documents, read from D1 by the caller. * - `question`: the visitor's question. * - `limit`: how many chunks to return. * - `near`: the vector search results, passed in. These are the chunk ids the * vector index (Vectorize) returned as closest in meaning to the question, * best first. This function does not call the vector index: the caller * (`retrieval` in app.ts) embeds the question, queries Vectorize, and hands the ids * in here. It may pass none, if there is no index or the query failed. * * The two rankings: * - keyword search: `bm25`, run here over `chunks`, which favours chunks that * share the question's exact words; * - vector search: `near`, as given. * * The two are merged by reciprocal rank fusion (RRF): each chunk scores * 1 / (RRF_K + its rank) in each list it appears in, and the scores add up, so * a chunk ranked well by either search rises, and one ranked well by both * rises furthest. * * Only ids that are among `chunks` count: a vector id for anything else, such * as a chunk since deleted, is dropped here and never shown. When no vector * ids are left (no index, or it failed), the result is keyword search alone. */
The contract Never runs
WhatThe doc comment states the inputs (the chunks from D1, the question, the limit, and near from Vectorize), the two rankings and how RRF combines them.
WhyIt also states two guarantees the code keeps: an id that is not one of these chunks (a chunk since deleted) is never shown, and with no vector ids the result is keyword search alone. The comment names the caller, retrieval() in app.ts, which the ask's answering() and the MCP tool search_documents both call.
exportfunctionfuseKeywordAndVector(chunks: Chunk[], question: string, limit: number, near: string[] = []): Chunk[] {// Chunks by id, to check the vector ids and to turn ids back into chunks.const byId = newMap(chunks.map((chunk) => [chunk.id, chunk]))
Signature and the id map Query time
Whatnear defaults to an empty list. byId maps each chunk's id to the chunk.
WhyThe map has two uses: to check that a vector id is still one of this account's chunks, and to turn ranked ids back into chunks.
// The vector search results passed in as `near`, kept only if they are still this demo's chunks.const meant = near.filter((id) => byId.has(id))if (meant.length === 0) returnbm25(chunks, question, limit)
Stale ids out; no vectors, keyword alone Query time
WhatVector ids that are not among the chunks are dropped. If none remain, the function returns BM25 at limit and stops.
WhyThe ids come from Vectorize, a different store from D1. A vector id that no longer matches a chunk in D1, such as a chunk removed by DELETE /api/files or the idle purge, is dropped here, so a removed document can never be cited. The early return is the fallback retrieval() relies on.
// Chunk id -> its summed RRF score. Ranks are 0-based, hence the + 1.const fused = newMap<string, number>()constadd = (ids: string[]) => ids.forEach((id, rank) => fused.set(id, (fused.get(id) ?? 0) + 1 / (RRF_K + rank + 1)))
Reciprocal rank fusion Query time
Whatfused maps an id to its summed score. add walks a ranked list and adds 1 / (60 + rank + 1) for each id. rank is 0-based, hence the + 1.
WhyRRF uses only ranks. vectorsFor's query keeps only the ids (models.ts:226), so Vectorize's scores never reach this function, and BM25 scores (book: around 18) and cosine similarities (book: around 0.5) are on different scales in any case.
Explained in Ep 2: Reciprocal rank fusion of the BM25 and vector rankings From RAG deep dive, Ep 2: RAG Embeddings Explained: BM25, Vector Search and Cosine Similarity
// Twice as many keyword results as needed, so a chunk just below the cut can still rise by its vector rank.add(bm25(chunks, question, limit * 2).map((chunk) => chunk.id))
The keyword list, at twice the pool Query time
WhatBM25 is asked for limit × 2 results (96 at the demo app's candidate pool size of 48), and their ids are added first.
WhyA chunk ranked 60th by keywords but high by vectors still gets its keyword share, and can reach the final 48.
// Then the vector search results, in their own order.add(meant)
The vector list Query time
WhatThe surviving vector ids are added in Vectorize's order.
WhyA chunk in both lists gets two shares and rises. In the book, for the k1-and-b question, b195 was BM25 rank 1 and vector rank 5, so it scored 1/61 + 1/65 = 0.0318. Fusion can also hurt. For "Why can't I trust a reply just because it sounds sure of itself?", the answering chunk b15 is vector rank 1 but shares no word with the question, and fusion drops it to 9th.
// Highest fused score first, cut to `limit`, ids turned back into chunks.return [...fused.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, limit) .map(([id]) => byId.get(id) asChunk)}
Best first, cut, back to chunks Query time
WhatSorted by fused score, highest first, cut to limit, and the ids mapped back to chunk objects.
WhyThe returned chunks are the same objects that all holds, so later code tests membership by object identity: answering() (app.ts:692), rerank() (models.ts:292) and widen().