← Back to Thinking

RAG Is an Architecture, Not a Recipe

Why enterprise retrieval stalls, and the system design that moves it

RAG Is an Architecture, Not a Recipe

The plateau is a retrieval problem wearing a generation costume

Most enterprise RAG systems reach usable accuracy in a few weeks and then stop improving. The team responds by tuning prompts, swapping models, and raising the temperature of the debate. The remaining failures are usually retrieval failures, and no prompt recovers a passage that was never fetched.

The plateau arrives late because demo corpora are small and topically separated. Production corpora are large and adversarially similar: forty policy documents differing in one effective date, a thousand clinical notes sharing vocabulary and differing in negation. Nearest neighbour in embedding space measures topical similarity, which is not the same thing as containing the answer.

Before any tuning, split the failures. This is the cheapest high-value instrumentation in the stack and most teams do not have it.

from dataclasses import dataclass
from enum import Enum

class FailureMode(Enum):
    RETRIEVAL_MISS  = "gold passage never retrieved"
    RANKING_MISS    = "retrieved, but below the context cutoff"
    GENERATION_MISS = "gold passage in context, answer still wrong"
    CORPUS_MISS     = "answer is not in the corpus at all"

@dataclass
class TriageResult:
    mode: FailureMode
    gold_rank: int | None   # position in the retrieved list, None if absent

def triage(gold_doc_ids: set[str],
           retrieved_ids: list[str],
           context_cutoff: int,
           answer_correct: bool,
           gold_exists: bool) -> TriageResult:
    """Classify one failed query. Run it over the whole eval set and count
    the modes before changing anything in the pipeline."""
    if not gold_exists:
        return TriageResult(FailureMode.CORPUS_MISS, None)

    rank = next((i for i, d in enumerate(retrieved_ids) if d in gold_doc_ids), None)

    if rank is None:
        return TriageResult(FailureMode.RETRIEVAL_MISS, None)
    if rank >= context_cutoff:
        return TriageResult(FailureMode.RANKING_MISS, rank)
    if not answer_correct:
        return TriageResult(FailureMode.GENERATION_MISS, rank)
    raise ValueError("triage called on a passing query")

The distribution across those four modes decides the next quarter of work.

Mostly RETRIEVAL_MISS means the index or the query representation is wrong. Mostly RANKING_MISS means you need a reranker, not a better embedding model. Mostly GENERATION_MISS means prompt and model work is genuinely the right call. Mostly CORPUS_MISS means this was never a RAG problem.

In most systems I have seen, the first two dominate and the third gets the budget.

The initial triage treats any matching gold passage as sufficient evidence. Compositional questions need more than that, and the evaluation section below extends the triage to handle them.

Retrieval is a ranking problem, not an embedding problem

Dense and sparse retrieval fail on disjoint inputs, which is the whole argument for running both.

Dense embeddings compress meaning, so they lose the tokens that carry precision: diagnosis codes, NDC numbers, policy section numbers, drug names that differ by two characters, dates. Ask for J45.909 and a dense retriever returns passages about asthma in general, which is topically correct and operationally useless.

Sparse retrieval through BM25 nails exact tokens and fails on paraphrase. A member asking about coverage for a breathing machine will not match a policy that says continuous positive airway pressure device.

The naive fix is to normalise both scores and add them. Do not. Cosine similarity and BM25 scores are not on comparable scales, the scales drift as the corpus grows, and a min-max normalisation over the current result set makes the fused score depend on which documents happened to be returned. Fuse on rank instead.

Reciprocal rank fusion ignores score magnitude entirely and uses position:

\mathrm{RRF}(d) = \sum_{r \in R} \frac{w_r}{k + \mathrm{rank}_r(d)}

The constant k damps the influence of the top positions, so a document ranked first by a noisy retriever cannot dominate the fused list on its own. Ranks are one-based, matching the original formulation. Starting at zero changes the effective damping and makes your k incomparable with any published value.

from dataclasses import dataclass, field


@dataclass
class Fused:
    doc_id: str
    score: float = 0.0
    sources: set[str] = field(default_factory=set)   # retriever keys that contributed


