Ingestion Validation Layer

Purpose

The ingestion validation layer is the upstream data production layer for the RAG system.

Its job is to transform raw source artifacts into validated canonical documents that are safe enough to pass downstream into enrichment, chunking, and indexing.

This layer should be treated as an independent subsystem.

It should not rely on retrieval, reranking, or downstream generation to discover basic document quality problems.

The key idea is simple:

Downstream intelligence should not be the first place upstream data defects are discovered.

Scope

This document covers the pipeline from raw source artifacts to published validated canonical documents — including the pass, repair, and quarantine branches at validation. The full flow is shown in High-Level Architecture below.

This document does not cover:

Out of scopeWhy
enrichmentHappens after validated canonical documents are produced
chunkingBelongs to downstream retrieval preparation
indexingBelongs to downstream retrieval preparation
retrievalBelongs to the online evidence-finding subsystem
grounded generationBelongs to downstream answer production

Those belong to downstream RAG components.

Why This Layer Should Be Independent

If ingestion and validation are weakly defined, downstream teams discover source defects during retrieval or user-facing answering.

That creates several bad outcomes:

Bad outcomeWhy it matters
failure is discovered too latedownstream systems become the first detector of upstream defects
debugging becomes expensiveroot cause is hidden behind retrieval or answer behavior
the wrong subsystem gets blamedmodel or retrieval teams inherit ingestion failures
stronger models are used to compensate for messy inputmodel cost increases while architecture quality stays weak
silent defects become visible only in production usageusers discover issues before engineers do

This layer exists to contain those failures early.

Design Goals

  1. preserve source lineage and versioning from the start
  2. reconstruct document structure before text is treated as trusted content
  3. normalize multiple parser or OCR outputs into a unified internal representation
  4. detect high-risk extraction failures before downstream publishing
  5. repair what can be repaired safely
  6. quarantine what cannot be trusted
  7. publish only validated canonical documents to downstream systems

Core Principles

1. Ingestion Is a Data Production System

Ingestion is not a file-loading step.

It produces an internal document representation that downstream systems depend on.

2. Structure Matters More Than Raw Text Volume

For many business documents, the main failure is not missing text.

The main failure is broken structure:

Structural failureTypical impact
misaligned tablesvalues map to wrong fields or rows
wrong reading ordertext becomes nonsensical or misleading
lost section hierarchylocal text loses policy or rule context
merged headers and body textsection meaning becomes ambiguous
flattened forms or listsstructured fields become hard to validate or retrieve

3. Validation Should Be a Publish Gate

Validation is not only for monitoring.

Validation should decide whether a document is allowed to move downstream.

4. Repair Must Be Conservative

Safe normalization and structured repair are good.

Speculative content repair is dangerous.

If confidence is too low, quarantine is better than false precision.

5. Multiple Independent Signals Are Better Than One Confidence Score

OCR confidence alone is not enough.

A strong validator should combine:

Signal typeWhy it is useful
OCR or parser confidenceearly raw extraction risk signal
structural consistencydetects layout and table failures
semantic consistencydetects plausible-looking but wrong values
business-rule checks when availablecatches domain-specific correctness failures
cross-extractor agreementadds independent technical validation
cross-language agreement when parallel documents existadds independent semantic and structural validation

High-Level Architecture

Source
-> Acquire
-> Parse / OCR
-> Structure reconstruction
-> Canonicalize / normalize
-> Validate
   -> pass
   -> repair and re-validate
   -> quarantine
-> Publish validated canonical document

Module Boundaries

