DataSpanner

Data Quality and Observability for LLM Systems (2026-2027 Guide)

By DataSpanner Architecture Team · · 9 min read · AI Infrastructure

Data Quality and Observability for LLM Systems (2026-2027 Guide) — AI Infrastructure cover illustration

Engineering Verification Note (Updated November 2026 for 2027 Planning): Updated with automated evaluation pipelines using DeepEval, Ragas, and OpenTelemetry instrumentation for real-time drift detection.

Large language models have introduced a new category of data quality problems that traditional frameworks weren't designed to handle. When your AI can hallucinate, embed biases from training data, or degrade silently as the world changes, conventional row-count checks and null value assertions are woefully inadequate.

This article examines the specific data quality challenges of LLM systems—both for retrieval-augmented generation (RAG) and fine-tuning—and provides a practical observability framework for detecting and responding to data quality degradation in production.

The LLM Data Quality Problem Space

Traditional data quality focuses on structural correctness: are values within expected ranges? Are required fields populated? Are there duplicates? These checks remain necessary but are no longer sufficient when LLMs are in the loop.

LLM-specific data quality issues include:

  • Semantic drift: Documents in your knowledge base become outdated, causing RAG systems to retrieve and confidently cite stale information
  • Embedding space corruption: Changes to your embedding model cause previously reliable retrieval to fail silently
  • Ground truth disagreement: Labeled training data contains contradictions that corrupt fine-tuned models
  • Prompt injection in training data: Malicious content in scraped data teaches models adversarial behaviors
  • Distribution shift: The world changes, but your knowledge base doesn't

RAG Data Quality: The Three Layers

A RAG system has three distinct data layers, each with its own quality requirements.

Layer 1: Source Documents

The quality of documents before chunking and embedding determines everything downstream. Key checks:

from dataclasses import dataclass
from typing import List
import re

@dataclass
class DocumentQualityReport:
    doc_id: str
    word_count: int
    avg_sentence_length: float
    has_structured_data: bool
    staleness_days: int
    language_confidence: float
    duplicate_of: str | None

def assess_document_quality(doc: dict) -> DocumentQualityReport:
    text = doc["content"]
    words = text.split()
    sentences = re.split(r'[.!?]+', text)
    
    return DocumentQualityReport(
        doc_id=doc["id"],
        word_count=len(words),
        avg_sentence_length=len(words) / max(len(sentences), 1),
        has_structured_data=bool(re.search(r'[\|\{\[\<]', text)),
        staleness_days=(datetime.now() - doc["last_updated"]).days,
        language_confidence=detect_language_confidence(text),
        duplicate_of=find_near_duplicate(text)
    )

# Quality gates
def should_index_document(report: DocumentQualityReport) -> tuple[bool, str]:
    if report.word_count < 100:
        return False, "Too short to be useful"
    if report.staleness_days > 365:
        return False, "Document is over 1 year old"
    if report.language_confidence < 0.85:
        return False, "Language detection confidence too low"
    if report.duplicate_of:
        return False, f"Near-duplicate of {report.duplicate_of}"
    return True, "OK"

Layer 2: Chunks and Embeddings

Chunking strategy profoundly affects retrieval quality. Common issues:

  • Chunk boundary problems: Splitting mid-sentence or mid-concept destroys semantic coherence
  • Context loss: Chunks without surrounding context are semantically ambiguous ("It increased by 30%" — what increased?)
  • Embedding model mismatch: Using a code-optimized embedding model for prose, or vice versa
# Evaluating chunk quality
def evaluate_chunk_coherence(chunks: List[str]) -> dict:
    metrics = {
        "avg_chunk_length": sum(len(c) for c in chunks) / len(chunks),
        "length_variance": statistics.variance([len(c) for c in chunks]),
        "incomplete_sentences": sum(
            1 for c in chunks 
            if not c.strip().endswith(('.', '!', '?', '"', "'"))
        ),
        "chunks_under_100_chars": sum(1 for c in chunks if len(c) < 100),
    }
    return metrics

