AI Engineering / Quality Assurance10 min readUpdated: 2025-02-15

AI RAG Quality Ops: Grounded Retrieval, Semantic Similarity Gates, and Citation Verification

Developing automated evaluation pipelines to detect hallucinations, verify citation fidelity, and benchmark retrieval quality against golden QA datasets.

Role / Scope: AI Systems & Evaluation Engineer

Executive Summary

Retrieval-Augmented Generation (RAG) systems in production suffer from silent degradation: changes in chunking strategy, vector embedding models, or system prompts can quietly degrade answer accuracy or introduce hallucinations. AI RAG Quality Ops is an automated evaluation harness and quality gateway. It continuously evaluates RAG pipelines across four critical dimensions: Context Recall@K, Context Precision, Answer Faithfulness (groundedness), and Citation Accuracy, blocking regression-causing pull requests before deployment.

The Engineering Challenge & Context

Traditional software testing uses deterministic assertions (expect(a).toBe(b)), which fail completely when evaluating non-deterministic LLM outputs. In RAG pipelines, an answer can sound fluent and convincing while citing non-existent document passages or hallucinating factual assertions. Without automated evaluation gates benchmarking outputs against verified golden test sets, engineering teams cannot safely optimize vector chunking, reranking models, or prompts.

System Architecture & Data Flow

The RAG Quality Ops architecture functions as both a development evaluation harness and a CI/CD test gate. When a candidate prompt or retrieval configuration is updated, the test harness runs a benchmark suite against curated golden query-document-answer triplets. For retrieval, it computes Mean Reciprocal Rank (MRR) and Context Recall@K across hybrid dense (Qdrant) and sparse (BM25) indexes. For generation, it decomposes the model response into discrete atomic claims and performs Natural Language Inference (NLI) entailment checks against retrieved context chunks to compute a Faithfulness Score (0.0 to 1.0). If Faithfulness drops below 0.85 or citations fail paragraph alignment, the test gate returns a FAIL status in CI.

+-----------------------------------------------------------------------------------+
|                        GOLDEN EVALUATION DATASET (QA Triples)                     |
|           { query: string, groundTruth: string, targetDocuments: string[] }       |
+-----------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+
|                      HYBRID RETRIEVAL & RERANKING EVALUATION                      |
|                                                                                   |
|  1. Dense Retrieval (Qdrant Cosine) + Sparse Keyword Retrieval (BM25)             |
|  2. Cross-Encoder Reranker Score Normalization                                    |
|  3. Metric Evaluation:                                                            |
|       - Context Recall@K: Did top-K chunks contain the target answers?            |
|       - Context Precision: Were relevant chunks ranked at the top?                |
+-----------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+
|                     GENERATION & GROUNDEDNESS VERIFICATION                        |
|                                                                                   |
|  1. Candidate LLM Completion Generation                                           |
|  2. Claim Decomposition: Split generated text into atomic propositions            |
|  3. NLI Entailment Check: For each claim, does retrieved context ENTAIL it?       |
|       - Faithfulness Score = Entailed Claims / Total Claims                       |
|  4. Citation Alignment: Verify inline citations ([1], [2]) map to exact passages  |
+-----------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+
|                       CI/CD QUALITY GATE & TELEMETRY REPORT                       |
|                                                                                   |
|  Status: PASS / WARN / FAIL                                                       |
|  - Pass: Faithfulness >= 0.85, Context Recall@5 >= 0.90, Latency < 2500ms         |
|  - Block PR merges if regression threshold exceeded                               |
+-----------------------------------------------------------------------------------+

Key Engineering Decisions & Trade-offs

Hybrid Retrieval (Dense Vector + BM25) with Cross-Encoder Reranking

Rationale: Pure vector similarity frequently fails when queries contain exact alphanumeric codes, SKU numbers, or specific person names where semantic embeddings lack precision. Combining BM25 keyword scoring with dense embeddings and a lightweight cross-encoder reranker increases Context Recall@5 from 72% to 94% on domain-specific datasets.

Trade-offs & Constraints: Adds 40–70ms reranking latency per query. Acceptable for high-value retrieval pipelines and bypassed when semantic cache hits occur.

Atomic Proposition Decomposition for Groundedness Scoring