def reciprocal_rank_fusion(
    rankings: dict[str, list[str]],      # retriever name -> ranked doc ids
    weights: dict[str, float] | None = None,
    k: int = 60,
    top_n: int = 50,
) -> list[Fused]:
    """Rank-based fusion. Scale-free, so retrievers with incomparable score
    distributions can be combined without normalisation.

    Provenance is carried deliberately. A fused list of (id, score) pairs
    loses which retriever, and therefore which sub-question, put each
    document there, and context selection needs that downstream.

    k controls how sharply early ranks are favoured. Lower k weights the top
    of each list more aggressively. Tune it on your own golden set; 60 is a
    starting point, not a constant of nature.
    """
    weights = weights or {name: 1.0 for name in rankings}
    fused: dict[str, Fused] = {}

    for name, ranked_ids in rankings.items():
        w = weights.get(name, 1.0)
        for rank, doc_id in enumerate(ranked_ids, start=1):
            entry = fused.setdefault(doc_id, Fused(doc_id))
            entry.score += w / (k + rank)
            entry.sources.add(name)

    return sorted(fused.values(), key=lambda f: f.score, reverse=True)[:top_n]


def hybrid_search(query: str, k_each: int = 100) -> list[Fused]:
    rankings = {
        "dense":  vector_index.search(embed(query), top_k=k_each),
        "sparse": bm25_index.search(query, top_k=k_each),
    }
    # Lexical precision matters more when the query carries codes or identifiers.
    weights = {"dense": 1.0, "sparse": 1.4 if has_identifier(query) else 1.0}
    return reciprocal_rank_fusion(rankings, weights=weights, k=60)

Two properties make this worth the extra index. Adding a retriever requires no retraining and no score calibration. And a document that both retrievers rank moderately well floats above one that a single retriever loves, which is usually the behaviour you want when the retrievers disagree.

The cost is that RRF throws away confidence. When one retriever is materially stronger on your corpus, a fixed weight is a blunt instrument, and the fused list carries no signal about how far apart first and second place really were. That is a reranker’s job, covered further down.

One practical note. Retrieve deeply from each retriever before fusing. Fusing two lists of ten gives the reranker almost nothing to work with, and the recall you lose at this stage cannot be recovered downstream.

The index is a tradeoff you chose, whether or not you knew it

Approximate nearest neighbour search trades recall for latency, and the default parameters in every vector database encode somebody else’s choice about where that line sits.

HNSW builds a layered proximity graph. Three parameters matter. M sets the number of neighbours per node and therefore graph connectivity and memory. efConstruction sets how hard the builder searches while inserting, paid once at build time. efSearch sets how far the query walks the graph, paid on every request, and it is the only one you can change without a rebuild.

The failure mode is silent. An ANN index that returns the wrong neighbours does not raise. It returns plausible documents, the generation model writes a fluent answer over them, and the accuracy loss is attributed to the model.

So measure it. Build a small exact index over a sample and treat it as ground truth for the approximation itself, separately from any question about answer quality.

import time

import numpy as np

def exact_neighbours(matrix: np.ndarray, q: np.ndarray, k: int) -> list[int]:
    """Brute-force cosine top-k. Assumes L2-normalised rows."""
    return np.argsort(-(matrix @ q))[:k].tolist()


def ann_recall_curve(index, matrix, queries, k=10, ef_values=(16, 32, 64, 128, 256)):
    """Recall@k of the ANN index against exact search, per efSearch setting.

    This measures index fidelity only. It says nothing about whether the
    embedding model puts the right documents near the query in the first
    place, which is a different experiment with a different fix.
    """
    truth = [set(exact_neighbours(matrix, q, k)) for q in queries]
    out = {}

    for ef in ef_values:
        index.set_ef(ef)
        hits, elapsed = 0, []
        for q, gold in zip(queries, truth):
            t0 = time.perf_counter()
            got = index.knn_query(q, k=k)[0][0].tolist()
            elapsed.append(time.perf_counter() - t0)
            hits += len(gold & set(got))
        out[ef] = {
            "recall_at_k": hits / (k * len(queries)),
            "p95_latency_ms": np.percentile(elapsed, 95) * 1000,
        }
    return out

Run that once and the conversation changes. You stop arguing about whether the index is good enough and start choosing a point on a curve you can see, with a latency number attached to each option.

The choice of index follows the corpus, not the fashion. Where the boundaries sit depends on dimensionality, query throughput, hardware, and your latency target, so treat the table as a starting shape and the recall curve above as the actual decision.

SituationIndexWhy
Small corpus, modest QPSFlat (exact)Exact search is often fast enough; measure before adding ANN
Millions of vectors, latency-boundHNSWStrong recall per millisecond, memory-hungry
Very large, memory-boundIVF-PQCompression costs recall, often acceptably
Frequent deletes and updatesCheck rebuild semanticsSome graph indexes degrade badly under churn

