05.10 Data Quality Checks

RetrievalLesson 10 of 1014,346 words13 parts
Module 05 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Everything in this module so far has been about producing data: parsing it, cleaning it, chunking it, describing it, versioning it, generating synthetic stand-ins for it. This lesson is about trusting it — the unglamorous discipline that decides whether the retrieval system you built in Modules 06 and 07 actually works on your real corpus. Data quality for AI is not the same as data quality for a dashboard: a BI analyst can spot a bad row in a table; an LLM system silently embeds a flattened table, a repeated footer or a stale policy and then answers confidently from it. This lesson gives you the dimensions of quality that matter for LLM pipelines, the checks that catch defects at every stage from raw file to served answer, the tools (Pydantic, pandera, Great Expectations, Soda, jsonschema, DuckDB) and when each earns its place, profiling and golden-set methods for catching regressions, drift monitoring and circuit breakers, stage contracts, human review loops, and a complete runnable quality-check suite you can drop into the pipeline from 05.9.

What you'll learn

  • What "data quality" means for an AI pipeline — the nine dimensions (completeness, validity, uniqueness, consistency, freshness, accuracy/fidelity, coverage, representativeness, provenance) — and why LLM systems fail silently on bad data
  • The checks that belong at every stage: raw files, parsed text, cleaned text, chunks, enriched metadata, vectors and served records
  • The validation-tool landscape as of November 2026: Pydantic, pandera, Great Expectations (GX Core), Soda, jsonschema, and plain assertion functions — with licences, versions and a decision table
  • How to profile a corpus before you trust it: length distributions, character histograms, language mix, duplicate rates, token and cost projections
  • Golden sets and spot checks: parser regression tests with diff tolerance, stratified sampling, and how many documents a human should actually eyeball
  • How to quantify parse and chunk quality: text coverage, table recovery, CER/WER, chunk coherence, and retrieval-proxy checks
  • Drift and monitoring: what drifts in a data pipeline, alert thresholds, and warn-vs-fail policies (circuit breakers for bad batches)
  • Contracts between stages and with upstream data owners, human-in-the-loop review queues, quality gates in CI/CD, compliance quality (licences, PII, retention, audit trail)
  • A complete, runnable quality-check suite (standard library only) that plugs into the 05.9 pipeline as a stage

What you don't need

  • API keys. The core suite in Part 12 is pure Python standard library; only the two optional library comparisons in 3.3 and 3.5 need the installs shown in Setup. The one LLM-shaped check (chunk coherence judged by a model) is shown behind an injectable function you can fake; its mechanics are 03.4 and 03.9, which this lesson links to but does not re-teach.
  • Embedding or vector-database internals. Module 06 owns those; this lesson only checks the outputs they produce.
  • Retrieval metrics in depth. Recall@k, MRR and answer-quality evals are Module 10A; this lesson uses a few cheap proxies and points forward.

Setup

The runnable code needs only Python 3.11+ and the standard library — no keys, no installs, no services:

bash
uv init data-quality --bare --python 3.13 && cd data-quality
# or just: python3 demo.py   (any Python 3.11+)

The lesson's samples come in four files, each shown in full in Part 12: dq.py (the check suite), profiling.py (corpus profiling), golden.py (golden-set and sampling helpers) and demo.py (a toy Kestrel Works corpus with planted defects). Save them side by side and run python3 demo.py. For the optional pandera comparison in 3.3 you would add:

bash
uv add "pandera[pandas]" pandas
# or: pip install "pandera[pandas]" pandas
# for the DuckDB profiling sample in 3.5:  uv add duckdb pandas

These commands install the newest release of each package. The pandera, pandas and DuckDB samples were checked against pandera 0.35.0, pandas 3.1.1 and duckdb 2.0.0 as of November 2026; a newer major version may change names or defaults, so check the library's changelog if something does not match. No .env file or keys are needed anywhere in this lesson.


What you must be able to do after this lesson#

  • Name the dimensions of data quality for an AI pipeline
  • Add checks at each pipeline stage
  • Profile a corpus before trusting it
  • Build a golden set for parser regression tests
  • Decide which checks warn and which fail a batch

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The bot gave a wrong answer but nothing errored." 1.2 Why LLM systems fail silently
"How do we know the ingestion is any good?" Part 2: Checks by stage
"Should we use Great Expectations or pandera?" 3.2 The dataframe validators and 3.3 Try it: pandera
"The parser changed and answers got worse." Part 5: Golden sets
"Half the corpus is one template page." Part 4: Profiling
"A website redesign broke retrieval overnight." Part 7: Drift and monitoring
"This stage promises X; the next stage requires Y." Part 8: Contracts
"The index has chunks whose source was deleted." 2.7 Served-side checks
"Gate the pipeline so bad data can't ship." Part 10: Quality gates

Part 1: What "data quality" means for an AI pipeline#

1.1 The nine dimensions#

Data-quality literature (DAMA-DMBOK and friends) lists a dozen dimensions; for LLM ingestion nine carry the weight. Each one maps to a concrete failure you have already met or will meet in this module.

