Evaluating Retrieval and Answers Separately

Consider a hypothetical documentation assistant for a fictional file-storage product called Orbit. It retrieves passages from the product documentation and answers customer questions with citations. A regression suite reports that 60% of its answers are correct. The team has to decide what to change: the chunking, the retriever, the number of passages in the prompt, the prompt, the model, or the rule for when to refuse. A single accuracy figure does not say. A wrong answer can come from a passage that was never retrieved, a correct passage that was retrieved but cut from the prompt, a stale passage that was faithfully summarized, or a model that ignored good evidence and answered from memory. Each cause calls for a different fix, and an end-to-end score mixes them.

Retrieval and answer generation are therefore evaluated as separate stages, each with its own labels, metrics, and failure definitions, and a diagnosis procedure assigns every failed case to the first stage that failed. Retrieval is scored on recall and relevance, answers on groundedness and correctness, and automated judges are audited before their scores are trusted. The running example is a small synthetic harness written in Python 3.12 with only the standard library, so every number shown traces to a few lines of code.

The pipeline being evaluated (index, retrieval, context assembly, generation) is the one in Retrieval-Augmented Generation and Tool-Using Agents, and the answer behavior (citations, conflicting sources, abstention when evidence is missing) is designed in Generating Grounded Answers and Handling Missing Evidence. General practice for building representative test sets and checking judges is in Evaluating AI Applications with Reproducible Test Sets; what changes when the application is retrieval-based is the subject here.

Why one answer score is not enough

A retrieval-based answer passes through four points where it can go wrong. The retriever returns a candidate pool. A selection step (a reranker, a cutoff, a token budget) turns the pool into the context that goes into the prompt. The generator writes claims and attaches citations, or declines to answer. Finally, the answer is used for a task and is either right or wrong. Evaluating each point separately asks a different question at each one.

StageQuestionWhat the test case must provideTypical measurements
Candidate retrievalDid the pool contain the evidence the question needs?Relevant evidence, with gradesRecall@k, hit@k, nDCG@k on the pool
Context selectionDid that evidence survive into the prompt?The same labels; the context budgetRecall and fact coverage on the final context; distractor count
GroundednessIs each claim supported by the context that was supplied?Nothing beyond the run’s own context and citationsClaim support rate, citation validity
CorrectnessDoes the answer satisfy the task as of the question’s date?Required facts, forbidden facts, answerable flagFact-level correctness, abstention accuracy

The stages interact, so these measurements locate where a failure appeared without proving why it happened. A retrieval miss may be caused by the corpus, the chunking, the query, or the retriever; the stage label only says where to start looking. Even so, a stage label turns “the system got worse” into “candidate recall on date-sensitive questions dropped”, which is a statement an engineer can act on.

What one test case records

Stage-level evaluation needs more per case than a question and a reference answer. A case that supports all four stages records the following.

  • The question and an as-of date. Answers to “what is the current limit” change when documents change, so the case states which version of the world is correct.
  • Relevant evidence, with grades. The passages that contain what a correct answer needs, marked essential (gain 2), helpful (gain 1), or irrelevant. Labels attach to source locations, such as a document ID with a character span, and not to chunk IDs. Chunk IDs change whenever the chunker or the index changes (see Building a Retrieval Index with Traceable Evidence), and labels tied to them would be invalidated by every re-chunking. A chunk then counts as relevant if it overlaps a labeled span.
  • Required facts. The atomic statements a correct answer must contain, for example “the Plus plan includes 1 TB”. They allow partial credit and a precise description of what an incomplete answer is missing.
  • Forbidden facts and known distractors. Statements that are wrong as of the question’s date, such as a superseded limit, and the passages that carry them. A superseded passage is not relevant, but it is also not noise: it is the passage most likely to produce a confident wrong answer.
  • An answerable flag. Unanswerable questions have no relevant evidence by definition. They are excluded from retrieval recall, where they would require dividing by zero, and evaluated on whether the system declines.

Labels of this kind are expensive, which is why the answerable set is usually small at first and grows from failures found in review. The harness below uses ten such cases over a fourteen-passage synthetic corpus. Ten cases demonstrate the mechanics and are far too few to support conclusions about a real system.

import math, re
from collections import Counter

CHUNKS = {
    "c01": "Orbit Standard includes 100 GB of storage per user.",
    "c02": "Orbit Plus includes 1 TB of storage per user.",
    "c03": "Deleted files stay in the trash for 30 days before permanent removal.",
    "c04": "Deleted files stay in the trash for 14 days before permanent removal. This replaces the earlier 30 day period.",
    "c05": "API requests are limited to 600 per minute for each workspace.",
    "c06": "When the limit is exceeded the API returns HTTP status 429 with a Retry-After header.",
    "c07": "Single sign-on through SAML 2.0 is available on the Plus plan.",
    "c08": "Audit logs are kept for 180 days on the Plus plan.",
    "c09": "Support answers email on weekdays from 09:00 to 17:00 UTC.",
    "c10": "Invoices are issued on the first day of each month.",
    "c11": "Workspace owners can transfer ownership to another admin in settings.",
    "c12": "File versions are kept for 90 days on Standard and 365 days on Plus.",
    "c13": "Shared links expire after 7 days unless the owner sets another period.",
    "c14": "Workspace owners can enforce two-factor authentication for all members.",
}
STOP = set("a an and any are can do does for how i in is it of on or the to what when which with you".split())

def tokens(text):
    return [t for t in re.findall(r"[a-z0-9]+", text.lower()) if t not in STOP]