That last row causes more production pain than the first three combined. Several HNSW implementations mark deletions as tombstones rather than repairing the graph, so a corpus with heavy turnover quietly loses recall between rebuilds. If your documents are versioned and superseded often, which is the normal condition for clinical policy and coverage criteria, put rebuild cadence in the design rather than discovering it in month eight.

Chunking is a document structure problem

Fixed-size chunking with overlap is the default because it is trivial to implement, and it is wrong for every document that has structure.

A 512-token window with 50-token overlap will cut a coverage criteria list in half, separate a table from its header, and strip the section heading that gives a paragraph its meaning. The retrieved chunk then says that prior authorisation is required without saying what for.

There are two competing pressures. Embeddings behave better over small focused passages, so retrieval wants small chunks. Generation wants enough surrounding context to answer correctly. Parent-child retrieval resolves this by separating what you search from what you send.

from dataclasses import dataclass, field

@dataclass
class Chunk:
    id: str
    text: str                      # the child: embedded and searched
    parent_id: str                 # the parent: retrieved and sent to the model
    headings: list[str]            # breadcrumb trail, e.g. ["Section 4", "4.2 Exclusions"]
    metadata: dict = field(default_factory=dict)

    def embedding_text(self) -> str:
        """Prepend the heading trail so the vector carries the context the
        passage assumes. A paragraph reading 'Prior authorisation is required'
        is nearly meaningless without the section it sits under."""
        trail = " > ".join(self.headings)
        return f"{trail}\n\n{self.text}" if trail else self.text


def structure_aware_chunks(doc, max_tokens: int = 320) -> list[Chunk]:
    """Split on the document's own boundaries first, size second.

    Atomic units are never split: a table with its header, a numbered
    criteria list, a code block, a definition. Oversized atomic units are
    kept whole and flagged rather than cut, because half a criteria list
    retrieved confidently is worse than one that was too long to index.
    """
    chunks, trail = [], []

    for node in doc.walk():            # headings, paragraphs, tables, lists
        if node.kind == "heading":
            trail = trail[: node.level - 1] + [node.text]
            continue

        if node.is_atomic:             # table, criteria list, code block
            chunks.append(Chunk(node.id, node.render(), node.parent_id, list(trail)))
            continue

        for window in pack_sentences(node.sentences, max_tokens):
            chunks.append(Chunk(new_id(), window, node.parent_id, list(trail)))

    return chunks


def retrieve_with_parents(query: str, top_k: int = 20) -> list[str]:
    """Search children, deduplicate to parents, send parents."""
    child_hits = hybrid_search(query, k_each=100)[:top_k]
    seen, parents = set(), []
    for hit in child_hits:
        pid = chunk_store[hit.doc_id].parent_id
        if pid not in seen:
            seen.add(pid)
            parents.append(parent_store[pid])
    return parents

The heading trail in embedding_text is the cheapest accuracy improvement in this entire document. It costs a string concatenation at index time, and in the corpora I have worked with it produced a clear recall gain, because it repairs passages whose meaning lives in a heading two levels up. Measure it on your own corpus rather than taking the number from anyone, including me.

The atomic unit rule matters more in healthcare than elsewhere. Coverage criteria are frequently conjunctive: all of A, B, and C must hold. Split that list across two chunks and retrieve one of them, and the system will confidently describe a partial rule. The failure is not a hallucination. The model faithfully reported a fragment that your chunker created.

The query you were given is not the query your index wants

Users write queries for a human colleague. Indexes answer queries written for an index. The transformation between them is a pipeline stage, and leaving it out caps your ceiling before retrieval starts.

Three transforms carry most of the value.

Routing decides whether to retrieve at all and from where. Not retrieving is the fastest retrieval, and a question about how to use the tool should never touch the clinical corpus.

Rewriting resolves what the query assumes. In a conversation, what about for children carries its subject from three turns back. In healthcare it also means expanding abbreviations, where MI is myocardial infarction, mitral insufficiency, or a state, depending on neighbouring tokens.

Decomposition splits questions that need two retrievals. Does this plan cover the drug my cardiologist mentioned is two lookups and a join, and single-shot retrieval answers it badly or not at all.

import json

ROUTER_SCHEMA = {
    "type": "object",
    "required": ["intent", "corpora", "sub_queries", "filters"],
    "properties": {
        "intent": {"enum": ["coverage", "clinical", "operational", "chitchat"]},
        "corpora": {"type": "array", "items": {"enum": ["policy", "clinical", "faq"]}},
        "sub_queries": {
            "type": "array",
            "items": {"type": "string"},
            "description": "Self-contained queries. One element when no decomposition is needed.",
        },
        "filters": {
            "type": "object",
            "properties": {
                "effective_on": {"type": ["string", "null"]},   # ISO date
                "plan_id": {"type": ["string", "null"]},
            },
        },
    },
}