# Embedding drift detection
def detect_embedding_drift(
    current_embeddings: np.ndarray,
    baseline_embeddings: np.ndarray,
    threshold: float = 0.05
) -> bool:
    """
    Compare distribution of current vs. baseline embeddings.
    High drift suggests the embedding model has changed or data has shifted.
    """
    from scipy.stats import ks_2samp
    
    # Compare distribution of embedding norms
    current_norms = np.linalg.norm(current_embeddings, axis=1)
    baseline_norms = np.linalg.norm(baseline_embeddings, axis=1)
    
    statistic, p_value = ks_2samp(current_norms, baseline_norms)
    return p_value < threshold  # True = drift detected

Layer 3: Retrieval Quality

The ultimate test of your RAG data quality is whether retrieved chunks actually help the model answer questions correctly.

# Retrieval quality evaluation
class RetrievalEvaluator:
    def __init__(self, vector_store, embedding_model):
        self.vector_store = vector_store
        self.embedding_model = embedding_model
    
    def evaluate_retrieval_on_golden_set(
        self, 
        golden_qa_pairs: List[dict]
    ) -> dict:
        """
        golden_qa_pairs: [{"question": str, "relevant_doc_ids": List[str]}]
        """
        hit_at_1 = []
        hit_at_3 = []
        hit_at_5 = []
        mrr_scores = []
        
        for pair in golden_qa_pairs:
            query_embedding = self.embedding_model.encode(pair["question"])
            results = self.vector_store.search(query_embedding, k=5)
            retrieved_ids = [r["doc_id"] for r in results]
            relevant = set(pair["relevant_doc_ids"])
            
            # Hit@K
            hit_at_1.append(1 if retrieved_ids[:1] and retrieved_ids[0] in relevant else 0)
            hit_at_3.append(1 if any(id in relevant for id in retrieved_ids[:3]) else 0)
            hit_at_5.append(1 if any(id in relevant for id in retrieved_ids[:5]) else 0)
            
            # MRR
            for rank, doc_id in enumerate(retrieved_ids, start=1):
                if doc_id in relevant:
                    mrr_scores.append(1 / rank)
                    break
            else:
                mrr_scores.append(0)
        
        return {
            "hit_at_1": sum(hit_at_1) / len(hit_at_1),
            "hit_at_3": sum(hit_at_3) / len(hit_at_3),
            "hit_at_5": sum(hit_at_5) / len(hit_at_5),
            "mrr": sum(mrr_scores) / len(mrr_scores),
        }

LLM Output Quality: What to Measure

Unlike traditional ML models, LLM output quality is inherently subjective and context-dependent. This doesn't mean you can't measure it—it means you need a portfolio of metrics.

Factuality and Groundedness

For RAG systems, every claim in the model's response should be traceable to a retrieved document. Hallucination detection measures the fraction of claims that cannot be attributed to the context.

# Using a smaller LLM to evaluate groundedness
GROUNDEDNESS_PROMPT = """
You are an evaluator checking if an AI response is grounded in the provided context.

Context:
{context}

AI Response:
{response}

For each claim in the AI response, determine if it is:
1. Directly supported by the context
2. Implied by the context
3. Not supported by the context (hallucination)

Return a JSON with:
- "grounded_claims": count of claims in categories 1+2
- "hallucinated_claims": count of claims in category 3
- "groundedness_score": grounded / total (0-1)
"""

def evaluate_groundedness(context: str, response: str, evaluator_llm) -> dict:
    prompt = GROUNDEDNESS_PROMPT.format(context=context, response=response)
    result = evaluator_llm.generate(prompt)
    return parse_json(result)

Semantic Similarity to Ground Truth

When you have reference answers, cosine similarity between response and reference embeddings provides a fast, scalable quality signal.

Response Quality Trends

Track quality metrics over time, not just point-in-time. A gradual degradation in groundedness scores over 30 days is a signal that your knowledge base is becoming stale.

Observability Infrastructure for LLM Systems

The LLM Observability Stack

Production LLM observability requires capturing more than request/response pairs:

