Filed underL04 · Data
Published
Reading time25 min
Words5,679
Field notes · L04 Data

Evaluating RAG in productionBuilding an eval set, the pitfalls of LLM-as-judge, and regression testing

RAG evaluation that holds up: retrieval vs generation metrics, building a span-labelled eval set, LLM-as-judge bias, and regression gates for chunking changes.

RAG evaluation means measuring two systems separately: retrieval (did the right evidence reach the model? Measure it with recall@k and MRR against labelled evidence) and generation (did the answer stick to that evidence and get the answer right? Measure it with faithfulness and answer correctness). Build the eval set mostly from real user queries. Label gold evidence as character spans in source documents, not chunk IDs. Use LLM judges only for narrow, binary questions, and only once you have checked them against human labels. Then gate every change to chunking, embeddings, prompts or models on a paired comparison against the current baseline.

Everything below is the detail behind that paragraph: what to measure, how to build the dataset, where LLM judges go wrong, and how to stop a "small chunking tweak" from quietly costing you five points of recall.

01Why RAG evaluation is two problems, not one

A RAG answer can be wrong for two separate reasons. The retriever never surfaced the evidence. Or the evidence was there and the generator ignored it, misread it or added to it. One end-to-end "answer quality" score mixes the two together, so you can't tell which part to fix.

Score retrieval and generation on every query and you get a diagnosis grid:

Answer correct Answer wrong
Gold evidence retrieved Working as intended Generation failure: prompt, model, context ordering, conflicting chunks
Gold evidence not retrieved Model answered from parametric memory, or your labels are incomplete. Investigate both. Retrieval failure: chunking, embeddings, query rewriting, filters, index freshness

The bottom-left cell is the one teams skip. A correct answer without retrieved evidence is not a win. Either the model is answering from training data, which won't hold for your private or recently changed documents, or your gold labels miss a valid source. Both are worth knowing.

This split also shows up in the literature. Ragas (Es et al.) and ARES (Saad-Falcon et al., NAACL 2024) both score context relevance separately from answer faithfulness and answer relevance. The detail that matters in production is how you compute each side.

02Retrieval metrics: recall@k, MRR and nDCG

Retrieval is the part you can measure deterministically, cheaply and without an LLM. Do that first.

Definitions, for a query with a set of relevant items R and a ranked result list:

  • Recall@k = |R ∩ top-k| / |R|. The share of the relevant evidence that made it into the top k.
  • Hit rate@k (sometimes loosely called recall@k) = 1 if any relevant item is in the top k, else 0. Fine for single-answer questions. Misleading for questions that need several pieces of evidence.
  • MRR (mean reciprocal rank) = mean of 1/rank of the first relevant item. It rewards putting the evidence near the top.
  • nDCG@k uses graded relevance (e.g. 0 = irrelevant, 1 = related, 2 = answers the question) and discounts by position.

Which one to watch depends on what the generator actually sees:

Your pipeline Primary metric Why
Top-k chunks stuffed into the prompt, no reranker Recall@k, where k = chunks you actually pass Position within the context matters less than presence. Evidence at rank k+1 might as well not exist.
Retrieve wide (k=50–100), rerank, pass top 5–10 Recall@50 for the first stage, recall@5 or nDCG@5 after reranking Two stages, two jobs. The retriever's job is recall. The reranker's job is order.
Single-answer lookup (FAQ, policy clause) MRR, hit rate@k One right chunk. You care how high it lands.
Multi-hop / synthesis questions Recall@k over all required spans Hit rate hides the case where half the evidence is missing.

Ordering still matters even when everything is in the context window. Liu et al., "Lost in the Middle" showed models use information at the start and end of long contexts more reliably than information in the middle. If your generation metrics look unstable while recall is flat, check where in the context the gold evidence lands.

For a published reference point on reporting this metric, Anthropic's contextual retrieval write-up reports "1 minus recall@20" as a retrieval failure rate. In their tests it fell from 5.7% to 2.9% with contextual embeddings plus contextual BM25, and to 1.9% with reranking added. Reporting the failure rate is a good habit. "Failures fell from 5.7% to 2.9%" is easier to reason about than "recall rose from 94.3% to 97.1%".

For the arithmetic, use ranx (0.3.21 at the time of writing) or pytrec_eval rather than writing your own. Hand-rolled MRR implementations are wrong more often than you would expect, usually over ties and empty result lists.