ROUTER_SYSTEM = """You rewrite user questions into retrieval plans.

Rules:
- Resolve every pronoun and ellipsis using the conversation. Each sub_query
  must stand alone with no prior context.
- Expand domain abbreviations only when the surrounding text makes the sense
  unambiguous. If it does not, keep the original token and add the expansion
  as an alternative sub_query rather than guessing.
- Decompose only when a sub_query cannot be answered without the answer to
  another one. Do not split for breadth.
- Extract temporal and plan filters into filters. Never bake a date into the
  query text; the index filters on metadata.
- Return chitchat with an empty corpora list.

Return JSON matching the schema. No prose."""


def plan_retrieval(question: str, history: list[dict], principal: Principal) -> dict:
    raw = llm.complete(
        system=ROUTER_SYSTEM,
        messages=history + [{"role": "user", "content": question}],
        response_schema=ROUTER_SCHEMA,
        model=SMALL_FAST_MODEL,      # this hop is on the critical path
        temperature=0,
    )
    try:
        plan = json.loads(raw)
        if not isinstance(plan, dict):
            raise ValueError("router returned a non-object")
    except (json.JSONDecodeError, TypeError, ValueError):
        plan = {}            # malformed output degrades to the fallback below

    # Fail open on availability, never on access. A router error must not
    # become a no-answer, and it must not widen scope either.
    # setdefault would keep an explicit null, which execute() cannot use.
    plan["filters"] = plan.get("filters") or {}
    validate_filters(plan["filters"])   # reject unknown keys and unparseable dates

    if not plan.get("sub_queries"):
        plan["sub_queries"] = [question]

    requested = plan.get("corpora") or DEFAULT_CORPORA
    # Intersect on every path, not only the fallback. The router is a
    # convenience; entitlement is decided here and again in the index.
    plan["corpora"] = [c for c in requested if c in authorized_corpora(principal)]
    return plan


def execute(plan: dict) -> list[Fused]:
    if not plan["corpora"]:
        return []                     # chitchat: answer without retrieval

    rankings = {}
    for i, sq in enumerate(plan["sub_queries"]):
        for corpus in plan["corpora"]:
            rankings[f"{corpus}:dense:{i}"]  = index(corpus).dense(sq, plan["filters"])
            rankings[f"{corpus}:sparse:{i}"] = index(corpus).sparse(sq, plan["filters"])

    # The trailing index in each key is the sub-query it came from. Fusion
    # keeps it, which is what makes group-aware context selection possible.
    return reciprocal_rank_fusion(rankings, k=60, top_n=50)

Two design decisions in that code are worth naming.

The router fails open. A router that returns malformed JSON and causes a no-answer is a worse outcome than a router that occasionally searches one corpus too many. Degradation should cost money, not correctness.

Filters live in metadata, not in the query string. Writing 2026 coverage policy into the text and hoping the embedding respects the year is how systems quietly answer from superseded documents. Effective dates are a WHERE clause.

The honest cost: this adds an LLM call before retrieval begins. On a conversational interface that is usually fine. On a high-volume batch path it may not be, in which case a distilled classifier handles routing and the LLM handles only the queries the classifier marks ambiguous.

Reranking is where the accuracy actually comes from

If you add one component to a struggling RAG system, add a cross-encoder reranker. When relevant documents are already in the candidate set but rank poorly, a cross-encoder can deliver larger gains than replacing the embedding model, because it is the direct fix for the RANKING_MISS bucket from the triage. It cannot recover a document that was never retrieved, which is why it is a complement to retrieval depth rather than a substitute for it.

The reason is architectural. A bi-encoder embeds the query and the document separately, so the two never interact before the dot product. That independence is what makes the index possible, because document vectors are computed once and reused. It is also what makes the scoring coarse.

A cross-encoder concatenates query and document and runs them through the model together, with full attention across both. It cannot be precomputed and it cannot be indexed, so it only works on a candidate set. That is precisely why the pipeline shape is retrieve wide, rerank narrow.

from dataclasses import dataclass

@dataclass
class RerankConfig:
    candidates: int = 50       # from fusion
    keep: int = 6              # context budget, applied downstream
    batch_size: int = 16
    min_score: float | None = None   # calibrate per model; no universal value


