6.2 Hybrid Retrieval, Reranking & Context Assembly
Key Takeaways
Hybrid dense and lexical retrieval can address both semantic paraphrases and identifiers; RRF combines ranks rather than incomparable raw scores.
Enforce verified access and lifecycle constraints before unauthorized evidence can enter the model. Searching within the eligible corpus can improve recall under selective filters.
Retrieve a measured candidate set and optionally rerank it, balancing recall, evidence quality, latency and context cost.
Choose full-corpus input, prebuilt RAG, or bounded on-demand retrieval based on corpus size/freshness, authorization, query complexity and SLA. Preserve parent context and source evidence.
6.2 Hybrid Retrieval, Reranking & Context Assembly
Core Principle: Production RAG is a precision funnel, not a dump truck. Large unfiltered retrieval sets can add latency, cost and distraction. Test a smaller reranked evidence set alongside the recall needed to answer the question.
Why Dense Vector Search Alone Fails in Enterprise
Bi-encoder embedding models project text into fixed-width dense vectors (with dimension determined by the embedding model). They excel at conceptual synonyms—matching "employee departure checklist" to "offboarding workflow"—but may miss exact lexical matches that enterprise workflows depend on:
- Identifiers & Codes: Part numbers (
AX-9042-REV3), error codes (ERR_KMS_0x4F), and policy IDs (HR-402). - Domain Acronyms & Rare Terms:
NSMIA,HIPAA BAA, or internal project codenames absent from public pre-training corpora. - Negations & Exact Numbers: Distinguishing
Section 4.1fromSection 4.10or $5,000 from $50,000.
Hybrid Search & Fusion Mechanics
Enterprise pipelines execute dense ANN vector search (such as HNSW) in parallel with sparse lexical search (BM25) over inverted term indices, then merge the two ranked lists:
| Fusion Method | How It Works | Enterprise Trade-Off |
|---|---|---|
| Reciprocal Rank Fusion (RRF) | Sums rank reciprocals: 1 / (k + rank_dense) + 1 / (k + rank_bm25) (typically k = 60) | Does not require comparable raw score scales; rank-fusion settings still need evaluation |
| Weighted Linear (Alpha) | Normalizes scores and computes alpha * dense + (1 - alpha) * bm25 | Supports query-router tuning (e.g., alpha = 0.25 for exact SKU lookups), but sensitive to score outliers |
Because BM25 scores can range from 3.1 to 42.8 while cosine similarity clusters tightly between 0.72 and 0.89, RRF is a useful baseline for merging ranks without normalizing scores. The common RRF constant 60 is different from retrieval top-k. For instance, rank 1 in dense and rank 4 in lexical contributes 1/61 + 1/64 ≈ 0.03202, whereas a candidate at rank 2 in only one list contributes 1/62 ≈ 0.01613. Missing-list contribution is zero. Test retrieval quality rather than treating the constant as universal.
Pre-Filtering vs. Post-Filtering for ACLs & Metadata
Enforcing document-level Access Control Lists (ACLs), tenant_id, is_deleted = false, and effective_date at the wrong stage breaks both recall and security:
- Why Post-Filtering Fails: Suppose an analyst queries "Q4 restructuring severance terms" across an enterprise index. If the top 10 global vector matches all belong to executive-only compensation folders, post-filtering after
top_k = 10discards all 10 results and returns zero documents—even though 40 authorized HR handbook chunks existed at ranks 14 through 60. Increasingtop_kto 500 in application memory wastes network I/O, may still miss highly selective authorized subsets, and risks leaking unauthorized snippets into debug logs or telemetry. - Scope before retrieval: Apply
acl_principals,tenant_id, and lifecycle predicates before candidate selection where supported, or search a verified authorized partition. The access boundary must be enforced before unauthorized content reaches model or untrusted consumers, independent of the index implementation. - Low-Selectivity HNSW Caveat: Highly selective filtering may increase traversal cost or reduce recall depending on the engine. Evaluate the actual engine’s prefilter semantics and exact-search option or a tenant-scoped index if necessary. Never relax authorization to improve recall.
- Trusted Claim Origin: Always extract user ACL principals from authenticated identity and trusted server-side authorization policy—never trust group names supplied in user prompts or tool inputs.
Exam Trap: Raising
top_kfrom 10 to 100 in a post-filtered pipeline is only a temporary band-aid. If a multi-tenant index holds 500 tenants and one small tenant owns 0.2% of chunks, eventop_k = 200on a generic query like "security audit policy" can return zero authorized results—making search within the authorized candidate set preferable. Post-filtering entirely within a trusted security boundary may protect confidentiality, but it can still have poor recall.
Cross-Encoder Reranking & Context Assembly
Bi-encoders embed the query and document independently for efficient similarity search; a separate cross-encoder can jointly assess query and candidate text. A two-stage retrieve-then-rerank architecture pairs fast Stage 1 recall with deep Stage 2 precision:
The following illustrative targets are candidates to measure, not intrinsic model or platform performance.
| Pipeline Stage | Example Candidate Count | Example Latency Budget (p95) | Primary Objective |
|---|---|---|---|
| Stage 1: Pre-Filtered Hybrid (Dense + BM25 + RRF) | 50–100 chunks | 20–45 ms | Maximize recall across semantic paraphrases and exact IDs within ACL scope |
| Stage 2: Cross-Encoder Reranker | 5–8 chunks | 80–150 ms | Jointly score (query, chunk) pairs and use a threshold calibrated for that reranker |
| Stage 3: Context Assembly & Claude Generation | 12K–20K tokens | 600–1,800 ms TTFT | Expand parent sections, deduplicate, order edges, and ground citations |
Query Routing & Safe Expansion Guardrails
For complex queries spanning multiple sub-topics ("Compare EU vs. US retention limits in HR-402"), lightweight query decomposition splits the question into two parallel hybrid searches before RRF and reranking. Avoid unconstrained LLM query rewriting on exact identifiers—if a model paraphrases ERR_KMS_0x4F into generic prose, BM25 loses the exact match. Preserve raw user tokens alongside any expanded synonyms.
Small-to-Big Retrieval, Deduplication & Token Budgets
Assembling the final prompt for Claude requires four disciplined steps:
- Parent-Document (Small-to-Big) Retrieval: Index fine-grained 200–300 token child chunks for fine-grained matching, then optionally expand a selected child to its verified, authorized enclosing section (e.g., 800–1,200 tokens) (with full caveats and headers) before sending to Claude.
- Near-Duplicate Deduplication: Merge duplicated overlapping passages using identifiers and source spans, or validated similarity criteria so duplicate boilerplate does not crowd out distinct evidence. Do not discard near-duplicate text that contains different dates, limits or exceptions.
- Lost-in-the-Middle Ordering: Long-context recall can degrade and evidence placement may matter; test ordering on the deployed model. Try placing important evidence prominently of the retrieved evidence section (or apply explicit XML document indices).
- Strict RAG Token Budgeting: Within a hypothetical 200K-token model window, budget explicitly—for instance:
4,000tokens for system instructions and tool schemas,10,000tokens for conversation state,12,000–20,000tokens capped for 5–8 parent chunks, and4,096tokens for output headroom. The listed budgets sum to 30,096–38,096 tokens including reserved output, leaving other limits to check. At an illustrative uncached input price of $2 per million tokens, reducing retrieval context from 70,000 to 15,000 tokens saves 55,000 × 2/1,000,000 = $0.11 per request on that input component. Reranking has its own cost and latency; measure the net result and ensure required caveats remain.
Choosing the retrieval architecture and fallback
A fixed RAG index is not always appropriate. Compare three designs using the actual corpus and query distribution:
| Design | Strong candidate when | Trade-off |
|---|---|---|
| Full-corpus prompt | A small, stable and fully authorized reference collection fits the available context and output budget | Simpler than index maintenance; every request processes a large prefix unless eligible caching works; recall still needs testing |
| Prebuilt RAG | Many queries target a larger corpus, and a maintained index can retrieve a small evidence set quickly | Index freshness, chunking and retrieval quality become operational responsibilities |
| Bounded agentic search | Information needs change during a complex research task or require current lookup from supported authorized sources | Additional search and model turns add variable latency and cost; require tool scope, budgets, evidence and abstention rules |
For example, a small static handbook may fit in the context and be cheaper to maintain as one authorized cacheable reference. A million-document support library with predictable queries is usually a better candidate for indexed retrieval. A multi-source research brief where later questions depend on earlier results may justify bounded on-demand lookups. A hybrid can use the indexed evidence first and invoke a permitted fresh source only when the required fact is absent. If the latency budget is binding and recall tests already pass, avoid an extra reranker or search turn. If recall is failing because exact identifiers are missed, introduce lexical retrieval rather than raising the model tier. If all eligible evidence is insufficient, abstain or route to review; never broaden the caller’s authorization to recover recall.
Primary references
Field technicians search an internal repair knowledge base for exact part codes like 'TX-9902B' and firmware alerts like 'ERR_BUS_0x19'. Under pure dense vector search, the top results are general troubleshooting guides that omit the exact part number. Which retrieval change directly resolves this failure?
Switch from cosine similarity to Euclidean distance on the existing dense embeddings
Increase the chunk size from 512 tokens to 4,096 tokens so rare part codes appear more frequently per chunk
Combine dense vector search with sparse BM25 lexical search over inverted term indices and merge rankings with Reciprocal Rank Fusion (RRF)
Ask Claude to expand all part numbers into natural-language descriptions before running dense vector search
A junior HR specialist asks an enterprise RAG assistant about bereavement leave policies and receives 'No matching documents found,' even though 18 general employee handbook pages cover bereavement leave. Logs show the top-10 global vector matches belonged to restricted executive M&A separation agreements that were stripped by application-level post-filtering. What architectural change fixes both recall and security?
Enforce server-verified ACL and tenant predicates via pre-filtering inside the search engine prior to top-k ranking
Pass the user's department name inside the Claude system prompt and instruct Claude to ignore restricted executive documents after retrieval
Disable ACL filtering for bereavement queries because the keyword appears harmless
Keep post-filtering at top-10 and retry with random query paraphrasing when zero documents remain
An engineering team passes all 60 retrieved hybrid chunks (~55,000 tokens) directly to Claude Sonnet for every customer support query. P95 latency exceeds 9 seconds, monthly inference costs jumped from $4,000 to $29,000, and answer accuracy drops whenever key facts sit in chunks 25–40. Which optimization is the best candidate to test against the cost, latency, and recall requirements?
Switch to a smaller embedding dimension at Stage 1 while continuing to send all 60 raw chunks to Claude
Cache the full 60-chunk prompt globally across all users regardless of query differences
Double the Stage 1 retrieval limit to 120 chunks and sort them alphabetically by source_uri
Rerank the authorized candidates, deduplicate without losing material differences, and assemble a measured number of passages within a context budget.
In a legal contract review pipeline, indexing 220-token child chunks yields excellent search precision for clauses like 'indemnification cap,' but Claude frequently misses a cross-referenced carve-out located in the subsequent subsection of the same clause. Which context assembly pattern preserves sharp matching without losing surrounding caveats?
Replace child chunks with 3,000-token chunks at embedding time
Use small-to-big (parent-document) retrieval: index 220-token child chunks for search, then substitute their enclosing 900-token parent section during context assembly
Run BM25 only without dense embeddings so longer subsections rank higher
Instruct Claude to guess standard commercial indemnification carve-outs whenever a clause ends abruptly
A company has a small static policy corpus of 18,000 tokens, entirely authorized for the requesting group. Its measured full-corpus prompt meets accuracy, latency and cost requirements with a reusable prefix. Which conclusion is most appropriate?
Build a multi-step agentic search loop for every query because indexed retrieval is mandatory
Keep the simpler measured full-corpus design, monitor its quality and costs, and revisit retrieval if size, freshness or latency requirements change
Truncate the policy collection to 1,000 tokens regardless of evidence loss
Move all requests to asynchronous batches even when immediate responses are needed
Sections you finish are checked off in the contents.