StepResponsibilityOutputsImportant rules
Acquirefetch files, pages, records, or images from source systems; preserve source identifiers, versions, timestamps, and ACL metadata; attach provenance for every artifactraw source artifact; source metadata; source lineage informationnever lose source id or version; every downstream document must trace back to a source artifact
Parse / OCRextract text from digital documents; run OCR for scanned or image-based documents; detect layout elements such as headings, paragraphs, tables, lists, and forms; capture confidence and coordinates when possibleparser or OCR output in tool-specific formkeep raw extractor output available for inspection; do not flatten everything into plain text immediately
Structure reconstructionrecover reading order; reconstruct section hierarchy; separate headers, footers, and body; rebuild tables and structured blocks; resolve layout artifacts such as multi-column flowdocument elements with logical structurechunking must not happen before structure reconstruction; tables must remain structured as long as possible
Canonicalize / normalizemap different parser or OCR outputs into one unified internal representation; normalize metadata fields into a standard schema; preserve both source truth and normalized values where needed; attach internal identifiers and trust-related fieldscanonical document object; normalized metadata schema; provenance links to source and extraction methodnormalization should unify representation, not silently rewrite content meaning; keep authoritative source values separate from inferred or repaired values when possible
Validatedetect whether the canonical document is trustworthy enough for downstream processing; attempt safe repair when possible; quarantine risky documents when trust is too lowpass; pass with warning; repair and pass; quarantine; failretrieval should not be the first place bad OCR or bad structure is discovered; low-trust content should not be silently published

Control and Governance in This Layer

Policy may be defined centrally, but this layer must enforce the controls that apply when raw source artifacts first enter the system.

Control concernHow it applies in this layer
source-level access metadatacapture ACLs, ownership, tenancy, and visibility scope at acquisition time
source lineagepreserve source id, version, and provenance from the start
trust gatingquarantine low-trust documents before they reach downstream preparation
repair auditabilityrecord whether repair was attempted and what changed
publish boundaryonly validated canonical documents may move downstream

Important principle:

If access scope, lineage, or trust is lost here, downstream layers cannot recover it safely.

This is the stage where a wrapper around multiple OCR methods usually belongs.

If several extractors produce different formats, this stage converts them into one canonical document schema.

Canonical Document Contract

By the time validation starts, the system should already have a unified internal document representation.

At minimum, it should support:

document_id
source_id
source_version
language
document_type
pages
elements[]
provenance
extractor_info
acl_metadata

Each element should support fields such as:

element_id
element_type
text
page_number
bbox_or_span
section_path
confidence
structured_payload

This representation gives validation one place to reason about parser output regardless of which OCR or extraction method produced it.

Validation Framework

Validation should not try to prove the document is perfect.

It should try to detect high-risk failure patterns before they become downstream truth.

The most important design distinction is this:

  • offline evaluation can use gold truth
  • production gating usually cannot

That means many good evaluation metrics are not directly usable as production publish gates.

The layer therefore needs three validation views.

Validation viewGoalCan use gold truth?Primary output
Offline evaluationselect extractors, parsers, validators, and thresholdsyesmodel choice, rule choice, threshold calibration
Production gatingdecide pass, warning, repair, quarantine, or fail for each documentnopublish decision
Post-production monitoringdetect drift, hidden failures, and quality regressions after publishsometimes through samplingalerts, audits, rule updates

Conceptually, validation spans six levels: OCR and parser confidence, structural, semantic, business-rule, cross-extractor, and cross-language consistency validation. These levels mix deterministic checks, model-assisted checks, business-specific checks, and comparative checks across extractors or languages, so the implementation view below groups them by engineering method and ownership instead.

Runtime flow per document:

Canonical document
-> risk checks
-> optional repair attempt
-> re-validation
-> pass or quarantine

Validation Categories

For implementation, the validation stack should be grouped into four categories:

CategoryWhat it coversPrimary ownerNotes
Technical deterministic validationRule-based checks on confidence, structure, fields, and metadataPlatform / ingestion engineeringDefault first line of defense
Technical model-based validationModel-assisted checks for messy structure or subtle semantic issuesPlatform / applied AI engineeringBounded support layer, not the default controller
Comparative consistency validationCross-checks across extractors or language versionsPlatform / ingestion engineeringStrong independent validation signal
Business-specific validationDomain checks for important document classesDomain team with platform supportSelective, high-value, document-type-aware

