Retrieval and Grounded Generation
Retrieval only helps when evidence identity, permissions, freshness and answer attribution survive every pipeline stage. This stage builds a controlled system where relevance, citation, abstention and leakage can be measured separately.
Section 3 of 8 · 11 units · about 51 hours
By the end you can On a versioned two-tenant corpus, prove permission-safe sparse, dense and hybrid retrieval; measured reranking; grounded citations; abstention; update and deletion behavior; and stagewise failure attribution under poisoned and stale content.
Units
- A no-retrieval baseline, and corpus, document, version and chunk identities4h
- Parsing with layout and metadata, chunking policy and source lineage5h
- Embedding contracts, and sparse and dense retrieval at matched candidate budgets5h
- Hybrid fusion, and query rewriting with its failure amplification4h
- Tenant and user filters before context assembly, and cross-tenant leak tests5h
- Cross-encoder reranking and evidence assembly under token budgets5h
- Claim-to-chunk citations and grounded generation contracts4h
- Unanswerable detection, abstention and calibrated fallback4h
- Freshness, deletion propagation, index versions and cache keys5h
- Retrieval, citation and groundedness metrics5h
- Stagewise failure attribution, and poisoned or injected documents5h
Build it
Mini project · about 16 to 20 hours
Permissioned retrieval with verifiable evidence and safe abstention
Extend agentlab with corpus/ and retrieval/ for its bounded workflow, preserving the gateway, context compiler and evaluator. Separate ranking relevance from authorized evidence, supported claims and current correctness. Use the section's pinned Python libraries on your machine, with deterministic fakes or a small open model behind your local OpenAI-compatible server and no paid APIs.
- 1Version the controlled two-tenant corpus, acquisition limits, parser and document/chunk lineage. Check layout and exact span resolution against fixtures; retain reingestion, truncation, duplicate/orphan and fixed-size versus structure-aware boundary tests. Before model runs, check hand-derived ranking and ALCE support fixtures against ir-measures and ALCE Figure 3.
- 2Enforce tenant/user ACLs before sparse, dense, hybrid and reranking exposure, then recheck context, citations, answer reuse and traces. Compare every sink with independently authorized sets and synthetic canaries; retain forged-scope, colliding-identity, missing-policy and in-flight revocation-barrier regressions before generation.
- 3Publish coherent corpus/index snapshots with current tombstones and policy epochs. Check paused readers, concurrent publication, stale answer reuse, orphan detection and rollback against an independent event ledger; retain update acceptance, publication and served-result times, distinguishing serving denial from physical erasure.
- 4Reject encoder-contract mismatches; independently check BM25 and RRF, including duplicates, absent IDs and empty runs. Compare matched-depth BM25, exact dense, hybrid and fixed-candidate reranking against SciFact qrels with ir-measures; retain rankings, candidate-union work, latency/memory and paired uncertainty. Optionally test negation/entity/date rewrite drift.
- 5Assemble authorized evidence under complete rendered-token budgets; check omission, deduplication and fixed-evidence position sweeps against support manifests. Validate claim-to-versioned-span pointers and policy independently from hand-labeled support; retain fabricated, stale and unsupported citation regressions, ALCE precision/recall, atomic-claim coverage and answer correctness separately.
- 6Compare no-retrieval, retrieved and oracle-evidence answers with fixed items, grader and generation budgets across repeated trials. Check paired answerable/near-miss fixtures and deterministic empty-evidence/dependency-failure handling; retain development-only threshold sweeps and held-out coverage, selective risk, over-refusal, denominators, tokens, latency and failures, marking fake-only quality unmeasured.
- 7Inject parser, index, packing, citation, timeout and grading faults; check first-failed-stage classifications using oracle-stage replays. Retain clean/poisoned pairs, attacker scope, isolated mock-action denials and hand-label judge audits with order/style controls; report retrieved exposure, packed exposure, factual corruption and instruction obedience separately, preserving regressions and uncertainty.
What you hand in
- Versioned
corpus/andretrieval/with permissioned ingestion, snapshot publication, retrieval variants, citations, abstention and regression tests. - SciFact rankings and controlled-corpus judgments with oracle-checked metrics, stage traces and complete paired trial artifacts.
- Rebuildable
reports/covering relevance, support, correctness, permissions, freshness, costs, attacks, attribution and a justified retrieval decision.
How to check it
- Self-grade with the rubric below
- BEIR SciFact relevance judgments
Use the section's SciFact protocol and original document identities; relevance judgments do not establish permissions, answerability or generated-answer correctness.
- ir-measures ranking metric oracle
Use the pinned package and declared gain/provider conventions; verify hand fixtures, duplicate policies, empty runs and complete query denominators.
- ALCE Figure 3 citation support fixtures
Check joint, individual and leave-one-out support arithmetic with hand labels; report deviations from the paper's citation policy without claiming benchmark replication.
How it's graded
Identity and authorized freshness
Pass: Your original-source span tests validate lineage and boundaries. Independent authorized-set and event-ledger checks reject denied evidence across sinks, stale readers, answer reuse, concurrent publication and rollback under declared revocation/deletion barriers.
Great: Planted parse, orphan, mixed-snapshot and cross-tenant defects fail before generation; update visibility is measured separately from publication, and serving denial is never presented as physical erasure.
Ranking and answer evidence
Pass: Your hand fixtures match ir-measures and ALCE conventions. Paired SciFact and controlled-corpus reports retain all-item denominators, resource costs, uncertainty, citation-support labels, answer correctness and held-out abstention errors without requiring a variant win.
Great: Candidate recall, packed support and generated correctness remain distinct; no-retrieval and oracle controls bound the retrieval claim, and unsupported but resolvable pointers cannot count as grounded answers.
Fault attribution and replay
Pass: Your stage oracles localize planted faults with controlled substitutions. Clean/poisoned pairs and judge audits preserve exposure, corruption and blocked-action evidence separately; raw records regenerate reports with fake-only limits and failed trials visible.
Great: A clean corpus rebuild reproduces identity-linked results and the retrieval decision; negative regimes, multiple contributors and judge blind spots remain explicit, with each diagnosed fault linked to a regression.
Resources
- AI Engineering Handbook - RetrievalHandbook Academy
Complete Part 6 Retrieval: parsing and chunking, embeddings and vector search, hybrid search and reranking, query understanding, citations, advanced retrieval, retrieval evaluation and production RAG. Implement each stage on one controlled corpus before adding abstractions.
- AI Agents in Depth - Knowledge BaseBojie Li
Read Chapter 3 sections 3.2.1 to 3.2.4 (chunking, dense, sparse and hybrid retrieval), 3.3.1, 3.3.3 (incremental updates, retiring obsolete content, multi-user permissions and tenant isolation), 3.3.4 (agentic retrieval and the security boundaries of RAG) and 3.3.5 contextual retrieval. Keep 3.1 memory for AI-5. The companion
chapter3/retrieval-pipeline/evaluate.py --no-dense --no-rerankruns offline. - Evidence-Grounded Retrieval SystemRoadmap-Final
Build the bounded slice first: Milestone A (no-retrieval and oracle-evidence baselines), the architecture constraint that authorization filters apply before exposure and are rechecked before context, citation and cache reuse, and Milestones D and E. Use a small hand-written two-tenant corpus with stable source, version and chunk IDs, deleted and conflicting facts, near-miss unanswerables and poisoned documents. The full project (80 to 130 hours) continues in AI-8.
- Sentence Transformers Retrieve and Re-RankSentence Transformers
Implement the documented bi-encoder retrieval plus cross-encoder reranking pattern on SciFact or your own corpus. Reranking only reorders the candidates, so measure recall before it and ranking quality, latency and cost after it. The MiniLM cross-encoder outputs raw logits, not 0 to 1 probabilities. Pin model revisions.
- The Probabilistic Relevance Framework: BM25 and BeyondStephen Robertson and Hugo Zaragoza
Read Sections 3.4.4 to 3.5 (term-frequency saturation, length normalization
(1 - b) + b * dl / avdl, variants). Library BM25 implementations differ in IDF handling, so record k1, b, tokenization and the implementation with every result. - Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning MethodsCormack, Clarke and Buettcher
Read the Section 1 equation: score each document by the sum of
1 / (k + rank)over the rankings, with ranks from 1 and k = 60 fixed in a pilot. Fusion cannot recover a document missing from every candidate list; record candidate depths and tie handling. - ir-measures: Measure Definitionsir-measures
Read the R, P, RR and nDCG entries and use the library as an oracle for your own metric code. Default nDCG uses linear gain with a
log2(rank + 1)discount, not2**rel - 1; precision@k divides by k. State the query set, unjudged-document handling and averaging. - Enabling Large Language Models to Generate Text with Citations (ALCE)Gao et al.
Read Section 3.3 Citation Quality with the Figure 3 examples and the Appendix E limitation. Citation recall is statement-support coverage and citation precision uses a leave-one-out rule; implement both with stable claim and chunk IDs and a hand-labeled entailment check instead of the 11B scorer.
- Know What You Don't Know: Unanswerable Questions for SQuADRajpurkar, Jia and Liang
Read Section 2 (plausible, relevant negatives) and the threshold paragraph in Section 5.1 (tuned on development data). Build answerable and unanswerable pairs from your corpus and report coverage, risk on answered items and errors on unanswerable items separately.
- Lost in the Middle: How Language Models Use Long ContextsLiu et al.
Read Section 2.1, Table 1 (closed-book and oracle controls) and Figure 11 (retriever recall versus answer accuracy). Run an evidence-position sweep with the query, distractors, model and token budget fixed.
- Not What You've Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt InjectionGreshake et al.
Read Sections 3.1 (injection delivery), 4.1.1 (the synthetic setup) and 5.2 (limits). Add a local document that carries an instruction beside benign facts, mock every tool, and test instruction-following separately from retrieval. Permission filters do not stop an authorized document from injecting.
- AlgoMaster - Evaluating RAG SystemsAlgoMaster
The owned premium lesson is a short pass on retrieval and generation metrics, fixed evaluation sets, automated judges and regression workflows. Recompute every metric it uses in your own harness and keep item-level evidence.
- The Hitchhiker's Guide to Agentic AI - Chapter 16Haggai Roitman
Use v3 Chapter 16 selectively: 16.3 (BM25, DPR, RRF), 16.4 chunking, 16.7 agentic RAG, 16.8 metrics and failure modes, 16.9.4 incremental indexing. Its Equation 16.28 divides context precision by K where the Ragas docs divide by the relevant items, and its
upsert_documentlisting deletes before adding with no transaction, so a query in between sees neither version: test that gap. - Ragas Metrics: Faithfulness, Context Precision and Context RecallRagas
Read the faithfulness, context precision (an AP-like quantity, not precision@K) and context recall pages and the local-model adapter guide. The legacy API was removed in 1.0, so pin a version. Calibrate any LLM-based metric against your hand labels before trusting it.
- FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text GenerationMin et al.
Read the Section 3.1 definition and Figure 1. FActScore is precision conditional on responding, so report it with the response rate; a system can raise it by saying less.
- Poisoning Retrieval Corpora by Injecting Adversarial PassagesZhong et al.
Read Section 3 (threat model) and Section 4.1 with Figure 2: success means one adversarial passage reaches the top k, and attacks transfer poorly across retrievers. Measure poison exposure at k separately from answer corruption.
- PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language ModelsZou et al.
Read Section 3.1 (attacker capabilities) and the retrieval and effectiveness conditions in Section 4.1, then Tables 2 and 4 (v1 numbering). Its attack success rate is target-substring matching, so check matches by hand.
- Contextual RetrievalAnthropic
Read "Introducing Contextual Retrieval", "Methodology" and the reranking section. The reported 5.7% to 2.9% retrieval failure is a 49% relative reduction in 1 - recall@20, not 49 points. Test one context-prefix ablation only after plain BM25, dense and hybrid retrieval pass, and keep the source text apart from generated context.
- Enterprise RAG and Perplexity AI Search Case StudiesEngineering Handbook
Read the Enterprise RAG case study as the main architecture review and compare it with the Perplexity AI Search case. Identify where tenant policy, freshness, citation, latency and evaluation belong, then defend what your bounded project deliberately omits.
- BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval ModelsBEIR Team
Read Section 3 and Table 1 (SciFact: 5,183 documents, 300 test queries) and the qrels workflow in the repository README, then run one small dataset as a relevance oracle. Dataset terms differ from the code license (SciFact annotations are CC BY 4.0, abstracts ODC-By). Full benchmark reproduction stays depth.