The retrieval pipeline: chunking, query rewriting, hybrid search, filtering

Everything between a document collection and the passages a model reads and cites: chunking, BM25 and learned sparse, fusion, query rewriting, filters, duplicates, prompt assembly, and measuring where an answer is lost. Measured on the topic's running example (SciFact, NFCorpus, QASPER, HotpotQA) on an Apple M1 Pro; published results kept apart. A child of Topic: rag-and-retrieval. Data as of October 2026. Reading: 47 min, plus 35 in closed details.

The idea in one screen

An answer can use only the evidence that survives every stage: cut into a chunk that holds it whole, found by words or vectors under the user's filters, kept through fusion and reranking into the few chunks the prompt holds, then read and cited. So the pipeline is built for recall first, and judged by where, on your own labelled questions, the evidence is lost.

Fig. 1 walks the stages with the largest measured effect of each stage's main knob, then follows the evidence of 188 SciFact claims through the root's measured pipeline. Most knobs move a result by one or two points; three move it by ten or more: cutting along the document's structure, a strong reranker after a recall-oriented first stage, and rewriting a chat follow-up into a standalone question. measured

  1. Index time, once per document. Parsed text is cut into chunks with metadata and stored twice: in a BM25 index (words) and a vector index. Cutting where the author did (paragraphs within sections) instead of fixed 256-token windows raised the QASPER questions whose evidence is handed over within 1,024 tokens from 56.8% to 70.0% (bge-small; §1).
  2. Query time, once per question. The question arrives with the chat history and the user's rights. A chat follow-up is rewritten into a standalone question (the relevant abstract at rank 1 for 2 of 8 constructed chats before, 6 after; §5); the user's filter goes inside each search, because a post-filter at 10% visibility returns 1.73 of 10 results (§6).
  3. Search both, fuse, rerank. BM25 and the vector index each return a ranked list; RRF merges them (Qwen3-Embedding on SciFact, nDCG@10 0.700 → 0.724; §4) and a cross-encoder reorders the top 30 (→ 0.778 with Qwen3-Reranker-0.6B, root runs; owned by the rerankers page).
  4. Assemble the prompt, answer, cite. The top k chunks go in with short ids and merged spans; Qwen3-1.7B answers and names the abstract it used. Raising k from 1 to 10 moved the strictly right answers only from 97 to 101 (§7, §8).
  5. Follow the evidence of 188 claims. 186 have their evidence in the fused top 30, 178 keep it in the top 3, and 96 are answered right and cited: 2 lost by retrieval, 8 by ranking, 82 by the generator (§9).

You need: what an embedding is and how one is chosen (Embedding models), and the stage map on the root, Topic: rag-and-retrieval, whose shared runs (its src/pipe) measured the headline results this page builds on. Approximate nearest-neighbour indexes are Vector indexes from the inside; rerankers are Rerankers and late interaction; parsing PDFs into text is Document ingestion and multimodal retrieval; loops where the model writes its own queries are Agentic retrieval, long context and memory.

Chunk
a piece of a document indexed on its own; the unit retrieval returns.
BM25
the standard word-matching score over an inverted index.
Hybrid search, fusion
run BM25 and a dense retriever, then merge the two ranked lists into one.
RRF
reciprocal rank fusion: each list adds 1 / (k + rank) for each document.
Pre-, post-filter
a metadata condition applied inside the search, or to its results afterwards.
Small to big
search small units (sentences), hand over the larger unit (paragraph) that contains the match.
HyDE, multi-query
search with a generated answer passage, or with several rewordings fused.
Self-query
a model turns conditions in the question into a structured filter.
MMR
maximal marginal relevance: choose each next result for relevance minus similarity to those already chosen.
r, p, g
found in the first stage's top K, kept in the top k that reach the prompt, answered correctly: A = r × p × g.