03Generation metrics: faithfulness vs answer correctness

These two are often treated as the same thing. They aren't.

  • Faithfulness (also called groundedness): is every claim in the answer supported by the retrieved context? It is reference-free, so it needs no gold answer. Ragas defines it as supported claims divided by total claims.
  • Answer correctness: does the answer match the gold answer? It needs a reference.

An answer can be faithful and wrong: it faithfully repeats an outdated document that was retrieved. It can be correct and unfaithful: the model knew the answer from pre-training and ignored the context. You want both scores because they point to different fixes. Low faithfulness is a prompt, model or context-assembly problem. Faithful but incorrect usually means the corpus or retrieval is wrong.

Track three more alongside them:

  1. Citation accuracy. If you show citations, check that each cited chunk actually supports the sentence it is attached to. This is cheap to check per claim and users notice when it fails.
  2. Abstention correctness. For questions the corpus cannot answer, did the system say so? This needs unanswerable questions in the eval set (see below). Without them you are only measuring how well the system answers and never how well it declines.
  3. Deterministic checks. Required entities present, numbers that match the source exactly, banned phrases absent, valid JSON if structured output is expected. Run these before any LLM judge. They are free, they never disagree with themselves and they catch a surprising share of regressions.

A practical order: deterministic checks, then retrieval metrics, then judge-based faithfulness and correctness only on the queries where they add information.

04How to build a RAG eval set that reflects production

The eval set is the asset. Metrics and tools are interchangeable. Five hundred well-labelled real queries will outlast three framework migrations.

Real queries vs synthetic queries

Real queries (logs, tickets, SME interviews) Synthetic queries (LLM-generated from chunks)
Distribution match Matches how users actually phrase things: typos, shorthand, underspecified Skews towards clean, well-formed, single-hop questions
Lexical overlap with source Natural High. The question is written from the chunk, so it shares the chunk's vocabulary. That inflates recall, especially for BM25 and hybrid search.
Unanswerables Present naturally Absent unless you generate them on purpose
Labelling cost High: someone must find the evidence Low: the source chunk is the label, at least at first
Privacy Contains user data; needs scrubbing and access control Clean
Best use The core regression set and the release gate Cold start, coverage of rare documents, stress tests

Our position: synthetic data is a bootstrap, not a benchmark. Use it to get a first eval set before launch and to cover documents no user has asked about yet. Replace it with real traffic as soon as you have any. Keep the two sets separate and report them separately. Synthetic recall numbers are optimistic by construction, and averaging them with real ones hides that.

If you do generate synthetic questions, reduce the overlap bias. Instruct the generator to paraphrase away from the chunk's vocabulary. Generate from pairs of chunks to get multi-hop questions. Generate questions about things the corpus deliberately does not cover. Then have a human discard the ones nobody would actually ask, which is usually a meaningful fraction.

Stratify, don't just sample

Production logs are dominated by a few frequent intents. Sample uniformly and your eval set will be mostly the easy head of that distribution. Stratify by:

  • Query type: lookup, how-to, comparison, multi-hop, numeric, time-sensitive.
  • Corpus area: one stratum per product line, document source or team.
  • Answerability: answerable, partially answerable, unanswerable. We would hold roughly 10–15% unanswerable as a starting point and adjust to what your logs show. That figure is our heuristic, not a measured optimum.
  • Permission scope, if retrieval is filtered by user ACLs (see permission-aware RAG). The same question has different correct answers for different roles.

Report metrics per stratum. An aggregate that stays flat while the "numeric" slice falls by 15 points is a regression your users will find before you do.

How big does the eval set need to be? A worked calculation

Treat a binary per-query metric (hit@5, or judge says "correct") as a proportion. Assume the true rate is around 80%. The 95% confidence interval half-width is 1.96 × √(p(1−p)/n):

n (queries) ± half-width at p = 0.8
100 ±7.8 pp
200 ±5.5 pp
400 ±3.9 pp
1,000 ±2.5 pp

So with 100 queries you cannot tell a 3-point regression from noise by comparing two absolute scores. The good news is that regression testing isn't comparing two independent samples. It compares two systems on the same queries, and paired tests are much more sensitive (more on that below). In our experience, 300–500 real queries per major stratum group is enough for a useful gate, and 50–100 is enough to catch catastrophic breakage in a pre-merge smoke test. Treat those as starting heuristics, not measured thresholds.

