RAG Ingestion, Retrieval Quality & Freshness
The ExampleCo assistant answers ordinary questions well but misses a carryover exception. The exception was split from the rule during ingestion. Later, HR updates the policy from version 2 to version 3, but a delayed worker reactivates version 2. Finally, a deleted document still appears through the answer cache.
These are not primarily language-model failures. RAG quality depends on how evidence is extracted, split, indexed, updated, filtered, and retired.
Treat Ingestion as a Data Pipeline
flowchart LR
U["Approved upload"] --> R["Store immutable document version"]
R --> E["Extract text and structure"]
E --> C["Chunk with source locations"]
C --> B["Embed and build keyword data"]
B --> V["Validate completeness and quality"]
V --> A["Activate version atomically"]
A --> S["Serve current permitted evidence"]An upload succeeding is not the same as the document becoming searchable. Expose states such as uploaded, processing, ready, and failed; keep activation as a deliberate step.
Extraction Errors Become Answer Errors
Check the material before choosing a chunk size:
| Source feature | Typical extraction failure | Consequence |
|---|---|---|
| Multi-column PDF | Columns interleaved | Conditions attach to the wrong rule |
| Table | Headers separated from rows | Region A value attributed to Region B |
| Scanned page | Text recognition reads 20 as 28 | Wrong numerical evidence |
| Footnote | Exception lost | Overgeneralized answer |
| Repeated page header | Header embedded into every chunk | Noisy retrieval |
Store enough location information to inspect the original: document version, section, page, or paragraph offsets. Do not silently index an empty extraction as a successful document.
Chunking: Keep Useful Meaning Together
A chunk is a searchable passage. It should be small enough to retrieve precisely but large enough to preserve meaning.
Bad split:
Chunk 1: "Unused leave may be carried forward."
Chunk 2: "Only up to five days, with approval, before March 31."
Better:
Chunk: "Unused leave may be carried forward, up to five days,
with approval, and must be used before March 31."The dates and numbers here are fictional examples.
| Strategy | Advantage | Risk |
|---|---|---|
| Fixed token count | Simple and predictable size | Cuts across rules and exceptions |
| Paragraph/section boundaries | Preserves document organization | Sections vary greatly in size |
| Limited overlap | Carries nearby context across boundaries | Duplicates evidence and inflates counts |
| Parent-child retrieval | Search small chunks, load their larger parent | Parent context adds size and authorization work |
Start with document-aware boundaries and a bounded size. Treat a size such as 400-600 tokens as an experiment, not a universal optimum.
Preserve the heading in the chunk or metadata. “20 days” means little if “Region A full-time staff” was discarded.
Stable Identity and Idempotent Jobs
A useful chunk identity is derived from:
tenant + document_id + document_version + chunker_version + chunk_ordinalUse a collision-resistant encoding or hash where appropriate. Store a content hash separately if you need change detection.
If a queue retries the same job, it should upsert the same versioned chunks rather than create duplicates. Reuse idempotency and retry/DLQ handling.
A worker must check that its document version is still eligible before activation. A stale version-2 job must not overwrite an active version-3 pointer.
Candidate Retrieval vs Final Context
Use different names for different sets:
50 keyword candidates + 50 vector candidates
-> merge and deduplicate
-> authorize current sources before downstream text processing
-> rerank a bounded candidate set
-> choose perhaps 5 complementary passages
-> pack within the context budgetThese counts are illustrative. They should be selected using evaluation and latency measurements.
Top-k is the number of results requested at a particular stage. A vector top-50, reranker top-10, and prompt containing 5 passages are not contradictory settings.
Hybrid Search and Rank Fusion
Keyword retrieval in this design means BM25 over an inverted index, not a bag of ad hoc string matches. Full-text search derives the formula. The working form is:
BM25(term, passage) = IDF(term) * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * passageLength / averageLength))k1 defaults to about 1.2 and saturates repeated terms. b defaults to about 0.75 and down-ranks long passages. BM25 wins when the question depends on a policy ID such as LV-2026-A, a section title, a negation, or a rare literal that an embedding smooths away. It loses paraphrases such as “holiday allowance” for “annual leave.”
Do not add a BM25 score to a cosine score. The scales are not probabilities and are not comparable. Combine ranked lists instead. One standard method is reciprocal rank fusion (RRF):
RRF(document) = sum over result lists of 1 / (c + rank)If c = 60, a passage ranked first in one list contributes 1/61. A passage in both lists receives both contributions. A missing passage contributes zero from that list.
This is a ranking heuristic, not a probability. The constant and candidate depths still need testing.
Reranking: Spend More Work on Fewer Candidates
The vector index is a bi-encoder. It embeds the question and each passage separately, stores the passage vectors, and compares them at query time. That is cheap enough to run over five million chunks, and it is why approximate search exists. It cannot look at the question and a passage in the same forward pass, so it blurs exceptions, negation, and “which of these fifty chunks is actually about Region A.”
A cross-encoder reranker reads the question and one candidate together and emits a relevance score. It sees token-level interaction, which is why it is the usual second stage. It cannot be precomputed for every future question, so it runs only on a shortlist.
- Bi-encoder retrieval cheaply narrows a large corpus.
- Cross-encoder reranking spends more computation on that shortlist.
- Context selection removes duplication and preserves evidence coverage.
Budget the shortlist against the product deadline, not against a demo. ExampleCo’s answer target is p99 under 10 seconds, with a 12-second request deadline, and generation still has to fit. If an unbatched rerank pass were 20 ms, 50 passages would cost about 1 second before generation; a batched reranker is the production shape, and 20 ms is a planning assumption, not a benchmark. Cap the shortlist. Authorize current sources before their text reaches the reranker.
A reranker cannot recover a passage that never entered its candidate set. It also does not grant authorization or prove factual support.
Make Updates Atomic From the Reader’s Perspective
Use immutable document versions and an authoritative active-version pointer.
PSEUDOCODE
job = load_ingestion_job()
require_document_not_deleted(job.document_id)
chunks = extract_and_chunk(job.immutable_version)
upsert_chunks_and_indexes(job.version, chunks)
verify_expected_chunks_and_index_readiness(job.version)
transaction:
current = lock_document_state(job.document_id)
if current.deleted or current.requested_version != job.version:
mark_job_superseded()
else:
activate(job.version)
increment_source_epoch()
enqueue_obsolete_chunk_and_cache_cleanup()The transaction cannot magically span every external index. The authoritative pointer determines which prepared version is eligible; index readiness must be verified before switching it.
If an external index temporarily returns an old version, the retrieval service filters it against authoritative state and may return an explicit “not ready” or no-evidence result rather than using retired text.
Deletion and Permission Revocation
Separate blocking use from physical cleanup:
- Mark the source deleted or revoke access in authoritative state.
- Make new source-use checks reject it.
- Invalidate dependent search and answer caches.
- Remove vectors, text derivatives, and obsolete index records asynchronously.
- Handle originals, backups, logs, and conversation state according to the retention policy.
Recheck selected source eligibility before returning a buffered answer. A revocation after bytes have already been delivered cannot retroactively make the user forget them; define the exact access-consistency boundary.
Scheduled Refresh vs Change Data Capture
| Method | Benefit | Limitation |
|---|---|---|
| Scheduled full refresh | Simple for small, infrequently changing collections | Freshness delay and repeated work |
| Incremental polling | Less work for changed sources | Requires reliable change/version detection |
| Change data capture (CDC) | Low-latency source-change events | Ordering, duplicate events, and operational complexity |
See CDC. Regardless of event delivery, current permissions must not depend solely on an eventually consistent index copy.
Test the Complete Lifecycle
| Test | Expected observation |
|---|---|
| Upload version 1 | Not searchable until preparation succeeds |
| Ask a supported question | Correct applicable passage and citation |
| Publish version 2 with a different value | New requests use version 2 after activation |
| Retry version-1 ingestion late | Version 1 cannot reactivate |
| Revoke one employee’s access | Future authorized-use checks reject the source |
| Delete document | No future answer or cache reuse depends on it |
| Change embedding model | Queries switch only with a compatible prepared index |
Track extraction failures, job retries, activation lag, active-version mismatch, and evidence recall. A low model-error rate says nothing about an ingestion pipeline that quietly dropped documents.
Related Concepts
- Vector search covers index and filter behavior.
- Full-text search covers the inverted index and BM25.
- RAG separates ingestion from answering.
- Evaluation measures evidence and answer quality.
Trade-offs
| Choice | Helps | Costs or risks |
|---|---|---|
| Small chunks | Precise retrieval | Missing surrounding conditions |
| Large chunks | More local context | Noise and token cost |
| Overlap | Preserves boundary information | Duplicates and extra storage |
| Hybrid retrieval | Combines exact and semantic matching | More tuning |
| Reranking | Better shortlist ordering | Extra processing and latency |
| Immutable versions with activation | Reader-visible consistency | More lifecycle state and cleanup |
Test Your Understanding
Try answering before expanding. Explain the missing assumption, not just the vocabulary.