Knowledge Ingestion and Real-Time Pipelines
Get source changes into the places agents read, completely, in the right order and soon enough.
A knowledge pipeline collects content from source systems, turns it into clean and searchable forms and keeps those forms in step with every change, including deletions. Make each step repeatable, process only what changed, tolerate duplicate and out-of-order events, and measure how long a change takes to become visible. Add real-time streaming only where a decision actually needs it.
What you will learn: pipeline stages, document processing and OCR, incremental indexing, change data capture, streaming and event time, feature values for agent context, and operations.
Prerequisites: Data Architecture for Agentic AI and Document Ingestion, Parsing and Chunking.
The stages
A one-time script that loads a folder is fine for a demonstration. A production pipeline must answer harder questions: what happens when a file is edited, moved, deleted or made private? What if the job stops halfway? How would you know that a source has quietly stopped sending updates?
Connecting to sources
| How changes are found | Strength | Weakness |
|---|---|---|
| Full rescan and compare | Simple and complete, finds deletions | Slow and costly for large sources |
| Modified-since query | Cheap | Often misses deletions and some permission changes |
| Webhooks or notifications | Fast | Messages can be lost, repeated or reordered |
| Provider change feed | Ordered list of changes with a resume token | Tokens can expire, so a rescan path is still needed |
| Change data capture | Every committed database change, including deletes | Needs database access and care with schema changes |
A dependable design usually combines a fast signal with a slower reconciliation. Notifications keep the index current, and a periodic full comparison catches whatever the fast path missed.
When someone removes a user from a folder, no file text changes. If the pipeline reacts only to edits, the old access rules stay in the index. Capture permission changes explicitly and treat a delay in applying them as a security measure to monitor.
Parsing, OCR and intelligent document processing
Documents arrive as scans, slides, spreadsheets and web pages. Parsing decides what the agent can ever know. Optical character recognition turns images of text into characters. Intelligent document processing goes further: it recognizes layout, extracts fields such as invoice totals, and classifies document types.
| Input | Approach | Check |
|---|---|---|
| Digital PDF with a text layer | Direct text and layout extraction | Reading order, headers, tables |
| Clean scan | OCR with layout detection | Character error rate on a sample |
| Photo, handwriting, stamps | Vision model or specialist service | Human review for low confidence |
| Forms and invoices | Field extraction against a schema | Totals add up, identifiers are valid |
| Spreadsheets | Read cells and sheet structure | Hidden sheets, formulas, merged cells |
Keep the page number and position of extracted text so that citations can point to the exact place. Cross-check extracted values with rules wherever possible: a line-item sum that disagrees with the stated total is a better warning than any confidence score. Multimodal, Vision, Video and Document Agents covers model-based reading.
Process only what changed, safely
Re-embedding an entire collection for every edit wastes money. Skipping work carelessly leaves stale entries. The example below applies a stream of change events using a version number and a content hash.
"""Apply change events to a search index safely, even when out of order."""
import hashlib
index = {} # doc_id -> {"version", "hash", "text"}; text None = deleted
embed_calls = 0
def digest(text):
return hashlib.sha256(text.encode()).hexdigest()[:12]
def apply(event):
global embed_calls
doc, version = event["doc"], event["version"]
current = index.get(doc)
if current and version <= current["version"]:
return "ignored: stale or repeated"
if event["op"] == "delete":
index[doc] = {"version": version, "hash": None, "text": None}
return "deleted (tombstone kept)"
new_hash = digest(event["text"])
if current and current["hash"] == new_hash:
current["version"] = version
return "metadata only: no new embedding"
embed_calls += 1
index[doc] = {"version": version, "hash": new_hash, "text": event["text"]}
return "indexed"
stream = [
{"doc": "leave", "version": 1, "op": "upsert", "text": "Leave is 20 days"},
{"doc": "leave", "version": 2, "op": "upsert", "text": "Leave is 25 days"},
{"doc": "leave", "version": 2, "op": "upsert", "text": "Leave is 25 days"},
{"doc": "leave", "version": 3, "op": "upsert", "text": "Leave is 25 days"},
{"doc": "travel", "version": 1, "op": "upsert", "text": "Book rail first"},
{"doc": "travel", "version": 3, "op": "delete"},
{"doc": "travel", "version": 2, "op": "upsert", "text": "Book air first"},
]
for event in stream:
print(f'{event["doc"]:<6} v{event["version"]} {event["op"]:<6} -> {apply(event)}')
live = {k: v["text"] for k, v in index.items() if v["text"] is not None}
print("searchable:", live)
print("embedding calls:", embed_calls, "for", len(stream), "events")
Output:
leave v1 upsert -> indexed
leave v2 upsert -> indexed
leave v2 upsert -> ignored: stale or repeated
leave v3 upsert -> metadata only: no new embedding
travel v1 upsert -> indexed
travel v3 delete -> deleted (tombstone kept)
travel v2 upsert -> ignored: stale or repeated
searchable: {'leave': 'Leave is 25 days'}
embedding calls: 3 for 7 events
Seven events caused only three embedding calls. The repeated version 2 was ignored. Version 3 changed no text, so only its recorded version moved forward. Most important, the travel document stayed deleted even though an older update arrived after the delete. Without the tombstone, the late event would have recreated a removed document.
Real pipelines add details that the miniature leaves out:
- The hash should cover everything that affects the output: text, parser version, chunking settings and embedding model. Otherwise a pipeline upgrade changes nothing.
- Metadata and permissions need their own comparison, so that an access change updates the index without re-embedding.
- The index write and the state update should succeed or fail together, or be safe to repeat.
- Tombstones can be removed eventually, but only after no older event can still arrive.
Change data capture
Change data capture (CDC) reads a database's transaction log and emits an event for each committed insert, update and delete. Tools such as Debezium publish these to a message system, from which consumers update search indexes, caches or feature stores.
| Concern | Practice |
|---|---|
| Initial load | Take a consistent snapshot, then continue from the matching log position |
| Ordering | Order is normally guaranteed per key or partition, not globally; key events by record |
| Duplicates | Assume at-least-once delivery and make consumers idempotent |
| Schema change | Agree compatibility rules, see Data Contracts, Access and Retention |
| Lag | Alert on the age of the oldest unprocessed change |
| Log retention | A consumer that falls too far behind needs a new snapshot |
A change event describes a row, while an agent often needs a business object assembled from several tables. Rebuild the object from the validated tables when any part changes, or have the application publish business events through an outbox, as shown in Distributed Systems, Networking and Databases.
Batch, micro-batch or streaming?
| Style | Delay | Choose it when |
|---|---|---|
| Batch | Hours to a day | Policies, manuals and reference data |
| Micro-batch | Minutes | Tickets, catalog and inventory summaries |
| Streaming | Seconds | Fraud signals, incidents, live operations |
| Live call, no copy | Current at call time | One record from a reliable system |
Streaming brings state, ordering, replay and on-call work. Ask what decision becomes wrong if the data is ten minutes old. If none does, a scheduled job is the better engineering.
Event time and late data
Every event has at least two times: when it happened and when your system received it. Networks and offline devices make these differ. Stream processors group events by event time and use watermarks, an estimate that most events up to a certain moment have arrived, to decide when to emit a result. Decide what happens to events that arrive later: update the result, record a correction or discard them with a count you monitor.
Feature values as agent context
An agent often benefits from small computed facts: failed logins in the last hour, open cases for this account, average delivery delay. A feature store or serving table computes these once and serves them consistently, both live and for later evaluation.
Evaluation raises a subtle trap. When you replay an old decision, you must use the value that was available then, not the value later known for that moment.
"""Read a feature as it was known at decision time, not as it is now."""
from bisect import bisect_right
# (event_time, arrival_time, failed_logins_in_last_hour), minutes after 09:00
updates = [(0, 1, 0), (10, 11, 2), (20, 34, 9), (40, 41, 1)]
def known_at(decision_time):
"""Latest value, by event time, among updates that had already arrived."""
seen = sorted((e, v) for e, a, v in updates if a <= decision_time)
return seen[-1] if seen else None
def by_event_time(decision_time):
"""Looks right, but uses data that had not arrived yet."""
times = [e for e, _, _ in updates]
i = bisect_right(times, decision_time)
return (times[i - 1], updates[i - 1][2]) if i else None
for now in (15, 25, 35):
honest = known_at(now)
leaky = by_event_time(now)
age = now - honest[0]
note = "" if honest == leaky else " <- hindsight leaked"
fresh = "fresh" if age <= 10 else "STALE"
print(f"t={now}: known={honest[1]} ({age} min old, {fresh}) "
f"replayed={leaky[1]}{note}")
Output:
t=15: known=2 (5 min old, fresh) replayed=2
t=25: known=2 (15 min old, STALE) replayed=9 <- hindsight leaked
t=35: known=9 (15 min old, STALE) replayed=9
At minute 25, the reading of nine failed logins had happened but had not yet arrived. A replay keyed only on event time would credit the agent with knowledge it never had and would report better results than production can achieve. Store both times. Notice also that the honest value was already stale at minute 25: the tool should say so, and a policy might require a live check before acting on old security data.
Real-time updates for agents
Fresh data matters during a long task too. An agent that read an order status ten steps ago should read it again before acting on it. Useful patterns:
- Re-read before write. Fetch the current record and its version immediately before an action, and make the action conditional on that version.
- Invalidate by event. When a record changes, drop cached answers and summaries built from it.
- Notify waiting agents. A change event can wake a paused task, as described in Event-Driven and Background Agents.
- Label context. Include retrieval time in what the model sees so that old observations are not treated as current.
Backfills and reprocessing
Sooner or later you will change a parser or embedding model and rebuild everything. Plan for it: keep raw inputs, version every transformation, build the new output beside the old one, compare quality and switch when tests pass, as shown in Metadata, Indexing, Quality and Lineage. Throttle backfills so they do not delay fresh changes, and make sure live updates reach both versions during the transition.
Reprocessing history from the beginning may recreate records that were later erased. Apply deletion and suppression lists during every rebuild, and test that an erased item stays absent afterward.
Operating the pipeline
| Signal | What it reveals |
|---|---|
| Source-to-searchable delay | Whether users see changes in time |
| Items in, out, quarantined | Silent loss between stages |
| Time since last change per source | A connector that stopped without errors |
| Reconciliation differences | Missed events and orphaned entries |
| Retry and dead-letter volume | Poison inputs and unstable dependencies |
| Cost per thousand items | Expensive parsing or needless re-embedding |
A useful end-to-end probe writes a harmless test document to a source, searches for it until it appears, then deletes it and confirms it disappears. This checks the whole path, including the part that dashboards for single stages miss.
Securing ingestion
- Give connectors read-only access to exactly the sources they ingest.
- Treat incoming content as untrusted. A document can contain instructions aimed at the agent, see Prompt Injection Attacks and Defenses.
- Run parsers on untrusted files in a restricted environment with resource limits.
- Scan for secrets and sensitive data before indexing, and decide whether to block or mask.
- Record who or what added each source.
Handling failures inside the pipeline
Some inputs will fail: a corrupted file, a parser bug, a temporary service error. The right response differs, so classify errors instead of retrying everything the same way.
| Failure | Response |
|---|---|
| Temporary, such as a timeout or rate limit | Retry with increasing delays and a limit |
| Permanent for this item, such as an unreadable file | Move to a dead-letter queue with the reason and an owner |
| Permanent for many items | Stop the stage and alert; a bad release is likely |
| Partial success, such as nine pages of ten | Publish only if policy allows, and mark the item incomplete |
| Downstream index unavailable | Hold the position in the stream and resume; do not acknowledge early |
Make partial results visible to the agent. If a contract was only half parsed, a search that returns its first pages without a warning invites the conclusion that a clause does not exist. Store a completeness flag and surface it with the passage.
A retailer's assistant answers stock and policy questions. Policies flow through a nightly batch. Product descriptions follow database change events within minutes. Stock levels are not copied at all; a tool calls the inventory service. After one connector stops silently over a weekend, the team adds an alert on time since last change and a daily reconciliation count.
Common mistakes
- Handling creates and updates but forgetting deletes and permission changes.
- Trusting notifications without periodic reconciliation.
- Skipping unchanged text but forgetting that the parser or model changed.
- Assuming events arrive once and in order.
- Evaluating with values that were not available at decision time.
- Monitoring job success while ignoring delay and completeness.
Checklist
- Each source has a change detection method and a reconciliation path.
- Deletes and permission changes are tested end to end.
- Stages are repeatable and consumers tolerate duplicates.
- Versions or timestamps prevent old events overwriting new ones.
- Extraction quality is sampled and reviewed.
- Delay targets exist and are alerted on.
- Backfills apply deletion lists.
- A synthetic probe checks the whole path.
Frequently asked questions
Do agents need real-time data?
Only for decisions that change within minutes. Many knowledge sources change rarely, and a scheduled refresh with a visible timestamp is enough.
What if a source offers no change feed?
Rescan on a schedule and compare identifiers, hashes and permissions. Detect deletions by finding items that were present before and are now missing.
Can I rely on exactly-once delivery?
Treat it with care. Some systems offer it within their own boundary, but writes to external indexes and services still need to be safe to repeat.
When is a feature store worth it?
When several models or agents share computed values and you need the same definitions live and in evaluation. A single serving table may be enough before that.
References and further reading
- Debezium documentation
- Apache Kafka documentation, including delivery semantics
- Apache Flink: timely stream processing
- Feast feature store documentation
- Tesseract OCR
- Docling document conversion
Next steps
Metadata, Indexing, Quality and Lineage
Decide what is fit to publish.
RAG Security, Freshness and Cost
Keep retrieval safe and current.
Data Engineering, Catalog and Quality Agents
Let agents help run pipelines.