class BM25:
    def __init__(self, chunks, k1=1.2, b=0.75):
        self.k1, self.b = k1, b
        self.docs = {i: Counter(tokens(t)) for i, t in chunks.items()}
        self.len = {i: sum(c.values()) for i, c in self.docs.items()}
        self.avg = sum(self.len.values()) / len(self.len)
        df = Counter(t for c in self.docs.values() for t in c)
        n = len(self.docs)
        self.idf = {t: math.log(1 + (n - d + 0.5) / (d + 0.5)) for t, d in df.items()}
    def search(self, query, k):
        scores = {}
        for i, tf in self.docs.items():
            s = 0.0
            for t in set(tokens(query)):
                if t in tf:
                    f = tf[t]
                    s += self.idf[t] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * self.len[i] / self.avg))
            if s > 0:
                scores[i] = s
        return sorted(scores, key=lambda i: (-scores[i], i))[:k]

CASES = [
    {"id": "q1", "q": "How much storage does the Plus plan include?", "rel": {"c02": 2}, "facts": ["1 TB"], "answerable": True},
    {"id": "q2", "q": "How long do deleted files stay in the trash?", "rel": {"c04": 2}, "facts": ["14 days"], "forbid": ["30 days"], "answerable": True},
    {"id": "q3", "q": "What happens when I exceed the API rate limit?", "rel": {"c06": 2}, "facts": ["429", "Retry-After"], "answerable": True},
    {"id": "q4", "q": "How long are file versions kept on the Plus plan?", "rel": {"c12": 2}, "facts": ["365 days"], "answerable": True},
    {"id": "q5", "q": "Which plan offers SAML single sign-on, and how long are audit logs kept?", "rel": {"c07": 2, "c08": 2}, "facts": ["Plus", "180 days"], "answerable": True},
    {"id": "q6", "q": "What is the phone support number?", "rel": {}, "facts": [], "answerable": False},
    {"id": "q7", "q": "When do shared links expire by default?", "rel": {"c13": 2}, "facts": ["7 days"], "answerable": True},
    {"id": "q9", "q": "How many days of version history does Standard keep?", "rel": {"c12": 2}, "facts": ["90 days"], "answerable": True},
    {"id": "q10", "q": "How long until a URL I sent to a colleague stops working?", "rel": {"c13": 2}, "facts": ["7 days"], "forbid": ["30 days"], "answerable": True},
    {"id": "q8", "q": "Can owners require two-factor authentication?", "rel": {"c14": 2}, "facts": ["enforce"], "answerable": True},
]

The corpus is written for this example. Passage c03 states a 30-day trash period and c04 states that it was replaced by 14 days, so a retriever that returns c03 first is serving a stale source. Case q6 asks for a phone number that the documentation does not contain, and case q10 asks about link expiry in words that share nothing with the passage that answers it. The retriever is BM25, a lexical scoring function that favors passages sharing rare query terms; the evaluation below does not depend on its details.

Evaluating retrieval: recall and relevance

Relevance labels are incomplete and graded

Retrieval metrics compare the ranked list with relevance labels, so the labels bound what the metrics can say. Three properties of labels matter in practice.

First, labels are incomplete. Nobody judges every chunk in the corpus against every question; a labeler checks the chunks the current retrievers return, plus whatever they know to be relevant. An unlabeled chunk is unjudged and not necessarily irrelevant. When a better retriever returns a useful passage nobody labeled, the metric counts it as a miss and the better system looks worse. The standard remedy in test-collection building is pooling: judge the union of the top results from several different systems, so the labels do not favor the one system that shaped them. Manning, Raghavan, and Schรผtze describe test collections and relevance judgments in their information retrieval textbook. For an application team, the equivalent habit is to sample unlabeled chunks from the top of every candidate run and have them judged before comparing runs.

Second, relevance is graded and sometimes conjunctive. A passage that states the answer is more useful than one that only mentions the topic, so labels carry gains. Some questions also need several passages at once. “Which plan offers SAML single sign-on, and how long are audit logs kept?” needs both c07 and c08; retrieving one of them does not let the generator answer correctly. Other questions can be answered from any one of several equivalent passages, and recall defined over all labeled passages would punish a system for returning only one of them. Per case, decide whether the labels are “all of these” or “any of these”, and record it.

Third, labels describe relevance to the question, not safety to use. A superseded passage can be topically perfect. It belongs in the labels as a known distractor, and the evaluation should count how often distractors reach the context.

Rank-based metrics

Let \(R\) be the set of relevant items for a question, \(k\) the cutoff, and \(\mathrm{rel}_i\) the gain of the item at rank \(i\) (zero if unlabeled or irrelevant). The metrics below answer different questions about the same ranked list.

  • Hit@k is 1 if any relevant item appears in the top \(k\), else 0. It asks whether the pool contains something useful. It is the right measure when one passage suffices and misleading when several are needed.
  • Recall@k is \(|R \cap \text{top-}k| / |R|\). It asks how much of the needed evidence was found, and it is the headline measure for a candidate pool because evidence missing from the pool cannot be recovered by later stages. It is the retrieval counterpart of the classification recall defined on labeled positives.
  • Precision@k is \(|R \cap \text{top-}k| / k\). It asks how much of the context is useful. For fixed \(k\) it falls as \(k\) grows, so it measures context efficiency and is not a quality score on its own.
  • Reciprocal rank is \(1/r\), where \(r\) is the rank of the first relevant item (0 if none), and its mean over questions is MRR. It rewards finding the first useful passage early.
  • nDCG@k uses graded gains with a position discount.

The last metric needs a formula. Discounted cumulative gain is

\[ \mathrm{DCG@}k = \sum_{i=1}^{k} \frac{\mathrm{rel}_i}{\log_2(i+1)}, \qquad \mathrm{nDCG@}k = \frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k}, \]