Label evidence as spans, not chunk IDs

This is the decision that determines whether your eval set survives its first chunking change.

If your gold labels say "the answer is in chunk_00412", they are tied to one chunking configuration. Change the chunk size from 512 to 800 tokens and chunk_00412 no longer exists. Your qrels are now meaningless, and you either relabel by hand or stop measuring.

Label evidence as character offsets into the source document instead, and derive chunk-level relevance at evaluation time:

json
{"qid": "q_0187",
 "query": "what's the notice period for terminating the enterprise plan?",
 "stratum": {"type": "lookup", "area": "contracts", "answerable": true},
 "gold_answer": "90 days' written notice before the renewal date.",
 "gold_evidence": [
   {"doc_id": "msa-2025-v3.pdf", "start": 48211, "end": 48390, "grade": 2}
 ],
 "acl_persona": "customer_admin",
 "source": "support_ticket",
 "labelled_by": "legal-sme-2",
 "labelled_at": "2026-03-10"}

The doc_id must be stable across re-ingestion: a content-addressed hash, or a canonical URL plus version. If your ingestion pipeline renames documents, fix that first.

05Mapping span labels to chunks and scoring retrieval

At evaluation time, a retrieved chunk counts as relevant if it overlaps a gold span enough. "Enough" is a choice. We use "covers at least half the span, or at least half the chunk is the span". That stops a chunk that contains one sentence of a two-page clause from counting as a hit.

python
# eval_retrieval.py: span-anchored retrieval scoring with ranx
import json
from ranx import Qrels, Run, evaluate

def overlap(a_start, a_end, b_start, b_end) -> int:
    return max(0, min(a_end, b_end) - max(a_start, b_start))

def chunk_relevance(chunk, gold_spans, min_frac=0.5) -> int:
    """Return the graded relevance of a chunk against gold spans, or 0."""
    best = 0
    for g in gold_spans:
        if g["doc_id"] != chunk["doc_id"]:
            continue
        ov = overlap(chunk["start"], chunk["end"], g["start"], g["end"])
        span_len, chunk_len = g["end"] - g["start"], chunk["end"] - chunk["start"]
        if ov >= min_frac * span_len or ov >= min_frac * chunk_len:
            best = max(best, g["grade"])
    return best

def build_qrels_and_run(evalset, retrieve, k=50):
    qrels, run = {}, {}
    for ex in evalset:
        if not ex["stratum"]["answerable"]:
            continue  # unanswerables are scored on abstention, not recall
        hits = retrieve(ex["query"], persona=ex["acl_persona"], k=k)
        # hits: [{"chunk_id", "doc_id", "start", "end", "score"}, ...]
        run[ex["qid"]] = {h["chunk_id"]: float(h["score"]) for h in hits}
        rels = {h["chunk_id"]: r for h in hits
                if (r := chunk_relevance(h, ex["gold_evidence"])) > 0}
        # Gold spans no chunk covered still count against recall:
        for i, g in enumerate(ex["gold_evidence"]):
            if not any(chunk_relevance(h, [g]) for h in hits):
                rels[f"__missing__{ex['qid']}_{i}"] = g["grade"]
        qrels[ex["qid"]] = rels
    return Qrels(qrels), Run(run)

if __name__ == "__main__":
    evalset = [json.loads(l) for l in open("evalset.jsonl")]
    from my_rag import retrieve  # your retriever
    qrels, run = build_qrels_and_run(evalset, retrieve)
    print(evaluate(qrels, run, ["recall@5", "recall@20", "mrr@10", "ndcg@10"]))

The __missing__ sentinel matters. Without it, a query whose evidence was never retrieved has no relevant items in its qrels and gets silently dropped. Your recall then rises as retrieval gets worse.

One caveat. A gold span split across two chunks will match neither under a strict threshold. That is arguably the right verdict: your chunker cut the evidence in half. But watch the count of __missing__ entries whenever chunk size changes.

06The pitfalls of LLM-as-judge

For faithfulness and answer correctness on free text, you will end up using an LLM as the grader. That's fine. But a judge is a model with its own failure modes, and its score is a measurement that needs calibrating like any other instrument.