def rerank(query: str, candidates: list[Document], cfg: RerankConfig) -> list[Document]:
    """Cross-encoder scoring over the fused candidate set.

    Cost scales linearly with len(candidates), unlike ANN search. This stage
    is where your p95 latency budget gets spent, so it is sized deliberately
    rather than set to whatever the example in the docs used.
    """
    pairs = [(query, d.text) for d in candidates[: cfg.candidates]]
    scores = cross_encoder.predict(pairs, batch_size=cfg.batch_size)

    floor = cfg.min_score if cfg.min_score is not None else float("-inf")
    scored = [(d, s) for d, s in zip(candidates, scores) if s >= floor]
    scored.sort(key=lambda ds: ds[1], reverse=True)

    # Scoring, thresholding and ordering happen here. The context budget is
    # applied downstream, so the whole surviving pool is returned: a plain
    # slice for single-hop queries, group-aware selection for compositional
    # ones. Truncating to a global top-k here would starve that selection.
    return [d for d, _ in scored]

The min_score threshold deserves more attention than it usually gets. Without it, a query whose answer is genuinely absent still returns keep documents, ranked confidently, and the generation model does what it was asked to do with them. A threshold tuned on held-out data makes it likelier that such a query surfaces as an explicit I do not have this, which in a regulated workflow is the better failure. Treat it as a mitigation rather than a guarantee. Cross-encoder scores are not calibrated probabilities, the distribution shifts with the model and the corpus, and a threshold reduces confident wrong answers without eliminating them. Tune it against the refusal cases in your golden set and report its false-refusal rate alongside its accuracy gain.

On sizing, the two parameters trade against each other and against latency. Widening candidates raises the ceiling on recall and costs linear time. Raising keep gives the model more to work with and costs context, cost per call, and attention dilution. Both have an empirical optimum on your corpus, and neither has a good default.

Note the division of labour. rerank scores, thresholds and orders the candidate pool. It does not apply the context budget, because for compositional queries that budget has to be allocated per sub-question rather than taken globally by score, which the evaluation section works through.

One note on the order of operations. Rerank after fusion, not before. Running a cross-encoder over each retriever’s list separately and then fusing wastes the most expensive stage in the pipeline on documents that fusion would have discarded anyway.

Evaluate retrieval separately from generation

A single end-to-end accuracy number tells you that something is wrong and nothing about what. Instrument the two stages independently or you will keep tuning the one that is already working.

Retrieval metrics need no model and no judge. They are cheap, deterministic, and they run in CI.

import numpy as np

def recall_at_k(gold: set[str], ranked: list[str], k: int) -> float:
    """Did we fetch it at all? The ceiling on everything downstream."""
    return len(gold & set(ranked[:k])) / len(gold) if gold else 0.0


def mrr(gold: set[str], ranked: list[str]) -> float:
    """How high was the first correct hit? Sensitive to the top of the list."""
    for i, doc_id in enumerate(ranked):
        if doc_id in gold:
            return 1.0 / (i + 1)
    return 0.0


def ndcg_at_k(relevance: list[float], k: int) -> float:
    """Graded relevance, position-discounted. Use when documents are not
    simply right or wrong, which is the normal case for policy text where
    several passages are partially responsive."""
    def dcg(rels):
        return sum(r / np.log2(i + 2) for i, r in enumerate(rels[:k]))
    ideal = sorted(relevance, reverse=True)
    return dcg(relevance) / dcg(ideal) if dcg(ideal) else 0.0

The golden set is the real work, and it is the part teams skip.

It needs real queries, not invented ones. Queries generated by a model from your own documents are circular: they use the document’s vocabulary, so they make dense retrieval look better than it is on the paraphrase and abbreviation cases that actually fail. Pull from support tickets, search logs, and recorded user sessions.

It needs negatives. Questions whose answers are genuinely not in the corpus, where the correct behaviour is refusal. Without these you cannot detect a system that answers everything confidently, which is the failure mode that matters most in a clinical or coverage setting.

It needs hard negatives specifically. The superseded version of the right policy. The same criteria for a different plan. The near-identical passage that differs in one exclusion. These are the cases that separate a system that works from one that demos.

Two hundred well-chosen queries with adjudicated gold passages will teach you more than twenty thousand generated ones. Budget for clinician or analyst time to build it, version it alongside the code, and treat a drop in recall@k as a build failure rather than a research finding.

Multi-hop queries need evidence groups