This makes it easier to decide:

  • what can be implemented as hard rules
  • what needs model support
  • what depends on multiple views of the same source
  • what belongs to domain teams rather than platform teams

Implementation View

To make the categories implementable, each validator should define:

FieldMeaning
signalthe raw measurement or detector output
metricthe computed value used for gating
thresholdthe pass, warning, or fail boundary
scopedocument, page, section, table, row, or field
actionpass, warn, repair, quarantine, or fail

Thresholds should be treated as calibration inputs, not universal constants.

They should be tuned by:

  • document class
  • source system
  • language
  • extractor type
  • business risk

In practice, each validation category should be expressed in both of these forms:

Metric typePurpose
Reference metricoffline metric computed against gold truth
Proxy metriconline or production-safe metric computed without gold truth

The gate should use proxy metrics, while offline evaluation should use reference metrics.

1. Technical Deterministic Validation

This category should be the default first line of defense.

These checks are usually rule-based, auditable, and stable.

They should run on every document before any model-heavy validation is used.

Deterministic areaTypical checksWhy it mattersOffline reference metricsProduction proxy metricsExample gate logicTypical action
OCR and parser confidencelow OCR confidence, suspicious substitution density, too many unknown characters, abnormal page quality, weak block-level confidenceFast early risk signalCER, WER, token F1average OCR confidence, low-confidence token ratio, unknown-character ratiowarn if mean confidence is below class baseline; quarantine if low-confidence token ratio exceeds tolerancewarn, repair, quarantine
Structural and layout validationreading order sanity, heading hierarchy consistency, page sequence consistency, plausible block boundaries, stable section orderingCatches layout failures before text is trustedpairwise order accuracy, inversion rate, heading hierarchy accuracybbox monotonicity violations, column-switch anomaly count, header-footer intrusion rate, orphan block ratioquarantine if multiple structure proxies fail together; warn on mild hierarchy anomalieswarn, repair, quarantine
Table structural validationrow and column consistency, header-body separation, stable column count, merged-cell plausibility, header alignment, monotonic rows, geometric plausibilityHigh-impact table failures are usually structuraltable cell F1, row grouping accuracy, column grouping accuracy, header alignment accuracycolumn-count variance, header-body alignment score, row-order anomaly count, cell-overlap ratioquarantine if structure proxies fall below minimum trust thresholdrepair, quarantine
Deterministic semantic validationdates parse as dates, identifiers match expected formats, enum values are valid, totals reconcile, duplicates appear only where allowedCatches plausible-looking but wrong extractionfield extraction F1, typed-value accuracyparse success rate for dates or ids, duplicate-key ratio, enum validity ratewarn if parse success falls below class baseline; quarantine on critical field failurewarn, repair, quarantine
Table semantic validationstable column types, valid dates/currencies/percentages/ids, plausible ranges, expected enums, count or total consistencyTable content can be locally coherent or obviously brokentyped-cell accuracy, key-field extraction accuracycolumn-type purity, numeric-range violation count, total-reconciliation errorquarantine if key columns show low type purity or totals diverge materiallyrepair, quarantine
Metadata and control-field validationmetadata completeness, source version consistency, ACL field presencePrevents downstream filtering and governance failuresfield accuracy, schema conformance accuracyrequired-field completeness rate, ACL completeness, source-version consistencyquarantine or fail if mandatory fields are missing or control state is inconsistentfail, quarantine

Three notes on the areas above:

  • OCR confidence is only an early signal: high token confidence does not guarantee correct structure, and tables can be wrong even when token-level confidence looks acceptable — structural checks must run regardless of what the extractor reports
  • structural and layout validation is often the highest-value layer, especially for layout-heavy documents; table-specific structural checks (row and column consistency, header-body separation, stable column counts, merged-cell plausibility, header alignment, monotonic ordering, cell geometry) belong here rather than in a separate bucket
  • deterministic semantic validation catches extraction that still looks superficially plausible: dates parse as dates, identifiers match expected formats, enum values are valid, totals reconcile, duplicates appear only where valid — with table-specific semantic checks (column-type purity, valid currencies and ranges, key-field consistency) in the same bucket, plus metadata completeness, source-version consistency, and ACL field presence