Documented biases

  • Position bias. In pairwise comparisons, judges favour an answer because of where it appears in the prompt. Wang et al., "Large Language Models are not Fair Evaluators" found that changing the order alone could flip rankings. With ChatGPT as the judge, Vicuna-13B appeared to beat ChatGPT on 66 of 80 queries, a result they attribute to order, not quality.
  • Verbosity bias. Judges prefer longer answers. Zheng et al. (the MT-Bench paper) documented this along with position bias and limited reasoning ability. The same paper reported strong judges such as GPT-4 reaching over 80% agreement with human preferences, roughly the level humans reach with each other. "Comparable to humans" and "unbiased" are different claims.
  • Self-preference. Panickssery, Bowman and Feng showed LLM evaluators recognise and favour their own generations, and that self-preference grows with self-recognition ability. If the judge and the generator come from the same model family, expect inflated scores.
  • Weak arithmetic and long-context reasoning. Zheng et al. flag limited reasoning ability. For RAG this shows up as judges accepting "£4.2m" when the source says "£42m", or missing that a claim relies on the third of five chunks.

What breaks specifically in RAG pipelines

Beyond the published biases, these are the failure patterns we design against:

  • Judge drift on silent model updates. If the judge is an alias such as latest, your baseline moves without any change to your system. Pin a dated snapshot. Treat a judge upgrade as its own change with its own re-calibration (see the matrix below).
  • Reference leakage. Give the judge the gold answer when scoring faithfulness and it starts scoring correctness instead. Use separate prompts and separate inputs for each metric.
  • 1–10 scales. Scores cluster, shift between judge versions and don't mean anything consistent. A "7" isn't a defined state.
  • Judging the whole answer at once. One hallucinated sentence in a ten-sentence answer gets averaged away.

How to make a judge trustworthy

  1. Decompose into binary, claim-level decisions. Split the answer into atomic claims. For each claim, ask: supported by the context, yes or no? Ragas' faithfulness metric uses the same structure. Binary decisions are easier to check against humans and more stable across judge versions.
  2. Use a different model family from your generator, for the self-preference reason above.
  3. Ask for the evidence first, then the verdict. Make the judge quote the supporting text before it decides. That matches the "multiple evidence calibration" Wang et al. propose, and it makes disagreements easy to audit.
  4. For pairwise comparisons, run both orders. Count a win only if the judge prefers the same answer in both orders. Otherwise record a tie. This doubles the cost and removes most of the position bias.
  5. Calibrate against humans, and keep doing it. Hold out 100–200 examples labelled by domain experts. Measure judge-vs-human agreement with Cohen's kappa, not raw accuracy: if 90% of claims are supported, a judge that always says "yes" gets 90% accuracy and a kappa of zero.
  6. Consider a specialised grounding model for faithfulness at volume. Ragas ships a FaithfulnesswithHHEM variant backed by Vectara's open hallucination-detection model. It is cheaper and more deterministic than a frontier-model judge, though you still need to calibrate it on your own domain.

A claim-level faithfulness judge, provider-agnostic:

python
# judge_faithfulness.py
import json

JUDGE_PROMPT = """You are checking whether claims are supported by source passages.
Use ONLY the passages. Background knowledge does not count as support.

PASSAGES:
{passages}

CLAIMS (JSON list):
{claims}

For each claim return an object:
{{"claim_id": <int>, "evidence": "<exact quote from passages, or empty>",
  "verdict": "supported" | "unsupported"}}
A claim is supported only if the quoted evidence entails it, including
exact numbers, dates and named entities. Return a JSON list only."""

def judge_faithfulness(claims: list[str], passages: list[str], call_judge) -> dict:
    """call_judge(prompt) -> str. Pin a dated model snapshot inside it."""
    prompt = JUDGE_PROMPT.format(
        passages="\n\n".join(f"[{i}] {p}" for i, p in enumerate(passages)),
        claims=json.dumps([{"claim_id": i, "text": c} for i, c in enumerate(claims)]),
    )
    verdicts = json.loads(call_judge(prompt))
    # Guard: a "supported" verdict whose evidence is not literally present is downgraded.
    corpus = "\n".join(passages)
    for v in verdicts:
        if v["verdict"] == "supported" and v["evidence"].strip() not in corpus:
            v["verdict"] = "unsupported"
            v["downgraded"] = True
    supported = sum(v["verdict"] == "supported" for v in verdicts)
    return {"faithfulness": supported / max(1, len(claims)), "verdicts": verdicts}