The running example (defined in the root's data README): SciFact, 5,183 scientific abstracts and 300 test claims, most with exactly one relevant abstract; NFCorpus, 3,633 medical documents and 323 test questions with many graded relevant documents each; QASPER, 281 NLP papers with 892 questions whose evidence paragraphs annotators located in the text (the set for chunking); HotpotQA, 200 two-hop questions over 9,760 Wikipedia paragraphs. Scores are nDCG@10 (1.0 when the relevant documents fill the top ranks) and recall@k (share of relevant documents in the top k), defined in section 9. measured = run on an Apple M1 Pro in October 2026; published = from the cited source; constructed = inputs written for this page.

Every knob measured on this page, in one table (reference)
stageknobwhat it did on the running examplesection
chunkingcut where the author did (paragraphs, sections) instead of every N tokensevidence kept whole for 607 → 832 of 892 QASPER questions; found within 1,024 tokens 56.8% → 70.0% (bge-small) root runs§1
chunkingretrieve small, return big (sentence → its paragraph)0.789 against 0.700 for paragraph-aware chunks at 1,024 tokens measured§1
chunkinglate chunking (embed the whole paper, pool per chunk)hurt here: paragraph-aware chunks found within 1,024 tokens 0.733 → 0.684, fixed windows 0.556 → 0.536 (modernbert-embed-base) measured§1
BM25k1 and b tuned on held-out queriesSciFact 0.679 → 0.678; NFCorpus 0.318 → 0.322 (barely moves) measured§2
BM25title as its own weighted field (BM25F)SciFact 0.679 → 0.689 measured§2
fusionscore fusion with a weight tuned on held-out queries, instead of RRFSciFact Qwen3: RRF 0.725, z-score 0.739; after a reranker: 0.782 against 0.776 measured§4
queryroute each query to BM25, dense or hybrida learned router 0.721 against always-hybrid 0.724; a perfect router would reach 0.798 measured§5
queryfilters extracted from the question by the local generator (self-query)the generator added a month to all 100 year-only requests, so its filter dropped the right paper for 93 of them; checking each extracted value against the request fixed that (found within 1,024 tokens, year-only requests: 22 with no filter, 17 raw filter, 25 checked) measured constructed queries§5
filtersfilter inside the search, not after itpost-filter at 10% visibility returns 1.73 of 10 results root runs§6
diversityMMR (penalise near-duplicates of what is already chosen)hurt on every set here; HotpotQA both gold paragraphs in the top 5: 137 → 75 at λ 0.5 measured§7
promptwhere the evidence sits among 10 abstractsgold abstract first, middle or last among 10: 116, 68 and 78 of 188 strictly right (the right label alone: 118, 109, 113) measured§8

Measure every knob on your own labelled queries, tuned on one split and reported on another.

1. Chunking: cut where the author did

An embedder reads a few hundred tokens and returns one vector; a prompt holds a few thousand tokens. So a 6,000-token paper is cut into chunks, each indexed alone, and only some reach the model. A cut can lose the answer in two ways: the evidence paragraph is split, so no chunk holds it whole, or the chunk that holds it has lost the context that would make it match ("the model" without saying which). The root's shared runs measured the headline on QASPER: fixed 256-token windows keep an evidence paragraph whole for 607 of 892 questions, splitting on paragraphs first keeps 832 to 838, and at an equal budget of 1,024 tokens the share of questions whose evidence is handed over rises from 56.8% to 70.0% (bge-small) root runs. Fig. 2 shows why, on one real section: the Common Voice section of the CoVoST paper (QASPER, arXiv 2002.01320), 600 tokens in five paragraphs, every one of them evidence an annotator used for some question.

  1. The section. One slab per paragraph, its length the paragraph's tokens (66, 114, 83, 303 and 34); the green strip marks annotated evidence. Predict before stepping: how many paragraphs survive whole under each splitter?
  2. Fixed windows of 128 tokens, 16 overlapping. Each window takes the next 128 tokens wherever they end, then steps back 16. Six windows; all five window ends that are not the section's end fall inside a paragraph (red walls).
  3. The evidence check, fixed windows. A paragraph counts when one chunk holds it whole: only the two short ones at the ends survive, 2 of 5.
  4. The recursive splitter at the same size. It splits on blank lines first and merges paragraphs while they fit, so its cuts fall between paragraphs; only the 303-token paragraph, longer than a chunk, is split again at sentence ends (two red walls).
  5. The evidence check, recursive. 4 of 5 paragraphs whole; the one it splits could not fit in any 128-token chunk.
  6. Over all 892 questions (root runs, 256-token chunks, bge-small): evidence intact for 607 with fixed windows plus overlap, 838 with the recursive splitter, 832 with paragraphs packed within sections; found within 1,024 tokens 56.8%, 67.9% and 70.0%.

The same cuts on the real text

Red bars are cuts; green underline is evidence an annotator used; orange is overlap, stored twice. The view follows Fig. 2's step, or switch it yourself.

What the recursive splitter does (LangChain's default, read in langchain-text-splitters 1.1.3): it holds separators from coarse to fine, ["\n\n", "\n", " ", ""]; splits on the first one present; keeps pieces already under the target; merges consecutive short pieces up to the target, carrying a tail of up to overlap into the next chunk; and recurses with the next separator on any piece still too long. The default list has no sentence separator: after the newline comes the space, so a long paragraph is cut between two words wherever the size runs out (add ". ", as the root's rule and Fig. 2 do). The source, and the check that the real library reproduces the root's numbers, are in the closed block below.

Size is counted in the embedder's tokens

A token is the unit a model reads, as cut by its tokenizer. Every model limit is in tokens (bge-small reads 512, all-MiniLM-L6-v2 reads 256 by default; anything longer is silently cut off), but LangChain's TextSplitter measures characters by default: chunk_size=4000, chunk_overlap=200, length_function=len (base.py lines 64 to 66).

Predict: LangChain's default splitter (4,000 characters) feeding all-MiniLM-L6-v2. What share of the text ends up in the vectors?
LangChain recursive splitter, as configuredmedian chunk, BERT tokenschunks over 256 (MiniLM)text MiniLM actually readschunks over 512 (bge-small)text bge-small reads

1,500 chunks sampled per setting (seed 0) from all 281 papers; counts include [CLS] and [SEP]. Even sized in tokens, the tokenizer must be the embedder's: of chunks cut to 256 Qwen3 tokens, 16.9% are longer than 256 for MiniLM's tokenizer (the same text is about 5% longer in a BERT vocabulary). src/exp/chunk_make.py measured

Overlap is stored twice. 32 tokens of overlap on 256-token windows add about 14% to the tokens embedded and move fixed windows from 546 to 607 intact questions, still far below the 832 of cutting at paragraphs root runs; the chunk-count formula is in the closed block.

Structure first, then small to big

When a document carries its own structure, cut along it. QASPER has Markdown headings, so LangChain's MarkdownHeaderTextSplitter splits at each heading, records the heading path as metadata (for filters and citations), and a size cap applies inside each section: 832 intact and 0.652 found with BM25 at 1,024 tokens, level with the root's paragraphs-within-sections rule (832; 0.645) measured.

Small chunks match precisely (a sentence is about one thing); big chunks carry the context the model needs. Small to big (or parent-child) retrieval does both: index small units, and when one matches, hand over the larger unit that contains it. LlamaIndex's SentenceWindowNodeParser is one form (it embeds single sentences and returns three on each side, DEFAULT_WINDOW_SIZE = 3, llama-index-core 0.14.25). Measured on QASPER within each question's paper (bge-small, parents handed over in the order their children rank until 1,024 tokens are used, each parent once):

Semantic chunking (embed each sentence, cut where neighbours are least similar) lost here: the root ran LangChain's SemanticChunker defaults (cut above the 95th percentile of distances) and got chunks of median 342 and up to 4,967 tokens, last at an equal 1,024-token budget (38.6% with BM25) root runs. It costs an embedding call per sentence and has no size cap; where real paragraphs exist, the author's breaks are the better boundaries.

Search by sentence, hand over the paragraph: the best unit here

evidence paragraph covered (root's rule)an extractive answer string handed over (646 questions)

Sentence → parent paragraph reaches 0.789 against 0.775 for ranking whole paragraphs and 0.700 for paragraph-aware 256-token chunks. Bare sentence windows look bad under the paragraph rule (0.398) but hold up when the test is only whether the answer string arrived (0.598 against 0.712). Whole sections as parents fall to 0.604: one section can eat the budget. measured

Giving a chunk its document's context

Two methods attack the second failure, a chunk that lost its context. Late chunking (Günther et al., Jina AI, arXiv 2409.04701) runs the whole document through a long-context, mean-pooling embedder once, then averages the token vectors inside each chunk's span, so a chunk that says "the model" carries which model; published gains are large for weak embedders and small for strong ones (NFCorpus nDCG@10 23.5 → 30.0 with jina-embeddings-v2-small, none with nomic-embed) published, authors' runs. Run here with modernbert-embed-base it hurt: hurt here: paragraph-aware chunks found within 1,024 tokens 0.733 → 0.684, fixed windows 0.556 → 0.536 (modernbert-embed-base) measured; every chunk competing within one paper shares the same context, which makes them more alike, not easier to tell apart. Contextual retrieval (Anthropic, post of 2024-09-19) has a model write 50 to 100 tokens situating each chunk and prepends them before indexing; the vendor's top-20 retrieval failure rate fell from 5.7% to 3.7%, and to 1.9% with contextual BM25 and a reranker published, vendor, while the root's run with Qwen3-1.7B on 71 papers was within noise (at 1,024 tokens 57.7% → 55.2%) root runs. Late chunking costs one extra forward pass per document; contextual prefixes cost a generator call per chunk.

Chunking in depth: chunk counts, the splitter's source, tokenizers, structure-aware splitters, sentence segmentation, the published numbers, mixed indexes (depth)

How many chunks, how many tokens stored.

Fixed windows of c tokens overlapping by o start a new chunk every c − o tokens (the stride). A 10,000-token document at c = 512, o = 64 gives a stride of 448, ⌈9,936 / 448⌉ = 23 chunks and 10,000 + 22 × 64 = 11,408 tokens stored, 14% more than the text:

n = ⌈(L − o) / (c − o)⌉,    T = L + (n − 1) · o
n
chunks for a document of L tokens (one when L ≤ c)
T
tokens stored and embedded: every overlap is stored twice

The formula gives the exact chunk count for all 281 papers at 128/16, 256/32 and 512/64, with stored overhead 14.1%, 13.9% and 13.5% measured.

Characters per token. How many tokens a character count means depends on the tokenizer:

tokenizer (all 281 QASPER papers, 6,762,684 characters)tokenscharacters per tokentokens per word

src/snippets/split_tokens.py (runs in the page's own env; its output below is real)

from transformers import AutoTokenizer
from langchain_text_splitters import RecursiveCharacterTextSplitter

tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")   # reads at most 256 tokens
n = lambda s: len(tok(s)["input_ids"])                                           # counts [CLS] and [SEP] too
for name, sp in [("library default, 4,000 characters", RecursiveCharacterTextSplitter()),
                 ("tutorial setting, 1,000 characters", RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)),
                 ("256 MiniLM tokens", RecursiveCharacterTextSplitter.from_huggingface_tokenizer(tok, chunk_size=254, chunk_overlap=32))]:
    sizes = [n(c) for c in sp.split_text(paper_text)]    # paper_text: QASPER's CoVoST paper (arXiv 2002.01320)
    seen = sum(min(s, 256) for s in sizes) / sum(sizes)
    print(f"{name:36s} {len(sizes):3d} chunks, largest {max(sizes):4d} tokens, MiniLM reads {seen:.0%} of the text")
# output
library default, 4,000 characters      5 chunks, largest  909 tokens, MiniLM reads 33% of the text
tutorial setting, 1,000 characters    24 chunks, largest  316 tokens, MiniLM reads 98% of the text
256 MiniLM tokens                     24 chunks, largest  256 tokens, MiniLM reads 100% of the text

langchain_text_splitters/character.py, lines 98 to 107 (defaults) and 110 to 149 (_split_text; abridged and reflowed onto fewer lines, highlighted lines verbatim)

    def __init__(self, separators=None, keep_separator=True, is_separator_regex=False, **kwargs):
        super().__init__(keep_separator=keep_separator, **kwargs)
        self._separators = separators or ["\n\n", "\n", " ", ""]

    def _split_text(self, text, separators):
        separator = separators[-1]; new_separators = []
        for i, s_ in enumerate(separators):              # first separator present in this text wins
            if not s_: separator = s_; break
            if re.search(re.escape(s_), text): separator = s_; new_separators = separators[i + 1:]; break
        splits = _split_text_with_regex(text, re.escape(separator), keep_separator=self._keep_separator)
        good_splits = []
        for s in splits:
            if self._length_function(s) < self._chunk_size: good_splits.append(s)   # short enough: keep for merging
            else:
                if good_splits: final_chunks.extend(self._merge_splits(good_splits, separator_)); good_splits = []
                if not new_separators: final_chunks.append(s)                    # nothing finer: an oversize chunk
                else: final_chunks.extend(self._split_text(s, new_separators))   # recurse with the next separator
        if good_splits: final_chunks.extend(self._merge_splits(good_splits, separator_))
        return final_chunks

The merge step (base.py lines 167 to 210) drops pieces from the front of the running chunk while the running total is above the overlap, which is how the overlap is made: the last few pieces of one chunk start the next.

Checked against the root. The root's runs reimplemented this rule. Running the real library on all 281 papers with sizes in Qwen3 tokens (from_huggingface_tokenizer, 256 tokens, 32 overlap) gives the same result: 838 of 892 questions with evidence intact (root: 838) and 0.617 found with BM25 at 1,024 tokens (root: 0.613) measured. The 1,000-character tutorial setting keeps 794 intact; the 4,000-character default keeps all 892 intact (its chunks are huge) but then fits almost nothing into a 1,024-token budget (0.385).

The Markdown splitter's quirk (markdown.py lines 250 to 257 and 107): it strips every line, drops blank lines and re-joins a section's lines with two spaces and a newline, so paragraph breaks ("\n\n") no longer exist when the size cap runs; the cap falls back to single newlines. Harmless on QASPER, where each paragraph is one line; costly on text whose paragraphs wrap across lines. The library also has HTMLHeaderTextSplitter and per-language separators for code (for Python "\nclass ", then "\ndef ", then "\n\tdef " before blank lines, character.py lines 366 to 374), so functions stay whole when they fit. Not run here: the running example has no HTML or code corpus.

Sentences. A regex such as the root's (cut after . ! ? followed by a capital, digit or bracket) breaks on abbreviations. On 94 QASPER papers the regex makes 15,931 sentences of which 252 end on an abbreviation such as "et al.", "Fig." or "No."; pySBD 0.3.4 makes 16,174 with 84 such ends measured. Under 2% either way, and sentence packing is a poor chunker here anyway (593 intact, below fixed windows with overlap) because it ignores paragraph and section breaks root runs.

Late chunking, published and run. It needs an embedder that pools by averaging and a context long enough for the document; longer documents go through in overlapping windows ("long late chunking", the paper's Algorithm 2). The paper's Table 2 (nDCG@10 on BEIR, 256-token chunks): jina-embeddings-v2-small NFCorpus 23.5 → 30.0 and SciFact 64.2 → 66.1 (Jina's blog of 2024-08-22 prints 23.46 and 29.98); jina-embeddings-v3 35.6 → 36.7 and 71.8 → 73.2; nomic-embed-text-v1 35.3 → 35.3 on NFCorpus; an average relative gain of about 3.5% for fixed-size chunks published, authors' runs. Merola and Singh (arXiv 2504.19754, April 2025) found contextual retrieval "preserves semantic coherence more effectively" while late chunking "offers higher efficiency but tends to sacrifice relevance and completeness". Run here with nomic-ai/modernbert-embed-base (ModernBERT, 149 M parameters, 8,192 tokens, mean pooling, Apache 2.0): it did not help. Within each question's own paper, at a 1,024-token budget, paragraph-aware chunks found 0.733 of questions embedded one by one and 0.684 with late chunking; fixed 256-token windows 0.556 against 0.536; the top-1 chunk is right for 0.318 against 0.243 (paragraph-aware) measured. The setting explains it: every chunk competing here comes from the same paper, so the document-wide context late chunking adds is shared by all of them and makes them more alike, not easier to tell apart. The published gains come from search across many documents (BEIR), where knowing which document a chunk belongs to is exactly what separates it. Cost: one pass over each whole paper (19 of 281 papers were longer than 8,192 tokens and went through in overlapping windows) took 376 s against 168 s for embedding the chunks one by one on MPS, because attention over long sequences costs more than over many short ones. The root lab's contextual prefixes showed the same within-paper pattern.

Contextual retrieval in detail. The vendor's failure rate was 2.9% with contextual embeddings plus contextual BM25, before the reranker. With prompt caching (the document is read once per document, not once per chunk) the vendor put the one-off cost at $1.02 per million document tokens, assuming 800-token chunks, 8,000-token documents and 100 tokens of context per chunk published, vendor. In the root's run, llama.cpp's prompt cache cut the prompt tokens from 11.1 M to 0.87 M, and bge-small top 3 moved 46.9% → 49.4% root runs.

Mixing chunking strategies in one index. The old version of this page said mixing strategies across ingestion runs "can cost about 8 points of recall". No source was found, so it was tested: one index over all 281 papers, half chunked in 128-token windows and half in 512-token windows, searched globally with bge-small:

indexfound within 1,024 tokens, all 892questions about the 512-token halfquestions about the 128-token halflong chunks: share of index / of top 10s

The mixed index lands between the two uniform ones. The papers re-chunked to 512 do worse than in an all-512 index (0.216 against 0.269), because they compete with small chunks for the same budget; so mixing moves recall by about five points for the affected half, and the old "8 points" is dropped. What holds: a chunker change should re-index the whole corpus, in both the BM25 and the vector index; how chunk boundaries move when one document is revised is measured in section 9 of Document ingestion and multimodal retrieval.

Chunking workbench: cut two real papers yourself, any strategy and size (interactive)

Two real QASPER papers, cut live in your browser by the same chunkers the topic measures (a line-by-line port of the root's src/pipe/chunkers.py, checked equal to the Python output on both papers by src/check_js.mjs: 18 of 18 configurations give identical spans). Sizes are counted in Qwen3 tokens, as everywhere on this page. Move the size and overlap, switch the strategy, and watch two things: whether an annotated evidence paragraph (green underline) survives whole inside one chunk, and whether the chunks a retriever would hand over within a token budget cover it.

Try: fixed windows at 256 tokens, then the same size with the recursive splitter: count the questions whose evidence stays intact. Then untick ". " (LangChain's default separators have no sentence separator) and watch long paragraphs get cut mid-sentence.
Recursive separators, tried in order:
chunks (alternating)overlap (stored twice)annotated evidencehanded over within the budget#1 BM25 rank

Every strategy on this paper, at this size

Overlap applies to fixed windows and the recursive splitter. "Found" = the chunks handed over within the budget cover at least 90% of an evidence paragraph (the root's rule). Retrieval in this table uses a small BM25 written for the page (Lucene formula, no stemmer), so it can differ slightly from the bm25s numbers measured over all 892 questions above.

Measured over all 281 papers and 892 questions: this section and the root's shared runs (src/pipe of Topic: rag-and-retrieval). Paper text: QASPER (CC BY 4.0), arXiv 1910.06592 and 2002.01320.

2. BM25: the tokenizer matters more than k1 and b

A dense retriever finds paraphrases but can rank a vaguely related abstract above the one that names the exact gene; a word-matching retriever finds the exact word every time. BM25 ("Best Match 25", Robertson and colleagues, 1990s) is the standard word-matching score, computed over an inverted index (for every word, the documents containing it and how often). The formula from zero, with a calculator, and how the index is stored inside a database are on Search and vector databases (its section 4, "Ranking with BM25"). In one line: score(D, Q) = Σt in Q idf(t) · tf / (tf + k1 · (1 − b + b · |D| / avgdl)), where k1 sets how fast repeats stop counting and b how much document length matters. One SciFact claim, scored term by term:

The non-relevant review wins because "statin" appears seven times in it, though saturation already caps that: in this 111-term abstract seven occurrences give 0.88 of the maximum, against 0.52 for one. The relevant abstract is missing "decrease" entirely. That is BM25's blind spot: it cannot know that "lowering LDL" means "decrease cholesterol".

Tuning k1 and b buys nothing once you pick on held-out queries

Test-split nDCG@10 for every (k1, b); switch to the tuning split (SciFact train, 809 claims; NFCorpus dev, 324 questions) to see what you would pick without peeking. Outlined: the default (1.2, 0.75). Ringed: the best pair on the tuning split. Across k1 0.9 to 3 and b 0.4 to 1 SciFact moves by about a point. Tuned on training claims, the best pair (k1 1.5, b 0.4) scores 0.678 on test against 0.679 for the default; the pair picked on the test claims themselves would claim 0.688, a point that exists only because it was chosen on the answers. NFCorpus: tuning on dev picks k1 1.5, b 0.6 and gives 0.322 against 0.318. Extreme values do hurt (k1 0.2, or b 0 on SciFact). src/exp/bm25_sweep.py measured

The tokenizer. BM25 only sees the terms its tokenizer produces. bm25s's default lowercases, keeps runs of two or more word characters (token_pattern=r"(?u)\b\w\w+\b", tokenization.py line 572), drops Lucene's 33 English stopwords (which include "no" and "not": "X causes Y" and "X does not cause Y" become the same query), and optionally stems ("decreases" and "decreased" both become "decreas"). Stemming is worth 1.7 points of nDCG@10 on SciFact and 1.3 on NFCorpus; stopwords change nothing here. The two-character pattern silently drops single characters: "Type 1 Diabetes" loses the "1", "IL-6" becomes just "il", "H2A.Z" loses its "Z"; 109 of the 300 SciFact claims contain such a token, and keeping them is worth 0.7 points measured. On technical text, check what the tokenizer does to identifiers before trusting the BM25 half of a hybrid.

tokenisation (k1 1.2, b 0.75)SciFact nDCG@10SciFact recall@100NFCorpus nDCG@10vocabulary (SciFact)
BM25 in depth: the Lucene variant, the reimplementation check, defaults, variants, BM25F (depth)

The one-line formula is the "Lucene" variant as bm25s computes it (bm25s/scoring.py lines 115 to 130 and 190 to 195, tag 0.3.13); the textbook version multiplies the fraction by (k1 + 1), a constant that changes no ranking. A 60-line NumPy version written for this page (src/exp/bm25lab.py) reproduces the setup's recorded bm25s run: identical top-10 scores for 281 of 300 SciFact claims and 310 of 323 NFCorpus questions (the rest differ only in how zero-score documents pad the list) measured.

Defaults differ: bm25s uses k1 1.5 and b 0.75 (bm25s/__init__.py lines 146 and 147); Lucene and Elasticsearch use 1.2 and 0.75, as does the running example.

Variants. The Robertson, ATIRE, BM25L and BM25+ formulas (bm25s implements all five, following Kamphuis et al., ECIR 2020) differ in the idf floor and in a small boost for long documents; on SciFact they span 0.679 to 0.686 and on NFCorpus 0.318 to 0.322. Pick one and move on.

Fields: BM25F. A title is short and on topic; a body is long. BM25F (Robertson, Zaragoza and Taylor, CIKM 2004) normalises each field by its own average length, weights it, and adds the fields before saturation, so a word in both title and body is not counted as two independent pieces of evidence:

tf̃ = Σf wf · tff / (1 − bf + bf · |Df| / avgdlf),   score = Σt idf(t) · tf̃ / (k1 + tf̃)

With the title weight chosen on the tuning split (titles average 10 terms against 147 for SciFact abstracts): SciFact 0.679 → 0.689 (title weight 2), NFCorpus 0.318 → 0.321 measured. Elasticsearch's combined_fields query "takes a principled approach to scoring based on the simple BM25F formula" (Elasticsearch docs, read 2026-10-14); multi_match with best_fields scores each field on its own and keeps the best, which is a different thing.

3. Learned sparse retrieval

Keep BM25's machinery (an inverted index, a score summed over shared terms) but let a model choose the terms and their weights, including expansion terms the text lacks but a reader would expect. How SPLADE builds that vector, why v2 pools by the maximum where v1 summed, how sparsity is trained, the inference-free variant and its published scores are taught on Rerankers and late interaction, section 10, with a real document vector. Here it matters as a third ranked list to fuse (section 4).

Run here: opensearch-neural-sparse-encoding-doc-v3-distill (67 M parameters, Apache 2.0) through sentence-transformers' SparseEncoder, documents encoded on MPS (42 and 38 documents per second, load average about 11 to 18 from other jobs). nDCG@10: SciFact 0.708 against 0.679 for BM25 and 0.700 for Qwen3-Embedding; NFCorpus 0.345 against 0.318 and 0.363 measured. Fused with Qwen3-Embedding by RRF it scores 0.724 (SciFact) and 0.364 (NFCorpus), level with BM25 + Qwen3 (0.724, 0.361). A document keeps 239 non-zero terms on average and a query 20 (SciFact) or 5 (NFCorpus), so the index stays an inverted index. Caveat: the model card lists SciFact and NFCorpus among its training sets, so these scores are in-domain and flatter it against BM25 and the dense models, which never saw these sets.

4. Fusion: merging two ranked lists

Hybrid search runs BM25 and a dense retriever on the same query and gets two ranked lists whose scores live on unrelated scales: a BM25 score of 8.96 and a cosine of 0.71. The root's shared runs measured the two common answers (RRF lifts Qwen3-Embedding on SciFact from 0.700 to 0.724; z-score fusion with a weight tuned on training claims reaches 0.739) root runs. This section is why each works and what each throws away.

Why raw scores cannot simply be added. BM25 is unbounded above (a SciFact claim's top-1 score ranges from 6.9 to 28.5, 5th to 95th percentile); Qwen3-Embedding's top-1 cosines range from 0.56 to 0.83 measured. Add them with equal weight and BM25 decides almost alone: 0.5 · BM25 + 0.5 · cosine scores 0.685, close to BM25 alone (0.679). The trap is the equal weight, not the addition: give the cosine 0.99 of the weight (chosen on training claims) and the raw sum scores 0.734, as good as any normalised method. The weight absorbs the scale difference, so it must be learned on labelled queries for each pair of retrievers, and again whenever either changes.

RRF(d) = Σlists r 1 / (k + rankr(d))
rankr(d)
position of d in list r, from 1; a list that does not contain d adds 0
k
60 in the paper (Cormack, Clarke and Büttcher, SIGIR 2009: "fixed during a pilot investigation"), the default rank_constant in Elasticsearch and OpenSearch and in most libraries: it damps the top ranks, so being in both lists counts for more than being first in one
Predict (the old page's worked example): dense returns A, B, C, D; BM25 returns C, D, E, A. With k = 60, what is the fused order?

Fig. 3 runs RRF on one claim's real lists (the claim chosen in the widget below; it opens on the claim about TET proteins).

  1. Two ranked lists, unrelated scales. BM25's top 10 behind, Qwen3-Embedding's in front, each bar its own score (BM25 about 6 to 9 here, cosines about 0.6); green is the annotators' relevant document.
  2. Only ranks count. Each list gives a document 1 / (60 + rank): rank 1 earns 1/61 = 0.0164 and rank 10 earns 1/70 = 0.0143, only 13% less. k = 60 flattens the top of each list.
  3. Agreement adds up. Each document's two contributions stack in the fused row (BM25 below, dense above), and the dots stream from where it ranked in each list; the label "b3 d5" means third in BM25, fifth dense. A document in both lists beats any document found by one, whatever its rank there.
  4. The fused top 10. On the TET claim five documents are in both top 10s, and they push the relevant abstract, third in the dense list and absent from BM25's top 20, down to seventh. The line under this list gives the ranks and nDCG@10 for the query chosen in the widget.
  5. Over every test query. On SciFact: BM25 0.679, Qwen3-Embedding alone 0.700, RRF at k 60 0.724, z-score fusion with a weight chosen on training claims 0.739 (nDCG@10). The bet on agreement loses on some claims and wins on average.

RRF uses only ranks, so it needs no calibration and no tuning, and the root's runs found k barely matters (0.724 to 0.732 across k from 1 to 1,000). Watch it work on real lists: the card fuses one query's BM25 and dense top 20 with method A, then re-sorts the same candidates into method B's order.

Same candidates, two fusion methods: watch which documents each promotes

BM25 and Qwen3-Embedding-0.6B lists for SciFact claims and NFCorpus questions, relevant documents in green. A starts as RRF (k 60), B as the raw scores added at equal weight; press Animate A → B, then try B = z-score. nDCG@10 here is over these top-20 lists (the aggregates use the full top 100); functions as in src/exp/fusion_deep.py.

BM25 (score)
Qwen3-Embedding (cosine)
A
B

Rows: fused rank, title, the fused score, and the document's rank in BM25 / dense ("b3 d12"; "–" = not in that top 20). measured

What RRF throws away is how sure each retriever is. Scores carry that: on SciFact, when a retriever's first result beats its second by a wide relative margin, the first result is relevant far more often.

What RRF bets on is agreement, and the bet is good: on SciFact with Qwen3-Embedding, of the documents in both top 10s, 22.8% are relevant; of those only BM25 found, 0.8%; only dense, 1.8%. On NFCorpus, with many relevant documents per question: 52.0% against 9.9% and 15.9% measured.

A runaway winner is usually right; RRF scores it like a near-tie

300 SciFact test claims split into five equal groups by the relative margin (s1 − s2) / s1 of each retriever's own top two scores; bar = share of claims whose top-1 result is relevant. Score fusion keeps a runaway winner's big normalised score; RRF gives it the same 1/(k+1) as a near-tie. src/exp/fusion_deep.py measured

The whole family, tuned honestly

The score-combination family is older than RRF (Fox and Shaw, TREC-2, 1994): normalise each list (min-max or z-score), then add with a weight (CombSUM), or multiply that sum by the number of lists containing the document (CombMNZ, an explicit agreement bonus). Each knob was chosen on the tuning split (SciFact train, NFCorpus dev) and scored once on test; the root's RRF, min-max and z-score numbers are reproduced exactly.

Every method's knob swept over all test queries; the ring is the honest number

nDCG@10 on the test split (SciFact 300, NFCorpus 323) as the knob moves, per embedder. Ringed: the knob chosen on held-out queries; the curve's peak is what tuning on test would claim. With a learned weight, normalised score fusion beats RRF for every model about as good as BM25: Qwen3 on SciFact 0.725 (RRF) against 0.739 (z-score) and 0.741 (CombMNZ); on NFCorpus 0.366 against 0.375. For gte-modernbert, nine points better than BM25 on SciFact, every method lands within a point of the model alone: when one list dominates, fusion has little to add. measured

Every method in one table, three-list fusion, products (depth)

nDCG@10 on test; in brackets the knob chosen on the tuning split (k for RRF, the dense weight otherwise). Bold: best per column. src/exp/fusion_deep.py measured

CombMAX keeps each document's best normalised score and is the weak member (it ignores agreement); weighted RRF gives each list its own weight; Borda count adds positions. Fusing three lists (BM25, Qwen3 and gte with RRF) scores 0.771 on SciFact, against 0.747 for the two embedders alone. In products the choice is a setting: Elasticsearch, OpenSearch and Weaviate let you weight the lists or fuse normalised scores instead of ranks (OpenSearch's normalization processor, docs); tune the weights on labelled queries, never by eye. Hybrid search measured inside Postgres (BM25 over Postgres lexemes, pgvector, and RRF in one SQL statement on 522,931 Quora questions and SciFact) is on Search and vector databases, section 11.

After a reranker, RRF is enough

The old page claimed weighted fusion "rarely beats plain RRF plus a reranker". Tested with the recorded Qwen3-Reranker-0.6B scores, reranking the top K of each fused list on SciFact test:

Before the reranker z-score fusion is ahead (0.739 against 0.724); after it the gap closes or flips: RRF's top 20, reranked, scores 0.782, z-score's 0.776; at K 30 they score 0.778 and 0.778. The reranker reorders the candidates itself, so what matters is which documents are in the top K, not their order. So the claim holds here: tune the fusion weight when there is no reranker; with one, RRF is enough and the effort is better spent on the depth K (measured on Rerankers and late interaction).

5. Understanding and rewriting the query

The text a user types may need a different retriever (an error code wants BM25), contain a condition that should be a filter ("papers from 2019"), lean on earlier turns of a chat ("does it help?"), be phrased unlike the documents, or ask two things at once. Query understanding is everything done to the query before the search (routing, extracting filters, rewriting); each costs time before retrieval starts, so each has to earn its place on measured queries.

Routing: the ceiling is high, the router is not

On SciFact, BM25 beats Qwen3-Embedding on 56 claims, loses on 81 and ties on 163, so a perfect router choosing per claim among BM25, dense and hybrid would score 0.798 against 0.724 for always-hybrid. A logistic-regression router on nine query-time features separates "BM25 wins" from "dense wins" only weakly (ROC AUC 0.67) and scores 0.721, slightly below always-hybrid. Even "identifiers go to BM25" fails: the 172 claims with a digit or an inner capital (gene and protein names) score 0.707 dense and 0.666 with BM25 measured. So fuse by default, and route only between query types that really differ (part-number lookups against natural questions) after checking on labelled queries that the router beats fusion. Routing between whole sources or tools is on Agentic retrieval, long context and memory.

Self-query: words in the question become a filter

"In the CoVoST paper, how many languages..." mixes a metadata condition into the question; embedded, the title words only nudge the vector, while as a filter they restrict the search to the right document. Self-query retrieval asks a language model to split the request into a cleaned query and a structured filter over known fields (LangChain's SelfQueryRetriever pattern). Measured with the local generator (Qwen3-1.7B, greedy) on 300 constructed requests: real QASPER questions with a reference to their paper added by template, a third by title, a third by month and year of the arXiv posting, a third by year only; search over all 6,463 default chunks of 281 papers with bge-small; found = the root's rule within 1,024 tokens.

Titles were resolved well, but the generator invented values: the generator added a month to all 100 year-only requests, so its filter dropped the right paper for 93 of them; checking each extracted value against the request fixed that (found within 1,024 tokens, year-only requests: 22 with no filter, 17 raw filter, 25 checked) measured. So an extracted filter is checked against the request and the schema before use (keep a value only if the request states it; fall back to no filter when it matches nothing): a wrong year silently removes the right document, which is worse than no filter. The filter itself runs inside the search (section 6).

Self-query, every request type and filter variant (depth)

What the numbers say. The generator always produced parseable JSON (300 of 300) and resolved titles well (the right paper alone for 88 of 100 title requests). But it invented values: every one of the 100 year-only requests came back with a month as well (always 12, December), which the request never stated, so the raw filter kept the right paper for only 7 of them and found less than no filter at all (17 against 22). Dropping any extracted value that the request does not literally state (a schema check, no model) keeps the right paper for 100 of 100 and lifts the month-and-year requests from 22 to 32 found. For title requests a filter adds little (34 without, 34 with): the title words in the query already pull the embedding to the right paper. The oracle row (the right paper as the filter) shows how much a correct filter is worth when the request only gives a date: 45 and 60 found.

Values extracted from free text (titles, names) need fuzzy matching against the real values; here the title was matched to the best word overlap among the papers that survive the year and month filters.

Rewriting: helps chat follow-ups, rarely anything else

The root's shared runs measured three rewrites on SciFact with the same generator root runs: HyDE (write a hypothetical answer passage and search with it; Gao et al., arXiv 2212.10496) lifts Qwen3-Embedding from 0.700 to 0.718 when the passage replaces the claim, and helps bge-small only when the passage vector is averaged with the claim's (0.713 → 0.733; the passage alone gives 0.692); multi-query (three rewordings fused with RRF) buys nothing on these already specific claims (0.699 for Qwen3); a conversational rewrite turns a follow-up that is meaningless alone into a standalone question and repairs most of eight constructed chats (the relevant abstract at rank 1 for 6 of 8 with bge-small, against 2 of 8 for the follow-up alone; one chat got worse). The old version of this page said HyDE is "largely superseded by instruction-aware embedders": here it still helped the instruction-aware Qwen3-Embedding by 1.8 points, so that claim is dropped.

Fig. 4 follows one claim through four rewrites (the claim chosen in the widget below; it opens on the ML-SA1 claim, where a rewrite moved the relevant abstract the most).

  1. The claim as typed. bge-small's top 10 over all 5,183 abstracts; the tall green box is the annotators' relevant abstract: rank 10 for the opening claim.
  2. HyDE. The generator (the glass plate) writes a hypothetical answer passage, hundreds of words where the claim had twenty, and the passage is searched instead: the relevant abstract jumps to rank 1. Purple boxes are abstracts that were not in the original top 10.
  3. HyDE + claim. The passage's vector averaged with the claim's: rank 3 here; this is the variant that helped bge-small on average.
  4. Multi-query. Three rewordings, each searched, their lists fused with RRF: rank 3.
  5. Step-back. The more general question behind the claim, searched on its own: rank 3 here, but it hurts on average (below).
  6. Over all 300 claims (bge-small, nDCG@10): original 0.713, HyDE alone 0.692, HyDE + claim 0.733, multi-query 0.724, step-back 0.669. Steps 1 to 5 show the effect where there is one; the average is what a pipeline gets.

Step-back (Zheng et al., arXiv 2310.06117: ask for the more general question behind the query and retrieve for both) and decomposition (split a multi-part question into sub-questions, retrieve for each, fuse) both hurt here: the general question retrieves general abstracts when a claim needs one specific study, and the 1.7 B generator rarely split HotpotQA's two-hop questions; where it did, fusing the lists lost gold paragraphs. A decomposition written before any retrieval cannot resolve a bridge question ("the director of the film that..."), because the second sub-question needs the first answer; that needs retrieval in a loop (Agentic retrieval, long context and memory). Tables in the closed block.

What it costs. Every rewrite is a generator call before the search: the root measured about 2.2 s per claim for HyDE and 0.8 s for three rewordings with the 1.7 B model on this laptop; here step-back took 0.3 s per claim and a decomposition 0.3 s per question measured. That is more than the whole retrieval stage (BM25 0.25 ms, query embedding 49 ms, exact search 0.5 ms in the root's latency table). Rewrite always for chat follow-ups; otherwise only for query types where it measurably helps.

One claim, the original list against a rewrite's list

Real SciFact claims, rewrites written by Qwen3-1.7B (HyDE and multi-query by the root's runs, step-back by this page), bge-small over all 5,183 abstracts (exact search). The ten claims are those, among the first 120 test claims, where a rewrite moved the relevant abstract the most: this shows the effect when there is one, not the average. Press animate and watch the green row.

Rows: rank, title, cosine (or RRF score), and the row's rank in the other list ("o3" = third in the original list; "–" = not in its top 10). Green = the annotators' relevant abstract. measured

What the generator wrote:

Routing features, NFCorpus, step-back and decomposition measured (depth)

The router. Nine features computable at query time: query length, the highest and mean idf of its terms, how identifier-like it is, each retriever's top score and its margin over the second, and how much the two top 10s overlap; two thresholds (send to BM25 above one, to dense below the other, fuse in between) chosen on the training claims. On NFCorpus: 0.360 against 0.361 (hybrid) and 0.363 (dense alone).

Step-back on the 300 SciFact claims, prompt adapted from the paper's (zero-shot, one line):

Step-back hurt every retriever: alone it scores 0.669 (Qwen3), 0.669 (bge-small) and 0.619 (BM25) against 0.700, 0.713 and 0.679 for the claim, and fused with the claim it still loses (0.678, 0.697, 0.652). The general question retrieves general abstracts, and a SciFact claim needs the one specific study. Step-back is designed for questions that need background principles (the paper tested STEM, time-sensitive knowledge and multi-hop questions), not for specific claims.

Decomposition on HotpotQA's two-hop questions (both gold paragraphs needed), the generator writing up to three sub-questions:

The 1.7 B generator mostly returned the question unchanged (1.12 sub-questions per question on average), and where it did split, fusing the lists hurt: with bge-small, questions with both gold paragraphs in the top 5 fell from 98 to 85 (bridge) and from 39 to 29 (comparison); BM25 fell the same way. Examples of what it wrote:

Conversational rewrites are measured on eight constructed chats by the root's runs and summarised on Topic: rag-and-retrieval (section 3); not repeated here.

6. Metadata filters: inside the search, never after it

Real queries carry conditions: this customer's documents, what this user may read, papers after 2020, the current version. A condition on metadata (structured fields stored next to each chunk) is a filter. The root's shared runs measured the central fact: applied after the search (a post-filter: fetch the top 10, drop what is not allowed), a filter that lets a user see 10% of SciFact returns 1.73 results of 10 on average and none at all for 14 of 300 claims; applied inside the search (a pre-filter: only allowed documents compete) it always returns 10 root runs.

  1. The corpus and one user. 200 tiles stand for the 5,183 abstracts (a constructed floor: distance from the query stands for similarity); the 20 tinted ones, 10%, are what this user may see.
  2. Filter after the search, K 10. The search fetches the 10 nearest, then the filter drops what the user may not see: 2 survive on this floor; measured over 300 claims, 1.73 of 10 on average, and none at all for 14.
  3. Fetch more first. Filtering the top 30 or the top 100 instead returns 3.70 or 9.19 of 10 (measured), for 3 or 10 times the search work, and still no guarantee.
  4. Filter inside the search. Only visible documents compete, so the 10 nearest of them come back: 10 of 10 for every claim (measured).

What to store on every chunk

  • Identity and provenance: document id, chunk index, character span or page, section path (the Markdown splitter's heading metadata, §1), source URL. Needed for citations (§8) and for deleting or replacing a document's chunks.
  • Version and time: document version or content hash, published and indexed dates. Needed for "current only" and for re-indexing (the ingestion page, section 9).
  • Access: tenant, owner, groups allowed. Needed for access control, which must be a filter inside the search, never an instruction in the prompt; measured with PostgreSQL row-level security on RAG in production.
  • Facets users filter on: language, document type, product, year. Store as typed fields (integer year, date), not inside the text, so the engine can index them.

Every chunk inherits its document's fields at index time; a metadata change (a permission revoked) must update every chunk of the document, in both the BM25 and the vector index.

The arithmetic of post-filtering

If an index returns its top K and then a filter keeps a share s of documents (the filter's selectivity), the expected number of survivors is about K · s, assuming the allowed documents are spread evenly through the ranking. The pgvector README gives the same arithmetic for its HNSW index: "If a condition matches 10% of rows, with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average" (README line 450 at tag v0.8.7, verified). Against the root's measurement:

The measured counts sit above K · s at small K because the user may always see the claim's own evidence abstract, which ranks high; real access patterns are correlated in both directions, so measure the survivors on your own data. The fix puts the filter inside the search (engines rescan or filter during graph traversal; closed block below), measured on Vector indexes from the inside (its filtered-search lab).

A post-filter keeps about K · s of the K results it fetched

Lines: K · s capped at 10. Dots: results returned of 10 asked, post-filter over the exact top K, mean over 300 SciFact claims (root runs, src/pipe/out/filter.json; each claim asked by a user who may see its evidence abstract, the constructed setting described there).

Correlated access, and how engines filter inside the search (depth)

Correlation cuts both ways: a user's own documents are often exactly what they search for; a tenant's documents may all sit far from a generic query. pgvector from 0.8.0 rescans more of the index until enough rows pass (SET hnsw.iterative_scan = strict_order or relaxed_order, stopping at hnsw.max_scan_tuples, 20,000 by default; README lines 480 and 527); Qdrant and Weaviate filter during graph traversal and switch to an exact scan when few points match.

Predict: hybrid search, with the filter applied to the fused list after RRF (each retriever returns its top 100 unfiltered). A tenant owns 1% of the corpus. How many results come back when you ask for 10?

Filters in hybrid search

BM25 filters cheaply: the engine intersects the query terms' posting lists with the set of allowed documents (a bitmap), so a selective filter makes BM25 faster. A vector index pays for a selective filter instead, because its graph or clusters were built over every document. So the two halves of a hybrid search behave differently under the same filter, and both must receive it before fusion. The filters a user never typed (tenant, permissions) come from the session; the ones they typed come from query understanding (§5).

7. Duplicates and diversity

Ten retrieved chunks that say the same thing waste nine slots of the prompt. Duplicates come from the corpus (the same abstract under two ids, a page crawled twice, mirrored documentation), from overlapping chunks (neighbours share their overlap), and from near-identical versions. Two remedies: remove duplicates, or penalise similarity among the chosen results.

NFCorpus has 41 pairs above cosine 0.995 with bge-small, and they are true duplicates: for example "Alkylphenols in human milk and their relations to dietary habits in central Taiwan." appears as MED-118 and MED-2651 with identical text measured. Exact duplicates are best removed at ingestion with a content hash, before they reach any index (the ingestion page covers content hashing). How much near-duplication each set has:

Near-duplicate pairs per corpus (reference)

Maximal marginal relevance hurt on every set

next = argmaxd not chosen [ λ · sim(q, d) − (1 − λ) · maxs chosen sim(d, s) ]
λ
1 = plain ranking by similarity to the query; lower values trade relevance for difference from what is already chosen

MMR (Carbonell and Goldstein, SIGIR 1998) builds the list greedily, each time taking the candidate most similar to the query and least similar to anything already taken. LangChain's max_marginal_relevance_search uses it with fetch_k 20 candidates and lambda_mult 0.5 by default (langchain-core 1.6.10, vectorstores/base.py lines 663 and 664). Measured on the dense top 50 of three sets:

On HotpotQA, where diversity sounds like exactly what a two-hop question needs, the questions with both gold paragraphs in the top 5 fall from 137 (λ 1) to 129 at 0.8 and 75 at 0.5 (bge-small) measured. The two gold paragraphs are not near-duplicates of each other, so MMR has nothing to remove, and the penalty pushes in loosely related paragraphs instead. MMR pays when a corpus has many near-duplicates crowding out other relevant material and when the reader wants coverage of several aspects; check that your corpus is like that before turning it on, and keep λ high.

Lower λ trades relevance for difference, and lost on all three sets

Overlapping chunks: merge, do not drop

With overlapping fixed windows, a chunk and its neighbour often both rank high, because both hold part of the same paragraph. Treating the neighbour as a duplicate and dropping it is wrong: on QASPER (bge-small, within the paper) dropping any chunk that overlaps one already chosen cuts the questions found within 1,024 tokens from 0.568 to 0.455, because the neighbour is what completes a paragraph the window boundary cut. Merging overlapping or touching chunks into one span and paying for the shared tokens once gives 0.571; MMR at λ 0.7 gives 0.512 measured.

8. Assembling the prompt, and citing

Retrieval ends with a ranked list; the generator needs one prompt. Between them sit decisions that change the answer: how many chunks (the context budget), in what order, and with what labels so the answer can cite them. Measured with the root's end-to-end task: Qwen3-1.7B (llama.cpp, greedy, thinking off) reads a SciFact claim and k abstracts and answers SUPPORT, CONTRADICT or NOT ENOUGH INFO with the number of the abstract it relied on; an answer is strictly right when the label matches the annotators' and the cited abstract is annotated evidence. 188 test claims with evidence; candidates from hybrid RRF, then Qwen3-Reranker-0.6B on the top 30; the root's answer prompt (answers identical to the root's runs were reused from its cache, so shared cells agree by construction).

How many chunks

Strictly right answers barely move with k: 97 of 188 with only the top abstract, 96 at k 3, 96 at k 5 and 101 at k 10, while the prompt grows from 504 to 3,644 tokens on average. The reranked top 3 already holds the evidence for 178 of the 188 claims (root lab), so more abstracts add little to find; this 1.7 B model's limit is reading, not finding (it never answered CONTRADICT in any of these runs, the same failure the root lab found). More context is not free even when the window allows it: prefill time grows with the prompt (about 1,040 prompt tokens per second for this model here, root's latency table), and a small model is distracted by more near-miss abstracts.

Order: put the best chunk first

Published: Liu et al., "Lost in the Middle" (arXiv 2307.03172, 2023) moved the one relevant document through 10, 20 and 30 retrieved documents and found a U shape for several models: accuracy highest with the document first or last, lowest in the middle published, authors' runs. Measured here with the claim's gold abstract placed first, in the middle or last among the reranker's highest-ranked non-evidence abstracts (hard distractors, which is what a real pipeline puts next to the evidence):

Position matters a lot here, but not as a U: the evidence first gives 111 (k 5) and 116 (k 10) strictly right of 188; in the middle 71 and 68; last 65 and 78. Look at what changes, though: the right label barely moves (107 to 118 of 188 across all six placements), the citation does. With the evidence elsewhere, the model still cites abstract [1] in 59 of 188 answers at k 10 (gold in the middle) and 45 (gold last), a pull toward the first abstract shown. So for this model, put the best chunk first, and treat citations to the first position with suspicion. Reversing the real reranked top 5 (best abstract last, nearest the question) gives 67 strictly right against 96 of 188 best-first. Longer contexts and more positions are measured on Agentic retrieval, long context and memory.

Moving the evidence away from first place costs the citation, not the label

Citation formats, and checking a citation

A citation is a pointer from the answer to a chunk; it is only useful if it can be resolved and checked. Three formats on the same top 5:

All three formats could be parsed and resolved to an abstract in the prompt for every answer (188, 188, 188 of 188), so labels the model can copy are what matters, not their style; corpus ids did as well as numbers (99 against 96 strictly right). Asking for a quote changed the answers themselves: the model never answered NOT ENOUGH INFO (0 times, against 25 with numbers), which raised strictly right answers to 108, but only 71 of its 188 quotes were found word for word in the cited abstract; the rest paraphrased or quoted the claim back. Strictly right with a verified quote: 38. A quote is the cheapest citation to check: a string match against the cited chunk, no model needed; judged support is section 9.

A template that holds up

  • Label each chunk with a short id the model can repeat exactly ([1], [2]...) and keep the mapping to document, section and span outside the prompt; here numbers and corpus ids both resolved for every answer.
  • Put each chunk's title and date in its header line: the model cannot weigh a 2019 document against a 2025 one if it never sees the dates.
  • Merge chunks that overlap or touch into one span (§7); drop exact duplicates; never truncate a chunk mid-sentence to fit the budget, drop the lowest-ranked chunk instead.
  • Keep instructions and the question outside the retrieved text, and treat retrieved text as data: a document that says "ignore previous instructions" is an injection (indirect prompt injection is owned by Agent security; its RAG specifics are on RAG in production).
  • Ask for the label or answer first and the citation in a fixed format, then parse it; count unparseable answers as wrong. If you ask for quotes, verify them: here most were not verbatim (§8).

9. Measuring the pipeline on your own set, and where an answer is lost

The golden set. Every number on this page needs one: real questions, each with the passages a human marked as answering it (and, to judge answers, a reference answer). A few hundred real, labelled questions separate systems that differ by a few points; synthetic questions written from a chunk are easy by construction, because they reuse the chunk's words. Version the set, re-label when the corpus is re-chunked, choose every knob (fusion weight, rerank depth, prompt) on a tuning split, and report the test split once: SciFact here has 809 training claims for tuning and 300 test claims for reporting.

Retrieval metrics, per question then averaged (computed with pytrec_eval, the TREC tool BEIR uses; definitions and their edge cases are owned by Evaluation metrics): recall@K, the share of a question's relevant passages in the top K (with one relevant passage, as for 277 of 300 SciFact claims, simply found or not); precision@k, the share of the top k that is relevant (irrelevant chunks in the prompt distract the generator); MRR, 1 / rank of the first relevant passage; nDCG@10, each relevant passage in the top 10 earns its grade divided by log2(rank + 1), normalised by the best possible order, so it rewards putting the right passage first. Measure the first stage's recall at the depth the reranker reads (K), not only at the k that reaches the prompt: a reranker cannot rescue what it was never given, and the two depths separate a retrieval miss from a ranking miss.

The decomposition. A question is answered correctly for the right reason only if its evidence survives three stages in a row, so end-to-end accuracy over N questions factors, and the N(1 − A) failures split into three buckets that add up exactly:

A = rK × pk|K × g,   Mretrieval = N(1 − r),  Mranking = N r (1 − p),  Mgeneration = N r p (1 − g)
rK
share whose evidence is in the first stage's top K (here K = 30): 186 / 188 = 0.989; a miss is fixed by chunking, hybrid search, query rewriting or a larger K
pk|K
of those, share whose evidence the reranker keeps in the top k that reach the prompt (k = 3): 178 / 186 = 0.957; fixed by a better reranker or a larger k
g
of those, share the generator answers correctly and cites: 96 / 178 = 0.539; fixed by the model, the prompt, the context format; so A = 0.989 × 0.957 × 0.539 = 0.511 = 96 / 188

In the full pipeline the generation bucket is 82 of 92 failures: no retrieval change can buy more than 10 answers. Two reference points bound it root runs: given only the gold abstracts (an oracle prompt), the same model and prompt get 112 of 188, the ceiling of g; with no abstracts at all (closed book) it gets the label right on 45 and can cite nothing. The decomposition assumes the answer needs its evidence, which is why the check also requires a cited evidence abstract: 4 claims got the right label with no evidence in the prompt and were refused, and without the citation check a label is cheap (two thirds of the labelled claims are SUPPORT, so always answering SUPPORT would score 66%). On another set the largest bucket may be ranking, and then the instinct "try a bigger model" is wrong; measuring the factors is what tells the two cases apart.

188 claims, one square each: where the evidence was lost

Predict first: in the root's measured pipeline, are most of the 92 failures retrieval, ranking or generation misses? Then change the pipeline and watch which colour moves.

The root's end-to-end run (src/pipe/out/e2e.json there): 188 SciFact test claims with evidence, BM25 + Qwen3-Embedding fused by RRF, Qwen3-Reranker-0.6B, Qwen3-1.7B answering with the tuned prompt; right = label matches and the cited abstract is evidence. "No reranker" hands the first stage's top k straight to the prompt (K = k). root runs

Faithfulness. Right-for-the-right-reason, as here, is the cheap check of grounding: the cited chunk must be evidence, and a requested quote must be found in it word for word (section 8: 71 of 188 were). Whether a cited chunk actually supports a free-text answer needs a judgement (a natural-language-inference model or an LLM judge); those metrics (faithfulness, groundedness, citation precision, context precision and recall), their tools and their calibration are on RAG and retrieval evaluation.

Debugging one bad answer. Log, per question, the first stage's top K, the reranked top k and the answer. Ask first "was the evidence in the prompt?", then "was it in the top K?": those one or two bits assign the failure to a stage before anyone touches a component. Then check the citation plumbing: labels the model can repeat, parse rate, resolution to chunks, quote match.

The old page's illustrative golden set, priced (depth)

The old version of this page used an illustrative golden set of N 200 with r 0.9, p 0.833 and g 0.9 illustrative: A = 0.9 × 0.833 × 0.9 = 0.675, buckets of 20 (retrieval), 30 (ranking) and 15 (generation); making r or g perfect gives 0.75, making p perfect gives 0.81 derived. There the ranking bucket was the largest, so a better reranker was the lever; on the measured run above it is the generator. Both presets are priced in this block; the root's old lever calculator was retired with its Pipeline lab on 2026-10-24.

10. Depth: mistakes, interview questions, how this was measured

Corrections to the old version of this page
  • "Mixed chunking strategies can cost ~8 points of recall": no source found; tested (§1): the affected half lost about five points; the number is dropped.
  • "HyDE is largely superseded by instruction-aware embedders": on SciFact HyDE still lifted the instruction-aware Qwen3-Embedding by 1.8 points (root runs).
  • Late chunking's "23.46 to 29.98 on NFCorpus" is right but is jina-embeddings-v2-small's; with jina-v3 and nomic-embed the gain was 1.1 points and 0 (paper Table 2).
  • "256 to 512 tokens with 10 to 20% overlap is the most reliable default": at an equal budget, fixed windows of every size tried (128 to 512 tokens, with or without overlap) found 13 to 24 points fewer questions than paragraphs packed within sections on QASPER (bge-small, 1,024 tokens; root runs).
  • Reranking claims (depth 50 to 150, model lists, latencies) moved to Rerankers and late interaction, which measures depth on this data (the hybrid list peaked at K 20 with Qwen3-Reranker).
  • Full list with every claim's verdict: src/coverage.md.
Common mistakes, one line each (checklist)
  • Sizing chunks in characters for a model that counts tokens: with LangChain's default and all-MiniLM-L6-v2 only 33.3% of the text reaches the vector, silently (§1).
  • Believing the default separators cut at sentences: they are blank line, newline, space, nothing; add ". " or split on structure (§1).
  • Dropping overlapping neighbours as duplicates: QASPER fell from 0.568 to 0.455 found; merging overlapping spans gave 0.571 (§7).
  • Tuning k1, b, the fusion weight or k on the test queries: the best BM25 pair on SciFact test claims claims 0.688; chosen on training claims it scores 0.678 (§2).
  • Adding BM25 and cosine scores with equal weight: BM25's scale wins (0.685, near BM25's 0.679); normalise, learn the weight, or use ranks (§4).
  • Tuning the fusion weight when a reranker follows: after it, RRF and tuned z-score fusion land within a point; spend the effort on rerank depth (§4).
  • Ignoring what the BM25 tokenizer does to identifiers and negations: one-character tokens dropped, "not" a stopword (§2).
  • Filtering after the search or after fusion: about K · s results come back, often none (§6).
  • Turning on MMR because diversity sounds good: it hurt on every set here, including the multi-hop one (§7).
  • Trusting an extracted filter without checking it: the generator added December to every year-only request (§5).
  • Accepting citations without resolving and checking them: an unresolvable citation is a wrong answer (§8).
  • Debugging a bad answer by swapping the model first: measure r, p and g; the largest bucket names the stage (§9).
Interview questions, short answers (optional rehearsal)

How would you choose a chunking strategy for a new corpus? Get a few hundred questions with located evidence. Split on the documents' own structure first (headings, paragraphs), cap the size in the embedder's tokens, and compare candidates on "evidence intact" and on retrieval at an equal token budget, never at an equal number of chunks. Try small-to-big (index sentences or paragraphs, return the paragraph) before tuning sizes.

Why does RRF work without calibration, and when would you not use it? It uses ranks, so the two score scales never meet, and it rewards agreement, which is a strong signal (documents in both top 10s were relevant 13 to 28 times as often as single-list ones on SciFact). It discards score margins; with no reranker and labelled queries to learn a weight, normalised score fusion did about 1 to 1.6 points better here. With a strong reranker after it, RRF is enough.

BM25 or dense for queries with product codes? Run both and fuse. Check the BM25 tokenizer keeps the codes intact (a two-character pattern drops "X1" pieces; hyphens split). A router is only worth it if it beats fusion on labelled queries; here a learned router did not.

Design a multi-tenant RAG search for 10,000 customers. Where do permissions go? Tenant id and ACL groups as typed metadata on every chunk, enforced as a filter inside both the BM25 and the vector search (or row-level security in the database), never in the prompt. Choose shared index plus filter or index per tenant by tenant size: tiny tenants make post-filtering useless and filtered ANN slow, so check the engine's filtered-search strategy (iterative scans, ACORN-style traversal, exact scan below a threshold) and measure recall for the smallest tenant. Re-index a document's chunks when its permissions change.

Your RAG answers cite the wrong document. How do you debug it? Split the failure: was the right chunk retrieved (recall at the rerank depth), did it reach the prompt (rank after reranking against the budget), and did the model use it (an oracle run with only the right chunk)? Then check the citation plumbing.

When is query rewriting worth its latency? Always for chat follow-ups (they are not queries without the history). Otherwise measure: HyDE helped one embedder and hurt another here; multi-query did nothing and step-back and decomposition hurt; a rewrite costs a generator call (0.3 to 2.2 s per query here, depending on how much it writes), more than the whole retrieval.

What is late chunking and what does it need? Embed the whole document with a long-context, mean-pooling embedder, then average token vectors per chunk span, so each chunk vector sees the document. It needs mean pooling and a long context; published gains are large for weak embedders and small for strong ones, and within a single document (where every chunk shares the same context) it hurt here.

How this was measured, and the limits (provenance)

Machine: Apple M1 Pro (8 performance and 2 efficiency cores, 16 GB unified memory), PyTorch MPS and llama.cpp Metal, October 2026, shared with other agents. Relevance numbers (nDCG, recall, found-within-budget) are deterministic and do not depend on the machine; the few timings are labelled with their load. Data and models: the root's running example (src/data/README.md there) and its precomputed vectors, runs and reranker scores; this page added nomic-ai/modernbert-embed-base (late chunking) and opensearch-neural-sparse-encoding-doc-v3-distill (learned sparse), revisions and sha256 in the shared SETUP notes. Generator: Qwen3-1.7B Q4_K_M in llama-server, temperature 0, seed 0, thinking off, answers cached by exact prompt. Libraries read at pinned versions: langchain-text-splitters 1.1.3, langchain-core 1.6.10, llama-index-core 0.14.25, bm25s 0.3.13, pgvector v0.8.7 README, pySBD 0.3.4.

What transfers: the shapes (structure-aware chunks beat fixed windows at equal budget; post-filters lose results in proportion to selectivity; fusion matters less after a reranker; tuning on test inflates) are properties of the methods. What does not: the exact numbers belong to these corpora (scientific abstracts and NLP papers, mostly one relevant document per SciFact claim), these embedders and a 1.7 B generator, which is weak at CONTRADICT; a larger generator changes the prompt-assembly numbers and the size of the generation bucket. Not run here: HTML and code splitting (no such corpus in the running example), BGE-M3's sparse head, LLM routers (on the agentic page), and contextual prefixes beyond the root's run.

Measured on the topic's shared runs: details the root page used to show (moved here when the root's Pipeline lab was retired, 2026-10-24; 3 min)

All recorded in the root page's src/pipe on the running example (load average during the runs 1.2 to 3.9).

  • BM25 by hand. Document frequency is the length of a term's postings list: in SciFact, "statin" appears in 23 of 5,183 abstracts, "decreas" in 573. BM25's first and third results for claim 1099 of the SciFact test set score 8.963 and 7.366 (k1 1.2, b 0.75), recomputed exactly from the bm25s index's term counts and lengths; the relevant abstract is the third.
  • Chunking, more cuts. Two fair ways to hand text over: the top k chunks, or a token budget filled in rank order. The 0.6 B Qwen3-Embedding shows the same gap between fixed windows and paragraph-aware chunks as bge-small (59.4% against 70.3%): a bigger embedder does not repair a bad cut. Semantic chunking cut at the 80th percentile gives small chunks that split the evidence (547 intact). A title and section prefix (no model) helps paragraph-aware chunks (bge-small at 1,024 tokens: 70.0% to 72.0%) and not fixed windows (56.8% to 54.9%), whose section label can be wrong for half the window. One caution: QASPER's evidence unit is the paragraph, so "one paragraph per chunk" (median 89 tokens, 888 of 892 intact, 77.5% at 1,024 tokens with bge-small) is favoured by construction; on documents whose answers span paragraphs, packing paragraphs up to a size is the safer default.
  • Contextual retrieval, run on the laptop. Qwen3-1.7B wrote the context with Anthropic's prompt verbatim on 71 papers (every fourth; 1,664 default chunks, 239 questions): 2,560 s of generation, 0.87 M new prompt tokens because llama.cpp kept each paper in its cache (11.1 M without that cache). Without and with the context: bge-small top 3 46.9% to 49.4%, but at a 1,024-token budget 57.7% to 55.2%; BM25 top 3 38.5% to 40.2%, budget 49.0% to 48.1%. With 239 questions a difference of 2 to 3 points is within noise: a 1.7 B writer gives no clear gain on this task, and some of its "contexts" just repeat the chunk's first lines. The setting differs from Anthropic's: here retrieval runs inside one paper, where every chunk shares the same document context.
  • Late chunking on the root's models was not run: their long-context embedders pool differently (gte-modernbert uses the CLS token, Qwen3-Embedding the last token of a causal model), so a late-chunking run would measure a pooling the models were never trained for (section 1 runs it with modernbert-embed-base instead).
  • Fusion tuning. BM25 and dense runs for the training and dev splits use the same settings as the recorded test runs (BM25 reproduces the recorded test top 10 for every query).
  • Rewrites. HyDE used the authors' SciFact prompt from their code (texttron/hyde, promptor.py): "Please write a scientific paper passage to support/refute the claim." Multi-query asks for three rewordings, retrieves with each and the original, and fuses the four lists with RRF. For BM25, appending the HyDE passage to the claim adds words the abstracts use: recall@100 rises from 0.913 to 0.943. Longer chats, where pasting everything dilutes the query, were not tested.
  • Post-filter, in numbers. When a user may see 10% of SciFact, the evidence reaches the post-filtered results for 255 claims, against 284 when the filter runs inside the search. Over-fetching repairs it only partly: with the top 100 fetched, the evidence is found as often as with the pre-filter (284), but 96 claims still get fewer than 10 results; at 1% visibility even 1,000 fetched leaves 112 claims short. The evidence count even rises as the filter narrows (284 at 10%, 299 at 1%, against 256 unfiltered), but that is the construction: the evidence is always allowed and fewer abstracts compete with it.
  • End to end, by label. The decomposition uses the 188 test claims that have evidence (124 SUPPORT, 64 CONTRADICT). None of the 64 CONTRADICT claims was answered correctly, and almost all of them reached the prompt, so they are lost at generation; on SUPPORT claims the model is right 96 times of 124. The reranker still pays: without it (first stage only, k 3) the evidence reaches the prompt for 171 claims instead of 178, and 90 claims are answered correctly instead of 96. A 4 B or frontier model would move g, not r or p.
  • How the answer prompt was chosen. Three prompts were compared on SciFact training claims, each with its gold abstracts (120 claims with evidence, 60 without), as right with evidence, right without, balanced: p1 "SUPPORT, CONTRADICT, or NOT ENOUGH INFO?" 17 / 120, 60 / 60, 0.571; p2 "SUPPORT or CONTRADICT? NOT ENOUGH INFO only if no abstract addresses the claim" (chosen) 78 / 120, 41 / 60, 0.667; p3 (a role and definitions of each label) 86 / 120, 11 / 60, 0.450. p2 was then run once on the test claims. Qwen3's thinking mode was started and stopped: about 8 s per answer, about 5 hours for the 2,300 answers of the end-to-end runs.