RAG done properly: chunking, hybrid search, reranking
Take the naive document Q&A tool from module A1, measure where it loses the answer, and fix retrieval one stage at a time: structure-aware chunks, a lexical arm, rank fusion, a cross-encoder, and contextual retrieval
Your docqa retrieves the 5 nearest chunks by cosine and scores 24/30 on 'gold answer in the top 5'. You add a cross-encoder that rescores those same 5 chunks and reorders them. What does the score become?
The baseline from the document Q&A project fails in three ways, and you classified each failure in its RESULTS.md: a fact cut in half by an 800-character boundary, a question whose distinguishing detail is a number the embedding cannot see, and a heading that outscored the paragraph under it. Each one has a standard fix. Applied in the wrong order or without measurement, each fix also has a standard way of making things worse. This chapter goes through them in the order you should try them, says what each one costs, and the lab measures every step against the same thirty questions.
Two numbers, and which one you are moving
Retrieval quality and answer quality are different numbers, and they move for different reasons.
Recall at k (hit@k) is the share of questions for which a chunk containing the gold answer appears in the top k. With one gold chunk per question it is the same as hit rate. MRR, mean reciprocal rank, averages 1/rank of the first correct chunk (0 when it is missing): it rewards putting the right chunk first, which matters because models use early passages more reliably than late ones. Answer accuracy is whether the generated answer is right, judged by reading it. Retrieval bounds accuracy: a question that misses at k cannot be answered from k chunks, whatever the prompt says.
Three traps sit in these numbers.
The k you measure must be the k you send. Recall at 20 is a fine diagnostic for a first stage, but if the generator sees 5 chunks, recall at 5 is the ceiling on accuracy. Anthropic’s contextual retrieval results are reported as failure rate at 20 because their pipeline sends 20 chunks; yours sends 5.
Bigger chunks win recall for free. A chunker that produces 1,200-character chunks contains more answers per chunk than one that produces 800-character chunks. Report the characters (or tokens) delivered at k next to recall, so that a gain bought with context length is visible as one. The lab’s recall table has a chars@5 column for this reason.
Ten questions is not a measurement. With ten questions each one is ten points, and the 95% confidence interval on 8/10 runs from roughly 0.49 to 0.94. The A1 set was enough to classify failures; it is too small to compare five pipelines. The lab extends it to thirty, which narrows the interval to about ±0.15 at the same rate, and the next chapter in this module, on building an eval set, goes to a hundred. Every comparison here is paired: the same thirty questions through every pipeline, so you can read differences question by question instead of trusting the totals.
Chunking: the unit of retrieval is the unit of failure
A chunk is the smallest thing retrieval can return. If the fact you need is split across two chunks, retrieval can only ever return half of it, and if a chunk mixes three topics its embedding is the average of three meanings and matches none of them well.
Fixed-size chunking cuts every N characters or tokens, with overlap. It is cheap and predictable, and it ignores the document. In the A1 corpus it cuts the LABS.md schema table between rows, separates FAULT_N_PLUS_ONE from the sentence that explains it in some runs, and splits the numbered list of authoring rules.
Structural chunking uses the structure the author already wrote. For markdown: split at headings, keep each fenced code block, table and paragraph whole, and pack consecutive blocks into a chunk until a size budget is reached. A block bigger than the budget is split on its natural seams, a table by rows with its header row repeated. Every chunk records its heading path, LABS.md > Course labs: shared infrastructure > labs/observability — the demo app, which you index with the chunk. The heading path repairs the most common chunk failure, a paragraph that does not repeat its subject: ‘Ports: gateway 8080, orders 8081, …’ does not say which lab it belongs to, but its heading does. HTML, PDF and code have equivalent structure (DOM sections, page layout blocks, function boundaries), and the parser for that structure is usually the most valuable piece of a production ingestion pipeline.
Semantic chunking embeds each sentence and cuts wherever the similarity between neighbours drops, so that chunks are topically coherent without relying on markup. It costs an embedding call per sentence at ingest. The evidence for it is weak: Qu, Tu and Bao (2024) compared it with fixed-size chunking on document retrieval, evidence retrieval and answer generation and found the gains inconsistent and not worth the computation. Use it for text with no structure at all (transcripts, scraped prose). Where structure exists, structure wins.
Size is a trade-off you measure. Small chunks (200 to 400 tokens) give precise matches and fit more distinct passages into the generator’s budget; large chunks (800 to 1,500 tokens) keep facts whole and give the model surrounding context. A common pattern decouples the two: retrieve small chunks, then send the generator the parent section they came from (‘small-to-big’ or parent-document retrieval). The lab uses a 1,200-character budget, about 300 tokens, which keeps every table row and list in LABS.md intact.
Lexical retrieval: what embeddings cannot see
Dense embeddings compress meaning into 768 numbers. They are good at ‘trainers’ versus ‘running shoes’ and bad at exact tokens: port numbers, version strings, error codes, SKUs, environment variable names. 5432 and 5433 sit almost on top of each other in embedding space; to a lexical index they are different words.
BM25 is the standard lexical ranking function, from Robertson and colleagues’ probabilistic relevance framework. For each query term it adds
IDF(t) × tf × (k1 + 1) / (tf + k1 × (1 − b + b × len / avg_len))
where tf is how often the term occurs in the chunk, len / avg_len normalises for chunk length, k1 (usually 1.2 to 2.0) controls how quickly repeated occurrences stop adding score, and b (usually 0.75) controls length normalisation. The part that matters most is IDF, inverse document frequency, log(1 + (N − n + 0.5) / (n + 0.5)) for a term in n of N chunks. A term in every chunk (‘the’, ‘lab’, ‘port’ in a corpus about labs) is worth almost nothing; a term in one chunk (FAULT_LEAK_PII, 4318) is worth a lot. That is exactly the signal embeddings blur.
Postgres full-text search is not BM25, and treating it as BM25 is a common mistake. to_tsvector('english', text) normalises words into lexemes (stemming, stop-word removal), a GIN index finds matching rows fast, and ts_rank or ts_rank_cd scores them using term frequency, proximity and document structure. The ranking functions use no corpus-wide statistics, so there is no IDF: a match on ‘lab’ counts the same as a match on LOADGEN_RPS. Second, plainto_tsquery and websearch_to_tsquery join the query’s words with AND, so a natural-language question matches only chunks that contain every one of its non-stop words, which for ‘Which port does the observability stack’s Postgres use, and why?’ is often no chunk at all. The lab builds an OR query from the question’s lexemes instead and measures both. Third, the english configuration stems identifiers in ways that occasionally surprise you; for code-heavy corpora index a second simple tsvector alongside.
You have three ways to get real BM25 next to pgvector: compute it in the application over a small corpus (the lab does this in twenty lines of Python), use a Postgres extension that implements it (ParadeDB’s pg_search is one), or run a search engine (OpenSearch, Elasticsearch, Vespa) beside the database. For a corpus that fits in memory, the first is enough; for millions of chunks with frequent updates, the third is what the industry runs.
Fusing two rankings
A hybrid retriever runs the dense and lexical retrievers and merges their lists. Their scores cannot be added: cosine similarity sits between roughly 0.4 and 0.8 for this model, BM25 scores range from 0 to 20 or more, and both distributions shift with every query.
Reciprocal rank fusion (Cormack, Clarke and Büttcher, 2009) ignores scores and uses ranks. Each list gives each document 1 / (c + rank), with c = 60; the fused score is the sum. A document first in one list and absent from the other scores 1/61 ≈ 0.0164; a document fifth in both scores 2/65 ≈ 0.0308 and wins. RRF rewards agreement, needs no tuning, and is robust to one retriever having a bad day. Weighted fusion of normalised scores can beat it once you have enough labelled queries to fit the weights, which you usually do not at first.
Hybrid search is not monotonic, and the lab shows it. On the thirty questions, fusion rescues the questions the dense retriever lost (identifiers, numbers) and costs a few it had right: a question the dense retriever ranked third and the lexical one ranked twentieth can fall to eighth after fusion. Recall at 10 and 20 rise reliably; recall at 5 sometimes does not. That is why hybrid retrieval is the first stage of a pipeline and not the last.
Reranking with a cross-encoder
The dense retriever is a bi-encoder: question and chunk are embedded separately and compared with one dot product, which is what makes it fast enough to search millions of chunks. A cross-encoder reads question and chunk together through one transformer and outputs a relevance score. Every attention layer can compare a question word with a chunk word, so it sees ‘which port’ against ‘5433 (so it does not clash with the shop)’ directly. It is far more accurate and far too slow to run over a corpus: one forward pass per (question, chunk) pair.
So you run it on a shortlist. The first stage (hybrid) produces 50 to 150 candidates cheaply; the cross-encoder rescores those and you keep the best 5 to 20. The lab uses cross-encoder/ms-marco-MiniLM-L6-v2, about 22 million parameters, trained on MS MARCO web-search relevance. On a laptop CPU it scores 50 pairs of 300-token chunks in a few hundred milliseconds. Larger rerankers (BAAI/bge-reranker-v2-m3, hosted reranking APIs) are more accurate and slower; the right one is the cheapest that clears your recall target at your latency budget, which you find by running the lab’s table with each.
ColBERT (Khattab and Zaharia, 2020) sits between the two designs: it stores one vector per token of every chunk and scores with a sum of per-token maximum similarities (‘late interaction’). It gets much of a cross-encoder’s precision at a bi-encoder’s query cost, paid for with an index ten to a hundred times larger. It is worth knowing when you meet a corpus too large to rerank and too precise for single vectors.
Two cautions. Cross-encoder scores are not calibrated probabilities across queries, so do not threshold them to decide ‘nothing relevant was found’ without checking the distribution on your own data. And a reranker trained on web search has opinions about relevance that may not match your domain; measure, do not assume.
Contextual retrieval
Structural chunking repairs a chunk that has lost its heading. It does not repair a chunk that has lost its document: a paragraph in COURSES.md saying ‘Lab: eval in CI; block a prompt change that regresses’ does not say it is about the AI course’s module A3. Contextual retrieval, published by Anthropic in September 2024, asks a small model to write that missing context. For each chunk, the model receives the whole document and the chunk and is asked for ‘a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk’. The 50 to 100 tokens it writes are prepended to the chunk before embedding and before lexical indexing; the chunk itself is unchanged.
Anthropic’s measurements across codebases, fiction, papers and other corpora, as the failure rate at 20 (one minus recall at 20): contextual embeddings cut failures from 5.7% to 3.7% (35%), contextual embeddings plus contextual BM25 to 2.9% (49%), and adding a reranker over the top 150 to 1.9% (67%). The cost is one model call per chunk, and prompt caching makes it small: the document is the same for every chunk in it, so it is written to the cache once and read at a tenth of the input price for every later chunk. Anthropic quoted $1.02 per million document tokens at 2024 prices. In the lab the call goes to Claude Haiku 5.5 (claude-haiku-5-5, $0.10 per million input tokens, $0.01 for cache reads, $0.50 output) and the whole 90-chunk corpus costs about three cents.
The pitfalls are specific. The context is model-written text, so it can be wrong; a context that names the wrong module sends the chunk to the wrong questions. It must be regenerated when the document changes, which makes it part of your ingestion pipeline’s versioning, not a one-off. The whole document has to fit in the context window, which for long manuals means situating against a section rather than the book. And it can contaminate your evaluation: if the hit check looks at the context as well as the chunk, a context that paraphrases the answer counts as a hit for a chunk that does not contain it. The lab’s hit check reads the original chunk only.
The order to try things in
| Change | Fixes | Costs | Not worth it when |
|---|---|---|---|
| Structural chunking with heading paths | facts cut at boundaries, chunks that lost their subject | a parser per format; re-ingest | the text has no structure: try semantic chunking or fixed size with overlap |
| Lexical arm and RRF | identifiers, numbers, rare terms | a second index and query; 1 to 10 ms | queries never contain exact tokens (rare in technical domains) |
| Cross-encoder over 50 to 150 candidates | right chunk retrieved but ranked low | 100 ms to 1 s per query on CPU, less on GPU | recall at 50 is itself low: fix the first stage |
| Contextual retrieval | chunks that lost their document | one small-model call per chunk at ingest, re-run on change | documents are short, or chunks already self-contained |
| Larger or domain-tuned embedding model | semantic misses across the board | re-embed everything; larger vectors | the misses are identifiers (the lexical arm is cheaper) |
Read your failure classification first and pick the row whose ‘fixes’ column matches it. The order above is the order in which each step’s cost grows.
Where it still goes wrong
Retrieval of top-k chunks answers questions whose answer lives in one or two places. It fails on aggregation (‘how many chapters in the AI course call the API?’ needs every chapter, not five), on multi-hop questions whose second search depends on the first answer (an agent that searches twice handles these better than a bigger k), and on negative questions (‘which lab does not use Postgres?’). It fails silently when the index is stale. And when retrieval returns nothing relevant, the generator still receives five passages and is tempted to answer from them; the abstention instruction you wrote in module A1 is the only thing standing in the way, and the hallucination chapter later in this module measures how often it holds.
Work in labs/ai/docqa/ (cd labs/ai/docqa from the root of your checkout). Every step adds one stage and re-runs the same recall table, so you can see what each stage bought. Leave doc_chunks and the A1 files untouched: the baseline is a pipeline in the table, not something you overwrite.
1. Thirty questions. Create questions-v2.json with the ten questions from questions.json plus twenty more, chosen so that a third hinge on an exact token and a third are phrased in words the corpus does not use:
uv run python - <<'PY'
import json
extra = [
{"q": "Which port does the OpenTelemetry Collector accept OTLP over HTTP on?", "answer": "4318", "source": "LABS.md"},
{"q": "What happens to charges when FAULT_SLOW_PAYMENTS_PCT is set?", "answer": "sleep 1.5 to 3 s", "source": "LABS.md"},
{"q": "How many distinct product categories does the shop have?", "answer": "40 values", "source": "LABS.md"},
{"q": "Which major version of Postgres does the shop run?", "answer": "Postgres 17", "source": "LABS.md"},
{"q": "Which environment variable sets the load generator's request rate?", "answer": "LOADGEN_RPS", "source": "LABS.md"},
{"q": "Which setting makes the payments service write the card-holder name to its logs?", "answer": "FAULT_LEAK_PII", "source": "LABS.md"},
{"q": "What share of orders comes from the heaviest 2% of customers?", "answer": "30% of orders", "source": "LABS.md"},
{"q": "What are the Grafana login credentials in the observability stack?", "answer": "admin / admin", "source": "LABS.md"},
{"q": "What is the default service.version of the demo services?", "answer": "1.0.0", "source": "LABS.md"},
{"q": "How long should the body of a course chapter be?", "answer": "1500–3500 words", "source": "AUTHORING.md"},
{"q": "How many reading list entries should a chapter have?", "answer": "4–8 entries", "source": "AUTHORING.md"},
{"q": "Which beats may a project chapter leave out?", "answer": "may drop Predict, Decide and Reading", "source": "AUTHORING.md"},
{"q": "How many minutes may a normal chapter take, according to the frontmatter rules?", "answer": "25–60 for a chapter", "source": "AUTHORING.md"},
{"q": "What is the target length of a lesson?", "answer": "12–20 minutes", "source": "DESIGN.md"},
{"q": "How many beats does every v2 lesson follow?", "answer": "seven beats", "source": "DESIGN.md"},
{"q": "Which directory does the static build write to?", "answer": "dist/", "source": "DEPLOY.md"},
{"q": "Which two secrets turn on accounts and sync?", "answer": "PUBLIC_SUPABASE_ANON_KEY", "source": "DEPLOY.md"},
{"q": "What do anonymous analytics events contain?", "answer": "lesson id, item id, pass/fail and attempt number", "source": "DEPLOY.md"},
{"q": "Which source must GitHub Pages be set to for deployment?", "answer": "GitHub Actions", "source": "DEPLOY.md"},
{"q": "What are the five levels a course chapter can be tagged with?", "answer": "Beginner, Working, Senior, Staff, Principal", "source": "COURSES.md"}]
qs = json.load(open("questions.json")) + extra
json.dump(qs, open("questions-v2.json", "w"), indent=1, ensure_ascii=False)
import re, pathlib
norm = lambda s: re.sub(r"\s+", " ", s).lower()
bad = [x["q"] for x in qs if norm(x["answer"]) not in norm(pathlib.Path("corpus", x["source"]).read_text())]
print(len(qs), "questions;", "not in corpus:", bad)
PY30 questions; not in corpus: []. The comparison normalises whitespace because some gold answers wrap across lines in the source file. If a question is listed, your frozen corpus predates the fact: replace it with another fact stated verbatim in the same file. Every number from here on is out of 30.2. The recall harness, and the baseline’s score. Add the pipelines file and the table that compares them. Create retrieve_v2.py:
"""Retrieval pipelines. Every function returns rows shaped like qa.retrieve's:
(id, source, chunk_no, text, score). text is the heading path plus the chunk as it
appears in the file; the generated context is never in it, so a hit check cannot be fooled."""
import functools, math, re
from collections import Counter
import ollama, psycopg
from ingest import DSN, MODEL, to_vec
from qa import retrieve as baseline
COLS = "id, source, chunk_no, heading || E'\\n' || content"
def qvec(q):
return to_vec(ollama.embed(model=MODEL, input=["search_query: " + q])["embeddings"][0])
def vector(q, variant, k=50):
with psycopg.connect(DSN) as conn:
return conn.execute(
f"SELECT {COLS}, 1 - (embedding <=> %(v)s::vector) FROM doc_chunks_v2 "
"WHERE variant = %(var)s ORDER BY embedding <=> %(v)s::vector LIMIT %(k)s",
{"v": qvec(q), "var": variant, "k": k}).fetchall()
# The question's lexemes joined with OR. websearch_to_tsquery would AND them, and a
# natural-language question almost never has every one of its words in a single chunk.
OR_QUERY = ("(SELECT string_agg(quote_literal(l), ' | ')::tsquery AS query "
"FROM unnest(tsvector_to_array(to_tsvector('english', %(q)s))) AS l) AS t")
def fts(q, variant, k=50):
with psycopg.connect(DSN) as conn:
return conn.execute(
f"SELECT {COLS}, ts_rank_cd(tsv, t.query) AS score FROM doc_chunks_v2, {OR_QUERY} "
"WHERE variant = %(var)s AND tsv @@ t.query ORDER BY score DESC LIMIT %(k)s",
{"q": q, "var": variant, "k": k}).fetchall()
STOP = set("a an and are as at be by do does for from how in is it of on or that the this to was "
"what when where which who why will with".split())
def tokens(s):
words = (t.strip(".:/@-") for t in re.findall(r"[a-z0-9_.:/@-]+", s.lower()))
return [t for t in words if t and t not in STOP]
class BM25:
def __init__(self, docs, k1=1.2, b=0.75):
self.tf = [Counter(tokens(d)) for d in docs]
self.len = [sum(t.values()) for t in self.tf]
self.avg, n = sum(self.len) / len(docs), len(docs)
df = Counter(w for t in self.tf for w in t)
self.idf = {w: math.log(1 + (n - f + 0.5) / (f + 0.5)) for w, f in df.items()}
self.k1, self.b = k1, b
def scores(self, query):
q = tokens(query)
return [sum(self.idf[w] * tf[w] * (self.k1 + 1)
/ (tf[w] + self.k1 * (1 - self.b + self.b * n / self.avg))
for w in q if w in tf)
for tf, n in zip(self.tf, self.len)]
@functools.lru_cache(maxsize=4)
def _bm25_index(variant):
with psycopg.connect(DSN) as conn:
rows = conn.execute(f"SELECT {COLS}, heading || ' ' || context || ' ' || content "
"FROM doc_chunks_v2 WHERE variant = %s ORDER BY id", (variant,)).fetchall()
return rows, BM25([r[4] for r in rows])
def bm25(q, variant, k=50):
rows, index = _bm25_index(variant)
s = index.scores(q)
order = sorted((i for i in range(len(rows)) if s[i] > 0), key=lambda i: -s[i])[:k]
return [rows[i][:4] + (s[i],) for i in order]
def rrf(*rankings, c=60, top=50):
"""Reciprocal rank fusion: each list votes 1 / (c + rank). Scores are ignored, only ranks count."""
score, row = Counter(), {}
for ranking in rankings:
for rank, r in enumerate(ranking, start=1):
score[r[0]] += 1 / (c + rank)
row[r[0]] = r
return [row[i][:4] + (s,) for i, s in score.most_common(top)]
@functools.lru_cache(maxsize=1)
def _cross_encoder():
from sentence_transformers import CrossEncoder
return CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
def rerank(q, rows, top=20):
scores = _cross_encoder().predict([(q, r[3]) for r in rows])
order = sorted(range(len(rows)), key=lambda i: -scores[i])[:top]
return [rows[i][:4] + (float(scores[i]),) for i in order]
PIPELINES = {
"baseline": lambda q, k: baseline(q, k), # A1.8: 800/200 chars, cosine only
"struct-vec": lambda q, k: vector(q, "struct", k),
"struct-fts": lambda q, k: fts(q, "struct", k),
"struct-bm25": lambda q, k: bm25(q, "struct", k),
"struct-hybrid": lambda q, k: rrf(vector(q, "struct"), fts(q, "struct"))[:k],
"struct-rerank": lambda q, k: rerank(q, rrf(vector(q, "struct"), fts(q, "struct")), k),
"ctx-hybrid": lambda q, k: rrf(vector(q, "struct+ctx"), fts(q, "struct+ctx"))[:k],
"ctx-rerank": lambda q, k: rerank(q, rrf(vector(q, "struct+ctx"), fts(q, "struct+ctx")), k),
}Then recall.py, which runs any subset of the pipelines over the thirty questions:
"""Recall@k and MRR for each retrieval pipeline over questions-v2.json. Local only, no API calls."""
import json, re, sys, time
from retrieve_v2 import PIPELINES
norm = lambda s: re.sub(r"\s+", " ", s).lower()
QS = json.load(open("questions-v2.json"))
print(f"{'pipeline':14} {'@1':>3} {'@5':>3} {'@10':>4} {'@20':>4} {'MRR':>5} {'chars@5':>8} {'ms/q':>5} missed at 5")
for name in sys.argv[1:] or PIPELINES:
ranks, chars, t0 = [], 0, time.perf_counter()
for x in QS:
rows = PIPELINES[name](x["q"], 20)
ranks.append(next((i + 1 for i, r in enumerate(rows) if norm(x["answer"]) in norm(r[3])), None))
chars += sum(len(r[3]) for r in rows[:5])
ms = (time.perf_counter() - t0) * 1000 / len(QS)
hit = lambda k: sum(1 for r in ranks if r and r <= k)
mrr = sum(1 / r for r in ranks if r) / len(QS)
missed = [i + 1 for i, r in enumerate(ranks) if not r or r > 5]
print(f"{name:14} {hit(1):>3} {hit(5):>3} {hit(10):>4} {hit(20):>4} {mrr:>5.2f} "
f"{chars // len(QS):>8} {ms:>5.0f} {missed}")uv run recall.py baselinebaseline 13 23 26 28 0.56 3900 45 [4, 8, 10, 13, 20, 22, 30]. Your numbers differ with the docs snapshot, but expect recall at 5 between 21 and 26 of 30, a few questions found only at 10 or 20, and at least one never found. chars@5 is about 4,000: five 800-character chunks. The missed list is question numbers in questions-v2.json; look at two of them with uv run qa.py --show "..." and confirm they are the failure types your A1 RESULTS.md named.3. Structural chunks with heading paths. Create chunkers.py:
"""Structural chunking for markdown: split on headings, keep blocks whole, pack to a budget."""
import re
MAX = 1200 # characters per chunk, about 300 tokens
MIN = 200 # merge a trailing fragment smaller than this into the previous chunk
def blocks(text):
"""Yield (kind, text) for each block: heading, code, table, para (lists stay in para)."""
lines, i = text.splitlines(), 0
while i < len(lines):
line = lines[i]
if line.startswith("```"): # fenced code: up to the closing fence
j = i + 1
while j < len(lines) and not lines[j].startswith("```"):
j += 1
yield "code", "\n".join(lines[i:j + 1]); i = j + 1
elif re.match(r"#{1,6} ", line):
yield "heading", line; i += 1
elif line.startswith("|"): # table: consecutive | lines
j = i
while j < len(lines) and lines[j].startswith("|"):
j += 1
yield "table", "\n".join(lines[i:j]); i = j
elif not line.strip():
i += 1
else: # paragraph or list: up to a blank line
j = i
while (j < len(lines) and lines[j].strip() and not lines[j].startswith(("```", "|"))
and not re.match(r"#{1,6} ", lines[j])):
j += 1
yield "para", "\n".join(lines[i:j]); i = j
def split_big(kind, text, size):
"""A block over budget: tables split by rows with the header repeated, others by lines."""
rows = text.splitlines()
head, body = (rows[:2], rows[2:]) if kind == "table" else ([], rows)
out, cur = [], list(head)
for r in body:
if len("\n".join(cur + [r])) > size and len(cur) > len(head):
out.append("\n".join(cur)); cur = list(head)
cur.append(r)
out.append("\n".join(cur))
return out
def chunk_markdown(name, text, size=MAX):
"""Return [(heading_path, content)]. Chunks never cross a heading or split a block."""
path, chunks, cur = [], [], []
def flush():
if cur:
chunks.append((" > ".join([name] + [h for _, h in path]), "\n\n".join(cur)))
cur.clear()
for kind, b in blocks(text):
if kind == "heading":
flush()
level = len(b) - len(b.lstrip("#"))
path[:] = [(l, h) for l, h in path if l < level] + [(level, b.lstrip("# ").strip())]
continue
for piece in (split_big(kind, b, size) if len(b) > size else [b]):
if cur and len("\n\n".join(cur + [piece])) > size:
flush()
cur.append(piece)
flush()
merged = [] # glue tiny chunks to their predecessor in the same section
for h, c in chunks:
if merged and merged[-1][0] == h and len(c) < MIN and len(merged[-1][1]) + len(c) <= size * 1.25:
merged[-1] = (h, merged[-1][1] + "\n\n" + c)
else:
merged.append((h, c))
return mergedCreate the new table next to the old one. The tsv column is generated from heading, context and content, so the lexical index always matches what was embedded:
cat > schema_v2.sql <<'SQL'
CREATE TABLE IF NOT EXISTS doc_chunks_v2 (
id bigserial PRIMARY KEY,
variant text NOT NULL, -- 'struct' or 'struct+ctx'
source text NOT NULL,
chunk_no int NOT NULL,
heading text NOT NULL, -- 'LABS.md > Course labs: shared infrastructure > labs/ai — the agent'
content text NOT NULL, -- exactly as in the file: the only text a hit check reads
context text NOT NULL DEFAULT '', -- contextual-retrieval sentence; '' for 'struct'
model text NOT NULL,
embedding vector(768) NOT NULL,
tsv tsvector GENERATED ALWAYS AS
(to_tsvector('english', heading || ' ' || context || ' ' || content)) STORED,
UNIQUE (variant, source, chunk_no)
);
CREATE INDEX IF NOT EXISTS doc_chunks_v2_tsv ON doc_chunks_v2 USING gin (tsv);
SQL
docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop < schema_v2.sqlCreate ingest_v2.py. Step 7 uses its --context flag; for now it runs without it:
"""Structural chunks, optionally with contextual retrieval, into doc_chunks_v2."""
import argparse, pathlib, anthropic, psycopg
from chunkers import chunk_markdown
from ingest import DSN, MODEL, embed, to_vec
CTX_MODEL = "claude-haiku-5-5"
PRICE = {"in": 0.10, "write": 0.125, "read": 0.01, "out": 0.50} # $ per 1M tokens, Haiku 5.5
CTX_PROMPT = """Here is the chunk we want to situate within the whole document
<chunk>
{chunk}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else."""
def situate(client, doc, chunk, spend):
"""One sentence or two placing the chunk in its document. The document block is cached,
so every chunk after the first in the same file reads it at a tenth of the input price."""
r = client.messages.create(
model=CTX_MODEL, max_tokens=1024, output_config={"effort": "low"},
messages=[{"role": "user", "content": [
{"type": "text", "text": f"<document>\n{doc}\n</document>",
"cache_control": {"type": "ephemeral"}},
{"type": "text", "text": CTX_PROMPT.format(chunk=chunk)}]}])
u = r.usage
spend["usd"] += (u.input_tokens * PRICE["in"] + (u.cache_creation_input_tokens or 0) * PRICE["write"]
+ (u.cache_read_input_tokens or 0) * PRICE["read"] + u.output_tokens * PRICE["out"]) / 1e6
spend["cached"] += u.cache_read_input_tokens or 0
# Haiku 5.5 has no server-side fallback, so a refusal lands here: index the chunk without context
if r.stop_reason != "end_turn":
print(f" [{r.stop_reason}] chunk indexed without context")
return ""
return "".join(b.text for b in r.content if b.type == "text").strip()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("folder")
ap.add_argument("--context", action="store_true", help="add contextual retrieval (Claude Haiku 5.5)")
a = ap.parse_args()
variant = "struct+ctx" if a.context else "struct"
client = anthropic.Anthropic() if a.context else None
spend = {"usd": 0.0, "cached": 0}
with psycopg.connect(DSN) as conn:
for path in sorted(pathlib.Path(a.folder).glob("*.md")):
doc = path.read_text()
chunks = chunk_markdown(path.name, doc)
ctx = [situate(client, doc, c, spend) if client else "" for _, c in chunks]
texts = ["\n".join(p for p in (h, x, c) if p) for (h, c), x in zip(chunks, ctx)]
vecs = embed(texts, "search_document: ")
conn.execute("DELETE FROM doc_chunks_v2 WHERE variant = %s AND source = %s", (variant, path.name))
conn.cursor().executemany(
"INSERT INTO doc_chunks_v2 (variant, source, chunk_no, heading, content, context, model, embedding) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s::vector)",
[(variant, path.name, n, h, c, x, MODEL, to_vec(v))
for n, ((h, c), x, v) in enumerate(zip(chunks, ctx, vecs))])
conn.commit()
print(f"{path.name}: {len(chunks)} chunks")
if client:
print(f"contextualised for ${spend['usd']:.4f}; {spend['cached']:,} input tokens read from cache")
if __name__ == "__main__":
main()uv run ingest_v2.py corpus
uv run recall.py baseline struct-vecCOURSES.md near 50, LABS.md near 8), fewer than the baseline’s 120 because they are larger. In the table, struct-vec typically gains 2 to 5 questions at 5 and lifts MRR, and its chars@5 is around 4,500 to 5,500, so part of the gain is size. Look at which questions moved: the schema-table question and the countries question usually come back because the table rows are now whole and carry the heading ‘labs/databases — the shop’. Then check SELECT heading, left(content, 60) FROM doc_chunks_v2 WHERE source = 'LABS.md' ORDER BY chunk_no; and see every chunk start at a block boundary.4. The lexical arm, and the AND trap. First see why the obvious query does not work:
docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
SELECT websearch_to_tsquery('english', 'Which port does the observability stack''s Postgres use, and why?');
SELECT count(*) AS and_matches FROM doc_chunks_v2
WHERE variant = 'struct' AND tsv @@ websearch_to_tsquery('english', 'Which port does the observability stack''s Postgres use, and why?');
SELECT count(*) AS or_matches FROM doc_chunks_v2,
(SELECT string_agg(quote_literal(l), ' | ')::tsquery AS query
FROM unnest(tsvector_to_array(to_tsvector('english', 'Which port does the observability stack''s Postgres use, and why?'))) AS l) AS t
WHERE variant = 'struct' AND tsv @@ t.query;
SQL
uv run recall.py struct-fts struct-bm25'port' & 'observ' & 'stack' & 'postgr' & 'use': every word ANDed, stemmed. and_matches is 0 or 1: no chunk contains all five. or_matches is most of the corpus, ranked by ts_rank_cd. In the recall table both lexical arms find the identifier questions (LOADGEN_RPS, FAULT_LEAK_PII, 4318) at rank 1 and miss most paraphrased ones, so their totals are lower than struct-vec (often 20 to 24 at 5). struct-bm25 usually ranks identifiers higher than struct-fts because of IDF: ‘lab’ and ‘port’ appear in many chunks and BM25 discounts them, ts_rank_cd does not.5. Hybrid with reciprocal rank fusion.
uv run recall.py struct-vec struct-fts struct-hybridstruct-hybrid has the best recall at 10 and 20 of the three, often 29 or 30 of 30 at 20, because each arm rescues the other’s misses. At 5 it is roughly level with struct-vec, and in the missed list you can usually find one question that struct-vec had at rank 2 or 3 and fusion pushed to 6 or 8, because the lexical arm ranked it low. That is the non-monotonic behaviour from the chapter, and the reason the next stage exists.6. The cross-encoder.
uv add sentence-transformers
uv run recall.py struct-hybrid struct-rerankstruct-rerank moves recall at 5 up to within one or two of its recall at 20, and hit@1 jumps, often by 5 to 10 questions, because the cross-encoder sees the question and the chunk together. ms/q rises by a few hundred milliseconds on a CPU: 50 pairs through a 22M-parameter model. Try the Predict’s experiment: change rerank(q, rrf(...), k) to rerank only the first 5 fused rows, rerank(q, rrf(vector(q, "struct"), fts(q, "struct"))[:5], k), and recall at 5 equals struct-hybrid’s exactly. Put it back.7. Contextual retrieval. This step calls Claude Haiku 5.5 once per chunk, about 90 calls. The document goes in a cached block, so within each file only the first call pays full input price.
ANTHROPIC_API_KEY=... uv run ingest_v2.py corpus --context
docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop -c \
"SELECT source, chunk_no, context FROM doc_chunks_v2 WHERE variant = 'struct+ctx' AND source = 'COURSES.md' ORDER BY chunk_no LIMIT 4;"
uv run recall.py struct-hybrid ctx-hybrid struct-rerank ctx-rerankcontextualised for $0.03 or so, with several hundred thousand input tokens read from cache: COURSES.md alone is about 10,000 tokens read 50 times. DEPLOY.md is under the 512-token minimum cacheable length on Haiku 5.5 and is not cached, which costs a fraction of a cent. The contexts read like ‘This chunk is from the AI Engineering course plan, module A3 (Senior), listing chapters on evaluation…’. In the table ctx-hybrid and ctx-rerank gain mostly on the COURSES.md and DESIGN.md questions whose chunks did not name their course or section. On a corpus this small the gain is one to three questions, and some runs show none; with thirty questions that is inside the noise, so look at which questions changed rather than the total. Read one context that is wrong or vague, and decide whether you would ship it.8. Answer accuracy, before and after. Retrieval is the means; correct answers are the end. Create evaluate_v2.py:
"""Answer accuracy for one pipeline: retrieve k, answer with qa.py's backends, mark, save."""
import argparse, json, re
from qa import answer_anthropic, answer_ollama
from retrieve_v2 import PIPELINES
norm = lambda s: re.sub(r"\s+", " ", s).lower()
ap = argparse.ArgumentParser()
ap.add_argument("--pipeline", default="ctx-rerank", choices=list(PIPELINES))
ap.add_argument("--backend", default="ollama", choices=["ollama", "anthropic"])
ap.add_argument("--k", type=int, default=5)
a = ap.parse_args()
answer = answer_anthropic if a.backend == "anthropic" else answer_ollama
out, QS = [], json.load(open("questions-v2.json"))
for i, x in enumerate(QS, 1):
chunks = PIPELINES[a.pipeline](x["q"], a.k)
hit = any(norm(x["answer"]) in norm(c[3]) for c in chunks)
text = answer(x["q"], chunks)
gold = norm(x["answer"]) in norm(text)
out.append({"n": i, "q": x["q"], "gold": x["answer"], "hit": hit, "gold_in_answer": gold,
"answer": text, "sources": [f"{c[1]}#{c[2]}" for c in chunks], "correct": None})
print(f"{i:>2} {'H' if hit else '.'} {'G' if gold else '.'} {x['answer'][:26]:26} {text[:80]!r}")
path = f"answers-{a.pipeline}-{a.backend}.json"
json.dump(out, open(path, "w"), indent=1, ensure_ascii=False)
n = len(out)
print(f"\nretrieval hits@{a.k}: {sum(r['hit'] for r in out)}/{n} "
f"gold string in answer: {sum(r['gold_in_answer'] for r in out)}/{n} saved {path}")answer_anthropic is the function from A1’s qa.py: claude-opus-5-5 at effort: "low", through client.beta.messages.create with the server-side-fallback-2026-07-01 beta and fallbacks="default", checking for a refusal before reading text. Run it on the baseline and on your best pipeline:
ANTHROPIC_API_KEY=... uv run evaluate_v2.py --pipeline baseline --backend anthropic
ANTHROPIC_API_KEY=... uv run evaluate_v2.py --pipeline ctx-rerank --backend anthropicH means the gold string was in the five chunks, G that it appears in the answer. G is a strict proxy: ‘2 million’ for ‘2 000 000’ or ‘three to four’ for ‘3–4’ is correct and unmarked. Open each answers-*.json, set correct to true or false for every row by reading it, and count. Typical results: the baseline answers 21 to 25 correctly, the improved pipeline 26 to 29, and almost every gained question is one that went from . to H. Rows with H and a wrong answer are generation failures, and they are what the hallucination chapter later in this module works on. Each run costs about $0.30 to $0.50.Finish by adding a section to RESULTS.md: the recall table from steps 2 to 7, the two accuracy numbers, which stage fixed which of your A1 failures, and the stage you would not ship given its cost and gain.
retrieve_v2.py, replace OR_QUERY’s lexeme list with the obvious version, (SELECT websearch_to_tsquery('english', %(q)s) AS query) AS t, and re-run uv run recall.py struct-fts struct-hybrid struct-rerank. Nothing errors. struct-fts now returns rows for only a handful of questions, struct-hybrid quietly becomes struct-vec with extra latency, and the rerank row drops back towards the dense-only numbers. A hybrid pipeline whose lexical arm returns nothing looks healthy in every log line. The guard is a metric: count, per query, how many candidates each arm contributed, and alert when one arm goes to zero.Template
# Retrieval quality report: <system>, <date>
Written by <retrieval owner>. Approved by <approver>. Decision needed by <date>.
## 1. Summary and decision needed
<two sentences: what is failing, and what you ask the approver to decide>
## 2. Baseline
Question set: <count> questions, frozen <date>. Pipeline: <chunking, retriever, k sent to the generator>.
| Pipeline | @1 | @5 | @10 | @20 | MRR | chars@5 | ms/q |
## 3. Failures by type
<each missed question number, its type, and the stage that should fix it>
## 4. Changes tried
| Change | Fixes | Effect at 5 and at 20 | chars@5 | Latency | Cost |
## 5. Cost
Ingest cost, query cost, re-run cost when documents change. Assumptions listed.
## 6. Proposal
Ship: <stages>. Do not ship: <stage and why>. Rollback: <how to return to baseline>.
## 7. How this could be wrong
<one way, and what would show it>
## 8. Out of scope
<what this report does not measure> WORKED EXAMPLE
The document Q&A tool from the lab, retrieving over the lab’s own docs. The retrieval owner writes the report; the head of engineering approves it.
Decision needed by Friday: approve structural chunks, a lexical arm with rank fusion and a cross-encoder for the docs search, and decide on contextual retrieval.
Baseline. 30 questions. The row below is the lab’s printed example, standing in for a real run. Baseline row: 13 at rank 1, 23 at 5, 26 at 10, 28 at 20, MRR 0.56, 3,900 characters at 5, 45 ms a question. Missed at 5: questions 4, 8, 10, 13, 20, 22 and 30. Because five chunks are sent, 23/30 is the ceiling on accuracy.
Failures by type. Assumption: after reading the seven misses, each is a fact cut at a boundary, an exact number the embedding cannot see, or a heading that outscored its paragraph. The first fix is structural chunks; the second, the lexical arm.
Changes, with the chapter’s expected effect. Structural chunks: 2 to 5 more questions at 5, but chars@5 rises to 4,500 to 5,500, so part of the gain is size. Hybrid with rank fusion: often 29 or 30 of 30 at 20, roughly level at 5. Cross-encoder: hit@1 up by 5 to 10 questions, a few hundred milliseconds more per query. Contextual retrieval: $0.03 for about 90 chunks, and a gain of one to three questions, inside the noise.
Proposal. Ship the first three. Do not ship contextual retrieval yet: three cents is cheap, but the contexts must be regenerated whenever a document changes. Rollback: the baseline chunks stay untouched, so returning to them means pointing the tool back at them.
How this could be wrong. 30 questions is small. Answer runs cost about $0.30 to $0.50 each; accuracy should move from 21 to 25 correct to 26 to 29. If the gain is smaller, or chars@5 grew as much as recall, part of it is size.
Out of scope. Aggregation and multi-hop questions. Assumed: the corpus does not change this week.
Now you
You work at Ferrowave, the bulk payouts API with 210 business customers and 9 people in customer success. Developer support wants an assistant that answers integration questions from the API documentation: signed webhooks per payout, the daily reconciliation file, payout statuses. The six-person Developer Experience team has a naive version, and customers get answers from the wrong page.
Write the retrieval quality report and change proposal for the VP Engineering, who approves it. Reuse your own RESULTS.md and the recall table from steps 2 to 7: your baseline row, the stages you tried and their cost lines. Ferrowave’s question count, corpus size and daily support volume are not given, so state each as an assumption. Say which stage you would not ship, and name the decision you need.
Self-check
Your company's internal support search runs dense retrieval over 2 million chunks of runbooks and tickets in pgvector. Recall at 20 on a 300-question labelled set is 0.81. Reading the 57 misses, 34 are queries containing an error code, hostname or ticket id (for example 'ERR_4471 on checkout-api'), 12 are chunks that do not say which service they describe, and 11 are paraphrases the model does not connect. The p95 latency budget is 600 ms and the current p95 is 120 ms. Which change do you make first?
- POST Introducing Contextual Retrieval Anthropic, 2024
The method in step 7, the exact prompt, and the measurements: failure rate at 20 down 35% with contextual embeddings, 49% with contextual BM25, 67% with a reranker over 150 candidates. Read the methodology and the 'further considerations' list; skip the product announcements.
- PAPER Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks Lewis et al., 2020
The paper that named RAG: a dense retriever over Wikipedia feeding a generator, trained end to end. Useful to see that the original design was retrieval plus generation as one system, and that its failure analysis already separated the two. Read: sections 1 and 2 for the architecture; section 4 for what retrieval did and did not fix.
- PAPER The Probabilistic Relevance Framework: BM25 and Beyond Stephen Robertson and Hugo Zaragoza, 2009
Where the BM25 formula, IDF and the k1 and b parameters come from, written by the people who made them. After this the twenty-line implementation in the lab will read as obvious. Read: sections 3.1 to 3.5 for the derivation of BM25 and its parameters; skip the field-weighting sections unless you index structured documents.
- PAPER Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods Cormack, Clarke and Büttcher, 2009
The source of RRF and of the constant 60. Short, and shows why a parameter-free rank fusion beat learned fusion methods on TREC data. Read: the whole paper; it is two pages.
- PAPER ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT Khattab and Zaharia, 2020
The clearest account of the precision and cost trade-off between bi-encoders and cross-encoders, and the late-interaction design that sits between them. Read: sections 1 to 3; figure 2 compares the bi-encoder, cross-encoder and late-interaction designs in one picture.
- PAPER Is Semantic Chunking Worth the Computational Cost? Qu, Tu and Bao, 2024
A controlled comparison of semantic and fixed-size chunking across three retrieval tasks, finding no consistent gain. Read it before anyone proposes semantic chunking for documents that already have headings. Read: the results tables and the discussion.
- DOC PostgreSQL documentation: Controlling Text Search
to_tsvector, the to_tsquery family and how each combines words, and the ranking functions with their normalisation options. Read the ranking section to see exactly what ts_rank_cd does and does not use.
- DOC Sentence Transformers: Cross-Encoder usage
How to load and call a cross-encoder, the predict and rank methods, and pointers to the pretrained rerankers with their speed and quality. Use it to swap the lab's MiniLM for a larger model and re-run the recall table.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.