The string check on evidence is a cheap guard against judges that invent quotes. Normalise whitespace before comparing in real use.

Calibration is a few lines:

python
from sklearn.metrics import cohen_kappa_score

human = [1, 1, 0, 1, 0, 1, 1, 1, 0, 1]   # expert labels per claim (illustrative)
judge = [1, 1, 0, 1, 1, 1, 1, 1, 0, 1]   # judge verdicts per claim
print(cohen_kappa_score(human, judge))

Set your bar before you look at the number. Common interpretive scales, such as Landis and Koch (1977), treat kappa above roughly 0.6 as substantial agreement. Whether that is good enough for a release gate is a judgement about your domain, not a universal threshold. If the judge falls short, fix the prompt or change the model before you trust any score it produces.

What judging costs: a worked model

Assumptions (illustrative, so substitute your own): 400 queries, a judge input of about 3,000 tokens per query (passages, claims and instructions), an output of about 300 tokens, and one faithfulness call plus one correctness call per query.

  • Input: 400 × 2 × 3,000 = 2.4M tokens per run
  • Output: 400 × 2 × 300 = 240k tokens per run
  • Cost per run = 2.4 × (input price per M) + 0.24 × (output price per M)

Double it if you run pairwise comparisons in both orders. Multiply by the number of PRs a week that touch the pipeline. The total is usually small next to engineering time, but it is a good reason to run retrieval metrics on every PR and judge metrics only when generation-relevant code changes. Batch APIs and prompt caching, covered in LLM cost engineering, cut it further.

07Regression testing RAG when chunking, embeddings or models change

Most RAG regressions come from changes that look harmless: a new chunk size, an embedding model upgrade, a reranker swap, a prompt edit, a corpus re-ingest with a new PDF parser. The aim is a gate that catches these before production and doesn't cry wolf on noise.

Compare at a fixed token budget, not just a fixed k

This is the trap with chunking changes. Move from 400-token to 1,000-token chunks and recall@5 will probably rise, because each chunk covers more text. Your context also grew by 2.5×, with matching cost, latency and middle-of-context dilution. Report recall at a fixed context budget next to recall@k: take ranked chunks until you reach, say, 4,000 tokens, then measure. A chunking change that only wins at fixed k isn't a win.

Re-embed everything, rebuild everything

Vectors from different embedding models are not comparable. Neither, in general, are vectors from different versions of the same model. An embedding change means a full re-embed and a fresh index, evaluated as a separate candidate next to the baseline. Never test against a half-migrated index. If your index is in Postgres, our post on pgvector vs Pinecone, hybrid search and filtering covers building a shadow index alongside the live one.

Use paired tests and look at the flips

Both systems answer the same queries, so compare them query by query:

  • Retrieval metrics (continuous per query): ranx's compare() runs paired significance tests across runs, with a paired Student's t-test by default and Fisher's randomisation test available.
  • Binary outcomes (hit@5, judge-correct): use McNemar's test. Only the discordant pairs matter, i.e. queries that flipped.

A worked example. On 400 queries, the candidate turns 20 previously correct answers wrong and 8 previously wrong answers correct. Under the null hypothesis, flips are equally likely in either direction, so the exact two-sided binomial test on 8 of 28 gives p ≈ 0.036. That is a real regression, even though the net change is only 12 queries, or 3 points, which sits inside the ±3.9 pp interval you would get from comparing two absolute scores. With 16 losses against 12 gains, p ≈ 0.57: noise.

Then read the flips. Twenty lost queries is a list someone can review in fifteen minutes. That review usually explains the regression ("the new parser drops table headers"), and the aggregate never will.

A regression gate in CI

python
# gate.py: fail the build on a statistically meaningful regression
import json, math, sys

def exact_mcnemar_p(losses: int, gains: int) -> float:
    n = losses + gains
    if n == 0:
        return 1.0
    k = min(losses, gains)
    tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n
    return min(1.0, 2 * tail)

base = {r["qid"]: r for r in map(json.loads, open("results/baseline.jsonl"))}
cand = {r["qid"]: r for r in map(json.loads, open("results/candidate.jsonl"))}

failed = False
for metric in ["hit@5", "faithful", "correct", "abstained_correctly"]:
    losses = [q for q in base if base[q].get(metric) == 1 and cand[q].get(metric) == 0]
    gains  = [q for q in base if base[q].get(metric) == 0 and cand[q].get(metric) == 1]
    p = exact_mcnemar_p(len(losses), len(gains))
    regressed = len(losses) > len(gains) and p < 0.05
    print(f"{metric:22} -{len(losses):3} +{len(gains):3}  p={p:.3f}  {'FAIL' if regressed else 'ok'}")
    if regressed:
        failed = True
        print("  lost:", ", ".join(sorted(losses)[:25]))

sys.exit(1 if failed else 0)

Run it per stratum too. A regression confined to one slice won't reach significance in the aggregate, so gate on the slices you care about most.

yaml
# .github/workflows/rag-eval.yml
name: rag-eval
on:
  pull_request:
    paths: ["rag/**", "ingest/**", "prompts/**", "evals/**"]
jobs:
  eval:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "3.12" }
      - run: pip install -r evals/requirements.txt
      - name: Retrieval eval (every PR, no LLM calls)
        run: python evals/eval_retrieval.py --out results/candidate.jsonl
      - name: Generation eval (only when generation paths change)
        if: contains(github.event.pull_request.labels.*.name, 'rag-gen')
        env: { JUDGE_API_KEY: "${{ secrets.JUDGE_API_KEY }}" }
        run: python evals/eval_generation.py --append results/candidate.jsonl
      - run: python evals/fetch_baseline.py --ref main --out results/baseline.jsonl
      - run: python evals/gate.py

Baselines must come from the same eval-set version, judge snapshot and corpus snapshot as the candidate. Store results as artefacts keyed by all three. Otherwise you end up comparing against a baseline computed on last month's documents.

08The RAG change-impact matrix

This is the reference we use to decide what a change needs re-run before it ships. Pin it next to your eval harness.

Two rules sit above the table. First, change one row at a time. A PR that changes the chunker and the embedding model together produces a number nobody can interpret. Second, a judge change is a change to the ruler, not to the system. Re-score the baseline with the new judge before you compare anything.

Change Re-map span labels Re-embed / rebuild index Retrieval eval Generation eval (judge) Re-calibrate judge
Chunk size / overlap / splitter Yes (automatic if span-labelled) Yes Yes Yes No
Document parser / OCR / ingest pipeline Check offsets are still valid; re-anchor if text changed Yes Yes Yes No
Embedding model or version No Yes, full Yes Spot-check No
Hybrid weights / BM25 params / filters No No Yes Spot-check No
Reranker model or cutoff No No Yes (post-rerank) Yes No
Query rewriting / HyDE / routing No No Yes Yes No
Prompt template / context ordering No No No Yes No
Generator model No No No Yes Only if judge shares its family
Judge model or judge prompt No No No Re-score baseline and candidate Yes, before trusting any score
Corpus refresh (new / changed docs) Yes for changed docs; flag labels on deleted docs Incremental Yes Spot-check No
Eval set edit – No Re-run baseline Re-run baseline No

The same changes again, with whether to compare at a fixed token budget and the gate we typically apply:

Change Compare at fixed token budget Typical gate
Chunk size / overlap / splitter Yes Recall@k and recall@budget, no significant loss; faithfulness no significant loss
Document parser / OCR / ingest pipeline Yes As above, and spot-check tables and headings
Embedding model or version No Recall@k first stage, no significant loss
Hybrid weights / BM25 params / filters No Recall@k, per-stratum
Reranker model or cutoff Yes nDCG@k / recall@final-k
Query rewriting / HyDE / routing No Recall@k on real queries only
Prompt template / context ordering No Faithfulness, correctness, abstention
Generator model No Faithfulness, correctness, abstention, latency/cost
Judge model or judge prompt No Kappa against human set ≥ your bar
Corpus refresh (new / changed docs) No No drop on unchanged docs; review labels on changed ones
Eval set edit No Version bump; never compare across versions

09From offline eval to production monitoring