Dimension The question it answers AI-pipeline failure it prevents
Completeness Is anything missing? Empty extractions, pages with no text layer, dropped tables, coverage gaps between chunks (05.2, 05.4)
Validity Does each value obey its rules? Chunks outside the embedder's limits, metadata with impossible dates, vectors of the wrong dimension
Uniqueness Are there duplicates? The same paragraph embedded five times flooding top-k retrieval; duplicate files wasting parse and OCR spend (05.5 owns dedup; this lesson checks it held)
Consistency Do related values agree? Chunk count ≠ vector count; prev_id/next_id chains that don't resolve; a doc's language field disagreeing with its text
Freshness / timeliness Is it current enough? The superseded 2024 refund policy outranking the 2026 one; a source that silently stopped syncing (05.9 detects changes; this lesson checks the lag)
Accuracy / fidelity Does the stored text match the source? OCR errors, flattened tables, headers glued to the wrong rows — the extraction lied, not the schema
Coverage Does the corpus represent what users ask about? A help centre missing its most-asked topic; contracts in one language only — retrieval can't return what was never ingested
Representativeness Does the sample match the population? Evaluating on synthetic data that looks nothing like production tickets (10A.2 owns generation; this lesson warns about its blind spots)
Provenance Can every chunk trace to a source, version and run? An answer you can't audit back to page 4 of contract v3; a re-parse that can't be reproduced (05.8 owns lineage metadata; this lesson verifies it's populated)

Two consequences fall out of the table. First, most dimensions can't be checked by looking at one file — uniqueness, consistency and provenance are properties of sets and relationships, which is why checks belong at pipeline stages, not in a linter. Second, accuracy and coverage are the dimensions a schema can't express: a perfectly valid record can still contain the wrong text. They need golden sets, coverage math and human spot checks — Parts 5 and 6.

1.2 Why LLM systems fail silently#

A classic ETL pipeline fails loudly: a NOT NULL constraint trips, a row count mismatches, a job goes red. An LLM pipeline is engineered to absorb mess — parsers have fallbacks, models tolerate typos, retrieval returns something for almost any query. That resilience is exactly what makes bad data dangerous: there is rarely an exception anywhere in the system. The failure shows up three stages later as a plausible-sounding wrong answer.

Three failure stories from earlier lessons, now seen through the quality lens:

  • The flattened table (05.2's failure gallery): the price column detached from the product column. Every record is valid JSON with non-null fields — and every answer about pricing is wrong. No schema catches this; only a golden set or a table-recovery check does.
  • The repeated footer (05.5): "© 2026 Kestrel Works — All rights reserved" embedded into 4,000 chunks. Valid records, wasted embedding spend, and retrieval results crowded by boilerplate — a uniqueness/consistency failure no parser flags.
  • The stale policy: last quarter's refund policy still in the index after the new one shipped. Every check passes — the data is valid, unique and fresh as far as the pipeline knows — because the source lied about which version is current. That's a freshness/provenance failure caught only by valid_until metadata (05.8) and freshness checks.

1.3 Quality is a property of the pipeline, not the file#

A file can be a perfectly good PDF and still produce garbage downstream (two-column interleaving), and a scruffy HTML page can parse perfectly. What you check is therefore the artifact each stage emits, not the input:

flowchart LR
    subgraph stages ["The pipeline (05.1–05.10)"]
        R["raw files"] --> P["parsed docs"] --> C["cleaned text"]
        C --> H["chunks"] --> M["enriched records"]
        M --> V["vectors / index"] --> S["served to RAG"]
    end
    Q1["raw checks<br/>2.1"] -.-> R
    Q2["parse checks<br/>2.2"] -.-> P
    Q3["clean checks<br/>2.3"] -.-> C
    Q4["chunk checks<br/>2.4"] -.-> H
    Q5["metadata checks<br/>2.5"] -.-> M
    Q6["index checks<br/>2.6 · Module 06"] -.-> V
    Q7["served checks<br/>2.7"] -.-> S

Each arrow is a contract boundary: the stage on the left promises the stage on the right a certain shape and quality. Part 8 formalizes those promises; this part gives you the checks that verify them. The suite you build in Part 12 is organized exactly this way — one function family per stage — so it drops into the 05.9 pipeline as one more stage that returns a verdict.


Part 2: Checks by stage#

Every check in this part is implemented in dq.py (Part 12) and run in demo.py. Each subsection gives the what and why; the full code lives in Part 12 so you can read the patterns once and run them.

2.1 Raw ingestion checks#

Before a single byte is parsed, check the inventory itself. These are cheap, run in milliseconds, and catch the failures that otherwise waste an entire OCR bill.

Check What it measures Typical threshold Severity when violated
no_empty_files Files with bytes == 0 0 fail — an empty file is never intentional at this stage
no_oversized_files Files over a size cap (e.g. 50 MB) 0 warn — likely a zip bomb, a video or a corpus export mistaken for a document
no_duplicate_files Same sha256 appearing twice 0 warn — same content under two paths (a synced copy, an export re-run)
file_formats Extension outside the corpus allow-list (.mp4, .zip in a document set) 0 warn — a fetch bug, a sync accident, or an export that was never meant to be ingested
file_readability Magic-byte sniff per format, UTF-8 decode for text, /Encrypt marker and %%EOF trailer for PDFs 0 warn — corrupt, mislabelled or password-protected files that parse to nothing two stages later
language_mix Share of docs whose dominant script isn't expected ≤ ~10% warn — a Japanese manual in an English-only pipeline, or a mojibake dump

Two details matter. Hash the normalized content, not the file bytes, when checking duplicates — the same document saved twice with different metadata isn't a duplicate at the text level but is at the byte level; decide which you mean and say so in the check name. And script detection is a tripwire, not identification: script_class in dq.py classifies by Unicode ranges (latin, cjk, cyrillic, arabic, other) — enough to catch "a whole folder of Cyrillic docs in an English pipeline", useless for telling Spanish from French. Real language ID is 05.5's lingua/fastText territory; the check only needs to be approximately right.

2.2 Parsed-output checks#

The parser's output is where most silent damage happens, so it gets the most checks. All operate on {doc_id, text, pages?, has_tables?} records.

Check What it measures Why it works
no_empty_extractions Docs whose extracted text is under ~40 chars A born-digital PDF returning nothing means the parser picked the wrong path; a scan needs OCR routing (05.4)
chars_per_page Extracted chars ÷ page count vs a sane band (~200–6,000) ~0 chars/page = missed text layer; ~10k+/page = duplicated text or double-OCR; both are silent
garbage_ratio Share of damaged chars: U+FFFD replacement chars, private-use-area glyphs, stray control chars, mojibake pairs — a lead character Ã/Â/†followed by a Latin-1 or cp1252 continuation look-alike (é, ’,  + NBSP); an ordinary letter after the à ("SÃO PAULO") doesn't count The signature of encoding damage and bad OCR — measure the ratio, not presence, so one stray char doesn't fail a 50-page doc
repeated_lines Fraction of lines identical to the line directly above A stuttering extraction (a layout engine re-emitting a line per text box, an OCR retry); >~30% means the parser or cleaner is looping. It only sees adjacent repeats: a footer that recurs once per page is caught by banned_patterns and chunk_uniqueness, not here
tables_recovered Docs flagged has_tables but with no Markdown table delimiter row (` ---
reading_order Lines ending mid-sentence followed by capital/digit-opening lines — the alternating-topics signature of two-column interleave Warn-level heuristic: wrapped prose continues lowercase, interleaved columns jump capitals every line. Cheap tripwire; golden sets give the verdict

The chars_per_page band deserves a note: it's a heuristic envelope, not a law. Dense legal text runs ~2–3k chars/page; sparse slide decks ~300. What you're detecting is outliers from your own corpus's median, so on a real corpus compute the per-source median first and flag docs at, say, <20% or >300% of it — the fixed band in dq.py is the toy version.

2.3 Cleaned-output checks#

Cleaning (05.5) is where the second class of silent damage is introduced: the cleaner itself can destroy signal. Three checks guard it.

Check What it measures Why
banned_patterns Regex sweep for leftovers: [PAGE n] markers, mojibake pairs, email signatures Whatever the cleaner was supposed to remove, verify it's gone
cleaning_magnitude len(cleaned) / len(raw) per doc, kept inside ~50–110% Over-cleaning is as dangerous as under-cleaning: below the floor the cleaner deleted the numbers and clause references that carry meaning; above the ceiling it added text — injected boilerplate, duplicated signatures. Both are smells
cleaning_idempotent clean(clean(x)) == clean(x) A non-idempotent cleaner compounds damage on every pipeline re-run — and 05.9 re-runs constantly
pii_scan Count of email / UK-phone / card-number hits (card candidates must pass the Luhn checksum), values never logged Tripwire only: regexes miss names, addresses, IDs in free text. Real PII handling is 05.5 + Presidio + Module 12; this check proves something is scanning

The PII point deserves emphasis: the check reports counts, never values. A quality report that logs the emails it found has just created a second PII leak. check_pii_scan returns doc_id:email×2 — enough to route the doc to the redaction queue, useless to an attacker reading the logs.

2.4 Chunk checks#

Chunks are the unit everything downstream consumes, so they get the densest check family — this is where "garbage in" most often becomes "wrong answer out".

Check What it measures Why
chunk_sizes min / p50 / max char length vs bounds The embedder's input limit is a validity constraint; a 5,000-char chunk may pass the schema and still be silently truncated at embed time (02.3)
chunk_uniqueness Empty chunks, exact-duplicate texts (whitespace-normalized) Duplicates waste embedding spend and flood top-k; empties are pure noise
chunk_coverage Union of [char_start, char_end) spans vs the source length The big one. Gaps mean content that exists in the parsed doc never reached the index — the system can't retrieve what was never chunked. Also flags offsets outside [0, len(doc)]
mid_word_splits Consecutive chunks where prev ends alnum and next starts alnum Heuristic for mid-word/mid-token splits — a boundary-quality proxy, warn-level because it's imperfect
chunk_links prev_id/next_id pointers resolve within the doc Broken links break neighbour-expansion at query time (05.6)
orphan_chunks Chunks whose doc_id has no entry in doc_lengths The inverse of coverage: a chunk pointing at a document the manifest doesn't know — stale manifest, deleted-then-reprocessed doc, bad join upstream
overlap_sanity Per-doc duplicated-span fraction 1 − union/sum vs ~50% Legitimate chunker overlap is ~5–20%; beyond that the same text is embedded repeatedly — wasted spend and top-k flooding

chunk_coverage is the check people skip and regret. Implemented naively it's a merge-intervals problem: sort spans, walk a cursor, flag gaps wider than a tolerance. The subtlety is overlap: chunks legitimately overlap (05.6's overlap parameter), so you compute the union of coverage, not the sum — char_start/char_end offsets make this exact. If your chunker doesn't emit offsets, coverage degrades to "sum of lengths vs doc length" which can't distinguish overlap from gaps; that's an argument for always storing offsets (05.6, 6.4).

2.5 Enriched-metadata checks#

Enrichment (05.8) adds the fields retrieval filters on, so its failures are findability failures: the data is there but can't be reached by the query that needs it.

Check What it measures Why
required_fields Null-rate per required field (doc_type, language, tenant_id, acl…) A null tenant_id is either unservable or a cross-tenant leak waiting to happen
enum_fields Values within the allowed set An LLM tagger inventing "blog-post" for a contract means the controlled vocabulary isn't controlled — the taxonomy drifted
vocabulary_drift Share of tag values not in the reference vocabulary Early warning that the enrichment prompt, model or input distribution changed

The enum_fields/vocabulary_drift pair is the LLM-specific version of a schema check: a tagger with strict structured output (03.4) can't emit an out-of-enum type, but it can absolutely emit an enum value you didn't anticipate semantically ("contract" vs "agreement" vs "msa"). The fix is upstream — closed vocabularies and normalization in 05.8 — the check just proves it held.

2.6 Indexed/vector checks (preview of Module 06)#

The vector store is the first stage whose output you don't fully control — the index is a black box that can drop, duplicate or corrupt records. Cheap invariants catch most of it:

Check What it measures Why
count_parity len(chunks) == len(vectors) The classic silent failure: a partial upsert leaves the index missing chunks with no error
vector_dims All vectors same dimension = expected A mixed-dimension index either rejects writes or silently can't compare across them
no_dead_vectors Zero vectors, NaN components (x != x) A zero or NaN vector sits at a meaningless point in space and can win or lose similarity arbitrarily
no_duplicate_vectors Identical vector hashes Two chunks with byte-identical embeddings are almost always duplicate text that survived dedup
single_embedding_model One model_id across all records Mixing embedding models in one index silently corrupts every similarity score — vectors from different models live in different spaces

Module 06 owns embedding models, index internals and the vector-store APIs; treat these as the contract checks you run on whatever comes out. check_model_consistency is the one people learn about the hard way: after a model upgrade, half the corpus re-embedded on v2 and half still on v1 produces an index that "mostly works" — until it doesn't.

2.7 Served-side checks#

The last mile: is what the retrieval layer serves still the data you ingested?

Check What it measures Why
freshness_sla Per-source last_synced_at vs an SLA (e.g. 24h) A connector that silently died leaves the index confidently stale — the freshest check is on the sync, not the doc
no_orphan_records Index IDs minus live source IDs Deletion propagation: a doc deleted upstream must disappear downstream, or the bot keeps quoting a contract that no longer exists
acl_coverage Every served record has tenant_id + non-empty acl An un-ACL'd record is either unservable or — worse — visible to every tenant (05.8, Part 5)

The served checks are the only ones that verify the whole loop — ingestion, indexing and deletion propagation together. They're also the cheapest to run continuously: they're set-difference and timestamp comparisons over metadata you already store.

2.8 The stage-check matrix#

Stage Checks Catch rate Cost
raw inventory, sizes, hashes, formats, readability, language mix High — cheap and total ~free
parsed empty, chars/page, garbage, repeats, tables, reading order High for mechanical damage ~free
cleaned banned patterns, magnitude, idempotency, PII Medium — needs good patterns ~free
chunked sizes, dupes, coverage, boundaries, links, orphans, overlap Highest value — catches the most answer-breaking bugs ~free
enriched required fields, enums, vocab drift Medium — catches findability bugs ~free
indexed parity, dims, dead/dup vectors, model id High for index corruption ~free
served freshness, orphans, ACL High for the whole-loop view ~free
all golden sets, CER/WER, coherence, retrieval proxies The only checks that measure meaning human/LLM time

The last row is the honest one: everything above is structural — it verifies shape, counts, ranges and links. No structural check can tell you the extracted text says what the PDF says. That needs Parts 5 and 6: golden sets, human spot checks and quality metrics that compare against ground truth.


Part 3: Validation tools#

Deep-dive

3.1 Pydantic as the base layer#

Every record your pipeline emits — ParsedDocument, Chunk, ChunkMeta, the vector-store payload — should already be a validated schema type (05.2, 05.6, 05.8): ParsedDocument and ChunkMeta are Pydantic models while Chunk is a dataclass, but all of them enforce their shape at construction. Where Pydantic is in the loop it is your first and cheapest validation layer: it runs on every record, catches type errors and constraint violations at construction time, and produces errors precise enough to feed back to a retry loop (03.4, Part 6 teaches the validate-and-retry pattern for LLM output; the same shape works for pipeline records).

Where Pydantic stops: it validates one object at a time. It can't answer "is the null rate on language under 2% across 40,000 chunks?" or "did the set of doc_type values drift?" Those are aggregate questions — and that's what the dataframe validators are for.

3.2 The dataframe validators#

When your records land in a table — a pandas DataFrame, a DuckDB table, a Polars frame — you want to assert properties over the whole column at once. Four tools dominate as of November 2026:

Tool What it is Licence (Nov 2026) Current version Best at
pandera Python-native schema + statistical checks on dataframes (pa.DataFrameModel, pa.Check) MIT 0.35.0 Column-level constraints in pure Python; integrates with check_types decorators and pipelines
Great Expectations (GX Core) The veteran framework: Expectations, suites, validation definitions, data docs Apache-2.0 1.24.1 Large estates, named reusable expectations, generated docs; heavier API
Soda Core Checks-as-code: SodaCL YAML files + data contracts, soda scan CLI Elastic License 2.0 (changed Jan 2026) 4.30.0 YAML-declared checks analysts can read; contracts as a product feature
jsonschema The JSON Schema validator itself MIT 4.26.0 Validating JSON/JSONL records against a schema document — the lingua franca every provider also speaks

Plus the honest fifth option: plain assertion functions — which is what dq.py is. More on that in 3.4.

3.3 Try it: pandera on the chunk table#

Pandera is the lightest way to get column-level assertions in Python. The API as of 0.35.0 (pandera[pandas] extra; verified against the README and docs):

python
# chunks_schema.py — validate a chunk DataFrame before indexing.
# Requires: pandera[pandas], pandas
import pandas as pd
import pandera.pandas as pa
from pandera.typing.pandas import Series


class ChunkFrame(pa.DataFrameModel):
    chunk_id: Series[str] = pa.Field(str_length={"min_value": 1})
    doc_id: Series[str]
    text: Series[str] = pa.Field(str_length=(200, 2400))
    char_start: Series[int] = pa.Field(ge=0)
    char_end: Series[int] = pa.Field(ge=0)
    # token_count is float, not int: a missing count becomes NaN, and
    # Series[int] (int64) can't hold it — nullable=True then skips the
    # element-wise checks on the null, which is what we want.
    token_count: Series[float] = pa.Field(ge=1, le=8000, nullable=True)

    @pa.dataframe_check
    def end_after_start(cls, df: pd.DataFrame) -> pd.Series:
        # char_end > char_start compares *two* columns, so it can't be a
        # column-level @pa.check — dataframe-level is the right decorator.
        return df["char_end"] > df["char_start"]


df = pd.DataFrame({
    "chunk_id": ["hb-000", "hb-001"],
    "doc_id": ["handbook", "handbook"],
    "text": ["x" * 300, "y" * 100],          # second row: 100 chars < 200
    "char_start": [0, 250],
    "char_end": [300, 50],                   # second row: 50 < 250 -> check fails
    "token_count": [80, None],               # pandas stores this as float64
})

try:
    validated = ChunkFrame.validate(df, lazy=True)
    print(validated)
except pa.errors.SchemaErrors as e:
    # lazy=True collects *every* failure into one report — one bad column
    # doesn't hide the others. failure_cases is a DataFrame of offenders.
    print(e.failure_cases[["schema_context", "column", "check",
                           "failure_case"]])
Example output · illustrative3 lines
   schema_context column              check failure_case  index
0          Column    text  str_length(200, 2400)  yyy...x100      1
1  DataFrameSchema    NaN   end_after_start(...)         False      1

Pandera's exact error formatting differs by version — the point is that lazy=True collects all failures into one SchemaErrors report instead of stopping at the first, which is what you want in a pipeline. Three API details this sample uses: pa.Field keyword arguments dispatch to the built-in Check methods — a dict becomes kwargs (str_length={"min_value": 1}) and a tuple unpacks as positional args (str_length=(200, 2400)), while isin takes an iterable of allowed values, not a predicate. And @pa.dataframe_check is for rules spanning columns (char_end > char_start); @pa.check only ever sees its own column. Also note pa.Field(..., coerce=True) will cast values (e.g. "80" → 80) rather than fail — coercion is convenient but dangerous on metadata you later filter on; prefer failing loudly for fields that must already be correct.

3.4 Custom assertion functions#

For checks that aren't "column X in range Y" — coverage gaps, link resolution, duplicate vectors, freshness lag — you write functions. The pattern that keeps them maintainable:

python
# checks.py — the shape every custom check follows.
from dq import CheckResult, ok, bad

def check_something(records: list[dict], threshold: float) -> list[CheckResult]:
    """One job: measure, compare to threshold, return CheckResults.

    Rules that make a check trustworthy:
      * it measures something concrete (a count, a ratio, a max)
      * it names the threshold it compared against
      * on failure it says *which* items tripped it (ids only, never values
        that could themselves be sensitive)
    """
    offenders = [r["id"] for r in records if r["score"] < threshold]
    measured = f"{len(offenders)}/{len(records)} below {threshold}"
    return [ok("score_floor", "stage", measured, f"0 offenders")
            if not offenders else
            bad("score_floor", "stage", "warn", measured,
                "0 offenders", ", ".join(offenders[:5]))]

This is deliberately the same CheckResult(name, stage, ok, severity, measured, expected, detail) shape the whole dq.py suite uses — so a hundred custom checks compose into one gate (10.1). The discipline is in the reporting, not the computation: every check must say what it measured and what it expected, because "check failed" without numbers is unactionable at 3am.

3.5 DuckDB/pandas for profiling#

Before reaching for a validation framework, remember that SQL answers most aggregate questions already. DuckDB (MIT licence, v2.0.0 as of November 2026, embeds in-process, reads CSV/JSON/Parquet) turns your JSONL chunk dump into a queryable table:

python
# profile_duckdb.py — chunk-table profile in five queries.
# Requires: duckdb, pandas   (.df() needs pandas installed)
import duckdb
import json

# chunks.jsonl: one JSON object per line, as 05.9's manifest writes it
con = duckdb.connect()
con.execute("CREATE TABLE chunks AS SELECT * FROM read_json_auto('chunks.jsonl')")

print(con.execute("""
    SELECT doc_type, COUNT(*) AS n,
           ROUND(AVG(length(text))) AS avg_chars,
           ROUND(MAX(length(text))) AS max_chars
    FROM chunks GROUP BY doc_type ORDER BY n DESC
""").df())

print(con.execute("""
    SELECT COUNT(*) AS total,
           COUNT(*) - COUNT(DISTINCT text) AS exact_dupes,
           COUNT(*) FILTER (WHERE length(text) < 200) AS too_small,
           COUNT(*) FILTER (WHERE length(text) > 2400) AS too_big
    FROM chunks
""").df())
Example output · illustrative7 lines
   doc_type   n  avg_chars  max_chars
0  handbook  412        812       2390
1  contract  187       1104       2388
2  ticket    96        340        980

   total  exact_dupes  too_small  too_big
0    695            12          3        0

DuckDB is the right tool when your "records" are already rows (chunks.jsonl, an enriched-metadata export, a tickets table) and the question is aggregate. It's the wrong tool for per-record content checks (does this chunk's text actually parse?) — that's what dq.py's functions are for. Use both: DuckDB to profile the table, dq.py to check the records.


Part 4: Data profiling#

Before you write a single check, profile the corpus. Profiling is the cheap, always-run first pass that tells you what "normal" looks like for your data — and every threshold in Parts 2–3 should be derived from the profile, not guessed. A threshold of "200–2,400 chars per chunk" is meaningless until you know your corpus's actual distribution.

4.1 What to profile#

Profile What it tells you Red flag it surfaces
Counts & sizes docs, total chars, min/p50/p95/max/mean length A corpus that's 90% one giant file, or thousands of 50-char stubs
Character-class histogram % letters, digits, whitespace, punctuation, symbols, other "other" > ~5% suggests encoding damage or heavy non-text content
Script/language mix Dominant script per doc Unexpected scripts, or a doc that's 40% "other" (mojibake)
Duplicate rate Exact-hash dupes Templated pages, re-exports, sync artefacts
Token estimate chars ÷ ~4 (English rule of thumb) Embedding cost projection: n_chunks × tokens × price (03.7, Module 06)
Per-source breakdown docs/chars per source system One source dominating, or a source that should exist but doesn't (coverage gap)

The character-class histogram is the sleeper metric: it's the fastest way to spot "this corpus is mostly tables-as-images" or "half the text is whitespace from a bad PDF extraction". profiling.py computes all of this in ~60 lines of stdlib.

4.2 A profiling report generator#

profiling.py's profile_corpus(docs) returns a stats dict; render_profile(stats) turns it into the Markdown block that lands in your quality report:

python
# profiling.py (abridged — full file in Part 12)
from profiling import profile_corpus, render_profile

stats = profile_corpus(DOCS)          # [{"doc_id","source","text"}]
print(render_profile(stats))

Real output from the demo corpus:

text
- Documents: **5** (3,924 chars, ~981 tokens at ~4 chars/token)
- Lengths (chars): min 219, median 752, p95 1,184, max 1,215 (mean 784)
- Character classes: letter 74.7%, space 19.3%, punct 2.7%, digit 1.8%, other 1.5%
- Dominant scripts: latin 5
- Exact duplicates: 0

| Source | Docs | Chars |
|---|---|---|
| html | 1 | 752 |
| jsonl | 1 | 219 |
| pdf | 3 | 2,953 |

Read it as a reviewer: 5 docs, all Latin script, healthy letter ratio (74.7% — text, not noise), one source (pdf) holding 75% of the corpus. On a real corpus this table is the first thing you check when "answers got weird" — a sudden shift in char_classes or scripts is often the earliest sign of a parser regression or a new upstream format.

4.3 Reading the profile#

Three uses beyond the report itself:

  1. Set thresholds from it. chunk_sizes bounds, chars_per_page bands, garbage_ratio limits — derive them from p5/p95 of your corpus, then tighten. A threshold set from a guess produces either noise (too tight) or blindness (too loose).
  2. Cost projection. est_tokens × price-per-token is the embedding/enrichment bill for a full reindex — the number you need before approving a re-chunk (05.9 owns reindexing; Module 06 owns embedding pricing).
  3. Drift baseline. Store the profile per run; Part 7's monitoring compares run-over-run. A profile that was 80% handbook docs last week and is 40% this week means the upstream source changed — before any check fails.

Part 5: Golden sets and spot checks#

Structural checks (Part 2) verify shape; golden sets verify content. This is the only way to catch "the parser produced valid-looking text that says the wrong thing" — the flattened-table failure, the wrong-column price, the OCR'd "l" for "1" in a part number.

5.1 Golden sets: the parser's unit tests#

A golden set is a small, human-verified sample of documents with their known-correct extracted text. For each source type you keep a handful — the running corpus might have 3 PDFs, 2 HTML pages, 1 scanned contract — and after every parser or cleaning change you re-run extraction and diff against the golden output.

The discipline that makes it work:

  • Small but stratified. Not 1,000 docs — 10–50 per source type, chosen to cover the hard cases (tables, two-column, scanned, multilingual, longest doc). 5.3 gives the math.
  • Human-verified once, frozen after. Someone reads the golden output against the source and signs it off. It's the ground truth everything else is measured against.
  • Versioned with the code. The golden set lives in git next to the parser; a parser PR that changes golden output must update the golden file — that's the review checkpoint.

5.2 Parser regression tests with diff tolerance#

The naive test — assert extracted == golden — fails on every harmless change (a whitespace normalization, a Unicode fix). You want a similarity ratio that tolerates cosmetic drift but catches real regressions:

python
# golden.py — compare extraction output to the golden set.
from difflib import SequenceMatcher

def similarity(a: str, b: str) -> float:
    """0.0 = completely different, 1.0 = identical.
    Compare WORDS, not characters: whitespace and line wrapping stop
    mattering, and the cost drops from quadratic-in-characters to
    quadratic-in-words. autojunk=False is essential (see the warning below).
    SequenceMatcher finds the longest matching blocks — robust to
    reordering and small edits, unlike a char-by-char diff."""
    return SequenceMatcher(None, a.split(), b.split(), autojunk=False).ratio()

golden_compare(expected, actual, tolerance=0.98) in golden.py runs this per document and returns CheckResults — the same shape as every other check, so golden failures flow into the gate like everything else. The demo shows it working: a parser regression that truncates returns-page at 60 chars scores 0.450 similarity and fails the gate, while the untouched handbook scores 1.000.

Choosing the tolerance is a judgement call: 0.98 catches truncation and column-swap but tolerates reflowed whitespace; 0.90 catches only catastrophic damage. Start at 0.95–0.98 for text, lower (~0.85) for OCR'd documents where the engine itself is nondeterministic across versions.

5.3 Sampling strategy: how many docs to eyeball#

You can't human-review every document every run — and you don't need to. The question "what fraction of docs have parse defects?" is a proportion estimate, and statistics gives you the sample size:

text
n = z² · p · (1−p) / e²        (then finite-population correction)
  • z = confidence z-score (1.645 for 90%, 1.96 for 95%, 2.576 for 99%)
  • p = expected defect rate (0.5 = worst case, largest n)
  • e = acceptable margin of error

sample_size(population, confidence, margin) in golden.py implements it with the finite-population correction (for small corpora you need proportionally fewer). Real numbers:

Corpus size Confidence Margin Docs to review
5 (toy) 95% ±10% 5 (all of them — FPC)
12,000 95% ±10% 96
12,000 95% ±5% 373
50,000 99% ±2% 3,830

Stratify, don't sample uniformly. A uniform sample of a corpus that's 90% help-centre articles tells you nothing about the 3% scanned contracts — which are where the defects live. stratified_sample allocates proportionally across strata (source type, doc_type, has_tables, language) by the largest-remainder method, so it draws exactly the number you asked for, and it never lets a non-empty stratum round down to zero: the one scanned contract in 200 documents still gets reviewed. Oversample the strata you distrust: contracts and scans deserve a higher sampling fraction than boilerplate HTML.

5.4 The human review workflow#

The review isn't "read 96 docs and guess" — it's a structured spot-check:

  1. The suite flags suspects first. Structural checks (Part 2) and profiling (Part 4) produce a suspect list — docs with high garbage ratio, coverage gaps, outlier lengths. Review those first; they're enriched for defects.
  2. A human opens source beside output. For each sampled doc, side-by-side: the PDF page and the extracted text (a notebook cell, a simple HTML diff, or a review UI). Mark pass/fail/partial per doc.
  3. Defects feed back as checks. A failure mode found in review ("tables in landscape PDFs always flatten") becomes a new golden case and possibly a new check — the review loop grows the suite.
  4. Results are recorded, not vibes. "3 of 96 sampled docs had material defects (3.1%)" is a number you can track, alert on and regress against. Store it in the run manifest (05.9).

Part 6: Quantifying parse and chunk quality#

Deep-dive

Golden sets tell you whether a parser regressed; these metrics tell you how much and where. They're the numbers you put on a dashboard and argue about in a postmortem.

6.1 Text coverage#

Text coverage = characters of meaningful source text that survived into the extracted/cleaned output, as a fraction of the source's text-layer content. For a born-digital PDF it's roughly len(extracted) / len(pdf_text_layer); for scans it's len(ocr_output) / estimated_source_chars (estimated from page area × typical char density, or from a second OCR engine). Below ~95% on a clean document means content was dropped — headers, footnotes, table cells, marginalia.

The trap: coverage can't distinguish good removal (boilerplate you meant to strip) from bad removal (a dropped clause). That's why you measure it before and after cleaning separately — parse coverage should be ~100% (minus images/figures you intentionally skip); cleaning coverage is where the 5–15% noise lives. A cleaning step that drops 40% of a legal contract isn't cleaning, it's amputation.

6.2 Table recovery rate#

For documents containing tables, table recovery rate = tables correctly extracted ÷ tables present. "Correctly" means the row↔column binding survived — a flattened table scores 0 even though all the words are present. Measure it on the golden set (hand-label which docs have tables and whether extraction preserved them) or with a structural heuristic: count |-table rows extracted vs the page's ruled-line count.

This is the metric that would have caught the flattened-pricing-table failure story in 1.2. Table recovery is the single highest-value quality metric for commercial corpora (invoices, price lists, spec sheets) because tables are where the facts live.

6.3 CER and WER for OCR#

For scanned sources, character error rate (CER) and word error rate (WER) measure extraction fidelity against ground truth — 05.4, 6.3 owns the definitions and a pure-Python edit-distance implementation. The quality-suite version is simpler: you already have golden_compare's similarity ratio; for OCR specifically you want CER because a single wrong digit in a part number is a character error that word-level metrics underweight. Build the tiny ground-truth set per 05.4, 6.4 and track CER per engine/version — it's the number that decides whether Tesseract or a VLM is earning its cost.

6.4 Chunk coherence#

A chunk can be structurally perfect (right size, good boundaries, coverage complete) and still be incoherent — a fragment that reads "...and the warranty covers" with the subject in the previous chunk. Two ways to score it:

  • Heuristic (free): a chunk should be self-contained — it starts near a boundary (heading, sentence start, paragraph start), doesn't begin or end mid-word, and has a minimum information density (not just a heading or a page number). Most of this is already covered by chunk_sizes, mid_word_splits and chunk_coverage; coherence adds the semantic check.
  • LLM-judged (costs tokens): ask a model "does this chunk make sense alone? rate 1–5" behind an injectable function. 10A.2's eval-set machinery and Module 10A's judge patterns apply; use a different model family than whatever generated the chunks to avoid self-preference bias. Run it on a sample, not the whole corpus — it's a spot-check metric, not a gate.

6.5 Retrieval-proxy checks#

The cheapest end-to-end signal: can each document be found by its own title or first sentence? For every doc in a sample, embed (or lexically match) its title/first-sentence and check whether its chunks appear in the top-k. A doc that can't find itself has a chunking or metadata problem upstream of any answer-quality metric. This is a proxy — it uses Module 06's retrieval machinery (06) but the check itself is just set membership: doc_id in top_k_ids.

The fuller version runs on 10A.2's synthetic question set: generate questions with known answer-bearing chunk IDs, run retrieval, measure whether the right chunk is retrieved. That's retrieval recall@k — formally Module 10A's metric, but the plumbing (question → retrieved chunk IDs → hit/miss) is a data-quality check on whether the corpus is retrievable at all.

6.6 The honest summary#

Metric Catches Cost Where it lives
Text coverage dropped content free Part 2 checks + golden
Table recovery flattened tables low golden set
CER/WER OCR errors ground-truth time 05.4 + golden
Chunk coherence fragments, orphans free–LLM Part 2 + optional judge
Self-retrieval chunking/metadata breaks embedding cost Module 06 proxy
Synthetic Q→chunk recall end-to-end retrievability generation + retrieval 10A.2 + Module 10A

No single metric is sufficient; the suite's job is to run the cheap ones always and the expensive ones on a schedule.

6.7 Cross-checking two extractions, and contradictions between documents#

Two further checks matter more now that pipelines route hard pages to vision-language models (05.2, 8.4 and 05.4 cover the routes and their risks). A model that reads a page can also invent it: a transposed digit in a price, a made-up table cell, a sentence that was never there. A structural check cannot see this, because the output is perfectly valid text. A cheap defence is to extract the page twice, with two independent methods (the text layer or a classical OCR engine, and the model), and compare the numbers, which are where mistakes cost the most:

python
# numeric_agreement.py — compare the numbers two independent extractions of
# the same page contain. Pure standard library.
import re
from collections import Counter

_NUM = re.compile(r"(?<![\w.])[-+]?\d[\d,]*(?:\.\d+)?%?")


def numbers(text: str) -> Counter:
    """Multiset of numeric tokens, thousands separators removed."""
    return Counter(m.group(0).replace(",", "") for m in _NUM.finditer(text))


def numeric_agreement(a: str, b: str) -> dict:
    """How many numeric tokens do the two extractions share? Numbers are where
    OCR slips (1 vs l) and where a vision model can invent or transpose values."""
    na, nb = numbers(a), numbers(b)
    agree = sum((na & nb).values())
    total = sum((na | nb).values())
    return {
        "agree": agree,
        "total": total,
        "ratio": round(agree / total, 3) if total else 1.0,
        "only_in_a": sorted((na - nb).elements()),
        "only_in_b": sorted((nb - na).elements()),
    }


if __name__ == "__main__":
    ocr = "Pro plan $49.00 per month. Returns within 14 days. 1,240 units shipped, up 8%."
    vlm = "Pro plan $49.00 per month. Returns within 30 days. 1,240 units shipped, up 8%."
    print(numeric_agreement(ocr, vlm))
    print(numeric_agreement(ocr, ocr))
Output · real — pure standard library2 lines
{'agree': 3, 'total': 5, 'ratio': 0.6, 'only_in_a': ['14'], 'only_in_b': ['30']}
{'agree': 4, 'total': 4, 'ratio': 1.0, 'only_in_a': [], 'only_in_b': []}

A ratio below, say, 0.95 on a page, or any mismatch on a field you answer questions from, routes the page to the review queue (9.1) rather than blocking the run. Treat agreement as evidence, not proof: two engines can make the same mistake, and legitimate differences (a date written "14/03" in one and "14 March" in the other) need normalizing first. The same idea works for any pair of sources: the PDF's text layer against its OCR, a parsed table against the spreadsheet it came from.

The second check is cross-document consistency. Two documents in the corpus can each be valid, unique and fresh and still disagree: the 2024 and 2026 versions of a policy both indexed, an FAQ that says 30 days where the contract says 14, a price list and a product page with different prices. Retrieval will happily return both. Cheap versions: group chunks by slug or title and flag groups with more than one live version (05.8, 4.3); extract numbers and units per topic (reusing numbers() above) and flag topics whose values differ between documents. An expensive version asks a model whether a pair of passages contradict each other, run only on candidate pairs that are highly similar by embedding or share an entity, on a schedule, with a different model family from whatever wrote the passages, and its findings go to humans, never straight to deletion. Count contradictions per source as a trend metric: a source that keeps generating them is a source that needs an owner (8.2).


Part 7: Drift and monitoring#

Deep-dive

Data quality isn't a one-time gate — it's a time series. The corpus you ingested in January is not the corpus in November, and the pipeline that worked last month can break silently when an upstream website redesigns or a parser library updates.

7.1 What drifts#

Drift type What changes What catches it
Source format drift A help-centre redesign changes the HTML structure; a CMS update alters PDF metadata Parser golden tests fail; chars_per_page and garbage_ratio shift; profile char_classes moves
Volume anomaly A sync job exports 10× documents, or zero no_empty_files-style counts vs rolling baseline; profile n_docs z-score
Null-rate spike An enrichment field that was 1% null goes to 40% required_fields threshold breach
Language shift A new market adds Japanese docs to an English pipeline language_mix / profile scripts
Schema drift Upstream API adds/removes/renames a field Pydantic validation fails at ingest; enum_fields/required_fields on metadata
Embedding-model drift Vectors re-embedded on a new model while old ones remain single_embedding_model — the mixed-model index
Freshness lag A connector dies; last sync ages past SLA freshness_sla
Parser/library drift A new major version of a PDF parser changes extraction order; a validation library relaxes a default (hypothetical examples) Golden-set similarity drops; pinned-version diff in CI

The unifying idea: every drift type has a metric that moves before the system breaks. Your job is to baseline each metric on "normal" runs and alert on deviation — which is what monitoring is.

7.2 Thresholds and anomaly detection#

Two threshold styles:

  • Fixed thresholds (what dq.py uses): "garbage_ratio ≤ 1%", "freshness ≤ 24h". Simple, explainable, but they don't adapt — a corpus that's legitimately 3% garbage will alert forever.
  • Baseline-relative thresholds: compare this run's metric to a rolling median/MAD (median absolute deviation) of the last N runs. "chars_per_page is 4σ below its 30-day median" catches a real change without hardcoding what "normal" is for your corpus.

Start fixed (you need a number to begin), graduate to baseline-relative once you have ~20 runs of history. The profile from Part 4 is your baseline — store it per run.

7.3 Circuit breakers: warn vs fail policies#

The most important operational decision: which check failures stop the pipeline and which only warn? Get this wrong in either direction and the suite is useless — too strict and it blocks every deploy on a cosmetic diff; too loose and bad data ships.

Policy When to use Example
fail the run The defect corrupts downstream irreversibly or at scale no_empty_extractions (a whole source returned nothing), count_parity (index missing chunks), single_embedding_model (mixed-model index), acl_coverage (cross-tenant leak risk)
warn, continue, queue for review The defect is bounded, recoverable, or needs human judgement garbage_ratio on one doc, pii_scan hits (route to redaction, don't block ingest), vocabulary_drift (new tags may be legitimate)
info only The metric is a trend, not a gate profile stats, cost projections, sampling counts

The severity field on every CheckResult encodes this, and gate() implements all three tiers: fail-severity failures trip the verdict, warn-severity failures annotate it, and info-severity failures are recorded in the reasons and the report's outcome column without affecting the verdict — they are trends (like cost_projection, the embedding-spend-vs-budget check in the suite), not gates. gate() in dq.py rolls it up: any fail → fail; else any warn → warn; else pass.

The circuit-breaker pattern for bad batches: when a fraction of items fail — say >5% of docs trip garbage_ratio — treat it as a systemic event (upstream changed, parser broke) rather than 50 independent doc bugs. One bad doc → quarantine it; 50 bad docs → stop the run, because the pipeline is broken, not the data. Implement it as a second gate on top of the per-check gate:

python
# circuit breaker: escalate warn→fail when failure rate exceeds a threshold
def circuit_breaker(per_item_failures: int, total_items: int,
                    max_fail_rate: float = 0.05) -> str:
    rate = per_item_failures / max(total_items, 1)
    return "trip" if rate > max_fail_rate else "hold"

Part 8: Contracts between stages and with upstream#

Deep-dive

8.1 Stage contracts#

Every arrow in the 1.3 diagram is a contract: the left stage promises the right stage a shape and quality. Formalise it and the checks stop being ad-hoc — they become contract tests.

Boundary Producer promises Consumer requires Check that verifies it
raw → parsed readable files, known formats non-empty text per page no_empty_extractions, chars_per_page
parsed → cleaned text with page/line structure no banned patterns remain banned_patterns, cleaning_magnitude
cleaned → chunked clean text + source offsets coverage complete, boundaries sane chunk_coverage, mid_word_splits, chunk_sizes
chunked → enriched chunk records with stable IDs required metadata fields, valid enums required_fields, enum_fields
enriched → indexed records with model_id + dims count parity, single model, no dead vectors count_parity, vector_dims, single_embedding_model
indexed → served index consistent with manifest freshness SLA, no orphans, ACL coverage freshness_sla, no_orphan_records, acl_coverage

The contract is versioned: lineage.chunker_version, lineage.parser_version, schema_version in the metadata (05.8, 2.5) mean a record produced by chunker-v1 and one by chunker-v2 are distinguishable — which is what lets you reindex one without touching the other. A contract without a version is a contract that will silently break on upgrade.

The schema types are the contracts: ParsedDocument (a Pydantic model in 05.2), Chunk (a dataclass in 05.6) and ChunkMeta/DocumentMeta (Pydantic models in 05.8) define the shape; the dq.py checks define the quality. Together they're "the stage emits records that are both well-formed and good".

8.2 Data contracts with upstream owners#

The pipeline's inputs have contracts too — with the people who own the sources. A data contract is a written agreement (YAML, a doc, a ticket) about what upstream promises: schema, freshness SLA, format stability, notification of breaking changes.

text
# data-contracts/help-centre.yml — what the web team promises the AI team
source: help-centre.kestrel.example
owner: web-team@kestrel.example
schema: sitemap.xml + article HTML, main content in <article>
freshness_sla: sync within 24h of publish
stability: "selectors #main-content h1/h2/p are stable; changes need 2 weeks notice"
pii: "no PII in public articles; contact forms excluded"
breaking_change_process: "file a ticket in AI-eng; we respond within 5 days"

This is Soda's data contracts product feature generalized — the idea predates the tool. The value isn't the YAML, it's the conversation: when the web team redesigns and the parser breaks, the contract tells you who to call and what they promised. Without it, "the bot is broken" becomes an unowned mystery.


Part 9: Human-in-the-loop#

Deep-dive

Some quality decisions can't be automated — low-confidence extractions, ambiguous tags, edge-case documents. The loop that handles them is what separates a demo from a production system.

9.1 Review queues#

A review queue is a prioritized list of items needing human judgement, fed by the checks:

Queue Fed by Human decides
Low-confidence parses garbage_ratio, OCR confidence below threshold (05.4, 6.5) re-OCR with different engine? send to VLM? accept as-is?
Golden-set failures golden_compare similarity < tolerance real regression or acceptable drift? update golden or fix parser?
PII hits pii_scan count > 0 redact, mask, or confirm it's a false positive (a public email in a press release)
Vocabulary drift vocabulary_drift new tags > threshold legitimate new category or tagger confusion? update vocabulary or fix prompt?
Coverage gaps chunk_coverage gaps chunker bug or intentional exclusion (front matter, indexes)?

The queue is a table (SQLite is fine), not a ticket system — each row has item_id, check_name, severity, reason, status (open/reviewed/resolved), reviewer, resolution. The point is accountability: every flagged item has a name and a decision.

9.2 From bad answers back to data fixes#

The feedback loop that closes the system: when a user reports "the bot gave a wrong answer", trace it back (05.8, 2.5 lineage makes this possible) to the chunk → the parse → the source. Was it a retrieval miss (wrong chunk), a generation error (right chunk, wrong answer — Module 10A's problem), or a data defect (the chunk itself was garbled)? Only the third is yours.

The discipline: every confirmed data defect becomes a regression test. "The invoice parser dropped the VAT column" → add that invoice to the golden set, add a tables_recovered check for VAT tables, add the pattern to banned_patterns. The suite grows from production scars — that's how it reaches "best in market" coverage rather than generic coverage.

9.3 Annotation basics#

For the metrics that need ground truth at scale (CER/WER, coherence scores, eval sets), someone has to label data. Keep it minimal:

  • Label the failure, not everything. You don't need 10,000 labelled docs — you need 50–200 labelled defects per failure mode to measure whether your fix worked.
  • Inter-annotator agreement matters for judgement calls. Two reviewers disagreeing on "is this table recovered?" means your definition is fuzzy — tighten it before scaling annotation.
  • Annotation is a cost, not a hobby. Budget reviewer-hours like you budget tokens; a golden set that nobody maintains decays into fiction.

Part 10: Quality gates and reports#

10.1 The gate function#

Everything converges here: the checks produce CheckResults, the gate rolls them into a verdict. gate() and render_report() in dq.py:

python
# gate(results) -> GateResult(verdict, reasons, results)
# verdict: "fail" if any fail-severity check failed,
#          "warn" if any warn-severity check failed (and none failed),
#          "pass" otherwise; "info" outcomes are recorded, never gating;
#          an EMPTY result list is "fail" — a gate that ran nothing verifies nothing

The demo run produces verdict: fail with 11 fail + 20 warn + 1 info — and the reasons list names every trip with its measured-vs-expected numbers and the offenders (CheckResult.detail). That's the whole point: the gate isn't a boolean, it's a report you can act on. "FAIL chunk_coverage (chunked): 3 gaps vs gaps <= 200 chars — handbook@320-678, returns-page@260-752, msr-contract:offsets outside 0-1215" tells the on-call exactly what broke and where. An empty result list is a fail ("no checks ran"): a gate that verified nothing must not wave data through.

10.2 Gates in CI/CD and in the pipeline#

Two places the gate runs:

In the pipeline (05.9): as a stage after each transform. dq.py's functions take the stage's output records and return CheckResults; the pipeline collects them, calls gate(), and branches on the verdict — fail → quarantine + alert, warn → continue + annotate, pass → proceed. The suite is deliberately stage-agnostic: same CheckResult shape whether it's checking raw files or served records.

In CI/CD: golden-set tests and a smoke-run of the suite on a fixture corpus run on every parser/chunker/cleaner PR. A PR that drops golden similarity below tolerance fails the build before it reaches the pipeline — the cheapest place to catch a regression. GitHub Actions sketch:

yaml
# .github/workflows/quality.yml — illustrative; golden_tests.py and requirements.txt are your own files
# (this lesson does not define them; the paragraph below says what the runner must do)
name: data-quality
on: [pull_request]
jobs:
  golden:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "3.13" }
      - run: pip install -r requirements.txt   # pydantic, pandera, etc.
      - run: python golden_tests.py            # exits non-zero on regression
      - run: python demo.py                    # suite smoke test on fixtures

The exit-code contract: a real runner ends with sys.exit(1 if g.verdict == "fail" else 0), so a fail verdict turns CI red while a warn-only run exits 0 and prints its report in the job log without blocking. The demo.py in Part 12 deliberately plants defects and prints Gate verdict: fail but exits 0, so the workflow's python demo.py step is a smoke test that the suite runs, not a gate; point a real workflow at a runner like the one above, over your own fixtures.

10.3 The quality report#

render_report() emits the Markdown that lands in your run manifest, your dashboard, or the PR comment. The demo's report has three parts: the verdict line, the check table (every check, its outcome, measured vs expected), and the reasons list — plus optional profile and sampling sections. On a real system you'd render the same data as HTML for a dashboard (Module 11A owns observability platforms; this is the content they'd display).

The report's job is triage: at 3am, "11 fail, 20 warn, 1 info" with named checks is actionable; "quality: bad" is not.


Deep-dive

Data quality has a legal dimension that the other dimensions don't: a perfectly accurate dataset can still be unlawful to hold or serve. These checks are compliance gates, not accuracy gates.

Concern What to check Where it lives
Licence tracking Every source's terms: may we store/embed/serve this? commercial use allowed? attribution required? DocumentMeta.licence (the usage-terms field per 05.8); a per-source licence registry
PII scan results Count of PII-pattern hits per doc; redaction status pii_scan check + DocumentMeta.confidentiality/acl; Module 12 owns the defence
Retention & deletion SLAs Docs past valid_until or deletion-requested must be gone from raw, chunks, vectors, caches freshness_sla-style age checks + a deletion-propagation job (05.9)
Audit trail Every ingest/enrich/delete run logged with actor, timestamp, manifest ID The run manifest (05.9) + lineage fields (05.8)

Two rules of thumb:

  1. Compliance checks fail closed. A missing licence field isn't "warn and continue" — it's "don't ingest until legal confirms". The severity: "fail" on required_fields for licence/confidentiality is deliberate.
  2. The audit trail is part of the data. "Who deleted this contract and when" must be answerable from the manifest alone — which is why 05.9 treats the manifest as a first-class artifact, not a log file.

Part 12: The complete quality-check suite#

This is the capstone: four files that implement everything above and plug into the 05.9 pipeline as a stage. All pure standard library — no keys, no installs, no services.

12.1 The files#

File Purpose Lines
dq.py Core types (CheckResult, GateResult) + all stage checks + gate() + render_report() ~950
profiling.py profile_corpus() + render_profile() ~115
golden.py golden_compare() + sample_size() + stratified_sample() ~115
demo.py Toy Kestrel Works corpus with planted defects; runs everything ~310

12.2 dq.py — the check suite#

python
"""dq.py — a small data-quality toolkit for an LLM ingestion pipeline.

Standard library only. Every check returns a CheckResult; gate() rolls
the results up into pass / warn / fail with reasons. This is the "quality
suite" the lesson wires into the 05.9 pipeline as a stage.
"""

from __future__ import annotations

import hashlib
import math
import re
import statistics
from dataclasses import dataclass, field
from datetime import datetime, timezone

# ---------------------------------------------------------------------------
# Core types
# ---------------------------------------------------------------------------

SEVERITIES = ("info", "warn", "fail")


def _text(record: dict) -> str:
    """A record's text, with a parser's explicit ``None`` treated as empty
    (``_text(d)`` only covers a *missing* key)."""
    return record.get("text") or ""


def _plural(n: int, singular: str, plural: str | None = None) -> str:
    """'1 gap' / '3 gaps' — keeps measured strings readable at 3am."""
    word = singular if n == 1 else (plural or singular + "s")
    return f"{n} {word}"


@dataclass
class CheckResult:
    """The outcome of one named check."""

    name: str
    stage: str
    ok: bool
    severity: str          # severity used when ok is False
    measured: str          # what we measured, human-readable
    expected: str          # what we wanted, human-readable
    detail: str = ""       # extra context for the report

    def __post_init__(self) -> None:
        if self.severity not in SEVERITIES:
            raise ValueError(f"severity must be one of {SEVERITIES}, "
                             f"got {self.severity!r}")

    @property
    def outcome(self) -> str:
        return "pass" if self.ok else self.severity


def ok(name, stage, measured, expected, detail=""):
    return CheckResult(name, stage, True, "warn", measured, expected, detail)


def bad(name, stage, severity, measured, expected, detail=""):
    return CheckResult(name, stage, False, severity, measured, expected, detail)


@dataclass
class GateResult:
    verdict: str                      # "pass" | "warn" | "fail"
    reasons: list[str] = field(default_factory=list)
    results: list[CheckResult] = field(default_factory=list)

    @property
    def counts(self) -> dict[str, int]:
        out = {"pass": 0, "info": 0, "warn": 0, "fail": 0}
        for r in self.results:
            out[r.outcome] += 1
        return out


# ---------------------------------------------------------------------------
# Stage 1 — raw ingestion checks
# ---------------------------------------------------------------------------

def _ext(path: str) -> str:
    """Lower-case extension including the dot; '' when there isn't one."""
    name = path.replace("\\", "/").rsplit("/", 1)[-1]
    return ("." + name.rsplit(".", 1)[-1].lower()
            if "." in name else "")


def check_file_inventory(files: list[dict], max_bytes: int = 50_000_000) -> list[CheckResult]:
    """files: [{"path", "bytes", "sha256"}]. Flags empties and monsters."""
    results = []
    empty = [f["path"] for f in files if f["bytes"] == 0]
    huge = [f["path"] for f in files if f["bytes"] > max_bytes]
    results.append(ok("no_empty_files", "raw",
                      _plural(len(empty), "empty file"),
                      "0 empty files") if not empty else
                   bad("no_empty_files", "raw", "fail",
                       _plural(len(empty), "empty file"),
                       "0 empty files", ", ".join(empty[:5])))
    results.append(ok("no_oversized_files", "raw", f"{len(huge)} > {max_bytes:,} B",
                      "0 oversized files") if not huge else
                   bad("no_oversized_files", "raw", "warn", f"{len(huge)} > {max_bytes:,} B",
                       "0 oversized files", ", ".join(huge[:5])))
    return results


def check_duplicate_hashes(files: list[dict]) -> list[CheckResult]:
    """Exact-duplicate detection by content hash."""
    seen: dict[str, list[str]] = {}
    for f in files:
        seen.setdefault(f["sha256"], []).append(f["path"])
    dupes = {h: ps for h, ps in seen.items() if len(ps) > 1}
    n_dupes = sum(len(ps) - 1 for ps in dupes.values())
    return [ok("no_duplicate_files", "raw",
               _plural(n_dupes, "duplicate file"),
               "0 duplicates") if not dupes else
            bad("no_duplicate_files", "raw", "warn",
                _plural(n_dupes, "duplicate file"),
                "0 duplicates", "; ".join(f"{h[:8]}: {ps}" for h, ps in list(dupes.items())[:3]))]


def check_file_formats(files: list[dict],
                       allowed_exts: set[str]) -> list[CheckResult]:
    """files: [{"path", ...}]. Flags extensions outside the allow-list —
    a .mp4 or .zip sitting in a document corpus is a fetch bug, a sync
    accident, or a corpus export that was never meant to be ingested."""
    offenders = [f["path"] for f in files if _ext(f["path"]) not in allowed_exts]
    ok_n = len(files) - len(offenders)
    return [ok("file_formats", "raw",
               f"{ok_n}/{len(files)} allow-listed",
               f"ext in {sorted(allowed_exts)}") if not offenders else
            bad("file_formats", "raw", "warn",
                f"{ok_n}/{len(files)} allow-listed",
                f"ext in {sorted(allowed_exts)}",
                ", ".join(offenders[:6]))]


# Magic-byte signatures for the binary formats this pipeline might meet.
# A file whose first bytes don't match its extension is corrupt,
# mislabelled, or not what the fetcher thought it downloaded.
MAGIC_SIGNATURES = {
    ".pdf": (b"%PDF-",),
    ".png": (b"\x89PNG\r\n\x1a\n",),
    ".jpg": (b"\xff\xd8\xff",),
    ".gif": (b"GIF87a", b"GIF89a"),
    ".zip": (b"PK\x03\x04",),
    ".docx": (b"PK\x03\x04",),
    ".xlsx": (b"PK\x03\x04",),
}

# ISO-BMFF files (mp4, m4a, mov) carry 'ftyp' at byte offset 4 instead.
BMFF_EXTENSIONS = {".mp4", ".m4a", ".mov"}

# Extensions whose content must decode as UTF-8 text.
TEXT_EXTENSIONS = {".txt", ".md", ".markdown", ".html", ".htm", ".json",
                   ".jsonl", ".csv", ".xml"}


def _magic_ok(ext: str, head: bytes) -> bool | None:
    """True/False for known signatures; None when the format has none —
    those are the allow-list's problem, not this check's."""
    if ext in BMFF_EXTENSIONS:
        return head[4:8] == b"ftyp"
    sigs = MAGIC_SIGNATURES.get(ext)
    if not sigs:
        return None
    return head.startswith(sigs)


def check_file_readability(files: list[dict]) -> list[CheckResult]:
    """files: [{"path", "content": bytes}]. 'content' is the raw file —
    toy corpora are small; production streams a head+tail sample instead.

    Three cheap probes: magic-byte sniffing for binary formats, UTF-8
    decoding for text formats, and the PDF-specific /Encrypt marker —
    a password-protected PDF parses to nothing and looks like an empty
    extraction two stages later."""
    problems = []
    for f in files:
        path = f["path"]
        content = f.get("content", b"")
        ext = _ext(path)
        magic = _magic_ok(ext, content[:16])
        if magic is False:
            problems.append(f"{path}:bad magic")
            continue
        if ext == ".pdf":
            if b"/Encrypt" in content:
                problems.append(f"{path}:encrypted")
            elif b"%%EOF" not in content[-2048:]:
                problems.append(f"{path}:truncated")
        elif ext in TEXT_EXTENSIONS:
            try:
                content.decode("utf-8")
            except UnicodeDecodeError:
                problems.append(f"{path}:not utf-8")
    return [ok("file_readability", "raw",
               _plural(len(files), "file") + " readable",
               "all readable") if not problems else
            bad("file_readability", "raw", "warn",
                _plural(len(problems), "unreadable file",
                        "unreadable files"),
                "all readable", ", ".join(problems[:6]))]


# A deliberately small script classifier: enough for "did an unexpected
# language sneak in", not a language-identification library.
def script_class(text: str) -> str:
    """Coarse script guess from Unicode ranges. Returns 'latin', 'cjk',
    'cyrillic', 'arabic', 'other' or 'empty'."""
    counts = {"latin": 0, "cjk": 0, "cyrillic": 0, "arabic": 0, "other": 0}
    letters = 0
    for ch in text[:5000]:
        o = ord(ch)
        if ch.isalpha():
            letters += 1
            if o < 0x0250:
                counts["latin"] += 1
            elif 0x0400 <= o < 0x0500:
                counts["cyrillic"] += 1
            elif 0x0600 <= o < 0x0700:
                counts["arabic"] += 1
            elif (0x4E00 <= o <= 0x9FFF) or (0x3040 <= o <= 0x30FF) or (0xAC00 <= o <= 0xD7AF):
                counts["cjk"] += 1
            else:
                counts["other"] += 1
    if letters == 0:
        return "empty"
    return max(counts, key=counts.get)


def check_language_mix(docs: list[dict], expected: set[str],
                       max_unexpected: float = 0.10) -> list[CheckResult]:
    """docs: [{"doc_id", "text"}]. Flags docs whose dominant script isn't
    in `expected`, when they exceed max_unexpected of the corpus."""
    classes = {d["doc_id"]: script_class(_text(d)) for d in docs}
    # "empty" (no letters at all) belongs to check_empty_extractions; counting
    # it here too would report one defect twice.
    unexpected = {k: v for k, v in classes.items()
                  if v not in expected and v != "empty"}
    ratio = len(unexpected) / max(len(docs), 1)
    detail = ", ".join(f"{k}:{v}" for k, v in sorted(unexpected.items()))
    return [ok("language_mix", "raw", f"{ratio:.0%} unexpected scripts",
               f"<= {max_unexpected:.0%}", detail) if ratio <= max_unexpected else
            bad("language_mix", "raw", "warn", f"{ratio:.0%} unexpected scripts",
                f"<= {max_unexpected:.0%}", detail)]


# ---------------------------------------------------------------------------
# Stage 2 — parsed-output checks
# ---------------------------------------------------------------------------

# UTF-8 text mis-decoded as Latin-1/cp1252 leaves a lead character (Ã, Â, â€)
# followed by what was a continuation byte: a Latin-1 control/punctuation
# character (U+0080-U+00BF) or one of the cp1252 look-alikes for 0x80-0x9F.
# Requiring that second character keeps legitimate "SÃO PAULO" and French
# "Âge" from matching: there the next character is an ordinary letter.
_CONT = ("[\u0080-\u00bf\u0152\u0153\u0160\u0161\u0178\u017d\u017e\u0192"
         "\u02c6\u02dc\u2013\u2014\u2018-\u201e\u2020-\u2022\u2026\u2030"
         "\u2039\u203a\u20ac\u2122]")
MOJIBAKE_RE = re.compile(rf"[ÃÂ]{_CONT}|â€{_CONT}?")


def _bad_char_count(text: str) -> tuple[int, dict[str, int]]:
    """Count characters that signal extraction damage."""
    counts = {"replacement_char": 0, "private_use": 0, "control": 0,
              "mojibake": 0}
    for ch in text:
        o = ord(ch)
        if ch == "�":
            counts["replacement_char"] += 1
        elif 0xE000 <= o <= 0xF8FF:
            counts["private_use"] += 1
        elif o < 0x20 and ch not in "\n\t\r":
            counts["control"] += 1
    counts["mojibake"] = len(MOJIBAKE_RE.findall(text))
    return sum(counts.values()), counts


def check_garbage_ratio(docs: list[dict], max_ratio: float = 0.01) -> list[CheckResult]:
    """docs: [{"doc_id", "text"}] after parsing. Ratio of damaged characters."""
    worst, offenders = 0.0, []
    for d in docs:
        n_bad, _ = _bad_char_count(_text(d))
        n = max(len(_text(d)), 1)
        ratio = n_bad / n
        worst = max(worst, ratio)
        if ratio > max_ratio:
            offenders.append(f"{d['doc_id']}:{ratio:.1%}")
    return [ok("garbage_ratio", "parsed", f"worst {worst:.2%}",
               f"<= {max_ratio:.0%}") if not offenders else
            bad("garbage_ratio", "parsed", "warn", f"worst {worst:.2%}",
                f"<= {max_ratio:.0%}", ", ".join(offenders[:5]))]


def check_empty_extractions(docs: list[dict], min_chars: int = 40) -> list[CheckResult]:
    empty = [d["doc_id"] for d in docs if len(_text(d).strip()) < min_chars]
    return [ok("no_empty_extractions", "parsed",
               _plural(len(empty), "empty extraction"),
               f">= {min_chars} chars") if not empty else
            bad("no_empty_extractions", "parsed", "fail",
                _plural(len(empty), "empty extraction"),
                f">= {min_chars} chars", ", ".join(empty[:8]))]


def check_chars_per_page(docs: list[dict], min_cpp: int = 200,
                         max_cpp: int = 6000) -> list[CheckResult]:
    """docs: [{"doc_id", "text", "pages"}]. Born-digital pages typically yield
    a few hundred to a few thousand chars; ~0 means a missed text layer,
    ~10k+ means duplicated/OCR-double text."""
    ratios = [(d["doc_id"], len(_text(d)) / max(d.get("pages", 1), 1))
              for d in docs if d.get("pages")]
    out = []
    for doc_id, cpp in ratios:
        if cpp < min_cpp or cpp > max_cpp:
            out.append(f"{doc_id}:{cpp:.0f}")
    return [ok("chars_per_page", "parsed", "all in range",
               f"{min_cpp}-{max_cpp} chars/page") if not out else
            bad("chars_per_page", "parsed", "warn",
                _plural(len(out), "outlier"),
                f"{min_cpp}-{max_cpp} chars/page", ", ".join(out[:8]))]


def check_repeated_lines(docs: list[dict], max_frac: float = 0.30) -> list[CheckResult]:
    """Fraction of lines identical to the line directly above — the signature
    of a stuttering extraction (a layout engine emitting the same line per
    text box, an OCR retry). It only sees ADJACENT repeats: a footer that
    recurs once per page is not adjacent to itself, so that shape is caught
    by ``check_banned_patterns`` (page markers) and by counting repeated
    chunks (``check_chunk_uniqueness``)."""
    worst, offenders = 0.0, []
    for d in docs:
        lines = [ln.strip() for ln in _text(d).splitlines() if ln.strip()]
        if len(lines) < 5:
            continue
        repeats = sum(1 for a, b in zip(lines, lines[1:]) if a == b)
        frac = repeats / (len(lines) - 1)
        worst = max(worst, frac)
        if frac > max_frac:
            offenders.append(f"{d['doc_id']}:{frac:.0%}")
    return [ok("repeated_lines", "parsed", f"worst {worst:.0%}",
               f"<= {max_frac:.0%}") if not offenders else
            bad("repeated_lines", "parsed", "warn", f"worst {worst:.0%}",
                f"<= {max_frac:.0%}", ", ".join(offenders[:5]))]


_TABLE_DELIM_RE = re.compile(
    r"^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)+\|?\s*$", re.M)


def check_missing_tables(docs: list[dict]) -> list[CheckResult]:
    """docs flagged has_tables=True but with zero markdown tables extracted.
    A table is a delimiter row (``|---|---|``) — a stray "|" in prose, or a
    shell command, is not evidence that a table survived."""
    missing = [d["doc_id"] for d in docs
               if d.get("has_tables") and not _TABLE_DELIM_RE.search(_text(d))]
    return [ok("tables_recovered", "parsed", "all flagged tables present",
               "table docs have a |---| row") if not missing else
            bad("tables_recovered", "parsed", "warn",
                _plural(len(missing), "missing table"),
                "table docs have a |---| row", ", ".join(missing[:8]))]


def check_reading_order(docs: list[dict], max_jump_frac: float = 0.30,
                        min_line_chars: int = 40) -> list[CheckResult]:
    """docs: [{"doc_id", "text"}]. Warn-level heuristic for column
    interleaving: a substantial line (>= min_line_chars) that ends
    mid-sentence — no terminal punctuation — followed by a line opening
    with a capital or digit suggests the extractor jumped between
    regions. Wrapped prose continues lowercase and doesn't trip this;
    two-column output alternates capitals every line."""
    suspects = []
    for d in docs:
        lines = [ln.strip() for ln in _text(d).splitlines()
                 if ln.strip()]
        pairs = jumps = 0
        for a, b in zip(lines, lines[1:]):
            if len(a) < min_line_chars:
                continue
            pairs += 1
            if not a.endswith((".", "!", "?", ":", ";", '"', "'", "”", ")")) \
                    and (b[0].isupper() or b[0].isdigit()):
                jumps += 1
        if pairs >= 3 and jumps / pairs > max_jump_frac:
            suspects.append(f"{d['doc_id']}:{jumps}/{pairs} jumps")
    return [ok("reading_order", "parsed", "0 suspects",
               f"jump frac <= {max_jump_frac:.0%}") if not suspects else
            bad("reading_order", "parsed", "warn",
                _plural(len(suspects), "suspect doc"),
                f"jump frac <= {max_jump_frac:.0%}",
                ", ".join(suspects[:5]))]


# ---------------------------------------------------------------------------
# Stage 3 — cleaned-output checks
# ---------------------------------------------------------------------------

BANNED_PATTERNS = {
    "page_marker": re.compile(r"\[PAGE \d+\]|^\s*-\s*\d+\s*-\s*$", re.M),
    "mojibake_marker": re.compile(MOJIBAKE_RE.pattern + "|\ufffd"),
    # RFC 3676 signature delimiter ("-- " alone on a line), then a line with
    # an address — any TLD, so name@kestrel.example counts.
    "email_signature": re.compile(r"^--[ \t]*\n.*@\S+\.\w+", re.M),
}


def check_banned_patterns(docs: list[dict]) -> list[CheckResult]:
    hits = []
    for d in docs:
        text = _text(d)
        for pname, pat in BANNED_PATTERNS.items():
            n = len(pat.findall(text))
            if n:
                hits.append(f"{d['doc_id']}:{pname}x{n}")
    return [ok("banned_patterns", "cleaned", "0 hits", "0 hits") if not hits else
            bad("banned_patterns", "cleaned", "warn",
                _plural(len(hits), "hit"), "0 hits", ", ".join(hits[:8]))]


def check_change_magnitude(pairs: list[dict],
                           min_kept_frac: float = 0.50,
                           max_kept_frac: float = 1.10) -> list[CheckResult]:
    """pairs: [{"doc_id", "before", "after"}]. kept = len(after)/len(before)
    must stay inside [min_kept_frac, max_kept_frac]: below the floor the
    cleaner deleted content; above the ceiling it *added* text (injected
    boilerplate, duplicated signatures) — both are smells."""
    offenders = []
    for p in pairs:
        before, after = p["before"], p["after"]
        if not before:
            continue
        kept = len(after) / len(before)
        if kept < min_kept_frac or kept > max_kept_frac:
            offenders.append(f"{p['doc_id']}:kept {kept:.0%}")
    return [ok("cleaning_magnitude", "cleaned", "all within bounds",
               f"kept {min_kept_frac:.0%}-{max_kept_frac:.0%}")
            if not offenders else
            bad("cleaning_magnitude", "cleaned", "fail",
                _plural(len(offenders), "outlier"),
                f"kept {min_kept_frac:.0%}-{max_kept_frac:.0%}",
                ", ".join(offenders[:8]))]


def check_idempotent(clean_fn, texts: list[str]) -> list[CheckResult]:
    """Running the cleaner twice must change nothing the second time."""
    bad_docs = []
    for i, t in enumerate(texts):
        once, twice = clean_fn(t), clean_fn(clean_fn(t))
        if once != twice:
            bad_docs.append(f"doc{i}")
    return [ok("cleaning_idempotent", "cleaned", "0 violations",
               "clean(clean(x)) == clean(x)") if not bad_docs else
            bad("cleaning_idempotent", "cleaned", "fail",
                _plural(len(bad_docs), "violation"),
                "clean(clean(x)) == clean(x)", ", ".join(bad_docs[:8]))]


def _luhn_ok(digits: str) -> bool:
    """Luhn checksum — what separates a card number from any 16-digit ID."""
    total = 0
    for i, ch in enumerate(reversed(digits)):
        d = int(ch)
        if i % 2:
            d = d * 2 - 9 if d > 4 else d * 2
        total += d
    return total % 10 == 0


_EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
# UK numbers: +44 or a leading 0, then ten digits in any of the usual
# groupings (07700 900123, 020 7946 0958, +44 7700 900123, 0117 496 0123).
_UK_PHONE_RE = re.compile(r"(?<![\w+])(?:\+44|0)(?:[ -]?\d){10}(?!\d)")
_CARD_RE = re.compile(r"(?<!\d)\d(?:[ -]?\d){12,18}(?!\d)")


def _card_hits(text: str) -> int:
    """13-19 digit runs (spaces/dashes allowed) that pass the Luhn check."""
    n = 0
    for m in _CARD_RE.finditer(text):
        digits = re.sub(r"\D", "", m.group(0))
        if 13 <= len(digits) <= 19 and _luhn_ok(digits):
            n += 1
    return n


def check_pii_scan(docs: list[dict]) -> list[CheckResult]:
    """Counts PII-pattern hits WITHOUT recording the values themselves.
    A regex sweep is a tripwire, not a compliance guarantee: it finds shapes
    (an address, a UK phone number, a Luhn-valid card number), never names,
    street addresses or free-text IDs."""
    hits = []
    for d in docs:
        text = _text(d)
        counts = {
            "email": len(_EMAIL_RE.findall(text)),
            "uk_phone": len(_UK_PHONE_RE.findall(text)),
            "card_like": _card_hits(text),
        }
        for pname, n in counts.items():
            if n:
                hits.append(f"{d['doc_id']}:{pname}x{n}")
    return [ok("pii_scan", "cleaned", "0 hits", "0 hits") if not hits else
            bad("pii_scan", "cleaned", "warn",
                f"{_plural(len(hits), 'hit')} (values not logged)",
                "0 hits", ", ".join(hits[:8]))]


# ---------------------------------------------------------------------------
# Stage 4 — chunk checks
# ---------------------------------------------------------------------------

def check_chunk_sizes(chunks: list[dict],
                      min_chars: int = 200, max_chars: int = 2400) -> list[CheckResult]:
    sizes = [len(_text(c)) for c in chunks]
    if not sizes:
        return [bad("chunk_sizes", "chunked", "fail", "0 chunks", ">= 1 chunk")]
    small = sum(1 for s in sizes if s < min_chars)
    big = sum(1 for s in sizes if s > max_chars)
    measured = f"min {min(sizes)}, p50 {int(statistics.median(sizes))}, max {max(sizes)}"
    detail = (f"{_plural(small, 'chunk')} below {min_chars} chars, "
              f"{_plural(big, 'chunk')} above {max_chars} chars")
    return [ok("chunk_sizes", "chunked", measured, f"{min_chars}-{max_chars} chars", detail)
            if not (small or big) else
            bad("chunk_sizes", "chunked", "warn", measured,
                f"{min_chars}-{max_chars} chars", detail)]


def check_chunk_uniqueness(chunks: list[dict]) -> list[CheckResult]:
    """Empty chunks and exact duplicates (after whitespace normalization)."""
    seen: dict[str, int] = {}
    empty = 0
    for c in chunks:
        norm = " ".join(_text(c).split())
        if not norm:
            empty += 1
            continue
        seen[norm] = seen.get(norm, 0) + 1
    dupes = sum(n - 1 for n in seen.values() if n > 1)
    problems = empty + dupes
    return [ok("chunk_uniqueness", "chunked", "0 empty chunks, 0 duplicates",
               "0 empty chunks, 0 duplicates") if not problems else
            bad("chunk_uniqueness", "chunked", "warn",
                f"{_plural(empty, 'empty chunk')}, "
                f"{_plural(dupes, 'duplicate chunk')}",
                "0 empty chunks, 0 duplicates")]


def check_chunk_coverage(chunks: list[dict], doc_lengths: dict[str, int],
                         max_gap: int = 200) -> list[CheckResult]:
    """chunks: [{"doc_id","char_start","char_end"}]. Every part of the source
    should be covered by some chunk; gaps mean silently dropped content."""
    by_doc: dict[str, list[tuple[int, int]]] = {}
    for c in chunks:
        by_doc.setdefault(c["doc_id"], []).append((c["char_start"], c["char_end"]))
    gaps = []
    for doc_id, length in doc_lengths.items():
        spans = sorted(by_doc.get(doc_id, []))
        if not spans and length > 0:
            # A document with no chunks at all is dropped content, however
            # short — the max_gap tolerance below must not excuse it.
            gaps.append(f"{doc_id}:no chunks")
            continue
        pos = 0
        for start, end in spans:
            if start < 0 or end > length:
                gaps.append(f"{doc_id}:offsets outside 0-{length}")
            if start - pos > max_gap:
                gaps.append(f"{doc_id}@{pos}-{start}")
            pos = max(pos, end)
        if length - pos > max_gap:
            gaps.append(f"{doc_id}@{pos}-{length}")
    return [ok("chunk_coverage", "chunked", "0 gaps", f"gaps <= {max_gap} chars")
            if not gaps else
            bad("chunk_coverage", "chunked", "fail",
                _plural(len(gaps), "gap"),
                f"gaps <= {max_gap} chars", ", ".join(gaps[:6]))]


def check_orphan_chunks(chunks: list[dict],
                        doc_lengths: dict[str, int]) -> list[CheckResult]:
    """chunks whose doc_id has no entry in doc_lengths — the chunker
    emitted a chunk for a document the manifest doesn't know about: a
    stale manifest, a deleted-then-reprocessed doc, or a bad join
    upstream. Warn-level: bounded and quarantinable, but it means the
    coverage accounting can't see this text."""
    orphans = sorted({c["doc_id"] for c in chunks} - set(doc_lengths))
    return [ok("orphan_chunks", "chunked", "0 orphans", "0 orphans")
            if not orphans else
            bad("orphan_chunks", "chunked", "warn",
                _plural(len(orphans), "orphan doc"), "0 orphans",
                ", ".join(orphans[:6]))]


def check_overlap_sanity(chunks: list[dict],
                         max_overlap_frac: float = 0.5) -> list[CheckResult]:
    """Per-doc duplicated-span fraction: 1 - union(spans)/sum(spans).
    The chunker's configured overlap is legitimately ~5-20%; beyond that
    the same text is embedded repeatedly — wasted spend and top-k
    flooding. Warn-level: the right bound depends on your chunker's
    configured overlap, so derive it from the profile."""
    by_doc: dict[str, list[tuple[int, int]]] = {}
    for c in chunks:
        by_doc.setdefault(c["doc_id"], []).append(
            (c["char_start"], c["char_end"]))
    worst, offenders = 0.0, []
    for doc_id, spans in by_doc.items():
        if len(spans) < 2:
            continue
        spans = sorted(spans)
        total = sum(e - s for s, e in spans)
        if total <= 0:
            continue
        union, cur_s, cur_e = 0, spans[0][0], spans[0][1]
        for s, e in spans[1:]:
            if s <= cur_e:
                cur_e = max(cur_e, e)
            else:
                union += cur_e - cur_s
                cur_s, cur_e = s, e
        union += cur_e - cur_s
        frac = 1 - union / total
        worst = max(worst, frac)
        if frac > max_overlap_frac:
            offenders.append(f"{doc_id}:{frac:.0%}")
    return [ok("overlap_sanity", "chunked", f"worst {worst:.0%}",
               f"<= {max_overlap_frac:.0%}") if not offenders else
            bad("overlap_sanity", "chunked", "warn", f"worst {worst:.0%}",
                f"<= {max_overlap_frac:.0%}", ", ".join(offenders[:5]))]


def check_mid_word_splits(chunks: list[dict],
                          max_frac: float = 0.05) -> list[CheckResult]:
    """Heuristic: a chunk ending in an alphanumeric char followed by a chunk
    starting with one suggests a mid-word split (unless whitespace sits at
    the boundary in the source — we can't see it, so this is a warn)."""
    by_doc: dict[str, list[dict]] = {}
    for c in chunks:
        by_doc.setdefault(c["doc_id"], []).append(c)
    suspects, total = [], 0
    for doc_id, cs in by_doc.items():
        cs.sort(key=lambda c: c.get("index", 0))
        for a, b in zip(cs, cs[1:]):
            total += 1
            ta, tb = a.get("text", ""), b.get("text", "")
            # Only for scripts that put spaces between words: in Chinese or
            # Japanese every boundary is "letter | letter" and would all look
            # like mid-word splits.
            if not (ta and tb and ord(ta[-1]) < 0x0250 and ord(tb[0]) < 0x0250):
                total -= 1
                continue
            if ta[-1].isalnum() and tb[0].isalnum():
                suspects.append(f"{doc_id}#{a.get('index')}→{b.get('index')}")
    frac = len(suspects) / max(total, 1)
    return [ok("mid_word_splits", "chunked", f"{frac:.0%} suspect boundaries",
               f"<= {max_frac:.0%}") if frac <= max_frac else
            bad("mid_word_splits", "chunked", "warn", f"{frac:.0%} suspect boundaries",
                f"<= {max_frac:.0%}", ", ".join(suspects[:5]))]


def check_chunk_links(chunks: list[dict]) -> list[CheckResult]:
    """prev_id/next_id pointers must resolve to a chunk of the SAME document.
    (Dangling and cross-document pointers are what this catches; it does
    not verify that prev/next are mirror images of each other.)"""
    by_doc: dict[str, list[dict]] = {}
    for c in chunks:
        by_doc.setdefault(c["doc_id"], []).append(c)
    broken = []
    for doc_id, cs in by_doc.items():
        ids = {c["chunk_id"] for c in cs}
        for c in cs:
            if c.get("prev_id") and c["prev_id"] not in ids:
                broken.append(f"{c['chunk_id']}:prev")
            if c.get("next_id") and c["next_id"] not in ids:
                broken.append(f"{c['chunk_id']}:next")
    return [ok("chunk_links", "chunked", "0 broken pointers",
               "prev/next resolve") if not broken else
            bad("chunk_links", "chunked", "warn",
                _plural(len(broken), "broken link"),
                "prev/next resolve", ", ".join(broken[:6]))]


# ---------------------------------------------------------------------------
# Stage 5 — enriched (metadata) checks
# ---------------------------------------------------------------------------

def _is_blank(v) -> bool:
    """None, empty/whitespace-only string, or empty container. 0 and False
    are real values."""
    return v is None or (isinstance(v, str) and not v.strip()) or v == [] or v == {}


def check_required_fields(records: list[dict], required: list[str],
                          max_null_frac: float = 0.02) -> list[CheckResult]:
    """Null-rate check per required field."""
    offenders = []
    n = max(len(records), 1)
    for field_name in required:
        missing = sum(1 for r in records if _is_blank(r.get(field_name)))
        frac = missing / n
        if frac > max_null_frac:
            offenders.append(f"{field_name}:{frac:.0%} null")
    return [ok("required_fields", "enriched", "all under threshold",
               f"null <= {max_null_frac:.0%}") if not offenders else
            bad("required_fields", "enriched", "warn",
                _plural(len(offenders), "field") + " over",
                f"null <= {max_null_frac:.0%}", ", ".join(offenders))]


def check_enum_fields(records: list[dict],
                      allowed: dict[str, set]) -> list[CheckResult]:
    """allowed: {field: {values}}. Flags values outside the enum — usually
    means an LLM tagger invented a category."""
    offenders = []
    for r in records:
        for fname, values in allowed.items():
            v = r.get(fname)
            try:
                invalid = v is not None and v not in values
            except TypeError:           # unhashable (a list or dict where a string belongs)
                invalid = True
            if invalid:
                offenders.append(f"{r.get('chunk_id', '?')}:{fname}={v!r}")
    return [ok("enum_fields", "enriched", "0 invalid", "all values in enum")
            if not offenders else
            bad("enum_fields", "enriched", "warn",
                _plural(len(offenders), "invalid value"),
                "all values in enum", ", ".join(offenders[:6]))]


def check_vocabulary_drift(records: list[dict], field_name: str,
                           reference_vocab: set[str],
                           max_new_frac: float = 0.20) -> list[CheckResult]:
    """Tags the LLM produced that aren't in the controlled vocabulary."""
    vocab: set[str] = set()
    for r in records:
        tags = r.get(field_name) or []
        if isinstance(tags, str):
            tags = [tags]
        vocab.update(t for t in tags if t)
    new_tags = vocab - reference_vocab
    frac = len(new_tags) / max(len(vocab), 1)
    return [ok("vocabulary_drift", "enriched", f"{frac:.0%} new tags",
               f"<= {max_new_frac:.0%}", f"new: {sorted(new_tags)[:5]}")
            if frac <= max_new_frac else
            bad("vocabulary_drift", "enriched", "warn", f"{frac:.0%} new tags",
                f"<= {max_new_frac:.0%}", f"new: {sorted(new_tags)[:5]}")]


# ---------------------------------------------------------------------------
# Stage 6 — index checks (preview of Module 06; vectors are plain lists)
# ---------------------------------------------------------------------------

def check_count_parity(n_chunks: int, n_vectors: int) -> list[CheckResult]:
    return [ok("count_parity", "indexed",
               f"{_plural(n_chunks, 'chunk')} = {_plural(n_vectors, 'vector')}",
               "equal") if n_chunks == n_vectors else
            bad("count_parity", "indexed", "fail",
                f"{_plural(n_chunks, 'chunk')} vs {_plural(n_vectors, 'vector')}",
                "equal")]


def _usd(x: float) -> str:
    """Compact dollar formatting: $0.00002, not $0.0000 or $0.000020."""
    return f"${f'{x:,.6f}'.rstrip('0').rstrip('.')}"


def check_cost_projection(est_tokens: int, price_per_1m_tokens: float,
                          budget_usd: float) -> list[CheckResult]:
    """Embedding-cost projection vs budget — an 'info'-tier check: a trend
    metric recorded in the report, never a gate. Going over budget is
    worth seeing; it isn't a correctness defect."""
    cost = est_tokens / 1_000_000 * price_per_1m_tokens
    return [CheckResult(
        "cost_projection", "indexed", cost <= budget_usd, "info",
        f"{_usd(cost)} for ~{est_tokens:,} tokens",
        f"<= {_usd(budget_usd)}",
        "info-tier: budget trend, does not affect the verdict")]


def check_vector_sanity(vectors: list[list[float]],
                        expected_dim: int | None = None) -> list[CheckResult]:
    """Two separate questions: are all dims *equal* (always checked), and
    do they equal expected_dim (only when given)? expected_dim=None still
    catches mixed dims — it just can't catch wrong-but-uniform dims."""
    results = []
    dims = {len(v) for v in vectors}
    if len(dims) > 1:
        results.append(bad("vector_dims", "indexed", "fail",
                           f"dims {sorted(dims)}", "all equal"))
    elif expected_dim is not None and dims != {expected_dim}:
        results.append(bad("vector_dims", "indexed", "fail",
                           f"dims {sorted(dims)}", f"all {expected_dim}"))
    else:
        expected = (f"all {expected_dim}" if expected_dim is not None
                    else "consistent")
        results.append(ok("vector_dims", "indexed",
                          f"dims {sorted(dims)}", expected))
    zero = sum(1 for v in vectors if all(x == 0.0 for x in v))
    nan = sum(1 for v in vectors if any(not math.isfinite(x) for x in v))  # NaN or +-inf
    results.append(ok("no_dead_vectors", "indexed",
                      f"{zero} zero, {nan} NaN/inf", "0 zero, 0 NaN/inf")
                   if not (zero or nan) else
                   bad("no_dead_vectors", "indexed", "fail",
                       f"{zero} zero, {nan} NaN/inf", "0 zero, 0 NaN/inf"))
    return results


def check_duplicate_vectors(vectors: list[list[float]]) -> list[CheckResult]:
    hashes = [hashlib.sha256(
        ",".join(f"{x:.6f}" for x in v).encode()).hexdigest()[:16] for v in vectors]
    dupes = len(hashes) - len(set(hashes))
    return [ok("no_duplicate_vectors", "indexed",
               _plural(dupes, "duplicate"), "0 duplicates") if not dupes else
            bad("no_duplicate_vectors", "indexed", "warn",
                _plural(dupes, "duplicate"), "0 duplicates")]


def check_model_consistency(vector_meta: list[dict]) -> list[CheckResult]:
    """vector_meta: [{"model_id", ...}]. Mixing embedding models in one index
    silently corrupts similarity."""
    models = {m.get("model_id") for m in vector_meta}
    if None in models or "" in models:
        missing = sum(1 for m in vector_meta if not m.get("model_id"))
        return [bad("single_embedding_model", "indexed", "fail",
                    _plural(missing, "vector") + " with no model_id",
                    "1 model id")]
    return [ok("single_embedding_model", "indexed",
               _plural(len(models), "model id"), "1 model id")
            if len(models) == 1 else
            bad("single_embedding_model", "indexed", "fail",
                f"{sorted(models)}", "1 model id")]


# ---------------------------------------------------------------------------
# Stage 7 — served-side checks
# ---------------------------------------------------------------------------

def check_freshness(records: list[dict], now: datetime,
                    sla_hours: float = 24.0) -> list[CheckResult]:
    """records: [{"source", "last_synced_at" (ISO str or None)}]. Naive
    timestamps are treated as UTC; a naive `now` is normalized the same
    way, so mixed offset-aware and naive inputs can't crash the check."""
    if now.tzinfo is None:
        now = now.replace(tzinfo=timezone.utc)
    stale = []
    for r in records:
        ts = r.get("last_synced_at")
        if ts is None:
            stale.append(f"{r['source']}:never")
            continue
        try:
            dt = ts if isinstance(ts, datetime) else datetime.fromisoformat(
                str(ts).replace("Z", "+00:00"))
        except ValueError:
            stale.append(f"{r['source']}:unparseable")   # a bad timestamp is a finding, not a crash
            continue
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        lag_h = (now - dt).total_seconds() / 3600
        if lag_h > sla_hours:
            stale.append(f"{r['source']}:{lag_h:.0f}h")
    return [ok("freshness_sla", "served", "all sources within SLA",
               f"<= {sla_hours}h") if not stale else
            bad("freshness_sla", "served", "warn",
                _plural(len(stale), "stale source"),
                f"<= {sla_hours}h", ", ".join(stale[:6]))]


def check_orphan_records(index_ids: set[str], source_ids: set[str]) -> list[CheckResult]:
    """Records still in the index whose source document is gone — the
    deletion-propagation check."""
    orphans = index_ids - source_ids
    return [ok("no_orphan_records", "served", "0 orphans", "0 orphans")
            if not orphans else
            bad("no_orphan_records", "served", "fail",
                _plural(len(orphans), "orphan"), "0 orphans",
                ", ".join(sorted(orphans)[:6]))]


def check_acl_coverage(records: list[dict]) -> list[CheckResult]:
    """Every served record must carry tenant + non-empty ACL, or it is
    either unservable or leaks across tenants."""
    bad_recs = [r.get("chunk_id", "?") for r in records
                if not r.get("tenant_id") or not r.get("acl")]
    return [ok("acl_coverage", "served", "all records ACL'd",
               "tenant_id + acl present") if not bad_recs else
            bad("acl_coverage", "served", "fail",
                _plural(len(bad_recs), "uncovered record"),
                "tenant_id + acl present", ", ".join(bad_recs[:6]))]


# ---------------------------------------------------------------------------
# Quality gate — roll check results up into a verdict
# ---------------------------------------------------------------------------

def _reason(label: str, r: CheckResult) -> str:
    """One reason line. ``detail`` (which file, which doc, which chunk) is
    what the person reading the report needs to act, so it goes in."""
    line = f"{label} {r.name} ({r.stage}): {r.measured} vs {r.expected}"
    return f"{line} — {r.detail}" if r.detail else line


def _cell(value: str) -> str:
    """Make a value safe inside a Markdown table cell."""
    return str(value).replace("|", "\\|").replace("\n", " ")


def gate(results: list[CheckResult]) -> GateResult:
    """Roll check results into a verdict: any fail -> fail; else any warn ->
    warn; else pass. 'info'-severity failures are recorded in the reasons
    but never affect the verdict — they are trends, not gates. An EMPTY
    result list is a fail: a gate that ran nothing must not wave data through."""
    fails = [r for r in results if r.outcome == "fail"]
    warns = [r for r in results if r.outcome == "warn"]
    infos = [r for r in results if r.outcome == "info"]
    reasons = [_reason("FAIL", r) for r in fails]
    reasons += [_reason("WARN", r) for r in warns]
    reasons += [_reason("INFO", r) for r in infos]
    verdict = "fail" if fails else ("warn" if warns else "pass")
    if not results:
        # A gate that ran no checks has verified nothing — never "pass".
        verdict = "fail"
        reasons.insert(0, "FAIL no checks ran: an empty result list is not a pass")
    return GateResult(verdict=verdict, reasons=reasons, results=results)


def render_report(run_name: str, g: GateResult,
                  extra_sections: list[tuple[str, str]] | None = None) -> str:
    """A compact Markdown quality report."""
    lines = [f"# Data quality report — {run_name}", ""]
    counts = g.counts
    parts = [f"{counts['pass']} pass"]
    if counts["info"]:
        parts.append(f"{counts['info']} info")
    parts += [f"{counts['warn']} warn", f"{counts['fail']} fail"]
    lines.append(f"**Verdict: {g.verdict.upper()}** ({', '.join(parts)})")
    lines.append("")
    lines.append("| Check | Stage | Outcome | Measured | Expected |")
    lines.append("|---|---|---|---|---|")
    for r in g.results:
        lines.append(f"| {_cell(r.name)} | {r.stage} | {r.outcome} | "
                     f"{_cell(r.measured)} | {_cell(r.expected)} |")
    if g.reasons:
        lines += ["", "## Reasons", ""]
        lines += [f"- {x}" for x in g.reasons]
    for title, body in extra_sections or []:
        lines += ["", f"## {title}", "", body]
    return "\n".join(lines)

12.3 profiling.py — corpus profiling#

python
"""profiling.py — corpus profiling for data-quality reports.

Pure standard library. Produces the numbers a data-quality dashboard shows:
length distributions, character-class histograms, script/language mix,
duplicate rates, rough token estimates and per-source breakdowns.
"""

from __future__ import annotations

import hashlib
import statistics
from collections import Counter

from dq import script_class


def _char_classes(text: str) -> Counter:
    """Histogram of character classes. 'letter', 'digit', 'space',
    'punct', 'symbol', 'other' — enough to spot OCR noise and encoding
    damage at a glance."""
    counts = Counter()
    for ch in text:
        if ch.isspace():
            counts["space"] += 1
        elif ch.isalpha():
            counts["letter"] += 1
        elif ch.isdigit():
            counts["digit"] += 1
        elif ch.isalnum():          # e.g. CJK ideographs count as alnum
            counts["letter"] += 1
        elif ch in ".,;:!?()[]{}'\"-–—/\\|@#$%^&*+=<>`~":
            counts["punct"] += 1
        else:
            counts["other"] += 1
    return counts


def _percentile(sorted_vals: list[int], p: float) -> int:
    if not sorted_vals:
        return 0
    k = (len(sorted_vals) - 1) * p
    lo, hi = int(k), min(int(k) + 1, len(sorted_vals) - 1)
    frac = k - lo
    return int(sorted_vals[lo] + (sorted_vals[hi] - sorted_vals[lo]) * frac)


def profile_corpus(docs: list[dict]) -> dict:
    """docs: [{"doc_id", "source", "text"}]. Returns a stats dict."""
    lengths = sorted(len((d.get("text") or "")) for d in docs)

    # character-class histogram across the whole corpus
    classes = Counter()
    for d in docs:
        classes.update(_char_classes((d.get("text") or "")))
    total_chars = sum(classes.values()) or 1

    # script mix (per-document dominant script)
    scripts = Counter(script_class((d.get("text") or "")) for d in docs)

    # exact duplicates by content hash
    hashes = Counter(
        hashlib.sha256((d.get("text") or "").encode("utf-8", "replace")).hexdigest()[:16]
        for d in docs
    )
    dup_files = sum(c - 1 for c in hashes.values() if c > 1)

    # rough token estimate: ~4 chars/token for English (rule of thumb,
    # see lesson 02.2 — real tokenizers differ per language and model)
    total_chars_all = sum(lengths)

    # per-source breakdown
    per_source: dict[str, dict] = {}
    for d in docs:
        s = per_source.setdefault(d.get("source", "?"),
                                  {"docs": 0, "chars": 0})
        s["docs"] += 1
        s["chars"] += len((d.get("text") or ""))

    return {
        "n_docs": len(docs),
        "total_chars": total_chars_all,
        "length_min": lengths[0] if lengths else 0,
        "length_p50": _percentile(lengths, 0.50),
        "length_p95": _percentile(lengths, 0.95),
        "length_max": lengths[-1] if lengths else 0,
        "mean_chars": int(statistics.fmean(lengths)) if lengths else 0,
        "est_tokens": total_chars_all // 4,
        "char_classes": {k: round(v / total_chars, 4)
                         for k, v in classes.most_common()},
        "scripts": dict(scripts),
        "duplicate_files": dup_files,
        "per_source": per_source,
    }


def render_profile(stats: dict) -> str:
    """Markdown rendering of a profile — what a report generator emits."""
    lines = [
        f"- Documents: **{stats['n_docs']}** "
        f"({stats['total_chars']:,} chars, ~{stats['est_tokens']:,} tokens "
        f"at ~4 chars/token)",
        f"- Lengths (chars): min {stats['length_min']:,}, "
        f"median {stats['length_p50']:,}, p95 {stats['length_p95']:,}, "
        f"max {stats['length_max']:,} (mean {stats['mean_chars']:,})",
        f"- Character classes: "
        + ", ".join(f"{k} {v:.1%}" for k, v in stats["char_classes"].items()),
        f"- Dominant scripts: "
        + ", ".join(f"{k} {v}" for k, v in sorted(stats["scripts"].items())),
        f"- Exact duplicates: {stats['duplicate_files']}",
        "",
        "| Source | Docs | Chars |",
        "|---|---|---|",
    ]
    for src, s in sorted(stats["per_source"].items()):
        lines.append(f"| {src} | {s['docs']} | {s['chars']:,} |")
    return "\n".join(lines)

12.4 golden.py — golden sets and sampling#

python
"""golden.py + sampling helpers — golden-set regression tests and
statistical sampling for human review.

Standard library only.
"""

from __future__ import annotations

import math
import random
from difflib import SequenceMatcher
from statistics import NormalDist

from dq import CheckResult, ok, bad


# ---------------------------------------------------------------------------
# Golden sets: parser regression tests
# ---------------------------------------------------------------------------

def golden_compare(expected: dict[str, str], actual: dict[str, str],
                   tolerance: float = 0.98) -> list[CheckResult]:
    """expected/actual: {doc_id: extracted_text}. Compares WORD sequences with
    a similarity ratio, so cosmetic differences (whitespace, line wrapping)
    don't fail the build while real parser regressions (dropped sentences,
    dropped columns) do.

    Two things that matter at real document sizes: ``autojunk=False`` — with
    the default, difflib treats every frequent character or word as "junk"
    once a sequence passes ~200 items, and a one-word edit to a 5,000-character
    page can score ~0.1 — and words rather than characters, because character
    matching is quadratic (a 90,000-character page took ~45 s in testing)."""
    results = []
    for doc_id, exp in expected.items():
        act = actual.get(doc_id)
        if act is None:
            results.append(bad(f"golden:{doc_id}", "golden", "fail",
                               "missing", "present",
                               "document produced no output"))
            continue
        ratio = SequenceMatcher(None, exp.split(), act.split(),
                                autojunk=False).ratio()
        results.append(ok(f"golden:{doc_id}", "golden",
                          f"similarity {ratio:.3f}", f">= {tolerance}")
                       if ratio >= tolerance else
                       bad(f"golden:{doc_id}", "golden", "fail",
                           f"similarity {ratio:.3f}", f">= {tolerance}"))
    extra = set(actual) - set(expected)
    if extra:
        n = len(extra)
        results.append(bad("golden:unexpected_docs", "golden", "warn",
                           f"{n} extra output{'s' if n != 1 else ''}", "0",
                           ", ".join(sorted(extra)[:5])))
    return results


# ---------------------------------------------------------------------------
# Sampling: how many documents a human should eyeball
# ---------------------------------------------------------------------------

def sample_size(population: int, confidence: float = 0.95,
                margin: float = 0.05, worst_case: bool = True) -> int:
    """Sample size for estimating a proportion (e.g. 'fraction of docs with
    parse errors') with a given margin of error, plus finite-population
    correction. worst_case=True uses p=0.5 (largest possible n).

    `confidence` is any value in (0, 1); z is the two-sided normal quantile,
    so 0.90 / 0.95 / 0.99 give the classic 1.645 / 1.96 / 2.576."""
    if not 0 < confidence < 1:
        raise ValueError("confidence must be in (0, 1)")
    if not 0 < margin < 1:
        raise ValueError("margin must be in (0, 1)")
    if population <= 0:
        return 0
    z = NormalDist().inv_cdf(1 - (1 - confidence) / 2)
    p = 0.5 if worst_case else 0.1
    n0 = (z ** 2) * p * (1 - p) / (margin ** 2)
    n = n0 / (1 + (n0 - 1) / population)
    return min(math.ceil(n), population)


def stratified_sample(docs: list[dict], n: int, seed: int = 7) -> dict[str, list[str]]:
    """Proportional allocation across strata (here: doc source/type), by the
    largest-remainder method, so exactly ``min(n, len(docs))`` documents are
    drawn. Every non-empty stratum gets at least one when ``n`` allows: a rare
    document type (the 1-in-200 contract) must not round down to zero reviews.
    Returns {stratum: [doc_ids]}. Deterministic for a given seed."""
    strata: dict[str, list[str]] = {}
    for d in docs:
        strata.setdefault(d.get("stratum", "misc"), []).append(d["doc_id"])
    total = len(docs)
    n = max(0, min(n, total))
    keys = sorted(strata)
    quota = {k: n * len(strata[k]) / total for k in keys} if total else {}
    take = {k: int(quota[k]) for k in keys}
    if n >= len(keys):
        take = {k: max(1, take[k]) for k in keys}          # no stratum left out
    # Over-allocated by the minimum-one rule? Trim the biggest strata first.
    while sum(take.values()) > n:
        k = max(keys, key=lambda x: (take[x] - quota[x], take[x]))
        take[k] -= 1
    # Hand out what is left by largest fractional remainder, within stratum size.
    while sum(take.values()) < n:
        open_keys = [k for k in keys if take[k] < len(strata[k])]
        k = max(open_keys, key=lambda x: (quota[x] - take[x], len(strata[x])))
        take[k] += 1
    rng = random.Random(seed)
    out: dict[str, list[str]] = {}
    for key in keys:
        pool = sorted(strata[key])
        rng.shuffle(pool)
        out[key] = sorted(pool[:take[key]])
    return out

12.5 demo.py — the toy corpus and the run#

python
"""demo.py — run the whole quality suite on a toy Kestrel Works corpus
with planted defects, and print real output.

Standard library only.
"""

import hashlib
from datetime import datetime, timezone

from dq import (
    check_file_inventory, check_duplicate_hashes, check_language_mix,
    check_file_formats, check_file_readability,
    check_garbage_ratio, check_empty_extractions, check_chars_per_page,
    check_repeated_lines, check_missing_tables, check_reading_order,
    check_banned_patterns, check_change_magnitude, check_idempotent,
    check_pii_scan,
    check_chunk_sizes, check_chunk_uniqueness, check_chunk_coverage,
    check_orphan_chunks, check_overlap_sanity,
    check_mid_word_splits, check_chunk_links,
    check_required_fields, check_enum_fields, check_vocabulary_drift,
    check_count_parity, check_cost_projection, check_vector_sanity,
    check_duplicate_vectors, check_model_consistency,
    check_freshness, check_orphan_records, check_acl_coverage,
    gate, render_report,
)
from profiling import profile_corpus, render_profile
from golden import golden_compare, sample_size, stratified_sample

NOW = datetime(2026, 11, 5, 12, 0, 0, tzinfo=timezone.utc)


def h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()[:16]


def clean_whitespace(text: str) -> str:
    """Toy stand-in for 05.5's cleaner: collapse runs of whitespace and
    strip line edges. Deliberately idempotent — clean(clean(x)) == clean(x)."""
    return "\n".join(" ".join(ln.split()) for ln in text.strip().splitlines())


# --------------------------------------------------------------------------
# Toy corpus: raw files, parsed docs, cleaned pairs, chunks, enriched
# records, vectors and served rows — each list carries planted defects.
# --------------------------------------------------------------------------

RAW_FILES = [
    {"path": "handbook.pdf", "bytes": 482_113, "sha256": h("handbook"),
     "content": b"%PDF-1.7\n1 0 obj<<>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF"},
    {"path": "help-centre/returns.html", "bytes": 18_204, "sha256": h("returns"),
     "content": b"<!doctype html><html><body><article>Returns policy: "
                b"unopened products may be returned within 30 days.</article>"
                b"</body></html>"},
    {"path": "contracts/msr-2026-014.pdf", "bytes": 96_440, "sha256": h("msr"),
     "content": b"%PDF-1.7\n2 0 obj<<>>endobj\ntrailer<</Root 2 0 R>>\n%%EOF"},
    # planted: password-protected PDF — parses to nothing downstream
    {"path": "contracts/board-pack.pdf", "bytes": 55_102, "sha256": h("boardpack"),
     "content": b"%PDF-1.7\n1 0 obj<</Type/Catalog/Encrypt 12 0 R>>endobj\n%%EOF"},
    # planted: truncated download — header OK, no %%EOF trailer
    {"path": "archive/legacy-scan.pdf", "bytes": 1_044_220, "sha256": h("legacyscan"),
     "content": b"%PDF-1.4\n% truncated transfer - connection dropped"},
    # planted: a video file in a document corpus (format allow-list bait)
    {"path": "media/walkthrough.mp4", "bytes": 4_194_304, "sha256": h("walkthrough"),
     "content": b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom"},
    {"path": "tickets/export-2026-10.jsonl", "bytes": 1_204_881, "sha256": h("tickets"),
     "content": b'{"ticket": 1042, "text": "pump housing cracked"}\n'
                b'{"ticket": 1043, "text": "invoice question"}\n'},
    {"path": "handbook-copy.pdf", "bytes": 482_113, "sha256": h("handbook"),
     "content": b"%PDF-1.7\n1 0 obj<<>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF"},  # dupe
    {"path": "notes-empty.txt", "bytes": 0, "sha256": h(""),
     "content": b""},                  # empty
]

ALLOWED_EXTS = {".pdf", ".html", ".jsonl", ".txt"}

DOCS = [
    {"doc_id": "handbook", "source": "pdf", "stratum": "handbook",
     "text": "# Kestrel Works Product Handbook\n\n## Warranty\n\nEvery Kestrel pump "
             "carries a two-year warranty covering manufacturing defects.\n\n"
             "## Returns\n\nCustomers may return an unopened product within "
             "30 days of delivery for a full refund.\n" * 3},
    {"doc_id": "returns-page", "source": "html", "stratum": "help-centre",
     "text": "Returns policy. Unopened products may be returned within 30 days. "
             "Opened pumps carry a two-year warranty instead. Refunds are issued "
             "to the original payment method within 5 business days. " * 4},
    {"doc_id": "msr-contract", "source": "pdf", "stratum": "contract",
     "text": "MASTER SERVICES AGREEMENT\n\n1. Definitions. \"Services\" means the "
             "managed retrieval services described in Schedule A. \"Client Data\" "
             "means data provided by Client.\n\n2. Term. This Agreement commences "
             "on 1 January 2026 and continues for 24 months.\n" * 5},
    {"doc_id": "ticket-1042", "source": "jsonl", "stratum": "ticket",
     "text": "Customer: Dana Whitfield\nOrder: KW-2026-0417\n\nMy Kestrel pump "
             "arrived this morning and the housing is cracked. The box looked "
             "fine but the pump will not turn on. Please advise on a replacement "
             "or refund under warranty.\n"},
    # planted defect: a scanned contract whose OCR layer is garbage
    {"doc_id": "scan-0099", "source": "pdf", "stratum": "contract",
     "text": "�Â�Â� contract Â\u00a0Â\u00a0Â\u00a0Â\u00a0Â\u00a0Â\u00a0terms not Â\u00a0legible Â\u00a0Â\u00a0Â\u00a0" * 20},
]

PARSED = [
    {"doc_id": "handbook", "text": DOCS[0]["text"], "pages": 3,
     "has_tables": False},
    {"doc_id": "returns-page", "text": DOCS[1]["text"], "pages": 1,
     "has_tables": False},
    {"doc_id": "msr-contract", "text": DOCS[2]["text"], "pages": 6,
     "has_tables": True},   # has tables flag but no '|' in text -> planted
    {"doc_id": "ticket-1042", "text": DOCS[3]["text"], "pages": 1,
     "has_tables": False},
    {"doc_id": "scan-0099", "text": DOCS[4]["text"], "pages": 2,
     "has_tables": False},
    {"doc_id": "empty-scan", "text": "   \n  ", "pages": 4,
     "has_tables": False},  # planted: OCR found nothing
    # planted: two-column leaflet whose lines alternate topics mid-sentence —
    # the signature of column interleaving
    {"doc_id": "promo-leaflet", "text":
     "The Kestrel KX-9 pump fits standard half-inch supply lines\n"
     "Orders over fifty pounds ship free within the continental US\n"
     "Every unit carries a two-year warranty on parts and labour\n"
     "Register online within thirty days to extend coverage to three years\n"
     "Ask about trade pricing for installers and property managers\n"
     "Most units leave our Ohio warehouse within two business days",
     "pages": 1, "has_tables": False},
]

CLEAN_PAIRS = [
    {"doc_id": "handbook", "before": DOCS[0]["text"],
     "after": DOCS[0]["text"].replace("\n\n", "\n")},          # fine
    {"doc_id": "msr-contract", "before": DOCS[2]["text"],
     "after": "[PAGE 1]\n" + DOCS[2]["text"][:200]},           # planted: over-cleaned
    {"doc_id": "ticket-1042", "before": DOCS[3]["text"],
     "after": DOCS[3]["text"] + "\n-- \nDana Whitfield, dana@kestrel.example"},  # PII + added text
]

CHUNKS = [
    # handbook: good chain
    {"chunk_id": "hb-000", "doc_id": "handbook", "index": 0,
     "text": "# Kestrel Works Product Handbook\n\n## Warranty\n\nEvery Kestrel pump carries a two-year warranty.",
     "char_start": 0, "char_end": 120, "prev_id": None, "next_id": "hb-001"},
    {"chunk_id": "hb-001", "doc_id": "handbook", "index": 1,
     "text": "warranty. covering manufacturing defects.\n\n## Returns\n\nCustomers may return an unopened product.",
     "char_start": 100, "char_end": 240, "prev_id": "hb-000", "next_id": "hb-002"},
    {"chunk_id": "hb-002", "doc_id": "handbook", "index": 2,
     "text": "unopened product. within 30 days of delivery for a full refund.",
     "char_start": 220, "char_end": 320, "prev_id": "hb-001", "next_id": None},
    # returns-page: planted mid-word split + coverage gap + duplicate chunk
    {"chunk_id": "rp-000", "doc_id": "returns-page", "index": 0,
     "text": "Returns policy. Unopened products may be retur",
     "char_start": 0, "char_end": 44, "prev_id": None, "next_id": "rp-001"},
    {"chunk_id": "rp-001", "doc_id": "returns-page", "index": 1,
     "text": "ned within 30 days. Opened pumps carry a two-year warranty instead.",
     "char_start": 44, "char_end": 120, "prev_id": "rp-000", "next_id": "rp-002"},
    {"chunk_id": "rp-002", "doc_id": "returns-page", "index": 2,
     "text": "warranty instead. Refunds are issued to the original payment method within 5 business days.",
     "char_start": 120, "char_end": 260, "prev_id": "rp-001", "next_id": "rp-999"},  # broken link
    {"chunk_id": "rp-003", "doc_id": "returns-page", "index": 3,
     "text": "warranty instead. Refunds are issued to the original payment method within 5 business days.",
     "char_start": 120, "char_end": 260, "prev_id": "rp-002", "next_id": None},
    # oversized chunk planted
    {"chunk_id": "msr-000", "doc_id": "msr-contract", "index": 0,
     "text": "MASTER SERVICES AGREEMENT " + "Definitions and terms. " * 200,
     "char_start": 0, "char_end": 5000, "prev_id": None, "next_id": None},
    # legacy-faq: planted excessive overlap — the same span re-chunked
    {"chunk_id": "lf-000", "doc_id": "legacy-faq", "index": 0,
     "text": "Legacy FAQ entry " + "covering pump maintenance and warranty terms. " * 8,
     "char_start": 0, "char_end": 300, "prev_id": None, "next_id": "lf-001"},
    {"chunk_id": "lf-001", "doc_id": "legacy-faq", "index": 1,
     "text": "FAQ entry continued " + "covering pump maintenance and warranty terms. " * 8,
     "char_start": 50, "char_end": 350, "prev_id": "lf-000", "next_id": "lf-002"},
    {"chunk_id": "lf-002", "doc_id": "legacy-faq", "index": 2,
     "text": "FAQ entry final " + "covering pump maintenance and warranty terms. " * 8,
     "char_start": 100, "char_end": 400, "prev_id": "lf-001", "next_id": None},
    # retired-faq: planted orphan — doc_id absent from DOC_LENGTHS
    {"chunk_id": "old-000", "doc_id": "retired-faq", "index": 0,
     "text": "Retired FAQ: legacy pump troubleshooting steps " * 8,
     "char_start": 0, "char_end": 400, "prev_id": None, "next_id": None},
]

DOC_LENGTHS = {"handbook": len(DOCS[0]["text"]),
               "returns-page": len(DOCS[1]["text"]),
               "msr-contract": len(DOCS[2]["text"]),
               "legacy-faq": 600}

ENRICHED = [
    {"chunk_id": "hb-000", "doc_type": "handbook", "language": "en",
     "tenant_id": "kestrel", "acl": ["all-staff"], "topics": ["warranty", "returns"]},
    {"chunk_id": "hb-001", "doc_type": "handbook", "language": "en",
     "tenant_id": "kestrel", "acl": ["all-staff"], "topics": ["warranty", "returns"]},
    {"chunk_id": "rp-000", "doc_type": "help-article", "language": "en",
     "tenant_id": "kestrel", "acl": ["all-staff"], "topics": ["refunds"]},
    {"chunk_id": "rp-001", "doc_type": "help-article", "language": "en",
     "tenant_id": "kestrel", "acl": [], "topics": ["warranty"]},          # no ACL
    {"chunk_id": "msr-000", "doc_type": "blog-post", "language": "en",     # invalid enum
     "tenant_id": "kestrel", "acl": ["legal"], "topics": ["misc"]},
    {"chunk_id": "hb-002", "doc_type": "handbook", "language": "en",
     "tenant_id": None, "acl": ["all-staff"], "topics": ["returns"]},       # null tenant
]

REFERENCE_VOCAB = {"warranty", "returns", "refunds", "shipping", "pricing"}

VECTORS = [
    [0.1, 0.2, 0.3], [0.1, 0.2, 0.3], [0.4, 0.5, 0.6],   # first two identical
    [0.0, 0.0, 0.0],                                       # zero vector
    [0.7, 0.8],                                            # wrong dim
]
VECTOR_META = [{"model_id": "text-embedding-3-small"}] * 4 + [
    {"model_id": "text-embedding-3-large"}]               # mixed model

SERVED = [
    {"chunk_id": "hb-000", "tenant_id": "kestrel",
     "acl": [{"principal_type": "group", "principal_id": "all-staff"}],
     "source": "handbook"},
    {"chunk_id": "rp-000", "tenant_id": "kestrel",
     "acl": [{"principal_type": "group", "principal_id": "all-staff"}],
     "source": "returns-page"},
    {"chunk_id": "msr-000", "tenant_id": "kestrel", "acl": [],   # no ACL
     "source": "msr-contract"},
    {"chunk_id": "ghost-001", "tenant_id": "kestrel",            # orphan
     "acl": [{"principal_type": "group", "principal_id": "legal"}],
     "source": "deleted-doc"},
]

SYNC_STATE = [
    {"source": "handbook", "last_synced_at": "2026-11-05T06:00:00Z"},
    {"source": "returns-page", "last_synced_at": "2026-11-04T20:00:00Z"},
    {"source": "msr-contract", "last_synced_at": "2026-10-28T09:00:00Z"},  # stale
]

GOLDEN = {"handbook": DOCS[0]["text"][:500], "returns-page": DOCS[1]["text"][:200]}
ACTUAL_PARSE = {
    "handbook": DOCS[0]["text"][:500],
    # regression: the returns-page parser now truncates at the first heading
    "returns-page": DOCS[1]["text"][:60],
}

# --------------------------------------------------------------------------
# Run every stage's checks
# --------------------------------------------------------------------------

results = []
results += check_file_inventory(RAW_FILES)
results += check_duplicate_hashes(RAW_FILES)
results += check_file_formats(RAW_FILES, ALLOWED_EXTS)
results += check_file_readability(RAW_FILES)
results += check_language_mix(DOCS, expected={"latin"})
results += check_garbage_ratio(PARSED)
results += check_empty_extractions(PARSED)
results += check_chars_per_page(PARSED)
results += check_repeated_lines(PARSED)
results += check_missing_tables(PARSED)
results += check_reading_order(PARSED)
results += check_banned_patterns([{"doc_id": d["doc_id"], "text": d["after"]}
                                  for d in CLEAN_PAIRS])
results += check_change_magnitude(CLEAN_PAIRS)
results += check_idempotent(clean_whitespace, [d["text"] for d in DOCS])
results += check_pii_scan([{"doc_id": d["doc_id"], "text": d["after"]}
                           for d in CLEAN_PAIRS])
results += check_chunk_sizes(CHUNKS)
results += check_chunk_uniqueness(CHUNKS)
results += check_chunk_coverage(CHUNKS, DOC_LENGTHS)
results += check_orphan_chunks(CHUNKS, DOC_LENGTHS)
results += check_overlap_sanity(CHUNKS)
results += check_mid_word_splits(CHUNKS)
results += check_chunk_links(CHUNKS)
results += check_required_fields(ENRICHED,
                                 required=["doc_type", "language",
                                           "tenant_id", "acl"])
results += check_enum_fields(ENRICHED, allowed={
    "doc_type": {"handbook", "help-article", "contract", "ticket"},
    "language": {"en"},
})
results += check_vocabulary_drift(ENRICHED, "topics", REFERENCE_VOCAB)
results += check_count_parity(len(CHUNKS), len(VECTORS))
# info-tier: a deliberately tiny budget so the third severity shows up
est_tokens = sum(len(d["text"]) for d in DOCS) // 4
results += check_cost_projection(est_tokens, price_per_1m_tokens=0.02,
                                 budget_usd=0.00001)
results += check_vector_sanity(VECTORS, expected_dim=3)
results += check_duplicate_vectors(VECTORS)
results += check_model_consistency(VECTOR_META)
results += check_freshness(SYNC_STATE, NOW, sla_hours=24)
results += check_orphan_records({r["chunk_id"] for r in SERVED},
                                {c["chunk_id"] for c in CHUNKS})
results += check_acl_coverage(SERVED)
results += golden_compare(GOLDEN, ACTUAL_PARSE, tolerance=0.98)

g = gate(results)

# Profiling + sampling extras for the report
stats = profile_corpus(DOCS)
n_review = sample_size(len(DOCS), confidence=0.95, margin=0.10)
n_real = sample_size(12_000, confidence=0.95, margin=0.10)
strata = stratified_sample(DOCS, n=n_review)

print("=" * 72)
print(render_report(
    "kestrel-corpus nightly run",
    g,
    extra_sections=[
        ("Corpus profile", render_profile(stats)),
        ("Human review sample",
         f"{n_review} of {len(DOCS)} docs at 95% confidence, ±10% margin "
         f"(on a 12,000-doc corpus the same settings give {n_real} docs).\n\n"
         + "\n".join(f"- {k}: {v}" for k, v in sorted(strata.items()))),
    ]))
print("=" * 72)
print("Gate verdict:", g.verdict)
print("Check outcomes:", g.counts)

12.6 Real output#

Running python3 demo.py on the toy corpus produces (real output — standard library only):

text
========================================================================
# Data quality report — kestrel-corpus nightly run

**Verdict: FAIL** (5 pass, 1 info, 20 warn, 11 fail)

| Check | Stage | Outcome | Measured | Expected |
|---|---|---|---|---|
| no_empty_files | raw | fail | 1 empty file | 0 empty files |
| no_oversized_files | raw | pass | 0 > 50,000,000 B | 0 oversized files |
| no_duplicate_files | raw | warn | 1 duplicate file | 0 duplicates |
| file_formats | raw | warn | 8/9 allow-listed | ext in ['.html', '.jsonl', '.pdf', '.txt'] |
| file_readability | raw | warn | 2 unreadable files | all readable |
| language_mix | raw | pass | 0% unexpected scripts | <= 10% |
| garbage_ratio | parsed | warn | worst 24.53% | <= 1% |
| no_empty_extractions | parsed | fail | 1 empty extraction | >= 40 chars |
| chars_per_page | parsed | warn | 1 outlier | 200-6000 chars/page |
| repeated_lines | parsed | pass | worst 0% | <= 30% |
| tables_recovered | parsed | warn | 1 missing table | table docs have a \|---\| row |
| reading_order | parsed | warn | 1 suspect doc | jump frac <= 30% |
| banned_patterns | cleaned | warn | 2 hits | 0 hits |
| cleaning_magnitude | cleaned | fail | 2 outliers | kept 50%-110% |
| cleaning_idempotent | cleaned | pass | 0 violations | clean(clean(x)) == clean(x) |
| pii_scan | cleaned | warn | 1 hit (values not logged) | 0 hits |
| chunk_sizes | chunked | warn | min 46, p50 95, max 4626 | 200-2400 chars |
| chunk_uniqueness | chunked | warn | 0 empty chunks, 1 duplicate chunk | 0 empty chunks, 0 duplicates |
| chunk_coverage | chunked | fail | 3 gaps | gaps <= 200 chars |
| orphan_chunks | chunked | warn | 1 orphan doc | 0 orphans |
| overlap_sanity | chunked | warn | worst 56% | <= 50% |
| mid_word_splits | chunked | warn | 14% suspect boundaries | <= 5% |
| chunk_links | chunked | warn | 1 broken link | prev/next resolve |
| required_fields | enriched | warn | 2 fields over | null <= 2% |
| enum_fields | enriched | warn | 1 invalid value | all values in enum |
| vocabulary_drift | enriched | warn | 25% new tags | <= 20% |
| count_parity | indexed | fail | 12 chunks vs 5 vectors | equal |
| cost_projection | indexed | info | $0.00002 for ~981 tokens | <= $0.00001 |
| vector_dims | indexed | fail | dims [2, 3] | all equal |
| no_dead_vectors | indexed | fail | 1 zero, 0 NaN/inf | 0 zero, 0 NaN/inf |
| no_duplicate_vectors | indexed | warn | 1 duplicate | 0 duplicates |
| single_embedding_model | indexed | fail | ['text-embedding-3-large', 'text-embedding-3-small'] | 1 model id |
| freshness_sla | served | warn | 1 stale source | <= 24h |
| no_orphan_records | served | fail | 1 orphan | 0 orphans |
| acl_coverage | served | fail | 1 uncovered record | tenant_id + acl present |
| golden:handbook | golden | pass | similarity 1.000 | >= 0.98 |
| golden:returns-page | golden | fail | similarity 0.450 | >= 0.98 |

## Reasons

- FAIL no_empty_files (raw): 1 empty file vs 0 empty files — notes-empty.txt
- FAIL no_empty_extractions (parsed): 1 empty extraction vs >= 40 chars — empty-scan
- FAIL cleaning_magnitude (cleaned): 2 outliers vs kept 50%-110% — msr-contract:kept 17%, ticket-1042:kept 119%
- FAIL chunk_coverage (chunked): 3 gaps vs gaps <= 200 chars — handbook@320-678, returns-page@260-752, msr-contract:offsets outside 0-1215
- FAIL count_parity (indexed): 12 chunks vs 5 vectors vs equal
- FAIL vector_dims (indexed): dims [2, 3] vs all equal
- FAIL no_dead_vectors (indexed): 1 zero, 0 NaN/inf vs 0 zero, 0 NaN/inf
- FAIL single_embedding_model (indexed): ['text-embedding-3-large', 'text-embedding-3-small'] vs 1 model id
- FAIL no_orphan_records (served): 1 orphan vs 0 orphans — ghost-001
- FAIL acl_coverage (served): 1 uncovered record vs tenant_id + acl present — msr-000
- FAIL golden:returns-page (golden): similarity 0.450 vs >= 0.98
- WARN no_duplicate_files (raw): 1 duplicate file vs 0 duplicates — b4128df2: ['handbook.pdf', 'handbook-copy.pdf']
- WARN file_formats (raw): 8/9 allow-listed vs ext in ['.html', '.jsonl', '.pdf', '.txt'] — media/walkthrough.mp4
- WARN file_readability (raw): 2 unreadable files vs all readable — contracts/board-pack.pdf:encrypted, archive/legacy-scan.pdf:truncated
- WARN garbage_ratio (parsed): worst 24.53% vs <= 1% — scan-0099:24.5%
- WARN chars_per_page (parsed): 1 outlier vs 200-6000 chars/page — empty-scan:2
- WARN tables_recovered (parsed): 1 missing table vs table docs have a |---| row — msr-contract
- WARN reading_order (parsed): 1 suspect doc vs jump frac <= 30% — promo-leaflet:5/5 jumps
- WARN banned_patterns (cleaned): 2 hits vs 0 hits — msr-contract:page_markerx1, ticket-1042:email_signaturex1
- WARN pii_scan (cleaned): 1 hit (values not logged) vs 0 hits — ticket-1042:emailx1
- WARN chunk_sizes (chunked): min 46, p50 95, max 4626 vs 200-2400 chars — 7 chunks below 200 chars, 1 chunk above 2400 chars
- WARN chunk_uniqueness (chunked): 0 empty chunks, 1 duplicate chunk vs 0 empty chunks, 0 duplicates
- WARN orphan_chunks (chunked): 1 orphan doc vs 0 orphans — retired-faq
- WARN overlap_sanity (chunked): worst 56% vs <= 50% — legacy-faq:56%
- WARN mid_word_splits (chunked): 14% suspect boundaries vs <= 5% — returns-page#0→1
- WARN chunk_links (chunked): 1 broken link vs prev/next resolve — rp-002:next
- WARN required_fields (enriched): 2 fields over vs null <= 2% — tenant_id:17% null, acl:17% null
- WARN enum_fields (enriched): 1 invalid value vs all values in enum — msr-000:doc_type='blog-post'
- WARN vocabulary_drift (enriched): 25% new tags vs <= 20% — new: ['misc']
- WARN no_duplicate_vectors (indexed): 1 duplicate vs 0 duplicates
- WARN freshness_sla (served): 1 stale source vs <= 24h — msr-contract:195h
- INFO cost_projection (indexed): $0.00002 for ~981 tokens vs <= $0.00001 — info-tier: budget trend, does not affect the verdict

## Corpus profile

- Documents: **5** (3,924 chars, ~981 tokens at ~4 chars/token)
- Lengths (chars): min 219, median 752, p95 1,184, max 1,215 (mean 784)
- Character classes: letter 74.7%, space 19.3%, punct 2.7%, digit 1.8%, other 1.5%
- Dominant scripts: latin 5
- Exact duplicates: 0

| Source | Docs | Chars |
|---|---|---|
| html | 1 | 752 |
| jsonl | 1 | 219 |
| pdf | 3 | 2,953 |

## Human review sample

5 of 5 docs at 95% confidence, ±10% margin (on a 12,000-doc corpus the same settings give 96 docs).

- contract: ['msr-contract', 'scan-0099']
- handbook: ['handbook']
- help-centre: ['returns-page']
- ticket: ['ticket-1042']
========================================================================
Gate verdict: fail
Check outcomes: {'pass': 5, 'info': 1, 'warn': 20, 'fail': 11}

Every defect planted in the toy corpus was caught by at least one check — and the report names exactly which. That's the suite working as designed: not "something is wrong" but "here are the 11 things wrong, ranked by severity".

12.7 Wiring it into the 05.9 pipeline#

The suite plugs in as one more stage. In the 05.9 pipeline's stage list, after enrich and before embed (or after index for the served checks):

python
# quality_gate.py — the dq.py suite as a stage in the 05.9 pipeline.
# Schematic: 05.9's toy manifest stores fewer fields than these checks
# need (no char_start/char_end, prev_id/next_id, tenant_id, acl or
# model_id columns yet) — the SELECTs show the shape; extend the schema
# per 05.8's lineage fields and adapt names to your own pipeline.
import json
import sqlite3

from dq import (
    GateResult, check_chunk_sizes, check_chunk_coverage,
    check_chunk_uniqueness, check_chunk_links, check_orphan_chunks,
    check_overlap_sanity, check_required_fields, check_enum_fields,
    check_count_parity, check_vector_sanity, check_duplicate_vectors,
    check_model_consistency, gate, render_report,
)

# REQUIRED_FIELDS / ALLOWED_ENUMS come from your stage contract (Part 8);
# record_error is 05.9's own helper for the manifest's errors table.

def quality_gate(manifest: sqlite3.Connection,
                 vectors: sqlite3.Connection,
                 doc_lengths: dict[str, int],
                 run_id: str,
                 expected_dim: int) -> GateResult:
    """Run the suite over what the pipeline just wrote. The caller decides
    what the verdict means: fail -> quarantine the batch + alert,
    warn -> attach the report and continue, pass -> proceed silently."""
    results = []

    # --- chunked stage: read back what process_document wrote ---------
    cols = ("chunk_id", "doc_id", "chunk_index", "text",
            "char_start", "char_end", "prev_id", "next_id")
    chunks = []
    for r in manifest.execute(
            "SELECT chunk_id, doc_id, chunk_index, text,"
            " char_start, char_end, prev_id, next_id FROM chunks"):
        c = dict(zip(cols, r))
        c["index"] = c.pop("chunk_index")
        chunks.append(c)
    results += check_chunk_sizes(chunks)
    results += check_chunk_coverage(chunks, doc_lengths)
    results += check_chunk_uniqueness(chunks)
    results += check_chunk_links(chunks)
    results += check_orphan_chunks(chunks, doc_lengths)
    results += check_overlap_sanity(chunks)

    # --- enriched stage: the metadata columns on the same rows ---------
    enriched = [dict(r) for r in manifest.execute(
        "SELECT chunk_id, doc_type, language, tenant_id, acl, topics"
        " FROM chunks")]
    results += check_required_fields(enriched, REQUIRED_FIELDS)
    results += check_enum_fields(enriched, ALLOWED_ENUMS)

    # --- indexed stage: the vector store -------------------------------
    n_chunks = manifest.execute(
        "SELECT COUNT(*) FROM chunks").fetchone()[0]
    vec_rows = vectors.execute(
        "SELECT model, vector FROM vectors").fetchall()
    vec_list = [json.loads(r[1]) for r in vec_rows]
    results += check_count_parity(n_chunks, len(vec_list))
    results += check_vector_sanity(vec_list, expected_dim=expected_dim)
    results += check_duplicate_vectors(vec_list)
    results += check_model_consistency(
        [{"model_id": r[0]} for r in vec_rows])

    g = gate(results)

    # record the verdict the way 05.9 records run state
    if g.verdict != "pass":
        record_error(manifest, run_id, "*", "quality_gate",
                     f"{g.verdict}: " + "; ".join(g.reasons[:5]))
    return g

# In 05.9's run_update(), call quality_gate(manifest, vectors,
# doc_lengths, run_id, EMBED_DIMS) after the process_document loop and
# before reconcile() — the served-side checks (freshness, orphans, ACL)
# run as a separate scheduled job over the serving layer, not inside a
# single update run.

The stage returns a GateResult the pipeline acts on — fail quarantines the batch and alerts, warn continues with the report attached, pass proceeds silently. Same shape for raw/parsed/cleaned stages: each transform's output feeds its check family, and the gate runs at every boundary.


Part 13: Module wrap-up — the one-page checklist#

Reference

This is the last lesson of Module 05. Before Modules 06 and 07 turn your chunks into a retrieval system, the ingestion side should be able to answer "yes" to every line below. Print it, tape it to the pipeline repo, revisit it after every parser or chunker change.

The ingestion-quality checklist#

Before you ingest

  • Corpus inventoried: counts, sizes, formats, languages, date ranges, duplicates known
  • Licence/terms confirmed per source; PII exposure assessed
  • Access-control requirements mapped (who may see what)
  • Golden set assembled per source type and human-verified

At every stage boundary

  • Raw: no empty/oversized files, no unexpected duplicates, language mix sane
  • Parsed: no empty extractions, chars/page in band, garbage ratio low, tables recovered
  • Cleaned: banned patterns gone, change magnitude sane, idempotent, PII scanned
  • Chunked: sizes in bounds, no dupes/empties, coverage complete, boundaries sane, links resolve
  • Enriched: required fields populated, enums valid, vocabulary in controlled set
  • Indexed: count parity, single model, dims consistent, no dead/duplicate vectors
  • Served: freshness within SLA, no orphans, ACL coverage complete

On every run

  • Profile computed and stored (baseline for drift detection)
  • Gate verdict recorded in the manifest; warn/fail reasons attached
  • Stratified sample of docs human-reviewed; defect rate tracked
  • Golden-set similarity within tolerance; regressions investigated
  • Drift metrics (volume, nulls, language, freshness) within baseline

When something fails

  • Failed items quarantined with reasons, never silently dropped
  • Fail-severity trips the run; warn-severity queues for review
  • Confirmed data defects become new golden cases and/or new checks
  • Bad-answer reports traced back through lineage to the data defect

Where to next#

The pipeline map from 05.1 ends here: discover → fetch → parse → clean → chunk → enrich → check → embed → index → serve. You now own every arrow up to check, and the checks that verify the rest.


What actually breaks, what it looks like, and which check catches it. Severity column is the default the suite assigns — your policy (Part 7.3) can always promote or demote.

Failure Symptom Caught by Severity Fix
Flattened table — prices detach from products Plausible-looking but wrong answers about pricing tables_recovered (parsed) + golden:* similarity warn / fail Re-parse with a table-aware extractor; add the doc to the golden set
Repeated footer/page numbers embedded Retrieval crowded by boilerplate; wasted embed spend repeated_lines (parsed), banned_patterns (cleaned) warn Extend cleaner rules; re-clean from raw
Stale policy still indexed Bot quotes superseded terms/returns window freshness_sla (served) + valid_until metadata warn / fail Re-sync the source; delete or supersede the old version
Mixed embedding models Similarity scores meaningless across the boundary single_embedding_model (indexed) fail Re-embed everything on one model; rebuild the index (06.4)
Partial upsert Count mismatch, missing chunks, retrieval holes count_parity (indexed) + chunk_coverage (chunked) fail Reconcile manifest↔store; re-run the upsert for the affected docs
Mojibake / encoding damage Garbled answers; garbage_ratio spike garbage_ratio (parsed), banned_patterns (cleaned) warn Fix the decode path (05.5); re-parse affected docs
Two-column interleave Sentences from different columns fused into nonsense reading_order (parsed, heuristic) + golden:* warn Re-parse with layout-aware mode; add to golden set
Orphan chunks after upstream delete Deleted docs still retrievable orphan_chunks (chunked) + no_orphan_records (served) warn / fail Propagate the deletion through chunk+vector layers; quarantine
Taxonomy drift — LLM invents tags Filters silently miss docs; dashboards disagree enum_fields, vocabulary_drift (enriched) warn Tighten the controlled vocabulary/prompt; re-enrich
PII survives cleaning Compliance exposure; values must never hit logs pii_scan (cleaned) — counts only warn Route doc to the redaction queue; escalate per Module 12
Connector death / freshness lag Index silently stale; "current" answers wrong freshness_sla (served) warn Restart the sync; backfill; alert on repeated trips
Over-aggressive cleaner Content amputated — numbers, clause refs gone cleaning_magnitude (cleaned), banned_patterns fail Roll back the cleaner version; re-clean from raw
Unexpected file format in corpus Wasted OCR/parse spend on non-documents file_formats (raw) warn Fix the fetch filter; quarantine the file
Encrypted or corrupt file Empty extraction two stages later, harder to trace file_readability (raw) — magic bytes, /Encrypt, %%EOF warn Route to manual handling/OCR; fix the downloader

The pattern across all fourteen: every failure has a stage it belongs to and a check that names it. When something breaks in production, the report's Reasons section is the first place to look — FAIL count_parity (indexed): 12 chunks vs 5 vectors tells you exactly which stage and which invariant. Two failures the toy suite has no row for, because they need more than a structural check, are in 6.7: a vision model that invents or transposes a number, and two valid documents that contradict each other.


Common misconceptions#

Misconception Reality
"If the schema validates, the data is good." Validity is one of nine dimensions. A perfectly valid record can contain flattened tables, wrong-column prices or stale text — only golden sets and coverage checks catch those.
"A wrong answer means the model failed." Usually it means the data failed upstream: the wrong chunk was retrieved, or the chunk itself was garbled. Trace back through lineage before blaming the model.
"We check quality once, at launch." Quality is a time series. Drift, parser updates and upstream changes break it continuously — the suite runs every pipeline run, and the profile is your baseline.
"More checks = better." Checks have costs (false positives, alert fatigue, review time). Severity discipline — fail only what corrupts irreversibly, warn what needs judgement — matters more than count.
"Duplicates don't matter much." Duplicate chunks waste embedding spend and flood top-k retrieval — the same answer surfaces five times and crowds out diversity. chunk_uniqueness is cheap insurance.
"Sampling for review is statistically rigorous." The sample-size formula assumes random sampling; stratified sampling across doc types is what makes it meaningful for a corpus that's 90% one format. And automation bias means reviewers need structure, not just a list.
"Great Expectations is the only serious option." As of November 2026 GX Core is community-maintained under Fivetran (Apache-2.0), Soda Core moved to Elastic License 2.0 in January 2026, and pandera/plain assertions cover most pipeline needs more cheaply. Choose by fit, not brand.
"The PII scan makes the data safe." Regex PII detection is a tripwire — it misses names, addresses and context-dependent identifiers. It's one layer; Presidio, redaction and Module 12's defences are the real control.
"A clean quality report means the answers will be good." The suite verifies data quality, not answer quality. Retrieval metrics (Module 10A) and generation evals are separate — good data is necessary, not sufficient.
"Quarantined data is lost data." Quarantine preserves the item and its failure reasons so it can be reprocessed when the parser/check is fixed. Deleting it guarantees you can never recover it.

Key takeaways#

  • Data quality for AI has nine dimensions — completeness, validity, uniqueness, consistency, freshness, accuracy/fidelity, coverage, representativeness, provenance — and most are properties of sets and relationships, not individual files.
  • LLM systems fail silently. Valid is not correct; correct is not useful. Every stage needs checks because no exception will tell you the data is bad.
  • Check every stage boundary: raw (inventory/hashes/language), parsed (empty/chars-per-page/garbage/tables), cleaned (patterns/magnitude/idempotency/PII), chunked (sizes/dupes/coverage/boundaries/links), enriched (fields/enums/vocab), indexed (parity/dims/model/dead vectors), served (freshness/orphans/ACL).
  • Structural checks verify shape; golden sets verify content. No schema proves a chunk says what the PDF said — that needs human-verified ground truth and similarity-diffed regression tests.
  • Profile before you threshold. Length distributions, char-class histograms, language mix and per-source breakdowns tell you what "normal" is; derive every threshold from the profile, not a guess.
  • Sample statistically, stratify deliberately. ~96 docs at 95%/±10% for a 12k corpus; oversample the strata you distrust (scans, contracts, tables).
  • Quantify quality: text coverage, table recovery rate, CER/WER (05.4), chunk coherence, self-retrieval proxies, and synthetic-question recall (10A.2 → Module 10A).
  • Drift is a time series. Baseline your metrics; alert on deviation. Fixed thresholds first, baseline-relative (median/MAD) once you have history.
  • Severity discipline is the circuit breaker. Fail what corrupts irreversibly (empty extractions, count parity, mixed models, ACL gaps); warn what needs judgement (garbage on one doc, PII hits, vocab drift); quarantine bad batches rather than dropping them.
  • Contracts make quality enforceable: stage boundaries are versioned Pydantic-model contracts; upstream sources get written data contracts with freshness SLAs and change notification.
  • Human-in-the-loop closes the loop: review queues for low-confidence items, bad-answer reports traced to data defects, and every confirmed defect becoming a new golden case or check.
  • The suite is the deliverable: dq.py + profiling.py + golden.py + demo.py — pure stdlib, runnable on toy data, pluggable into the 05.9 pipeline as a stage that returns pass/warn/fail with reasons.

Terms introduced in this lesson#

Term One-line definition
Data quality dimensions The nine properties that define "good data" for an AI pipeline: completeness, validity, uniqueness, consistency, freshness, accuracy/fidelity, coverage, representativeness, provenance
Silent failure A pipeline defect that produces no error but corrupts downstream output — the defining hazard of LLM systems
Garbage ratio Fraction of damaged characters (replacement chars, private-use glyphs, control chars, mojibake) in extracted text
Chars-per-page Extracted characters divided by page count — a heuristic band for detecting missed text layers or duplicated extraction
Cleaning magnitude len(cleaned)/len(raw) per doc — detects over-cleaning that destroys signal
Idempotent cleaning clean(clean(x)) == clean(x) — a cleaner that changes nothing on re-run
PII scan A regex tripwire counting email/phone/card-pattern hits without logging the values
Chunk coverage The union of [char_start, char_end) spans vs source length — detects content that never reached the index
Mid-word split A chunk boundary heuristic flagging prev-ends-alnum + next-starts-alnum
Vocabulary drift Share of enrichment tag values outside the controlled reference vocabulary
Count parity len(chunks) == len(vectors) — detects partial index writes
Dead vector A zero or NaN embedding — meaningless in similarity space
Model consistency All vectors in an index produced by one embedding model — mixing models silently corrupts similarity
Orphan record An index entry whose source document no longer exists — a deletion-propagation failure
Freshness SLA Maximum acceptable lag between source change and index update
ACL coverage Every served record carrying tenant + non-empty access-control list
Golden set A small human-verified sample of documents with known-correct extracted output
Parser regression test Re-extracting golden docs and comparing similarity to catch parser breakage
Diff tolerance The similarity threshold below which a golden comparison fails
Sample size (proportion) n = z²p(1−p)/e² with finite-population correction — how many docs a human must review
Stratified sampling Allocating the review sample proportionally across document strata
Text coverage Fraction of source text surviving into extracted/cleaned output
Table recovery rate Tables correctly extracted (row↔column binding intact) ÷ tables present
CER / WER Character/word error rate vs ground truth — OCR fidelity metrics (05.4)
Chunk coherence Whether a chunk is self-contained and readable alone — heuristic or LLM-judged
Self-retrieval proxy Checking each doc can be found by its own title/first sentence
Data drift Metric degradation over time: format, volume, nulls, language, schema, model, freshness
Baseline-relative threshold Alerting on deviation from a rolling median/MAD rather than a fixed bound
Circuit breaker A policy that escalates warn→fail when a failure rate exceeds a threshold — stops bad batches
Quarantine Isolating failed items with reasons for later reprocessing — never silently dropping
Stage contract The versioned shape+quality promise one pipeline stage makes to the next
Data contract A written upstream agreement on schema, freshness SLA and change notification
Review queue A prioritised table of items needing human judgement, fed by check failures
Quality gate A function rolling CheckResults into pass/warn/fail with actionable reasons
Audit trail The manifest record of every ingest/enrich/delete run — who, when, what
Numeric agreement Comparing the numbers in two independent extractions of one page to catch OCR slips and model-invented values
Cross-document consistency Whether valid documents in the corpus contradict each other (old and new versions, conflicting figures)

All terms are also collected in the glossary.


Exercises#

  1. Run the suite. Save dq.py, profiling.py, golden.py and demo.py side by side and run python3 demo.py. Pick three FAIL checks and, for each, say which pipeline stage produced the defect and what a human would do first.
  2. Extend it. dq.py already ships check_orphan_chunks (chunk doc_ids absent from doc_lengths) and check_overlap_sanity (per-doc duplicated-span fraction). Add a third chunked check of your own — e.g. check_chunk_language_consistency (all chunks of one doc share a dominant script) — and show the new row firing in demo.py.
  3. Tune a threshold. check_chunk_sizes uses 200–2,400 chars. Profile a real corpus of yours (or the demo's) and propose bounds from its p5/p95. At what point does tightening the bound start producing false positives?
  4. Golden-set tolerance. In golden_compare, lower tolerance to 0.90 and re-run demo.py. Does the previously-failing golden:returns-page check now pass? Then craft a smaller regression (for example, delete a six-word phrase from the handbook entry of ACTUAL_PARSE) and find the tolerance at which it starts to fail. What does that tell you about choosing a tolerance?
  5. Sampling. Your corpus has 8,000 docs: 7,000 HTML articles, 500 PDFs, 400 scanned contracts, 100 spreadsheets. At 95% confidence ±5%, how many docs should be reviewed in total, and how should stratified_sample allocate them? Why might you oversample the 100 spreadsheets?
  6. Circuit breaker. The demo has 11 fail + 20 warn + 1 info across 37 checks on 12 chunks. If circuit_breaker trips at >5% item failure and you have 8 chunks with 3 defective, does it trip? Should it? Defend your answer.
  7. Pandera. Install pandera[pandas] and pandas per Setup. Write a DataFrameModel for the ENRICHED records (doc_type, language, tenant_id, acl, topics) with the same constraints as check_required_fields/check_enum_fields. Which check catches what pandera can't, and vice versa?
  8. Drift baseline. Modify profile_corpus to also return n_docs and est_tokens. Write a function detect_drift(current, baseline, z_threshold=3) that flags metrics more than 3 MADs from a stored baseline. What two metrics would you watch first on a help-centre corpus?
  9. Contract test. Write a CONTRACT dict documenting what check_chunk_coverage promises its consumer (the index stage): input shape, output shape, quality guarantee, version. Where would you store it so a chunker upgrade can't silently violate it?
  10. Module wrap-up. Take the Part 13 checklist and mark which items your current project (or the module's starter project) already does, which are missing, and which you'd add first.

Hints and worked answers

  1. Typical mapping: no_empty_files is a raw-stage defect (fetch or sync produced a 0-byte file) — a human first checks the source system; chunk_coverage is a chunk-stage defect (the chunker dropped spans) — compare chunk offsets against the parsed text; count_parity is an index-stage defect (a partial upsert) — reconcile and re-upsert (05.9, 3.5). The point is naming the stage, not only the check.
  2. A language-consistency check can reuse script_class from dq.py: group chunks by doc_id, compute each chunk's dominant script, and flag docs whose chunks disagree. Add a planted defect (one chunk of CJK text in an English doc) to demo.py and confirm the new row shows warn, and that the report's totals change by exactly one.
  3. Take p5 and p95 of chunk lengths from your profile. The bound is too tight when roughly 5% of chunks fail by construction on healthy data; the signal that you have gone too far is that the same documents trip it on every run without anything having changed.
  4. At 0.90 golden:returns-page still fails: its similarity is 0.450, because truncating the page to 60 characters is catastrophic damage, far below any sensible tolerance. A small regression (six words deleted from the 76-word handbook excerpt) scores about 0.96 and slips past 0.90; it only fails at a tight tolerance such as 0.98. Hence the guidance: start tight (0.95–0.98) for deterministic text, loosen only for sources whose extractor is non-deterministic, and look at which diff caused a failure before loosening.
  5. The formula with finite-population correction gives 367 documents for 8,000 documents at 95% and ±5%. Proportional allocation gives about 321 HTML, 23 PDF, 18 scanned contracts and 5 spreadsheets. Five spreadsheets cannot reveal a defect that affects one in five, so oversample: reserve a minimum per stratum (for example 20–30) and let the total grow; scans and spreadsheets are where parse defects concentrate.
  6. 3 of 8 is 37.5%, far above 5%, so it trips. Whether it should depends on what the defects are: three garbled chunks out of eight in one document is a document problem (quarantine it); three garbled chunks spread over many documents is a pipeline problem (stop). A rate computed over too few items is noisy, so require a minimum batch size (for example, only evaluate the rate once there are 30 or more items).
  7. Pandera can express null-rate and enum membership per column (nullable, isin) and cross-column rules. It cannot see inside a text field, compare against the source file, or relate chunks to vectors; the dq.py checks (coverage, parity, model consistency) cover those. Conversely, pandera gives dataframe-wide checks in a few declarative lines, which dq.py writes by hand.
  8. A reasonable detect_drift computes abs(x - median) / (1.4826 * MAD) per metric over the stored baseline and flags anything above z_threshold. Guard against MAD = 0 (flat history) by using a small floor. For a help-centre corpus, watch n_docs (a redesign or failed sync changes volume first) and the character-class other share (encoding damage shows up there first).
  9. A contract names: input shape (list of chunk dicts with doc_id, char_start, char_end), output shape (a list of CheckResult), the guarantee (spans cover the document except gaps of at most the tolerance, in characters), and a version. Store it next to the code that produces the chunks and test it in that repository's CI, so a chunker change that breaks the promise fails the producer's build, not the consumer's.
  10. There is no single right answer; a good answer lists items as done, partial or missing and picks one first, typically the golden set plus chunk_coverage and count_parity, which are cheap and catch the most answer-breaking defects.

Check yourself#

  1. Name the nine data-quality dimensions and give one AI-pipeline failure each prevents.
  2. Why do LLM pipelines fail silently where ETL pipelines fail loudly?
  3. Which stage gets the most checks and why?
  4. What does chunk_coverage measure, and why is it the highest-value chunk check?
  5. What's the difference between a warn-severity and a fail-severity check, and which kinds of defects deserve each?
  6. Why must the PII scan report counts but never values?
  7. What four tools dominate dataframe validation as of November 2026, and what are their licences?
  8. What happened to Soda Core's licence in January 2026, and what does it restrict?
  9. What is a golden set, and why does assert extracted == golden fail in practice?
  10. How many docs should a human review in a 12,000-doc corpus at 95% confidence ±10%, and why stratify?
  11. What is CER vs WER, and when do you need each?
  12. Name three drift types and the metric that catches each earliest.
  13. What is a circuit breaker in the quality-gate context, and what's the failure mode of setting the threshold too low vs too high?
  14. What's the difference between a stage contract and a data contract with an upstream owner?
  15. Why is "mixing embedding models in one index" a fail-severity check rather than a warn?

Further resources#


← 05.9 — Ingestion Pipelines and Incremental Updates | Module 05 overview | Module 06: Embeddings & Vector Search →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close