where IDCG is the DCG of the best possible ordering of the labeled items. The discount \(1/\log_2(i+1)\) is 1 at rank 1, about 0.63 at rank 2, and 0.5 at rank 3; it decreases slowly, so a relevant passage at rank 5 still counts for something. Dividing by IDCG puts the score between 0 and 1 and makes questions with different numbers of relevant passages comparable. Consider a hypothetical ranking for the SAML question, \([\text{c12}, \text{c07}, \text{c08}]\), where c07 and c08 each have gain 2. Then \(\mathrm{DCG@3} = 0 + 2/\log_2 3 + 2/\log_2 4 \approx 1.262 + 1.0 = 2.262\). The ideal order places both relevant passages first, so \(\mathrm{IDCG@3} = 2/\log_2 2 + 2/\log_2 3 \approx 3.262\), and \(\mathrm{nDCG@3} \approx 0.693\). Edge cases need a rule: when a question has no relevant items, IDCG is zero and the score is undefined, which is one more reason to keep unanswerable questions out of retrieval metrics. For derivations of ranking metrics and their variants, see Regression and Ranking Metrics.

Candidate pool versus final context

Retrieval is measured at two places. The candidate pool is what the retriever and any first-stage fusion return. The final context is what reaches the prompt after reranking, deduplication, and the token budget. Recall on the pool is an upper bound on recall in the context, because later stages can only drop or reorder what they receive. When pool recall is high and context recall is low, the selection step is the problem; when pool recall is already low, no amount of reranking helps. This split is the basis for the diagnosis procedure later.

Rank metrics treat each relevant passage as separately valuable, but a generator needs facts. A second measure, fact coverage, asks what fraction of the required facts appear in the text of the final context. Two chunks that both hold the same fact add recall but not coverage; a single chunk that holds two required facts adds coverage faster than recall. A rough textual match (does the string “365 days” appear in the context) is cheap and deterministic; its weakness is that it cannot recognize a paraphrase, so it is a floor that should be audited, not a verdict.

Running the metrics

The code below implements these measures and applies them to the harness. Unanswerable cases return no metrics. Macro-averaging means each answerable question contributes equally regardless of how many passages it needs.

def retrieval_metrics(ranked, rel, k):
    top = ranked[:k]
    if not rel:
        return None                       # unanswerable: no relevant items to find
    hit = float(any(i in rel for i in top))
    recall = sum(i in rel for i in top) / len(rel)
    precision = sum(i in rel for i in top) / k
    rr = next((1 / r for r, i in enumerate(top, 1) if i in rel), 0.0)
    dcg = sum(rel.get(i, 0) / math.log2(r + 1) for r, i in enumerate(top, 1))
    ideal = sorted(rel.values(), reverse=True)[:k]
    idcg = sum(g / math.log2(r + 1) for r, g in enumerate(ideal, 1))
    return {"hit": hit, "recall": recall, "precision": precision, "rr": rr, "ndcg": dcg / idcg}

def fact_coverage(context_ids, facts):
    text = " ".join(CHUNKS[i] for i in context_ids).lower()
    return sum(f.lower() in text for f in facts) / len(facts) if facts else None
def macro(retriever, k):
    rows = []
    for c in CASES:
        m = retrieval_metrics(retriever.search(c["q"], 10), c["rel"], k)
        if m is not None:                  # unanswerable cases have no relevant items
            rows.append(m)
    return {name: round(sum(r[name] for r in rows) / len(rows), 3) for name in rows[0]}, len(rows)

retriever = BM25(CHUNKS)
for k in (1, 2, 3, 5):
    print("k =", k, *macro(retriever, k))
print("per case, k=3")
for c in CASES:
    ranked = retriever.search(c["q"], 10)
    m = retrieval_metrics(ranked, c["rel"], 3)
    if m:
        cov = fact_coverage(ranked[:2], c["facts"])
        print(" ", c["id"], ranked[:3], "rr", round(m["rr"], 2), "ndcg", round(m["ndcg"], 3), "fact coverage@2", cov)
k = 1 {'hit': 0.667, 'recall': 0.611, 'precision': 0.667, 'rr': 0.667, 'ndcg': 0.667} 9
k = 2 {'hit': 0.889, 'recall': 0.889, 'precision': 0.5, 'rr': 0.778, 'ndcg': 0.807} 9
k = 3 {'hit': 0.889, 'recall': 0.889, 'precision': 0.333, 'rr': 0.778, 'ndcg': 0.807} 9
k = 5 {'hit': 0.889, 'recall': 0.889, 'precision': 0.2, 'rr': 0.778, 'ndcg': 0.807} 9
per case, k=3
  q1 ['c08', 'c02', 'c07'] rr 0.5 ndcg 0.631 fact coverage@2 1.0
  q2 ['c03', 'c04'] rr 0.5 ndcg 0.631 fact coverage@2 1.0
  q3 ['c06', 'c05'] rr 1.0 ndcg 1.0 fact coverage@2 1.0
  q4 ['c12', 'c08', 'c07'] rr 1.0 ndcg 1.0 fact coverage@2 1.0
  q5 ['c08', 'c07', 'c12'] rr 1.0 ndcg 1.0 fact coverage@2 1.0
  q7 ['c13'] rr 1.0 ndcg 1.0 fact coverage@2 1.0
  q9 ['c12', 'c01', 'c08'] rr 1.0 ndcg 1.0 fact coverage@2 1.0
  q10 [] rr 0.0 ndcg 0.0 fact coverage@2 0.0
  q8 ['c14', 'c11'] rr 1.0 ndcg 1.0 fact coverage@2 1.0

