{"slug": "rag-systems-need-separate-tests-for-retrieval-and-generation", "title": "RAG Systems Need Separate Tests for Retrieval and Generation", "summary": "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.", "body_md": "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.\n\nIn 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.\n\nTeams 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.\n\n**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.”\n\nNobody 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.”\n\nIn 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.\n\nTeams often start tuning prompts when answers go wrong, but a prompt cannot fix an answer built on the wrong evidence.\n\n**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.”\n\n``` python\ndef 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)\n```\n\nHere 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.\n\n``` php\nimport 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\n```\n\nStore 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.\n\nOnce 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.\n\n**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.”\n\n``` python\nimport 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),    }\n```\n\nA 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.\n\nA knowledge base that changes daily turns the index into a release artifact, and diffing generated answers between versions produces mostly noise.\n\n**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.\n\n``` python\nTHRESHOLDS = {\"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))\n```\n\nThe 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.\n\nMost 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.\n\n**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.”\n\nThat 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.\n\n``` php\ndef 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\n```\n\nBecause 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.\n\n**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.”\n\n``` php\nimport 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(\"- \")]\n```\n\nEach 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.\n\nA gate checks the system at the moment of change, and retrieval can still drift between publishes as the questions customers ask shift over time.\n\n**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.\n\n**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.”\n\nA 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.\n\n**Credits for Commentary**\n\n[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.", "url": "https://wpnews.pro/news/rag-systems-need-separate-tests-for-retrieval-and-generation", "canonical_source": "https://pub.towardsai.net/rag-systems-need-separate-tests-for-retrieval-and-generation-97872d4770fa?source=rss----98111c9905da---4", "published_at": "2026-12-04 23:01:03+00:00", "updated_at": "2026-12-04 23:13:29.504692+00:00", "lang": "en", "topics": ["ai-agents", "large-language-models", "ai-safety"], "entities": ["Goldman Sachs", "Vijay Kumar Sridharan", "Apple Card", "Apple"], "also_reported_by": [], "takeaway": "Split RAG evaluation into separately owned context recall, context precision and index freshness scores, and store a SHA-256 content hash per chunk so a stale-document check re-embeds changed sources before recall is measured.", "recommendation": {"advice": "Hash each source document when you embed it and run a stale-document check before every eval, re-embedding any changed doc first so recall scores reflect the index customers actually query.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/rag-systems-need-separate-tests-for-retrieval-and-generation", "markdown": "https://wpnews.pro/news/rag-systems-need-separate-tests-for-retrieval-and-generation.md", "text": "https://wpnews.pro/news/rag-systems-need-separate-tests-for-retrieval-and-generation.txt", "jsonld": "https://wpnews.pro/news/rag-systems-need-separate-tests-for-retrieval-and-generation.jsonld"}}