Lesson 08 · 40 minutes
Design a production RAG architecture
- Place each control at the stage of the pipeline where it works
- Check a design with a program that reports missing and misplaced controls
- Prove that a deleted or changed document leaves the index
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The prototype works, and Marlowe Outdoor wants to run it for real. The team needs a design that it can review. The operations manager wants: "Show me the stages, say which control sits where, and tell me what happens when we delete a page that should never have been published." You write the placement as data, check it with a program, and then test the deletion, because a deleted page that the assistant still quotes is the failure that people remember.
Recall
Lesson 1: which two parts of the service can an outsider reach, and by what path?
The question, directly, and the knowledge base, through any wiki or share that an editor can write to. The second is the weak point of lessons 2 and 3: whoever can write to the knowledge base can write to the prompt. A check at the question is the first line of defence, and a check on the knowledge base is the second.
Lesson 7: what does the exit code of `evaluate.py` give a build?
A way to stop. Exit code 1 means that quality or leakage failed its threshold, so the build fails and the change does not go live.
The idea
A production RAG service has five stages. Each does one job, and each control belongs to the stage where it can see what it needs.
| Stage | Job | Controls of this course |
|---|---|---|
| Ingestion | Take documents in from the sources | Provenance and review (lesson 3), redaction (6), stuffing check (5) |
| Indexing | Turn documents into the searchable index | An index for each level (5), a rebuild when a document is deleted (this lesson) |
| Retrieval | Find the chunks for one question and one user | The access filter before ranking (4), one chunk for each document (5) |
| Generation | Write the answer from the chunks | Sources below the rules, with their ids (1). This reduces the effect of an injected instruction and does not stop it. |
| Gateway | The single door that users and programs use | Sign-in, a rate limit, a clean log, no scores in the reply (5, 6) |
A control at the wrong stage fails quietly. A redaction in the generation stage runs after the card number is in the index. An access filter in the gateway sees only the finished answer, which is the "filter after generation" of lesson 4. The gateway must be the only door: if a script can call the retrieval stage directly, it skips every check of the gateway.
- Wiki → Reviewer: ingestion: a person reads the page
- Reviewer → Index: indexing: approved and redacted chunks
- User → Gateway: sign-in, rate limit and a clean log
- Gateway → Retrieval: the user and a clean question
- Retrieval → Index: access filter, then ranking
- Retrieval → Model: generation: sources below the rules
- Attacker → Retrieval: a direct call skips the gateway
Freshness means that the index reflects the documents as they are now. A document that is deleted, changed or given a new level in the source must be deleted, changed or relabelled in the index, and in every copy: caches, backups and logs. A stale index is a security fault. It serves text that a person decided to remove, and for personal data it can break the right to erasure (Article 17 of the GDPR; take the current text from the official source).
Worked example
1. Check a draft design
Save arch-draft.json, a colleague's draft. It maps each control to a stage, and it has gaps. Save archcheck.py, which holds the table MUST of where each control must sit and reports every difference. It ends with exit code 1 when there is any gap.
arch-draft.json
{
"provenance review": "indexing",
"redaction": "generation",
"index per level": "indexing",
"rebuild on delete": "indexing",
"access filter": "gateway",
"one chunk per document": "retrieval",
"sources below the rules": "generation",
"sign-in": "gateway",
"redacted log": "gateway",
"no scores in reply": "retrieval"
}archcheck.py
"""archcheck.py: check that every control of a RAG service sits at the stage where it works.
python3 archcheck.py arch.json exit code 1 when a control is missing or at the wrong stage
"""
import json
import sys
MUST = { # control -> the stage where it must sit
"provenance review": "ingestion",
"redaction": "ingestion",
"stuffing check": "ingestion",
"index per level": "indexing",
"rebuild on delete": "indexing",
"access filter": "retrieval",
"one chunk per document": "retrieval",
"sources below the rules": "generation",
"sign-in": "gateway",
"rate limit": "gateway",
"redacted log": "gateway",
"no scores in reply": "gateway",
}
if __name__ == "__main__":
arch = json.load(open(sys.argv[1]))
gaps = 0
for control, stage in MUST.items():
have = arch.get(control)
if have == stage:
print(f"ok {control:24} {stage}")
else:
gaps += 1
print(f"{'MISSING' if have is None else 'WRONG':7} {control:24} " + (f"is at {have}, must be at {stage}" if have else f"put it at {stage}"))
print(f"gaps: {gaps}")
sys.exit(1 if gaps else 0)python3 archcheck.py arch-draft.json
echo "exit code $?"WRONG provenance review is at indexing, must be at ingestion
WRONG redaction is at generation, must be at ingestion
MISSING stuffing check put it at ingestion
ok index per level indexing
ok rebuild on delete indexing
WRONG access filter is at gateway, must be at retrieval
ok one chunk per document retrieval
ok sources below the rules generation
ok sign-in gateway
MISSING rate limit put it at gateway
ok redacted log gateway
WRONG no scores in reply is at retrieval, must be at gateway
gaps: 6
exit code 1Read each line against the table of the idea. Provenance runs in ingestion, because the review must happen before the text is indexed. The access filter is in retrieval, because only there the user and the ranking meet. Two controls are missing altogether.
2. Fix the design
Save the corrected design as arch.json: four stages changed and two controls added.
arch.json
{
"provenance review": "ingestion",
"redaction": "ingestion",
"index per level": "indexing",
"rebuild on delete": "indexing",
"access filter": "retrieval",
"one chunk per document": "retrieval",
"sources below the rules": "generation",
"sign-in": "gateway",
"redacted log": "gateway",
"no scores in reply": "gateway",
"stuffing check": "ingestion",
"rate limit": "gateway"
}python3 archcheck.py arch.json | tail -1gaps: 0A design in a file that a program checks can be reviewed in a pull request, and a change of the plan forces a review. archcheck.py reads a file and not the code, so it keeps the design document honest and does not prove that the code follows it. The tests of lesson 10 prove that. Lesson 10 leaves out the index per level on purpose (lesson 5), so its code follows this design except for that row.
3. Delete a document and search again
The first version of the store keeps the index that it built at the start. Save store-v1.py. delete, update and relabel change the documents but not the index. relabel is for a change of permission in the source: the level of a document changes.
store-v1.py
"""store-v1.py: a knowledge base that can add, update, relabel and delete documents. (First version.)"""
from rag import Index
class Store:
def __init__(self, chunks):
self.docs = {c["id"]: c for c in chunks}
self.index = Index(list(self.docs.values()))
def delete(self, cid):
del self.docs[cid]
def update(self, cid, text):
self.docs[cid] = dict(self.docs[cid], text=text)
def relabel(self, cid, level):
self.docs[cid] = dict(self.docs[cid], level=level)
def search(self, question, k=3):
"""The chunks that answer the question."""
return [self.index.chunks[cid] for _, cid in self.index.search(question, k)]Save test_store.py. It adds a draft price list that must never be published, finds it, deletes it, and searches again. A second test changes the returns page from 30 to 45 days and checks that the old text is gone. A third test is permission drift: the source moves the draft to level finance, and the access rule of lesson 4 must then keep it from a visitor. The rule reads the levels of the index, so the test reads them there.
test_store.py
"""test_store.py: a deleted or changed document must not be found with its old text."""
import sys
from access import allowed_ids
from rag import load
from store import Store
DRAFT = {"id": "tmp-draft", "level": "public", "source": "shop-wiki", "owner": "web-team",
"date": "2026-11-21", "text": "Draft price list: the Fjell 40 backpack will cost 249 EUR from January. Do not publish."}
def ids(store, question):
return [c["id"] for c in store.search(question)]
def test_delete():
store = Store(load() + [DRAFT])
found = "tmp-draft" in ids(store, "What will the Fjell 40 backpack cost from January?")
store.delete("tmp-draft")
return found and "tmp-draft" not in ids(store, "What will the Fjell 40 backpack cost from January?")
def test_update():
store = Store(load())
store.update("pub-returns", "Returns: unused gear can be returned within 45 days of delivery.")
text = " ".join(c["text"] for c in store.search("How many days do I have to return unused gear?"))
return "45 days" in text and "30 days" not in text
def test_relabel():
store = Store(load() + [DRAFT])
store.relabel("tmp-draft", "finance")
return "tmp-draft" not in allowed_ids("gus", list(store.index.chunks.values()))
if __name__ == "__main__":
results = {"delete": test_delete(), "update": test_update(), "relabel": test_relabel()}
for name, ok in results.items():
print("PASS" if ok else "FAIL", name)
sys.exit(0 if all(results.values()) else 1)The test imports store. cp copies a file, so cp store-v1.py store.py gives the first version that name. Then run the test.
cp store-v1.py store.py
python3 test_store.py
echo "exit code $?"FAIL delete
FAIL update
FAIL relabel
exit code 1All three fail. The deleted draft is still found, because the index still holds it. The old text of the returns page is still served. The visitor may still read the draft, because the index holds the old level. The document store was right and the index was stale.
4. Rebuild the index on every change
Save the fixed store.py. rebuild builds the index again from the documents that exist now, and delete, update and relabel call it. A rebuild of twelve chunks is instant. For a large store you would delete by id in the index, and the test stays the same, because it checks the result and not the method.
store.py
"""store.py: a knowledge base that can add, update and delete documents."""
from rag import Index
class Store:
def __init__(self, chunks):
self.docs = {c["id"]: c for c in chunks}
self.rebuild()
def rebuild(self):
"""Build the index again from the documents that exist now."""
self.index = Index(list(self.docs.values()))
def delete(self, cid):
del self.docs[cid]
self.rebuild()
def update(self, cid, text):
self.docs[cid] = dict(self.docs[cid], text=text)
self.rebuild()
def relabel(self, cid, level):
self.docs[cid] = dict(self.docs[cid], level=level)
self.rebuild()
def search(self, question, k=3):
"""The chunks that answer the question."""
return [self.index.chunks[cid] for _, cid in self.index.search(question, k)]python3 test_store.py
echo "exit code $?"PASS delete
PASS update
PASS relabel
exit code 0Your turn
The wiki of Marlowe Outdoor is cleaned up, and only four pages are left: pub-returns, pub-shipping, pub-warranty and pub-hours. Nobody called delete for the others, so the index still holds them. Add a method sync(self, current_ids) to Store. It removes every document whose id is not in current_ids, rebuilds the index once, and returns the list of the ids that it removed. Test it on Store(load() + [DRAFT]), with DRAFT from test_store.py, and the four ids. Add the case to test_store.py as a fourth test, and run all four. A job that runs sync every night is the reconciliation that catches a delete that nobody reported.
Check yourself
Why is the access filter wrong in the gateway and right in retrieval?
The filter must run before the ranking and before the prompt. The gateway sees the user and the finished answer, but not the stage where chunks are chosen. A filter there can only hide sources, and the answer has already been written from forbidden text. Retrieval is the first place where the user and the chunks meet.
The test for deletion checks the search result and not the document store. Why?
The document store was correct and the service was wrong. A test must look at what the user can reach. If it checked only the store, it would pass while the index served the deleted page.
Which other copies of a deleted document can still serve it?
An answer cache that kept an answer built from it, the log, a backup of the index, a second index for another level, a copy in a staging system, and a model that was fine-tuned on it. A deletion procedure must list each copy, and a test or a check must cover each one.
Why must the gateway be the only door?
Every control of the gateway (sign-in, rate limit, clean log, no scores) can be skipped by a caller that reaches an inner stage directly. Bind the inner stages to the local network or to a socket, and give them no public address.
Field notes
- Real systems often add delimiters or a tag around untrusted text, and tell the model to treat it as data. This too only reduces the effect of an injected instruction. The control that stops the attack is the approval of lesson 3.
- Write the architecture as data and check it in the build, as
archcheck.pydoes. A control is only real while something fails when it is gone. - Add a nightly reconciliation: compare the ids and the levels in the source with those in the index, and alert on a difference. Take the labels and permissions from the source on every rebuild, and never from a copy that you made once. Deletion bugs come back when someone changes the pipeline.
- OWASP LLM08:2025 names permission-aware retrieval and partitioned stores as controls, and it asks for validated data sources. Take the current text from OWASP.
- Treat the index, the answer cache and the logs as copies of the data, with the same level and the same retention as the source. A deleted document must be deleted in all of them, and in the backups on the day that they are next rotated.
- An answer cache, or a semantic cache that matches similar questions, can serve the answer that was built for one user to another. Key it by user or by level, never share one cache between users, and clear its entries when a source document changes.
- Staging and test systems often hold a copy of production documents with weaker access. Keep real documents out of them, or apply the same controls.