Each summary line shows the macro average over the nine answerable cases (the trailing 9). Raising the cutoff from 1 to 2 lifts hit@k from 0.667 to 0.889, because in q1 and q2 the relevant passage is in second place. The metrics do not change from 2 to 5. That plateau has a cause visible in the per-case lines: q10 returns an empty list, because its wording (“URL”, “sent”, “colleague”) shares no term with the passage about shared links. A larger cutoff cannot repair a case with no candidates; vocabulary mismatch of this kind is what query rewriting and hybrid retrieval address, as covered in Hybrid Retrieval, Reranking, and Query Transformation. MRR (0.778) is below hit@3 (0.889) because the rank-2 hits in q1 and q2 earn only 0.5 each.

The q2 line deserves a second look. Its recall is perfect and its relevant passage c04 is present, but the stale c03 is ranked first. Retrieval metrics defined only over relevant items do not register that. The distractor labels from the previous section are what make the problem visible, and the generation-side metrics later in the article show its consequence. The fact-coverage column is 1.0 for every case with candidates, including q2, which shows how little a coverage number says about conflicting evidence.

Groundedness: is each claim supported by what was supplied

Claims, citations, and support

Groundedness (also called faithfulness or attribution) measures whether the answer’s statements are supported by the evidence the system supplied to the model. It is a property of the answer relative to the context, independent of whether the world agrees. The unit of measurement is the claim: a single checkable statement. A long answer is first split into atomic claims, and each claim is checked against the passages it cites or, if it cites nothing, against the whole context. Min and colleagues use this decomposition in FActScore, which reports the fraction of atomic facts supported by a knowledge source. Rashkin and colleagues define “attributable to identified sources” (AIS) as the human-evaluation criterion for whether a statement is supported by the source it names.

Each claim receives one of three verdicts: supported (the cited text entails the claim), contradicted (the cited text conflicts with it), or unsupported (the text neither entails nor contradicts it). The distinction between the last two matters in diagnosis, because contradiction usually means misreading and unsupported usually means the model added content. Several measures follow from the verdicts:

  • Claim support rate, the fraction of claims that are supported. A high rate on an answer that makes few claims says little, so report it with the claim count and macro-average per question.
  • Citation validity, the fraction of citations that point to a passage actually supplied in the context. This is a deterministic check that catches invented identifiers.
  • Citation precision and recall, in the sense used by Gao and colleagues in ALCE, which evaluates the quality of generated citations: recall asks whether each claim is fully supported by what it cites, and precision asks whether each cited passage contributes to the claim it is attached to. A claim that cites three passages when one is enough lowers precision, and a supported claim with no citation lowers recall.

Reference-free frameworks such as Ragas (Es et al.) package this decomposition, scoring faithfulness together with context relevance and answer relevance without gold labels. These frameworks are useful because they run on unlabeled traffic; their scores come from model judges and carry the limits discussed in the section on judging.

Groundedness does not require the claim to be true. An answer that restates a stale passage faithfully is fully grounded. Nor does it require that every claim be in the question’s scope: an extra grounded claim about audit logs in an answer about storage is supported and irrelevant. Relevance of the answer to the question is a separate property, and the correctness check later in the article handles the cases where extra content changes the verdict.

A cheap verifier and where it fails

A deterministic verifier is useful as a first pass because it is free, repeatable, and exact about things it can check. The one below marks a claim as supported if its citation points to a passage in the context, every number in the claim occurs in that passage, and at least 80% of the claim’s content words occur in the passage. It is a stand-in for an entailment model or a model judge, and it fails in characteristic ways that are shown next.

def numbers(text):
    return set(re.findall(r"\d+(?::\d+)?", text))

def claim_supported(claim, context_ids, min_overlap=0.8):
    """Stub verifier: cited chunk must be in the context, contain every number in
    the claim, and contain most of the claim's content words."""
    if claim["cite"] is None or claim["cite"] not in context_ids:
        return False
    source = CHUNKS[claim["cite"]]
    if not numbers(claim["text"]) <= numbers(source):
        return False
    words = set(tokens(claim["text"]))
    return len(words & set(tokens(source))) / len(words) >= min_overlap
for text in ["Deleted files stay in the trash for 14 days before permanent removal.",
             "Removed items are kept in the bin for two weeks, then erased.",
             "Deleted files stay in the trash for 41 days before permanent removal.",
             "Deleted files do not stay in the trash for 14 days before permanent removal."]:
    print(claim_supported({"text": text, "cite": "c04"}, ["c04"]), "|", text)
True | Deleted files stay in the trash for 14 days before permanent removal.
False | Removed items are kept in the bin for two weeks, then erased.
False | Deleted files stay in the trash for 41 days before permanent removal.
True | Deleted files do not stay in the trash for 14 days before permanent removal.

The first line is a verbatim restatement and passes. The second is a correct paraphrase of the same fact that the verifier rejects, because it shares few words with the passage. Lexical checks have false negatives on paraphrase, so a low support rate from such a check overstates the problem. The third changes 14 to 41, and the number check catches it. The fourth inserts a negation and still passes, because the negated claim contains almost all the passage’s words and the same number. That is a false positive on the exact kind of error a user cares about. Lexical overlap detects missing content far better than it detects contradiction. A natural-language-inference model or a model judge is needed for contradiction, and its own error rates then need to be measured; the section on judging returns to that.

Groundedness is not correctness

The two properties cross, and each cell of the cross has a different cause and a different remedy.

CorrectIncorrect
Supported by the contextThe intended behaviorThe evidence was wrong, stale, or misread: fix sources, versions, or conflict handling
Not supported by the contextThe model answered from memory; the answer cannot be verified and may change with the next model versionFabrication: fix the refusal behavior and the generation constraints

