07.2 Retrieval Strategies for RAG
Lesson 07.1 assembled the RAG pipeline and froze its contract: search(query, k, filters) -> list[Hit]. Module 06 built and measured the retriever itself — embeddings, indexes, BM25, hybrid fusion, rerankers, filters and an evaluation harness. This lesson is where those pieces become a strategy: which retriever configuration to run, how many results to ask for and how many to keep, what to do when the corpus is really several corpora, when to skip retrieval entirely, and how to keep it fast, cheap and permission-safe. Retrieval is where most RAG quality is won or lost, because the generator can only answer from what retrieval returns — a perfect prompt cannot rescue a chunk that was never fetched.
What you'll learn
- How Module 06's retrievers compose into named retrieval configurations (dense, hybrid + RRF, + reranker, + filters), driven by a
RetrievalConfigobject you can A/B test - How to choose k and the context budget: recall@k versus tokens, the three depths (candidate, rerank, final), adaptive-k techniques (score floors, elbows, reranker cut-offs), over-retrieval then trimming, token-budgeted selection, deduplication, MMR diversity, adjacent-chunk merging and small-to-big parent expansion
- Multi-source and multi-index RAG: routing queries to the right index with an LLM classifier plus a heuristic fallback, federated retrieval and score fusion, freshness and authority weighting, and handling conflicts between sources
- Structured data alongside unstructured: treating SQL tables and APIs as retrievers, text-to-SQL and entity lookups as retrieval tools, metadata-first retrieval, and detecting "answerable from the database"
- Retrieval triggers: always-retrieve versus retrieve-when-needed, cheap classifiers, tool-based retrieval, and the cost/latency/quality trade-offs
- Access control that cannot leak: mandatory filters applied inside retrieval, never post-filtered, plus tenant-isolation tests
- Freshness and versions: latest-only filters, as-of queries and superseded documents
- Query-time latency tactics: parallel retrievers, early termination, hot-query caching, approximate index settings and warm connections
- A complete
docs_qa/retrieval.pyyou can run today with fakes, plus the decision table, failure gallery and exercises to tune it on your own data
What you don't need
- API keys. Every part of
retrieval.pyruns on in-memory fakes and pure Python; the two places a model could help (the route classifier and the retrieve-or-not trigger) take an injectablecomplete(prompt) -> strcallable, so you can wire a provider later or use the built-in heuristics now. - A vector database or embedding API. The demos use tiny in-memory retrievers that satisfy the same
Retrieverprotocol; swap in your Module 06 stack and nothing else changes. - How embeddings, BM25, RRF, rerankers or filters work internally — those are Module 06 lessons. This lesson composes them; it does not re-teach them.
Setup
The code lives in the docs_qa package that lesson 07.1 starts, built on the corpus.py/retrievers.py files that lesson has you copy from 06.10 into the project root. Hit — the frozen dataclass at the centre of the retriever contract — is defined in retrievers.py, not inside the package; docs_qa/types.py holds the Pydantic request/response types (Question, Answer, Trace). If you haven't built it yet, create the project and package skeleton first:
uv init docs-qa --bare --python 3.13 && cd docs-qa # first time only; or: pip install pydantic
mkdir docs_qa && touch docs_qa/__init__.py
uv add pydantic # or: pip install pydanticThis lesson's file is docs_qa/retrieval.py, checked against pydantic 2.x (2.14.3 as of November 2026; see 07.1's Setup for the compatibility note). It is stdlib + Pydantic only — no SDKs, no network, no services. The .env keys from earlier modules are only needed if you later swap the fake complete callable for a real provider call (03.4 shows how to make that call schema-constrained).
Run the demo at the end of the file with:
uv run python -m docs_qa.retrievalWhat you must be able to do after this lesson#
- Turn Module 06 retrieval into a RAG retriever
- Choose k and a context size
- Retrieve from several sources and merge results
- Apply access control and filters at retrieval time
- Decide when a query needs retrieval at all
Why this matters for an AI engineer#
Retrieval strategy is the highest-leverage tuning surface in a RAG system: it decides what the model is even allowed to know for a given question. These are the phrases you'll hear and the sections that explain them:
| You'll hear... | You'll understand it after... |
|---|---|
| "Let's try dense-only versus hybrid on the eval set." | 1.4 Choosing a configuration |
| "We're sending too many chunks — the answer gets worse." | 2.1 recall@k versus the context budget and 2.4 Token-budgeted selection |
| "Make k adaptive — some questions need one chunk, some need ten." | 2.3 Adaptive k |
| "The top results are five copies of the same paragraph." | 2.5 Diversity and deduplication |
| "Search the small chunks but return the whole section." | 2.6 Merging and parent expansion |
| "Route handbook questions to one index, billing tickets to another." | Part 3: Multi-source and multi-index RAG |
| "Half our questions are really SQL lookups." | Part 4: Structured data alongside unstructured |
| "Don't retrieve for 'hi' or 'what's 12% of 80'." | Part 5: Retrieval triggers |
| "We filter by tenant after retrieval — is that OK?" | Part 6: Access control and filters — it is not |
| "The docs say $75 per diem but the policy changed to $85." | Part 7: Freshness and versions |
| "Retrieval p95 is 900 ms — where do we cut?" | Part 8: Query-time latency tactics |
Part 1: From Module 06's pieces to a RAG retriever#
1.1 The contract, restated for RAG#
Everything in this lesson satisfies the retriever contract from 06.10's handoff:
def search(query: str, k: int = 10, filters: dict | None = None) -> list[Hit]:
...A Hit carries five things, and each one earns its place downstream:
| Field | Who consumes it |
|---|---|
id |
Deduplication, merging, citations and debugging — the stable identity of the chunk |
score |
Thresholds and adaptive-k decisions — retriever-specific, never comparable across systems (06.10, 1.1) |
text |
What goes into the prompt context (07.4 formats it) |
metadata |
doc_id, section, tenant, lang, dates, source route — for filters, citations, freshness and ACL |
source |
Provenance: which stage produced the hit ("dense", "lexical", "rrf", "sql:orders") — the debugging signal for "which side won". A reranked hit keeps its first-stage source; the reranker records its score in metadata["rerank_score"] instead. Fused hits additionally carry metadata["stage_sources"] listing every stage that surfaced them (what source_mix counts, 4.3) |
The strategy layer this lesson adds is a set of composable wrappers around that contract: fusion, reranking, shaping, routing, guarding, caching, triggering. Each wrapper is itself a retriever, so they nest in any order — and the order matters, as 1.3 shows.
1.2 The retrieval configuration object#
A RAG retriever has more knobs than "which engine": how deep each first stage looks, whether a reranker runs and over how many candidates, how many hits survive to the prompt, which filters are mandatory, whether results are cached, and how the output is shaped (adaptive k, token budget, diversity). Hard-coding those choices per call site is how retrieval rots; instead, name each configuration once:
# docs_qa/retrieval.py — section: configuration models
"""docs_qa/retrieval.py — retrieval strategies for the docs_qa RAG pipeline.
Lesson 07.2. Everything here satisfies the retriever contract from lesson
06.10 (and the package skeleton from 07.1):
search(query: str, k: int = 10, filters: dict | None = None) -> list[Hit]
The file is organised as composable stages:
first-stage retrievers (built in Module 06)
-> fusion (RRF) -> reranker -> shaping (adaptive k / budget / MMR)
plus RAG-level strategies wrapped around them:
routing (multi-index), triggers, ACL guards, freshness filters,
caching and latency tactics.
Stdlib + pydantic only. Every place a model could help — the route
classifier, the retrieve-or-not trigger — takes an injectable
`complete(prompt) -> str` callable, so the whole file runs and tests
with no API keys. Wire a provider adapter (lesson 03.4) or a fake.
"""
from __future__ import annotations
import asyncio
import hashlib
import inspect
import json
import math
import re
import time
from collections.abc import Callable, Mapping, Sequence
from typing import Any, Protocol
from pydantic import BaseModel, Field
from retrievers import Hit # the 06.10 contract — top-level module, as in 07.1
class Retriever(Protocol):
"""The contract every retriever satisfies (06.10 handoff, imported by
07.1's rag.py): a query in, ranked Hits out. `filters` carries ACL,
freshness and route constraints — always applied BEFORE scoring
(lesson 06.6)."""
name: str
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]: ...
class RetrievalConfig(BaseModel):
"""One named retrieval pipeline shape.
`build_retriever` (1.3) turns a config plus a retriever registry into a
composed Retriever. The fields map to the knobs this lesson teaches:
first_stage registry keys searched in parallel, fused with RRF
candidate_k how deep EACH first-stage retriever looks
rerank_depth fused candidates sent to the reranker; None = off
pool_k over-retrieval depth before shaping trims to k
rrf_k the RRF constant (60 is the paper's default, 06.8)
min_score score floor for shaping (per-scale! see 2.3)
min_hits keep ≥N hits even below the floor, flagged
below_score_floor — the over-aggressive-floor
rescue (2.3); 0 = the floor is absolute
elbow/max_k adaptive-k cuts (2.3)
token_budget shaping budget in tokens (2.4)
diversity MMR weight, 0..1 (2.5)
dedupe_threshold near-duplicate overlap coefficient (2.5)
merge_adjacent merge neighbouring chunks of one doc (2.6)
expand_parents swap hits for parent passages (2.6)
mandatory_filters enforced on every call — ACL/freshness (Parts 6-7)
cache_ttl_seconds hot-query cache TTL; None = off (Part 8)
trigger wrap in the retrieve-or-skip decision (Part 5)
"""
name: str
first_stage: list[str]
candidate_k: int = 20
rerank_depth: int | None = None
pool_k: int = 30
rrf_k: int = 60
min_score: float | None = None
min_hits: int = 0
elbow: bool = False
max_k: int | None = None
token_budget: int | None = None
diversity: float | None = None
dedupe_threshold: float | None = None
merge_adjacent: bool = False
expand_parents: bool = False
mandatory_filters: dict[str, Any] = Field(default_factory=dict)
cache_ttl_seconds: float | None = None
trigger: bool = False
# The four shapes this lesson compares. Real deployments add their own —
# the point is that a config is data, so A/B testing is a config diff.
PRESETS: dict[str, RetrievalConfig] = {
# Cheapest: one embedding search, no fusion, no second stage.
"dense": RetrievalConfig(name="dense", first_stage=["dense"]),
# The usual default: lexical + dense fused with RRF.
"hybrid": RetrievalConfig(name="hybrid", first_stage=["dense", "lexical"]),
# Hybrid plus a reranker over the top candidates (06.9).
"hybrid+rerank": RetrievalConfig(
name="hybrid+rerank", first_stage=["dense", "lexical"],
rerank_depth=50),
# The production shape: fused, reranked, deduped and budgeted. Guards
# and freshness can't be preset constants — they're tenant-scoped, so
# they arrive per request via mandatory_filters (Parts 6-7).
"hybrid+rerank+shaped": RetrievalConfig(
name="hybrid+rerank+shaped", first_stage=["dense", "lexical"],
rerank_depth=50, pool_k=40, dedupe_threshold=0.85,
token_budget=2400, merge_adjacent=True),
}1.3 Assembling the pipeline — and why wrapper order matters#
build_retriever composes the wrappers innermost-first, so the call order is outermost-first:
flowchart LR
Q["query + filters"] --> T{"trigger?<br/>(Part 5)"}
T -- "skip" --> E["return []"]
T -- "retrieve" --> G{"guard:<br/>mandatory filters<br/>(Part 6)"}
G --> C{"cache?<br/>(Part 8)"}
C -- "hit" --> H["cached hits"]
C -- "miss" --> R{"router?<br/>(Part 3)"}
R --> S["first stage:<br/>dense + lexical → RRF"]
S --> RR["reranker?<br/>(06.9)"]
RR --> SH["shaping:<br/>adaptive k · dedup · MMR ·<br/>merge · expand · budget"]
SH --> H# docs_qa/retrieval.py — section: pipeline assembly (continues the same file)
# ... (RetrievalConfig and PRESETS above) ...
def build_retriever(config: RetrievalConfig, *,
retrievers: Mapping[str, Retriever],
reranker: Any = None,
trigger: "Trigger | None" = None,
parents: Mapping[str, str] | None = None,
count_tokens: "Callable[[str], int] | None" = None
) -> Retriever:
"""Assemble the configured pipeline.
`retrievers` is the registry of first-stage retrievers built in Module
06 (dense store, BM25 index, table retriever, ...). Wrappers nest
innermost-first, so the call order is:
trigger -> guard -> cache -> [route] -> fuse -> rerank -> shape
Order is a security and correctness decision, not cosmetics:
the guard sits OUTSIDE the cache so the cache key always includes the
mandatory (ACL) filters — a cached result can never leak across tenants;
the trigger sits outermost so a skipped query costs one classifier call,
not a retrieval."""
count_tokens = count_tokens or estimate_tokens
stages = []
for key in config.first_stage:
if key not in retrievers:
raise KeyError(
f"config {config.name!r} wants retriever {key!r}; "
f"registry has {sorted(retrievers)}")
stages.append(retrievers[key])
if not stages:
raise ValueError("config.first_stage is empty")
inner: Retriever = stages[0] if len(stages) == 1 else FusedRetriever(
stages, rrf_k=config.rrf_k, candidate_k=config.candidate_k)
if config.rerank_depth is not None:
if reranker is None:
raise ValueError(
f"config {config.name!r} sets rerank_depth but no reranker was given")
inner = RerankedRetriever(inner, reranker, depth=config.rerank_depth)
shape = build_shape(config, count_tokens=count_tokens, parents=parents)
if shape is not None:
inner = ShapedRetriever(inner, shape, pool_k=config.pool_k)
if config.cache_ttl_seconds is not None:
inner = CachedRetriever(inner, ttl_seconds=config.cache_ttl_seconds)
if config.mandatory_filters:
inner = GuardedRetriever(inner, config.mandatory_filters)
if config.trigger:
inner = TriggeredRetriever(inner, trigger or Trigger())
inner.name = config.name
return innerNote the deliberate omissions: the fused/reranked/shaped core is built here, but routing is not — a RoutedRetriever (Part 3) replaces the first-stage block when a query might belong to different indexes, and each of its indexes can itself be a build_retriever product. Composition, not configuration, handles multi-index.
1.4 Choosing a configuration with evidence#
Which preset should you ship? The honest answer: whichever wins on your labelled eval set, measured with the 06.10 harness. The harness takes any Retriever — including everything this file builds — and reports recall@k, MRR, nDCG, latency and cost per query, with paired bootstrap comparisons between runs.
The decision inputs, before you measure:
| Input | Pushes you toward... |
|---|---|
| Corpus is one homogeneous doc set, queries are natural language | dense or hybrid — hybrid earns its keep when queries mix exact terms (error codes, names, SKUs) with paraphrase (06.8, 1.1) |
| Corpus has identifiers, error codes, jargon, non-English terms | hybrid at minimum — dense alone is weak on exact tokens |
| Quality matters more than ~100 ms and a rerank call | hybrid+rerank — reranking is the biggest single quality lever after hybrid (06.9) |
| ACL/freshness filters are mandatory | add mandatory_filters to any config — they are orthogonal to ranking |
| p95 latency budget is tight | drop the reranker first, then fusion depth; see Part 8 |
| You have no labelled set yet | start with hybrid; it is the most forgiving default |
A worked ablation — the shape of the experiment, not real measurements. These numbers are illustrative; your corpus, chunking and embedding model will produce different ones, which is exactly why you run the harness:
| Configuration | recall@5 | MRR | nDCG@10 | p50 latency | notes |
|---|---|---|---|---|---|
dense |
0.71 | 0.58 | 0.62 | 45 ms | misses exact-term queries |
hybrid (RRF) |
0.79 | 0.63 | 0.68 | 70 ms | +1 BM25 lookup, nearly free |
hybrid+rerank |
0.84 | 0.72 | 0.75 | 190 ms | reranker call dominates latency |
hybrid+rerank+shaped |
0.83 | 0.74 | 0.76 | 200 ms | dedup/budget help precision, cost ~nothing |
(Illustrative numbers, not measurements: they are invented to show the usual shape of such a table. Run the real harness on your own labelled set for yours.)
Two readings of this illustration matter more than the rows: in a table like this the gains often concentrate at hybrid→rerank (your own run may say otherwise), and shaping is nearly free — dedup, budgets and merges are pure Python over ~30 hits. The expensive choices are the reranker (an extra model call per query) and, earlier in the pipeline, the embedding call itself (one per query, ~one chunk's worth of tokens — cheap, but not zero; 03.7 covers counting it).
Part 2: Choosing k and the context size#
2.1 recall@k versus the context budget#
The single most important retrieval decision is how many chunks to send to the generator. The trade is fundamental:
- Too few and the answering chunk sits at rank 8 while you only fetch 5 — perfect recall@50, useless recall@5 (06.10, 1.1).
- Too many and you pay for tokens you didn't need, dilute the relevant text among near-misses, and push the prompt toward the "lost in the middle" failure where models under-use middle-positioned context (04.6, 5.1).
The context budget itself is finite and shared: system prompt, conversation history, tool definitions and the retrieved chunks all compete for the same window (04.6, Part 2). A useful mental model:
final_k = min( what retrieval can confidently supply,
what the token budget can afford )Both sides are measurable: the left side with retrieval metrics on your eval set, the right side by counting tokens before you send (03.7, Part 2; 04.6, 2.2).
2.2 Three depths, kept separate on purpose#
Beginners conflate three different "how many" numbers. The code keeps them separate because they answer different questions:
| Knob | Question it answers | Typical value | Cost of raising it |
|---|---|---|---|
candidate_k |
How deep does each first-stage retriever look before fusion? | 20–50 | Near zero — a wider posting-list scan or a bigger efSearch/nprobe (06.4) |
rerank_depth / pool_k |
How many fused candidates does the expensive stage (reranker, shaper) see? | 30–100 | Reranker: one scoring call per candidate; shaping: microseconds |
k (per call) |
How many hits survive to the prompt (the "final k" of the mental model in 2.1)? | 3–10 | Input tokens × every generation call, plus dilution |
Over-retrieval is cheap; under-retrieval is fatal. The standard pattern is therefore: dig deep early, trim late — fetch 30–50 candidates, rerank the best 50, then keep the 5–8 that fit the budget. You only pay the reranker's per-candidate cost on the candidates that had a chance anyway.
2.3 Adaptive k: score floors, elbows and reranker cut-offs#
A fixed k is wrong for two opposite reasons: some queries are answered by one perfect chunk (extra chunks are noise), and some need many (comparisons, multi-part questions). Adaptive k picks the count per query. Three mechanisms, in increasing sophistication:
Score floor. Drop everything below a threshold. The catch — drilled into in 06.3, Part 3 and 06.10, 1.1 — is that scores are not comparable across retrievers or across queries. A cosine of 0.71 means something different for one embedding model than for another, and the same retriever's distribution shifts per query. So a floor must be tuned per retriever+model on labelled pairs (06.3, 3.3), and after RRF fusion the fused scores have yet another scale. The code below therefore uses an effective_score helper that prefers the reranker's score when the pipeline produced one — reranker scores (typically 0–1 or a small integer scale) are far more threshold-friendly than first-stage scores.
Elbow detection. Look at the ranked score list and cut where it "falls off a cliff":
# docs_qa/retrieval.py — section: adaptive k and context shaping
# (continues the same file)
def effective_score(hit: Hit) -> float:
"""The score shaping decisions use: the reranker's score when the
pipeline produced one (06.9 adapters put it in metadata as
`rerank_score`), else the retriever's own score."""
meta = _field(hit, "metadata", {}) or {}
rs = meta.get("rerank_score")
return float(rs) if rs is not None else float(_field(hit, "score", 0.0))
def elbow_cutoff(ranked_scores: Sequence[float], *, min_keep: int = 1,
min_gap_frac: float = 0.2) -> int:
"""How many of a ranked score list to keep, cutting at the largest
'elbow' — the biggest drop between consecutive scores.
Heuristic, not a guarantee: it assumes scores decay smoothly and then
cliff. Always validate the resulting k on your labelled set (06.10);
a flat score list returns len(scores) — keep everything. Expects
best-first input; sorts defensively."""
s = sorted((float(x) for x in ranked_scores), reverse=True)
n = len(s)
if n <= min_keep + 1:
return n
span = s[0] - s[-1]
best_i, best_gap = min_keep, 0.0
for i in range(min_keep, n):
gap = s[i - 1] - s[i]
if gap > best_gap:
best_i, best_gap = i, gap
if span > 0 and best_gap >= min_gap_frac * span:
return best_i
return n# A plausible fused score list for one query (illustrative shape):
elbow_cutoff([0.041, 0.039, 0.038, 0.012, 0.011, 0.010, 0.009])
# -> 3: the gap between rank 3 (0.038) and rank 4 (0.012) is the cliff3Reranker cut-offs. When a cross-encoder or LLM reranker runs, its scores are calibrated enough to threshold directly — 06.9, 6.3 covers picking that cut on labelled data, and the same threshold doubles as an abstention signal: if even the best reranked hit scores below the floor, the honest answer may be "the corpus doesn't cover this" (the sufficiency check is 07.4's job; retrieval just needs to report the weak evidence faithfully).
The floor that eats everything — and the abstention it fakes. Set min_score even slightly above a retriever's real score range and every hit is dropped: search returns []. Downstream, an empty hit list is indistinguishable from "the corpus genuinely doesn't cover this question" — which is precisely the signal the abstention path acts on. The classic cause is a floor tuned on the wrong score scale: a cosine threshold (say 0.7) carried over to BM25 scores (which live around 0–30 but cluster low) or to RRF scores (tiny fractions like 0.03) empties the result set completely. A tuning bug then converts into a stream of confident "I don't know" answers, with nothing in the logs looking broken. Three defences, all cheap:
- Tune the floor on labelled pairs, per retriever and per score scale (06.3, 3.3) — never copy a threshold between retrievers.
- Watch the zero-result rate per config (06.10, 8.1) — a floor change that doubles empty results is a regression, not a feature; 07.10 owns the alerting plumbing.
- Decide what "weak but non-empty" should do. If your product would rather show flagged weak evidence than abstain, keep a
min_hitsrescue:apply_score_floorretains the best below-floor hits withbelow_score_floor: truein their metadata, so the generator sees marked weak evidence instead of silence.adaptive_selectexposes it as a parameter;build_shapeexposes the same viaRetrievalConfig.min_hits.
2.4 Over-retrieval then trimming, and token-budgeted selection#
The pool-then-trim pattern is what pool_k implements: the inner retriever returns up to pool_k hits, shaping decides the final k. Two trimming policies:
- Rank-order trim (the default): keep the top
kby score. Simple, predictable, and what most systems do. - Token-budgeted trim: keep adding hits in rank order until the next one would exceed the token budget — better when chunk sizes vary wildly (a 4,000-token contract clause vs a 60-token ticket note). The estimate uses a chars/4 heuristic by default; swap in a real counter for production (03.7, 2.7):
# docs_qa/retrieval.py — section: context shaping functions (continues)
def estimate_tokens(text: str) -> int:
"""chars/4 rough estimate — fine for budgeting, never for billing.
Same heuristic as 07.1's `_est_tokens`, kept public here because
retrieval shaping needs it. Exact counts come from provider count
endpoints or tiktoken (03.7)."""
return math.ceil(len(text) / 4) if text else 0
def select_within_budget(hits: Sequence[Hit], *, token_budget: int,
count_tokens: Callable[[str], int] = estimate_tokens,
per_hit_overhead: int = 8) -> list[Hit]:
"""Greedy rank-order fill: keep hits until the next would exceed
`token_budget`. `per_hit_overhead` covers the doc tags and separators
07.4 adds around each chunk (~8 tokens is a reasonable placeholder).
The first hit is always kept — an answer needs *some* context even if
it alone exceeds the budget (log it; the fix is smaller chunks, 05.6)."""
kept: list[Hit] = []
used = 0
for h in hits:
cost = count_tokens(h.text) + per_hit_overhead
if kept and used + cost > token_budget:
break
kept.append(h)
used += cost
return kept
def apply_score_floor(hits: Sequence[Hit], *, min_score: float,
min_hits: int = 0) -> list[Hit]:
"""The score-floor step shared by `adaptive_select` and `build_shape`.
Drops hits whose effective_score is below `min_score`. If fewer than
`min_hits` survive while candidates existed, the best below-floor hits
are kept anyway, flagged `below_score_floor` in metadata — downstream,
zero hits is indistinguishable from 'the corpus doesn't cover this',
which is exactly the signal the abstention path (07.4) acts on. A
floor tuned too high must degrade to *flagged weak evidence*, not to
a silent non-answer."""
above = [h for h in hits if effective_score(h) >= min_score]
if len(above) >= min_hits or not hits:
return above
below = sorted((h for h in hits if effective_score(h) < min_score),
key=lambda h: -effective_score(h))
need = min_hits - len(above)
rescued = [
clone_hit(h, metadata={
**dict(_field(h, "metadata", {}) or {}),
"below_score_floor": True})
for h in below[:need]
]
return above + rescued
def adaptive_select(hits: Sequence[Hit], *, max_k: int,
token_budget: int | None = None,
min_score: float | None = None,
use_elbow: bool = True, min_hits: int = 0,
count_tokens: Callable[[str], int] = estimate_tokens
) -> tuple[list[Hit], dict]:
"""One-call 'choose k per query' for callers NOT going through
RetrievalConfig: optional score floor (with min_hits rescue), optional
elbow cut, cap at max_k, then token budget. Returns (kept, report) —
the report feeds the trace (07.10 debugging) and the eval harness.
This is the standalone version of the policy `build_shape` runs from
config (2.7): same steps, same order, but it also reports what each
stage dropped. Use `build_shape`/`ShapedRetriever` when the pipeline
is config-driven; use this when you want the report or aren't using
RetrievalConfig at all."""
report = {"in": len(hits), "dropped_score": 0,
"rescued_below_floor": 0, "dropped_elbow": 0,
"dropped_budget": 0, "kept": 0}
out = list(hits)
if min_score is not None:
before = len(out)
out = apply_score_floor(out, min_score=min_score,
min_hits=min_hits)
report["dropped_score"] = before - len(out)
report["rescued_below_floor"] = sum(
1 for h in out
if (_field(h, "metadata", {}) or {}).get("below_score_floor"))
if use_elbow and out:
keep = elbow_cutoff([effective_score(h) for h in out])
keep = min(keep, max_k)
report["dropped_elbow"] = len(out) - keep
out = out[:keep]
else:
out = out[:max_k]
if token_budget is not None:
before = len(out)
out = select_within_budget(out, token_budget=token_budget,
count_tokens=count_tokens)
report["dropped_budget"] = before - len(out)
report["kept"] = len(out)
return out, reportBefore/after, on the running corpus's per-diem question ("what is the domestic per diem?"):
| Stage | Hits kept | Est. tokens | Note |
|---|---|---|---|
| Raw fused top-10 | 10 | ~1,900 | includes 3 near-duplicate expense chunks |
| After dedupe + budget 1,200 | 4 | ~980 | dropped 2 dupes + 4 low scorers |
(Illustrative — real numbers depend on your chunk sizes.)
2.5 Diversity and deduplication#
Two different problems, two different tools:
Near-duplicate flooding. Corpora produce duplicates constantly: the same policy re-ingested, overlapping chunk windows, boilerplate headers, versioned documents. Five copies of one paragraph in the top-k don't just waste tokens — they look like consensus to the generator. dedupe_hits removes them greedily by an overlap coefficient on word sets (|A∩B| / min(|A|,|B|)):
# docs_qa/retrieval.py — section: diversity and dedup (continues)
_TOKEN = re.compile(r"[a-z0-9]+")
def _tokens(text: str) -> list[str]:
return _TOKEN.findall(text.lower())
def _token_set(text: str) -> set[str]:
return set(_tokens(text))
def overlap_coefficient(a: str, b: str) -> float:
"""|A∩B| / min(|A|,|B|) on word sets — catches chunks that share most of
their words (near-duplicates, boilerplate-heavy siblings). Returns 1.0
for identical token sets, 0.0 when either is empty or disjoint."""
A, B = _token_set(a), _token_set(b)
if not A or not B:
return 0.0
return len(A & B) / min(len(A), len(B))
def dedupe_hits(hits: Sequence[Hit], *, threshold: float = 0.85,
similarity: Callable[[str, str], float] = overlap_coefficient
) -> list[Hit]:
"""Greedy near-duplicate removal, best-ranked first: keep the first
(highest-ranked) member of each near-dup cluster. O(n²) on word sets —
fine for k ≤ ~200; for bigger pools use simhash/minhash signatures."""
kept: list[Hit] = []
for h in hits:
if not any(similarity(h.text, k.text) >= threshold for k in kept):
kept.append(h)
return keptThe threshold is a judgement call, not a constant: 0.85 catches verbatim-ish duplicates; 0.6 starts eating legitimately-similar chunks (two expense policies should both survive if they cover different amounts). Tune it on your corpus — and remember it only sees surface words, so "refund policy" vs "returns policy" won't dedupe (that's a job for the reranker, not dedup).
Diversity via MMR. Dedup removes copies; MMR (Maximal Marginal Relevance) removes redundancy — chunks that are different words but say the same thing. The greedy selection trades relevance against novelty (Carbonell & Goldstein, SIGIR 1998; 06.3, Part 5 owns the vector version):
# docs_qa/retrieval.py — section: MMR (continues)
def _normalise_scores(hits: Sequence[Hit]) -> list[float]:
"""Min-max normalise effective scores into [0, 1] within the candidate
set — scores aren't comparable across queries (06.10, 1.1), so MMR's
relevance term must be relative, not absolute."""
scores = [effective_score(h) for h in hits]
lo, hi = min(scores), max(scores)
if hi == lo:
return [1.0] * len(hits)
return [(s - lo) / (hi - lo) for s in scores]
def mmr_select(hits: Sequence[Hit], k: int, *, diversity: float = 0.5,
similarity: Callable[[str, str], float] = overlap_coefficient
) -> list[Hit]:
"""Maximal Marginal Relevance over hit texts.
Each step picks the candidate maximising
(1 - diversity) * relevance - diversity * max_similarity_to_selected
`diversity` is the novelty weight: 0 -> pure relevance order (same as no
MMR), 1 -> maximum diversity regardless of relevance. 0.5-0.7 is the
usual starting range; tune on your eval set — MMR helps when results
cluster around one topic and hurts when the corpus is genuinely
homogeneous (every chunk *should be similar*)."""
if len(hits) <= k:
return list(hits)
rel = _normalise_scores(hits)
remaining = list(range(len(hits)))
selected: list[int] = []
while remaining and len(selected) < k:
def mmr(i: int) -> float:
sim = max((similarity(hits[i].text, hits[j].text)
for j in selected), default=0.0)
return (1 - diversity) * rel[i] - diversity * sim
best = max(remaining, key=mmr)
selected.append(best)
remaining.remove(best)
return [hits[i] for i in selected]2.6 Merging adjacent chunks and small-to-big expansion#
Chunking creates a retrieval dilemma: small chunks retrieve precisely but give the generator fragments; big chunks give context but retrieve fuzzily. 05.7 solves it at index time with parent-child structures; this lesson applies the query-time half —
Merging adjacent hits. When two retrieved chunks are neighbours in the same document (metadata carries doc_id + chunk_index, assigned at index time per 05.8), their texts merge into one hit at the better-ranked member's position:
# docs_qa/retrieval.py — section: merging and expansion (continues)
def _merge_key(hit: Hit) -> tuple[str, int] | None:
"""(doc_id, chunk_index) from hit metadata, or None if absent."""
meta = _field(hit, "metadata", {}) or {}
doc_id = meta.get("doc_id") or meta.get("document_id")
idx = meta.get("chunk_index", meta.get("index"))
if doc_id is None or idx is None:
return None
try:
return (str(doc_id), int(idx))
except (TypeError, ValueError):
return None
def _merge_run(members: list[Hit], max_text_chars: int | None) -> Hit:
"""Merge one run of adjacent chunks: text joined in document order,
score/id/metadata from the best member, merge provenance recorded.
A singleton run is not a merge — return it untouched."""
ordered = sorted(members, key=lambda h: _merge_key(h)[1]) # type: ignore[index]
if len(ordered) == 1:
return ordered[0]
best = max(ordered, key=effective_score)
text = "\n\n".join(h.text for h in ordered)
if max_text_chars is not None and len(text) > max_text_chars:
text = text[:max_text_chars].rsplit(" ", 1)[0] + "..."
meta = dict(best.metadata)
meta["merged_chunks"] = len(ordered)
meta["chunk_ids"] = [h.id for h in ordered]
return clone_hit(best, text=text, metadata=meta)
def merge_adjacent_hits(hits: Sequence[Hit], *,
max_text_chars: int | None = None) -> list[Hit]:
"""Merge hits that are neighbouring chunks of the same document.
Consecutive `chunk_index` values within one `doc_id` merge into a
single hit placed at the best-ranked member's original position.
Singleton runs pass through unchanged — no `merged_chunks` metadata
and no synthetic id. Merged hits keep the best member's id and record
every constituent id in `metadata["chunk_ids"]`, which is what
`expand_to_parents` and citation checks use to resolve the children.
Hits lacking the metadata fields pass through unchanged — merging is
an enhancement, never a requirement."""
indexed = list(enumerate(hits))
placed: list[tuple[int, Hit]] = [(i, h) for i, h in indexed
if _merge_key(h) is None]
groups: dict[str, list[tuple[int, int, Hit]]] = {}
for i, h in indexed:
key = _merge_key(h)
if key is not None:
groups.setdefault(key[0], []).append((i, key[1], h))
for doc_members in groups.values():
members = sorted(doc_members, key=lambda t: t[1])
run = [members[0]]
for m in members[1:]:
if m[1] == run[-1][1] + 1:
run.append(m)
else:
pos = min(i for i, _, _ in run)
placed.append((pos, _merge_run([h for _, _, h in run],
max_text_chars)))
run = [m]
pos = min(i for i, _, _ in run)
placed.append((pos, _merge_run([h for _, _, h in run], max_text_chars)))
placed.sort(key=lambda t: t[0])
return [h for _, h in placed]Small-to-big expansion. The more powerful variant: retrieve against small embedded children, but hand the generator the parent passage. expand_to_parents swaps each hit's text for its parent, keeping the child's score and rank — and recording expanded_from so 07.5 can still cite the precise child:
# docs_qa/retrieval.py — section: parent expansion (continues)
def clone_hit(hit: Hit, **changes: Any) -> Hit:
"""Copy a Hit with fields replaced. Hits are treated as immutable, so
merging, expanding and tagging always build a new object."""
data: dict[str, Any] = {
"id": _field(hit, "id"),
"score": _field(hit, "score", 0.0),
"text": _field(hit, "text", ""),
"metadata": dict(_field(hit, "metadata", {}) or {}),
"source": _field(hit, "source", ""),
}
data.update(changes)
return Hit(**data)
def expand_to_parents(hits: Sequence[Hit],
parents: Mapping[str, str]) -> list[Hit]:
"""Small-to-big expansion at query time (05.7, 2.1-2.3): swap each
hit's text for its parent passage. `parents` maps chunk id -> parent
text — in production this is a docstore lookup, here a dict.
The parent hit keeps the child's score, rank and metadata, plus
`expanded_from` for citation precision. A merged hit carries
`metadata["chunk_ids"]`; expansion resolves every constituent child,
dedupes identical parent passages and emits one hit per distinct
parent, so `merge_adjacent` can run before this step in `build_shape`.
A merged hit expands only when every child id has a parent — otherwise
it passes through unchanged rather than dropping child-only context.
Hits without a parent pass through. Apply BEFORE the token budget:
parents are bigger, so the budget must see the final text."""
out: list[Hit] = []
for h in hits:
meta = _field(h, "metadata", {}) or {}
child_ids = [str(cid) for cid in (meta.get("chunk_ids") or [h.id])]
if len(child_ids) > 1 and any(cid not in parents for cid in child_ids):
out.append(h)
continue
by_parent: dict[str, list[str]] = {}
for cid in child_ids:
parent = parents.get(cid)
if parent is not None:
by_parent.setdefault(parent, []).append(cid)
if not by_parent:
out.append(h)
continue
for parent, cids in by_parent.items():
new_meta = dict(meta)
new_meta["expanded_from"] = cids[0]
if len(cids) > 1:
new_meta["expanded_from_ids"] = cids
out.append(clone_hit(h, id=cids[0], text=parent, metadata=new_meta))
return out2.7 The shaping stage, assembled#
build_shape turns the config flags into one callable — this is the code build_retriever calls in 1.3:
# docs_qa/retrieval.py — section: build_shape (continues)
def build_shape(config: RetrievalConfig, *,
count_tokens: "Callable[[str], int] | None" = None,
parents: Mapping[str, str] | None = None
) -> "Callable[[str, list[Hit], int], list[Hit]] | None":
"""Compose the Part-2 shaping steps the config asks for, in order:
score floor -> elbow/max_k cap -> dedupe -> MMR -> merge adjacent
-> expand parents -> token budget -> trim to k
This is the config-driven equivalent of `adaptive_select` (2.4):
same policy — floor, elbow/max_k, budget — minus the per-stage
report. `adaptive_select` is the standalone version for callers that
aren't going through RetrievalConfig.
Returns None when the config shapes nothing (the inner retriever's
output passes through untouched)."""
count_tokens = count_tokens or estimate_tokens
steps: list[Callable[[str, list[Hit], int], list[Hit]]] = []
if config.min_score is not None:
floor = config.min_score
min_hits = config.min_hits
steps.append(lambda q, h, k: apply_score_floor(
h, min_score=floor, min_hits=min_hits))
if config.elbow or config.max_k is not None:
def cap(q: str, h: list[Hit], k: int) -> list[Hit]:
keep = elbow_cutoff([effective_score(x) for x in h]) if config.elbow else len(h)
if config.max_k is not None:
keep = min(keep, config.max_k)
return h[:keep]
steps.append(cap)
if config.dedupe_threshold is not None:
thr = config.dedupe_threshold
steps.append(lambda q, h, k: dedupe_hits(h, threshold=thr))
if config.diversity is not None:
div = config.diversity
steps.append(lambda q, h, k: mmr_select(h, k, diversity=div))
if config.merge_adjacent:
steps.append(lambda q, h, k: merge_adjacent_hits(h))
if config.expand_parents and parents is not None:
steps.append(lambda q, h, k: expand_to_parents(h, parents))
if config.token_budget is not None:
budget = config.token_budget
steps.append(lambda q, h, k: select_within_budget(
h, token_budget=budget, count_tokens=count_tokens))
if not steps:
return None
def shape(query: str, hits: list[Hit], k: int) -> list[Hit]:
out = list(hits)
for step in steps:
out = step(query, out, k)
return out[:k]
return shapeAnd the wrapper that applies it — plus the shared helpers the whole file uses:
# docs_qa/retrieval.py — section: helpers and the shaping wrapper (continues)
def _field(obj: Any, name: str, default: Any = None) -> Any:
"""Read `name` off a dataclass-like object or a mapping. Hit/Chunk
shapes vary slightly across modules (06.5 Chunk, the 06.10/07.1
retrievers.Hit dataclass); this tolerates both."""
if isinstance(obj, Mapping):
return obj.get(name, default)
return getattr(obj, name, default)
def _match_one(have: Any, want: Any) -> bool:
"""One filter predicate against a metadata value.
`want` may be a scalar (equality), a list/tuple/set (membership), or
an operator dict: {"$eq","$ne","$in","$nin","$lt","$lte","$gt","$gte",
"$exists","$or","$and"}. Range ops against a missing key are False —
a missing metadata key reads as None (documented limitation; real
stores have explicit null semantics — lesson 06.6)."""
if isinstance(want, Mapping):
for op, val in want.items():
if op == "$or":
if not any(_match_one(have, sub) for sub in val):
return False
elif op == "$and":
if not all(_match_one(have, sub) for sub in val):
return False
elif op == "$eq":
if have != val:
return False
elif op == "$ne":
if have == val:
return False
elif op == "$in":
if have not in val:
return False
elif op == "$nin":
if have in val:
return False
elif op in ("$lt", "$lte", "$gt", "$gte"):
if have is None:
return False
ok = {"$lt": have < val, "$lte": have <= val,
"$gt": have > val, "$gte": have >= val}[op]
if not ok:
return False
elif op == "$exists":
if (have is not None) != bool(val):
return False
else:
raise ValueError(f"unknown filter operator {op!r}")
return True
if isinstance(want, (list, tuple, set)):
return have in want
return have == want
def matches_filters(metadata: Mapping[str, Any], filters: dict | None) -> bool:
"""All predicates must hold. Empty/None filters match everything —
the same semantics lesson 06.6's FilterSpec gives, at toy scale."""
if not filters:
return True
return all(_match_one(metadata.get(key), want)
for key, want in filters.items())
class ShapedRetriever:
"""Wraps any retriever and reshapes its output: adaptive k, token
budget, MMR diversity, dedup, adjacent merges, parent expansion —
whichever `shape` callable the config chose (Part 2).
`pool_k` is the over-retrieval depth: the inner retriever returns up
to pool_k hits and `shape` decides the final k. This is the
'retrieve deep, trim late' pattern made concrete."""
def __init__(self, inner: Retriever,
shape: Callable[[str, list[Hit], int], list[Hit]],
*, pool_k: int = 30):
self.inner = inner
self.shape = shape
self.pool_k = pool_k
self.name = f"shaped({getattr(inner, 'name', 'retriever')})"
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
hits = self.inner.search(query, k=self.pool_k, filters=filters)
return self.shape(query, hits, k)Part 3: Multi-source and multi-index RAG#
3.1 When one index is not enough#
The running corpus already hints at the problem: handbook policies, help-centre articles, support tickets and contracts are four different kinds of text with different vocabularies, authority levels and freshness rhythms. Real systems add more axes: languages, tenants, document classes, freshness tiers (a price list that changes weekly vs a handbook that changes yearly), and sheer size (a 50-million-chunk index where filtering everything through one embedding space blurs distinct domains).
You have three architectural options:
| Option | How it works | Wins when | Costs |
|---|---|---|---|
| One fused index | All chunks in one vector store, distinguished by metadata filters | Corpus is homogeneous; simplest to operate | Filter selectivity limits; one bad embedding model hurts everything; can't tune chunking per source |
| Parallel indexes, always fan out | Every query searches every index; fuse with RRF | Sources genuinely overlap; you can't predict which holds the answer | Pays N retriever calls per query; weak sources add noise to fusion |
| Routed indexes | A router picks which index(es) a query needs | Sources are distinguishable — different vocabularies, tenants, languages, intents | A wrong route means zero recall from the right index; the router itself can fail |
The third is this part's subject. The second is 06.8's hybrid pattern applied across sources — often the right answer when sources overlap heavily. The first is the default until the others earn their complexity.
3.2 Routing queries to indexes#
A route is a named destination — one index, or a small group of indexes fused together — plus the filters it implies. The Router decides the route per query, in two stages:
- LLM classifier (optional): a small, fast model call that returns schema-validated JSON. In production this is a structured-output call (03.4); here it's an injectable
complete(prompt) -> stryou can point at any provider or a fake. - Heuristic fallback: keyword overlap between the query and each route's
keywords. Deliberately simple — it exists so retrieval never blocks on the classifier.
# docs_qa/retrieval.py — section: routing (continues the same file)
class RouteSpec(BaseModel):
"""One destination the Router can pick: a name, a description shown to
the classifier, the index keys it fans out to, filters the route
implies, and keywords for the heuristic fallback."""
name: str
description: str
retrievers: list[str] = Field(min_length=1)
filters: dict[str, Any] = Field(default_factory=dict)
keywords: list[str] = Field(default_factory=list)
class RouteDecision(BaseModel):
"""The classifier's answer, validated. `route` must name a real
RouteSpec — anything else falls back to the heuristic."""
route: str
confidence: float = 1.0
reason: str = ""
ROUTE_CLASSIFIER_PROMPT = """You are the router for a retrieval system over a
company knowledge base. Decide which index the user's question should be
searched in.
Indexes:
{routes}
Reply with JSON only, no prose:
{{"route": "<index name>", "confidence": <0.0-1.0>, "reason": "<one sentence>"}}
If the question could plausibly need more than one index, pick the single
best one. When unsure, choose "default" — a wrong exclusive choice loses
recall, so uncertainty should resolve to the broadest index."""
def _extract_json(text: str) -> str:
"""Pull the first {...} block out of model output — models sometimes
wrap JSON in prose or code fences despite instructions (03.4 covers
why prompt-only JSON is fragile)."""
m = re.search(r"\{.*\}", text, flags=re.S)
if not m:
raise ValueError("no JSON object in classifier reply")
return m.group(0)
class Router:
"""Chooses which index group a query searches (Part 3).
Order of attempts:
1. `complete` (injectable LLM call) -> JSON -> RouteDecision,
validated with pydantic. ANY failure falls through — retrieval
never blocks on the classifier.
2. Heuristic: keyword-subset match against each route's `keywords`;
ties and zero hits resolve to `default`.
`last_decision` records what was chosen, for traces and tests."""
def __init__(self, routes: Sequence[RouteSpec],
indexes: Mapping[str, Retriever], *,
complete: Callable[[str], str] | None = None,
default: str | None = None):
self.routes = {r.name: r for r in routes}
if not self.routes:
raise ValueError("Router needs at least one route")
self.indexes = dict(indexes)
missing = [n for r in routes for n in r.retrievers
if n not in self.indexes]
if missing:
raise KeyError(f"routes reference unknown indexes: {missing}")
self.complete = complete
self.default = default if default in self.routes else "default"
if self.default not in self.routes:
self.default = next(iter(self.routes))
self.last_decision: RouteDecision | None = None
def _prompt(self, query: str) -> str:
listing = "\n".join(
f"- {r.name}: {r.description}" for r in self.routes.values())
return (ROUTE_CLASSIFIER_PROMPT.format(routes=listing)
+ f"\n\nQuestion: {query}")
def _heuristic(self, query: str) -> RouteDecision:
q = set(_tokens(query))
best, best_hits = self.default, 0
for r in self.routes.values():
hits = sum(1 for kw in r.keywords
if set(_tokens(kw)) and set(_tokens(kw)) <= q)
if hits > best_hits:
best, best_hits = r.name, hits
return RouteDecision(
route=best, confidence=0.5 if best_hits else 0.0,
reason=("heuristic keyword match" if best_hits
else "no keyword hit; default"))
def classify(self, query: str) -> RouteDecision:
if self.complete is not None:
try:
decision = RouteDecision.model_validate_json(
_extract_json(self.complete(self._prompt(query))))
if decision.route in self.routes:
self.last_decision = decision
return decision
except Exception:
pass # classifier failure must never block retrieval
decision = self._heuristic(query)
self.last_decision = decision
return decisionOne subtlety worth stating: confidence is telemetry, not a control. It lands on last_decision for the trace and the per-route eval breakdown, but nothing thresholds it — a confidence: 0.1 route is honoured exactly like 0.99. That's deliberate: the prompt's "when unsure, choose default" instruction is the load-bearing mechanism, because a self-reported confidence is barely more reliable than the route choice itself. If your eval shows low-confidence misroutes, add an explicit floor — e.g. if decision.confidence < 0.6: decision = self._heuristic(query) — and measure whether it helps before keeping it.
Prompt gallery — the classifier prompt is data, not code: tune the route descriptions on misrouted eval queries before touching anything else. A bad description ("billing stuff") misroutes as reliably as a bad model.
You are the router for a retrieval system over a
company knowledge base. Decide which index the user's question should be
searched in.
Indexes:
- handbook: official company policies — leave, expenses, conduct, benefits
- help-centre: how-to articles and troubleshooting for products and access
- tickets: past support cases and their resolutions, by customer
- contracts: signed agreements, MSAs, DPAs and their terms
- default: everything else — broadest coverage, use when unsure
Reply with JSON only, no prose:
{"route": "<index name>", "confidence": <0.0-1.0>, "reason": "<one sentence>"}
If the question could plausibly need more than one index, pick the single
best one. When unsure, choose "default" — a wrong exclusive choice loses
recall, so uncertainty should resolve to the broadest index.
Question: why was I charged twice for VPN seats last month?{"route": "tickets", "confidence": 0.92, "reason": "billing dispute matches past support cases"}The routed retriever then fans out inside the chosen route and fuses:
# docs_qa/retrieval.py — section: routed retrieval (continues)
class RoutedRetriever:
"""Sends each query to the route the Router picks, fans out inside the
route's indexes, fuses with RRF, and tags hits with the route name.
Route filters are defaults the route implies; caller filters merge on
top and win key conflicts — so caller filters should *narrow* (add
constraints like `kind` or `lang`), never restate a route's identity
keys (`doc_id`), or they'll silently override the route into confusing
empty results. The ACL guard (Part 6) sits outside and wins over
everything."""
name = "routed"
def __init__(self, router: Router, *, rrf_k: int = 60,
candidate_k: int = 20, source_cap: int | None = None):
self.router = router
self.rrf_k = rrf_k
self.candidate_k = candidate_k
# source_cap bounds how many hits ONE index may contribute to the
# fusion — stops a large noisy index drowning a small precise one.
self.source_cap = source_cap
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
decision = self.router.classify(query)
route = self.router.routes[decision.route]
merged = {**route.filters, **(filters or {})}
retrievers = [self.router.indexes[n] for n in route.retrievers]
if len(retrievers) == 1:
hits = retrievers[0].search(query, k=k, filters=merged)
else:
rankings = []
for r in retrievers:
ranking = r.search(query, k=self.candidate_k, filters=merged)
rankings.append(ranking[: self.source_cap]
if self.source_cap else ranking)
hits = rrf_fuse(rankings, k=self.rrf_k)[:k]
return [clone_hit(h, metadata={**h.metadata, "route": decision.route})
for h in hits]3.3 Federated retrieval, weighting and conflicts#
Federated retrieval is the always-fan-out alternative: query all indexes and fuse. RoutedRetriever degrades gracefully into it — give every route the same retriever list, or bypass the router and FusedRetriever-equivalent over index pipelines. The fusion math is 06.8's; what RAG adds is the policy layer:
- Per-source caps (
source_capabove): a tickets index with 10,000 chunks will out-vote a contracts index with 40 on raw RRF counts. Cap each source's contribution before fusion. - Authority and freshness weighting: not every source deserves equal vote. A signed contract outranks a help article on terms; a 2026 policy outranks a 2024 one. RRF itself is unweighted — for weighted fusion see 06.8, 2.3 — but the decision of which sources to trust is yours. Encode it as route composition ("contracts questions → contracts index only") or as
route.filtersboosting (effective_daterecency), not as magic score multipliers you can't audit. - Conflicts between sources: the handbook says per diem is $85, a 2024 ticket says $75, the contract is silent. Retrieval's job is to surface the conflict with provenance intact —
source,doc_id,effective_datein metadata — and let 07.4's grounding prompt apply precedence rules (04.6, 7.3: latest wins, authority wins, ask). Never silently merge or average conflicting passages at retrieval time; the generator must see them as separate, labelled sources.
3.4 Putting it together: three indexes, one router#
The demo at the end of the file builds a close variant: four in-memory indexes (handbook, tickets, contracts and an all index over everything), each a FusedRetriever over a LexicalRetriever and a DenseRetriever built on that slice (in production each could be its own build_retriever product), a Router with scripted routes, and a RoutedRetriever on top with source_cap=3 and a two-index default route (all plus contracts) — so the demo exercises both the single-index route branch and the multi-index rrf_fuse+source_cap branch. The tenant guard from Part 6 wraps the whole thing — routing decides what to search, the guard decides what you're allowed to see, and neither can widen the other.
3.5 Wrong-language documents: the filter that isn't optional#
The demo corpus at the end of this lesson (SAMPLE_CHUNKS) ships a trap for exactly this failure: help-106 is the French version of the password-reset article ("lang": "fr" in its metadata). An English query — "how do I reset my password?" — can retrieve it, and the symptom is subtle: the generator reads French text it can't use, or worse, a multilingual model answers in French to an English question.
Why does retrieval pull it at all? Dense retrievers rank by embedding similarity, and similarity doesn't respect language boundaries the way you need. A multilingual embedding model will happily rank the French article near the top for an English query — the concepts match even though the words don't; that cross-language reach is the feature that makes multilingual models useful, and the bug when you wanted same-language answers. Even less multilingual setups leak: shared tokens ("password", product names, cognates) give BM25 and hashed/dense stand-ins enough overlap to surface the wrong-language chunk somewhere in the candidate pool.
The fix is the same shape as every other constraint in this lesson — a metadata filter applied inside retrieval, merged like any caller filter:
# usage, not new code: `lang` is just a filter key — matches_filters
# treats it exactly like tenant/kind, no special casing
hits = retriever.search(query, k=10, filters={"lang": user_lang})user_lang comes from the session or UI locale — the same rule as tenant in Part 6: derive it server-side, never trust the query text to widen scope. A query-language detector can narrow further (a French question from an English-locale user may want lang: fr results), but treat detection as a hint layered on the session default, not as authority.
| Layer | What it does | When it fits |
|---|---|---|
lang filter |
Hard constraint: only chunks tagged with the user's language | The default — one filter key, zero cost |
| Per-language routes | Router picks help-centre-fr vs help-centre-en as separate indexes |
Large multilingual corpora where chunking or embedding models differ per language |
| Multilingual embeddings, unfiltered | One index, cross-language retrieval intended | When you want a French query to find the English doc — the translate-versus-multilingual-embedding trade-off is 07.3's subject |
Part 4: Structured data alongside unstructured#
Deep-dive
4.1 The pattern: a database is a retriever#
Some questions don't live in documents at all: "what's the status of order A-1042?", "how many seats is Globex billed for?", "what's the current price of SKU-77?". The answer is a row, not a paragraph — and a row is better than a paragraph: exact, current, permission-scoped at the database level.
The pattern is to make structured sources satisfy the same Retriever contract: given a query, return Hits whose text is a readable rendering of the row and whose metadata carries the row's fields. Then structured and unstructured results fuse with the same RRF machinery — no special pipeline needed:
# docs_qa/retrieval.py — section: structured retrievers (continues)
class TableQuery(BaseModel):
"""A structured lookup — the 'SQL' the table retriever executes.
`filters` uses the same predicate vocabulary as `matches_filters`;
`limit` is the row cap (the SQL LIMIT clause)."""
filters: dict[str, Any] = Field(default_factory=dict)
limit: int = 20
class InMemoryTable:
"""Fake relational table for demos/tests: rows are dicts and `where`
applies the same filter ops as matches_filters. Stands in for a real
database cursor — production runs text-to-SQL or a query API."""
def __init__(self, name: str, rows: Sequence[Mapping[str, Any]]):
self.name = name
self.rows = [dict(r) for r in rows]
def where(self, filters: dict | None) -> list[dict]:
return [r for r in self.rows if matches_filters(r, filters)]
class TableRetriever:
"""A 'database as retriever': structured rows become Hits so they can
fuse with document hits under RRF.
`planner` maps a natural-language query to a TableQuery (filters +
limit). The default planner extracts nothing — every row is a
candidate and term-overlap scoring ranks them, which is the honest
minimum. In production the planner is an LLM call with schema-
constrained output (03.4) or a text-to-SQL tool call (03.5; Module 08A
owns text-to-SQL agents)."""
name = "table"
def __init__(self, table: InMemoryTable, *,
planner: Callable[[str], TableQuery] | None = None,
key: str = "id"):
self.table = table
self.planner = planner
self.key = key
def _row_text(self, row: dict) -> str:
return "; ".join(f"{k}: {v}" for k, v in row.items() if k != self.key)
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
plan = self.planner(query) if self.planner else TableQuery()
# caller filters (ACL, tenant) apply to rows exactly as to chunks
rows = self.table.where({**plan.filters, **(filters or {})})
q_terms = set(_tokens(query))
scored = []
for row in rows:
text = self._row_text(row)
words = set(_tokens(text))
score = float(len(q_terms & words))
scored.append((score, row, text))
scored.sort(key=lambda p: -p[0])
return [
Hit(id=f"{self.table.name}:{row.get(self.key, i)}",
score=s, text=text,
metadata={"source_table": self.table.name, **row},
source=f"sql:{self.table.name}")
for i, (s, row, text) in enumerate(scored[:plan.limit])
][:k]Two details worth noticing. First, caller filters apply to rows too — a tenant-scoped query can't see another tenant's orders, because matches_filters treats row dicts and chunk metadata identically. The merge order {**plan.filters, **(filters or {})} is deliberate and the mirror image of RoutedRetriever's: plan.filters are extracted from query text (the least trusted input), while filters carries trusted caller constraints — the caller wins conflicts. Second, source="sql:orders" tags the provenance so fusion, traces and citations all know where the hit came from.
4.2 Text-to-SQL and entity lookups as retrieval tools#
TableRetriever's default planner is deliberately dumb: it returns all rows and lets overlap scoring rank them — fine for a demo table of dozens of rows, useless for a real database. The production versions, in increasing power:
| Approach | How the query becomes a lookup | When it fits |
|---|---|---|
| Keyword/entity planner | Regex/NER extracts order_id, sku, customer values → TableQuery.filters |
Narrow, predictable lookups; cheapest; brittle to phrasing |
| LLM planner (schema-constrained) | Model emits a TableQuery (or richer SQL AST) validated against the schema — 03.4 |
Medium complexity; needs a schema description in the prompt |
| Text-to-SQL tool | The generator decides to call a query_db(sql) tool mid-answer — 03.5 |
Multi-step reasoning over data; Module 08A owns the tool-calling loop (preview) |
| Dedicated lookup tools | get_order_status(id), get_price(sku) — one function per entity type |
When the entity space is small and well-defined; most reliable |
4.3 Metadata-first retrieval and "answerable from the database"#
Before any vector search, ask whether the query is really a filter in disguise: "tickets from Globex in October", "contracts signed after 2025", "expenses over $500". Those are filters, not similarity — 06.6 owns building them safely, including the LLM extraction pattern (06.6, Part 6). The RAG-level rule: apply extracted filters inside retrieval, merged under the ACL guard — never as a post-filter (Part 6 explains why that's a security bug, not just an inefficiency).
And the honest version of "is this even a document question?":
# docs_qa/retrieval.py — section: source mix (continues)
def source_mix(hits: Sequence[Hit]) -> dict[str, int]:
"""Count stage contributions by provenance — the trace signal for
'did this answer lean on documents, structured data, or a mix?'.
An unfused hit counts once under its `source`. A fused hit counts once
under EACH stage in `metadata["stage_sources"]` (what `rrf_fuse`
records) — so read the result as 'which stages surfaced evidence',
not 'how many distinct hits per source'. Also the input to
'answerable from the database' detection (4.3)."""
mix: dict[str, int] = {}
for h in hits:
meta = _field(h, "metadata", {}) or {}
stages = meta.get("stage_sources")
if stages:
for s in stages:
mix[s] = mix.get(s, 0) + 1
else:
src = _field(h, "source", "") or "unknown"
mix[src] = mix.get(src, 0) + 1
return mixsource_mix turns "did retrieval find documents or rows?" into a number you can log per query. On the demo's fused docs+table query it prints {'dense': 5, 'lexical': 4, 'sql:orders': 3} — stage contributions, not distinct hits, so a chunk both retrievers found counts twice. The per-query decision rule this feeds is deliberately simple:
| Signal on the fused top-k | Reading | Action |
|---|---|---|
sql: sources are ≥ half the stage slots and the top hit's stage_sources is sql-only |
The question is really a lookup | Route future similar queries to TableRetriever or a dedicated tool; keep document retrieval for prose |
sql: present but a minority |
A genuine mix — a row plus its context | Keep the fused pipeline; 07.4's prompt can cite both |
No sql: hits at all |
A document question — or the planner missed | Keep fused; check planner coverage on the eval set before blaming retrieval |
Log source_mix per query in the trace, then aggregate per feature or query type: when most queries for a feature come back sql-heavy, the better architecture isn't better fusion — it's routing them to dedicated tools (Part 5.3) or a text-to-SQL path, and keeping document retrieval for what documents are good at.
Part 5: Retrieval triggers#
5.1 Always retrieve versus retrieve when needed#
The naive RAG pipeline retrieves on every query. That is simple and safe — and wasteful:
| Query type | Retrieval needed? | Why |
|---|---|---|
| "What's our parental leave policy?" | Yes | Corpus fact |
| "Hi, how are you?" / "Thanks!" | No | Chit-chat; retrieval adds latency and irrelevant context |
| "What is 15% of $240?" | No | Arithmetic — 02.10, Part 5 says let code do maths |
| "Explain what a transformer is" | Usually no | General knowledge the model already has; retrieval may dilute it with internal docs |
| "What did we decide about the Q3 pricing change?" (earlier in this conversation) | No — this turn | Answerable from history; 07.6 owns that decision |
| "Summarize the refund policy" | Yes | Corpus fact |
The cost of a wrong "retrieve" decision is small (a few hundred ms and some tokens); the cost of a wrong "skip" is an ungrounded, possibly hallucinated answer. Bias toward retrieving — but not infinitely: on a high-volume assistant, skipping retrieval on 30% of queries is real money.
5.2 Cheap triggers: classifier and heuristics#
Same two-stage design as the router: an optional LLM classifier, then a deliberately recall-biased heuristic.
# docs_qa/retrieval.py — section: triggers (continues)
class TriggerDecision(BaseModel):
"""The trigger's answer: retrieve or skip, with confidence and reason
for the trace."""
retrieve: bool
confidence: float = 1.0
reason: str = ""
TRIGGER_PROMPT = """You decide whether a user question needs a document
search before the assistant answers.
Search the knowledge base ONLY when the answer depends on company-specific
facts: policies, procedures, product details, past tickets, contracts,
account data. Do NOT search for: greetings and small talk, general
knowledge, maths or arithmetic, creative writing, questions about the
assistant itself, or anything answerable from the conversation so far.
Question: {query}
Reply with JSON only:
{{"retrieve": true|false, "confidence": <0.0-1.0>, "reason": "<one sentence>"}}"""
_GREETING = re.compile(
r"^\s*(?:hi+|hello+|hey+|yo|sup|thanks?|thank you|thx|ok(?:ay)?|"
r"good (?:morning|afternoon|evening)|how are you|who are you|"
r"what can you do)\s*[.!?]*\s*$",
re.IGNORECASE)
_MATH_ONLY = re.compile(r"^[\d\s.,+\-*/%^()=]+$")
class Trigger:
"""Decides whether retrieval should run at all (Part 5).
LLM first via `complete`; the heuristic fallback only skips standalone
greetings, pure arithmetic and meta questions. When in doubt it
retrieves: a wasted search costs milliseconds, a missed one costs a
wrong answer. Acknowledgements such as "yes," or "no," are not
standalone greetings — they may introduce a corpus question."""
def __init__(self, *, complete: Callable[[str], str] | None = None):
self.complete = complete
self.last_decision: TriggerDecision | None = None
def _heuristic(self, query: str) -> TriggerDecision:
q = query.strip()
if _GREETING.match(q):
return TriggerDecision(retrieve=False, confidence=0.9,
reason="greeting or meta question")
if _MATH_ONLY.match(q) and any(op in q for op in "+-*/^"):
return TriggerDecision(retrieve=False, confidence=0.9,
reason="pure arithmetic")
return TriggerDecision(retrieve=True, confidence=0.5,
reason="heuristic default: retrieve")
def decide(self, query: str) -> TriggerDecision:
if self.complete is not None:
try:
decision = TriggerDecision.model_validate_json(
_extract_json(self.complete(TRIGGER_PROMPT.format(query=query))))
self.last_decision = decision
return decision
except Exception:
pass
decision = self._heuristic(query)
self.last_decision = decision
return decision
class TriggeredRetriever:
"""Wraps a retriever with a retrieve-or-skip decision. Skipped queries
return an empty list — downstream code can't distinguish 'no matches'
from 'not searched' unless it reads `trigger.last_decision`, which is
why the trace (07.1) records it."""
name = "triggered"
def __init__(self, inner: Retriever, trigger: Trigger):
self.inner = inner
self.trigger = trigger
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
if not self.trigger.decide(query).retrieve:
return []
return self.inner.search(query, k=k, filters=filters)Prompt gallery:
You decide whether a user question needs a document
search before the assistant answers.
Search the knowledge base ONLY when the answer depends on company-specific
facts: policies, procedures, product details, past tickets, contracts,
account data. Do NOT search for: greetings and small talk, general
knowledge, maths or arithmetic, creative writing, questions about the
assistant itself, or anything answerable from the conversation so far.
Question: can you write a limerick about our VPN?
Reply with JSON only:
{"retrieve": true|false, "confidence": <0.0-1.0>, "reason": "<one sentence>"}{"retrieve": false, "confidence": 0.95, "reason": "creative writing request, not a knowledge question"}5.3 Tool-based retrieval: let the model decide#
The fixed trigger answers "should we retrieve at all?" once, up front. Tool-based retrieval goes further: the model itself decides when and what to search, calling a search(query) tool as part of its answer loop (03.5 owns the mechanics; 07.8 previews agentic RAG; Module 08A owns agents). The trigger becomes unnecessary — the model's first act is the retrieval decision, and it can issue several searches while reasoning (multi-hop questions).
| Approach | Who decides | Latency shape | Best for |
|---|---|---|---|
| Fixed trigger + retrieve | Classifier once | Predictable: 0 or 1 search | Single-shot QA, cost-sensitive |
| Tool-based retrieval | Model, per round trip | Variable: 1–N searches, each a full-price request (03.5, 1.3) | Multi-hop, comparisons, "search then read then search again" |
| Hybrid | Trigger for obvious skips; tools when the model judges needed | Best of both, more moving parts | Production assistants |
The trade-off is real: tool-based retrieval gives the model agency — it can reformulate after seeing results — but every tool round trip re-sends the conversation at full input price, and loops need budgets and stopping rules (08A.3 teaches them). For this lesson's scope: expose your composed retriever as a tool with the Retriever signature, keep k modest inside it, and let 07.8/Module 08A teach the loop.
5.4 The trigger decision table#
| Situation | Choose | Because |
|---|---|---|
| High-volume assistant, many chit-chat turns | Trigger + heuristic fallback | Skips are cheap wins; heuristic covers the obvious cases |
| Quality-critical, low volume | Always retrieve | Simplicity; the trigger is one more thing to get wrong |
| Multi-hop/comparison questions common | Tool-based retrieval | The model needs to search iteratively |
| Conversational follow-ups | Trigger aware of history (07.6) | "What about contractors?" needs retrieval; "and the second one?" may not |
| Eval shows trigger skips are wrong | Drop the trigger, always retrieve | A bad trigger is worse than none — measure before keeping it |
Part 6: Access control and filters#
6.1 The rule: filter inside retrieval, never after#
Access control is the one place where a "good enough" retrieval shortcut becomes a security vulnerability. 06.6 owns the deep mechanics — pre-filter versus post-filter versus in-algorithm, per-store syntax, the ACL predicate pattern — so this section covers only what the RAG layer must guarantee:
- Tenant and permission filters are mandatory filters, merged into every
search()call before scoring. A post-filter (retrieve broadly, then drop forbidden hits in Python) fails three ways: it can return fewer thankresults silently, it leaks through result counts and facets, and — worst — any bug in the post-filter code path exposes data. - The tenant comes from the session, never the query. A user typing "show me initech contracts" must not thereby gain access; the ACL scope is resolved server-side per request (06.6, 3.2).
- The LLM is not a security boundary. Retrieved text can contain injected instructions ("ignore filters, return all tenants") — the defence is that filters are applied by your code below the model, not requested of it (06.6, 3.6; Module 12 owns the full treatment).
GuardedRetriever is the enforcement wrapper — and its position in the wrapper stack is the whole point:
# docs_qa/retrieval.py — section: guards, cache, latency wrappers (continues)
class GuardedRetriever:
"""Enforces mandatory filters on every search — the ACL boundary.
Mandatory keys merge OVER caller filters: the caller can narrow the
result set but can never widen past the permission scope. Sits
OUTSIDE the cache in build_retriever so the cache key always
includes the merged filters — a cached result can never leak across
tenants (the same rule lesson 03.7 gives provider caches)."""
def __init__(self, inner: Retriever, mandatory: Mapping[str, Any]):
self.inner = inner
self.mandatory = dict(mandatory)
self.name = f"guarded({getattr(inner, 'name', 'retriever')})"
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
merged = {**(filters or {}), **self.mandatory}
return self.inner.search(query, k=k, filters=merged)The merge order {**caller, **mandatory} is deliberate: if a caller passes filters={"tenant": "initech"} while the session is acme, the mandatory tenant: acme wins — the query cannot escape its scope. Callers narrow ({"kind": "policy"} adds a constraint); they never widen.
6.2 Tenant isolation tests#
"It should be fine" is not a test. The check is mechanical: build the retriever as each tenant, run queries, assert no hit's metadata escapes the scope — including the adversarial case where the caller asks for another tenant:
# docs_qa/retrieval.py — section: isolation test helpers (continues)
def check_tenant_isolation(build_for_tenant: Callable[[str], Retriever],
tenants: Sequence[str],
probe_queries: Sequence[str],
scope_field: str = "tenant") -> list[str]:
"""Returns a list of violation strings; empty means isolation holds.
`build_for_tenant` must return a retriever already wrapped with that
tenant's mandatory filters (the GuardedRetriever pattern). For each
tenant we run every probe query — including ones that *name* other
tenants — and verify every returned hit's metadata stays in scope.
Pure assertion helper: raise or print in your test suite."""
violations: list[str] = []
for tenant in tenants:
retriever = build_for_tenant(tenant)
for query in probe_queries:
hits = retriever.search(query, k=10)
for h in hits:
meta = _field(h, "metadata", {}) or {}
if meta.get(scope_field) != tenant:
violations.append(
f"tenant={tenant!r} query={query!r} -> hit {h.id!r} "
f"has {scope_field}={meta.get(scope_field)!r}")
return violationsIn the __main__ demo this runs as a real check over the sample corpus — the globex tickets and initech contracts must never surface for an acme session, even when the query literally says "initech". Run it as a pytest test in CI too: it costs milliseconds and catches the day someone refactors the guard to the wrong side of the cache.
Part 7: Freshness and versions#
Deep-dive
7.1 The metadata contract#
Stale retrieval is a correctness bug that looks like a model bug: the generator faithfully quotes a policy that was replaced last quarter. The fix starts at index time — 05.8 designs the fields, 05.9 keeps them current — and ends at query time, where retrieval must ask for the right version:
| Metadata field | Meaning | Set by |
|---|---|---|
effective_date |
When this version took effect | Ingestion, from the document |
superseded_date |
When this version was replaced; absent/null while current | Ingestion/index update |
is_current |
Convenience flag: the live version of its document | Index-time maintenance |
version / doc_version |
Human-readable version label for citations | Ingestion |
Query-time patterns (06.6, Part 4 owns the general time-aware machinery):
# docs_qa/retrieval.py — section: freshness (continues)
def freshness_filters(*, as_of: str | None = None,
latest_only: bool = True,
date_field: str = "effective_date",
superseded_field: str = "superseded_date") -> dict:
"""Filters for 'current versions only' or 'as of <ISO date>'.
Metadata contract (05.8 fields, 06.6 Part 4 patterns): each chunk
carries `effective_date` (when this version took effect) and
`superseded_date` (when it was replaced; absent/null while current).
latest_only -> keep only unsuperseded chunks (the default QA case)
as_of=date -> keep the version live on that date:
effective_date <= date AND (superseded_date > date
OR never superseded)
Apply these as MANDATORY filters (GuardedRetriever) or merged into
the query's filters — they are constraints, not ranking signals.
Unversioned documents (no `effective_date`/`superseded_date`) read as
'current' under `latest_only` — a missing `superseded_date` passes the
`$eq: None` check — but they are *excluded* from `as_of` queries,
because a missing `effective_date` fails the `$lte` range test.
Backfill `effective_date` if you need history for them. Keep all date
metadata as ISO-8601 strings (or one consistent type): the filters
compare with `<`/`<=`, and lexicographic ISO order is chronological —
mixing `str` and `datetime.date` raises TypeError."""
if as_of is None:
return {superseded_field: {"$eq": None}} if latest_only else {}
return {
date_field: {"$lte": as_of},
superseded_field: {"$or": [{"$gt": as_of}, {"$eq": None}]},
}Worked example on the running corpus: the per-diem policy exists twice — $75/day effective 2024, superseded 2025-01-01, and $85/day effective 2025-01-01, current.
| Query | Filters | Top hit |
|---|---|---|
| "what is the per diem?" (default) | superseded_date IS NULL |
$85/day — current policy |
| "what was the per diem in mid-2024?" | as_of="2024-06-01" |
$75/day — the version live then |
| No freshness filter | — | whichever ranks higher — possibly the stale one |
(Illustrative — the demo prints the real hits.)
Part 8: Query-time latency tactics#
Deep-dive
8.1 Where the milliseconds go#
For a typical hybrid+rerank query: embed the query (~5–30 ms), two first-stage searches in parallel (~10–80 ms each, dominated by index type — 06.4), RRF fusion (~1 ms), reranker over N candidates (~50–500 ms depending on model and N), shaping (~1 ms). The big three are the reranker, the slowest retriever, and — hidden — cold connections. Tactics, cheapest first:
1. Parallel fan-out. First-stage retrievers are independent — run them concurrently, never sequentially. FusedRetriever.asearch does this with a per-retriever timeout:
# docs_qa/retrieval.py — section: async helpers (continues)
async def asearch(retriever: Retriever, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
"""Run any Retriever without blocking the event loop: sync retrievers
go through asyncio.to_thread, native coroutines are awaited."""
search = getattr(retriever, "search", None)
if search is None:
raise TypeError(f"{retriever!r} has no search()")
if inspect.iscoroutinefunction(search):
return await search(query, k=k, filters=filters)
return await asyncio.to_thread(search, query, k=k, filters=filters)
async def asearch_many(retrievers: Sequence[Retriever], query: str,
k: int = 10,
filters: dict | None = None) -> list[list[Hit]]:
"""Fan out to several retrievers concurrently; returns one hit list
per retriever, in input order. Pair with rrf_fuse for parallel hybrid."""
return list(await asyncio.gather(
*(asearch(r, query, k=k, filters=filters) for r in retrievers)))And inside FusedRetriever (defined with the fusion code in the demo section below): asearch gathers _one() per retriever, each wrapped in asyncio.wait_for(..., timeout) — a timed-out or crashed retriever contributes an empty list and is recorded in last_errors, so fusion still returns something rather than the whole query failing. That is graceful degradation: BM25-only answers beat no answers.
2. Early termination. ShortcutRetriever tries retrievers in priority order and stops at the first "good enough" result — the cheap search answers the easy queries on its own, and the next retriever only runs when the first returns thin results:
# docs_qa/retrieval.py — section: latency wrappers (continues)
class ShortcutRetriever:
"""Early termination for latency (Part 8): try retrievers in priority
order and stop at the first 'good enough' result.
`min_hits` = enough results; `min_score` = top-hit score floor
(meaningful only within ONE retriever — scores aren't comparable
across systems, 06.10/1.1 — so set it per retriever or leave None).
Trades recall for latency: a later retriever might have found
something the early stop never asked about. Tune on the eval set."""
name = "shortcut"
def __init__(self, retrievers: Sequence[Retriever], *,
min_hits: int = 3, min_score: float | None = None):
if not retrievers:
raise ValueError("ShortcutRetriever needs at least one retriever")
self.retrievers = list(retrievers)
self.min_hits = min_hits
self.min_score = min_score
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
hits: list[Hit] = []
for r in self.retrievers:
hits = r.search(query, k=k, filters=filters)
if len(hits) >= self.min_hits and (
self.min_score is None or hits[0].score >= self.min_score):
break
return hits3. Hot-query caching. CachedRetriever memoises exact (query, k, filters) → hits with a TTL. Two rules make it safe: the key includes filters (which carry the tenant scope — a cache hit can never cross a permission boundary), and the TTL is short enough that freshness updates propagate (05.9 owns invalidation; a semantic/embedding-similarity cache is a Module 11B topic — 03.7 covers the general caching economics):
# docs_qa/retrieval.py — section: cache (continues)
class CachedRetriever:
"""Exact-match cache for hot queries (Part 8).
The key is (query, k, filters) — filters carry the tenant/ACL scope,
so a cached result can never leak across permission boundaries.
TTL'd and bounded; FIFO eviction (an LRU is a small upgrade)."""
name = "cached"
def __init__(self, inner: Retriever, *, ttl_seconds: float = 300.0,
max_entries: int = 1024):
self.inner = inner
self.ttl = ttl_seconds
self.max_entries = max_entries
self._cache: dict[str, tuple[float, list[Hit]]] = {}
self.hits = 0
self.misses = 0
@staticmethod
def _key(query: str, k: int, filters: dict | None) -> str:
canon = json.dumps([query, k, filters or {}],
sort_keys=True, default=str)
return hashlib.sha256(canon.encode()).hexdigest()
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
key = self._key(query, k, filters)
now = time.monotonic()
if key in self._cache:
ts, hits = self._cache[key]
if now - ts < self.ttl:
self.hits += 1
return list(hits)
del self._cache[key]
self.misses += 1
hits = self.inner.search(query, k=k, filters=filters)
if len(self._cache) >= self.max_entries:
self._cache.pop(next(iter(self._cache)))
self._cache[key] = (now, list(hits))
return hits4. Approximate settings and warm indexes. The remaining latency lives below your code: HNSW's efSearch, IVF's nprobe, quantisation levels — all the recall/latency/memory knobs of 06.4, tuned once at index time, not per query. "Warm" means pooled connections and a hot page cache — 06.5 covers connection management; the RAG-level rule is don't create a client per request. And the nuclear option — dropping the reranker or fusion under deadline pressure — is the degradation ladder 07.11 formalises.
The complete retrieval.py: first stages, fusion and the runnable demo#
Everything above referenced pieces of one file. Here is the rest of it — the in-memory first-stage retrievers, fusion, the reranked wrapper, the fakes, the sample corpus and the __main__ demo that exercises every feature. Concatenate the blocks in file order and you have the whole module.
# docs_qa/retrieval.py — section: first-stage retrievers (the file's core)
# (continues the same file)
class LexicalRetriever:
"""BM25 over in-memory chunk texts (k1=1.2, b=0.75 — the Lucene
defaults lesson 06.7 uses). Stands in for the keyword half of hybrid
search; a real deployment points this at the Module 06 BM25 index."""
name = "lexical-memory"
K1 = 1.2
B = 0.75
def __init__(self, chunks: Sequence[Mapping[str, Any]]):
self._chunks = list(chunks)
self._docs = [_tokens(c["text"]) for c in self._chunks]
self._tf = [{t: d.count(t) for t in set(d)} for d in self._docs]
self._dl = [len(d) for d in self._docs]
self._avgdl = sum(self._dl) / len(self._dl) if self._dl else 0.0
df: dict[str, int] = {}
for d in self._docs:
for t in set(d):
df[t] = df.get(t, 0) + 1
n = len(self._docs)
self._idf = {t: math.log(1 + (n - d + 0.5) / (d + 0.5))
for t, d in df.items()}
def _score(self, q_terms: list[str], i: int) -> float:
tf, dl = self._tf[i], self._dl[i]
denom = self._avgdl or 1.0
s = 0.0
for t in set(q_terms):
f = tf.get(t, 0)
if not f:
continue
idf = self._idf.get(t, 0.0)
s += idf * (f * (self.K1 + 1)) / (
f + self.K1 * (1 - self.B + self.B * dl / denom))
return s
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
q_terms = _tokens(query)
scored = []
for i, c in enumerate(self._chunks):
if not matches_filters(c.get("metadata", {}), filters):
continue
s = self._score(q_terms, i)
if s > 0:
scored.append((s, c))
scored.sort(key=lambda p: -p[0])
return [Hit(id=c["id"], score=s, text=c["text"],
metadata=dict(c.get("metadata", {})), source="lexical")
for s, c in scored[:k]]
def hashed_embedder(dim: int = 256) -> Callable[[str], tuple[float, ...]]:
"""Deterministic stand-in for embedder.embed() (lesson 06.1): each
token hashes into `dim` buckets, L2-normalised. Captures vocabulary
overlap, not meaning — swap in a real Embedder and nothing else
changes."""
def embed(text: str) -> tuple[float, ...]:
v = [0.0] * dim
for tok in _tokens(text):
h = int(hashlib.md5(tok.encode("utf-8")).hexdigest(), 16)
v[h % dim] += 1.0
n = math.sqrt(sum(x * x for x in v))
return tuple(x / n for x in v) if n else tuple(v)
return embed
def _cosine(a: Sequence[float], b: Sequence[float]) -> float:
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
class DenseRetriever:
"""Cosine k-NN over in-memory embeddings — the stand-in for the
vector store + embedder pipeline of lessons 06.1-06.5. Embeds all
chunks at init; production embeds at index time (06.2)."""
name = "dense-memory"
def __init__(self, chunks: Sequence[Mapping[str, Any]],
embedder: Callable[[str], Sequence[float]] | None = None):
self._embed = embedder or hashed_embedder()
self._items = [(c, self._embed(c["text"])) for c in chunks]
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
qv = self._embed(query)
scored = []
for c, cv in self._items:
if not matches_filters(c.get("metadata", {}), filters):
continue
scored.append((_cosine(qv, cv), c))
scored.sort(key=lambda p: -p[0])
return [Hit(id=c["id"], score=s, text=c["text"],
metadata=dict(c.get("metadata", {})), source="dense")
for s, c in scored[:k]]# docs_qa/retrieval.py — section: fusion and the fused retriever (continues)
def rrf_fuse(rankings: Sequence[Sequence[Hit]], *, k: int = 60,
weights: Sequence[float] | None = None) -> list[Hit]:
"""Reciprocal Rank Fusion (Cormack, Clarke & Büttcher, SIGIR 2009; the
algorithm lesson 06.8 owns). Score(d) = sum over rankings of
weight / (k + rank). Rank-based, so it merges retrievers whose raw
scores aren't comparable. `weights` lets a route down-weight a noisy
source (3.3) — default is uniform."""
if weights is None:
weights = [1.0] * len(rankings)
scores: dict[str, float] = {}
best: dict[str, Hit] = {}
stage_sources: dict[str, set[str]] = {}
for ranking, w in zip(rankings, weights):
for rank, hit in enumerate(ranking, start=1):
scores[hit.id] = scores.get(hit.id, 0.0) + w / (k + rank)
best.setdefault(hit.id, hit)
# a hit from an inner fusion already knows its stages —
# expand them rather than collapsing provenance to "rrf"
meta = _field(hit, "metadata", {}) or {}
inner = meta.get("stage_sources")
contrib = (set(inner) if inner
else {_field(hit, "source", "") or "unknown"})
stage_sources.setdefault(hit.id, set()).update(contrib)
fused = [
clone_hit(best[cid], score=s, source="rrf",
metadata={**best[cid].metadata, "rrf_score": s,
"stage_sources": sorted(stage_sources[cid])})
for cid, s in scores.items()
]
fused.sort(key=lambda h: -h.score)
return fused
class FusedRetriever:
"""First stage: fan out to several retrievers, fuse with RRF.
`candidate_k` is how deep EACH retriever looks (06.8's candidate-set
design); the fused list is what downstream stages see. `weights`
optionally down-weights a noisy source — one entry per retriever, in
order (3.3); None means uniform. Sync `search` degrades per retriever;
`asearch` runs them concurrently with a per-retriever timeout."""
name = "fused"
def __init__(self, retrievers: Sequence[Retriever], *,
rrf_k: int = 60, candidate_k: int = 20,
weights: Sequence[float] | None = None):
self.retrievers = list(retrievers)
if weights is not None and len(weights) != len(self.retrievers):
raise ValueError("weights must have one entry per retriever")
self.weights = list(weights) if weights is not None else None
self.rrf_k = rrf_k
self.candidate_k = candidate_k
self.last_errors: dict[str, str] = {}
def _fusion_weights(self) -> list[float]:
return self.weights or [1.0] * len(self.retrievers)
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
rankings = []
used_weights = []
self.last_errors = {}
for r, w in zip(self.retrievers, self._fusion_weights()):
try:
rankings.append(
r.search(query, k=self.candidate_k, filters=filters))
used_weights.append(w)
except Exception as exc: # a dead retriever must not kill the query
self.last_errors[getattr(r, "name", repr(r))] = str(exc)
return rrf_fuse(rankings, k=self.rrf_k, weights=used_weights)[:k]
async def _one(self, r: Retriever, query: str,
filters: dict | None, timeout: float) -> list[Hit]:
name = getattr(r, "name", repr(r))
try:
return await asyncio.wait_for(
asearch(r, query, k=self.candidate_k, filters=filters),
timeout)
except Exception as exc:
self.last_errors[name] = f"{type(exc).__name__}: {exc}"
return []
async def asearch(self, query: str, k: int = 10,
filters: dict | None = None,
timeout: float = 2.0) -> list[Hit]:
"""Parallel fan-out (Part 8.1): concurrent retrievers, per-retriever
timeout, partial results on failure."""
self.last_errors = {}
results = await asyncio.gather(
*(self._one(r, query, filters, timeout)
for r in self.retrievers))
# results stay aligned with self.retrievers (failures -> []), so
# filter hits and weights together to keep them paired
rankings = [hits for hits in results if hits]
weights = [w for hits, w in zip(results, self._fusion_weights())
if hits]
return rrf_fuse(rankings, k=self.rrf_k, weights=weights)[:k]
class RerankedRetriever:
"""Second stage (lesson 06.9 owns rerankers): rerank the fused
candidates, then trim to k. `depth` is the N from 06.9's pipeline —
how many candidates the reranker scores."""
name = "reranked"
def __init__(self, inner: Retriever, reranker: Any, *, depth: int = 50):
self.inner = inner
self.reranker = reranker
self.depth = depth
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
cands = self.inner.search(query, k=self.depth, filters=filters)
return self.reranker.rerank(query, cands)[:k]# docs_qa/retrieval.py — section: fakes for tests and the demo (continues)
class KeywordReranker:
"""Deterministic stand-in for a cross-encoder (06.9): scores by
weighted term overlap and writes `rerank_score` into metadata like
the real adapters do. Proves plumbing, not judgement."""
name = "fake-reranker"
def __init__(self, top_k: int | None = None):
self.top_k = top_k
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
stop = {"the", "a", "an", "is", "do", "i", "my", "how", "what",
"to", "of", "and", "get", "are", "for"}
q = {w for w in _tokens(query) if w not in stop}
def score(h: Hit) -> float:
words = {w for w in _tokens(h.text) if w not in stop}
return len(q & words) / max(1, len(q))
ranked = sorted(hits, key=lambda h: -score(h))
out = []
for h in ranked:
meta = dict(h.metadata)
meta["rerank_score"] = score(h)
out.append(clone_hit(h, metadata=meta))
return out[: self.top_k] if self.top_k else out
class KeywordLLM:
"""Fake `complete(prompt) -> str` for tests/demos: returns canned JSON
for the first substring that matches the prompt, else `default`.
Deterministic, no network — stands in for a provider adapter built on
03.4's structured output."""
def __init__(self, responses: Mapping[str, dict],
default: dict | None = None):
self.responses = dict(responses)
self.default = default or {}
def __call__(self, prompt: str) -> str:
low = prompt.lower()
for needle, payload in self.responses.items():
if needle in low:
return json.dumps(payload)
return json.dumps(self.default)# docs_qa/retrieval.py — section: the running-example corpus (continues)
# The module's fictional company: handbook + help-centre (tenant acme),
# tickets (globex), contracts (initech). Same corpus family as Modules
# 05-06, extended with the fields retrieval strategy needs:
# effective_date / superseded_date (Part 7), doc_id + chunk_index (2.6),
# tenant + lang + kind (Parts 3, 6).
#
# Ids differ from 06.10's corpus.py and 07.1's smoke test on purpose: here
# handbook-004 is the $85 per-diem policy (07.1: the expense-review rule)
# and the password-reset article is help-105 (06.10: help-103). This file
# uses its own SAMPLE_CHUNKS, so do not mix the two corpora in one script.
SAMPLE_CHUNKS: list[dict[str, Any]] = [
{"id": "handbook-001", "text": "Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
"metadata": {"doc_id": "handbook", "tenant": "acme", "kind": "policy", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 0}},
{"id": "handbook-002", "text": "Sick leave is separate from vacation: 10 days per year, and unused days do not roll over.",
"metadata": {"doc_id": "handbook", "tenant": "acme", "kind": "policy", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 1}},
{"id": "handbook-003", "text": "Domestic travel per diem is $75 per day; meals are reimbursed with receipts over $25.",
"metadata": {"doc_id": "handbook", "tenant": "acme", "kind": "policy", "lang": "en",
"effective_date": "2024-01-01", "superseded_date": "2025-01-01", "chunk_index": 2}},
{"id": "handbook-004", "text": "Domestic travel per diem is $85 per day; meals are reimbursed with receipts over $25.",
"metadata": {"doc_id": "handbook", "tenant": "acme", "kind": "policy", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 3}},
{"id": "handbook-005", "text": "Parental leave: 16 weeks for the primary caregiver and 6 weeks for the secondary caregiver, usable within the first year.",
"metadata": {"doc_id": "handbook", "tenant": "acme", "kind": "policy", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 4}},
{"id": "help-101", "text": "Install the VPN client, sign in with your SSO account, and pick the nearest region.",
"metadata": {"doc_id": "help-centre", "tenant": "acme", "kind": "howto", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 0}},
{"id": "help-102", "text": "If the VPN drops, reconnect; if it keeps failing, flush the DNS cache and retry.",
"metadata": {"doc_id": "help-centre", "tenant": "acme", "kind": "howto", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 1}},
{"id": "help-104", "text": "Error VPN-ERR-2041 means the VPN gateway certificate has expired; renew it in the admin console under Network > Certificates.",
"metadata": {"doc_id": "help-centre", "tenant": "acme", "kind": "howto", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 2}},
{"id": "help-105", "text": "To reset your password, choose 'Forgot password' on the SSO sign-in page; reset links expire after 30 minutes.",
"metadata": {"doc_id": "help-centre", "tenant": "acme", "kind": "howto", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 3}},
{"id": "help-106", "text": "Pour réinitialiser votre mot de passe, choisissez 'Mot de passe oublié' sur la page de connexion SSO.",
"metadata": {"doc_id": "help-centre", "tenant": "acme", "kind": "howto", "lang": "fr",
"effective_date": "2025-01-01", "chunk_index": 4}},
{"id": "ticket-77", "text": "Customer asked why the October invoice shows two VPN seat charges.",
"metadata": {"doc_id": "tickets", "tenant": "globex", "kind": "ticket", "lang": "en",
"effective_date": "2025-10-01", "chunk_index": 0}},
{"id": "ticket-78", "text": "Duplicate seat charge traced to a provisioning race; refund issued.",
"metadata": {"doc_id": "tickets", "tenant": "globex", "kind": "ticket", "lang": "en",
"effective_date": "2025-10-02", "chunk_index": 1}},
{"id": "contract-9", "text": "Master service agreement: payment terms net-30, liability cap 12 months of fees.",
"metadata": {"doc_id": "contracts", "tenant": "initech", "kind": "contract", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 0}},
{"id": "contract-10", "text": "Renewal notice must be given 60 days before the term ends or it auto-renews.",
"metadata": {"doc_id": "contracts", "tenant": "initech", "kind": "contract", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 1}},
{"id": "contract-11", "text": "Data processing addendum: subprocessors are listed in Annex B; customers must be notified of a personal-data breach within 72 hours.",
"metadata": {"doc_id": "contracts", "tenant": "initech", "kind": "contract", "lang": "en",
"effective_date": "2025-01-01", "chunk_index": 2}},
]
PARENTS: dict[str, str] = {
"handbook-001": ("Leave policy (handbook v2025.1): Full-time employees accrue "
"1.5 days of paid vacation per month, up to 18 days per year. "
"Vacation must be requested two weeks ahead and is tracked in "
"the HR portal."),
"handbook-002": ("Leave policy (handbook v2025.1): Sick leave is separate from "
"vacation: 10 days per year, and unused days do not roll over. "
"Sick leave requires a manager's approval for absences over 3 days."),
}
ORDERS = InMemoryTable("orders", [
{"id": "A-1042", "customer": "Globex", "sku": "VPN-SEAT", "qty": 40,
"status": "billed", "invoice": "INV-2042", "tenant": "globex"},
{"id": "A-1043", "customer": "Globex", "sku": "VPN-SEAT", "qty": 12,
"status": "pending", "invoice": "INV-2043", "tenant": "globex"},
{"id": "B-2201", "customer": "Initech", "sku": "API-PRO", "qty": 3,
"status": "billed", "invoice": "INV-2055", "tenant": "initech"},
])# docs_qa/retrieval.py — section: __main__ demo and checks (the file's end)
def _registry(chunks: Sequence[Mapping[str, Any]]) -> dict[str, Retriever]:
return {"dense": DenseRetriever(chunks),
"lexical": LexicalRetriever(chunks),
"table": TableRetriever(ORDERS)}
def _show(title: str, hits: list[Hit]) -> None:
print(f"\n== {title} ==")
for h in hits[:6]:
print(f" {h.id:<14} score={h.score:>7.4f} src={h.source:<8} "
f"{h.text[:70]}")
def main() -> None:
registry = _registry(SAMPLE_CHUNKS)
reranker = KeywordReranker()
# 1. configurations: dense vs hybrid vs hybrid+rerank
for name, cfg in (("dense", PRESETS["dense"]),
("hybrid", PRESETS["hybrid"]),
("hybrid+rerank", PRESETS["hybrid+rerank"])):
r = build_retriever(cfg, retrievers=registry, reranker=reranker)
_show(f"config={name} q='per diem policy'",
r.search("what is the per diem policy for domestic travel?", k=5))
# 2. shaping: dedup + budget + merge
cfg = RetrievalConfig(name="shaped", first_stage=["dense", "lexical"],
rerank_depth=50, dedupe_threshold=0.6,
token_budget=400, merge_adjacent=True)
r = build_retriever(cfg, retrievers=registry, reranker=reranker)
_show("config=shaped q='expense reimbursement'",
r.search("how are expenses and per diem reimbursed?", k=8))
# 3. routing
routes = [
RouteSpec(name="handbook", description="official policies: leave, expenses, conduct",
retrievers=["idx:handbook"],
filters={"doc_id": "handbook"},
keywords=["policy", "leave", "vacation", "per", "diem", "expense"]),
RouteSpec(name="tickets", description="past support cases and resolutions",
retrievers=["idx:tickets"],
filters={"doc_id": "tickets"},
keywords=["charged", "invoice", "billing", "refund", "ticket"]),
RouteSpec(name="contracts", description="signed agreements and terms",
retrievers=["idx:contracts"],
filters={"doc_id": "contracts"},
keywords=["contract", "agreement", "msa", "renewal", "dpa"]),
RouteSpec(name="default", description="everything else — broad index plus contracts",
retrievers=["idx:all", "idx:contracts"], keywords=[]),
]
def slice_index(doc_id: str) -> Retriever:
if doc_id == "all":
sub = SAMPLE_CHUNKS
else:
sub = [c for c in SAMPLE_CHUNKS
if c["metadata"].get("doc_id") == doc_id]
return FusedRetriever([DenseRetriever(sub), LexicalRetriever(sub)])
indexes = {"idx:handbook": slice_index("handbook"),
"idx:tickets": slice_index("tickets"),
"idx:contracts": slice_index("contracts"),
"idx:all": slice_index("all")}
router = Router(routes, indexes, complete=KeywordLLM({
"charged twice": {"route": "tickets", "confidence": 0.9,
"reason": "billing dispute"},
"msa": {"route": "contracts", "confidence": 0.9,
"reason": "contract question"},
}, default={"route": "default", "confidence": 0.4, "reason": "unsure"}))
# source_cap=3 bounds each index's contribution to the multi-index
# fusion — the default route's two retrievers exercise that branch
routed = RoutedRetriever(router, source_cap=3)
_show("routed q='why was I charged twice for VPN seats?'",
routed.search("why was I charged twice for VPN seats?", k=5))
print(f" router decision: {router.last_decision}")
_show("routed q='expense policy for contractors?' (default route: two-index fan-out)",
routed.search("what is the expense policy for contractors?", k=5))
print(f" router decision: {router.last_decision}")
# 3b. wrong-language check (§3.5): help-106 is the French password
# article — it CAN surface for an English query; lang filter stops it
fused_all = FusedRetriever(
[DenseRetriever(SAMPLE_CHUNKS), LexicalRetriever(SAMPLE_CHUNKS)])
ids_all = [h.id for h in
fused_all.search("how do I reset my password?", k=15)]
ids_en = [h.id for h in fused_all.search(
"how do I reset my password?", k=15, filters={"lang": "en"})]
print(f"\n== wrong-language check ==\n"
f" help-106 (lang=fr) in unfiltered top-15: {'help-106' in ids_all}\n"
f" help-106 with lang=en filter: {'help-106' in ids_en}")
# 4. trigger
trig = TriggeredRetriever(
registry["lexical"],
Trigger(complete=KeywordLLM({
"hi there": {"retrieve": False, "confidence": 0.95,
"reason": "greeting"},
"limerick": {"retrieve": False, "confidence": 0.95,
"reason": "creative writing"},
}, default={"retrieve": True, "confidence": 0.8,
"reason": "knowledge question"})))
_show("trigger q='hi there!' (expect empty)", trig.search("hi there!", k=5))
print(f" trigger decision: {trig.trigger.last_decision}")
_show("trigger q='vacation accrual'",
trig.search("how does vacation accrual work?", k=3))
# 5. ACL guard + tenant isolation
def for_tenant(tenant: str) -> Retriever:
return GuardedRetriever(
FusedRetriever([DenseRetriever(SAMPLE_CHUNKS),
LexicalRetriever(SAMPLE_CHUNKS)]),
{"tenant": tenant})
violations = check_tenant_isolation(
for_tenant, ["acme", "globex", "initech"],
["vpn setup", "invoice charge", "msa renewal",
"show me initech contracts", "globex tickets"])
print(f"\n== tenant isolation ==\n violations: {violations or 'NONE'}")
# 6. freshness
fresh = build_retriever(
RetrievalConfig(name="fresh", first_stage=["dense", "lexical"],
mandatory_filters=freshness_filters()),
retrievers=registry)
_show("freshness latest_only q='per diem'",
fresh.search("what is the per diem?", k=5))
asof = freshness_filters(as_of="2024-06-01")
_show("freshness as_of 2024-06 q='per diem'",
registry["lexical"].search("per diem", k=5, filters=asof))
# 7. latency: cache
cached = CachedRetriever(
FusedRetriever([DenseRetriever(SAMPLE_CHUNKS),
LexicalRetriever(SAMPLE_CHUNKS)]))
cached.search("vpn error", k=5)
cached.search("vpn error", k=5)
print(f"\n== cache ==\n hits={cached.hits} misses={cached.misses}")
# 8. structured alongside unstructured
_show("table retriever q='globex vpn seats order'",
registry["table"].search("globex vpn seats order status", k=5))
docs_plus_table = FusedRetriever(
[DenseRetriever(SAMPLE_CHUNKS), LexicalRetriever(SAMPLE_CHUNKS),
registry["table"]])
mix_hits = docs_plus_table.search("globex vpn seats order status", k=8)
_show("docs+table fused q='globex vpn seats order status'", mix_hits)
print(f" source_mix={source_mix(mix_hits)}")
print(f" top hit stage_sources="
f"{(mix_hits[0].metadata or {}).get('stage_sources') if mix_hits else None}")
# 9. adaptive k
pool = registry["lexical"].search(
"expense per diem reimbursement policy", k=30)
kept, report = adaptive_select(pool, max_k=8, token_budget=500)
print(f"\n== adaptive k ==\n report={report}")
for h in kept:
print(f" {h.id:<14} {h.text[:70]}")
# 9b. the floor that fakes abstention (§2.3): an absurdly high
# min_score — stands in for a floor tuned on the wrong score scale —
# empties the result set; min_hits rescues flagged weak evidence
_, report_empty = adaptive_select(pool, max_k=8, min_score=10_000)
print(f"\n== floor=10000 (wrong scale) ==\n report={report_empty}")
rescued, report_rescue = adaptive_select(
pool, max_k=8, min_score=10_000, min_hits=2)
print(f" + min_hits=2 -> {report_rescue}")
for h in rescued:
print(f" {h.id:<14} below_floor="
f"{(h.metadata or {}).get('below_score_floor')} {h.text[:60]}")
# 10. parent expansion
expanded = expand_to_parents(
registry["lexical"].search("vacation accrual sick leave", k=4), PARENTS)
_show("parent expansion q='leave policy'", expanded)
if __name__ == "__main__":
main()Note what the demo deliberately does not show: provider calls. Every complete is a KeywordLLM fake; every retriever is in-memory. To run the same file against real models, swap KeywordLLM for an adapter built on 03.4's structured output and the in-memory retrievers for your Module 06 stack — the wrappers don't change.
Failure gallery#
The ways this lesson's strategies fail — each row names the trace signal that gives it away and the section that fixes it:
| Failure | What you see (trace signal) | Root cause | Fix — where |
|---|---|---|---|
| Retrieving too much | Input-token cost and latency climb; answers get vaguer; dropped_budget is high in the shaping report |
Fixed large k sent straight to the prompt — no pool-then-trim |
pool_k + token_budget + adaptive k (2.1–2.4) |
| Near-duplicates flooding | Top-k is five copies of one chunk; the generator sees "consensus" that isn't | Overlapping chunk windows, re-ingested versions, boilerplate | dedupe_threshold + MMR diversity (2.5) |
| Wrong-language docs | French/other-language hits inside an English answer; the model answers in the wrong language | No lang filter; multilingual embeddings cross languages by design |
lang filter inside retrieval, or per-language routes (3.5, Part 6) |
| Stale versions | The answer quotes the replaced policy ($75 when it's $85) | Both versions retrieved; no freshness constraint | mandatory_filters=freshness_filters(); index-time versioning (Part 7) |
| Missing filter (ACL) | Cross-tenant chunks reach the prompt — or get silently dropped post-hoc | Post-filtering, or mandatory_filters forgotten on one config |
GuardedRetriever + check_tenant_isolation (Part 6) |
| Over-aggressive thresholds | Zero hits on queries that should match — looks exactly like "no coverage", so the system abstains | A score floor tuned on the wrong scale (cosine floor on BM25/RRF scores) | Tune floors on labelled pairs per retriever; alert on zero-result rate; min_hits rescue (2.3) |
| Router confident-empty | A routed query returns [] and nothing downstream looks broken |
Wrong route — an exclusive index choice lost the recall | Keep a broad default route; log router.last_decision; zero-hit fallback (3.3 ⚠️, 3.4) |
| Trigger false-skip | An ungrounded answer that sounds fine on a corpus question | The trigger said retrieve=false on a question that needed documents |
Bias toward retrieving; log every skip; measure skip precision (Part 5) |
| Post-filter ACL leak | Fewer than k results, counts leak, or — worst — forbidden hits in the prompt |
"Retrieve broadly, filter in Python" pattern | Filters inside search(), never after (6.1) |
| Cache-key leak | Tenant A's cached hits served to tenant B | Cache key missing the permission scope | Key includes filters; guard sits outside the cache (8.1, 1.3) |
| SQL-as-evidence | The generator treats a stale or buggy row as authoritative | Rows-as-Hits with dishonest or missing provenance |
Honest source="sql:…", validate values against row metadata (4.3 ⚠️) |
| Expansion blowing the budget | Parent passages are 3–10× the child size — fewer hits fit, or the budget is exceeded | expand_parents runs before the token budget without measuring |
Expand before the budget step; measure both shapes on the eval set (2.6) |
| Timed-out retriever degrading silently | Partial results; last_errors fills up; quality dips without an error |
One retriever times out or crashes mid-query | Per-retriever timeout + last_errors monitoring + alerting (8.1) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Retrieval is just vector search — pick an embedding model and you're done." | Retrieval is a strategy: which retrievers, how deep, what order, what filters, what shaping. The embedding model is one component; the pipeline around it decides quality. |
| "Bigger k is always better for recall." | recall@k rises with k, but the context budget, token cost and "lost in the middle" dilution punish it. The answer can only come from retrieved chunks — but only if they're findable in the noise. |
| "The reranker fixes bad retrieval." | A reranker reorders candidates; it cannot rescue a chunk that never made the candidate set. First-stage recall is the ceiling — rerank for precision, not recall. |
| "Filters can be applied after retrieval." | Post-filtering returns fewer than k results, leaks via counts, and is a security bug for ACLs. Filters go inside retrieval, always. |
| "One index for everything is simpler and therefore better." | Simpler until sources diverge in vocabulary, authority, freshness or permissions. Routing exists because "search everything" drowns the right answer in noise. |
| "Always retrieve — it's safer." | It is safer, but it costs latency and tokens on every chit-chat turn, and irrelevant context can actively hurt answers. A measured trigger beats a blanket rule. |
| "RRF needs calibrated scores to work." | That's its whole point — it fuses ranks, so incomparable score scales are fine. The k=60 constant is the only knob that matters. |
| "Cached retrieval results are always safe." | Only if the cache key includes the permission scope. A key of (query, k) alone leaks across tenants — include filters, always. |
| "Score thresholds transfer between retrievers." | They don't — cosine 0.7 means different things for different models, and RRF scores have yet another scale. Tune floors per retriever, per eval set. |
| "Elbow detection gives you the right k automatically." | It's a heuristic that assumes smooth decay then a cliff. Near-duplicate clusters fake elbows; flat distributions produce none. Validate on labelled data. |
| "Structured data doesn't need retrieval — just query the DB." | Deciding what to query is itself retrieval (planner/tool call). Treating rows as Hits lets them fuse with documents under one contract. |
| "Parent expansion always improves answers." | It trades breadth for depth and can blow the token budget. Right when answers need surrounding context; wrong when chunks are already answer-sized. |
Key takeaways#
- Retrieval is a pipeline, not a component. First-stage retrievers → fusion → reranker → shaping → guards → cache → trigger, each a composable wrapper around the
Retrievercontract. - Choose configurations with evidence. Name each pipeline shape as a
RetrievalConfig, change one stage per experiment, and measure on the 06.10 harness — never ship on intuition. - k is three numbers, not one.
candidate_k(how deep each retriever digs),rerank_depth/pool_k(how many candidates the expensive stages see), and finalk(how many reach the prompt). Over-retrieve, trim late. - Adaptive k beats fixed k when tuned. Score floors need per-retriever calibration; elbows are heuristics; reranker cut-offs are the most threshold-friendly. Always validate on labelled data.
- Shape before you send. Dedup near-duplicates, apply MMR for diversity, merge adjacent chunks, expand to parents, and trim to a token budget — all cheap pure-Python wins.
- Multi-index needs routing, not just more indexes. An LLM classifier with a heuristic fallback picks the index; federated fan-out with RRF is the alternative when sources overlap.
- Structured data is a retriever too. Tables and APIs return
Hits; they fuse with documents under the same contract. Text-to-SQL is a retrieval tool, not a separate pipeline. - Triggers save money but can cost correctness. Bias toward retrieving; a false skip produces ungrounded answers that sound fine.
- ACL is a wrapper, not a filter. Mandatory filters merge over caller filters and sit outside the cache — the tenant comes from the session, never the query, and the LLM is never the security boundary.
- Freshness is metadata plus query-time filters.
latest_onlyfor current answers,as_offor historical ones — and the durable fix is index-time version management, not query-time heroics. - Latency is a budget, not a mystery. Parallel fan-out, per-retriever timeouts, hot-query caching with scope-safe keys, early termination, and approximate index settings — measure p50 and p99.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| retrieval configuration | A named, versioned pipeline shape (RetrievalConfig) — first stages, depths, reranker, shaping, guards, cache, trigger |
candidate depth (candidate_k) |
How many results each first-stage retriever returns before fusion |
rerank depth (rerank_depth) |
How many fused candidates the reranker scores (the "N" from 06.9) |
pool depth (pool_k) |
How many hits the shaping stage sees before trimming to k |
| over-retrieval | Fetching more candidates than you'll keep, then trimming — cheap recall insurance |
| score floor | A minimum effective_score for a hit to survive shaping |
| effective score | The reranker's score when present, else the retriever's own — the score shaping decisions use |
| elbow cutoff | Adaptive-k heuristic: cut the ranked list at the largest gap between consecutive scores |
| token-budgeted selection | Keeping hits in rank order until the next would exceed a token budget |
| overlap coefficient | |A∩B| / min(|A|,|B|) on token sets — the near-duplicate similarity used by dedupe_hits |
| MMR (Maximal Marginal Relevance) | Greedy selection trading relevance against novelty to reduce redundancy (Carbonell & Goldstein, 1998) |
| small-to-big / parent expansion | Retrieving small embedded children but returning their parent passages to the generator |
| multi-index routing | Choosing which index(es) a query searches via a classifier + heuristic fallback |
| route decision | The router's output: which route, confidence, reason — logged for traces |
| federated retrieval | Querying all indexes and fusing results, as opposed to routing to one |
| route filters | Constraints a route implies (e.g. doc_id=handbook), applied inside retrieval |
| retrieval trigger | The retrieve-or-skip decision made before search runs |
| mandatory filters | Filters (ACL, freshness) merged over caller filters by GuardedRetriever — cannot be widened |
| as-of query | A query resolved against the document version live on a given date |
| freshness filters | latest_only / as_of filter dicts built by freshness_filters() |
| tenant isolation test | Mechanical check that no hit escapes its permission scope, including adversarial queries |
| exact-match cache | CachedRetriever: memoises (query, k, filters) → hits with TTL; filters carry the ACL scope |
| early termination / shortcut retrieval | Trying retrievers in priority order and stopping at the first "good enough" result |
| graceful degradation | Returning partial results when a retriever fails or times out, instead of failing the query |
| source mix | Stage-contribution counts by provenance (source_mix) — the trace signal for document-vs-structured reliance |
stage sources (stage_sources) |
The per-stage provenance list rrf_fuse records on fused hits — the unit source_mix counts |
score-floor rescue (min_hits, below_score_floor) |
Keeping the best below-floor hits flagged in metadata, so an over-aggressive floor degrades to weak evidence instead of a silent empty result |
| table retriever | A Retriever that returns database rows as Hits, enabling SQL+docs fusion |
Exercises#
-
Run the demo and read the traces.
uv run python -m docs_qa.retrieval. For each section, predict the top hit before running it, then checksource,scoreandroute/last_decisionfields. Which queries route wrong? Why? -
Build a real ablation. Using the 06.10 harness (
eval_queries.jsonl+harness.py), evaluatedense,hybrid, andhybrid+rerankon your own labelled set of 30+ queries spanning the corpus types. Report recall@5, MRR, nDCG@10, and p50 latency for each — one stage changed per run. -
Tune the rerank depth. Sweep
rerank_depth∈ {10, 20, 50, 100} on the same eval set. Plot quality vs latency. Where's the knee? Doespool_kneed to matchrerank_depth? -
Write the tenant-isolation pytest. Turn
check_tenant_isolationinto a real test file with parametrised tenants and probe queries. Add a probe that explicitly asks for another tenant's data — verify the mandatory filter wins. -
As-of archaeology. Extend the corpus with a third version of the per-diem policy (say, $90 effective 2026-01-01). Verify
as_of="2025-06-01"still returns $85 andas_of="2024-06-01"returns $75. What happens if you forgetsuperseded_dateon one version? -
Trigger precision. Build a labelled set of 20 queries (10 needing retrieval, 10 not). Run the
Triggerheuristic on all of them. What's the skip precision? Where does it fail? Now wire aKeywordLLMfake with better coverage — does precision improve without hurting recall? -
Latency budget. Time
FusedRetriever.search(sync) vsFusedRetriever.asearch(async) on the sample corpus over 100 queries. Is the difference measurable at this scale? At what corpus size would it matter? -
Extend the table retriever. Write a
plannerthat extractscustomer=Xandstatus=Yfrom queries like "show globex billed orders". Fuse its output with document hits viarrf_fuseand checksource_mixon the result.
Check yourself#
- Why does
GuardedRetrieversit outsideCachedRetrieverin the wrapper order?So the cache key always includes the merged mandatory filters. If the cache were outside the guard, two tenants asking the same query with the same caller filters would produce the same cache key and leak results across permission boundaries. - What are the three "depth" knobs and what does each control?
candidate_k— how deep each first-stage retriever looks before fusion.rerank_depth/pool_k— how many fused candidates the expensive stages (reranker, shaper) see. Finalk— how many hits survive to the prompt. Over-retrieve early, trim late. - Why can't you compare
hit.scoreacross two different retrievers?Scores are retriever-specific: cosine similarity, BM25, and RRF fused scores live on different scales. A 0.7 cosine means something different than a 0.7 RRF score. Only rank order is meaningful within one retriever's output. - What's the difference between deduplication and MMR?Dedup removes copies — chunks sharing most of their words (overlap coefficient ≥ threshold). MMR removes redundancy — chunks that are worded differently but convey the same information, by trading relevance against novelty during selection.
- When should you route queries to different indexes instead of searching one fused index?When sources are distinguishable — different vocabularies, document types, tenants, languages, or freshness rhythms — and a wrong-source result would be noise. Routing pays off when the classifier can reliably tell which index holds the answer; fused fan-out is better when sources genuinely overlap.
- Why is a post-filter a security bug, not just an inefficiency?It can return fewer than k results, leaks information through counts/facets, and any bug in the post-filter path exposes data. ACL filters must be applied inside retrieval before scoring — the permission boundary is code, not a Python
ifafter the fact. - What's the difference between
latest_onlyandas_offreshness filters?latest_onlykeeps only unsuperseded chunks — the default "current policy" case.as_of=datekeeps the version that was live on that date:effective_date ≤ dateAND (superseded_date > dateOR never superseded). The first answers "what is the policy?", the second answers "what was the policy then?". - Why does
TriggeredRetrieverreturn an empty list on skip instead of raising?Because a skip is a legitimate outcome, not an error: the pipeline carries on as a normal turn with no context. The cost is that downstream code cannot tell "no matches" from "not searched" by looking at the list, which is exactly whytrigger.last_decisionmust be logged in the trace — the empty list carries no reason, the trace does. - What does
source_mixtell you and why does it matter?It counts stage contributions by provenance: an unfused hit counts once under itssource, and a fused hit counts once under each stage inmetadata["stage_sources"](for exampledense,lexical,sql:orders), so a chunk that both retrievers found counts twice. A mix heavy onsql:sources means the evidence leaned on structured data; heavy ondense/lexicalmeans it leaned on text. It's the trace signal for "did retrieval find the right kind of evidence?" - When does early termination (
ShortcutRetriever) help, and when does it hurt?It helps when a cheap retriever answers most queries confidently — you save the expensive one's latency. It hurts when the early retriever returns "good enough" results that miss what a later retriever would have found. Tunemin_hits/min_scoreon your eval set; it's a recall-for-latency trade. - Why must the cache key include
filters?Because filters carry the ACL/tenant scope. Two users asking the same query with different permission scopes must not share a cached result — the key(query, k, filters)ensures each scope gets its own cache entry. - What's the "ablation trap" and how do you avoid it?Changing two pipeline stages at once makes it impossible to attribute the quality change. Change one stage per experiment, log the config name and eval-set version, and keep the test split untouched until the end.
- A
min_scorefloor returns zero hits on every query after a retriever swap — why is that worse than it looks, and what's the fix?Empty results are indistinguishable from "the corpus doesn't cover this" — the abstention path treats it as a legitimate non-answer, so a threshold tuned on the wrong score scale silently converts into confident "I don't know" replies. Fix: tune the floor on labelled pairs per retriever and score scale (06.3 §3.3), alert on the zero-result rate, and usemin_hits/below_score_floorto keep flagged weak evidence instead of silence. - Why can an English query retrieve the French help article, and which layer fixes it?Dense retrievers rank by embedding similarity, which doesn't respect language boundaries — multilingual models match concepts across languages by design, and shared tokens leak through lexical search too. The fix is a
langmetadata filter applied inside retrieval (or per-language routes). Wrong-language queries — a French question against an English corpus — are 07.3's problem, not a filter's.
Further resources#
- Lewis et al., 2020 — Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — the paper that named the pattern
- Cormack, Clarke & Büttcher, 2009 — Reciprocal Rank Fusion — the fusion algorithm (06.8 owns the deep dive)
- Carbonell & Goldstein, 1998 — The Use of MMR, Diversity-Based Reranking — the diversity algorithm (06.3 Part 5 owns the vector version)
- Manning, Raghavan & Schütze — Introduction to Information Retrieval — the BM25 and evaluation foundations
- 06.10: Evaluating and Tuning Retrieval — the harness this lesson's configs plug into
- 06.8: Hybrid Search — fusion algorithms in depth
- 06.9: Reranking — the second stage this lesson composes
- 06.6: Metadata Filtering and Multi-Tenancy — ACL and time-aware search mechanics
- 04.6: Context Selection and Ordering — what happens to retrieved chunks downstream
- 05.7: Advanced and Document-Specific Chunking — parent-child structures at index time
- 07.3: Query Understanding, Rewriting and Expansion — what happens to the query before it reaches this retriever
- 07.4: Grounded Generation — what happens to the hits after retrieval
- 07.8: Advanced RAG Patterns — agentic retrieval preview
- 07.9: Evaluating RAG — end-to-end evaluation that includes retrieval quality
- Module 08A: Agent Foundations — tool-based retrieval and text-to-SQL
- Module 11B: Cost, Usage and Token Management (caching), Module 11A: Observability and AgentOps (monitoring) and Module 11C: Deployment, Reliability and Model Lifecycle (degradation at scale)
- Module 12: Safety and Security — the full ACL and injection treatment
← 07.1 — RAG Architecture: From Question to Grounded Answer | Module 07 overview | 07.3 — Query Understanding, Rewriting and Expansion →