RAGops is a data platform problem
Retrieval-augmented generation looks like a model feature and behaves like a data platform. The model only ever sees what the pipeline hands it, so answer quality is bounded by ingestion hygiene, chunk boundaries, embedding coverage, and index freshness long before prompt wording enters the picture. RAGops is the practice of owning those stages with the same rigour a data engineering team would apply to an analytics warehouse: explicit contracts, idempotent jobs, measurable quality, and alerts when any stage drifts.
The pipeline has six stages in practice. Documents are ingested and normalised. Normalised text is chunked into retrieval units. Chunks are embedded into vectors. Vectors and metadata are written to an index. Queries are embedded and matched at request time. Matched chunks are assembled into context for generation. Each hand-off has its own failure mode, and each failure looks identical from the user's seat: an answer that is confident, fluent, and wrong.
Diagnosing those failures requires instrumentation per stage rather than one end-to-end score. Ingestion reports documents processed and rejected. Chunking reports size distributions. Indexing reports upsert counts and staleness. Retrieval reports ranked metrics against a labelled query set. Only when you can point at a stage does tuning become engineering instead of guesswork.
Ingestion: contracts at the document boundary
Ingestion is where quality is won or lost, and the single most useful decision is content hashing. Give every document a stable hash over its extracted text; if the hash is unchanged on the next run, skip it entirely. This makes ingestion idempotent, allows incremental refreshes instead of nightly full rebuilds, and gives you a lineage key you can trace from a bad answer back to the source file.
The second decision is what to reject. Boilerplate, navigation chrome, legal footers, and documents under a minimum length all degrade retrieval because they embed as near-duplicates of each other and crowd out real content. A cleaning pass that strips repeated whitespace, normalises punctuation, and drops sub-fifty-character fragments removes a surprising share of the noise.
Metadata travels with the text from the first moment: source URI, page or section, title, owner, last-updated timestamp, and access-control tags. Retrieval that cannot filter on permissions will eventually return a document to someone who should not see it, and no prompt can un-say that.
import hashlib
import re
from dataclasses import dataclass, field
@dataclass
class Document:
doc_id: str
content: str
metadata: dict = field(default_factory=dict)
@property
def content_hash(self) -> str:
return hashlib.sha256(self.content.encode()).hexdigest()
class IngestionPipeline:
MIN_CHARS = 50
def __init__(self, extractors: dict):
self.extractors = extractors
self.seen_hashes = {}
self.stats = {"ingested": 0, "skipped": 0, "rejected": 0}
def ingest(self, source: str, kind: str) -> list[Document]:
if kind not in self.extractors:
raise ValueError(f"no extractor registered for {kind}")
accepted = []
for raw in self.extractors[kind].load(source):
doc = self._clean(raw)
if len(doc.content) < self.MIN_CHARS:
self.stats["rejected"] += 1
continue
previous = self.seen_hashes.get(doc.doc_id)
if previous == doc.content_hash:
self.stats["skipped"] += 1
continue
self.seen_hashes[doc.doc_id] = doc.content_hash
self.stats["ingested"] += 1
accepted.append(doc)
return accepted
@staticmethod
def _clean(doc: Document) -> Document:
text = re.sub(r"\s+", " ", doc.content).strip()
text = re.sub(r"[ \t]+", " ", text)
doc.content = text
doc.metadata.setdefault("char_count", len(text))
return doc
Chunking: the decision that sets the ceiling
Chunking determines the unit of retrieval, and therefore the granularity of every answer. Too large and the embedding averages over several topics, so similarity scores blur and the retriever returns a paragraph that contains the answer somewhere. Too small and chunks lose the surrounding context needed to interpret pronouns, tables, and definitions, so the generator receives fragments it must stitch together correctly.
Overlap is the standard mitigation at fixed sizes: slicing with a step smaller than the chunk size keeps boundary-straddling sentences in two places. Beyond that, the strategy should follow the document structure. Recursive splitting on paragraph, then sentence, then word boundaries preserves prose coherence. Table-aware chunking keeps a header row attached to every slice. Code chunking should respect function boundaries rather than character counts.
| Strategy | Typical size | Preserves structure | Best suited for |
|---|---|---|---|
| Fixed token windows | 300â512 tokens | No | Homogeneous plain text |
| Recursive character split | Variable | Partly | Mixed documentation |
| Sentence grouping | 3â8 sentences | Prose only | FAQ and knowledge base |
| Semantic segmentation | Variable | Topic | Long reports |
| Structure-aware (tables, code) | Element-wise | Yes | Technical corpora |
Whatever you choose, record chunk size and strategy in metadata. When retrieval quality changes after a re-embed, you need to know whether the model moved or the boundaries did.
Embedding and indexing workflows
Embedding is the stage most often treated as a one-time script. In operation it is a versioned batch job: the model identifier, its revision, the pooling method, and the normalisation choice all belong in the index metadata, because mixing vectors from two embedding models produces a space in which distances are meaningless. Re-embedding must be a full, atomic migration â write to a new index, backfill, then swap the alias â never an incremental mix of two models in one collection.
Batch size matters for both cost and recall. Very large batches reduce throughput but can degrade quality for models with length-dependent pooling; very small batches waste the provider's latency budget. Normalising embeddings at write time lets you use dot product at query time, which is measurably cheaper than recomputing cosine on every candidate.
class EmbedAndIndex:
def __init__(self, model, index, batch_size: int = 64):
self.model = model
self.index = index
self.batch_size = batch_size
def run(self, chunks: list[Document], embedding_version: str) -> dict:
written = 0
for start in range(0, len(chunks), self.batch_size):
batch = chunks[start:start + self.batch_size]
vectors = self.model.encode(
[c.content for c in batch],
normalize_embeddings=True,
batch_size=self.batch_size,
)
self.index.upsert([
{
"id": c.doc_id,
"values": vec.tolist(),
"metadata": {
**c.metadata,
"text": c.content,
"embedding_version": embedding_version,
},
}
for c, vec in zip(batch, vectors)
])
written += len(batch)
return {"upserted": written, "version": embedding_version}
Retrieval quality metrics you can act on
End-to-end answer scores tell you that something is wrong; retrieval metrics tell you where. Recall@K answers whether the evidence was fetched at all â if recall@5 is low, no generator can rescue the answer, and tuning prompts is wasted motion. Precision@K tells you whether the fetched set is dominated by distractors that push the real passage below the context limit. Mean reciprocal rank rewards placing the useful passage first, which matters because models attend unevenly across long contexts. Normalised discounted cumulative gain extends that idea to queries with several relevant passages.
Build a labelled query set of one to two hundred questions with known source passages, drawn from real support tickets or search logs rather than written by the team that built the system. Re-run it on every ingestion or embedding change and store the scores next to the pipeline version. That single habit converts "the answers feel worse this week" into a bisectable regression.
Keeping the index fresh without reindexing the world
Freshness policies should be per source, not global. A pricing page changes hourly; an architecture handbook changes quarterly. Driven by the content hash from ingestion, only changed documents are re-chunked, re-embedded, and upserted, while deletions and permission changes propagate through a tombstone pass. Track staleness explicitly â the age of the oldest document still in the index â and alert when it exceeds the source's declared refresh interval.
Diagnosing a bad answer: retrieval or generation?
When an answer is wrong, run the retrieved context past a human before blaming the model. If the supporting passage was not retrieved, the defect is upstream: fix chunking, embedding version, or query rewriting. If the passage was retrieved and the model still misread it, the defect is downstream: fix the prompt, the context assembly order, or the generator itself. This single triage rule prevents the most common and most expensive wasted effort in RAG operations â endlessly re-prompting a retrieval problem.
Best Practices
- Hash document content at ingestion so refreshes are idempotent and bad answers can be traced to a source file.
- Attach source, owner, timestamp, and access-control metadata to every chunk before it reaches the index.
- Choose chunking strategy from document structure, then record the strategy and size in metadata.
- Migrate embedding models by building a new index and swapping an alias â never mix two models in one collection.
- Maintain a labelled query set and track recall@K, precision@K, and MRR beside every pipeline version.
- Run per-source freshness policies instead of a single global reindex schedule.
Key Takeaways
- RAG quality is bounded by ingestion, chunking, and indexing â the model only receives what the pipeline delivers.
- Content hashing makes ingestion idempotent and gives every answer a traceable lineage key.
- Chunk size trades topical purity against contextual completeness; overlap and structure-aware splitting soften the boundary.
- Embedding version must be uniform across an index; mixed vector spaces silently destroy distance semantics.
- Retrieval metrics localise failures: low recall means fetch problems, good recall with bad answers means generation problems.
- Triage every wrong answer by inspecting retrieved context first â it separates upstream defects from downstream ones.