Module 2 · Parsing & chunking
Deduplication, caching and incremental ingestion
5 min read
A knowledge base is never finished: policies change, product sheets arrive, manuals are withdrawn. Reindexing the whole corpus at every change is slow, expensive (embeddings, LLM extractors, parsing) and risky (an ingestion that fails halfway leaves an inconsistent index). Incremental ingestion only reprocesses what changed. It rests on three mechanisms partly seen in lesson 1.4: stable identifiers, the docstore and the cache.
The three pillars
| Pillar | Question it answers | Typical failure |
|---|---|---|
| Stable identifier | "Have I seen this document before?" | Identifiers derived from an absolute path or an editable title |
| Docstore (content hash) | "Has it changed since?" | Docstore not persisted: everything looks new after a restart |
| Transformation cache | "Have I already computed this result?" | Local cache lost at each deployment |
If any of the three is missing, incremental ingestion silently degrades into "reindex everything".
The test that proves it
Lumen's test_incremental_ingestion test copies the corpus to a temporary folder and checks the complete behavior:
first = await pipeline.arun(documents=readers.load_all(data))
assert len(first) > 0
# rien n'a changé : rien n'est retraité
assert await pipeline.arun(documents=readers.load_all(data)) == []
addition = "\n\n## Retrait en magasin\n\nGratuit à Lyon.\n"
shipping.write_text(shipping.read_text(encoding="utf-8") + addition, encoding="utf-8")
changed = await pipeline.arun(documents=readers.load_all(data))
assert {n.metadata["source"] for n in changed} == {"policies/shipping.md"}
(data / "faq.csv").write_text("question,answer,category\n", encoding="utf-8") # FAQ vidée
await pipeline.arun(documents=readers.load_all(data))
remaining = pipeline.docstore.get_all_document_hashes().values()
assert not any(ref.startswith("faq.csv") for ref in remaining)
Four properties are checked: the first ingestion processes everything, the second nothing, a modification only reprocesses the affected document, and a deletion removes its nodes (UPSERTS_AND_DELETE strategy). This test actually revealed a bug while building Lumen: the source path was computed relative to the default data folder instead of the folder actually provided. Write this test for your own pipeline: it's the only way to be sure incremental ingestion works.
Granularity: document or node?
The docstore compares documents. If a document changes by a single character, all its nodes are recomputed: four nodes for the modified shipping policy. For a 300-page document, that's 300 pages of parsing and embeddings.
The remedy is to choose a fine document granularity: a page, a section or a FAQ entry rather than a whole file. The PDF reader already produces one document per page; a FAQ is loaded row by row. Don't count on the cache to compensate: it stores the result of a transformation for an identical batch of nodes, not node by node. It avoids recomputing a batch already seen (an ingestion relaunched after a failure, another environment), not the unchanged nodes of a modified document.
Deduplication
The same content often exists in several copies: a policy copied into two document spaces, a FAQ exported twice. Indexing duplicates skews retrieval — the top four results may be four copies of the same passage, at the expense of complementary information.
- Exact duplicate documents are dropped by the docstore (same hash).
- For content duplicates under different identifiers, normalize at the source (a single canonical path per document) or add a deduplication step at the start of the pipeline, computing a hash of the normalized text.
- At retrieval, a post-processor can drop passages that are too similar to each other, to diversify the context.
Scheduling refreshes
In Lumen, refreshing is an admin route, protected by a token:
@app.post("/admin/refresh")
async def refresh(x_admin_token: str | None = Header(default=None)) -> dict:
expected = os.environ.get("LUMEN_ADMIN_TOKEN")
if not expected or x_admin_token != expected:
raise HTTPException(403, "Jeton d'administration requis.")
report = await app.state.kb.refresh()
return {"documents": report.documents, "new_nodes": report.new_nodes}
It can be called by a scheduled job (hourly, nightly), by a webhook from your documentation tool on each publication, or manually. The choice depends on the expected freshness: a pricing policy must be up to date within the hour, an assembly manual can wait for the night.
Two precautions:
- One refresh at a time. Two simultaneous ingestions on the same docstore step on each other's toes. Protect the route with a lock, or hand refreshes to a task queue.
- Log each run: documents read, nodes created, deleted, errors. A refresh that suddenly processes nothing, or reprocesses everything, is a warning sign.
Persisting the ingestion state
Docstore and cache must survive restarts, or incremental ingestion is lost:
pipeline.persist("storage/pipeline")
pipeline.load("storage/pipeline")
These local files suit a single instance. With several servers, or ephemeral containers, use the shared versions (docstore and cache on Redis, MongoDB or PostgreSQL), or run ingestion in a dedicated service with its own persistent storage.
Key takeaways
- Incremental ingestion rests on stable identifiers, a persisted docstore and a cache; without any of them, everything is reindexed.
- An incremental ingestion test (nothing, modification, deletion) is essential.
- The docstore compares documents: a fine granularity (page, section) limits reprocessing; the cache works by batch, not by node.
- Deduplicate at the source; diversify results at retrieval.
- Scheduled or triggered refreshes, one at a time, logged; persisted and shared state with multiple instances.
Practice
- Run
pytest tests/test_ingestion.py -k incremental -vand read the test step by step. - Add a case to the test: renaming a file. How many nodes are created and deleted? Is that the desired behavior?
- Protect
KnowledgeBase.refreshwith anasyncio.Lockto prevent two simultaneous refreshes, and test it.