RAG Ingestion, Retrieval Quality & Freshness

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 featureTypical extraction failureConsequence
Multi-column PDFColumns interleavedConditions attach to the wrong rule
TableHeaders separated from rowsRegion A value attributed to Region B
Scanned pageText recognition reads 20 as 28Wrong numerical evidence
FootnoteException lostOvergeneralized answer
Repeated page headerHeader embedded into every chunkNoisy 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.

StrategyAdvantageRisk
Fixed token countSimple and predictable sizeCuts across rules and exceptions
Paragraph/section boundariesPreserves document organizationSections vary greatly in size
Limited overlapCarries nearby context across boundariesDuplicates evidence and inflates counts
Parent-child retrievalSearch small chunks, load their larger parentParent 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_ordinal

Use 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 budget

These 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:

  1. Mark the source deleted or revoke access in authoritative state.
  2. Make new source-use checks reject it.
  3. Invalidate dependent search and answer caches.
  4. Remove vectors, text derivatives, and obsolete index records asynchronously.
  5. 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

MethodBenefitLimitation
Scheduled full refreshSimple for small, infrequently changing collectionsFreshness delay and repeated work
Incremental pollingLess work for changed sourcesRequires reliable change/version detection
Change data capture (CDC)Low-latency source-change eventsOrdering, 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

TestExpected observation
Upload version 1Not searchable until preparation succeeds
Ask a supported questionCorrect applicable passage and citation
Publish version 2 with a different valueNew requests use version 2 after activation
Retry version-1 ingestion lateVersion 1 cannot reactivate
Revoke one employee’s accessFuture authorized-use checks reject the source
Delete documentNo future answer or cache reuse depends on it
Change embedding modelQueries 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

Trade-offs

ChoiceHelpsCosts or risks
Small chunksPrecise retrievalMissing surrounding conditions
Large chunksMore local contextNoise and token cost
OverlapPreserves boundary informationDuplicates and extra storage
Hybrid retrievalCombines exact and semantic matchingMore tuning
RerankingBetter shortlist orderingExtra processing and latency
Immutable versions with activationReader-visible consistencyMore lifecycle state and cleanup

Test Your Understanding

Try answering before expanding. Explain the missing assumption, not just the vocabulary.

  1. The upload API returned success. Why is the document not searchable yet?
Upload can mean durable receipt, not completed extraction, embedding, indexing, or activation. Expose processing state rather than treating every accepted upload as immediately queryable.
  1. Why can a smaller chunk make a correct rule dangerous?
It can separate the rule from its exception, scope, or deadline. A retrieved sentence may become misleading when its qualifying context is missing.
  1. Does overlap solve every chunk-boundary problem?
No. It only repeats nearby content within a chosen window. Tables, long-distance references, and widely separated exceptions can still require structure-aware processing or parent retrieval.
  1. A reranker is excellent, but the needed policy is candidate 500. Will reranking the top 50 help?
Not if the policy never enters those 50. Candidate-generation recall bounds what reranking can recover.
  1. Why not add raw keyword and cosine scores?
They may use unrelated scales. One can dominate for accidental numerical reasons. Calibrate them or use a tested rank-fusion method such as RRF.
  1. Does an RRF score represent factual confidence?
No. It combines ranked-list positions. It does not establish support, policy applicability, or correctness.
  1. Why is a deterministic chunk ID useful with at-least-once delivery?
A retry can upsert the same versioned chunk instead of creating duplicates. Include enough version information to avoid overwriting a different document representation.
  1. Version 3 is active when a delayed version-2 job finishes. What must prevent regression?
The activation transaction must compare the job’s version with the currently requested version and deletion state. A stale worker should mark itself superseded, not move the active pointer backward.
  1. Can deleting vectors alone satisfy document deletion?
No. Text derivatives, originals, keyword indexes, caches, histories, logs, and backups may also contain source information. Apply the documented retention and deletion policy across those surfaces.
  1. Why authorize before sending candidates to a hosted reranker?
The reranker receives the source text too. It is a downstream data processor and must not receive documents the request is not allowed to use.
  1. What if only half the chunks reached an external index?
Do not activate a version that requires completeness. Verify expected chunks and index visibility, or mark the version unavailable with a clear error while recovery proceeds.
  1. Why keep page or section locations after extracting plain text?
They let humans inspect the original evidence, resolve precise citations, and diagnose extraction errors such as a misplaced table value.
  1. Is a 500-token chunk universally optimal?
No. Document structure, model behavior, question type, and latency budget differ. Compare a few sensible configurations on the same evaluation set.
  1. What happens if an embedding upgrade reuses old vectors?
Queries can be compared against an incompatible coordinate space. Prepare and validate a new matched index, then switch the query encoder and index together.
  1. Why can duplicate overlapping chunks inflate retrieval metrics?
Several near-identical passages may appear as multiple relevant hits without adding evidence coverage. Deduplicate and define relevance labels so repeated text does not masquerade as broader recall.
  1. A permission event is delayed. Must the assistant wait for the index update?
No. Current authorization should be checked against authoritative state before source use and response release. Index metadata alone should not establish sensitive access.
  1. Can a background cleanup job guarantee immediate physical erasure everywhere?
No. Replicas, backups, and other retained systems have their own timelines. Distinguish immediate blocking of future use from the documented physical-deletion process.
  1. Why does reranking all two million chunks defeat the architecture?
Reranking is usually more expensive per passage than initial retrieval. Its role is to improve a bounded shortlist, not replace efficient candidate generation for the full corpus.
  1. A source is revoked after its answer was already displayed. Can the system undo that disclosure?
No. It can stop future access, reuse, and retrieval, but cannot retract knowledge already delivered. Define and enforce the authorization boundary before release.
  1. What lifecycle test catches more than a static question-answer test?
Upload a policy, activate it, answer from it, change its value, retry an old job, revoke access, and delete it. Confirm each later query and cache lookup follows current authoritative state.