Barnett et al., "Seven Failure Points When Engineering a Retrieval Augmented Generation System" conclude that validation of a RAG system "is only feasible during operation". We agree, with a caveat: offline evals stop known regressions, and production telemetry finds the unknown ones. You need both, connected:

  • Sample and judge live traffic. Run the same calibrated faithfulness judge on a small, fixed percentage of production answers, asynchronously. Tracing LLM apps with the OpenTelemetry GenAI conventions gives you the spans to sample from. Alert on a sustained drop, not a single bad hour.
  • Watch retrieval-side signals that need no labels: top-1 similarity score distribution, the share of queries where no result clears your relevance threshold, abstention rate, and the share of answers with zero citations. Shifts in these often come before complaints.
  • Turn failures into eval cases. Every thumbs-down, escalation or support ticket that traces back to the assistant is a candidate. Label the evidence span, add it to the right stratum and bump the eval-set version. Your eval set should grow monthly and lean towards the cases you got wrong.
  • Re-check old labels. Documents change. A gold span pointing at last year's pricing page is now a wrong label. Expire or re-verify labels when their source document's hash changes.

10Where RAG evaluation crosses other layers

RAG evaluation rarely stays inside the AI team. Your eval set is built from production queries, so it contains customer data. It needs the same access control, retention and redaction as any other dataset holding PII, and it shouldn't sit in a public bucket because "it's only test data". If retrieval is filtered by permissions, evaluation has to run as specific personas, so it depends on your identity model being clean. Your corpus is also an attack surface: a document seeded with instructions is a prompt-injection vector, covered in securing AI agents against prompt injection. Re-embedding a corpus to test a new model is a data-pipeline job with real compute and storage cost. And many "retrieval regressions" turn out to be upstream ingestion changes that nobody on the AI side was told about. When agents sit on top of RAG, the failure modes compound. Agent failure modes in production: loops, drift, tool misuse and recovery covers that side, and evaluating agents with trajectory evals covers how to test it.

11A minimal starting plan

If you have nothing today, this is the order we would follow:

  1. Week 1. Pull 200–300 real queries from logs or support tickets, stratified. Have domain experts label evidence spans and short gold answers. Add 10–15% unanswerables. Version the file.
  2. Week 1. Wire up span-to-chunk mapping and retrieval metrics with ranx. Run it on every PR. It costs nothing.
  3. Week 2. Add deterministic answer checks, then a claim-level faithfulness judge from a different model family. Have humans label 100–200 claims and compute kappa. Don't gate on the judge until it clears your bar.
  4. Week 3. Add the McNemar gate per metric and per key stratum, and publish the flip list as a PR comment.
  5. Ongoing. Sample production, feed failures back into the set and re-calibrate the judge whenever it changes.

You probably don't need a commercial evaluation platform to start. A JSONL file, ranx, one judge prompt and a forty-line gate script cover most of the value. Buy a platform when trace volume, the number of people labelling, or dashboards for non-engineers make the home-grown version painful. Don't buy one before that.

12FAQ

What is the difference between RAG evaluation and LLM evaluation?

LLM evaluation scores a model's outputs. RAG evaluation also scores the retrieval step that decides what the model sees, and the interaction between the two. Most RAG failures in production are retrieval or ingestion failures, so measuring only the generated answer misses most of the system.

Is Ragas enough for RAG evaluation?

Ragas (0.4.x at the time of writing) gives you sensible reference-free metric definitions, including faithfulness, context precision, context recall and response relevancy. It doesn't give you a representative eval set, span-level labels that survive re-chunking, judge calibration against your experts, or a regression gate. Use it as a metric library inside your own harness, not as the harness.

How many examples do I need in a RAG eval set?

For paired regression testing, our rule of thumb is that 300–500 real queries usually detects regressions of a few points. For comparing absolute scores, you need more: see the confidence-interval table above. 50–100 queries work as a fast pre-merge smoke test. Size per stratum matters more than the total.

Can I use the same LLM as both generator and judge?

You can, but expect inflated scores. Panickssery et al. showed models favour their own generations. Use a different model family for the judge where you can, and calibrate either way.

Should I use synthetic questions for RAG evaluation?

Use them for a cold start and for coverage of documents no user has asked about yet. Don't use them as your main benchmark. Synthetic questions share vocabulary with their source chunks, which inflates retrieval scores, and they under-represent the messy, multi-hop and unanswerable queries real users send.

How do I evaluate RAG after changing chunk size?

Re-chunk and re-index the whole corpus. Map your span-level gold labels onto the new chunks automatically. Compare recall at both a fixed k and a fixed token budget, and run a paired test against the baseline. If your labels are chunk IDs, you will need to relabel, so switch to spans first.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →