Knowledge Ingestion and Real-Time Pipelines

Get source changes into the places agents read, completely, in the right order and soon enough.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Beginner From source to searchable

The stages

Detectwhat changed
Fetchcontent and permissions
Parsetext, tables, layout
Checkquality and policy
Transformchunk, enrich, embed
Publishindex and record lineage
↺ Failures go to a retry queue or quarantine, never nowhere
Each stage reads from a stored input and writes a stored output, so it can be rerun.

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 foundStrengthWeakness
Full rescan and compareSimple and complete, finds deletionsSlow and costly for large sources
Modified-since queryCheapOften misses deletions and some permission changes
Webhooks or notificationsFastMessages can be lost, repeated or reordered
Provider change feedOrdered list of changes with a resume tokenTokens can expire, so a rescan path is still needed
Change data captureEvery committed database change, including deletesNeeds 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.

Permissions are content too

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.

InputApproachCheck
Digital PDF with a text layerDirect text and layout extractionReading order, headers, tables
Clean scanOCR with layout detectionCharacter error rate on a sample
Photo, handwriting, stampsVision model or specialist serviceHuman review for low confidence
Forms and invoicesField extraction against a schemaTotals add up, identifiers are valid
SpreadsheetsRead cells and sheet structureHidden 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.

Intermediate Incremental and reliable processing

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.

ConcernPractice
Initial loadTake a consistent snapshot, then continue from the matching log position
OrderingOrder is normally guaranteed per key or partition, not globally; key events by record
DuplicatesAssume at-least-once delivery and make consumers idempotent
Schema changeAgree compatibility rules, see Data Contracts, Access and Retention
LagAlert on the age of the oldest unprocessed change
Log retentionA 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?

StyleDelayChoose it when
BatchHours to a dayPolicies, manuals and reference data
Micro-batchMinutesTickets, catalog and inventory summaries
StreamingSecondsFraud signals, incidents, live operations
Live call, no copyCurrent at call timeOne 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.

Expert Event time, features and operations

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.

Replaying old events can resurrect data

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

SignalWhat it reveals
Source-to-searchable delayWhether users see changes in time
Items in, out, quarantinedSilent loss between stages
Time since last change per sourceA connector that stopped without errors
Reconciliation differencesMissed events and orphaned entries
Retry and dead-letter volumePoison inputs and unstable dependencies
Cost per thousand itemsExpensive 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.

FailureResponse
Temporary, such as a timeout or rate limitRetry with increasing delays and a limit
Permanent for this item, such as an unreadable fileMove to a dead-letter queue with the reason and an owner
Permanent for many itemsStop the stage and alert; a bad release is likely
Partial success, such as nine pages of tenPublish only if policy allows, and mark the item incomplete
Downstream index unavailableHold 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.

Illustrative example: a product knowledge feed

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

Next steps