The triage in the opening section treats the presence of a gold passage as sufficient evidence. Compositional questions break that. Is this drug covered for a patient with this diagnosis is a formulary lookup and a clinical criteria lookup, and the answer exists only in the combination. Retrieve one of them and the triage reports a generation miss while retrieval supplied half the evidence, which sends the team to prompt tuning for a quarter.

Model gold as a conjunction of disjunctions instead. Each sub-question gets a group of passages, any one of which establishes it, and every group must be satisfied for the query to be answerable.

from dataclasses import dataclass
from enum import Enum

EvidenceGroup = set[str]              # alternatives; any one establishes the sub-question
GoldEvidence  = list[EvidenceGroup]   # every group must be satisfied


class GroupStatus(Enum):
    ABSENT_FROM_CORPUS = "no member of this group exists in the corpus"
    NOT_RETRIEVED      = "no member reached the candidate set"
    BELOW_CUTOFF       = "retrieved, but no member reached the context"
    IN_CONTEXT         = "represented in the final context"


class Verdict(Enum):
    COMPLETE         = "all groups in context, answer correct"
    GENERATION_MISS  = "all groups in context, answer still wrong"
    PARTIAL_EVIDENCE = "some groups in context, at least one missing"
    NO_EVIDENCE      = "no group reached the context"


@dataclass
class Diagnosis:
    verdict: Verdict
    coverage: float                   # fraction of required groups in context
    per_group: list[GroupStatus]      # why each group failed, where it did


def validate_gold(gold: GoldEvidence) -> None:
    """Evaluation-set validation. Runs when the golden set is authored, not
    per query. An empty group can never be satisfied, so it is an authoring
    error rather than a failure to measure."""
    if not gold:
        raise ValueError("a query with no required evidence groups cannot be scored")
    if any(not group for group in gold):
        raise ValueError("an empty evidence group can never be satisfied")


def diagnose(gold: GoldEvidence,
             corpus_ids: set[str],
             retrieved: list[str],
             context_cutoff: int,
             answer_correct: bool) -> Diagnosis:
    """Status and cause are reported separately. One query can carry a corpus
    gap, a retrieval miss and a ranking miss at the same time, and collapsing
    them into a single label hides the work that needs doing."""
    validate_gold(gold)

    candidates = set(retrieved)
    context = set(retrieved[:context_cutoff])

    def status(group: EvidenceGroup) -> GroupStatus:
        if not group & corpus_ids:
            return GroupStatus.ABSENT_FROM_CORPUS
        if not group & candidates:
            return GroupStatus.NOT_RETRIEVED
        if not group & context:
            return GroupStatus.BELOW_CUTOFF
        return GroupStatus.IN_CONTEXT

    per_group = [status(g) for g in gold]
    covered = sum(s is GroupStatus.IN_CONTEXT for s in per_group)

    if covered == len(gold):
        verdict = Verdict.COMPLETE if answer_correct else Verdict.GENERATION_MISS
    elif covered == 0:
        verdict = Verdict.NO_EVIDENCE
    else:
        verdict = Verdict.PARTIAL_EVIDENCE

    return Diagnosis(verdict, covered / len(gold), per_group)


def group_coverage_at_k(gold: GoldEvidence, retrieved: list[str], k: int) -> float:
    """Fraction of required groups represented in the top k. Replaces flat
    recall as the retrieval metric for compositional queries."""
    validate_gold(gold)
    window = set(retrieved[:k])
    return sum(bool(group & window) for group in gold) / len(gold)

Status and cause are deliberately separate. A three-group query can have one group in context, a second that was retrieved and then lost at reranking, and a third that is not in the corpus at all. The verdict records that the query had partial evidence. per_group records which lever to pull for each missing piece, and those are three different levers.

Four consequences follow.

Group coverage replaces document recall as the retrieval metric. Covering one of two groups does not establish sufficient evidence, but flat recall reports 0.5 and it reads as partial credit.

Context selection has to become group-aware. A fixed keep with global reranking can return five passages from one group and none from the other, because relevance scoring has no concept of group membership, and raising keep does not fix it. Allocate slots per group first, then fill the remainder by score.

Corpus completeness is a per-group property. One required group can be missing from the corpus entirely while the others are present, which is an acquisition problem rather than a retrieval one, and a single gold_exists flag cannot express it.

Annotation cost is the real constraint. The router’s decomposition supplies the sub-questions, but which passages count as acceptable alternatives for each one still needs human validation, and that is where the golden set budget goes.

Group-aware selection needs one caveat before it can be implemented. The evaluation harness knows the adjudicated evidence groups; a live system does not. What the system has at inference is the router’s decomposition, so sub-queries stand in for groups as a runtime proxy, and coverage becomes an estimate rather than a measurement.