The lower-left cell is the one teams are tempted to ignore, because the user got a right answer. It still counts as a failure of a retrieval-based design: the application promised answers traceable to the documents, the claim cannot be traced, and the same behavior on a nearby question produces a wrong answer with equal confidence. A quick way to find these cases is to compare a closed-book run (no context) with the retrieved run on the same questions. A question answered correctly closed-book is a weak test of retrieval, and test sets built from widely known facts overestimate the value of the retriever. The hallucination glossary entry covers the broader notion of unsupported generation.

Correctness: does the answer do the job

Correctness compares the answer with the task requirements, and on answerable questions it is usually checked against required facts. A case passes when every required fact is present and no forbidden fact is asserted. Required-fact checks give partial credit (3 of 4 facts present is different from 0 of 4) and a precise account of omissions. Forbidden facts catch the stale-source failure that required-fact matching alone misses: the answer to q2 contains “14 days” and “30 days”, and without the forbidden-fact rule it would pass.

For free-text answers, string matching is a floor. It misses paraphrases and numeric formats (“one terabyte”), and it accepts an answer that states a required fact in the wrong context. Normalization (lowercasing, units, numeric tolerance) removes some of that. The rest needs either a human-written rubric applied by a reviewer or a model judge with the limits discussed below. The harness uses string matching because its answers are verbatim passages.

Unanswerable questions need their own measures, since for them the correct behavior is to abstain. Treat abstention as a classifier over the question set and report the two error rates separately:

  • False answer rate on unanswerable questions: the fraction of unanswerable questions that receive an answer. This is the risky error, because the answer is by construction unsupported.
  • False abstention rate on answerable questions: the fraction of answerable questions refused. This is the cost error: the evidence was available and the user got nothing.

Raising the refusal threshold trades one for the other, which is the same trade-off that threshold selection makes for any classifier. Reporting only an overall accuracy hides it, because a system that always abstains scores perfectly on unanswerable questions and a system that never abstains scores perfectly on answerable ones. How the generator decides to abstain is covered in Generating Grounded Answers and Handling Missing Evidence; the evaluation side is to measure both rates on a set that contains both kinds of question, and to set the acceptable ratio from the cost of each error, as in the acceptance criteria discussed in Framing an AI Application.

Putting the stages together

The next block adds a stub generator and an evaluation function that records, per case, candidate recall, context recall, abstention, claim support, and correctness. The generator is a deterministic stub, not a language model. It selects up to two context passages whose words overlap the question by at least 40%, copies them as cited claims, and abstains if none qualifies. With the option use_memory it falls back to a canned “memory” answer when it has no supported claim, which stands in for a model that answers from its parameters; both canned answers are deliberately fabricated or wrong. The pipeline retrieves a pool of five and passes the top two to the generator.

MEMORY = {"q6": "Call +1 555 0100 during business hours.",   # fabricated by the stub on purpose
          "q10": "Links expire after 30 days."}               # plausible but wrong

def overlap(question, text):
    q = set(tokens(question))
    return len(q & set(tokens(text))) / len(q)

def generate(question, qid, context_ids, tau=0.4, max_claims=2, use_memory=False):
    scored = sorted(((overlap(question, CHUNKS[i]), i) for i in context_ids), reverse=True)
    claims = [{"text": CHUNKS[i], "cite": i} for s, i in scored[:max_claims] if s >= tau]
    if not claims and use_memory and qid in MEMORY:
        claims = [{"text": MEMORY[qid], "cite": None}]
    if not claims:
        return {"abstained": True, "claims": []}
    return {"abstained": False, "claims": claims}

def run_pipeline(retriever, cases, k_pool=5, k_ctx=2, **gen):
    rows = []
    for c in cases:
        pool = retriever.search(c["q"], k_pool)
        ctx = pool[:k_ctx]
        rows.append({"case": c, "pool": pool, "ctx": ctx,
                     "answer": generate(c["q"], c["id"], ctx, **gen)})
    return rows
def evaluate(rows, k_pool=5):
    out = []
    for r in rows:
        c, a = r["case"], r["answer"]
        text = " ".join(x["text"] for x in a["claims"]).lower()
        rel = set(c["rel"])
        pool_rec = len(rel & set(r["pool"])) / len(rel) if rel else None
        ctx_rec = len(rel & set(r["ctx"])) / len(rel) if rel else None
        support = [claim_supported(x, r["ctx"]) for x in a["claims"]]
        correct = (all(f.lower() in text for f in c["facts"])
                   and not any(f.lower() in text for f in c.get("forbid", [])) and not a["abstained"]
                   if c["answerable"] else a["abstained"])
        flags = []
        if c["answerable"]:
            if pool_rec < 1: flags.append("retrieval_miss")
            elif ctx_rec < 1: flags.append("context_selection")
            elif a["abstained"]: flags.append("false_abstention")
        elif not a["abstained"]:
            flags.append("answered_unanswerable")
        if not all(support): flags.append("unsupported_claim")
        if c["answerable"] and not correct and not a["abstained"] and all(support):
            flags.append("wrong_but_grounded")
        out.append({"id": c["id"], "pool_rec": pool_rec, "ctx_rec": ctx_rec,
                    "abstained": a["abstained"], "supported": support,
                    "correct": correct, "flags": flags})
    return out

def show(res):
    print(f"{'id':4} {'pool':>5} {'ctx':>5} {'abst':>5} {'supp':>5} {'corr':>5}  flags")
    for e in res:
        sup = f"{sum(e['supported'])}/{len(e['supported'])}"
        f = lambda v: "-" if v is None else f"{v:.2f}"
        print(f"{e['id']:4} {f(e['pool_rec']):>5} {f(e['ctx_rec']):>5} {str(e['abstained'])[0]:>5} {sup:>5} {str(e['correct'])[0]:>5}  {', '.join(e['flags'])}")