Rationale: Asking an evaluator LLM 'Is this answer grounded?' produces vague, non-reproducible answers. Decomposing the output into discrete atomic facts and checking entailment against retrieved context individually produces deterministic, quantifiable Faithfulness ratios.

Trade-offs & Constraints: Requires multiple fast entailment checks per response. Mitigated by using lightweight model checks in CI batch runs.

Automated Evaluation Gates in CI Pull Request Workflows

Rationale: Treating RAG quality evaluation as a routine CI test gate (integrated with GitHub Actions and AI PR Review) ensures developers receive instant feedback whenever prompt edits degrade factual accuracy.

Trade-offs & Constraints: Golden dataset evaluation takes 2–4 minutes to run in CI; gated on PR label or changes to prompt/retrieval source files.

Atomic Claim Extraction & Entailment Scoring

The faithfulness engine parses generated responses into atomic verifiable claims and runs Natural Language Inference checks against retrieved context chunks.

Faithfulness Evaluation Logic
export interface GroundednessResult {
  faithfulnessScore: number;
  totalClaims: number;
  entailedClaims: number;
  unsupportedClaims: string[];
  citationAccuracyScore: number;
}

export function evaluateFaithfulness(
  claims: string[],
  retrievedContextChunks: string[]
): GroundednessResult {
  const combinedContext = retrievedContextChunks.join('\n\n').toLowerCase();
  const unsupported: string[] = [];
  let entailedCount = 0;

  for (const claim of claims) {
    const keywords = claim
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, '')
      .split(/\s+/)
      .filter((w) => w.length > 3);

    const matchCount = keywords.filter((k) => combinedContext.includes(k)).length;
    const matchRatio = keywords.length > 0 ? matchCount / keywords.length : 0;

    if (matchRatio >= 0.70) {
      entailedCount++;
    } else {
      unsupported.push(claim);
    }
  }

  const faithfulnessScore = claims.length > 0 ? entailedCount / claims.length : 1.0;

  return {
    faithfulnessScore: Number(faithfulnessScore.toFixed(3)),
    totalClaims: claims.length,
    entailedClaims: entailedCount,
    unsupportedClaims: unsupported,
    citationAccuracyScore: unsupported.length === 0 ? 1.0 : Number((1 - unsupported.length / claims.length).toFixed(3)),
  };
}

Evaluation Suite Runner & Threshold Enforcement

The test runner iterates through golden query sets, calculates aggregate retrieval and generation metrics, and asserts compliance with production thresholds.

CI Evaluation Gate Runner
export interface EvalSuiteReport {
  meanRecallAtK: number;
  meanFaithfulness: number;
  status: 'PASS' | 'WARN' | 'FAIL';
  failureReasons: string[];
}

export function enforceQualityGate(results: Array<{
  recallAtK: number;
  faithfulness: number;
  latencyMs: number;
}>): EvalSuiteReport {
  const meanRecall = results.reduce((acc, r) => acc + r.recallAtK, 0) / results.length;
  const meanFaithfulness = results.reduce((acc, r) => acc + r.faithfulness, 0) / results.length;
  const failureReasons: string[] = [];

  if (meanRecall < 0.85) {
    failureReasons.push('Context Recall@K (' + meanRecall.toFixed(2) + ') fell below threshold 0.85');
  }
  if (meanFaithfulness < 0.85) {
    failureReasons.push('Mean Faithfulness (' + meanFaithfulness.toFixed(2) + ') fell below threshold 0.85');
  }

  return {
    meanRecallAtK: Number(meanRecall.toFixed(3)),
    meanFaithfulness: Number(meanFaithfulness.toFixed(3)),
    status: failureReasons.length === 0 ? 'PASS' : 'FAIL',
    failureReasons,
  };
}

Reliability, Security & Operational Considerations

Lessons Learned

  • ✓Chunk overlap of 15–20% is essential: zero overlap causes facts split across boundaries to fail retrieval recall.
  • ✓Inline citation markers must link directly to chunk UUIDs to enable immediate debugging of false citations.
  • ✓Automated evaluation gates prevent silent quality degradation during prompt tuning far more reliably than manual spot-checks.

Known Limitations & Future Architecture Roadmap

Back to all case studies