@dataclass
class Selection:
    documents: list[Fused]
    unmet: dict[str, int]        # sub-question -> reserved slots left unfilled


def sub_questions_of(doc: Fused) -> set[str]:
    """Retriever keys are formatted "{corpus}:{retriever}:{sub_query_index}",
    so provenance survives fusion and one document can serve several
    sub-questions at once."""
    return {src.rsplit(":", 1)[1] for src in doc.sources}


def select_context(sub_queries: list[str],
                   ranked: list[Fused],
                   keep: int,
                   reserved_per_sub_query: int = 2) -> Selection:
    """Reserve slots per sub-question, then fill the remainder by relevance.

    Global top-k ranks on relevance alone and has no notion of which
    sub-question a passage serves, so it can return five passages for one
    and none for another. Raising keep does not fix that; reserving does.

    Unfilled reservations are returned rather than swallowed. They are the
    runtime evidence-sufficiency signal, and the generation step decides
    whether to answer or abstain on the strength of them.
    """
    if keep < reserved_per_sub_query * len(sub_queries):
        raise ValueError("context budget too small to represent every sub-question")

    chosen: list[Fused] = []
    taken: set[str] = set()
    filled = {str(i): 0 for i in range(len(sub_queries))}

    for idx in filled:
        for doc in ranked:
            if filled[idx] >= reserved_per_sub_query:
                break
            if doc.doc_id in taken or idx not in sub_questions_of(doc):
                continue
            chosen.append(doc)
            taken.add(doc.doc_id)
            for served in sub_questions_of(doc) & filled.keys():
                # One document can serve several sub-questions, but credit is
                # clamped so a shared document cannot push a counter past its
                # reservation and distort the accounting.
                filled[served] = min(reserved_per_sub_query, filled[served] + 1)

    for doc in ranked:                       # fill the remainder by global score
        if len(chosen) >= keep:
            break
        if doc.doc_id not in taken:
            chosen.append(doc)
            taken.add(doc.doc_id)

    unmet = {idx: reserved_per_sub_query - n
             for idx, n in filled.items() if n < reserved_per_sub_query}
    return Selection(chosen[:keep], unmet)

This only works if provenance survives fusion, which is why reciprocal_rank_fusion returns Fused objects carrying their contributing retriever keys rather than bare (id, score) pairs. A fused list of pairs discards exactly the information selection needs, and one document can legitimately serve several sub-questions, so provenance is a set rather than a label.

Unfilled reservations are returned, not swallowed. An unmet reservation means the system could not find evidence for one of the sub-questions it decomposed the query into, which is the runtime signal for the evidence sufficiency check and the basis for abstaining. Silently handing a short context to the generation step is how a partial answer gets presented as a complete one.

An unmet reservation is a warning that a sub-question may lack sufficient evidence, not proof that the evidence is absent. Filling every reservation does not establish that the answer is supported either. Both are statements about retrieval behaviour, and evidence sufficiency in the strict sense still requires validation against the adjudicated groups.

It remains a proxy and it will be wrong sometimes, since a passage retrieved for one sub-question can be the evidence for another. The measured version stays in the harness, where the labels are adjudicated.

This extension came out of a question from Timothy Urista after the first version of this piece was published.

For generation, keep the metrics separate and name what each one measures. Faithfulness asks whether the answer is supported by the retrieved context. Correctness asks whether it is actually right. A system can be perfectly faithful to a wrong passage, which is why the two numbers must be reported separately and never averaged into one score.

Four failure modes that are specific to clinical and coverage text

Generic RAG advice assumes documents that mean what they say. Clinical and policy corpora violate that assumption in structured, predictable ways.

Negation inverts meaning and barely moves the vector. Patient denies chest pain and patient reports chest pain are near-identical in embedding space and opposite in fact. A retriever asked about chest pain returns both, and a generation model summarising ten such passages can produce a clinically wrong picture while being faithful to every one of them. Detect negation and assertion status at index time, store it as metadata, and make it filterable. The NLP for this is well established and considerably cheaper than the alternative.

Documents have effective dates and most pipelines ignore them. Coverage policy is versioned, superseded, and retroactively amended. The semantically best match is frequently last year’s version, because the versions are nearly identical in wording. Effective date is a retrieval filter, not a detail in the footer, and the index must know which version was in force on the date of service rather than today.

Abbreviations are ambiguous and the ambiguity is domain-specific. PCP is primary care physician or phencyclidine. RA is rheumatoid arthritis or right atrium. The disambiguating signal is usually in the document section or the specialty, which your chunker threw away unless it kept the heading trail. This is a second reason to carry structure into the embedding text.

