Artificial Intelligence
Maintainable RAG project structure: split by what each change invalidates
Someone changes the chunk size of a RAG system and tweaks the prompt on the same day. By the next morning the answers are worse. Which change did it? Does everything need re-indexing? Are last week's evaluations still valid? When the project is a single file, nobody can tell without reading all of it again.
RAG (Retrieval-Augmented Generation) means, in the words of Barnett and co-authors, “finding documents that semantically match a query and then passing the documents to a large language model”. You can wire that path in a few lines, and it holds up as long as nobody touches it. Once it grows, one folder per step is the tempting layout. That describes the flow, but it says nothing about which parts change together.
This article argues for a different criterion: split by what each change invalidates. We measured neither quality nor latency. The few quality figures here belong to vendors and are labeled as theirs, and where something is our opinion, we say so.
Why the steps are not the modules
In 1971, Parnas suggested starting somewhere else: “We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change.” He also spelled out what follows: “Since, in most cases, design decisions transcend time of execution, modules will not correspond to steps in the processing.”
The embedding model, which turns text into vectors, runs at indexing time and again at query time. Give each path its own folder, let each folder pick its model, and one decision now lives in two places with nothing keeping them in step.
One limit applies to any structure, ours included. Sculley and co-authors named it CACE: “Changing Anything Changes Everything”. It reaches hyper-parameters, data and “essentially every other possible tweak”. It was written about machine learning models; applying it to RAG is our reading. A new chunk size can alter an answer even when the prompt stays put. Folders organize code; they don't isolate behavior.
What each change invalidates
We sort changes into three groups: what forces a re-index, what only forces a new evaluation, and what never touches a model. The table is Nippysoft's opinion, inferred from those sources and from the Gemini and Haystack documentation. None of them publishes it in this form, and it is not a measured result.
| Change | What it invalidates | What to run again |
|---|---|---|
| Embedding model, document prefix | The whole index | Re-index; evaluate retrieval and generation |
| Chunk size, overlap, parser | The whole index, or the documents that parser handles | Re-index; evaluate retrieval and generation |
| Text added to each chunk before embedding, or the prompt and model that generate it | The whole index | Re-index and evaluate |
| Query prefix | Nothing in the vectors; the manifest does change | Rewrite the manifest; evaluate retrieval and generation |
| A document edited or deleted | Its chunks | Re-index it and delete the old chunks |
| Top-k, filters on fields already indexed, reranking | Nothing in the index | Evaluate retrieval and generation |
| Filter on a new field | That field, in every document | Load it or rebuild, depending on the store |
| Answer prompt, answer model, output format | Nothing in the index | Evaluate generation with a fixed context |
| Endpoint, authentication | Nothing about the model | API tests |
Part of this shows in the signature of build_index: it receives neither the answer prompt nor k, so they cannot end up in the index.
# rag/ingest.py (signature only)
def build_index(
documents: dict[str, str],
embedder: Embedder,
chunk_size: int,
chunk_overlap: int,
cache: dict[str, Vector] | None = None,
parser_version: str = "none",
enrichment_version: str = "none",
) -> tuple[VectorIndex, int]:
The third row is the sneaky one. Anthropic's Contextual Retrieval adds a piece of context to each chunk “before embedding”. It is pitched as a retrieval improvement, and the vendor reports that, combined with BM25 and reranking, it “reduced the top-20-chunk retrieval failure rate by 67% (5.7% → 1.9%)”. That number is theirs and we did not reproduce it. What matters for the layout is something else: despite the name, it lives in ingestion and forces a re-index.
The contract that crosses two steps
Whatever must match between writing the index and querying it is a contract. Microsoft states it as a condition: “To ensure accurate results, use the same embedding model for indexing and querying.” And Gemini's documentation, on moving to gemini-embedding-2: “you must re-embed all of your existing data.”
The model is only part of it. The nomic-embed-text-v1.5 card warns that “the text prompt must include a task instruction prefix”, while the bge-small-en-v1.5 card says “no instruction needs to be added to passages”. Each model brings its own rules, and scattering them through the code invites forgetting one. We keep them in a manifest, the IndexSpec object, stored with the index, and the query path refuses to start when it doesn't match. We don't know how far quality drops when this contract breaks: we didn't measure it.
Switching models without downtime
A post by Google AI on DEV, a blog rather than documentation, sums up the problem: “Existing vectors in your database are incompatible with queries from the new model.” One way out is a parallel column holding the new vectors, which is what that post proposes. The other is an alias: Qdrant explains that “it is possible to build a second collection in the background and then switch alias from the old to the new collection.”
Picture an internal knowledge base moving to a new model. The new index is built on the side with its own manifest, evaluated against the same questions, and the alias flips last. In our opinion that last step is the delicate one: the alias and the query-side model have to change together. If only one changes and the dimensions match, the store won't complain. And a Retriever already created doesn't check again: recreate it when the alias moves.
The modules and the reason for each
The sample layout is one package. It starts with what the stages share. The rest does follow the data's path, but no file picks its own model.
rag/
contracts.py # Shared types and the Embedder and Llm protocols
chunking.py # Index time: splits documents
ingest.py # Index time: builds the index
index_store.py # Keeps vectors next to the spec that produced them
retrieval.py # Query time: checks the contract and searches
prompts/ # Versioned prompt files
answering.py # Checks the citations in a model reply
pipeline.py # The only place that knows the query-time order
evals/
retrieval_metrics.py
tests/
doubles.py
hostile.py
- Contract. Every stage imports
contracts.py, which also holds theEmbedderandLlmprotocols. Sculley and co-authors give the reason: “An important strategy for combating glue-code is to wrap black-box packages into common API's.” - Ingestion. It runs in batches. Haystack tells “indexing pipelines” apart from “query pipelines” and notes that one pipeline can combine both, and the Azure sample repository keeps
app/backend/prepdocslib/apart fromapp/backend/approaches/. - Separate store. In the sample it is a concrete class,
VectorIndex. With a real product, an interface lets you replace it and migrate with an alias or a parallel column. - Retrieval. Top-k, filters on fields already indexed and reranking evolve without touching the index.
- Prompts as versioned files. In the sample, nothing at indexing time reads them.
- Reply check. It tells two facts apart: the model replied, and its citations are in what was retrieved.
- Composition root.
pipeline.pyis the only place that knows the order of the query-time stages: changing that order touches one file. - Evaluation outside the package. What ships carries no questions or results. Azure has
evals/ground_truth.jsonl,evals/evaluate_config.jsonandevals/results/.
Something that isn't a module is missing: per-stage traces. OpenTelemetry defines a gen_ai.retrieval span with Development status, so that convention can still change.
What over-separating costs
We didn't measure what a network boundary or an extra layer adds, so these are arguments, not numbers:
- A network boundary is not a folder. Fowler: “microservices introduce complexity on their own account. This adds a premium to a project's cost and risk”.
- Boundaries are found late. Fowler again: “even experienced architects working in familiar domains have great difficulty getting boundaries right at the beginning.”
- A linear flow doesn't need Modular RAG. Gao and co-authors propose “decomposing complex RAG systems into independent modules and specialized operators”. We find that useful when the flow branches.
Our opinion: one package and one process to begin with, with modules and contracts. The first candidate for physical separation is ingestion, because it runs in batches. Anything else needs a concrete reason: different scale, another owning team, or data isolation.
How to test each piece
Google's rule 5 states the idea: “Test the infrastructure independently from the machine learning.”
| Piece | What is tested | Check | Model? |
|---|---|---|---|
| Chunking | Boundaries, overlap, offsets that rebuild the text | Unit tests | No |
| Index contract | Rejects a different model, dimension or prefix | Contract tests | No |
| Retrieval | Whether it brings the right text, with annotated references | Recall@k, precision@k, MRR, token IoU | Embeddings only |
| Retrieval without fine annotations | Context ordering and coverage | Context Precision, Context Recall | Yes, LLM judge |
| Generation in isolation | The answer given a fixed, correct context | Faithfulness; verifiable literal quote | Yes |
| Full system | Comparing two runs | Difference against a baseline | Yes |
| Production | Unknown inputs | Per-stage traces and continuous calibration | Yes |
The definitions:
- MRR. Elastic: “For every query in the test suite, this metric calculates the reciprocal of the rank of the first relevant document.”
- Token IoU. Chroma evaluates “via precision, recall, and intersection-over-union (Jaccard index) on the basis of retrieved tokens”. It counts all the retrieved text, repeated text included.
- Faithfulness. Ragas: “A response is considered faithful if all its claims can be supported by the retrieved context.”
- Context Precision. It “evaluates the retriever's ability to rank relevant chunks higher than irrelevant ones for a given query” (Ragas).
- Context Recall. It measures whether the retrieved context covers the reference. Ragas warns: “calculating context recall always requires a reference to compare against”. The Ragas paper speaks of “a framework for reference-free evaluation”, and its three metrics need no reference; Context Recall, which is in the library but not in that paper, does.
The sample departs from these in three places. retrieval_metrics.py counts characters instead of tokens, so it is an approximation. Its relevance threshold, 50 characters of overlap or half of a shorter reference, is our own decision. And first_relevant_rank returns the rank: averaging the reciprocals is left to the caller. The rest follows Chroma: results from other documents and repeated text count in the denominator.
Which stage to blame
Barnett and co-authors study three real cases and list seven failure points. Without separating stages you can't tell which one happened. This design is our own proposal, with no results behind it. For each question in the set:
- Run generation with the correct, annotated context.
- Run the full system.
- Check whether retrieval brought back the reference.
| Retrieved | With correct context | Full system | Diagnosis |
|---|---|---|---|
| No | Answers well | Answers badly | Retrieval or ingestion fails |
| Yes | Answers badly | Answers badly | Generation fails |
| Yes | Answers well | Answers badly | The chunk didn't reach the prompt, or there is noise |
| No | Answers badly | Answers badly | Both fail, or the question is badly annotated |
An LLM judge has limits too. The Azure repository warns that “the "groundedness" evaluator is not reliable for multimodal RAG”, because it “does not currently incorporate the image sources”, and that running an evaluation “may take a long time, possibly several hours”. In our judgment, an LLM judge is no absolute guarantee: in critical applications, check it against human evaluation.
Common mistakes
- Leaving no way to decline. Barnett and co-authors' first failure is “Missing Content”: with no data for a question, the correct reply is that the answer isn't known.
- Copying a chunk size from an example. Chroma warns that “default settings for certain popular chunking strategies can lead to relatively poor performance” and reports differences of “up to 9% in recall” between strategies, a vendor figure. The Azure repository uses about 1,000 characters with 10% overlap, which is its default and not a rule.
- Mixing customer data and filtering afterwards. OWASP: “Implement fine-grained access controls and permission-aware vector and embedding stores.” One forgotten filter returns another customer's chunks.
- Treating documents as trusted. OWASP describes altered documents in the repository, and warns that RAG is not enough: “they do not fully mitigate prompt injection vulnerabilities.”
The contract in code
The sample is Python, using only the standard library. It loads no models and calls no provider: it shows the contract and is not production-ready. The full package isn't published: these blocks won't run on their own. First, two types from contracts.py:
# rag/contracts.py (its imports and two of its types)
from __future__ import annotations
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import Protocol
Vector = list[float]
class Embedder(Protocol):
"""Adapter over one embedding model. It applies its own prefixes and must return unit-length vectors."""
model_name: str # Include the model revision if the provider publishes one.
dimensions: int
document_prefix: str
query_prefix: str
def embed_documents(self, texts: list[str]) -> list[Vector]: ...
def embed_query(self, text: str) -> Vector: ...
@dataclass(frozen=True)
class IndexSpec:
"""Decisions recorded with the index. All but query_prefix change the stored vectors."""
embedding_model: str
dimensions: int
document_prefix: str
query_prefix: str
chunk_size: int
chunk_overlap: int
chunker_version: str # CHUNKER_VERSION from chunking.py.
parser_version: str = "none" # Set by hand: nothing notices a forgotten change.
enrichment_version: str = "none" # Same: text added to each chunk before embedding.
def fingerprint(self) -> str:
"""Detects an accidental edit of the manifest. It is not a signature."""
canonical = json.dumps(asdict(self), sort_keys=True).encode("utf-8")
return hashlib.sha256(canonical).hexdigest()[:16]
The sample store uses the dot product over normalized vectors, which equals the cosine, and rejects any that aren't; elsewhere, whether to normalize depends on the model and the metric, and it must be done the same way at indexing and at query time.
And the query path, where the contract is checked when the Retriever is created:
# rag/retrieval.py
"""Query-time path. The contract is checked once, when the retriever is created."""
from __future__ import annotations
from .contracts import Embedder, IndexContractError, SearchHit
from .index_store import VectorIndex
MAX_QUERY_CHARS = 2_000
class Retriever:
def __init__(self, embedder: Embedder, index: VectorIndex) -> None:
expected = (index.spec.embedding_model, index.spec.dimensions, index.spec.query_prefix)
actual = (embedder.model_name, embedder.dimensions, embedder.query_prefix)
if expected != actual:
raise IndexContractError(f"index was built for {expected}, embedder is {actual}")
self._embedder = embedder
self._index = index
def search(self, query: str, k: int = 5) -> list[SearchHit]:
cleaned = query.strip()
if not cleaned:
raise ValueError("the query is empty")
if len(cleaned) > MAX_QUERY_CHARS:
raise ValueError(f"the query is longer than {MAX_QUERY_CHARS} characters")
return self._index.search(self._embedder.embed_query(cleaned), k)
It compares names: if a provider swaps the weights under the same name, this won't notice. In production, also compare version, provider, normalization and distance metric, which this sample doesn't record separately. The query prefix it compares is the declared one, not the one the adapter applies. The document prefix is left out because it plays no part at query time. The composition root:
# rag/pipeline.py
"""The composition root: the only place that knows the order of the query-time stages."""
from __future__ import annotations
from .answering import CheckedAnswer, check_reply
from .contracts import Llm
from .prompts import render_answer_prompt
from .retrieval import Retriever
def answer_question(question: str, retriever: Retriever, llm: Llm, k: int = 5) -> CheckedAnswer:
chunks = [hit.chunk for hit in retriever.search(question, k)]
return check_reply(llm.complete(render_answer_prompt(question, chunks)), chunks)
We ran 85 hostile inputs with python tests/hostile.py, on Python 3.14.3 and Windows 11, using test doubles. The script exits with an error if any output differs from the saved one. The inputs check contracts, not quality, and were not run on Linux or macOS. A selection, with the literal output:
H13 other model, same dimensions: raised IndexContractError: index was built for ('fake-a', 8, ''), embedder is ('fake-b', 8, '')
H15 same model, query prefix differs: raised IndexContractError: index was built for ('fake-a', 8, ''), embedder is ('fake-a', 8, 'query: ')
H16 store alone, other model, same dimensions: hits returned, no error: 3
H24 manifest edited by hand: raised IndexContractError: the manifest does not match its fingerprint
H25 manifest edited, fingerprint recomputed: fake-b
H26 vectors swapped, manifest untouched: raised IndexContractError: the stored files do not match the manifest
H50 cites a chunk it never saw: unknown_chunk
H51 invented quote: quote_not_found
H55 true quote, unrelated answer: ok
H57 model abstains: abstained
H66 query prefix changes: same vectors, texts embedded: (True, 0)
H69 vectors swapped, file hashes recomputed: fake-a
H73 load after the interrupted save: raised IndexContractError: the stored files do not match the manifest
Four of those outputs mark deliberate limits:
- H16. Without the
Retriever, the store accepts a query from another model and returns results. - H25 and H69. The fingerprint catches an accidental edit of the manifest (H24), and the data files' sha256 hashes catch an interrupted
saveor a file changed by mistake (H26, H73). Anyone who recomputes the fingerprint or the hashes gets through. - H55.
check_replyonly proves that each quote exists in the cited chunk. A real quote with an unrelated answer returnsok. That's why we call it a citation check and not faithfulness.
What this code does not protect
- Prompt injection, from a document or from the question: inside each chunk, only the literal
<chunkand</chunktags are neutralized. - Permissions, multi-tenancy and poisoned data.
- Embedding inversion and information leaks through prompts, traces or logs.
- Huge documents, and graphemes split by a cut.
- Scale:
VectorIndexis a linear in-memory search. - Concurrency and interruptions:
savewrites three files without atomicity. If it stops midway,loadrefuses the index, but the old one is lost. - Updates: an edited or deleted document means rebuilding everything.
- Forgetfulness: a person changes
parser_version,enrichment_versionandCHUNKER_VERSION. - Provider costs, rate limits and retries.
Frequently asked questions
When does a RAG project need re-indexing?
When the embedding model, its document prefix, the chunk size, the overlap, the parser, or the text added to each chunk before embedding change. Top-k, filters on fields already indexed and the answer prompt don't touch the index, although they still call for an evaluation.
Can a RAG system be evaluated without annotated references?
Partly. Faithfulness is judged against the retrieved context, by an LLM judge, but Context Recall requires a reference. Without references you also can't blame a stage using the method above, since it needs the annotated context.
Should ingestion be a separate service from the start?
In our opinion, no: start with one package and one process, and split it off once there is a concrete reason, such as a batch load getting in the way of queries.
Conclusion
None of this is needed for a throwaway demo or a proof of concept. If the project is going to live on and change hands, don't start by moving folders. Write down what each change invalidates in your case and store the index decisions next to the index.
References
- Parnas (1971) — On the criteria to be used in decomposing systems into modules: prl.khoury.northeastern.edu/img/p-tr-1971.pdf
- Sculley et al. (2015) — Hidden Technical Debt in Machine Learning Systems: proceedings.neurips.cc/.../Paper.pdf
- Barnett et al. (2024) — Seven Failure Points When Engineering a Retrieval Augmented Generation System: arxiv.org/abs/2401.05856
- Google — Rules of Machine Learning: developers.google.com/.../rules-of-ml
- Microsoft — Azure AI Search, generate embeddings: learn.microsoft.com/.../vector-search-how-to-generate-embeddings
- Anthropic — Contextual Retrieval: anthropic.com/research/contextual-retrieval
- Chroma — Evaluating Chunking Strategies: trychroma.com/research/evaluating-chunking
- OWASP — LLM01, Prompt Injection: genai.owasp.org/llmrisk/llm01-prompt-injection
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment