Chapter 3 · concept 4 of 6 · show all
2Tokens, cost and your first RAG
4Chunking
- 4.1Why we chunk, and the main chunking strategies
- 4.2Structure aware chunking and tables
- 4.3Chunk size, overlap and token based sizing
- 4.4Contextual chunking and late chunking
- 4.5Parent child and multi representation indexing
- 4.6Chunk metadata, provenance and the chunking debugging playbook
- Chapter overview
7Finding the right chunks
8When retrieval fails
Cleaning, normalization and quality gates
What to clean before indexing, what to leave alone, and the automatic checks that stop broken, duplicate or poisoned documents from reaching search.
A real question
What stops a broken or dangerous document from getting into my search index?
Nothing, unless you add checks. Clean what is noise, and let automatic quality gates hold back anything that fails, before it is indexed.

The problem
Why this matters

If the parser produced text, index it. Search will sort out what is useful.

Search returns whatever is in the index: footers, duplicates, and documents with hidden instructions. Our checks found 12 of 25 documents missing a field, and one planted attack.
Why not the simpler way
The simple pipeline indexes whatever the parser produced. Then search returns cookie banners, page footers and five copies of the same FAQ. Worse, it can return a document that contains instructions aimed at the model, or one with missing access labels that should never have been visible. Cleaning fixes noise; quality gates stop the documents that should not get in at all.
The idea
The idea in plain words
Cleaning removes what is not content: navigation, boilerplate, repeated headers, broken line breaks, invisible characters. Normalization makes equal things look equal: Unicode forms, whitespace, dates, units. Quality gates are automatic checks that a document must pass before it is indexed, and that send failures to a person instead of to search.
A restaurant kitchen washes vegetables (cleaning), cuts them to the same size (normalization), and throws out anything spoiled before it reaches a plate (the gate).
How it works
Step by step
1Clean the noise, carefully
Remove menus, footers and broken line breaks. Keep case and punctuation: codes like PT-MOB-25GB depend on them.
2Check the required fields
Every document needs an id, a version, dates and access labels. Missing fields break filters later.
3Hold back what fails
Text that tries to give the model orders, empty pages and duplicates go to review, not to the index.
In detail
Clean conservatively. Remove what you are sure is noise and keep everything else, because over-cleaning deletes content you cannot get back. Normalize Unicode (NFKC), whitespace and line breaks; keep case and punctuation, since codes like PT-MOB-25GB depend on them.
Typical gates, each with a clear pass or fail:
- Required metadata present: id, version, dates, access labels.
- Not empty: enough text after parsing, so a failed OCR does not index blank pages.
- No exact duplicates: same content hash as an existing document.
- No instruction-like text: patterns such as "ignore previous instructions" go to review.
- Language matches the index it goes into.
The code
Try it in Python
import hashlib, re, unicodedata
INJECTION = re.compile(r"ignore (all )?previous instructions|disregard the above|system prompt", re.I)
REQUIRED = ("doc_id", "version", "effective_from", "allowed_roles")
def gate(doc: dict, seen_hashes: set[str]) -> list[str]:
"""Return the reasons a document fails; an empty list means it may be indexed."""
text = unicodedata.normalize("NFKC", doc["text"]).strip()
fails = [f"missing {k}" for k in REQUIRED if k not in doc["meta"]]
if len(text) < 50:
fails.append("too little text")
h = hashlib.sha256(text.encode()).hexdigest()
if h in seen_hashes:
fails.append("duplicate")
if INJECTION.search(text):
fails.append("instruction-like text")
seen_hashes.add(h)
return fails
See it
What we measured
Measured · quality gate results on the Polder corpus
25 English documents, 34 recursive 512 chunks. Gates: required frontmatter fields, exact duplicate chunks, and three instruction patterns (ignore previous instructions, disregard the above, system prompt).
Measured 2026-11-03. The pattern gate caught the one planted injection document; a determined attacker can avoid fixed patterns, so this is one layer, not a defence on its own. The missing sector field is a real gap in the corpus, left in on purpose as a teaching example.
Try it on a real example
A document planted in our corpus, and what the gate does with it
SYN-POL-INJ1 · Polder Bank Experimental AI Operations Guide
It looks like a normal policy, but one sentence talks to the model, not to the reader.
Choosing
Use it when, avoid it when
- Conservative cleaning plus NFKC and whitespace normalization
- Automatic gates with a visible failure report and quarantine
- Aggressive cleaning that lowercases or strips punctuation from codes
- Trusting a pattern filter as the only injection defence
What it costs · Gates run in milliseconds per document. The real cost is reviewing quarantined documents, which is also where you learn about your sources.
In production
Run the gates in the ingestion pipeline, not by hand, and make every failure visible in a report with the document, the gate and the reason. Quarantine instead of delete. Treat the instruction filter as one layer only: the prompt must still tell the model that sources are data, and the output should be checked. Count gate failures over time; a sudden jump usually means a source changed its format.
Watch out
Common mistakes
- More cleaning is better. Over-cleaning deletes content and breaks exact codes.
- Injection is a prompt problem only. It starts in the documents you index.
- Metadata gaps are cosmetic. They turn into missing answers as soon as you filter.
Check yourself
Remember this
Remember these
- Cleaning removes noise; normalising makes equal text look equal.
- Quality gates check fields, emptiness, duplicates and hidden instructions.
- Failures go to quarantine with a reason, never silently deleted.
- Our gates flagged 12 of 25 documents without a sector field and the planted attack.
Say it in an interview
- 01Cleaning removes noise, normalization makes equal text equal, gates keep bad documents out.
- 02I clean conservatively; codes like PT-MOB-25GB need their case and punctuation.
- 03My gates check metadata, emptiness, duplicates, instruction-like text and language.
- 04On my corpus they found 12 of 25 documents without a sector field and the planted injection.
- 05Failures are quarantined and reported, never silently deleted.
Quick quiz