2. Technical Model-Based Validation

This category is used when deterministic checks are not enough.

It is useful for messy layouts, subtle semantic mismatches, and ambiguity that is hard to encode as rules.

These checks may use LLMs or smaller task-specific models, but they should remain bounded and auditable.

Model-based areaTypical usesGuardrailOffline reference metricsProduction proxy metricsExample gate logicTypical action
Semantic plausibility reviewsemantic comparison of aligned sections, content plausibility beyond pattern matchingUse only after deterministic checksagreement with human review, semantic defect detection precision and recallmodel consistency score, contradiction score, evidence coverage scoreuse as support signal only when confidence exceeds calibrated floor; do not hard-gate alonewarn, route to repair
Structural ambiguity resolutionclassify ambiguous structural blocks, interpret messy table headersDo not let the model silently redefine structure without traceblock classification accuracy, header interpretation accuracyheader interpretation confidence, block classification confidenceuse only when deterministic checks are inconclusive and confidence is highrepair suggestion, manual review
Repair suggestion supportlow-confidence repair suggestions, likely OCR corruption hintsSuggestions must be re-validated deterministicallyrepair success rate after re-validationrepair confidence, predicted corruption severitynever publish from this alone; require deterministic re-validation after repairrepair then re-validate

The governing rule: model-based validation should support technical validation, not replace it. Concretely that means LLM-based section-consistency review, model interpretation of messy table headers, comparison of extracted summaries against underlying block content, and model-assisted detection of OCR-corruption patterns that deterministic rules missed — all used as support signals or repair suggestions, never as standalone gates.

3. Comparative Consistency Validation

This category compares independent representations of the same content.

It is often stronger than trusting one extractor’s internal confidence.

This category can combine deterministic and model-based checks.

Comparative areaWhat is comparedTypical signalsOffline reference metricsProduction proxy metricsExample gate logicTypical action
Cross-extractor validationmultiple OCR or parser outputs for the same sourcestructure mismatch, table shape mismatch, reading-order mismatch, key-field disagreementbest-extractor agreement with gold, disagreement precision for defect detectionextractor agreement rate, structure edit distance, key-field disagreement countwarn if disagreement exceeds class baseline; quarantine if key fields disagree materiallywarn, repair, quarantine
Cross-language consistency validationparallel language versions of the same documentsection mismatch, table-shape mismatch, key-field mismatch, coverage mismatch, semantic mismatchaligned-field match rate, section match accuracy, bilingual table field accuracysection alignment rate, normalized key-field match rate, coverage gap countwarn on small drift; quarantine when key sections or key numeric fields diverge materiallywarn, repair, quarantine
Comparative table validationtables across extractor outputs or bilingual versionssame approximate dimensions, same key values, same row coverage, same field mappingbilingual key-field accuracy, table alignment accuracytable-shape similarity, row-coverage overlap, key-value match ratequarantine if table-shape similarity or key-value match rate falls below minimum trust thresholdrepair, quarantine

3.1 Cross-Extractor Validation

When multiple OCR or parsing methods are available, disagreement is a useful signal — and typically a stronger one than either extractor’s internal confidence.

Design principle:

Independent disagreement is often more informative than one model’s self-confidence.

3.2 Cross-Language Consistency Validation

When documents exist in parallel language versions, cross-language agreement can be a very strong validation signal — especially for bilingual corpora where the same document is maintained in two language versions.

Checks compare section structure, table shape and coverage, normalized key fields such as dates, amounts, percentages, and codes, and semantic consistency of aligned sections — so neither version silently misses a section, table, or note. Table validation belongs in this category when bilingual versions exist: compare table dimensions, key numeric or coded values, row coverage, and major field mapping.

Important caution:

  • mismatch does not automatically mean one side is correct and the other side is wrong
  • mismatch may indicate OCR failure, layout failure, translation drift, version drift, or source inconsistency

Cross-language consistency should therefore be used as:

  • a validation signal
  • a repair hint
  • a trust-scoring input

not as blind overwrite logic.

4. Business-Specific Validation

For high-value document classes, domain-specific checks are often worth the effort.

Business-specific areaTypical checksExample document classesOffline reference metricsProduction proxy metricsExample gate logicTypical action
Required field presenceexpected fields are presentpolicy tables, forms, contractsrequired-field extraction accuracyrequired-field hit ratequarantine if critical fields are missingquarantine
Domain value validationknown codes, worker types, product ids, region setsfee schedules, eligibility matrices, catalogsdomain-field accuracyvalid-domain-value ratio, unknown-code countwarn on minor unknown values; quarantine on critical code mismatchwarn, quarantine
Numerical reconciliationtotals, rates, counts, limits are internally consistentinvoices, rate cards, finance tablesreconciliation accuracy on gold setabsolute reconciliation error, percentage reconciliation errorquarantine when error exceeds domain tolerancerepair, quarantine
Regulatory or policy structure validationexpected section presence or clause layoutlegal docs, policies, compliance documentsmandatory-clause detection accuracyexpected-section coverage, mandatory-clause presencequarantine if mandatory sections or clauses are absentquarantine

Validation Decision Policy

A simple implementation pattern is to maintain separate scores or flags per category rather than one opaque global score.

The production gate should use proxy metrics, not offline reference metrics.

Offline reference metrics are for:

  • selecting OCR or parser models
  • selecting repair methods
  • calibrating thresholds
  • deciding which proxy metrics are trustworthy enough to gate on
CategoryExample policy
Technical deterministichard gate for critical failures
Technical model-basedsupporting signal only
Comparative consistencystrong gate when independent views disagree materially
Business-specifichard gate for high-risk document classes

Practical decision rules:

ConditionRecommended decision
critical metadata or ACL failurefail or quarantine
severe structural failure in key tables or reading orderquarantine
deterministic checks mostly pass but comparative drift is moderatepass_with_warning or repair_and_pass
model-based validator suspects corruption but deterministic checks are cleanwarn and queue for sampling, not immediate quarantine
repair succeeds and deterministic re-validation passesrepair_and_pass

Post-Production Monitoring

Some failures will still escape production gates.

The system should therefore monitor published content using:

Monitoring methodPurpose
sampled manual auditscatch hidden quality failures
downstream retrieval or answer failure reviewtrace missed defects back to ingestion
drift dashboards by source, language, or extractordetect quality regressions over time
periodic re-evaluation on gold setsdetect whether model or parser upgrades helped or harmed

This closes the loop between offline evaluation, online gating, and production feedback.

Business-specific validation should remain selective and document-type-aware.

Repair Strategy

Misaligned tables are one of the highest-impact ingestion failures because the output often looks plausible while being structurally wrong.

Common failure patterns:

  • rows merged incorrectly
  • columns shifted by one cell
  • headers attached to wrong columns
  • multi-line cells split into extra rows
  • merged cells flattened incorrectly
  • table values extracted as free text with lost cell boundaries
Suspicious table
-> re-run extraction differently
-> re-check structure
-> re-check semantics
-> compare with alternate extractor or paired language version
-> pass, repair and pass, or quarantine
Repair methodWhen to useLimitation
deskew image and rerun OCRpage image is skewed or visually noisymay not fix logical table structure
crop and rerun table extractiontable region is known but full-page extraction is poordepends on good region detection
use a table-specialized extractorgeneric OCR preserved text but lost cell structureadds tool complexity
use geometry-aware row or column reconstructionbounding boxes exist but row or column grouping is weakstill needs re-validation
use stronger paired-language extraction as a repair hintbilingual version is structurally cleanershould guide repair, not overwrite blindly

Important rule:

  • do not perform speculative semantic repair when structure remains uncertain

Common Failure Modes and Responses