res = evaluate(run_pipeline(retriever, CASES, k_ctx=2, use_memory=True))
show(res)
id    pool   ctx  abst  supp  corr  flags
q1    1.00  1.00     F   2/2     T  
q2    1.00  1.00     F   2/2     F  wrong_but_grounded
q3    1.00  1.00     F   1/1     T  
q4    1.00  1.00     F   2/2     T  
q5    1.00  1.00     F   2/2     T  
q6       -     -     F   0/1     F  answered_unanswerable, unsupported_claim
q7    1.00  1.00     F   1/1     T  
q9    1.00  1.00     T   0/0     F  false_abstention
q10   0.00  0.00     F   0/1     F  retrieval_miss, unsupported_claim
q8    1.00  1.00     F   1/1     T  

Columns pool and ctx are recall of the labeled passages in the candidate pool and in the final context. abst is whether the system abstained, supp is supported claims out of claims made, and corr is correctness under the required-fact, forbidden-fact, and abstention rules. Cases without flags pass every check. The flagged rows show the failure types the stages were separated to find:

  • q2 has perfect retrieval recall and fully supported claims and is still wrong. The stub copied both c03 and c04, so the answer asserts 30 days and 14 days. Every claim is grounded; the evidence is in conflict and nothing resolved it.
  • q6 is unanswerable. No passage overlapped enough to produce a claim, so the stub fell back on its fabricated phone number. The claim has no citation and fails support, and the case is flagged as an unanswerable question that was answered.
  • q9 has the relevant passage in context and abstains anyway. The retrieval stages are clean, so the fault is in the abstention rule: the passage c12 overlaps only 33% of the question’s content words, under the 40% gate.
  • q10 has an empty pool, which is a retrieval miss, and the fallback produces an ungrounded wrong claim. Two stages failed in one case, which is why flags are a list.

The table also shows a limit of the correctness check. Case q1 passes because “1 TB” is present, but its answer also contains an unrelated audit-log claim. Required-fact matching does not penalize irrelevant additions. If extra content matters for the product, add a check for it, such as the share of answer claims that bear on the question.

Limits of judging

Relevance, support, and correctness often need judgments that string rules cannot make. The usual substitute is a language model prompted with a rubric (see LLM-as-a-Judge), or a trained entailment model. These judges make evaluation scale from dozens of cases to thousands, and they bring their own errors, which have to be measured and then accounted for in the numbers that are reported.

Known judge behavior

Zheng and colleagues, who studied model judges on MT-Bench and Chatbot Arena, report that strong judges can reach more than 80% agreement with human preferences, similar to the agreement between humans, and also document position bias (preferring an answer because of where it appears), verbosity bias (preferring longer answers), and self-enhancement bias (favoring answers from the same model family). Those findings come from pairwise comparisons of general chat responses, and the same failure modes are plausible in retrieval evaluation but have to be checked there. Several retrieval-specific considerations follow:

  • What the judge sees. A support judge must see the cited passages and not the model’s memory of the world; if it can use its own knowledge, it will mark true but unsupported claims as supported, which hides exactly the failures groundedness exists to catch. Give the judge the claim and the cited text and ask for a verdict relative to that text.
  • Judge and generator overlap. Using the same model as generator and judge risks the self-enhancement effect. Prefer a different model family, or at least confirm on the audit set that agreement does not depend on which model produced the answer.
  • Version and variance. A judge is a pinned model, prompt, and decoding configuration. Changing any of them changes scores, so rescore stored outputs when the judge changes and compare old and new judges on the same outputs before trusting a trend.
  • Critical categories. Overall agreement can be high while missing a rare category that matters. A judge that passes every claim scores 95% agreement on a set with 5% unsupported claims and catches none of them.

Prefer deterministic checks wherever they can decide. Citation validity, numeric agreement, forbidden-fact strings, and format rules are exact, free, and repeatable. Spend judge calls on what they cannot decide, and have the judge answer narrow questions (“does this passage state this number”) instead of holistic ones (“is this answer good”).

Auditing a judge: sensitivity, specificity, and correcting the rate

A judge is validated against human labels on an audit sample. Humans label a set of claims; the judge labels the same claims; the confusion matrix gives two numbers for the failure class of interest. If “unsupported” is the positive class, sensitivity is the fraction of truly unsupported claims the judge flags, and specificity is the fraction of truly supported claims the judge passes. Because failures are rare, the audit sample should be stratified: oversample claims the judge flagged and claims it passed, so that each class has enough items for a stable estimate. Agreement between the human labelers is part of the picture, because a reference the humans cannot agree on cannot validate anything; Inter-Annotator Agreement explains how that is measured and why it is context, not a ceiling for the judge.

Sensitivity and specificity also correct the headline rate. Suppose the true fraction of unsupported claims is \(p\). A judge with sensitivity \(s\) and specificity \(c\) flags a fraction

\[ p_{\text{obs}} = s\,p + (1-c)(1-p) \]

of claims: true failures it catches plus supported claims it wrongly flags. This follows from treating \(s\) and \(c\) as constants, and solving it for \(p\) gives

\[ p = \frac{p_{\text{obs}} + c – 1}{s + c – 1}. \]

This is the Rogan-Gladen estimator from epidemiology, which corrects prevalence measured by an imperfect test. It assumes the judge’s error rates are the same in the audit sample and in production, and it requires \(s + c > 1\), that is, a judge better than a coin flip; at \(s + c = 1\) the denominator is zero and the observed rate carries no information about \(p\). The audit estimates of \(s\) and \(c\) are themselves proportions from finite samples and have uncertainty, which the Wilson score interval (see Wilson Score Interval) handles better than the normal approximation when proportions are near 0 or 1 or counts are small:

\[ \frac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}. \]

