Citations break quietly. Most teams learn about it from a user, not a test, because the answer still reads well while the evidence behind it has moved. A spot check that passed on last week's demo says nothing about the build you ship today. The reliable fix is to have the pipeline re-check citations on every retrieval, prompt or source change, the same way it already checks that the code compiles.
Staging spot checks cannot gate a release
A RAG answer can read well and still cite the wrong policy, an old revision, or a passage that never supported the claim. Nobody skimming staging will notice. Spot checks also cannot keep up with everything that moves grounding: retrieval changes, rebuilt embeddings, prompt edits, a new reranker, refreshed sources. Any of these can change which passage the model relies on.
So the release decision should rest on a regression test over a stable golden set, a fixed list of test questions with known good answers. The pipeline runs it on every change, whether or not anyone is watching staging. Each case stores the expected evidence next to the expected wording, much like a handoff note between Claude Code sessions keeps what was checked with the result. For each case the gate checks three things. Was an acceptable source retrieved? Does a precise span back every required claim? Does the answer stay within that span? If scores fall below policy, the run stops at a review gate before the merge and nothing ships.
Two things are easy to confuse. Finding the right document does not mean citing it correctly. And a citation can be present but still not support the sentence it sits under. A neat list of links can look fine while unsupported claims sit in the text between them.
This was the original promise of RAG. When Lewis et al. introduced retrieval-augmented generation in 2020, one argument was provenance. A model that reads from an external index can show where an answer came from, and the index can be updated without retraining. A citation shows that provenance to the user. Without tests it turns into decoration, and decoration is worse than nothing: a footnote makes readers stop checking.
Treat each citation as a testable claim
To judge grounding, the gate needs a unit of proof smaller than a document. That unit is the claim-evidence pair. A claim is a factual statement a user might act on. The evidence is a fixed span of text in a versioned source that supports it. A document ID alone is too rough, because one policy page often holds both the rule and the exception to it.
To keep that relationship intact from service to evaluator, have the response follow a contract like this:
{
"answer": "Refund requests are accepted within 30 days.",
"claims": [{
"id": "c1",
"text": "Refund requests are accepted within 30 days.",
"citations": [{
"source_id": "refund-policy-v4",
"start": 412,
"end": 470,
"span_sha256": "..."
}]
}],
"retrieved_ids": ["refund-policy-v4", "terms-v8"]
}
Offsets point into the source text stored in the test suite, not into whatever the UI shows. The span hash catches quiet failures. A source ID can stay the same while editors change the text, and then the same offsets land on different words. If the product shows only footnote markers, keep this structure in the service response or trace anyway. The interface can drop the offsets; the evaluator cannot.
Each golden case then lists the question, the required claims and one or more acceptable sources for each claim. Alternatives matter when, say, a handbook and a policy page state the same rule and either should pass. What you should not accept is a random chunk from the right document that does not contain an approved supporting span.
Three scores expose different failure modes
A single pass or fail tells you that a run broke, but not where. And fixing a retrieval miss is very different from fixing a careless citation. So publish three metrics on every run:
- Retrieval Recall@k: whether the top k items include an approved source for each required claim. Failures suggest indexing, query rewriting, embeddings, metadata filters, or reranking.
- Citation Precision: valid supporting citations divided by emitted citations. A citation is valid only when source, offsets, hash, and claim-to-source mapping verify; this finds decorative or stale citations.
- Answer Faithfulness: supported factual claims divided by factual claims in the structured answer. A claim is supported only if a validated citation entails it.
Retrieval Recall@k = required claims with an approved source in top k / required claims
Citation Precision = valid supporting citations / emitted citations
Faithfulness = supported factual claims / emitted factual claims
Do not merge these into one number. High recall with weak precision means the evidence reached the model but was cited carelessly. High precision with weak recall usually means the model cites only the few sources it saw and leaves out required facts. And a good average faithfulness can still hide one unsafe case. That is why the most important floors are set per case.
A worked run makes the split concrete. The numbers here are illustrative. Say the golden set has 60 cases with 150 required claims, and policy sets k = 5. Retrieval finds an approved source in the top five for 141 claims, so Recall@5 is 141 / 150 = 0.94. The answers emit 212 citations; 190 pass the source, offset and hash checks, so Citation Precision is 190 / 212, about 0.90. Of 171 factual claims in the structured answers, 160 carry a validated citation, so Faithfulness is 160 / 171, about 0.94.
Say the overall floors are 0.90, 0.85 and 0.90. That run passes. Now suppose one of the 11 unsupported claims sits in a critical case about refund eligibility. The average barely moves: one claim out of 171 is 0.6 points of faithfulness. Yet that sentence is the one most likely to end in a complaint or a chargeback. A per-case rule of zero unsupported claims in critical cases turns the run red. The averages never would.
Citation drift hides behind stable answer text
The worst regressions leave the answer text unchanged. That is where per-case floors earn their keep. Citation drift is the classic case, and it usually follows a source update. The wording stays the same, but the proof underneath has moved. When chunk boundaries or offsets shift, a citation can slide to the next sentence. The answer still sounds right, but the evidence shown no longer proves it.
Retrieval drift is different. The expected source drops out of the top k, and the model answers from a similar document instead. This usually follows an embedding-model change, a metadata migration or a reranker tweak. It is tempting to let it pass while the text still reads correctly. But that near match is one source update away from being wrong.
Generation drift is harder to spot. Retrieval is fine and the cited span is valid, but the answer adds a condition, a date or an exception the source never states. Span checks only confirm the address. Whether the span actually supports the claim is a separate question, so the harness needs its own entailment check on top.
Part of this has a known cause. In "Lost in the Middle" (2023), Liu et al. showed that language models use information at the start or end of a long context more reliably than information in the middle. A reranker change can leave Recall@k exactly the same but move the supporting chunk from first place to fourth out of eight. The retrieval metric sees nothing. The answer, though, starts to rely on whatever sits at the edges. So a retrieval change has caused generation drift. Log the rank of the cited chunk, not only whether it was retrieved. Treat a jump in the average cited rank as a warning, even when every gate is green.
For high-risk claims, add tricky goldens on purpose: a policy exception, two near-identical texts with different eligibility rules, an outdated revision, and a question whose answer must be “not stated in the source.” These cases stop a fluent answer from passing by luck.
Put the harness in the repository, next to the code
All three kinds of drift appear after ordinary commits. So the checks must live with the code, or they fall behind. Keep the corpus snapshot, the golden cases and the threshold policy in the repository:
rag-ci/
corpus/documents.json
golden/cases.json
tests/test_citations.py
policy.json
documents.json holds the source text, keyed by source_id. cases.json holds the approved evidence for each case. The service takes a query and returns the contract shown above. The pytest test below runs against a local or preview endpoint that accepts POST /answer.
import hashlib, json, os
from urllib.request import Request, urlopen
ROOT = os.path.dirname(os.path.dirname(__file__))
def load(p):
with open(os.path.join(ROOT, p), encoding="utf-8") as f: return json.load(f)
def ask(query):
req = Request(os.environ["RAG_URL"]+"/answer", data=json.dumps({"query":query}).encode(),
headers={"Content-Type":"application/json"}, method="POST")
with urlopen(req, timeout=30) as r: return json.loads(r.read())
def valid(c, cid, accepted, docs):
if c["source_id"] not in accepted[cid]: return False
span = docs[c["source_id"]]["text"][c["start"]:c["end"]]
return bool(span.strip()) and hashlib.sha256(span.encode()).hexdigest() == c["span_sha256"]
def test_golden_citation_gate():
docs, cases, policy = load("corpus/documents.json"), load("golden/cases.json"), load("policy.json")
t = dict(required=0, retrieved=0, citations=0, valid=0, claims=0, supported=0)
for case in cases:
result, accepted = ask(case["query"]), case["accepted_sources"]
required = set(case["required_claim_ids"]); t["required"] += len(required)
hit = {x for x in required if set(result["retrieved_ids"][:policy["k"]]) & set(accepted[x])}
t["retrieved"] += len(hit)
assert len(hit)/len(required) >= case["min_retrieval_recall"], case["id"]
assert required.issubset({c["id"] for c in result["claims"]}), f"missing required claim in {case['id']}"
for claim in result["claims"]:
cites = claim["citations"]
ok = [c for c in cites if claim["id"] in accepted and valid(c, claim["id"], accepted, docs)]
t["claims"] += 1; t["citations"] += len(cites); t["valid"] += len(ok); t["supported"] += bool(ok)
assert t["retrieved"]/t["required"] >= policy["min_retrieval_recall"]
assert t["valid"]/max(t["citations"], 1) >= policy["min_citation_precision"]
assert t["supported"]/max(t["claims"], 1) >= policy["min_faithfulness"]
This test checks two things reliably: that each citation points to real text, and that the evidence covers the required claims. It cannot tell whether a reworded claim actually follows from its span. For that, use a pinned evaluator. Give it the claim and the span, fix its prompt and model version, and save its verdict as a CI artifact. If you change the evaluator, you have changed the test system, so set a new baseline on purpose.
A model judge has its own known biases. Zheng et al. ("Judging LLM-as-a-Judge", NeurIPS 2023) found that LLM judges favour certain answer positions, longer answers and their own output. On their benchmark the judges still agreed with human raters more than 80% of the time, but that number belongs to their setup, not yours. Before the judge can block a merge, ask two people to label a sample of claim-span pairs (100 is a good start). Compare the judge with them and compute Cohen's kappa, a standard agreement score. On the Landis and Koch scale, 0.61-0.80 means substantial agreement. A sensible rule: below 0.6, the check only reports and never fails the build. Above it, the check blocks critical cases only, until a second round on fresh samples confirms the score.
Set thresholds that make a release decision
The harness reads its limits from policy.json, so those numbers decide what ships. Nobody can give you the right ones. They depend on what a wrong answer costs your users. A support bot that answers account questions needs much stricter rules than an internal document search. Start with a small golden set that people have reviewed. Pick limits that reject the versions you already know are bad but allow the normal noise of a test environment.
Use both overall and per-case rules. The overall citation precision catches slow, broad decline. Each critical case should demand full retrieval recall, at least one valid citation per required claim and zero unsupported claims. Leave ordinary cases in the overall scores. That way a slow decline still shows up, but a harmless wording change does not block a release.
Is all this too much? A judge model could simply read the answer and the retrieved documents and score faithfulness. For a prototype, an internal search tool or a corpus rewritten every week, that shortcut is the right choice. Span contracts break on every edit, and keeping them up costs more than the risk they remove. The picture changes when a wrong citation costs money or trust, when an auditor may ask which revision backed an answer, or when the judge is the same model that writes the answers and shares its blind spots. A simple rule: if an answer can trigger a refund, a compliance decision or an account change, require span-level proof. Otherwise a judge-only score with a tracked trend is enough.
Save the pipeline version, corpus snapshot, embedding model, reranker, prompt version and evaluator version with each result. Without them, a red run tells you something changed but not where to look.
Make citation failure visible in pull requests
A red run helps only if the reviewer can see why it failed. So wire the gate into the pull request itself. Run it after the preview environment has indexed the new corpus and before anything is promoted:
- name: Run citation regression suite
run: RAG_URL=${{ steps.preview.outputs.url }} pytest -q tests/test_citations.py
Attach a readable report to each run: failed case IDs, missing sources, broken span hashes, retrieval ranks, the answer's claims and the cited text. When the expected evidence sits next to the actual span, a reviewer can see at a glance whether the source changed or retrieval got worse. A bare failed assertion with no excerpts just creates extra work.
Never quietly edit the goldens to turn a red run green. A real source update may need a new span, a new accepted source or a new expected answer. That is a content change, and it should be reviewed like one. Put golden-file edits in their own pull request, and ask the author to name the document revision behind each edit.
Ship only when the proof still holds
Once the goldens are protected, grow them from the right end. Start with the customer questions that cause escalations, depend on policy exceptions or lead to costly mistakes. They expose weak retrieval much faster than a pile of easy lookups.
A golden set frozen on launch day ages faster than the system it guards. Every incident, source update and product change shifts what a correct citation looks like. A quarter later, the most useful cases are often ones nobody wrote at the start. Add each real failure back as a new case. For the same reason, the report must name the check that rejected an answer. A wrong address, missing evidence and an unsupported claim point to different parts of the pipeline. A red build that does not say which one leaves the team guessing.