Failure modeTypical symptomsPrimary response
Misaligned tableswrong row or column mapping; table looks readable but answers are wrongstructural validation; semantic validation; alternate extraction; cross-language comparison; quarantine if unresolved
Small OCR typosids, names, policy numbers, or codes are slightly wrongkeep source and normalized variants; apply safe normalization for known patterns; compare against expected identifier formats; use fuzzy recovery cautiously for validation
Broken reading ordermulti-column text interleaves; headers or footers mix into body textlayout-aware parsing; reading-order validation; document-type-specific heuristics
Lost section hierarchytext is locally correct but globally ambiguouspreserve heading levels during reconstruction; validate section ordering and nesting; compare against paired-language structure where available
Missing or wrong metadatasource version, language, or ACL fields are missing or inconsistentrequired metadata checks; explicit unknown state rather than fake defaults; quarantine when mandatory fields are absent
Duplicate or stale artifactsold versions appear alongside new versions; deletes are not reflected in staging corpusstrict source versioning; tombstone handling; pre-publish consistency checks
Overaggressive normalizationsemantically meaningful formatting is lostpreserve raw representation alongside normalized form; use conservative normalization policies

Publish and Quarantine Policy

Validation should produce explicit decision artifacts.

ArtifactPurpose
quality_scoreoverall quality signal for downstream trust decisions
risk_flagsexplicit record of detected issues
repair_attemptedindicates whether any repair flow was used
trust_levelcompact trust summary for downstream systems
publish_decisionfinal gate decision
Publish decisionMeaning
passtrusted for downstream processing
pass_with_warningusable but marked with known limitations
repair_and_passusable after repair and re-validation
quarantineblocked from downstream use pending review or reprocessing
failunusable extraction outcome

Only trusted outputs should move downstream by default.

Quarantined outputs should remain inspectable for debugging and manual review.

Downstream Contract

The output of this layer should be a validated canonical document that downstream systems can depend on.

Downstream consumers should not need to guess:

Downstream questionMust be answered by this layer
which extractor produced the contentyes
whether the structure is trustedyes
whether a repair was attemptedyes
whether the document passed bilingual consistency checksyes
whether the content is quarantinedyes
Downstream output fieldPurpose
canonical document contentvalidated content for downstream use
source lineagetraceability back to source artifact
validation statuspublish-state summary
trust score or trust leveldownstream confidence input
risk flagsexplicit known issues
repair historyauditability of repair flow

Minimal Serious Baseline

For a practical baseline, this layer should at least provide:

Baseline capabilityWhy it matters
source id, version, and ACL preservationpreserves traceability and governance
layout-aware parsing or OCRavoids flattening structure too early
structure reconstruction before chunkingprevents downstream chunking on corrupted layout
unified canonical representation across extractorsgives validation one stable interface
structural and semantic validationcatches high-risk extraction failures early
table-specific validationtables are high-impact and structurally fragile
cross-language consistency checks when paired documents existprovides strong independent validation
quarantine for low-trust documentsblocks bad content from becoming downstream truth
explicit publish decisions and traceabilitymakes system behavior inspectable and governable

Tooling Options

Keep this section short and practical.

Use caseRecommended optionWhy
smallest strong open-source OCR baselinePaddleOCRpractical multilingual OCR, good performance, relatively lightweight
strongest open-source document parsing and extraction stackMinerUstrong open-source performance for document understanding and structured extraction
managed commercial fallbackAzure Document Intelligencestrong OCR, layout, and table extraction with enterprise support

Practical recommendation:

  • start with PaddleOCR when you want a lightweight open-source OCR base
  • use MinerU when document understanding quality matters more than minimal footprint
  • use a managed commercial service only when support, compliance, or document complexity justifies it

When parsing quality is the deciding factor, the set-wide default for parsing in CH03_RAG-Layer.md’s Reference Stack is MinerU.

Final Note

The goal of this layer is not to guarantee perfect OCR or perfect parsing.

The goal is to prevent low-trust extracted content from quietly becoming downstream truth.

That is why ingestion and validation should be treated as a first-class independent subsystem rather than a preprocessing detail.