The block below uses hypothetical audit counts. In production the judge flags 12% of 1,000 claims as unsupported. In the audit it flags 40 of 50 human-labeled unsupported claims and 6 of 150 human-labeled supported claims (so it passes 144).

import math

def wilson(successes, n, z=1.96):
    p = successes / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return centre - half, centre + half

def corrected_prevalence(p_obs, sens, spec):
    denom = sens + spec - 1
    if denom <= 0:
        raise ValueError("judge is no better than chance; correction undefined")
    return min(1.0, max(0.0, (p_obs + spec - 1) / denom))

p_obs = 0.12                       # judge flags 12% of 1,000 production claims as unsupported
caught, bad = 40, 50               # audit: judge flagged 40 of 50 human-labeled unsupported claims
passed, good = 144, 150            # audit: judge passed 144 of 150 human-labeled supported claims
sens, spec = caught / bad, passed / good
print("sensitivity", sens, "specificity", spec)
print("point estimate", round(corrected_prevalence(p_obs, sens, spec), 3))

s_lo, s_hi = wilson(caught, bad)
t_lo, t_hi = wilson(passed, good)
print("sensitivity 95% interval", round(s_lo, 3), round(s_hi, 3))
print("specificity 95% interval", round(t_lo, 3), round(t_hi, 3))
vals = [corrected_prevalence(p_obs, s, t) for s in (s_lo, s_hi) for t in (t_lo, t_hi)]
print("corrected prevalence range over the interval corners", round(min(vals), 3), round(max(vals), 3))
sensitivity 0.8 specificity 0.96
point estimate 0.105
sensitivity 95% interval 0.67 0.888
specificity 95% interval 0.915 0.982
corrected prevalence range over the interval corners 0.044 0.156

The judge catches 80% of true failures and wrongly flags 4% of supported claims. The corrected unsupported rate is 10.5%, a little below the 12% the judge reported, because some of its flags were false alarms that outweigh the failures it missed. The audit has only 50 positive examples, so sensitivity could plausibly lie anywhere from 0.67 to 0.89, and the corrected rate moves between 4.4% and 15.6% across the corners of those two intervals. That range is a rough indication of how much audit uncertainty matters, not a joint confidence interval. The practical reading is that a judge-scored rate from a modest audit should be reported as a range, and that growing the audit set on the failure class typically narrows the range more than scoring more production claims does. Prediction-powered inference (Angelopoulos et al.) is a general method that combines a small human-labeled set with a large judge-scored set to produce valid confidence intervals, and it is worth studying once the audit habit exists.

The unit of resampling

A single answer contains several claims, and claims from the same question are not independent. Averaging over all claims and bootstrapping them as if they were independent understates uncertainty. Compute a per-question score first, then resample questions. The same applies to relevance labels over multiple passages of one query. The bootstrap in the regression section uses questions as the resampling unit for this reason.

Diagnosis: assigning failures to stages

The per-case flags in the earlier table come from a decision procedure that checks stages in order and records the first failure, plus any later ones. For an answerable question:

  1. If recall of the labeled evidence in the candidate pool is below 1, the failure is a retrieval miss. Inspect, in order: whether the evidence exists in the corpus at all (a corpus gap is a data problem, not a retrieval problem), whether extraction and chunking kept the passage intact, whether the query shares vocabulary with it, and whether access filters removed it.
  2. Otherwise, if context recall is below 1, the failure is context selection. Inspect the reranker, the cutoff, deduplication, and the token budget.
  3. Otherwise, if the evidence was in the context and the system abstained, the failure is a false abstention. Inspect the refusal rule and the prompt.
  4. Otherwise, if a claim is unsupported, the failure is an unfaithful claim. Inspect the prompt, the generation constraints, and whether the model fell back on parametric knowledge.
  5. Otherwise, if the answer is wrong while every claim is supported, it is grounded but wrong: the evidence in context is stale, conflicting, or incomplete for the task, or the answer omits a required fact. Inspect source versions and conflict handling.

For an unanswerable question the only first-order check is whether the system abstained. The ordering is a convention that matches how failures propagate (a missing passage makes later checks moot), and it is a heuristic: a context-selection failure and a generator failure can co-occur in one case, which is why the flags are recorded as a list and not collapsed to one label.

Counterfactual runs

Flags tell where the evidence disappeared. Counterfactual runs measure what each stage costs. Two controls are cheap. In the oracle run, the generator receives exactly the labeled relevant passages; its result is a ceiling on what the generator can do and isolates generator and abstention faults from everything upstream. In the closed-book run, the generator receives no passages; correct answers there mark questions that do not test retrieval. The gap between the oracle run and the retrieved run is the quality lost to retrieval and context selection, and the gap between a perfect score and the oracle run is what the generator and the task design lose. The next block runs the oracle control on the harness, then does a controlled change of the context budget to show regression comparison.

import random

def oracle_run(cases, **gen):
    rows = []
    for c in cases:
        ctx = sorted(c["rel"])
        rows.append({"case": c, "pool": ctx, "ctx": ctx,
                     "answer": generate(c["q"], c["id"], ctx, **gen)})
    return rows

base = evaluate(run_pipeline(retriever, CASES, k_ctx=2, use_memory=True))
oracle = evaluate(oracle_run(CASES, use_memory=True))
cand = evaluate(run_pipeline(retriever, CASES, k_ctx=1, use_memory=True))

def rate(res, key):
    return sum(key(e) for e in res) / len(res)

print("correct: retrieved ctx", rate(base, lambda e: e["correct"]),
      "| oracle ctx", rate(oracle, lambda e: e["correct"]))
print("oracle failures:", [(e["id"], e["flags"]) for e in oracle if not e["correct"]])