@dataclass
class LLMTrace:
    trace_id: str
    timestamp: datetime
    
    # Input
    user_query: str
    retrieved_chunks: List[dict]  # {doc_id, chunk_text, similarity_score}
    prompt: str
    
    # Output  
    response: str
    tokens_used: int
    latency_ms: int
    
    # Quality signals (computed async)
    groundedness_score: float | None = None
    user_feedback: int | None = None  # -1, 0, 1
    retrieval_hit_at_1: bool | None = None
    
    # Metadata
    model_version: str = ""
    embedding_model_version: str = ""
    knowledge_base_version: str = ""

Platforms like Langfuse, Phoenix (Arize), Weights & Biases, and Helicone provide managed observability for LLM traces. For teams with strict data privacy requirements, self-hosted options exist.

Automated Alerting on Quality Regression

# Example alert configuration
alerts:
  - name: groundedness_degradation
    metric: p50_groundedness_score
    window: 1h
    threshold: 0.75
    comparison: less_than
    action: slack_notify + create_incident
    
  - name: retrieval_quality_drop
    metric: hit_at_3_rate  
    window: 24h
    threshold: 0.65
    comparison: less_than
    action: slack_notify + trigger_reindex_eval
    
  - name: high_hallucination_rate
    metric: hallucinated_claims_fraction
    window: 1h
    threshold: 0.15
    comparison: greater_than
    action: pagerduty_alert + auto_rollback_model

Fine-Tuning Data Quality

When fine-tuning LLMs on proprietary data, data quality issues translate directly into model behavior problems. Key practices:

Instruction-Response Pair Quality

# Quality checks for fine-tuning datasets
def validate_training_pair(pair: dict) -> List[str]:
    issues = []
    
    instruction = pair.get("instruction", "")
    response = pair.get("response", "")
    
    # Length checks
    if len(instruction.split()) < 5:
        issues.append("Instruction too short (< 5 words)")
    if len(response.split()) < 10:
        issues.append("Response too short (< 10 words)")
    
    # Content quality
    if response.count("I don't know") > 2:
        issues.append("Response admits too much ignorance")
    if any(pii_pattern.match(response) for pii_pattern in PII_PATTERNS):
        issues.append("Response contains potential PII")
    
    # Consistency
    if "do not" in instruction.lower() and "do not" not in response.lower():
        issues.append("Response may not follow negative instruction")
    
    return issues

# Deduplication before training
def deduplicate_training_data(pairs: List[dict], threshold: float = 0.95) -> List[dict]:
    """Remove near-duplicate training examples using MinHash LSH."""
    from datasketch import MinHash, MinHashLSH
    
    lsh = MinHashLSH(threshold=threshold, num_perm=128)
    unique_pairs = []
    
    for i, pair in enumerate(pairs):
        minhash = MinHash(num_perm=128)
        for word in pair["instruction"].lower().split():
            minhash.update(word.encode("utf8"))
        
        if not lsh.query(minhash):
            lsh.insert(f"pair_{i}", minhash)
            unique_pairs.append(pair)
    
    return unique_pairs

Key Takeaways

  • RAG data quality has three layers: source documents, chunks/embeddings, and retrieval—each requires different quality checks.
  • Embedding drift is silent and catastrophic: Monitor embedding distributions over time, not just indexing success rates.
  • Build a golden evaluation set early: You cannot measure retrieval quality improvement without ground truth.
  • LLM output quality requires a portfolio of metrics: No single metric captures the full picture. Use groundedness, semantic similarity, user feedback, and task-specific metrics together.
  • Fine-tuning data quality controls behavior: Garbage in, garbage model. Invest in deduplication, PII scrubbing, and consistency checks before training.

FAQ

Q: How large should a golden evaluation set be for RAG? A: Start with 100-200 hand-curated question-answer-source triples. This is enough to detect significant regressions. Scale to 500+ for production systems where small improvements matter.

Q: How often should I re-evaluate retrieval quality? A: After every knowledge base update, every embedding model change, and on a scheduled basis (weekly or biweekly) to catch silent degradation from world-knowledge drift.

Q: What's the cheapest way to detect hallucinations at scale? A: Use a smaller, faster model (GPT-4o-mini, Llama 3 8B) as an evaluator on a random sample of production traces. Sample 1-5% of traffic for cost-effective continuous monitoring.