RAG Systems Need Separate Tests for Retrieval and Generation Goldman Sachs VP of Software Engineering Vijay Kumar Sridharan, who builds and evaluates the conversational AI behind Apple Card's voice and chat support serving more than 12 million US cardholders, says RAG pipelines need separate tests for retrieval and generation after a knowledge-base edit caused a support bot to tell a customer their rate was 4 percent when the source only said rates go up to 4 percent. Sridharan recommends tracking three independently owned scores — context recall, context precision and index freshness — and gating knowledge-base updates like code releases, noting that a content-hash freshness check would have caught the error without any model. "Retrieval looked fine in demos, but a knowledge-base update changed a source doc and the bot kept confidently stating a specific figure the source no longer supported," Sridharan said. A credit card support bot tells a customer that their rate is 4 percent. Because the knowledge base article behind that answer was edited the week before and now says rates go up to 4 percent, so the bot sounds certain, matches the old document and gives this customer a figure nobody promised them. In consumer finance, a wrong rate quoted to a cardholder is a compliance problem as much as a quality one. And it usually comes from two failures that look like one on a dashboard, a retrieval layer serving stale context and a generation layer turning a qualified statement into a specific promise. Teams that test those two layers separately, and gate every knowledge base update the way they gate a code release, are far more likely to catch these answers before customers do. The rest of this piece shows how, with Python you can adapt to an existing RAG pipeline. Vijay Kumar Sridharan , VP of Software Engineering at Goldman Sachs, builds and evaluates the conversational AI behind Apple Card’s voice and chat support, which serves more than 12 million US cardholders. The 4 percent answer came from his team’s experience. “Retrieval looked fine in demos, but a knowledge-base update changed a source doc and the bot kept confidently stating a specific figure the source no longer supported,” he explains. “It passed every demo because demos use fresh, hand-picked queries.” Nobody was checking grounding on every answer, so the error kept appearing in low-volume intents until someone caught it. Sridharan now treats each layer as its own system with its own tests. “Retrieval failure, generation failure, index freshness failure, they each behave differently,” he says. “You need to instrument, gate and monitor each independently. Eyeballing conflates those three into a single, ambiguous ‘looks okay’, which is exactly why it misses the cases which kill your product.” In practice that means three scores on the dashboard instead of one, each with an owner. Retrieval quality belongs to whoever runs the index, freshness belongs to whoever publishes content into it, and faithfulness belongs to whoever owns the prompt and the model. Teams often start tuning prompts when answers go wrong, but a prompt cannot fix an answer built on the wrong evidence. Sridharan’s first metric is context recall , meaning whether the chunk that contains the answer shows up in the top results for a labeled set of questions. “Drop recall here, and nothing in your prompt tuning saves you,” he says. “You cannot ground on evidence you never saw.” python def recall at k retriever, labeled set, k=5 : """Each row looks like {"query": ..., "answer chunk ids": ... }.""" hits = 0 for row in labeled set: results = retriever.search row "query" , k=k if any chunk.id in row "answer chunk ids" for chunk in results : hits += 1 return hits / len labeled set Here retriever.search stands in for your vector store's query call. His team also tracks context precision , which measures how much irrelevant text dilutes the prompt, and index freshness , which checks whether a source document changed without being re-embedded. Freshness is the check most likely to have caught the 4 percent answer, and it needs no model at all. php import hashlibdef stale documents source docs: dict, index metadata: dict - list: """Return IDs whose current text differs from what was embedded.""" stale = for doc id, text in source docs.items : current = hashlib.sha256 text.encode "utf-8" .hexdigest if index metadata.get doc id, {} .get "content sha256" = current: stale.append doc id return stale Store the content hash next to each chunk when it is embedded, and run this check before every evaluation. Any document it returns gets re-embedded first, so the recall score describes the index customers will actually query. Once retrieval returns the right evidence, the open question is whether the answer stays inside it, and an overall quality score hides answers that mostly do. Sridharan breaks every answer into atomic claims and checks each one against the retrieved context with natural language inference, labeling it Entailed, Contradicted or Neutral. “If a single Contradicted or Neutral, we fail the response,” he explains. “This is what catches the subtle partial hallucination of one unsupported claim in an otherwise valid answer, masked by an overall 1 to 5 quality score.” python import refrom sentence transformers import CrossEncodernli = CrossEncoder "cross-encoder/nli-deberta-v3-base" Label order from the model cardLABELS = "contradiction", "entailment", "neutral" def split into claims answer: str - list: A sentence split keeps the example short. Production systems usually ask an LLM to rewrite the answer as atomic, self-contained claims. sentences = re.split r" ?<= . ? \s+", answer return s.strip for s in sentences if s.strip def label claim claim: str, chunks: list - str: scores = nli.predict chunk, claim for chunk in chunks labels = {LABELS i for i in scores.argmax axis=1 } if "entailment" in labels: return "Entailed" if "contradiction" in labels: return "Contradicted" return "Neutral"def check answer answer: str, chunks: list - dict: claims = {c: label claim c, chunks for c in split into claims answer } entailed = sum label == "Entailed" for label in claims.values return { "claims": claims, "faithfulness": entailed / max len claims , 1 , "passed": entailed == len claims , } A chunk that says rates go up to 4 percent does not entail the claim that this customer’s rate is 4 percent, so the claim should come back Neutral or Contradicted and the whole answer fails. Run this on the evaluation set for every release and on a sample of production answers, since scoring every claim of every response adds cost a busy support channel may not need. A knowledge base that changes daily turns the index into a release artifact, and diffing generated answers between versions produces mostly noise. Sridharan gates on scores instead. “Treat the prompt, model version, and index as three versioned artifacts,” he says. “Any change to any artifact means we trigger the same gate.” The gate re-runs a fixed set of golden queries plus synthetic adversarial queries that probe stale and edge-case retrieval, and it blocks the release if recall or faithfulness falls below a threshold. “Failing this test is not a judgment call,” he adds. python THRESHOLDS = {"recall at 5": 0.92, "faithfulness": 0.98}def release gate metrics: dict, versions: dict - None: """versions names the prompt, model and index behind these metrics.""" problems = f"{name} {metrics name :.3f} is below {limit}" for name, limit in THRESHOLDS.items if metrics name < limit failed = metrics "failed answers" if failed: problems.append f"{failed} answers had an unsupported claim" if problems: raise SystemExit f"Blocked release {versions}: " + "; ".join problems The thresholds here are examples, so set yours from a few weeks of scores on the current index. But a gate only protects customers if every path into the index goes through it, and the 4 percent answer came from a document edit that no code review ever saw. Most teams already run code through CI before it reaches customers, while knowledge base content often goes straight from an editor’s save button into the production index. Shahid Ali Khan , Principal Engineer for DevOps at TestMu AI, an AI-native software testing platform formerly known as LambdaTest, sees that gap in almost every RAG rollout he reviews. “Most teams put every code change through CI and then let the knowledge base update straight into production,” Khan explains. “The index changes what customers hear just as much as a deploy does, so it should go through the same pipeline, with a staging copy, an evaluation gate and a one-step rollback. If you cannot roll the index back in minutes, you are not really releasing it, you are just hoping.” That pipeline is easier to build than it sounds. Build each new index next to the current one, run the gate against it, and switch customers over only after it passes. Most search engines and vector stores, including OpenSearch and Qdrant, support aliases, so the switch and the rollback are each a single pointer change. php def publish index new version: str, store, evaluate - str: """store and evaluate stand in for your vector store and eval suite.""" store.build new version metrics = evaluate index=new version release gate metrics, {"index": new version} raises if the gate fails previous = store.alias target "kb-prod" store.point alias "kb-prod", new version return previous keep this version ready for a one-step rollback Because the gate raises before the alias moves, a failing index never reaches customers. And the previous version stays one call away if scores on production traffic start to fall after the switch. Khan also pushes teams to build the adversarial set from the content that just changed, instead of relying on a generic list of tricky questions. “The cheapest win is to build part of the adversarial set from the diff itself,” he says. “When a policy page changes, write questions that only the old version would have answered, and check that the bot stops answering them. Those are exactly the questions a stale index gets wrong, and they are the ones a fixed golden set will never contain.” php import difflibimport redef sentences text: str - list: return s.strip for s in re.split r" ?<= . ? \s+", text if s.strip def removed sentences old text: str, new text: str - list: """Sentences the latest edit removed from a source document.""" diff = difflib.ndiff sentences old text , sentences new text return line 2: for line in diff if line.startswith "- " Each removed sentence becomes the seed for a question whose correct answer changed with the edit, written by a reviewer or drafted by an LLM and then reviewed. If the rate page dropped “The standard rate is 4%,” the probe asks the bot for the customer’s rate, and the gate checks that the answer now carries the qualified wording from the new page. A gate checks the system at the moment of change, and retrieval can still drift between publishes as the questions customers ask shift over time. Sridharan’s team covers that gap by re-scoring a rolling 2 to 5 percent of production traffic with the same retrieval and claim checks and trending the results over time. Sampling by a hash of the conversation ID keeps the slice stable across days, and an alert on a falling trend catches gradual decline long before any single answer fails the gate. In a bank, redact personal data from those conversations before they reach any evaluator, the same way any other tool that touches customer records would. Khan wants that alert treated like any other production signal. “When grounding scores start falling, the alert should page the same on-call engineer who gets paged when the service goes down,” he says. “An unsupported answer in a bank’s support bot is a production incident. It needs an owner, a runbook and the authority to roll the index back without waiting for the content team to find the bad edit.” A practical first step is to pick the ten intents where a wrong figure would do the most harm, label the chunk that answers each one and add the freshness check to the publishing job. Then put the claim check and the release gate in front of the index alias, so the next knowledge base update reaches customers only after both pass. Credits for Commentary RAG Systems Need Separate Tests for Retrieval and Generation https://pub.towardsai.net/rag-systems-need-separate-tests-for-retrieval-and-generation-97872d4770fa was originally published in Towards AI https://pub.towardsai.net on Medium, where people are continuing the conversation by highlighting and responding to this story.