print("\nbaseline k_ctx=2 vs candidate k_ctx=1, paired by case")
diff = [int(c["correct"]) - int(b["correct"]) for b, c in zip(base, cand)]
for b, c in zip(base, cand):
    if b["correct"] != c["correct"] or b["flags"] != c["flags"]:
        print(" ", b["id"], "correct", b["correct"], "->", c["correct"], "| flags", b["flags"], "->", c["flags"])
print("mean paired difference", sum(diff) / len(diff))

random.seed(7)
boots = sorted(sum(random.choices(diff, k=len(diff))) / len(diff) for _ in range(5000))
print("95% bootstrap interval", boots[125], boots[4874])
correct: retrieved ctx 0.6 | oracle ctx 0.7
oracle failures: [('q6', ['answered_unanswerable', 'unsupported_claim']), ('q9', ['false_abstention']), ('q10', ['unsupported_claim'])]

baseline k_ctx=2 vs candidate k_ctx=1, paired by case
  q1 correct True -> False | flags [] -> ['context_selection', 'wrong_but_grounded']
  q2 correct False -> False | flags ['wrong_but_grounded'] -> ['context_selection', 'wrong_but_grounded']
  q5 correct True -> True | flags [] -> ['context_selection']
mean paired difference -0.1
95% bootstrap interval -0.3 0.0

With oracle context, correctness rises from 0.6 to 0.7: the one case repaired is q2, where passing only the relevant passage removes the stale one. The three remaining failures survive the oracle and so belong to the generator side: q6 (answering an unanswerable question), q9 (the 40% gate refusing with the evidence in hand), and q10 (a fallback to memory because the stub’s lexical gate fails on the paraphrased question). That reading assigns q9 to the abstention rule without any further investigation, which is what the oracle run is for. It also shows that a retrieval improvement could raise this system’s correctness by at most one case of ten, and that most remaining failures need generator changes.

Limits of the attribution rules

The oracle run shifts the generator’s input distribution: in production the context contains distractors the oracle context lacks, so a generator that passes the oracle run can still fail on noisy context. Treat the oracle result as an upper bound and not as a guarantee. The flag rules also encode the order in which the checks happen, so a team with a different pipeline (for example, a rewrite step before retrieval) adds that stage to the procedure.

Regression: detecting change without chasing noise

A retrieval application has more moving parts than a model alone: corpus snapshot, chunker, embedding model, index, retriever, reranker, context budget, prompt, generator, and judge. A regression suite fixes all but the one being changed and compares per-case results, so that a change in a number can be attributed to the change in the system.

What to pin and what to store

  • Pin the inputs. Record the corpus snapshot or document versions, the index build and the embedding model, the prompt version, the generator model and decoding settings, and the judge model, prompt, and version. Without these, two runs cannot be compared.
  • Store per-case outputs, not only aggregates. For every case keep the pool, the context, the answer, the claim verdicts, and the stage flags. The aggregate is derived from this record, and the record is what an engineer opens when a number moves.
  • Keep labels independent of the index. Labels attached to source spans survive a change of chunker; labels attached to chunk IDs have to be redone each time. When the corpus changes, review the cases whose source documents changed, because their correct answers may have changed too.

Compare paired, report intervals, and read the flips

The baseline and candidate configurations run on the same cases, so compare them per case. The difference in a metric on each case, averaged, has less variance than the difference of two independent averages, because the case-to-case difficulty cancels; Comparing Models: Uncertainty and Significance develops this pairing. In the block above, the candidate reduces the context budget from two passages to one. The mean paired difference in correctness is -0.1, which is one case flipping from pass to fail (q1: its only context passage is now the audit-log passage). The bootstrap interval resamples the ten per-case differences and runs from -0.3 to 0.0. An interval that touches zero on ten cases means the data cannot distinguish this change from noise, not that the change is harmless. The interval shows how little ten cases can say, and it shows why reading the individual flips matters more than the mean at this size.

The flips are the useful output. Three cases changed flags: q1 went from passing to failing, q2 stayed wrong and gained a context-selection flag (now only the stale passage is supplied), and q5 still passes while gaining a context-selection flag, because the single audit-log passage happens to contain both required facts while the SAML passage no longer reaches the context. The last case shows a pass that hides a degraded stage. It is the reason regression gates look at stage metrics (context recall) as well as final correctness: a fact-matching check passed by luck would not warn that the next question in this family would fail.

Gates, slices, and maintenance

  • Gate each stage separately. Set a floor and a maximum allowed drop for candidate recall, context recall, claim support rate, false answer rate on unanswerable questions, false abstention rate, and correctness. A change that improves correctness by hiding a recall drop behind a lucky pass should fail the retrieval gate.
  • Slice the set. Report by question type (single-fact, multi-passage, unanswerable, date-sensitive, vocabulary-mismatch) and by source type. A mean over a mixed set can hide a 30-point drop on a small slice that matters, and per-class floors are the same idea as in the acceptance criteria of Framing an AI Application.
  • Add every investigated failure. Each production failure that is diagnosed becomes a case with labels, so the same failure is tested after the fix. Adversarial documents, such as passages that contain instructions aimed at the model, are one more slice in the same harness; their design is the subject of Prompt Injection and Untrusted Content Boundaries.
  • Re-label on a schedule. Documents change, and so do correct answers. Cases with an as-of date and a recorded corpus version can be re-checked against the new corpus; the ones whose source changed go back to a reviewer.

Where offline evaluation stops

A fixed set measures the questions someone thought to write down. Real queries are phrased differently, arrive in a different mix, and touch documents that were added after the set was built, and a model judge scoring production samples shares the blind spots documented earlier. Offline stage metrics are a screen before release and a map for debugging; whether users complete their tasks is measured with the methods in Online Evaluation, Feedback, and Controlled Rollout.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.