05.9 Ingestion Pipelines and Incremental Updates
Lessons 05.1 to 05.8 turned a pile of messy source files into clean, well-chunked, well-labelled records. This lesson is about the machinery that does it repeatedly, automatically and safely: the ingestion pipeline that runs on a schedule or on events, detects what changed since last time, re-processes only what it must, keeps the manifest and the vector store consistent, survives crashes and poison documents, and can be re-run from scratch at any time. It is where classical data engineering — idempotency, lineage, change detection, reconciliation — meets an AI system whose downstream stages (embedding, retrieval, generation) are expensive and unforgiving of silent inconsistency. By the end you will have a complete, runnable minimal pipeline, plus the decision tables for when plain Python is enough and when you need an orchestrator.
What you'll learn
- The pipeline design principles that make an AI ingestion system trustworthy: idempotency, determinism, immutability of raw data, stage separation, checkpointing, fail-soft per document, and versioning everywhere
- How to detect change cheaply and correctly: content hashes,
ETag/Last-Modified, source change feeds (Drivechanges, Graph delta, S3 events, webhooks, CDC), directory snapshots, tombstones, renames, and meaningful change - The manifest/state-store pattern and the full incremental-update algorithm: classify new/changed/unchanged/deleted, re-process only what changed, reuse embeddings of surviving chunks by content-addressed ID, delete stale records, swap atomically, and reconcile manifest against vector store
- Versioned indexes and reindexing: when a full re-embed is unavoidable, blue/green indexes with aliases, shadow evaluation, cost estimation, backfills and rollback
- Orchestration options from cron to Temporal: queues (Celery, RQ, Dramatiq, arq), workflow engines (Prefect, Dagster, Airflow 3, Temporal), cloud-native and streaming patterns — with a decision table and a minimal Prefect and Dagster version of the pipeline
- Concurrency, provider rate limits and cost control for parse/embed/enrich stages (the mechanics live in 03.8, 03.9 and 06.2; this lesson applies them)
- Production error handling: per-document isolation, retry policies, dead-letter/quarantine, poison documents, timeouts, resumability after crash
- Security and compliance inside pipelines: secrets, least privilege, PII steps, data residency, right-to-erasure deletion, tenant isolation, audit logs
- Observability (structured logs, metrics, freshness SLAs, run reports, lineage) and pipeline testing (unit, golden documents, idempotency property tests, parser contract tests, CI)
- Connectors and ingestion frameworks (LlamaIndex, LangChain, Haystack, Unstructured, Airbyte-style ELT) and what they hide
- Streaming and near-real-time ingestion: webhooks, queues, debouncing, ordering, and exactly-once vs at-least-once semantics
What you don't need
- A running vector database, an orchestrator server, or any API key. The complete pipeline in Part 4 is pure Python standard library and runs on a toy folder you create in seconds; every output shown is a real run of that code. Provider and library snippets are labelled illustrative.
- Deep knowledge of the parse/clean/chunk/metadata stages. This lesson calls them: 05.2–05.4 own parsing, 05.5 owns cleaning, 05.6–05.7 own chunking, 05.8 owns the metadata schema including the content-addressed IDs this lesson depends on. Where the pipeline needs a detail from them, it links.
- Embedding API mechanics, batching and caching (06.1, 06.2) or vector-store internals (06.4, 06.5). This lesson owns the pipeline side: when to re-embed, how to keep stores consistent, and how to cut over.
Setup
The core of this lesson needs only the Python standard library (Python 3.11+) — no packages, no services, no keys:
uv init ingest-pipeline --bare --python 3.13 && cd ingest-pipeline
# (or follow the shared setup in lesson 03.1 if you haven't made a project yet)Copy the appendix's pipeline.py into the project, create the toy sources/ folder with the make_sources.py script from 4.1 (six small files, so your counters match the ones printed in Part 4), and run:
python pipeline.py --sources sources --db pipeline.db --vectors vectors.db
python pipeline.py --sources sources --db pipeline.db --vectors vectors.db # second run: nothing to do
python pipeline.py --sources sources --db pipeline.db --vectors vectors.db --dry-run
python pipeline.py --sources sources --db pipeline.db --vectors vectors.db --repair # fix reconciliation drift (3.5)Optional, only for the HTTP conditional-request snippet in 2.3 (checked against httpx 0.28.1 as of November 2026; a newer major version may change names, so check the changelog if the call does not match):
uv add httpx # or: pip install httpxThe orchestrator snippets in Part 6 are labelled with the package versions they were checked against (Prefect 3.9, Dagster 1.13, Airflow 3.3; Airflow 3.4.0 appeared on PyPI on 6 November 2026, too recently for the snippets to be checked against it) but are not run — installing them is optional and explained where they appear.
What you must be able to do after this lesson#
- Explain idempotency and the other pipeline design principles
- Detect changed, new and deleted documents with hashes
- Run an incremental update from a manifest
- Build a minimal pipeline end to end
- Choose when a full reindex is needed
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just re-run the whole ingestion every night." | 1.2 The engineering contract and 5.1 When you must re-embed |
| "Why did it re-embed 40,000 chunks for a one-word edit?" | 3.3 Chunk-level diffing |
| "The vector store and the manifest disagree. Which is right?" | 3.5 Reconciliation |
| "We need the corpus fresh within an hour of a Drive edit." | 2.4 Change feeds and Part 13 |
| "Can we make the index update atomic?" | 3.4 Atomicity |
| "Which orchestrator should we pick?" | 6.6 The decision table |
| "A 2 GB PDF crashed the worker." | 8.3 Timeouts and memory limits |
| "Legal wants a deleted contract gone everywhere." | 9.3 Deletion requests |
| "How do we know the pipeline is healthy?" | Part 10: Observability |
| "The parser library updated and broke." | 11.2 Contract tests |
| "Should we use LlamaIndex/LangChain ingestion?" | Part 12 |
Part 1: Pipeline design principles for AI data#
1.1 The stage map#
05.1 draws the pipeline map: discover → fetch → parse → clean → chunk → enrich → embed → index → serve. This module owns the middle stages; Module 06 owns embed/index; Module 07 owns retrieve/generate. Your pipeline is the code that moves work through those stages repeatedly and safely. The engineering question is never "can it parse a PDF" — it's "can it do that for 50,000 documents, every night, without losing track of what it already did, without paying twice for work it already did, and without a silent failure leaving the index stale for a week".
flowchart LR
subgraph src ["Sources"]
FS["files / object storage"]
SAAS["Drive / SharePoint / ticketing APIs"]
DB[("databases / CDC")]
WEB["web / feeds"]
end
subgraph pipe ["Your ingestion pipeline (this lesson)"]
direction TB
S1["scan / fetch"] --> S2["parse"] --> S3["clean"] --> S4["chunk"] --> S5["enrich"]
S5 --> S6["embed (06.2)"]
MAN[("manifest / state store")]
S1 -.-> MAN
S6 -.-> MAN
end
subgraph out ["Downstream (other modules)"]
VS[("vector store / index (06)")]
RAW[("raw + parsed store")]
end
src --> S1
S6 --> VS
S2 -.-> RAW
VS --> RAG["retrieve + generate (07)"]Three stores matter and they are different things:
- Raw store — the immutable copy of what was fetched (bytes, response bodies, export files). You keep it so you can re-parse without re-fetching, prove provenance, and replay.
- Manifest / state store — the pipeline's memory: which sources it has seen, their content hashes, which chunks exist, what each run did, what failed. Usually SQLite, DuckDB or a Postgres table.
- Vector store / index — the serving-side copy of chunk text + vectors + metadata. Owned by Module 06; your pipeline writes to it.
1.2 The engineering contract#
Every trustworthy ingestion pipeline honours the same contract. Each principle below is a rule you can check a design against — and each has a failure mode if you skip it.
| Principle | What it means here | The failure it prevents |
|---|---|---|
| Idempotency | Running the pipeline twice on the same inputs produces the same end state, not double the data | Duplicate chunks, doubled embedding bills, duplicated search results |
| Determinism | Same input + same code version → same outputs (same chunk boundaries, same IDs, same embeddings request set) | Unexplained diffs; impossible debugging; re-embedding everything on every run |
| Immutability of raw data | Fetched bytes are stored once, never mutated; every later stage reads raw and writes new derived artefacts | Cleaning bugs corrupting the only copy; unreproducible parses |
| Stage separation | Each stage is a pure-ish function with typed input/output; stages don't reach into each other's state | A "cleaning" change silently altering chunk boundaries; untestable monoliths |
| Checkpointing / resumability | Progress is recorded per document/chunk; a crash resumes where it stopped | Re-paying for a 6-hour OCR run that died at hour 5 |
| Backpressure | Downstream capacity (embed RPM, store write throughput) bounds upstream fetch/parse rate | A burst of 10k files triggering a rate-limit storm and a retry storm |
| Fail-soft per document | One bad file becomes a recorded error, not a failed run | One corrupt PDF blocking 50,000 good documents |
| Re-runnability | Any stage can be re-run over the raw store without re-fetching sources | Being hostage to an API that no longer serves last month's export |
| Versioning everywhere | Parser version, cleaner version, chunker version, embedding model+version, schema version all recorded per record | "Which chunker made this chunk?" becoming unanswerable; silent mixing of two chunkings |
| Small testable stages | Each stage has unit tests and a golden-file test | Parser library updates breaking production silently |
1.3 Checkpointing, resumability and backpressure#
Checkpointing means the unit of progress is small and durable. The checkpoint is not "the run finished" — it is "document doc_x has chunks chk_a…chk_f written and vectors stored". With per-document transactions (Part 3), the checkpoint is free: commit per document, record the run row, and a crash mid-run leaves every completed document consistent. What you must not do is hold one giant transaction for the whole run — that turns a crash into total rollback and hours of lost work.
Resumability follows: on restart, re-scan, re-classify against the manifest, and only unfinished work remains. Because classification is content-based, "finished" is detectable without extra bookkeeping — a document whose manifest content_hash matches its source hash and whose chunks are all present needs nothing.
Backpressure is the polite name for "don't outrun your slowest stage". In a pipeline, the slowest stage is usually the paid one (embedding/enrichment API calls) or the rate-limited one (a source API). The mechanisms:
- Bounded concurrency — a semaphore or worker-pool size, not "as many threads as files". 03.9, Part 4 owns the async mechanics.
- Token-bucket rate limiting against each provider's documented limits — 03.8, Part 9 owns the limiter; 06.2, Part 3 applies it to embeddings.
- Queue depth limits — a queue between fetch and embed that blocks (or sheds load) when full, so memory stays bounded on million-file backfills.
- Batch APIs for the expensive stages — enrichment and embedding both have batch modes that trade latency for 50%-class discounts: 03.9, Part 6 and 06.2, Part 4.
Overlapping runs are the last unguarded failure mode in this section: a cron firing while a manual run or a webhook-triggered run is still in flight can process the same documents twice — mostly harmless thanks to idempotency, but wasteful and confusing in runs. Production pipelines take a run mutex: insert a runs row with a status column flipped to running inside one transaction (or take a database advisory lock, or use the orchestrator's concurrency limits), so a second trigger exits immediately with "already running". The toy doesn't implement it — a single-operator cron doesn't need it — but it's a five-line guard worth adding before you schedule anything shared.
1.4 Fail-soft per document#
The unit of failure isolation is the document, not the run. Every per-document operation — fetch, parse, clean, chunk, enrich, embed — is wrapped so that:
- The exception is caught and recorded with stage, source URI, message and run ID.
- The document is marked
quarantined(or left at its last-good state) in the manifest. - Its dependent downstream work is skipped — you do not embed chunks you couldn't produce.
- The run continues and reports
N ok / M quarantinedin its summary.
Two subtleties worth stating now:
- A quarantined document is retried next run (its manifest row still shows the old hash, or no row exists). That's usually what you want — a transient OCR failure heals itself — but a poison document (deterministically unparseable) will fail every run forever. Track repeat offenders and alert; optionally back off per-document retry counts.
- Partial documents are worse than failed ones. If chunk 40 of 60 fails to embed, do not write 59 chunks and mark the doc ok — either retry the missing ones or quarantine the whole document version. A half-indexed document produces confident wrong answers. This is the same "all-or-nothing per document" rule that makes the transaction boundary in Part 3 sit at the document level.
1.5 Small testable stages#
Each stage should be a function (or small class) with a typed input and output, callable standalone in a test:
SourceFile --fetch--> RawBlob --parse--> ParsedDocument --clean--> CleanText
--chunk--> list[Chunk] --enrich--> list[ChunkMeta] --embed--> list[Vector]The toy pipeline in Part 4 follows exactly this shape: scan_sources, parse_clean, chunk_document, chunk_ids_for, FakeEmbedder.embed, and the store writers. In production each of those is the real thing from 05.2–05.8 and 06.2, behind the same signature. The payoff is that a parser library upgrade becomes a contract test problem (11.2), not a mystery.
Part 2: Change detection#
2.1 Why change detection is the whole game#
Re-processing everything every run is the naive correct answer — and it is unaffordable. Embedding is priced per token; parsing 50k PDFs is hours; OCR is minutes per page. The entire economics of incremental ingestion rest on answering one question cheaply and correctly: did this source meaningfully change since we last saw it?
Get it wrong in one direction and you re-pay for everything (slow, expensive, but correct). Get it wrong in the other and your index silently serves stale content — the "the policy says 30 days but it's 14 now" failure that erodes trust in the whole system. So change detection needs two properties: cheap (don't fetch content to decide whether to fetch content) and conservative (when in doubt, re-process — a false "changed" costs money, a false "unchanged" costs correctness).
2.2 Content hashing for files#
For files you control or can list, the cheapest correct signal is a content hash: sha256(bytes). It catches every change, ignores timestamps and rename-with-same-content ambiguity is handled by treating URI+hash as the identity pair.
Two refinements matter:
- Hash the bytes you store, not the file on disk. For sources where "the file" can change underneath you (a file share, a synced Drive folder), hash what you actually fetched and stored in the raw store — that's the content your chunks derive from.
- Meaningful-change hashing. Sometimes you want to ignore changes that can't affect the chunks: a trailing newline, a re-ordered JSON key, a bumped "last modified" HTML comment. The rule from 05.8, 3.2 applies: hash the canonical text — the exact post-normalisation string that will be chunked. If your cleaning is deterministic, hash its output. If a source legitimately changes only in ways cleaning erases (whitespace churn from a CMS re-export), you can hash post-clean and skip re-chunking entirely — but only when you can prove cleaning erases the difference, because post-clean hashing can also hide real changes that cleaning mangles. When in doubt, hash raw bytes.
2.3 HTTP sources: ETag and Last-Modified#
For web pages, feeds and API endpoints, the standard mechanism is the conditional request: send the validator you stored last time; the server replies 304 Not Modified (no body) if nothing changed, or 200 with new content.
ETag— an opaque version tag the server assigns to a representation. Send it back asIf-None-Match. Strongest signal; survives timestamp granularity issues.Last-Modified— a timestamp; send asIf-Modified-Since. Weaker (1-second granularity, clock skew) but universal.
# conditional_fetch.py — one GET with validators; returns (status, body, new_etag)
# Illustrative: needs network access. Requires httpx.
import httpx
def fetch_if_changed(client: httpx.Client, url: str,
etag: str | None, last_modified: str | None):
headers = {}
if etag:
headers["If-None-Match"] = etag
if last_modified:
headers["If-Modified-Since"] = last_modified
r = client.get(url, headers=headers, timeout=30.0, follow_redirects=True)
if r.status_code == 304:
return "unchanged", None, etag
r.raise_for_status()
return "changed", r.content, r.headers.get("ETag")
# usage sketch — store etag/last_modified per URL in the manifest:
# status, body, new_etag = fetch_if_changed(client, url, old_etag, old_lm)
# if status == "changed": store raw bytes, update validators, re-processThree production notes: honour Cache-Control/rate-limit headers and Retry-After on 429/503 (03.8); canonicalise the URL before keying the manifest (tracking params and fragments create phantom "new" documents); and treat a missing validator as "always changed" — first fetch stores the validators for next time.
2.4 Change feeds: webhooks, CDC and delta APIs#
Polling every file every night is fine up to a point; past it you want the source to tell you what changed. The patterns, in increasing sophistication:
| Mechanism | What it gives you | Examples (verify current docs before building) |
|---|---|---|
| Polling + hash | Correct, simple, O(corpus) work per run | filesystem snapshots, changes.list-style feeds |
| Conditional HTTP | Cheap revalidation without downloading bodies | any HTTP source with ETag/Last-Modified |
| Webhook / push channel | Near-real-time "something changed" ping; you still fetch to learn what | Google Drive changes.watch channels, Drive push notifications, generic webhooks |
| Change feed / delta API | A resumable cursor: "give me changes since token T" | Google Drive changes.list + getStartPageToken; Microsoft Graph delta (@odata.nextLink/@odata.deltaLink, deleted facet); SharePoint/OneDrive via Graph |
| Object-store events | "Object created/deleted in bucket X" events | S3 → EventBridge (Object Created, Object Deleted — all event types once the bucket opts in); SNS/SQS/Lambda destinations additionally receive an s3:TestEvent when the notification is first configured; GCS Pub/Sub notifications; Azure Event Grid |
| Database CDC | Row-level change stream from the DB itself | logical replication slots (Postgres), binlog (MySQL), cloud CDC services; preview-level here — Module 08A's tool-calling systems consume the results |
| Message queue / stream | Ordered change events you consume | Kafka-style topics, cloud queues; see Part 13 |
The important design point: a change feed gives you hints, not content. A Drive notification says "file X changed"; a Graph delta entry says "item Y modified or deleted"; an S3 event says "object Z created". Your pipeline must still fetch the current content and run the same hash → classify → process path. The feed replaces discovery, not processing. Store the feed's cursor (page token, deltaLink, replication slot position, queue offset) in the manifest so the feed itself is resumable — Drive's startPageToken and Graph's deltaLink are exactly "checkpoints" for the source side.
2.5 Directory snapshots, renames and meaningful change#
For a filesystem or object-store corpus, the snapshot diff is the change detector: list (uri, size, mtime, hash) now vs the manifest's last snapshot.
- Cheap pre-filter:
sizeandmtimecatch most changes without reading content — but mtime lies (copies, sync tools,touch), so treat it as a hint: if size+mtime match the manifest and you trust the source, skip hashing; if anything is uncertain, hash. - Renames and moves: a rename shows up as
deleted old_uri + new new_uri. Whether that's correct depends on identity: if yourdoc_idderives from the URI (05.8's default), a rename is a new document — old chunks tombstoned, new ones embedded. If the source system has a stable ID (Drive file ID, ticket ID), hash that instead and a rename keeps itsdoc_id, its chunks and its embeddings for free. This is the single highest-value identity decision in the whole lesson; 05.8, 3.5 covers it. - Tombstones: deletions must be recorded, not just absent. The manifest's
tombstonestable keeps the fact thatdoc_xwas deleted at runrun_n—doc_id,source_uri, lastcontent_hash,deleted_at,run_id— so reconciliation can verify the vector store dropped its chunks and so you can answer "when did this document disappear?" later. The appendix'sprocess_deletionwrites one inside the same transaction that removes the document and chunk rows (3.1 has the schema). - Near-duplicate churn: a CMS that rewrites every page nightly with a new timestamp in the HTML will look like 100% changed every run. If cleaning normalises the timestamp away, post-clean hashing (2.2) collapses the churn to zero work. If it doesn't, you have a source problem — fix the export or the cleaner, not the pipeline.
Part 3: The manifest and the incremental update algorithm#
3.1 The manifest schema#
The manifest is the pipeline's memory. Minimum viable schema (SQLite shown; DuckDB or Postgres work identically — pick whatever your team already runs):
CREATE TABLE documents (
doc_id TEXT PRIMARY KEY, -- content-addressed source identity (05.8)
source_uri TEXT NOT NULL UNIQUE, -- canonical URI/path — what we fetch
content_hash TEXT NOT NULL, -- sha256 of stored raw bytes
status TEXT NOT NULL, -- ok | quarantined
chunker_version TEXT NOT NULL,
parser_version TEXT NOT NULL,
run_id TEXT NOT NULL, -- last run that touched it
updated_at TEXT NOT NULL,
error TEXT -- last quarantine reason
);
CREATE TABLE chunks (
chunk_id TEXT PRIMARY KEY, -- chk_… from 05.8's scheme
doc_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
text TEXT NOT NULL,
embed_input TEXT NOT NULL,
content_hash TEXT NOT NULL,
ingested_at TEXT NOT NULL,
UNIQUE(doc_id, chunk_index)
);
CREATE TABLE runs (
run_id TEXT PRIMARY KEY, started_at TEXT, finished_at TEXT,
dry_run INTEGER NOT NULL,
seen INT, new INT, changed INT, unchanged INT, deleted INT,
chunks_new INT, chunks_reused INT, chunks_deleted INT,
embed_calls INT, errors INT
);
CREATE TABLE errors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id TEXT NOT NULL, source_uri TEXT NOT NULL,
stage TEXT NOT NULL, message TEXT NOT NULL, at TEXT NOT NULL
);
CREATE TABLE tombstones (
doc_id TEXT NOT NULL,
source_uri TEXT NOT NULL,
content_hash TEXT NOT NULL, -- hash of the last seen content
deleted_at TEXT NOT NULL,
run_id TEXT NOT NULL
);Four design notes. First, documents.content_hash is the change-detection key while chunks.content_hash/chunk_id is the embedding-reuse key — different granularities on purpose. Second, the runs row is your audit trail and your metrics source: every observability claim in Part 10 is a GROUP BY over this table. Third, documents.status/error are real state, not decoration: a failed document upserts status='quarantined' + the reason while keeping its last-good content_hash, versions and chunks — which is exactly what makes "quarantined = retry me next run" work in 3.2. Fourth, tombstones is the deletion audit trail: the document and chunk rows are gone, but the record of what was deleted, its last hash and when survives — reconciliation and "when did this disappear?" both read it. The schema itself is versioned like everything else: a live manifest that gains a column ships a schema_version marker plus a migration, the same discipline 05.8, 9.2 applies to metadata — old rows stay interpretable because the version that wrote them is recorded.
3.2 Classification: new / changed / unchanged / deleted#
flowchart TD
A["scan sources / consume change feed"] --> B{"uri in manifest?"}
B -- "no" --> NEW["NEW: full process"]
B -- "yes" --> C{"content_hash equal?"}
C -- "no" --> CHG["CHANGED: re-process, diff chunks"]
C -- "yes" --> V{"versions current AND status ok?"}
V -- "no" --> CHG
V -- "yes" --> UNCH["UNCHANGED: skip entirely"]
B -- "manifest uri not in scan" --> DEL["DELETED: tombstone + delete chunks/vectors"]
NEW --> P["parse → clean → chunk → enrich → embed-new-only"]
CHG --> P
DEL --> T["delete manifest rows + vector rows; log tombstone"]
P --> W["commit per document (atomic)"]
T --> W
W --> R["reconcile manifest ↔ vector store"]Classification is a set operation, not a per-file decision: build {uri: hash} for the scan and for the manifest, then diff. Cost is O(sources), and for change-feed sources the "scan" is just the delta since the stored cursor — the classify step doesn't care where the set came from.
"Changed" is deliberately broader than "hash differs". The classifier also re-processes a document when:
- Its stored versions are stale —
documents.chunker_version/parser_version(written on every successful run, 3.1) are compared against the running code's constants. BumpCHUNKER_VERSIONand every unchanged-content document classifieschanged, gets re-chunked under the new version, and produces all-new chunk IDs — a clean full re-chunk, exactly what 5.1 prescribes. Without this check a version bump would classify everythingunchangedand skip it forever: old-version chunks stay in the manifest and vector store while new documents arrive with new-version IDs — the silent mixed-version index this lesson exists to prevent. This is "versioning everywhere" made mechanical. - It is quarantined —
status='quarantined'means "retry me": a transient parse/OCR failure heals itself next run, and a poison document keeps failing visibly rather than disappearing.
A false changed costs a re-parse (and re-embed only for genuinely new chunk IDs); a false unchanged serves stale or mixed-version content silently. When in doubt, re-process — the same conservative bias as 2.1.
3.3 Chunk-level diffing and embedding reuse#
This is where the content-addressed chunk_id from 05.8, 3.3 pays for itself. When a document is re-processed:
- Chunk the new text → new
chunk_ids (position deliberately absent from the hash). old_ids − new_ids= retired chunks → delete their manifest rows and vector rows.new_ids − old_ids= fresh chunks → the only ones needing embedding calls.old_ids ∩ new_ids= surviving chunks → keep rows and vectors untouched.
Edit one sentence in a 200-chunk handbook: typically 1–3 chunks change, ~197 keep their IDs and embeddings. Insert a paragraph at the top: every surviving chunk keeps its ID — the nightmare scenario (re-embed the tail) only happens if your IDs contain position, which is exactly what 05.8's scheme avoids. Change the chunker version: the 3.2 version check classifies every document changed, every ID changes → clean full re-chunk, which is correct — you want a fresh index, and Part 5 covers doing it safely. 4.7 shows it running.
3.4 Atomicity: write-then-flip#
"Atomic" here means: an observer never sees a document half-updated. Two levels:
- Within a document: write the new chunk rows and delete retired ones in one transaction. The manifest commit is the flip — before it, the old version is fully visible; after it, the new version is. Never interleave "delete old chunks" and "insert new chunks" as separate commits.
- Manifest ↔ vector store: these are two systems, so true atomicity across them is impossible without a distributed transaction (which you don't want anyway). The practical pattern is write-then-flip with reconciliation: upsert new vectors first, then commit the manifest, then delete retired vectors after — ordered so the failure modes are "extra vectors" (harmless, reconciled away) rather than "missing vectors" (visibly broken). The reconciliation job (3.5) is what makes the residual inconsistency window safe.
For blue/green index swaps (whole-corpus version changes) the flip is an alias repoint — instant and reversible — covered in 5.2.
3.5 Failures mid-update and reconciliation#
A crash can land anywhere: mid-fetch, mid-parse, mid-embed-batch, between manifest commit and vector delete. The recovery rules:
- Per-document transactions mean a crash leaves each finished document consistent and the in-flight one untouched — next run re-classifies and redoes only it.
- Embed calls are the expensive part — make them idempotent by content: embedding the same
embed_inputtwice yields the same vector, and upserts are idempotent, so re-running a partially-completed embed batch is safe (just wasteful). 06.2, 5.3 covers the embedding cache that makes this cheap. - Reconciliation is the janitor: a scheduled (or end-of-run) job diffs
manifest.chunks.chunk_idagainstvector_store.chunk_idin both directions —manifest_only= chunks whose vectors are missing (re-embed them);store_only= orphan vectors (delete them). In the toy pipeline it runs at the end of every update and only reports; run with--repairandrepair_driftfixes what it found (re-embeddingmanifest_onlychunks from theembed_inputthe manifest stores, deletingstore_onlyorphans) and then re-checks. In production it runs on a schedule and after any suspected failure, because it is the only thing that detects drift you didn't cause on purpose.
Part 4: The minimal pipeline, end to end#
Everything above is real in pipeline.py — about 450 lines of pure standard library. It implements: directory scan → content-hash classify → parse/clean/chunk stand-ins → content-addressed chunk IDs → chunk diff → embed-only-fresh → per-document transactions → vector-store upsert/delete → reconciliation (with an opt-in --repair) → run report. The parse/clean/chunk/embed stages are deliberately trivial stand-ins for the real stages from 05.2–05.8 and 06.2; the pipeline machinery — classification, diffing, transactions, reconciliation — is production-shaped.
4.1 The toy corpus#
sources/ holds six files: a product handbook, a returns policy, two help-centre pages, a meeting transcript, and one deliberately broken file (<!-- POISON --> triggers the quarantine path). Create them with this script, run once from your project folder:
# make_sources.py — create the toy corpus used in Part 4.
from pathlib import Path
FILES = {
"handbook.md": """# Acme Product Handbook
## Safety
Wear eye protection and gloves when operating any Acme power tool.
## Warranty
Every Acme Drill carries a two-year limited warranty against defects.
## Battery care
Store battery packs at room temperature and charge them before first use.
## Maintenance
Clean the chuck after each job and keep vents free of dust.
""",
"returns-policy.md": """# Returns Policy
## Eligibility
Unused tools may be returned within 30 days of delivery for a full refund.
## Process
Contact support for a return authorisation number, then ship the tool back.
""",
"help-centre/billing-faq.md": """# Billing FAQ
## Invoices
Invoices are emailed on the first of each month.
## Refunds
Refunds go to the original payment method within five working days.
""",
"help-centre/reset-password.md": """# Reset your password
## Steps
Choose Forgot password on the sign-in page and follow the emailed link.
""",
"transcript-q3.txt": """Alice: Let's review Q3 priorities.
Bob: Returns tooling first, then the warranty portal.
""",
"broken-doc.md": "# Broken\n<!-- POISON -->\n",
}
for name, text in FILES.items():
path = Path("sources") / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
print(f"wrote {len(FILES)} files under sources/")wrote 6 files under sources/The chunk_document stand-in starts a new chunk at every ## heading, so this corpus yields 14 chunks (handbook 5, returns policy 3, billing FAQ 3, reset-password 2, transcript 1, nothing for the broken file). The run IDs (run_…) and timestamps in the outputs below are different on every run; the counters are what you should match. The full pipeline source is in the appendix; key excerpts:
# pipeline.py — excerpts. Full file: appendix.
CHUNKER_VERSION = "heading-v1"
PARSER_VERSION = "toy-parser-1.0"
EMBED_MODEL = "fake-embedder-v0" # deterministic pseudo-vector stand-in
def classify(manifest_docs, scanned):
"""new / changed / unchanged / deleted — one pass over both key sets."""
new, changed, unchanged, deleted = [], [], [], []
for uri, sf in scanned.items():
doc = manifest_docs.get(uri)
if doc is None:
new.append(sf)
elif (doc["content_hash"] != sf.content_hash
or doc["chunker_version"] != CHUNKER_VERSION
or doc["parser_version"] != PARSER_VERSION
or doc["status"] == "quarantined"):
changed.append(sf)
else:
unchanged.append(sf)
scanned_uris = set(scanned)
for uri, doc in manifest_docs.items():
if uri not in scanned_uris:
deleted.append(doc)
return new, changed, unchanged, deleted4.2 First run: everything is new#
$ python pipeline.py --sources sources --db pipeline.db --vectors vectors.db
run run_a9b87ed908b28946 dry_run=False
docs: 6 new, 0 changed, 0 unchanged, 0 deleted
chunks: 14 new, 0 reused, 0 deleted; embed calls: 14
quarantined: 1
reconciliation drift: {'manifest_only': [], 'store_only': []}Six sources scanned, five processed (14 chunks, 14 embed calls — everything is fresh), one quarantined. The broken file produced an errors row and a documents row with status='quarantined' — its failure is visible in the manifest itself, and because quarantined means "retry me", next run it classifies changed, not unchanged. Real output from the real code.
4.3 Second run: idempotency#
run run_9d8e94c629828529 dry_run=False
docs: 0 new, 1 changed, 5 unchanged, 0 deleted
chunks: 0 new, 0 reused, 0 deleted; embed calls: 0
quarantined: 1
reconciliation drift: {'manifest_only': [], 'store_only': []}Zero chunk work, zero embed calls — the "1 changed" is broken-doc.md being retried: its documents row now exists with status='quarantined' (the failure is recorded in the manifest itself, not just the errors table), and quarantined means retry (8.2). Drift is empty: manifest and vector store agree exactly.
4.4 Edit, delete, add: chunk-level diffing in action#
Change returns-policy.md ("30 days" → "14 days"), delete transcript-q3.txt, add pricing.md, run again. In a shell, from the project folder (sed -i '' is the macOS form; on Linux use sed -i), or make the same three changes in your editor:
sed -i '' 's/30 days/14 days/' sources/returns-policy.md
rm sources/transcript-q3.txt
printf '# Pricing\n\n## Plans\nThe Pro plan costs $49 per month billed annually.\n' > sources/pricing.md
python pipeline.py --sources sources --db pipeline.db --vectors vectors.dbrun run_a52ac436f91f3cf2 dry_run=False
docs: 1 new, 2 changed, 3 unchanged, 1 deleted
chunks: 3 new, 2 reused, 2 deleted; embed calls: 3
quarantined: 1
reconciliation drift: {'manifest_only': [], 'store_only': []}Read it as the algorithm working. docs: 1 new is pricing.md alone — both its chunks are fresh by definition. docs: 2 changed is returns-policy.md (content hash differs) plus broken-doc.md again — it never earns a success row, so its quarantine retry counts as changed every run, exactly as in §4.3. returns-policy.md produces three chunks (the # Returns Policy title is its own chunk under the ## -heading splitter): of them only the edited "Eligibility" chunk got a new ID and an embed call, while the title and "Process" chunks kept their IDs and vectors — chunks_reused: 2, both survivors inside that one document. transcript-q3.txt's single chunk was deleted with its vector, and returns-policy's one retired Eligibility ID makes chunks_deleted: 2. Three embed calls total for a corpus edit — versus fifteen for a full re-run of the 15-chunk corpus. That ratio is the business case for content-addressed IDs.
The deletion left a tombstone — the audit record that outlives the deleted rows:
$ sqlite3 pipeline.db "SELECT source_uri, deleted_at, run_id FROM tombstones"
transcript-q3.txt|2026-11-05T16:03:40+00:00|run_a52ac436f91f3cf2And the runs table keeps the full audit (a fourth idempotency run is shown for completeness — same inputs, same zero-work result):
run_id seen new changed unchanged deleted chunks_new chunks_reused chunks_deleted embed_calls errors
run_a9b87ed908b28946 6 6 0 0 0 14 0 0 14 1
run_9d8e94c629828529 6 0 1 5 0 0 0 0 0 1
run_a52ac436f91f3cf2 6 1 2 3 1 3 2 2 3 1
run_f9f6753c84939f9a 6 0 1 5 0 0 0 0 0 14.5 Dry-run mode#
--dry-run runs the full classify + diff and reports what would happen, writing nothing (the runs row is never committed). In production this is your pre-flight check before a backfill or a chunker upgrade: "this run would embed 1,240 chunks ≈ 380k tokens ≈ $X at current prices" — pair it with the cost model in 7.4.
4.6 What the toy omits — and what production adds#
Be honest about the gap; each omission maps to a later part:
- Real parsers —
parse_cleanis a stand-in; production calls 05.2–05.4's parsers with their own timeouts and fallbacks. - Real chunker/metadata —
chunk_documentis heading-naive; production uses 05.6/05.7 chunkers and 05.8's fullChunkMeta— and 05.8'smake_chunk_id/chunk_ids_forfor IDs (05.6'sChunk.chunk_idproperty is already the same position-free scheme). - Composite identity — the toy's
doc_idhashes the URI alone; production uses 05.8'stenant|system|uricomposite so two tenants' identical paths don't collide. - Raw store — there isn't one: for filesystem sources the file is the raw bytes. Connector sources would write fetched bodies to object storage first (the
RAWnode in §1.1) — that's what makes "re-parse without re-fetching" possible for APIs that no longer serve last month's export. - Real embedder —
FakeEmbedderreturns deterministic pseudo-vectors; production uses 06.2's batching/caching embedder. - A real vector store —
vectors.dbsimulates it; production writes via theVectorStoreprotocol (06.5, 7.1). - Orchestration, retries, alerts, dead-letter — Parts 6–10; the poison file is retried forever here by design.
- Connector sources — Part 12 and 2.4.
- Blue/green — the toy re-indexes in place; Part 5 is the reversible version.
4.7 What a version bump does#
The version columns earn their keep here. Bump CHUNKER_VERSION from "heading-v1" to "heading-v2" in pipeline.py — same sources, same manifest — and run again:
run run_049a509a06adc9d5 dry_run=False
docs: 0 new, 6 changed, 0 unchanged, 0 deleted
chunks: 15 new, 0 reused, 15 deleted; embed calls: 15
quarantined: 1
reconciliation drift: {'manifest_only': [], 'store_only': []}Every document classified changed — not because any content hash moved, but because each stored chunker_version is now stale. Every chunk ID embeds the version, so all 15 chunks were retired and re-created fresh: chunks_reused: 0, embed_calls: 15 — a clean full re-chunk, and the only correct outcome. The poison file still fails (now under the v2 attempt), and the version check means it can never be skipped either. Verify the state landed:
$ sqlite3 pipeline.db "SELECT source_uri, status, chunker_version FROM documents"
broken-doc.md|quarantined|heading-v1
handbook.md|ok|heading-v2
help-centre/billing-faq.md|ok|heading-v2
help-centre/reset-password.md|ok|heading-v2
returns-policy.md|ok|heading-v2
pricing.md|ok|heading-v2Two details worth noticing. First, broken-doc.md still shows heading-v1: the quarantine upsert deliberately does not overwrite the version columns — they describe the last successful ingest (it has none), and status='quarantined' is what keeps it in the retry path. Second, this in-place re-chunk mutated the live index — fine for a toy, but for a planned chunker upgrade on a real corpus you would run the same bump through Part 5's blue/green path so the old index survives for rollback. The version check is what makes both paths correct: it guarantees no document is ever silently skipped just because its stored versions are stale.
Part 5: Versioned indexes and reindexing#
Deep-dive
5.1 When you must re-embed everything#
Incremental updates handle content changes. They do not handle model changes. You must plan a full re-embed when any of these change:
| Trigger | Why everything changes |
|---|---|
| New embedding model (or new version/dimensions) | Vectors from different models are incomparable — 02.3, 7.5 and 06.1, Part 9 own this; old and new vectors can't share an index |
| New chunking strategy/version | chunker_version is in every chunk_id and compared at classify time (3.2), so all docs re-process and all chunks are "new" |
| New cleaning rules that alter text | Chunk texts change → new chunk IDs → new embeddings (the content hash is downstream of cleaning) |
| Embed-input changes | Breadcrumb format, embed_input composition, metadata fields fed to the embedder |
| Index/migration | Moving vector stores, changing distance metric, quantization changes that alter recall |
| Backfill of a field | Adding a filterable metadata field is cheap (no re-embed); adding one that feeds embed_input is a re-embed |
The decision rule: if the bytes sent to the embedder change for any chunk, that chunk needs a new vector. Everything else is a metadata update.
5.2 Blue/green indexes and aliases#
The safe pattern for a full re-embed is blue/green: build the new index alongside the old one, verify it, then flip a pointer.
flowchart LR
subgraph old ["blue (live)"]
OI[("index_v1<br/>model A, chunker-1")]
end
subgraph new ["green (building)"]
GI[("index_v2<br/>model B, chunker-2")]
end
SRC["manifest + raw store"] -->|"re-embed all chunks"| GI
SRC --> OI
Q["queries"] --> ALIAS{"alias: 'prod'"}
ALIAS -.->|"before cutover"| OI
ALIAS -.->|"after cutover"| GI
GI --> EV["shadow evaluation"]
EV -->|"pass"| FLIP["repoint alias → instant, reversible"]
FLIP --> ALIASConcretely:
- Build green against a fresh manifest and a fresh index. This is the part people get wrong: the green build does not share the live manifest. The
chunkstable is keyed bydoc_id+chunk_index, so writing green chunks into the live manifest would overwrite blue's chunk inventory — andprocess_documentretires old chunk IDs, which would delete blue's vectors. Instead, point the pipeline at a second manifest (pipeline_green.db) and second vector store (vectors_green.db); with an empty manifest every document classifiesnewand the whole corpus re-processes under the new versions — the version-aware classify from 3.2 is what makes the in-place path (like 4.7) safe when you deliberately skip blue/green on a small corpus. Blue's manifest+store stay byte-for-byte frozen, which is exactly what rollback and shadow evaluation need. Write every chunk fresh into the green index namespace/collection/table (your store's equivalent of a versioned index — Qdrant collections, Pinecone indexes/namespaces, a Postgres schema or table suffix, Chroma collections). - Keep blue serving: production queries continue hitting blue. Nothing user-visible changes during the build, which may take hours or days.
- Shadow-evaluate: replay a sample of real queries (or your eval set from 10A.2/Module 10A) against both indexes; compare recall and answer quality before cutover (5.3).
- Flip the alias and the manifest: repoint
prod(or your store's alias mechanism — Pinecone aliases, Qdrant collection aliases where available, or an app-level config value) to green, and promotepipeline_green.db/vectors_green.dbto the live paths in the same config change. The manifest and index version together — never flip one without the other. Sources that changed during the build are not lost: the next incremental run on the promoted manifest scans live sources and picks them up as ordinarychanged/newwork. - Retire blue later: keep it for a defined window (days to weeks) as the rollback target and for diffing, then delete. Deleting early is how you discover you needed it.
5.3 Shadow evaluation before cutover#
"Green built successfully" is not "green is better". Before flipping:
- Replay your question set (the synthetic eval set from 10A.2, or Module 10A's retrieval eval) against blue and green; compare recall@k and answer-bearing-chunk hit rate.
- Diff a sample of top-k results for real logged queries — a new model can change which chunks surface even when recall is equal.
- Check latency and cost: new index size, quantization differences, any per-query cost change.
- Keep the comparison reproducible: same queries, same k, same filters — write the harness once and run it against both aliases (06.5's
VectorStoreprotocol makes "same queries, different store" a loop, not a rewrite).
If green is worse, you lost build cost but not correctness — blue never stopped serving. That's the entire point of the pattern.
5.4 Cost estimation, backfills and rollback#
Cost estimation for a full re-embed is arithmetic you should do before starting:
# reindex_cost.py — estimate a full re-embed before you commit to it.
# Illustrative prices are parameters, not facts — check your provider's page.
def estimate_reindex(n_chunks: int, avg_chunk_tokens: int,
usd_per_1m_tokens: float,
batch_discount: float = 1.0) -> dict:
total_tokens = n_chunks * avg_chunk_tokens
cost = total_tokens / 1_000_000 * usd_per_1m_tokens * batch_discount
return {
"chunks": n_chunks,
"tokens": total_tokens,
"usd": round(cost, 2),
"hours_at_50k_tok_min": round(total_tokens / 50_000 / 60, 1),
}
# example: 120k chunks x 180 tokens, $0.02/1M tokens, batch API at 50% off
print(estimate_reindex(120_000, 180, 0.02, batch_discount=0.5)){'chunks': 120000, 'tokens': 21600000, 'usd': 0.22, 'hours_at_50k_tok_min': 7.2}(Real output — pure arithmetic. The dollar figure is illustrative because the token price is a parameter; embedding prices change, so always plug in today's number from the provider's pricing page — 06.1 shows where they live.)
Three practical notes:
- Batch APIs roughly halve the price for embeddings that don't need instant turnaround — but a reindex is the batch workload, so use it: 06.2, Part 4 owns the mechanics.
- Backfills are reindexes with extra steps: when you add a metadata field that requires touching every chunk, run it as a backfill job — same blue/green discipline if the field feeds retrieval, plain upserts if it's filter-only. Version the backfill (
backfill_chunker_v2_2026_11) so you can prove which records got it. - Rollback is a repoint, not a restore — as long as you kept blue. If you deleted blue "to save space", rollback means re-embedding everything again; keep the old index until the new one has survived a full evaluation cycle.
Part 6: Orchestration#
Deep-dive
6.1 The options landscape#
"Orchestration" is the layer that decides when the pipeline runs, retries failures, and shows you what happened. The spectrum, cheapest to most capable:
| Option | What it gives you | What it doesn't | Fits when |
|---|---|---|---|
| Plain Python + cron/systemd/launchd | A script on a timer; your own logging | No UI, no retries beyond what you code, no run history | Single node, <~daily cadence, you can SSH in |
Task runner (make, just, nox, tox) |
Defined steps, local reproducibility | Still manual/scheduled externally; no distributed state | Dev/CI convenience, not production scheduling |
| Queue workers (Celery, RQ, Dramatiq, arq) | Job queue + workers + retries; per-job concurrency | You model the DAG yourself; state lives in the broker/result backend | Event-driven per-document work at modest scale |
| Workflow orchestrators (Prefect, Dagster, Airflow, Temporal) | DAGs/assets, retries, scheduling, UI, run history, alerting hooks | A server to run; a framework to learn | Team pipelines, SLAs, audits, multiple pipelines |
| Cloud-native (Step Functions, Cloud Workflows, Dataflow, Cloud Composer) | Managed infra, IAM, integrations | Vendor lock-in, cost at scale, less Python-native | Already deep in one cloud; big data workloads |
| Streaming (Kafka-style, Kinesis, Pub/Sub) | Ordered, durable event flow between services | The most moving parts; ordering/semantics complexity | Near-real-time requirements (Part 13) |
The honest default for an AI ingestion pipeline: start with plain Python + a scheduler (the Part 4 pipeline is this), graduate to a queue when work becomes event-driven or parallel, and adopt a workflow orchestrator when you have multiple pipelines, SLAs, or a team that needs the UI and audit trail. Most teams over-buy orchestration on day one and under-invest in idempotency — the thing that actually determines whether re-runs are safe.
6.2 Queue workers: Celery, RQ, Dramatiq, arq#
All four are Python task-queue libraries: your code enqueues a job (document URI, chunk batch, embed request), workers pick it up. Versions verified on PyPI as of November 2026.
| Celery 5.7 | RQ 3.0 | Dramatiq 2.2 | arq 0.28 | |
|---|---|---|---|---|
| Broker | RabbitMQ / Redis / others | Redis | RabbitMQ / Redis | Redis |
| Model | @app.task + delay()/apply_async(); chords/groups for fan-out |
Queue().enqueue(func, *args); job.timeout, result_ttl |
@dramatiq.actor + actor.send()/send_with_options(delay=); middleware pipeline |
@worker.func + redis.enqueue_job(name, *args); WorkerSettings |
| Async style | sync or asyncio via pools/gevent |
sync | sync or async def actors |
native asyncio |
| Retries | autoretry_for, retry_backoff |
job-level Retry |
max_retries + middleware |
max_tries per function |
| Scheduling | beat (cron-ish) | ScheduledJobRegistry/cron |
no built-in scheduler | _defer_by/_defer_until |
| Best for | Mature, batteries-included, huge ecosystem | Simplest Redis queue | Clean middleware, RabbitMQ semantics | Async-native Python shops |
The ingestion-relevant differences are small: all give you "enqueue per document/chunk", retries, and result inspection. Choose on team familiarity and broker preference — none of them gives you the pipeline semantics (manifest, diffing, reconciliation) for free; that's still your code. Where they genuinely help: parallelism and isolation — a worker crash kills one job, not the run; retries are per-job; and queues naturally implement backpressure (bounded queue depth).
6.3 Workflow orchestrators: Prefect, Dagster, Airflow, Temporal#
These model the pipeline as a DAG of tasks/assets with scheduling, retries, run history and a UI. All verified against current docs as of November 2026.
| Prefect 3.9 | Dagster 1.13 | Airflow 3.3 | Temporal (SDK 1.35) | |
|---|---|---|---|---|
| Core idea | @flow/@task decorate plain Python; dynamic graph at runtime |
@dg.asset functions + Definitions; assets as first-class data products |
@dag/@task TaskFlow (Airflow 3: import from airflow.sdk) |
@workflow.defn/@activity.defn; durable execution — state persisted server-side |
| State model | Flow/task run states (Completed/Failed/...) | Asset materializations + observations | Task instances, DAG runs | Event history replay — survives crashes inside a run |
| Retries | retries=, retry_delay_seconds per task/flow |
RetryPolicy on ops/assets |
retries on tasks |
Retry policies per activity; workflow code replays deterministically |
| Scheduling | .serve()/deployments, cron |
Schedules/sensors/automation conditions | schedule= on the DAG (cron, timetable) |
Schedules on the Worker/Client |
| Server needed | Optional (local-first; Prefect server/Cloud for UI+concurrency) | dg dev launches UI+daemon; Dagster+ for prod |
Airflow components (scheduler, API server, workers) — heaviest to self-host | Temporal server (dev server for local) — heaviest conceptually, strongest guarantees |
| Data-aware? | No — generic tasks | Yes — assets, partitions, backfills, freshness policies are the point | Partitions/backfills yes; asset model thinner | No — pure execution engine |
| Best for | Python-native pipelines wanting simplicity + UI | Data-platform teams wanting asset-centric modelling | Established data-engineering shops, many existing DAGs | Long-running, mission-critical, exactly-once-ish workflows |
Two notes specific to 2026:
- Airflow 3 moved the authoring API. The decorators now live in
airflow.sdk(from airflow.sdk import dag, task), notairflow.decorators, and task code can't touch the metadata DB directly — it uses the Task SDK/context. Code written for Airflow 2 needs porting; check the public interface docs before copying examples. - Temporal is a different beast: your "pipeline" is a workflow definition whose progress is replayed from an event history on the server, so a crash mid-run resumes inside the workflow, not just between tasks. That's the strongest resumability guarantee available — and the most machinery. For ingestion pipelines it's usually overkill unless runs are long, expensive and must not restart.
6.4 Minimal Prefect version (illustrative)#
Prefect 3 keeps your pipeline readable as plain Python — the orchestrator wraps it, it doesn't replace it. prefect (the sample was checked against 3.9.1, the version this path tested; 3.9.2 followed on 6 November 2026, and a plain install gives you the newest release):
# pipeline_prefect.py — the Part 4 pipeline as Prefect tasks.
# Illustrative: requires `uv add prefect` and `prefect server start`
# (or Prefect Cloud) for the UI; the flow also runs locally without one.
import sqlite3
from pathlib import Path
from prefect import flow, task
# Reuse the Part 4 functions by importing pipeline.py (same folder):
from pipeline import (FakeEmbedder, classify, open_manifest, open_vector_store,
process_deletion, process_document, reconcile,
run_update, scan_sources)
@task(retries=2, retry_delay_seconds=30, timeout_seconds=600)
def scan_and_classify(sources_dir: str):
"""One task = one checkpointable unit. Returns the work lists."""
manifest = open_manifest(Path("pipeline.db"))
manifest.row_factory = sqlite3.Row
scanned = scan_sources(Path(sources_dir))
docs = {r["source_uri"]: dict(r) for r in manifest.execute(
"SELECT * FROM documents")}
return classify(docs, scanned), scanned
@task(retries=1, retry_delay_seconds=10)
def process_one(sf, run_id: str) -> dict:
"""Per-document task: Prefect retries the *task*, the manifest makes
re-processing cheap and safe (idempotent by content hash)."""
manifest = open_manifest(Path("pipeline.db"))
vectors = open_vector_store(Path("vectors.db"))
return process_document(sf, manifest, vectors, FakeEmbedder(),
run_id, dry_run=False)
@flow
def ingest(sources_dir: str = "sources") -> dict:
(new, changed, unchanged, deleted), scanned = scan_and_classify(sources_dir)
run_id = "run_prefect_demo"
stats = [process_one.submit(sf, run_id) for sf in new + changed]
results = [s.result() for s in stats]
# deletions + reconciliation would follow the same pattern
return {"processed": len(results),
"embed_calls": sum(r["embed_calls"] for r in results)}
if __name__ == "__main__":
ingest.serve(name="kestrel-ingest", cron="0 2 * * *") # nightly at 02:00What the orchestrator buys you here: per-task retries with backoff, a run history UI, scheduled execution via .serve()/deployments, and the ability to re-run just the failed task. What it does not buy you: the manifest, diffing and reconciliation are still your code — Prefect doesn't know what a "document" is.
6.5 Minimal Dagster version (illustrative)#
Dagster's twist: your pipeline outputs are assets (an asset depends on another by naming it as a function parameter, as classified_changes(scanned_sources) does below; Dagster's default I/O manager pickles each returned value to disk, so values must be picklable — the SourceFile dataclass is) — named data products with dependencies, freshness and lineage built in. dagster (the sample was checked against 1.13.28 as of November 2026), scaffolded with uvx create-dagster project then dg dev for the UI:
# defs/assets.py — Dagster assets mirror the pipeline stages.
# Illustrative: requires the Dagster project scaffold; not run here.
import sqlite3
from pathlib import Path
import dagster as dg
from pipeline import (FakeEmbedder, classify, open_manifest,
open_vector_store, process_document, scan_sources)
@dg.asset
def scanned_sources() -> list:
"""Asset 1: the snapshot of what exists upstream."""
return list(scan_sources(Path("sources")).values())
@dg.asset
def classified_changes(scanned_sources) -> tuple:
"""Asset 2: the manifest diff — new/changed/unchanged/deleted."""
manifest = open_manifest(Path("pipeline.db"))
manifest.row_factory = sqlite3.Row
docs = {r["source_uri"]: dict(r) for r in manifest.execute(
"SELECT * FROM documents")}
return classify(docs, {s.uri: s for s in scanned_sources})
@dg.asset
def ingested_chunks(classified_changes) -> dict:
"""Asset 3: process the changed set; unchanged docs are skipped by design."""
new, changed, _, _ = classified_changes
manifest = open_manifest(Path("pipeline.db"))
vectors = open_vector_store(Path("vectors.db"))
run_id = "run_dagster_demo"
out = [process_document(sf, manifest, vectors, FakeEmbedder(), run_id,
dry_run=False) for sf in new + changed]
return {"embed_calls": sum(r["embed_calls"] for r in out)}Dagster's payoff is the asset graph: each stage is a named, observable, independently-materializable product, and Dagster tracks freshness/lineage/runs for you. The cost: more machinery (project scaffold, dg CLI, definitions loading) and a data-platform mental model. For a single-document-corpus pipeline it's heavier than Prefect; for a multi-source data platform it's often the right tool.
6.6 The decision table#
| Your situation | Start with | Graduate to |
|---|---|---|
| One engineer, nightly batch, <10k docs | Plain Python + cron/launchd (Part 4 as-is) | Add a queue when per-doc work parallelises |
| Event-driven (webhooks, uploads), need retries per item | Queue worker (arq if async, Dramatiq/RQ if sync, Celery if you need chords/groups) | Orchestrator when you have multiple pipelines |
| Team pipeline, need run history/UI/audit, SLAs | Prefect (simplest Python-native) or Dagster (asset-centric data platform) | Temporal if runs are long, expensive, must-resume |
| Existing Airflow shop / many DAGs | Airflow 3 (port to airflow.sdk imports) |
— |
| Deep in one cloud, huge data volumes | Cloud-native (Step Functions/Dataflow/Composer) | — |
| Sub-hour freshness, event streams | Streaming (Part 13) | — |
The anti-pattern to avoid: adopting Temporal/Airflow for a pipeline that runs nightly over 500 files. The orchestration tax (server, concepts, debugging) exceeds the benefit; your idempotent Python script plus cron is genuinely sufficient — and you can always wrap it later.
Part 7: Concurrency, rate limits and cost control#
Deep-dive
7.1 Safe parallelism for parse/embed#
Two different parallelism axes, don't confuse them:
- Across documents — parse/clean/chunk are CPU/IO-bound and embarrassingly parallel. Bound by cores and memory (a 2 GB PDF can OOM a worker — 8.3). Process pools for CPU-bound parsing, threads for IO-bound fetching.
- Across API calls — embedding/enrichment calls are network-bound and rate-limited. Bound by the provider's limits, not your cores. The mechanics —
asyncio.Semaphore, token buckets,TaskGroupvsgather— are 03.9, Part 4–5 and 06.2, Part 3; this lesson only insists on the pipeline-level rule: the concurrency budget is a config value per provider, set from observed 429 rates, not a guess.
A sane shape: a bounded worker pool where each worker owns one document end-to-end (parse→chunk→embed→write). Per-document isolation means a slow or failing doc occupies one worker, not the pipeline; the manifest makes its partial work resumable.
7.2 Provider rate limits in the pipeline#
You will hit provider limits in two places: the embedder (06.2 owns its batching/TPM budgeting) and any LLM enrichment (classification, tagging, summaries — 05.8, Part 7 owns the enrichment design). The pipeline-level rules:
- One limiter per provider credential, shared across all pipeline stages that call it — don't let parse-time enrichment and embed-time enrichment each think they have the full quota.
- Respect
Retry-Afterand backoff — 03.8, Parts 7–9 own the retry machinery; the pipeline just needs to treat rate-limit errors as stage-level retryable failures, not document poison. - Ramp up gradually — providers penalise sudden traffic spikes; start workers low and increase while watching 429 rates (03.8, 9.4, 03.9, 4.7).
- Budget tokens/cost per run — a config cap ("this run may spend at most $X") checked before each paid stage; exceeding it fails the run cleanly rather than burning budget on a runaway backfill.
7.3 Batch APIs for enrichment#
Enrichment (tagging, classification, summaries, hypothetical questions) is the pipeline stage most suited to batch APIs: it's not latency-sensitive, it's chunky, and batch endpoints typically cost roughly half of synchronous calls. 03.9, Part 6 owns the batch lifecycle (build JSONL, submit, poll/webhook, reconcile by custom_id); 06.2, Part 4 covers embedding batches specifically.
The pipeline-level pattern: enrichment is a separate stage with its own checkpoint — collect the chunks needing enrichment into a batch job, submit, and on completion write results back keyed by chunk_id. If the batch fails or the run crashes, the manifest shows which chunks still lack enrichment and the next run resubmits only those. Never let an enrichment batch block the parse/chunk/embed path — they're independent pipelines that happen to share a corpus.
7.4 Budgets, dry-run cost estimates and guardrails#
Before any paid stage at scale, produce a cost estimate and gate on it:
# cost_gate.py — dry-run cost estimate before a paid stage.
# Illustrative: prices are parameters; check provider pages for current values.
def estimate_embed_cost(n_chunks: int, avg_tokens: int,
usd_per_1m: float, batch: bool = True) -> float:
tokens = n_chunks * avg_tokens
price = usd_per_1m * (0.5 if batch else 1.0) # batch ~50%: verify per provider
return round(tokens / 1_000_000 * price, 2)
def estimate_enrich_cost(n_items: int, in_tok: int, out_tok: int,
in_price: float, out_price: float) -> float:
return round(n_items * (in_tok * in_price + out_tok * out_price)
/ 1_000_000, 2)Guardrails worth implementing on day one:
- Per-run budget cap — refuse to start a stage that would exceed it; alert rather than silently truncate.
- Per-document cost ceiling — a single pathological document (a 5,000-page PDF → 40k chunks) shouldn't be able to spend the whole budget; cap chunks-per-doc and route the rest to quarantine for review.
- Dry-run mode — always available, always the default for backfills and reindexes: report counts and estimated cost, write nothing.
- Cost in the run report — tokens and dollars per stage per run, so a cost anomaly is visible in the same dashboard as a failure anomaly (Part 10).
Part 8: Error handling and resilience#
Deep-dive
8.1 Per-document isolation with structured errors#
The pattern from 1.4, made concrete. Every per-document stage wraps its work and records a structured error — never a bare except: pass, never a crash:
def process_document_safe(sf, manifest, vectors, embedder, run_id):
try:
return process_document(sf, manifest, vectors, embedder, run_id,
dry_run=False)
except Exception as exc: # last-resort isolation
record_error(manifest, run_id, sf.uri, "pipeline",
f"{type(exc).__name__}: {exc}")
return {"status": "quarantined", "error": str(exc)}The errors table (schema in 3.1) captures run_id, source_uri, stage, message, at — enough to answer "what failed, when, where, why" without grep-ing logs. Stage-level errors (parse vs chunk vs embed) are recorded at the stage that raised them; the outer wrapper catches anything the stage didn't.
8.2 Retry policies, poison documents and the dead-letter#
Three distinct failure classes need three different responses:
| Failure | Example | Response |
|---|---|---|
| Transient | network timeout, 429, 503, source API blip | Retry with backoff — 03.8 owns the policy; pipeline applies it per stage |
| Document-specific | corrupt PDF, unsupported format, OCR failure | Quarantine: record error, keep last-good manifest state, continue. Retried next run (may heal) |
| Poison | deterministically unparseable file, triggers a crash/OOM | Dead-letter after N attempts: move to a quarantine area, alert, stop retrying — otherwise it fails every run forever |
The poison-document pattern: track per-document failure count in the manifest (errors count per source_uri); after a threshold (say 3 consecutive failures), mark the document dead_lettered, exclude it from future runs, and surface it in the run report and alerts. The file isn't deleted — it's preserved for human review, because "the parser can't read it" is a signal, not noise.
8.3 Timeouts, memory limits and resumability#
- Parser timeouts: a parser that hangs on a malformed file blocks a worker forever. Wrap each parse in a timeout (subprocess isolation for untrusted files — Module 12 covers the security angle); on timeout, quarantine.
- Memory limits: run memory-hungry stages (OCR, large-PDF parsing, big embeddings batches) in bounded workers or subprocesses with memory caps; stream large files rather than
read()-ing 2 GB into a string. - Resumability after crash: per-document transactions mean a crash loses at most the in-flight document. On restart, re-scan → re-classify → the manifest shows exactly what's done; only unfinished work remains. For within-document resumability (a 500-page OCR that dies at page 300), checkpoint at page/batch granularity inside the stage — that's a stage-level concern, but the pipeline should pass a "resume from" hint where the stage supports it.
Part 9: Security and compliance in pipelines#
Deep-dive
9.1 Secrets and least privilege#
- Secrets via env/.env, never in code, config files committed to git, or logs.
python-dotenvfor local dev; your platform's secret manager in production. 03.1 covers the.envpattern. - Least-privilege connectors: the Drive service account should have read on the corpus folder only, not your whole Drive; the S3 role should have
s3:GetObject/ListBucketon the corpus prefix, not account admin; the vector-store key should have write on the index, not delete-everything. Scope every credential to exactly what the pipeline stage needs. - No secrets in the manifest or logs: the manifest stores URIs and hashes, not credentials or signed URLs (signed URLs expire and leak). If a fetch needs a token, fetch-time only.
9.2 PII handling as a pipeline stage#
PII detection/redaction is a stage, not an afterthought — and it must run before text reaches the embedder or any provider (05.5 owns the detection/redaction design; 05.8, Part 10 owns metadata minimisation). Pipeline-level rules:
- PII handling is versioned like every other stage (
pii_redactor_v1) — a change to redaction rules is a content change that may require re-chunking/re-embedding affected docs, so treat it as a pipeline-version bump. - The raw store keeps the unredacted original (under access control) so redaction is reversible for authorised humans — but the indexed corpus only ever sees redacted text.
- Log hygiene: never log document content, only URIs, hashes, counts and error messages. Error messages must not echo the offending text.
9.3 Deletion requests (right to erasure)#
"Delete this customer's data" must propagate through every copy: raw store objects, manifest rows, chunk rows, vector rows, embedding caches, search indexes, backups (within their retention policy), and any derived artefacts (synthetic data generated from it — 10A.2). The pipeline supports this with:
- A deletion path keyed by identity — you must be able to find every artefact for a given person/document:
doc_id/source_uri→ chunks → vectors → raw object. If PII is embedded in chunk text, deletion means deleting those chunks, not just filtering them out of results. - A deletion job, not a manual SQL session — same code path as the tombstone flow (2.5, 3.2), but triggered by a request and audited.
- Backup awareness — deleted data persists in backups until rotation; your privacy policy/retention schedule must account for it (legal question — say so, don't guess; Module 12 previews the compliance frame).
9.4 Tenant isolation and audit logs#
For multi-tenant corpora, the pipeline must carry tenant_id through every artefact (05.8, Part 5 owns the ACL model) and the manifest must record which tenant each document belongs to — you can't enforce isolation at query time if the pipeline never recorded it. Audit logs (who ran what, when, on which sources, with what result) come free from the runs/errors tables plus access logs on the stores; make sure they're retained long enough to answer "what happened to this document last Tuesday?".
9.5 Data residency and regional constraints#
Data residency is the requirement that data physically lives in a given region — a legal or contractual constraint (privacy regimes, government data, customer terms), not a performance one. An ingestion pipeline touches data in four places, and residency applies to all of them:
- Raw store — the fetched bytes; choose a region-pinned bucket or cluster.
- Manifest — URIs and hashes are metadata, but still data about your corpus; same region discipline.
- Vector store — chunk text sits beside the vectors for serving and citations; the easiest place to forget.
- Provider calls — the embedder and any LLM enrichment send chunk text out of your infrastructure to the provider's region. A residency requirement can forbid that outright, or constrain which provider/endpoint you may use — check each provider's data-residency documentation before choosing models. 02.9, Part 9 owns the privacy frame; Module 12 previews the compliance side.
When residency forbids provider calls, the escape hatch is self-hosted open-weight models: a locally-run embedding model keeps chunk text on your own hardware (06.1, Part 4). The trade-off is operational — GPU capacity, model updates, your own scaling — versus compliance, and it must be decided before the pipeline is built: retrofitting residency means re-architecting where data flows, not just where it is stored. This is an engineering note, not legal advice.
Part 10: Observability#
Deep-dive
10.1 Structured logs per stage#
Every stage emits structured (JSON) log lines with run_id, stage, source_uri/doc_id, duration_ms, status, and counters — not print() statements. The run_id is the join key that lets you reconstruct one run's story across stages and stores. Per-document failures log at WARN/ERROR with the structured error; per-run summaries log counts at INFO.
10.2 The metrics that matter#
Derivable entirely from the runs/errors/documents tables:
| Metric | From | Why |
|---|---|---|
| Docs/sec per stage | runs timing + counts |
Throughput regression = upstream or downstream problem |
| Failure/quarantine rate | errors count / seen |
Parser breakage, source degradation, poison docs |
| Embed calls + tokens + cost | embed_calls, token counts, price params |
The bill; anomaly = runaway backfill or chunker bug |
| Staleness lag | now − source.last_modified vs freshness SLA |
"How old is the index?" — the metric users actually feel |
| Reuse ratio | chunks_reused / (reused+new) |
Health of content-addressing; sudden drop = chunker churn |
| Drift | reconciliation output | Manifest↔store consistency — should always be zero |
10.3 Run reports, lineage and freshness SLAs#
- Run report: end-of-run summary (the toy prints one; production writes it to the
runstable and/or a dashboard) — counts per classification, per-stage timings, errors, cost, drift. A run that ends withdrift ≠ 0orerrors > thresholdshould alert, not just log. - Lineage: every chunk already carries
lineage.*from 05.8, 2.5 — parser name/version, cleaner version, chunker version, embed model — so "which version produced this bad chunk?" is a metadata query, not an investigation. - Freshness SLA: define it ("index reflects sources within 1 hour") and measure it as
source_change_time → indexed_timelag; alert when p95 lag exceeds it. This is the number that decides whether you need polling, change feeds, or streaming (Part 13). - Dashboards are a Module 11A concern; the pipeline's job is emitting the metrics, not rendering them.
Part 11: Testing pipelines#
Deep-dive
11.1 Unit tests per stage#
Each stage function gets unit tests on small fixtures: chunk_document on a two-heading text, classify on a hand-built manifest dict, parse_clean on edge-case inputs. Because stages are pure-ish, tests are fast and deterministic — no mocks of external services needed for the core logic.
11.2 End-to-end fixtures and contract tests#
- Golden documents: keep a small set of representative files (a tricky PDF, a malformed HTML page, a scanned page) with expected outputs (chunk count, key phrases present, no exceptions). Run the full pipeline on them in CI; a parser-library upgrade that changes output fails the golden test before it reaches production.
- Idempotency property test: run the pipeline twice on the fixture folder; assert the second run produces zero chunk/embed work and identical manifest state. This is the single most valuable pipeline test — it catches non-determinism (timestamps in IDs, unordered iteration, "current time" in a stage).
- Contract tests for parsers: when a parsing library updates, its output shape may change subtly (different block types, reordered text). Pin the version, and have a test asserting the
ParsedDocumentfields your pipeline depends on still exist and look sane — 05.2'sParsedDocumentmodel is the contract. - CI: the whole suite runs with no network and no keys (the toy pipeline proves this is possible); provider-touching stages get mocked or skipped in CI and tested against recorded fixtures.
11.3 The test pyramid for pipelines#
Many cheap stage tests → fewer golden-document end-to-end tests → rare full-corpus dry-runs before releases. The dry-run-before-release habit catches "this chunker upgrade will re-embed 2M chunks" before you push it.
Part 12: Connectors and frameworks#
Reference
12.1 What the frameworks give you#
| Framework | What it provides | Verified (Nov 2026) | The trade-off |
|---|---|---|---|
LlamaIndex IngestionPipeline |
transformations=[splitter, extractor, embedder]; pipeline.run(documents=...); per-node+transform caching; num_workers parallelism; SimpleDirectoryReader and a large reader ecosystem |
llama-index-core 0.14.25 |
Opinionated node/Document model; caching keyed to its objects; less control over stage boundaries |
| LangChain loaders + splitters | DirectoryLoader, WebBaseLoader, TextLoader, PyPDFLoader etc.; RecursiveCharacterTextSplitter and friends |
langchain-core 1.8.x, langchain-text-splitters 1.1.x; the DirectoryLoader, WebBaseLoader and PyPDFLoader classes come from langchain-community 0.4.2, which is sunset and archived (22 May 2026): use a partner package or your own loader (08F.4, 3.7, 08F.9, Part 2) |
Loader quality varies; abstraction can hide failure modes; version churn between langchain/partner packages, and the community loaders no longer receive fixes |
| Haystack | Document converters + DocumentSplitter preprocessors; pipeline abstraction |
haystack-ai 3.4.1 |
Strong for search/RAG pipelines; heavier conceptual model |
| Unstructured | partition_* functions turning many formats into elements |
unstructured 0.27.36 |
Great format coverage; heavy deps; you're still building the pipeline around it |
| dlt (data load tool) | Python-first library for loading API/database data with incremental cursors and append/replace/merge write dispositions |
dlt 1.32.0 (Apache-2.0) |
Strong for extracting and loading structured sources (SaaS APIs, databases) into a warehouse or lake that your pipeline then reads; it does not parse, chunk or embed |
| CocoIndex | A declarative incremental-indexing framework (Rust core, Python API): you declare transformations and targets such as pgvector, and it re-runs only what changed, keyed on input and function-code hashes, with lineage back to the source | cocoindex 1.1.1 (Apache-2.0; its performance claims are the project's own, so measure before relying on them) |
It is a manifest-and-diff engine, so it replaces part of what this lesson hand-rolls — a good thing to evaluate once you understand the algorithm; you inherit its model, targets and release cadence |
| Airbyte / ELT connectors | Managed source→destination sync for SaaS/db sources | pattern-level; verify current connectors | Solves extraction for structured sources, not parsing/chunking/embedding; a complement, not a replacement |
| Managed ingestion (OpenAI vector stores and file search, Gemini File Search, cloud knowledge-base sync jobs, search-service indexers) | The provider parses, chunks, embeds and indexes files you upload or point it at | owned by 07.7 | Least code, least control: chunking, metadata and change detection follow the service's rules, and per-user ACLs usually cannot be expressed. A reasonable first version for a prototype; read 07.7's decision table before committing |
12.2 The lock-in / hidden-behaviour trade-off#
Frameworks accelerate the stages but the pipeline — manifest, change detection, reconciliation, versioning — is still yours. The risks to weigh:
- Hidden state: a framework's cache or docstore can silently skip work your manifest thinks happened — keep your manifest authoritative and treat framework caches as disposable accelerators.
- Abstraction leakage: when a loader fails, you need to know whether it was the fetch, the parse, or the framework's retry — framework logs help but the structured error must still name the real stage.
- Version churn: these libraries move fast (LangChain's package split is exhibit A); pin versions and lean on contract tests (11.2).
- Escape hatch: whatever you choose, keep your stage functions behind your own signatures (the Part 4 shape) so swapping a framework in or out doesn't rewrite the pipeline.
A useful way to compare any of them with this lesson: ask what plays the manifest (where does "what did I already process, with which code version?" live), what is the change signal (hash, cursor, feed), and how does a deletion propagate. If a framework cannot answer all three, you still own that part.
Recommendation: hand-roll the pipeline skeleton (it's ~400 lines and you understand every line); use framework loaders/partitioners for the stages where they genuinely save time (PDF/Office parsing, SaaS connectors); avoid framework orchestration unless you're already bought into its ecosystem. The pipeline is the part you can't afford to have be a black box.
Part 13: Streaming and near-real-time ingestion#
Reference
13.1 From batch to near-real-time#
The nightly batch is the right default for most corpora. You need streaming/near-real-time when the freshness SLA is minutes-to-hours: a help centre that must reflect edits quickly, a ticketing system feeding a support bot, a regulatory corpus where "stale" is a liability. The shape:
flowchart LR
SRC["source change"] --> WH["webhook / queue / change feed"]
WH --> Q[("queue")]
Q --> D["debounce + coalesce"]
D --> WK["worker: fetch → classify → process (same pipeline!)"]
WK --> V[("vector store")]
WK --> M[("manifest")]The crucial point: the per-document processing is identical — streaming changes discovery and scheduling, not the parse→chunk→embed→write path. A webhook handler doesn't parse the document; it enqueues "document X changed" and the worker runs the same process_document as the batch pipeline.
13.2 Ordering, exactly-once vs at-least-once#
- Ordering: change feeds are roughly ordered but not guaranteed; two rapid edits to one document can arrive out of order or coalesce. Your defence is not ordering — it's the content hash: processing an older snapshot after a newer one produces chunks for old content, but the next event (or a reconciliation sweep) fixes it. If you must order, key the queue by
doc_idso one document's events process serially. - Exactly-once vs at-least-once: true exactly-once end-to-end is famously hard; at-least-once delivery + idempotent consumer is the standard correct pairing. Your consumer is already idempotent (content-hash classification, chunk-ID upserts, per-document transactions) — a duplicated event just re-classifies as "unchanged" and does nothing. Design for duplicates; they're cheaper than the machinery to prevent them.
- Debouncing: a user editing a doc 50 times in a minute shouldn't trigger 50 processing runs. Coalesce events per
doc_idover a short window (a few seconds to minutes) and process the latest state once — the content hash means only the final state matters anyway. - Webhooks need verification — signature checks, replay protection, idempotent receivers: 03.9, 13.6–13.7 owns the mechanics.
Part 14: Decision table and failure gallery#
Reference
14.1 Orchestration and architecture decision table#
| Question | Answer |
|---|---|
| Batch or streaming? | Batch nightly unless freshness SLA < ~1 hour → then change feeds + queue |
| Poll or feed? | Feed when the source offers one (Drive changes, Graph delta, S3 events); poll+hash otherwise |
| Orchestrator? | Plain Python+cron → queue (event-driven) → Prefect/Dagster (team+UI) → Temporal (long critical runs) → cloud-native (cloud-committed, big data) |
| Incremental or full? | Incremental always for steady state; full re-embed only on model/chunker/cleaner change, via blue/green |
| Sync or async worker? | Async (arq) if IO-bound API calls dominate; sync workers fine for CPU-bound parsing |
| Framework or hand-roll? | Hand-roll skeleton; framework loaders for hard formats; framework orchestration only if already committed |
14.2 The failure gallery#
| Failure | Symptom | Prevention / detection |
|---|---|---|
| Timestamp/ordering bug in IDs | Every run re-embeds everything | Determinism; idempotency property test (11.1) |
| Chunker version not bumped | Old+new chunks mixed silently | chunker_version in every ID + lineage and the classify-time version check (3.2); contract test |
| Manifest↔store drift | Missing vectors, orphan vectors | Reconciliation job (3.5) |
| Poison doc fails every run | errors grows, run never clean |
Dead-letter after N failures (8.2) |
| Half-indexed document | Confident wrong answers | All-or-nothing per document; per-document transactions |
| Embed-input changed, chunk_id didn't | Stale vectors for changed context | Include embed-input hash in ID material (3.3) |
| Rate-limit storm on backfill | 429s, retries, cost spike | Bounded concurrency + token bucket + budget cap (7.2) |
| Parser lib upgrade breaks output | Golden test fails / weird chunks | Pinned versions + golden docs + contract tests (11.2) |
| Deletion not propagated | Deleted data still retrievable | Deletion job across raw+manifest+vectors+caches (9.3) |
| Webhook replay/duplicate | Same doc processed twice | Idempotent consumer; dedupe by event ID + content hash (13.2) |
| "Clean" run that's actually stale | Freshness SLA breached silently | Staleness-lag metric + alert (10.2) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Just re-run everything every night; it's simpler." | Simple but pays full parse+embed cost every run and still needs change detection for deletions. Incremental is cheaper and you need the manifest anyway. |
| "The vector store is the source of truth." | The manifest is. The store is a serving replica; reconciliation exists precisely because they drift. |
| "Content hash means I never re-process unchanged files." | True for the file, but a chunker/model/cleaner version change invalidates downstream work — versioning decides what "unchanged" means at each stage. |
| "At-least-once delivery means duplicates in the index." | Only if your consumer isn't idempotent. Content-hash classification + upserts make duplicates no-ops. |
| "Orchestrators handle retries so I don't need idempotency." | They retry tasks; your pipeline still must be safe to re-run — retries are exactly when idempotency matters. |
| "A failed document should fail the run." | No — fail-soft per document: quarantine it, keep last-good, alert on the pattern. One poison file shouldn't block 50k good ones. |
| "Blue/green is only for zero-downtime deployments." | It's for reversibility: a bad re-embed flips back in seconds instead of re-embedding for days. |
| "I need Kafka/streaming for real-time." | You need it for sub-hour freshness at scale. For most corpora, change feeds + a queue get you "near-real-time" without the moving parts. |
| "Frameworks (LlamaIndex etc.) handle ingestion for me." | They handle stages; the manifest, diffing, reconciliation and versioning are still yours — and they're the part that determines correctness. |
Key takeaways#
- An AI ingestion pipeline is an ETL system with two extras: content-addressed outputs (so unchanged work is free) and a manifest (so "what changed?" is answerable). Master those two and the rest is engineering hygiene.
- The contract: idempotent, deterministic, immutable raw, stage-separated, checkpointed, fail-soft per document, versioned everywhere, re-runnable, observable. Violating any one produces a specific, nameable failure.
- Change detection is cheap signals (hash, ETag, change feeds, delta cursors) feeding a conservative classifier: when in doubt, re-process — false "changed" costs money, false "unchanged" costs correctness.
- The incremental algorithm: classify → re-process changed → diff chunks by content-addressed ID → embed only fresh → per-document transaction → reconcile manifest↔store. The toy pipeline in the appendix does all of it in stdlib Python.
- Full re-embeds are for model/chunker/cleaner changes, done blue/green with alias flip + shadow eval + rollback window — never in-place.
- Orchestration is a spectrum: cron → queue → Prefect/Dagster → Temporal → cloud/streaming. Start simple; the pipeline's correctness comes from idempotency, not the orchestrator.
- Concurrency is bounded by provider rate limits, not cores; cost is controlled by dry-run estimates, budget caps and batch APIs.
- Errors are per-document: quarantine transient/document failures, dead-letter poison after N tries, never let one file sink the run.
- Compliance is pipeline mechanics: scoped credentials, PII as a versioned stage before embedding, deletion as a first-class job across every copy, tenant ID carried end-to-end.
- Observability = structured logs +
runs/errorstables → throughput, failure rate, cost, staleness lag, reuse ratio, drift. Test with golden docs, idempotency property tests and parser contract tests.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Ingestion pipeline | The repeatable machinery that moves sources through parse→clean→chunk→enrich→embed→index |
| Manifest / state store | The pipeline's memory: seen sources, content hashes, chunk inventory, run history, errors |
| Idempotency | Re-running on the same inputs yields the same end state, not duplicated work |
| Determinism | Same input + same versions → same outputs (IDs, boundaries, embed set) |
| Content hash | sha256 fingerprint used for change detection and content-addressed IDs |
| Meaningful-change hashing | Hashing canonical/normalised content so irrelevant churn doesn't trigger reprocessing |
| ETag / Last-Modified | HTTP validators for cheap conditional revalidation (304 Not Modified) |
| Change feed / delta API | A resumable cursor of source changes (Drive changes, Graph deltaLink, replication slots) |
| Delta cursor / page token | The stored position that lets a change feed resume where it left off |
| Tombstone | A recorded deletion marker so removals propagate and are auditable |
| Classification (new/changed/unchanged/deleted) | The manifest diff that decides what work a run must do |
| Chunk-level diffing | Comparing old vs new chunk_ids so only changed chunks re-embed |
| Embedding reuse | Keeping vectors for surviving chunk IDs instead of re-calling the embedder |
| Atomic write-then-flip | Per-document transaction ordering so observers never see half-updated state |
| Reconciliation | The job diffing manifest vs vector store to detect and repair drift |
| Blue/green index | Building a new index alongside the live one, then flipping an alias |
| Alias repoint | The instant, reversible cutover that makes blue/green safe |
| Shadow evaluation | Replaying queries against old and new indexes before cutover |
| Backfill | A versioned job that touches every record to add/change a field |
| Orchestrator | The layer scheduling runs, retrying failures and recording history (Prefect/Dagster/Airflow/Temporal) |
| Durable execution | Temporal's model: workflow state persisted server-side so runs resume mid-flight |
| Queue worker | A process consuming jobs from a broker (Celery/RQ/Dramatiq/arq) |
| Backpressure | Bounding upstream rate to downstream capacity (concurrency, queues, rate limits) |
| Dead-letter / quarantine | Isolating poison documents after N failures for review, not silent retry forever |
| At-least-once + idempotent consumer | The correct pairing for streamed/event-driven ingestion |
| Debouncing | Coalescing bursts of change events per document before processing |
| Staleness lag | The freshness metric: source-change time → indexed time |
| Right-to-erasure deletion | Propagating a delete request through raw store, manifest, vectors, caches, backups |
| Golden document | A representative fixture with expected output used to catch parser regressions |
| Contract test | A test asserting a library's output still satisfies the shape your pipeline depends on |
| Run mutex / leader lock | A guard ensuring only one pipeline run is in flight at a time |
| Drift repair | Acting on reconciliation: re-embed manifest_only chunks from the manifest, delete store_only orphans (--repair in the toy) |
| Incremental indexing framework | A tool (for example CocoIndex) that keeps an index in sync with changing sources by re-running only what changed |
Exercises#
Using the appendix pipeline.py and the sources/ toy corpus:
- Idempotency proof: run the pipeline twice; confirm the second run reports
0 embed calls,5 unchanged,1 changed(the poison retry) and empty drift. Then add a trailing newline to one file and run again — did it re-process? Why or why not, and what does that tell you about hash granularity? - Chunk-level diffing: edit one sentence inside a
##section ofhandbook.md. Run and inspectchunks_new/chunks_reused. How many chunks re-embedded for a one-sentence change, and why is that number what it is? - Deletion propagation: delete a file and verify its chunks and its vector rows are gone (
SELECT COUNT(*) FROM vectors). What would break if the vector delete were skipped? - Dry-run: run with
--dry-runafter a change; confirm nothing was written (SELECT COUNT(*) FROM runsunchanged) but the report shows what would happen. - Poison handling: the
broken-doc.mdfails every run. Count its rows inerrorsafter 4 runs. Sketch (don't necessarily implement) the dead-letter logic from 8.2 — where would the failure count live? - Meaningful change: modify
parse_cleanso it also strips HTML comments, then change only an HTML comment in a.mdfile. Should it re-process? Argue both sides (raw-hash vs post-clean-hash) using 2.2. - Cost model: use
estimate_reindexwith your corpus's real chunk count (querySELECT COUNT(*) FROM chunks) and a plausible per-1M-token price. At what corpus size does a nightly full re-embed become absurd vs incremental? - Orchestration choice: for a 3-person team ingesting a client's SharePoint site nightly plus a Zendesk webhook feed, pick an orchestration option from 6.6 and justify it in three sentences.
- Reconciliation: manually
DELETE FROM vectors WHERE chunk_id = (SELECT chunk_id FROM chunks LIMIT 1)invectors.db, then run the pipeline. What does drift report, and which direction is dangerous vs merely untidy? Does a second run fix it? Then run with--repairand readrepair_driftto see why the manifest keepsembed_input. - Design review: a colleague proposes "store chunks only in the vector DB, skip the manifest". Write three concrete failure scenarios that design produces, mapped to principles in 1.2.
- Version-aware classification: bump
CHUNKER_VERSIONto"heading-v2"and run on the post-§4.4 corpus. Predict thedocs:/chunks:lines before running — every document should re-process. Then inspectdocuments.chunker_versionand explain whybroken-doc.mdstill showsheading-v1.
Hints and worked answers (compare against your own run's counters — the shapes below are what the toy corpus produces; your file edits will shift the chunk counts):
- Second run:
0 embed calls;docs:shows5 unchanged+1 changed— thechangedone isbroken-doc.md, whose quarantine upsert deliberately leavescontent_hash/version columns at their last successful values so it keeps classifyingchangedand retrying. A trailing newline changes the content hash → the document classifieschangedand is re-parsed:scan_sourceshashes the raw file bytes, so "changed" currently means "any byte". The payoff comes next:parse_cleanstrips the trailing newline, so every chunk ID is unchanged — expectchunks_new: 0, all chunks reused andembed calls: 0. You paid for a re-parse, not for embeddings, which is exactly what chunk-level diffing is for. - A one-sentence edit retires and re-creates only the chunk(s) containing it — expect
chunks_new≈chunks_deleted≈ 1–2 andchunks_reused= the rest;embed callsequalschunks_newbecausechunk_idis position-free. - After deletion: the doc's chunk rows go inside the manifest transaction and its vector rows in the post-commit delete —
SELECT COUNT(*) FROM vectorsdrops by that doc's chunk count andtombstonesgains a row. Skipping the vector delete leavesstore_onlyorphans: deleted content still retrievable, plus wasted space. --dry-runreturnsstatsbefore anywith manifest:/with vectors:block —runs,documents,chunks,vectorsall unchanged while the printed counters show what would happen.broken-doc.mdwrites oneerrorsrow per run (4 after 4 runs) and stayschangedforever. Dead-letter sketch: afailurescount ondocuments(or adead_letterstable) incremented inrecord_error's caller, andclassifyskipping docs past N failures — the count must live in the manifest becauseerrorsis per-run, not per-doc state.- Both arguments are defensible: raw-hash re-processes (safe, wasteful — the chunker output is provably identical so chunk diffing reuses everything anyway, costing only parse time); post-clean-hash skips (cheaper, but now "unchanged" means "unchanged to the chunker" — a cleaning regression that adds noise back could hide). The lesson's stance: hash what you feed downstream, and let chunk-level diffing absorb the cost.
estimate_reindexis linear:chunks × ~tokens-per-chunk × price-per-token. Compare it against the incremental path's cost (onlychunks_newembeds). Crossover intuition: once the corpus is large enough that a nightly full re-embed costs more than the engineering time saved, incremental wins — at toy scale both are cents, at 1M chunks nightly it is real money.- Any defensible pick works if justified: e.g. plain Python + cron for the nightly SharePoint sweep plus a small always-on webhook consumer, or Prefect/Dagster if the team wants a UI, retries and scheduling in one place. Three engineers argues against heavyweight Airflow/Temporal; the webhook argues for some always-on process, not a batch cron.
- Deleting a
vectorsrow →manifest_only: [<that chunk_id>]— the dangerous direction (retrieval silently misses it). Run the pipeline again and the samemanifest_onlyid is reported every time: the chunk is still in the manifest, soclassifycalls the documentunchangedand nothing re-embeds it — detection is not repair. Run with--repairand the pipeline re-embeds it from the storedembed_inputand the next drift line is empty. Deleting achunksrow instead →store_only— an untidy orphan (but a privacy risk if it was a deleted document), which--repairdeletes. - Three concrete failures: (a) no change detection → every run re-embeds everything (cost); (b) no deletion record → deleted files leave orphan vectors forever, still retrievable (correctness/privacy); (c) no run history/manifest → can't audit what was ingested when, can't reconcile drift, can't reproduce a bad run.
- Verified on the toy corpus:
docs: 0 new, 6 changed, 0 unchanged, 0 deleted(the poison doc classifieschangedtoo — its stored hash never matches — and is quarantined again),chunks: 15 new, 0 reused, 15 deleted,embed calls: 15. Everychunk_idchanges becausechunker_versionis in the hash.broken-doc.mdstill showsheading-v1indocuments.chunker_versionbecause the quarantine upsert'sON CONFLICTupdates onlystatus/run_id/updated_at/error— the version columns keep describing the last successful ingest, and it never succeeded.
Check yourself#
- Name the two things that make an AI ingestion pipeline different from a generic ETL job.Content-addressed outputs (unchanged work is free via chunk-ID embedding reuse) and a manifest/state store (change detection, run history, reconciliation).
- Why is content-hash change detection "conservative" — which error direction is cheap and which is expensive?False "changed" costs re-processing money; false "unchanged" serves stale content silently — so bias toward re-processing.
- What does
ETag/Last-Modifiedgive you that a content hash doesn't, and when do you still need the hash?They let the server say "not modified" without you downloading the body (304). You still need the hash as the authoritative post-fetch check and for chunk-level diffing. - A Drive notification says "file X changed". What must your pipeline still do, and what does the notification replace?It must still fetch current content and run the same hash→classify→process path; the notification replaces discovery/polling, not processing.
- Why does a rename show up as delete+new under URI-derived
doc_id, and how do you avoid re-embedding on renames?Becausedoc_idderives from URI, a new path is a new identity. Hashing a stable source-system ID (Drive file ID) instead survives renames for free. - What are the four classifications in the incremental update, and which one costs zero work?new / changed / unchanged / deleted; unchanged costs zero work (skipped entirely).
- Why does
chunk_idexclude position, and what breaks if you include it?So inserting a paragraph doesn't re-ID every later chunk — position-free IDs mean surviving chunks keep embeddings. Including position makes every edit after the change point look new. - What's the difference between
manifest_onlyandstore_onlydrift, and which is dangerous?manifest_only= chunks missing vectors (dangerous — broken retrieval);store_only= orphan vectors (untidy, wastes space, can leak deleted content). - When is a full re-embed unavoidable, and what's the safe pattern for doing it?New embedding model, new chunker version, cleaning that alters text, embed-input changes, index migration. Safe pattern: blue/green build + shadow eval + alias flip + keep-old-for-rollback.
- Why is "at-least-once delivery + idempotent consumer" preferred over trying to guarantee exactly-once?Exactly-once end-to-end is extremely hard; at-least-once + idempotent consumer gives correctness with simple retries — duplicates become no-ops.
- What's the difference between a quarantined document and a dead-lettered one?Quarantined = failed but retried next run (may heal); dead-lettered = failed N times, excluded and alerted for human review.
- Give two reasons a pipeline run can be non-deterministic even with deterministic stages.Timestamps/
nowinside stages, unordered iteration (sets/dicts) affecting output order or IDs, random seeds, wall-clock in filenames/run IDs leaking into content. - Why must PII redaction happen before embedding, and why is the raw store kept unredacted?Because embeddings and provider calls would carry PII to third parties; raw is kept unredacted (access-controlled) so authorised humans can reverse redaction and replay.
- Which single test best catches non-determinism in a pipeline, and what does it assert?The idempotency property test: run twice, assert second run does zero chunk/embed work and identical state — catches timestamps-in-IDs, unordered iteration, hidden state.
- Why does
classifytreat a storedchunker_version/parser_versionmismatch aschangedeven when the content hash matches — and what breaks if it doesn't?Because the stored versions are the only record of which code produced the stored chunks — a stale version means the index is mixing two chunkings. Skipping the check lets a version bump pass silently: old-version chunks stay while new docs get new-version IDs (the mixed-version failure in 14.2).
Further resources#
- Google Drive API — Retrieve changes and Push notifications:
changes.getStartPageToken/changes.list/changes.watch— the canonical change-feed pattern. - Microsoft Graph — Use delta query to track changes and driveItem: delta:
@odata.nextLink/@odata.deltaLinkand thedeletedfacet. - Amazon S3 — Using EventBridge and Event notification types and destinations: object event types for EventBridge, and the
s3:TestEventsent to SNS/SQS/Lambda destinations on first configuration. - Prefect docs — Quickstart and Write and run a workflow:
@flow/@task,.serve(), retries, timeouts. - Dagster docs — Defining assets and Definitions API:
@dg.asset,Definitions,dg dev. - Airflow docs — TaskFlow tutorial and Public interface for Airflow 3:
airflow.sdkdecorators in Airflow 3. - Temporal docs — Workflow basics and Temporal Client:
@workflow.defn,@activity.defn,Client.connect, durable execution. - arq docs — arq documentation:
enqueue_job,WorkerSettings,create_pool. - Dramatiq docs — User Guide and API reference:
@dramatiq.actor,send_with_options, brokers/middleware. - LlamaIndex — Ingestion Pipeline:
IngestionPipeline, transformations, caching,num_workers. - Module 03 — 03.8 Errors and retries, 03.9 Async, concurrency and batch (webhook receivers in 13A.6–13A.7): the retry/rate-limit/batch mechanics this lesson applies.
- Module 06 — 06.2 Embedding pipelines, 06.5 Vector databases: embedding batching/caching/cost and the
VectorStoreprotocol. - Module 05 siblings — 05.5 Cleaning, 05.8 Metadata design (IDs at 3.3/3.5), 10A.2 Synthetic data, 05.10 Data quality.
Appendix: pipeline.py — full source#
The complete minimal pipeline (pure standard library; the outputs in Part 4 are real runs of this file):
# pipeline.py — minimal incremental ingestion pipeline, lesson 05.9.
# Standard library only. See the lesson for the stage-by-stage explanation.
from __future__ import annotations
import argparse
import hashlib
import json
import sqlite3
import sys
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
CHUNKER_VERSION = "heading-v1"
PARSER_VERSION = "toy-parser-1.0"
EMBED_MODEL = "fake-embedder-v0"
EMBED_DIMS = 8
DOC_SUFFIXES = {".md", ".txt"}
SCHEMA = """
CREATE TABLE IF NOT EXISTS documents (
doc_id TEXT PRIMARY KEY,
source_uri TEXT NOT NULL UNIQUE,
content_hash TEXT NOT NULL,
status TEXT NOT NULL,
chunker_version TEXT NOT NULL,
parser_version TEXT NOT NULL,
run_id TEXT NOT NULL,
updated_at TEXT NOT NULL,
error TEXT
);
CREATE TABLE IF NOT EXISTS chunks (
chunk_id TEXT PRIMARY KEY,
doc_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
text TEXT NOT NULL,
embed_input TEXT NOT NULL,
content_hash TEXT NOT NULL,
ingested_at TEXT NOT NULL,
UNIQUE(doc_id, chunk_index)
);
CREATE TABLE IF NOT EXISTS runs (
run_id TEXT PRIMARY KEY,
started_at TEXT NOT NULL,
finished_at TEXT,
dry_run INTEGER NOT NULL,
seen INTEGER, new INTEGER, changed INTEGER, unchanged INTEGER,
deleted INTEGER, chunks_new INTEGER, chunks_reused INTEGER,
chunks_deleted INTEGER, embed_calls INTEGER, errors INTEGER
);
CREATE TABLE IF NOT EXISTS errors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id TEXT NOT NULL,
source_uri TEXT NOT NULL,
stage TEXT NOT NULL,
message TEXT NOT NULL,
at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tombstones (
doc_id TEXT NOT NULL,
source_uri TEXT NOT NULL,
content_hash TEXT NOT NULL, -- hash of the last seen content
deleted_at TEXT NOT NULL,
run_id TEXT NOT NULL
);
"""
VECTOR_SCHEMA = """
CREATE TABLE IF NOT EXISTS vectors (
chunk_id TEXT PRIMARY KEY,
doc_id TEXT NOT NULL,
model TEXT NOT NULL,
dims INTEGER NOT NULL,
vector TEXT NOT NULL
);
"""
@dataclass
class SourceFile:
path: Path
uri: str
content_hash: str
def scan_sources(root: Path) -> dict[str, SourceFile]:
out = {}
for p in sorted(root.rglob("*")):
if p.is_file() and p.suffix.lower() in DOC_SUFFIXES:
data = p.read_bytes()
uri = p.relative_to(root).as_posix()
out[uri] = SourceFile(path=p, uri=uri,
content_hash=hashlib.sha256(data).hexdigest())
return out
def parse_clean(path: Path) -> str:
text = path.read_text(encoding="utf-8")
if "<!-- POISON -->" in text:
raise ValueError("simulated unparseable document")
lines = [ln.rstrip() for ln in text.splitlines()]
out, blank = [], 0
for ln in lines:
if ln.strip():
out.append(ln)
blank = 0
else:
blank += 1
if blank <= 1:
out.append("")
return "\n".join(out).strip() + "\n"
def chunk_document(text: str) -> list[str]:
sections, cur = [], []
for ln in text.splitlines():
if ln.startswith("## ") and cur:
sections.append("\n".join(cur))
cur = [ln]
else:
cur.append(ln)
if cur:
sections.append("\n".join(cur))
chunks = []
for sec in sections:
buf = ""
for ln in sec.split("\n"):
if len(buf) + len(ln) > 400 and buf:
chunks.append(buf.strip())
buf = ""
buf += ln + "\n"
if buf.strip():
chunks.append(buf.strip())
return [c for c in chunks if c]
def make_chunk_id(doc_id: str, chunk_text: str, occurrence: int) -> str:
ch = hashlib.sha256(chunk_text.encode("utf-8")).hexdigest()
digest = hashlib.sha256(
f"{doc_id}|{CHUNKER_VERSION}|{ch}|{occurrence}".encode("utf-8")
).hexdigest()
return f"chk_{digest[:24]}"
def chunk_ids_for(texts: list[str], doc_id: str) -> list[str]:
seen: dict[str, int] = {}
ids = []
for t in texts:
h = hashlib.sha256(t.encode()).hexdigest()
n = seen.get(h, 0)
seen[h] = n + 1
ids.append(make_chunk_id(doc_id, t, n))
return ids
class FakeEmbedder:
def embed(self, text: str) -> list[float]:
digest = hashlib.sha256(text.encode("utf-8")).digest()
return [round((digest[i % len(digest)] - 128) / 128.0, 4)
for i in range(EMBED_DIMS)]
def embed_many(self, texts: list[str]) -> list[list[float]]:
return [self.embed(t) for t in texts]
def open_manifest(path: Path) -> sqlite3.Connection:
con = sqlite3.connect(path)
con.executescript(SCHEMA)
return con
def open_vector_store(path: Path) -> sqlite3.Connection:
con = sqlite3.connect(path)
con.executescript(VECTOR_SCHEMA)
return con
def classify(manifest_docs: dict[str, dict], scanned: dict[str, SourceFile]):
"""new / changed / unchanged / deleted — one pass over both key sets.
'changed' covers three cases: content hash differs, the stored
chunker/parser versions are stale (a version bump must re-process every
document — skipping them would silently mix two chunkings), or the doc
is quarantined and due for a retry."""
new, changed, unchanged, deleted = [], [], [], []
for uri, sf in scanned.items():
doc = manifest_docs.get(uri)
if doc is None:
new.append(sf)
elif (doc["content_hash"] != sf.content_hash
or doc["chunker_version"] != CHUNKER_VERSION
or doc["parser_version"] != PARSER_VERSION
or doc["status"] == "quarantined"):
changed.append(sf)
else:
unchanged.append(sf)
scanned_uris = set(scanned)
for uri, doc in manifest_docs.items():
if uri not in scanned_uris:
deleted.append(doc)
return new, changed, unchanged, deleted
def process_document(sf: SourceFile, manifest: sqlite3.Connection,
vectors: sqlite3.Connection, embedder: FakeEmbedder,
run_id: str, dry_run: bool) -> dict:
stats = {"chunks_new": 0, "chunks_reused": 0, "chunks_deleted": 0,
"embed_calls": 0, "status": "ok", "error": None}
doc_id = "doc_" + hashlib.sha256(sf.uri.encode()).hexdigest()[:24]
try:
text = parse_clean(sf.path)
except Exception as exc:
stats.update(status="quarantined", error=str(exc))
if not dry_run:
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
with manifest:
record_error(manifest, run_id, sf.uri, "parse", str(exc))
# Upsert marks the doc quarantined. content_hash and the
# version columns are NOT updated on conflict: they keep
# describing the last successful ingest, so the doc keeps
# classifying 'changed' and is retried next run. A doc that
# never ingested gets content_hash='' — still != the real
# hash, so it is retried too.
manifest.execute(
"""INSERT INTO documents (doc_id, source_uri, content_hash,
status, chunker_version, parser_version, run_id,
updated_at, error)
VALUES (?,?,?,?,?,?,?,?,?)
ON CONFLICT(source_uri) DO UPDATE SET
status=excluded.status, run_id=excluded.run_id,
updated_at=excluded.updated_at,
error=excluded.error""",
(doc_id, sf.uri, "", "quarantined", CHUNKER_VERSION,
PARSER_VERSION, run_id, now, str(exc)))
return stats
texts = chunk_document(text)
ids = chunk_ids_for(texts, doc_id)
old_ids = {r[0] for r in manifest.execute(
"SELECT chunk_id FROM chunks WHERE doc_id = ?", (doc_id,))}
new_ids = set(ids)
retired = old_ids - new_ids
fresh = [i for i, cid in enumerate(ids) if cid not in old_ids]
stats["chunks_new"] = len(fresh)
stats["chunks_reused"] = len(ids) - len(fresh)
stats["chunks_deleted"] = len(retired)
stats["embed_calls"] = len(fresh)
if dry_run:
return stats
# Write-then-flip (3.4): embed and upsert fresh vectors BEFORE the
# manifest commit, so a crash in the gap leaves orphan vectors
# (store_only drift, swept by reconcile) — never manifest rows pointing
# at missing vectors. Retired vectors are deleted only after the flip.
if fresh:
embs = embedder.embed_many([texts[i] for i in fresh])
with vectors:
for i, vec in zip(fresh, embs):
vectors.execute(
"""INSERT INTO vectors (chunk_id, doc_id, model, dims, vector)
VALUES (?,?,?,?,?)
ON CONFLICT(chunk_id) DO UPDATE SET
vector=excluded.vector, model=excluded.model""",
(ids[i], doc_id, EMBED_MODEL, EMBED_DIMS,
json.dumps(vec)))
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
with manifest:
manifest.execute(
"""INSERT INTO documents (doc_id, source_uri, content_hash, status,
chunker_version, parser_version, run_id, updated_at, error)
VALUES (?,?,?,?,?,?,?,?,?)
ON CONFLICT(source_uri) DO UPDATE SET
doc_id=excluded.doc_id, content_hash=excluded.content_hash,
status=excluded.status, chunker_version=excluded.chunker_version,
parser_version=excluded.parser_version, run_id=excluded.run_id,
updated_at=excluded.updated_at, error=excluded.error""",
(doc_id, sf.uri, sf.content_hash, "ok", CHUNKER_VERSION,
PARSER_VERSION, run_id, now, None))
manifest.execute("DELETE FROM chunks WHERE doc_id = ?", (doc_id,))
for i, (cid, t) in enumerate(zip(ids, texts)):
manifest.execute(
"""INSERT INTO chunks (chunk_id, doc_id, chunk_index, text,
embed_input, content_hash, ingested_at)
VALUES (?,?,?,?,?,?,?)""",
(cid, doc_id, i, t, t,
hashlib.sha256(t.encode()).hexdigest(), now))
if retired:
with vectors:
vectors.executemany("DELETE FROM vectors WHERE chunk_id = ?",
[(c,) for c in retired])
return stats
def process_deletion(doc: dict, manifest: sqlite3.Connection,
vectors: sqlite3.Connection, run_id: str,
dry_run: bool) -> int:
doc_id = doc["doc_id"]
n = manifest.execute(
"SELECT COUNT(*) FROM chunks WHERE doc_id = ?", (doc_id,)).fetchone()[0]
if dry_run:
return n
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
with manifest:
manifest.execute(
"""INSERT INTO tombstones (doc_id, source_uri, content_hash,
deleted_at, run_id) VALUES (?,?,?,?,?)""",
(doc_id, doc["source_uri"], doc["content_hash"], now, run_id))
manifest.execute("DELETE FROM chunks WHERE doc_id = ?", (doc_id,))
manifest.execute("DELETE FROM documents WHERE doc_id = ?", (doc_id,))
with vectors:
vectors.execute("DELETE FROM vectors WHERE doc_id = ?", (doc_id,))
return n
def record_error(manifest: sqlite3.Connection, run_id: str, uri: str,
stage: str, message: str) -> None:
manifest.execute(
"INSERT INTO errors (run_id, source_uri, stage, message, at)"
" VALUES (?,?,?,?,?)",
(run_id, uri, stage, message,
datetime.now(timezone.utc).isoformat(timespec="seconds")))
def reconcile(manifest: sqlite3.Connection, vectors: sqlite3.Connection) -> dict:
m = {r[0] for r in manifest.execute("SELECT chunk_id FROM chunks")}
v = {r[0] for r in vectors.execute("SELECT chunk_id FROM vectors")}
return {"manifest_only": sorted(m - v), "store_only": sorted(v - m)}
def repair_drift(manifest: sqlite3.Connection, vectors: sqlite3.Connection,
embedder: FakeEmbedder, drift: dict) -> int:
"""Fix what reconcile() found. manifest_only chunks are re-embedded from the
embed_input stored in the manifest (that is why the manifest keeps it);
store_only vectors are orphans and are deleted. Returns how many were fixed.
Toy limit: the IN (...) list must stay under SQLite's variable limit."""
fixed = 0
missing = drift["manifest_only"]
if missing:
marks = ",".join("?" * len(missing))
rows = manifest.execute(
f"SELECT chunk_id, doc_id, embed_input FROM chunks "
f"WHERE chunk_id IN ({marks})", missing).fetchall()
embs = embedder.embed_many([r[2] for r in rows])
with vectors:
for r, vec in zip(rows, embs):
vectors.execute(
"INSERT OR REPLACE INTO vectors "
"(chunk_id, doc_id, model, dims, vector) VALUES (?,?,?,?,?)",
(r[0], r[1], EMBED_MODEL, EMBED_DIMS, json.dumps(vec)))
fixed += len(rows)
orphans = drift["store_only"]
if orphans:
with vectors:
vectors.executemany("DELETE FROM vectors WHERE chunk_id = ?",
[(c,) for c in orphans])
fixed += len(orphans)
return fixed
def run_update(sources_dir: Path, db_path: Path, vec_path: Path,
dry_run: bool = False, repair: bool = False) -> dict:
manifest = open_manifest(db_path)
manifest.row_factory = sqlite3.Row
vectors = open_vector_store(vec_path)
embedder = FakeEmbedder()
run_id = "run_" + hashlib.sha256(
f"{time.time()}|{dry_run}".encode()).hexdigest()[:16]
started = datetime.now(timezone.utc).isoformat(timespec="seconds")
if not dry_run:
manifest.execute(
"INSERT INTO runs (run_id, started_at, dry_run) VALUES (?,?,?)",
(run_id, started, int(dry_run)))
scanned = scan_sources(sources_dir)
manifest_docs = {r["source_uri"]: dict(r) for r in manifest.execute(
"SELECT * FROM documents")}
new, changed, unchanged, deleted = classify(manifest_docs, scanned)
totals = {"new": 0, "changed": 0, "unchanged": 0, "deleted": 0,
"chunks_new": 0, "chunks_reused": 0, "chunks_deleted": 0,
"embed_calls": 0, "errors": 0}
for sf in new + changed:
st = process_document(sf, manifest, vectors, embedder, run_id, dry_run)
totals["new" if sf in new else "changed"] += 1
for k in ("chunks_new", "chunks_reused", "chunks_deleted", "embed_calls"):
totals[k] += st[k]
if st["status"] == "quarantined":
totals["errors"] += 1
for doc in deleted:
totals["chunks_deleted"] += process_deletion(
doc, manifest, vectors, run_id, dry_run)
totals["deleted"] = len(deleted)
totals["unchanged"] = len(unchanged)
drift = reconcile(manifest, vectors)
repaired = 0
if repair and not dry_run and (drift["manifest_only"] or drift["store_only"]):
repaired = repair_drift(manifest, vectors, embedder, drift)
drift = reconcile(manifest, vectors) # prove it worked
finished = datetime.now(timezone.utc).isoformat(timespec="seconds")
if not dry_run:
manifest.execute(
"""UPDATE runs SET finished_at=?, seen=?, new=?, changed=?,
unchanged=?, deleted=?, chunks_new=?, chunks_reused=?,
chunks_deleted=?, embed_calls=?, errors=? WHERE run_id=?""",
(finished, len(scanned), totals["new"], totals["changed"],
len(unchanged), totals["deleted"], totals["chunks_new"],
totals["chunks_reused"], totals["chunks_deleted"],
totals["embed_calls"], totals["errors"], run_id))
manifest.commit()
return {"run_id": run_id, "totals": totals, "drift": drift,
"dry_run": dry_run, "repaired": repaired}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--sources", type=Path, default=Path("sources"))
ap.add_argument("--db", type=Path, default=Path("pipeline.db"))
ap.add_argument("--vectors", type=Path, default=Path("vectors.db"))
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--repair", action="store_true",
help="re-embed manifest_only chunks, delete store_only orphans")
args = ap.parse_args()
result = run_update(args.sources, args.db, args.vectors, args.dry_run,
args.repair)
t = result["totals"]
print(f"run {result['run_id']} dry_run={result['dry_run']}")
print(f" docs: {t['new']} new, {t['changed']} changed, "
f"{t['unchanged']} unchanged, {t['deleted']} deleted")
print(f" chunks: {t['chunks_new']} new, {t['chunks_reused']} reused, "
f"{t['chunks_deleted']} deleted; embed calls: {t['embed_calls']}")
print(f" quarantined: {t['errors']}")
if result["repaired"]:
print(f" repaired: {result['repaired']} drifted chunk(s)")
print(f" reconciliation drift: {result['drift']}")
if __name__ == "__main__":
sys.exit(main())← 05.8 — Metadata Design | Module 05 overview | 05.10 — Data Quality Checks →