De-identification leaves artifacts that embeddings happily match on. Scrubbed notes carry placeholder tokens and date-shifted timestamps. Those placeholders are high-frequency and distinctive, so passages can retrieve each other on the basis of shared redaction patterns rather than shared clinical content. Normalise them at index time.

One boundary that is not a modelling question at all. Retrieval crosses an access control boundary every time it runs. A vector index that was built across multiple members, plans, or care teams will happily return a neighbour from outside the requesting user’s authorisation scope, because similarity has no concept of permission. Entitlement has to be enforced inside the retrieval system as a pre-filter evaluated during the search, not applied to the candidate list afterwards. Application-side filtering after retrieval fails in two ways. The candidate set is itself evidence about documents the user cannot see, and discarding results after the fact silently degrades recall for exactly the users whose scope is narrowest. Nor can you rely on the generation model to decline to mention what it was handed.

The model is not an access control layer and should never be asked to act as one.

What gets the system shut down is rarely accuracy

Everything above concerns whether the answer is right. The failures that end an enterprise deployment are usually governance failures, and they are properties of the retrieval layer rather than the model.

ConcernWhat breaksThe control
ProvenanceAn answer cannot be reproduced or defended weeks laterLog document id, version, chunk id, retriever scores and model version with every response
SupersessionThe system answers from a policy no longer in forceEffective-dated documents, version-aware filters, explicit tombstones, a rebuild cadence
Authorization syncA revoked entitlement keeps returning results until the next reindexEvaluate entitlement at query time against live authorization, never a snapshot baked into the index
Tenant isolationOne tenant’s document appears in another tenant’s candidate setSeparate indexes where blast radius justifies the cost; shared indexes only with enforced partition keys
AuditabilityNo record of which evidence produced a decisionTreat the retrieval trace as a first-class event, retained to the same standard as the decision it supported
Cost and latencySpend and p95 degrade invisibly as the corpus growsPer-stage latency budgets and cost per query tracked as SLOs, with retrieval depth as the tuning knob

Two of those deserve expanding.

Citation is not a user interface feature. The document id and version that produced an answer are the audit record, and a system that renders a citation in the response without persisting it has given the user a reference and the organisation nothing. Persist the trace, not the footnote.

Authorization drift is the one that will surprise you. Entitlements change continuously through role changes, care team reassignment, and plan termination, while indexes are rebuilt on a schedule. Any design that copies access decisions into the index at build time has committed to a window during which the index is wrong about who may see what. Evaluate at query time, or accept and document the window explicitly.

The reference shape, and the order to build it in

Retrieve wide, rerank narrow, answer from parents. Route, rewrite, decompose → entitlement filter → dense (HNSW) and sparse (BM25), top 100 each → reciprocal rank fusion, top 50 → cross-encoder rerank → group-aware context selection → parent expansion → evidence sufficiency check → generate with citations, or abstain.

RAG reference architecture: route, rewrite, decompose; entitlement filter; dense (HNSW) and sparse (BM25) retrieval, top 100 each; reciprocal rank fusion, top 50; cross-encoder rerank; group-aware context selection; parent expansion; evidence sufficiency check; generate with citations, or abstain

The candidate set narrows at every stage, which is why retrieval depth at the top matters more than any single component lower down.

Build order matters as much as the architecture, because each step tells you whether the next one is worth doing.

  1. Instrument the failures first. The triage from the opening section, over a golden set you actually built. Everything below is guesswork without it.
  2. Add lexical retrieval and fuse. Cheap, no retraining, and it fixes the identifier and code failures that dense retrieval cannot.
  3. Fix chunking and carry the heading trail. A string concatenation at index time, and usually the largest single gain per hour spent.
  4. Add the cross-encoder reranker with a threshold. Addresses the ranking misses and gives you a principled refusal path.
  5. Add routing and rewriting. Now that retrieval works, the query transformation has something worth feeding.
  6. Only then touch the embedding model or the generation prompt. By this point you will know from the triage distribution whether either is actually your constraint.

Most teams run that list backwards. They start at step six because it is the most visible and the most discussed, spend a quarter there, and arrive at step one having already concluded that the technology is not ready.

The pattern underneath all of it is the same one that governs agentic systems and model monitoring. The probabilistic component is not where your guarantees live. Retrieval quality, access control, refusal behaviour, and reproducibility are properties of the surrounding architecture, and no amount of prompt work will install them.