05.1 Data Sources, Formats and the Ingestion Mindset

RetrievalLesson 1 of 1013,333 words8 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

Every lesson in this module exists because of one uncomfortable fact: an LLM system is only as good as the data you feed it, and "the data" is never one clean file. It is a folder of PDFs where half the pages are scans, a help centre with the same navigation bar on every page, a database of tickets that must become sentences, a contracts drive where the newest policy must outrank the old one, and a web of pages you are only sometimes allowed to read. This lesson is the map before the territory: why ingestion quality decides everything downstream, the nine-stage pipeline every source flows through, every kind of source you will meet and how to reach it, the formats cheat sheet, how to turn rows into text, how to audit a corpus before you build anything, and where lineage, provenance and the build-versus-buy decision fit. By the end you will have a project scaffold, a runnable corpus audit, and a small fictional corpus that every later lesson in this module reuses.

What you'll learn

  • Why "garbage in, garbage out" is the most expensive failure mode in LLM systems, with three concrete failure stories
  • The nine-stage ingestion pipeline (discover → fetch → parse → clean → chunk → enrich → embed → index → serve), who owns each stage, and the batch vs incremental vs streaming choice
  • How to reach every common source: local files and file shares, object storage, databases, the web (including Markdown-first content negotiation and hosted "LLM-ready" crawlers), SaaS systems (Drive, SharePoint, Notion, Confluence, Slack, Jira, Zendesk, GitHub), email and chat exports, RSS/Atom feeds, audio/video, code repositories and spreadsheets
  • The formats cheat sheet: what structure each format gives you for free, its typical pitfalls, and which parser class fits
  • Structured vs semi-structured vs unstructured data, and how to turn database rows into retrievable text ("row-as-document", templates, entity-centric documents) — plus when text-to-SQL beats retrieval
  • How to audit a corpus before building: inventory, sampling, the questions document, coverage gaps, sensitive content, licences, permissions and freshness — with a runnable audit script
  • Why every chunk needs lineage back to its source, version, page and parsing run
  • Build vs buy for ingestion: managed parsers, connector platforms, vector-database ingestion, application frameworks and hand-rolled pipelines, honestly compared
  • This lesson's project setup (uv, dependency groups, a data/ layout) and the running corpus the module shares

What you don't need

  • API keys, cloud accounts or any running service. Object-storage and SaaS samples are written carefully and marked illustrative; every sample that can run on your machine alone does run (the audit script and corpus generator are pure Python standard library).
  • How to parse any specific format. PDFs are 05.2, HTML and Office files are 05.3, OCR is 05.4, cleaning is 05.5, chunking is 05.6 and 05.7, metadata fields are 05.8, pipeline mechanics are 05.9.
  • What embeddings and vector search are. Module 02, lesson 03 covers the concept and Module 06 owns the engineering.

Setup

This lesson uses a uv project called data-pipeline; each lesson's own Setup names its project, so treat this as the module's reference layout rather than a single shared project. If uv is new to you, lesson 03.1, Part 4 walks through installing it; the short version:

bash
uv init data-pipeline --bare --python 3.13
cd data-pipeline

Then give the project dependency groups — named sets of packages you install only when a lesson needs them, instead of one giant install. uv supports PEP 735 dependency groups directly in pyproject.toml (support landed in uv 0.4.27; check your uv --version):

toml
# pyproject.toml (the [project] table already exists after uv init)
[project]
name = "data-pipeline"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["pydantic"]

[dependency-groups]
core = []
web = ["httpx", "feedparser", "playwright"]
files = ["pandas", "pyarrow", "openpyxl", "python-docx"]
storage = ["boto3", "google-cloud-storage", "azure-storage-blob"]
office-extra = ["markitdown", "trafilatura", "beautifulsoup4"]
dev = ["pytest"]

Note the two version numbers: requires-python = ">=3.11" is the floor — the path-wide Python minimum — while uv init --python 3.13 makes 3.13 the interpreter uv actually resolves. 3.13 is also the version 05.3 recommends, because one of the large parsers (unstructured) does not support Python 3.14 as of November 2026. If a library later demands a newer Python, uv will say so.

Install what each lesson needs with uv sync --group <name> (or uv sync --all-groups for everything), and run scripts with uv run python script.py. The listing above names packages only, so uv sync --group web resolves the newest release of each package and records the exact versions in uv.lock; if you create a group with uv add --group web httpx instead, uv also writes a lower bound such as httpx>=0.28.1 into the file, so your own pyproject.toml will differ from this listing. The module's samples were checked against the releases current on PyPI on 7–8 November 2026 (for example pandas 3.1.1 and httpx 0.28.1; several packages have had patch releases since, and pypdf has just reached 7.0.x — see 05.2), and each lesson's Setup states the versions it was checked against. The per-lesson uv add lines that follow name packages only, so they install the newest release too. When a lesson adds a parser library under this layout, it extends this table and says which group it joins. The .env file matters only when a lesson calls a model API (the provider samples in 03.6 send documents to models); this lesson needs no keys at all.

Create the working directories the rest of the module assumes:

bash
mkdir -p data/raw data/parsed data/chunks data/exports
git init    # optional, but lets you ignore data/ later

The convention: data/raw/ holds source files exactly as fetched (never edited), data/parsed/ holds structured parse output, data/chunks/ holds the retrievable units, and data/exports/ holds anything you hand to another system. Keeping raw bytes immutable is the first rule of ingestion pipelines (05.9 makes it a design principle).


What you must be able to do after this lesson#

  • Explain why data quality decides AI quality
  • Name the stages of the ingestion pipeline and who owns each
  • Reach common data sources such as files, storage, databases and the web
  • Audit a corpus before building on it
  • Decide when to build and when to buy parts of ingestion

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The chatbot gives wrong prices." 1.1 Three failure stories
"Our retrieval is great but answers cite the wrong page." 1.2 What good data means and Part 6
"Should we re-crawl everything nightly or watch for changes?" 2.2 Batch vs incremental vs streaming
"The docs live in SharePoint / Confluence / a shared drive." 3.1 Local files and file shares and 3.5 SaaS systems
"Can we just send the PDF to the model?" 3.9 Choosing a connector and 03.6
"Is a .docx just a zip?" 4.1 The formats cheat sheet
"How do we feed a customers table to the assistant?" 4.3 Turning rows into text
"Why not let the model write SQL instead?" 4.4 When not to chunk at all
"Where do we even start with 40,000 documents?" Part 5: The corpus audit
"LlamaIndex / LangChain already does ingestion — why bother?" Part 7: Build vs buy
"How do we handle the scanned contracts folder?" 3.9, 05.2 and 05.4

Part 1: Why data decides AI quality#

1.1 Three failure stories#

The model is rarely the villain. In production LLM systems, the most expensive bugs are upstream, in the data pipeline, and they all look the same from the outside: plausible-sounding answers built on subtly wrong input.

Story one: the flattened table. A retailer ingests its product catalogue PDF — a beautifully formatted price list where each product row has a name, a SKU and a price. The PDF parser extracts the text but loses the table structure, so the output is a stream of words in reading order: product names grouped together, then a column of prices. The ingestion team chunks the text every 500 tokens and embeds it. Six months later a customer asks "how much is the Acme Cordless Drill?" and the assistant confidently answers "$45" — a real price, from a real document, attached to the wrong product. Nothing hallucinated; the association was destroyed at parse time and no model, prompt or eval downstream could have known. The fix was representing the table as rows (Markdown, CSV, or one document per product) so each price travels with its product — the techniques of 05.2 and 4.3 exist precisely for this.

Story two: the repeated footer. Acme crawls its own help centre — 4,000 HTML pages sharing one template. The parser keeps everything between <html> and </html>, including the 200-word navigation menu, cookie banner and "© 2024 Acme" footer that appear on every page. Those boilerplate chunks are short, repetitive and keyword-rich ("contact support", "returns policy"), so they dominate the embedding space: a query about returns retrieves the footer chunk, not the returns article. Worse, the footer contains the old support phone number, so the assistant quotes a disconnected line. The fix was boilerplate removal and per-page main-content extraction (05.3) plus deduplication (05.5).

Story three: the stale policy. An HR team uploads the employee handbook to the knowledge base in January. In March, remote-work policy changes from "two days" to "three days"; someone uploads the new PDF — but the old file is still in the folder, still indexed, still fresher-looking because its modified date was preserved by a bad sync tool. A new hire asks the assistant about remote work and gets the January answer, cited to a real page. The retrieval wasn't wrong; the corpus contained two contradictory truths and nothing in the pipeline knew which was current. The fix is change detection, versioning and supersession — 05.9 owns the mechanics, and Part 6 explains why you must be able to trace which parse produced which chunk.

1.2 What "good data" means for an LLM system#

"Clean data" is vague. For retrieval and generation, good ingestion data has specific, checkable properties:

Property What it means What breaks without it
Self-contained units Each chunk makes sense alone: it carries its subject, not just pronouns and table fragments Answers that reference "it", "the above", or numbers with no labels (05.6)
Structure preserved where it matters Tables stay tables, headings stay headings, lists stay lists Flattened associations (story one), lost hierarchy
Provenance Every chunk knows its source, version, page and parsing run Uncitable answers, unfixable bugs, compliance failures (05.8)
Freshness and supersession The newest authoritative version wins; stale copies are gone or marked Contradictory answers (story three)
Deduplication Near-identical copies don't flood the top-k results One topic crowds out everything else (05.5)
Correct access metadata Every chunk knows who may see it Leaks across teams and tenants (05.8, Module 12)
Language coverage The corpus's languages are known and handled Silent English-only retrieval for multilingual users
Noise removed, signal kept Boilerplate, OCR garbage and PII handled deliberately Junk chunks, privacy incidents (05.5)
Measured, not assumed You know counts, formats, sizes, gaps before building Building on a guess (Part 5)

Notice that almost every row is a data engineering property, not a model property. The model consumes whatever it is given; your job is to make sure what it is given is true, current, complete, permitted and traceable.

1.3 The audit-first mindset#

Experienced data engineers share a habit: you do not build an ingestion pipeline until you have audited the corpus. The audit (Part 5) answers questions like "how many PDFs are actually scans?", "which folder has no dates?", "is there PII in the tickets export?", "who owns this SharePoint site and may we mirror it?" — before a single parser is chosen. Skipping it is how teams discover in week six that 30% of their "PDFs" have no text layer, or that the contracts folder is synced read-only and their incremental strategy can't work.

The order of operations for this whole module is therefore:

flowchart LR
    A["Audit the corpus<br/>(Part 5)"] --> B["Choose sources & formats<br/>(Parts 3-4)"]
    B --> C["Parse & clean<br/>(05.2-05.5)"]
    C --> D["Chunk & enrich<br/>(05.6-05.8)"]
    D --> E["Pipeline & updates<br/>(05.9)"]
    E --> F["Quality checks<br/>(05.10)"]

Part 2: The ingestion pipeline#

2.1 The nine stages and who owns them#

Every source, from a single PDF on your laptop to a 40,000-page crawled documentation site, flows through the same nine stages. The names matter because every tool, framework and later lesson in this module plugs into one of them.

flowchart LR
    subgraph mod5 ["Module 05: Data Engineering for AI"]
        direction TB
        A["1. Discover"] --> B["2. Fetch"] --> C["3. Parse"] --> D["4. Clean"] --> E["5. Chunk"] --> F["6. Enrich"]
    end
    subgraph mod6 ["Module 06: Embeddings & Vector Search"]
        G["7. Embed"] --> H["8. Index"]
    end
    subgraph mod7 ["Module 07: RAG"]
        I["9. Serve<br/>(retrieve, generate, cite)"]
    end
    F --> G --> H --> I
Stage What happens Typical failures Taught in
1. Discover Enumerate what exists: directory listings, sitemaps, API queries, database SELECTs, change feeds Missed files, permission errors, listing truncated at scale This lesson (Part 3), 05.9
2. Fetch Get the bytes: HTTP downloads, SDK calls, mounted drives, database dumps Timeouts, rate limits, partial downloads, auth expiry, robots.txt/ToS violations This lesson, 05.3, 05.9
3. Parse Bytes → structured text with blocks, pages, tables: ParsedDocument Scanned pages with no text layer, tables flattened, wrong reading order, mojibake 05.2, 05.3, 05.4
4. Clean Normalise encoding, whitespace, boilerplate; deduplicate; handle PII Over-cleaning that destroys signal, missed near-duplicates 05.5
5. Chunk Split into retrievable units with boundaries that respect structure Chunks that split sentences/tables, lose context, or are the wrong size 05.6, 05.7
6. Enrich Attach metadata: dates, language, ACL, tags, lineage, quality flags Missing ACLs, unfilterable free text, metadata drift 05.8
7. Embed Turn chunk text into vectors Wrong model for the language/domain, truncation of long chunks Module 06
8. Index Store vectors + metadata in a searchable index Dimension mismatch, missing filter fields, stale entries Module 06
9. Serve Retrieve relevant chunks, generate an answer, cite sources Retrieval misses, ungrounded answers Module 07

2.2 Batch vs incremental vs streaming ingestion#

The same pipeline runs in three rhythms, and choosing wrong is one of the most common architecture mistakes:

Rhythm How it works Latency Cost shape Right when
Batch (full) Re-process the whole corpus on a schedule (nightly, weekly) Hours to a day Predictable; wasteful if nothing changed Small corpora (< ~100k docs), static archives, first build, periodic re-parsing after a parser upgrade
Incremental Detect what changed (hashes, timestamps, change feeds, webhooks), re-process only that Minutes Pay only for changes; needs a manifest/state store The default for production: docs, tickets, help centres, anything living
Streaming / near-real-time Events (webhooks, queues, CDC) trigger ingestion of one item at a time Seconds Highest engineering cost; per-item overhead Chat messages, live tickets, sensor-like feeds where minutes matter

The honest answer for most systems is incremental batch: a scheduled job that diffs the source against a manifest and processes only new/changed/deleted items (05.9 builds exactly this). True streaming ingestion is rare outside chat and high-frequency feeds, because parsing and chunking are CPU-bound batch-shaped work — you debounce events into small batches rather than process each one instantly.

flowchart TD
    Q1{"Does the source offer<br/>change events or feeds?<br/>(webhooks, delta API, CDC)"} -- "yes" --> Q2{"Is seconds-level<br/>freshness required?"}
    Q2 -- "yes" --> S["Streaming / near-real-time<br/>debounce into small batches"]
    Q2 -- "no" --> I["Incremental batch<br/>(scheduled diff + manifest)"]
    Q1 -- "no" --> Q3{"Corpus size and churn?"}
    Q3 -- "small or static" --> B["Full batch re-run"]
    Q3 -- "large or frequently updated" --> I

2.3 Cross-cutting properties (preview)#

Three properties apply to every stage and every rhythm; 05.9 turns them into working code:

  • Idempotency: running the pipeline twice on the same input produces the same output, not duplicates. Content-hash keys make re-runs safe and make retries free.
  • Per-document failure isolation: one corrupt PDF or one malformed API page must not kill the run. Fail that document, record why, continue, and report at the end.
  • Provenance at every hop: each stage records what it consumed and produced (parser name/version, cleaning rules version, chunker config), so a bad answer can be traced back to the exact parse that caused it. Part 6 expands this.

Part 3: Sources and access#

"Where is the data?" is the first engineering question, and the answer determines everything: sync mechanism, auth, rate limits, freshness, and who is allowed to read it. This part surveys the source types you will meet, roughly in order of how pleasant they are to work with.

3.1 Local files and file shares#

The friendliest source is a directory on disk or a mounted drive. pathlib is all you need to enumerate it:

python
from pathlib import Path

for p in sorted(Path("data/raw").rglob("*")):
    if p.is_file():
        print(p.relative_to("data/raw"), p.stat().st_size)

Variants you will meet:

  • A local folder you control: easiest case; mtimes and hashes give you change detection for free.
  • A network file share (SMB/NFS mount, or a synced folder from Dropbox/OneDrive/Google Drive desktop apps): looks like a local path but lies about freshness — sync clients write temp files, preserve odd mtimes, and can serve a stale cached copy while "syncing". Treat it as unreliable local storage: always re-read and hash contents rather than trusting mtime, and expect partial files mid-sync (write-then-rename is the usual pattern, but verify).
  • Watching for changes: on a live folder, watchdog (7.1.0 as of November 2026) gives you filesystem events for near-real-time ingestion; on a schedule, a diff against a manifest is simpler and more robust. 05.9 covers both.

3.2 Object storage: S3, GCS, Azure Blob#

Cloud object stores are where most "document dumps" live: a bucket per team, a prefix per folder, lifecycle rules that quietly delete old versions. All three have mature Python SDKs; the pattern is identical — list, then fetch.

AWS S3 Google Cloud Storage Azure Blob Storage
Python SDK (PyPI, Nov 2026) boto3 1.43.124 google-cloud-storage 3.17.1 azure-storage-blob 12.31.1
Client creation boto3.client("s3") storage.Client() BlobServiceClient(account_url=..., credential=...)
Listing list_objects_v2(Bucket=..., Prefix=...) (paginated) bucket.list_blobs(prefix=...) container.list_blobs(name_starts_with=...)
Auth IAM user keys, instance role, SSO Service-account JSON key, workload identity Connection string, SAS token, or azure.identity.DefaultAzureCredential
Change signal Event notifications → SNS/SQS/EventBridge Pub/Sub notifications, object versioning Event Grid

Here is the whole access pattern for S3 — the other two are structurally identical:

python
# s3_2_list_and_download.py — needs AWS credentials; run with real creds or moto
import boto3

s3 = boto3.client("s3", region_name="eu-west-1")
BUCKET = "acme-documents"
PREFIX = "contracts/"

# 1. Discover: list every key under the prefix (handles pagination)
paginator = s3.get_paginator("list_objects_v2")
keys = [
    obj["Key"]
    for page in paginator.paginate(Bucket=BUCKET, Prefix=PREFIX)
    for obj in page.get("Contents", [])
]
print(f"{len(keys)} objects under {PREFIX!r}")
for k in keys[:5]:
    print(" ", k)

if not keys:
    raise SystemExit(f"no objects under {PREFIX!r}")  # empty prefix or no ListBucket

# 2. Fetch: download one object to data/raw/, keeping the remote key as provenance
key = keys[0]
s3.download_file(BUCKET, key, f"data/raw/{key.replace('/', '_')}")
print("downloaded", key)
Example output · illustrative6 lines
4 objects under 'contracts/'
  contracts/nda-acme-2025.pdf
  contracts/vendor-agreement.pdf
  contracts/scan-001.png
  contracts/scan-002.png
downloaded contracts/nda-acme-2025.pdf

3.3 Databases and warehouses#

Relational data reaches an LLM system in two distinct ways, and confusing them is a classic beginner error:

Approach What it is Use when
Export to text, then retrieve Turn rows into documents at ingestion ("row-as-document", templates — 4.3) The assistant should know the data (product catalogue, policies, ticket history)
Let the model query the database Give the model schema context plus a SQL tool; it writes queries at answer time The data is huge, frequently changing, or questions need aggregates/joins the corpus can't pre-compute ("text-to-SQL" — 4.4, Module 08A)

For the export path, the source can be anything with a SQL interface: Postgres/MySQL via psycopg/pymysql, SQLite via the stdlib sqlite3, or analytical stores like DuckDB (2.0.0 as of November 2026) and BigQuery/Snowflake exports. A dump file (.sql, .csv) is also just a file source from Part 4's point of view.

Incremental updates from a database need change detection: either poll a updated_at/version column with a watermark ("give me rows where updated_at > last_run"), or use change data capture (CDC) — the database's own transaction log streamed to a consumer (Debezium-style for Postgres/MySQL, DynamoDB Streams, SQL Server CDC). CDC gives you inserts, updates and deletes in order, which polling can't fully provide (a hard delete leaves no updated_at row to find). 05.9 designs the manifest and tombstone handling this feeds into; treat CDC as a preview here — the pattern is "the database tells you what changed; you re-process only those rows and propagate deletes".

3.4 The web: crawling, sitemaps and polite scraping#

Public web content is the richest and most legally sensitive source. Three things gate it: robots.txt, terms of service, and basic courtesy.

robots.txt is the Robots Exclusion Protocol, standardised as RFC 9309 (September 2022). A site publishes /robots.txt saying which user-agents may fetch which paths; Disallow rules are directives to crawlers, not law — but ignoring them is how you get blocked, and on many sites it also violates the terms of service. Check it before crawling anything you don't own, honour any Crawl-delay the site publishes (a widely implemented extension supported by major crawlers, though not part of RFC 9309 itself — the RFC's "other records" clause leaves such directives to implementers), and always identify yourself with a descriptive User-Agent that includes a contact URL. (There are also standards-adjacent files worth knowing: sitemap.xml lists URLs — see below; llms.txt is an emerging convention where site owners publish LLM-friendly content indexes.)

Sitemaps are the polite way to discover pages: /sitemap.xml (or an index of sitemaps) lists URLs with optional lastmod dates — exactly the change signal an incremental crawler needs. The protocol is simple XML (<urlset> of <url><loc>…</loc></url> entries, or nested <sitemapindex>); 05.3 covers parsing site structure in depth.

Fetching politely with httpx (0.28.1 as of November 2026 — the same client Module 03 uses):

python
# s3_4_polite_fetch.py — fetch one page, conditionally, with backoff
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

import httpx

HEADERS = {
    "User-Agent": "AcmeDocsBot/1.0 (+https://acme.com/bot; contact: ops@acme.com)",
    "Accept": "text/html,application/xhtml+xml",
}
TIMEOUT = httpx.Timeout(30.0)
MIN_INTERVAL = 1.0  # seconds between requests to the same host — be polite
_last_hit: dict[str, float] = {}


def retry_after_seconds(resp: httpx.Response) -> float:
    """Seconds to wait per Retry-After — delay-seconds or HTTP-date (RFC 9110)."""
    value = resp.headers.get("Retry-After")
    if not value:
        return 5.0
    try:
        return max(0.0, float(value))
    except ValueError:
        pass  # not delay-seconds — try the HTTP-date form
    try:
        when = parsedate_to_datetime(value)
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
        return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
    except (TypeError, ValueError):
        return 5.0


def polite_get(client: httpx.Client, url: str, etag: str | None = None) -> httpx.Response | None:
    """GET with rate limiting, conditional requests and 429/503 backoff."""
    host = httpx.URL(url).host
    wait = MIN_INTERVAL - (time.monotonic() - _last_hit.get(host, 0.0))
    if wait > 0:
        time.sleep(wait)
    headers = dict(HEADERS)
    if etag:
        headers["If-None-Match"] = etag  # server may answer 304: unchanged
    resp = client.get(url, headers=headers, timeout=TIMEOUT)
    _last_hit[host] = time.monotonic()
    if resp.status_code == 304:
        return None  # not modified — keep the stored copy
    if resp.status_code in (429, 503):
        time.sleep(retry_after_seconds(resp))  # honour the server's own hint
        return polite_get(client, url, etag)
    resp.raise_for_status()
    return resp


if __name__ == "__main__":
    with httpx.Client(follow_redirects=True) as client:
        r = polite_get(client, "https://docs.example.com/guide/install")
        if r is not None:
            print(r.status_code, len(r.content), "bytes; etag:", r.headers.get("ETag"))
Example output · illustrative1 line
200 48213 bytes; etag: "a1b2c3d4e5"

The ETag/If-None-Match pair is the cheap change-detection mechanism for the whole web: most pages don't change, and a 304 Not Modified costs you a few hundred bytes instead of a re-parse. The retry-with-Retry-After pattern is the same discipline 03.8 teaches for API calls — rate limits are a fetch-stage concern here too.

JavaScript-rendered pages are the main technical trap: many modern sites serve an empty shell and build content in the browser, so httpx gets HTML with no article text. Detection is easy (tiny body, lots of <script>); the fix is a headless browser — Playwright (1.64.1 as of November 2026, uv add playwright then playwright install chromium) driving a real page and returning the rendered DOM:

python
# s3_5_rendered_fetch.py — render a JS page and return its HTML
from playwright.sync_api import sync_playwright


def fetch_rendered(url: str) -> str:
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(user_agent=(
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36"
        ))
        page.goto(url, wait_until="networkidle", timeout=60_000)
        html = page.content()
        browser.close()
    return html


if __name__ == "__main__":
    html = fetch_rendered("https://app.example.com/docs/getting-started")
    print(len(html), "bytes of rendered HTML")
Example output · illustrative1 line
183204 bytes of rendered HTML

Markdown-first and hosted fetch services (as of November 2026). Because so many LLM applications read the web, a second route has appeared beside "download HTML, then extract the article" (05.3 teaches the extraction stack). Try these before you build a rendering fleet:

  1. Ask the site for Markdown. Some sites publish a Markdown twin of each page or an /llms.txt index. Others do content negotiation: the client sends Accept: text/markdown and the server answers with Content-Type: text/markdown. Cloudflare's Markdown for Agents feature (announced 12 February 2026) does this at the edge for sites that switch it on; per its documentation it converts HTML only, limits conversion to 6 MiB of decompressed HTML, and adds Vary: Accept so caches keep the two representations apart. If the site sends a Content-Signal header (for example ai-input=no), treat it as the site owner's stated preference about AI use and read it as part of the terms check above (Cloudflare keeps the origin's value when there is one; when the origin sends none, the converted response carries a default of ai-train=yes, search=yes, ai-input=yes, so that default is not evidence the owner has agreed to AI use: read the site's terms). Not every site supports any of this, so always keep the HTML fallback.
  2. Use a hosted or self-hosted "LLM-ready" crawler when you need many pages with JavaScript rendering and do not want to run browsers yourself. Three names you will meet, all checked on their official pages in November 2026:
Tool Shape Good for Watch out for
Crawl4AI (crawl4ai 0.9.5 on PyPI, Apache-2.0 repository) Python library, crwl CLI and a Docker server you run yourself Self-hosted crawling to Markdown with content filters and CSS/XPath extraction You operate the browsers; the licence text asks for an attribution badge or credit, so read it before shipping
Firecrawl (firecrawl-py 4.55.0, hosted API with a self-host option; the repository is AGPL-3.0, so read the licence before embedding it in a product) Scrape, crawl, map (URL discovery) and search endpoints returning Markdown, HTML or JSON A managed "give me the site as Markdown" call, plus a map step for discovery Per-credit pricing and your pages pass through a third party: check its terms and current pricing page
Jina Reader (https://r.jina.ai/<url>) A prefix URL that returns a page as Markdown; a search twin at s.jina.ai One-off single-page fetches and prototypes without any setup Single-page oriented (you still write the crawl loop); the site says it is operated under Elastic, and its ReaderLM-v2 and jina-vlm models carry a non-commercial licence (CC-BY-NC 4.0), so read the current terms before production use

None of these removes your obligations from the previous paragraphs: robots.txt, terms of service, licensed content and rate limits still apply, and a hosted service adds a new data-processing party (privacy: 02.9 Part 9). Treat their Markdown as a parse result like any other: record the tool name and version in lineage (Part 6), keep the raw response for re-parsing, and compare it with a local trafilatura extraction on a sample of pages before trusting it. The following sketch asks for Markdown first and falls back to HTML:

python
# s3_4b_markdown_negotiation.py — prefer a Markdown representation, fall back to HTML
import httpx

HEADERS = {
    "User-Agent": "AcmeDocsBot/1.0 (+https://acme.com/bot; contact: ops@acme.com)",
    # q-values: prefer Markdown, accept HTML as the fallback
    "Accept": "text/markdown, text/html;q=0.8",
}


def fetch_best(url: str) -> tuple[str, str]:
    """Return (kind, body) where kind is 'markdown' or 'html'."""
    with httpx.Client(follow_redirects=True, timeout=30.0, headers=HEADERS) as client:
        resp = client.get(url)
        resp.raise_for_status()
    ctype = resp.headers.get("content-type", "").split(";")[0].strip().lower()
    return ("markdown" if ctype == "text/markdown" else "html"), resp.text


if __name__ == "__main__":
    kind, body = fetch_best("https://docs.example.com/guide/install")
    print(kind, len(body), "characters")
    if kind == "html":
        print("no Markdown twin: extract the main content with trafilatura (05.3)")
Example output · illustrative1 line
markdown 6120 characters

When to avoid scraping entirely: if the site offers an API, use it; if the terms forbid crawling, don't; if the content is licensed (paywalled news, proprietary docs), buy the licence or export — scraping around a paywall is both a legal and an ethical problem, and the Module 12 preview applies. This is engineering guidance, not legal advice — when in doubt, ask the site owner or your legal team.


3.5 SaaS systems: Drive, SharePoint, Notion, Confluence, Slack, Jira, Zendesk, GitHub#

Most real corpora live behind SaaS APIs, not on disks. The good news: every major system has a REST API, official auth, rate limits, and usually a Python SDK. The bad news: each has its own pagination, permission and "what counts as content" quirks. The pattern is always the same — authenticate, list, fetch, respect rate limits — and 05.9 turns it into resumable jobs.

System What you can get Auth model Rate limits (check docs) Python SDK (PyPI, Nov 2026)
Google Drive File metadata + files.export to text/HTML/PDF; revisions via revisions.list; changes via the Changes API OAuth 2.0 or service account Per-project and per-user quotas (order of thousands of queries/minute; check docs) google-api-python-client 2.201.0 (+ google-auth)
SharePoint / OneDrive Sites, document libraries, driveItem content; delta queries for changes Microsoft Entra ID app registration (delegated or application permissions) Per-app/per-user throttling msgraph-sdk 1.65.0
Notion Pages and databases shared with an integration; blocks → text/markdown Internal integration token ~3 requests/second average per integration (check docs) notion-client 3.1.0
Confluence / Jira (Atlassian Cloud) Pages, blog posts, spaces; issues, comments, attachments API token (basic auth) or OAuth 2.0 Per-tenant limits atlassian-python-api 5.0.5
Slack Channel history via Web API; better: the workspace data export (JSON per channel/day) for bulk Bot/user token (xoxb-/xoxp-) Tiered per-method limits slack-sdk 3.46.0
Zendesk Tickets via Support API, incl. an incremental export endpoint OAuth 2.0 or API token Per-account limits zenpy 2.0.57
GitHub Repos via git clone, REST/GraphQL APIs for issues/PRs/wikis; archive tarballs PAT, GitHub App, gh CLI ~5,000 req/hr authenticated REST (verify on docs) PyGithub 2.10.0 or plain git

A few SaaS-specific traps worth knowing now:

  • Permissions are part of the content. A SharePoint site's ACL decides who may read each file; if you flatten everything into one corpus you have built a leak. Capture the permission model during enrichment (05.8) and enforce it at query time (Module 12).
  • "Shared with me" ≠ "owned by the workspace". Personal drives and private channels often can't be bulk-exported at all; the audit (Part 5) must record what fraction of the corpus is actually reachable.
  • Exports vs APIs. Slack and Zendesk both offer bulk exports that are far kinder than paginating an API for a full history; Google Takeout produces a one-off archive. For a one-time migration, an export file is a file source (Part 4); for continuous sync, use the API's change feed.
  • Check the platform's current API terms before you design a bulk read. They change. For example, Slack's changelog of 29 May 2025 limited conversations.history and conversations.replies to 1 request per minute and 15 objects per response for new commercially distributed apps that are not in the Slack Marketplace (and new installs of them); Marketplace apps and internal customer-built apps keep the higher limits. A bulk read of history for a RAG corpus therefore goes through the workspace export or an internal app, not a distributed one (source: docs.slack.dev/changelog/2025/05/29/rate-limit-changes-for-non-marketplace-apps, read November 2026; later changes may exist, so re-check).
  • Licences of the client libraries differ from the platforms'. Some convenient community SDKs are copyleft: on PyPI in November 2026 zenpy is GPLv3, extract-msg is GPL and ebooklib is AGPL, while slack-sdk, PyGithub and the cloud SDKs are permissive. A copyleft library inside a closed-source service is a legal question: ask before you ship it, and see the licence discussion in 05.2 for the same trap with PyMuPDF.
  • Service accounts see only what they're granted. A Google service account with no shared-drive membership sees an empty Drive — a classic "the API works but returns nothing" debugging session.

3.6 Email and chat exports#

Email arrives in three file formats, all parseable with the standard library:

Format Standard What it is Python
.eml RFC 5322 (Internet Message Format, 2008) One message: headers + MIME multipart body email stdlib
.mbox / MBOXRD RFC 4155 (application/mbox) Many messages concatenated with From separators mailbox.mbox stdlib
.msg Proprietary (Outlook OLE compound file) Outlook's native format: folders, flags, RTF bodies extract-msg 0.58.1 (Nov 2026) or export to .eml/.mbox via Outlook/Graph
python
# s3_6_read_mbox.py — read an MBOX export with the standard library
import mailbox


def first_text(msg) -> str:
    """Best text body of a message, preferring text/plain over text/html.

    mailbox.mbox yields email.message.Message objects (the compat32 API),
    which have no get_body()/get_content() — those exist only on
    EmailMessage. Walk the MIME parts by hand instead.
    """
    texts = {}
    for part in (msg.walk() if msg.is_multipart() else [msg]):
        if (part.get_content_maintype() == "text"
                and part.get_content_disposition() != "attachment"):
            payload = part.get_payload(decode=True)
            if payload:
                texts[part.get_content_type()] = payload.decode(
                    part.get_content_charset() or "utf-8", "replace")
    return texts.get("text/plain") or next(iter(texts.values()), "")


mbox = mailbox.mbox("data/raw/mail/Support-Export.mbox")
for i, msg in enumerate(mbox):
    if i >= 3:
        break
    print("Subject:", msg.get("Subject"))
    print("From:", msg.get("From"), "| Date:", msg.get("Date"))
    body = first_text(msg)
    print("Body:", " ".join(body.split())[:160] or "(no body)")
    print("---")
mbox.close()
Example output · illustrative4 lines
Subject: Re: order delay
From: customer@example.com | Date: Mon, 27 Oct 2026 09:14:00 +0000
Body: Hi, my order AC-2026-1044 has been "in transit" for nine days...
---

The path in the sample is a placeholder: the Acme corpus contains no mail, so point it at any .mbox file you have (a Gmail Takeout export is one). If the file is missing, mailbox.mbox either raises FileNotFoundError (the folder does not exist) or quietly creates an empty mailbox so the loop prints nothing, so check that the path exists first.

Email bodies need real cleaning before they are useful: quoted replies (> lines, "On … wrote:" blocks), signatures, disclaimers, inline images-as-attachments and HTML-vs-plain dual bodies. 05.5 owns that; the parser's job is to preserve which message and which thread a chunk came from (05.7 covers thread-aware chunking).

Chat exports (Slack, Teams, Discord, WhatsApp, Intercom, Zendesk messaging) are usually JSON or CSV dumps: channels/rooms → messages with author, timestamp, thread ID. The universal pattern: one message is too small to retrieve alone, so chunk by thread or time window rather than per message — but that's 05.7's recipe; here you only need to know the export gives you timestamps and thread IDs worth preserving as metadata.

3.7 APIs and feeds#

Some sources are born as APIs: RSS/Atom feeds, JSON endpoints, webhooks. Feeds are the classic low-volume, high-freshness source — news, changelogs, status pages, blogs.

RSS 2.0 is a de-facto XML standard (spec maintained by the RSS Advisory Board); Atom is the IETF-standardised successor (RFC 4287). feedparser (6.0.14 as of November 2026) parses both into the same object shape:

python
# s3_7_rss_feed.py — parse an RSS or Atom feed
import feedparser

FEED_URL = "https://status.acme.com/feed.xml"
feed = feedparser.parse(FEED_URL)

print("Feed:", feed.feed.get("title"), "| entries:", len(feed.entries))
for e in feed.entries[:3]:
    print("-", e.get("title"), "|", e.get("published") or e.get("updated"))
    print("  ", (e.get("summary") or "")[:120].replace("\n", " "))
Example output · illustrative3 lines
Feed: Acme Status | entries: 4
- Scheduled maintenance complete | Tue, 03 Nov 2026 02:00:00 +0000
   All systems operational. The planned database upgrade finished ahead of schedule...

For feeds, the ingestion rhythm is naturally incremental: store feed.entries[0].published (or the feed's ETag/Last-Modified) as the watermark and only ingest newer entries — the same manifest pattern as everything else.

3.8 Audio, video, code repositories and spreadsheets#

Four source families get brief previews here because later lessons or modules own them:

  • Audio/video → transcripts: meeting recordings, podcasts, support calls. Raw audio means nothing to a text pipeline; you need speech-to-text first (Module 09 owns ASR), then treat the transcript as a text source with timestamps — speaker turns and timestamps become chunk metadata (05.7). Subtitle files (SRT/VTT) are already timed text and need no ASR.
  • Code repositories: git clone (or a tarball) gives you files plus history. Ingestion means choosing which files matter (language detection, .gitignore-style filtering), splitting code at function/class boundaries rather than paragraphs (05.7 has the recipe), and carrying file paths and commit SHA as provenance. 05.3 covers repo handling.
  • Spreadsheets: CSV/TSV/Excel/Parquet are structured sources — they go through 4.3 (rows as documents) or 4.4 (query them live), not the document pipeline. Parquet (pyarrow 26.0.1, Nov 2026) and DuckDB (2.0.0) are the efficient ways to read large ones.
  • Logs and metrics: application logs, audit trails, event streams. Usually semi-structured lines with timestamps — parse to JSONL, then decide per-line vs per-session chunking. Keep them out of the default corpus unless a use case needs them; they're high-volume and low-prose.

3.9 Choosing a connector#

If the source is… Reach it via… Watch out for
A folder you control pathlib walk + hash diff Sync-conflict duplicates, phantom files
A bucket/archive Cloud SDK list+download (boto3, google-cloud-storage, azure-storage-blob) No real folders; versioning; egress cost
A database SQL export → rows-to-text, or CDC for live changes Deletes invisible to polling; schema drift
Public web pages Sitemap → httpx polite fetch → Playwright only if needed robots.txt, ToS, JS rendering, anti-bot
A SaaS app Official API + SDK; bulk export for one-off history Rate limits, permission propagation, "shared with me" gaps
A SaaS app that offers an MCP server Usually query-time access (the agent searches the app live with the user's own permissions: Module 08E owns MCP), not an ingestion pipeline No manifest, lineage or quality gates of your own; latency and rate limits on every question; fine for freshness and per-user permissions, poor for corpus-wide retrieval
Email/chat .eml/.mbox/extract-msg, or platform export Quoted replies, signatures, thread reconstruction
A feed/API feedparser or plain httpx + JSON Watermark management, feed format drift
Audio/video ASR first (Module 09), then text pipeline Cost per hour, diarization, timestamps
Code git clone + file filtering + AST-aware chunking Repo size, generated/vendored files, secrets in history
Spreadsheets/DB tables Rows-to-text or live SQL queries Wide tables, nulls, locale formats

Part 4: Formats — the cheat sheet#

Reference

4.1 The formats cheat sheet#

The single most useful table in this module. "Structure available" means: what the format itself tells you about document structure (headings, tables, pages) before any clever parsing. "Best parser class" is the family of tools that fits — the specific libraries are taught in the lessons named.

Format What it actually is Structure available for free Typical pitfalls Best parser class
Plain text / .txt / .md Characters; Markdown adds light markup Markdown: headings, lists, code fences, (sometimes) tables Encoding (Latin-1 vs UTF-8), hard-wrapped lines, BOM, mojibake pathlib + encoding detection; Markdown → mistune/markdown-it-py (05.3)
HTML / XHTML A DOM tree of elements Real structure: headings, lists, tables, links, lang, metadata Boilerplate (nav/ads/footers), malformed markup, JS-rendered content, relative links httpx fetch → trafilatura/readability-lxml/BeautifulSoup (05.3)
PDF A page-description format: glyphs placed at coordinates — not a document format Almost none guaranteed: no paragraphs, no reading order; sometimes an outline, tags, AcroForm fields, metadata Two-column interleaving, headers/footers, ligatures, font encodings, scanned pages with no text layer, encrypted files Text-layer PDFs → pypdf/pdfplumber/PyMuPDF (05.2); scans → OCR (05.4); hard pages → VLM (03.6)
.docx / .xlsx / .pptx OOXML: a ZIP of XML parts (ISO/IEC 29500, ECMA-376) Styles → headings, real tables, slides, cell values Shared strings, merged cells, formulas vs cached values, tracked changes, headers/footers python-docx, openpyxl, python-pptx, or Pandoc/MarkItDown (05.3)
Legacy Office .doc / .xls / .ppt Proprietary binary formats Varies; often worse than OOXML Binary, fragile, macros LibreOffice headless conversion → then OOXML route (05.3)
EPUB ZIP of XHTML files + OPF manifest + navigation (W3C EPUB 3.3, Jan 2026) Chapters, headings, real XHTML structure DRM (can't parse), nested archives, weird CSS ebooklib 0.21 (Nov 2026) → treat as HTML per chapter
.eml RFC 5322 message: headers + MIME multipart Headers (From/To/Date/Subject), MIME parts HTML+text dual bodies, base64, attachments, charsets stdlib email
.mbox RFC 4155 mailbox of concatenated messages Message boundaries + per-message headers >From quoting escapes, giant files (stream it) stdlib mailbox.mbox
.msg Proprietary Outlook OLE file Folders, flags, RTF bodies, attachments Binary, needs a dedicated lib or export extract-msg 0.58.1 (Nov 2026)
JSON / JSONL Self-describing text; schema varies per source Keys and nesting are the structure Schema drift, deeply nested objects, one bad line kills JSONL stdlib json; ijson 3.6.0 for huge files
CSV / TSV Delimited rows Columns by position + header row Quoting, embedded newlines, encoding, delimiter sniffing, locale decimals stdlib csv (or pandas for scale)
Parquet Columnar binary (Apache Parquet) Typed columns, schema in footer Needs a reader (pyarrow/DuckDB); not human-editable pandas/pyarrow/DuckDB → then rows-to-text
XML Hierarchical elements with namespaces Real tree structure Namespaces, DTD/entity attacks (XXE), huge docs, schema-less ambiguity defusedxml/lxml (never naive xml.etree on untrusted input)
Logs Semi-structured lines, usually timestamped Timestamps, levels, maybe JSON Multi-line stack traces, clock skew, high volume Line parser → JSONL; structured logging preferred
Archives .zip / .tar / .tar.gz / .gz Container of mixed files (OOXML/EPUB are zips too — they have their own row) Whatever the members contain Nested archives, zip bombs, member-path loss, encrypted members Unpack with limits → route each member through the parser registry (05.3)
Images (PNG/JPEG/TIFF) Pixels None — needs interpretation Resolution, rotation, handwriting, tables-as-images OCR engines or VLMs (05.4, Module 09)
Audio / video Waveforms / compressed media Container metadata, maybe subtitles No text at all without ASR Speech-to-text → transcript text (Module 09)

Two takeaways from the table. First, the extension lies: .pdf can be a text-layer document or a photo of one; .docx is really a zip; a file named .csv may be UTF-16 with semicolons. Detect by content (magic bytes via the filetype package, 1.2.0 as of November 2026, or file(1)) when it matters — 05.3 builds a registry that does exactly this. Second, "best parser class" is a decision, not a library: the lessons in this module each end with a decision table mapping document types to tools for this reason.

4.2 Structured vs semi-structured vs unstructured#

The classic data taxonomy, with LLM-specific meaning:

Kind Definition Examples How an LLM system handles it
Structured Fixed schema, typed fields, queryable SQL tables, CSV, Parquet, JSON with a stable schema, CRM records Two routes: flatten to text for retrieval (4.3) or query live via text-to-SQL/tools (4.4)
Semi-structured Structure present but inconsistent or nested JSONL logs, emails, tickets exports, XML feeds, Markdown docs, chat logs Parse into blocks/fields, preserve the parts that carry meaning, normalise the rest
Unstructured Free prose, layout-dependent PDFs, scanned documents, web pages, office docs, transcripts, images Parse → clean → chunk; structure must be recovered (headings, tables, reading order) — this is most of this module

4.3 Turning rows into text#

Structured data becomes retrievable text in three patterns. Choosing between them is one of the highest-leverage decisions in the whole module, because it determines what the assistant can say.

Pattern 1: row-as-document. Each row becomes one retrievable document. Right when rows are the natural unit of question ("what's the price of SKU X?", "what did ticket T-1002 say?") and rows are small enough to embed well.

Pattern 2: template rendering. Same idea, but you control the phrasing: a template turns fields into a sentence or short paragraph that reads naturally and embeds better than raw key-value dumps. Fields that matter get mentioned explicitly; nulls get handled deliberately.

Pattern 3: entity-centric documents. Group rows by the entity a user asks about — one document per customer containing all their orders, one per product containing its price history and specs. Right when questions are entity-shaped ("tell me about customer X") and the per-entity volume is bounded.

Here's the row-as-document + template pattern in code, run against the running corpus's tickets and pricing files:

python
# s4_3_row_to_text.py — turn JSONL tickets and CSV products into documents
import csv
import json
import string
from pathlib import Path


def row_to_text(row: dict, template: str) -> str:
    """Fill {field} placeholders; missing fields render as ''."""
    fields = {f for _, f, _, _ in string.Formatter().parse(template) if f}
    return template.format_map({k: row.get(k, "") for k in fields})


TICKET_TEMPLATE = """\
Support ticket {id} ({status}, opened {created})
Customer: {customer}
Subject: {subject}"""

PRODUCT_TEMPLATE = """\
{sku} — {name}
Price: ${price_usd} | In stock: {stock} units
Category: power tools"""


def tickets_as_docs(path: Path) -> list[str]:
    return [row_to_text(json.loads(line), TICKET_TEMPLATE)
            for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]


def products_as_docs(path: Path) -> list[str]:
    with path.open(newline="", encoding="utf-8") as f:
        return [row_to_text(row, PRODUCT_TEMPLATE) for row in csv.DictReader(f)]


if __name__ == "__main__":
    base = Path("data/corpus")
    for d in tickets_as_docs(base / "tickets/tickets.jsonl"):
        print(d, "\n---")
    for d in products_as_docs(base / "finance/pricing.csv"):
        print(d, "\n---")
Output · this one is real — pure Python, no model, no network20 lines
Support ticket T-1001 (open, opened 2026-10-28)
Customer: A. Okafor
Subject: Drill housing cracked
---
Support ticket T-1002 (resolved, opened 2026-10-29)
Customer: L. Fischer
Subject: Wrong item delivered
---
Support ticket T-1003 (open, opened 2026-10-30)
Customer: M. Tanaka
Subject: Where is my order?
---
AC-101 — Cordless Drill
Price: $129.00 | In stock: 45 units
Category: power tools
---
AC-102 — Socket Set
Price: $79.00 | In stock: 112 units
Category: power tools
---

When rows are wide (hundreds of columns) or deeply nested, don't flatten blindly: summarise the shape ("this table has 40 columns; key fields are X, Y, Z") and keep the full row queryable. That leads to the alternative:

4.4 When not to chunk at all: text-to-SQL and direct queries#

Sometimes the right ingestion is no ingestion: leave the data in the database and let the model query it. The pattern (taught properly in Module 08A) gives the model the table schemas plus a run_sql tool; at answer time it writes SELECT … WHERE sku = 'AC-101' and your code executes it read-only. Use this when:

  • Questions need aggregation or joins ("total revenue by region last quarter") that no fixed chunk set can answer;
  • The data is too big or too fresh to mirror into a corpus (a live inventory, a transactions table);
  • Answers must be exact — a price or a count should come from the database, not from an embedding's memory of a rendered row.

The trade-offs are real: text-to-SQL is less reliable than retrieval for prose questions, needs careful read-only permissions and query guardrails (Module 12), and fails differently (bad SQL, not bad chunks). The mature answer is often both: chunk the documentation about the data (catalogue descriptions, schema docs) for retrieval, and expose the data itself through a query tool for facts. Module 08A owns the tool-calling mechanics; Module 07 owns when retrieval beats querying.


Part 5: The corpus audit#

Before choosing parsers, before writing a single line of pipeline code, you audit. The audit is a structured investigation with eight questions; each has a concrete artefact you produce. It is half an hour of work on a toy corpus and days of work on a real one — and it is the difference between an ingestion project that lands and one that gets rebuilt in month three.

5.1 The eight questions#

# Question What you produce Why it matters
1 What is actually there? Inventory: file counts, sizes, extensions, folder breakdown Reveals the real format mix (often different from what people claim)
2 What do the files contain? Sample-and-eyeball notes per format Extensions lie; only reading reveals scans, tables, languages, damage
3 What must the system answer? The questions document (5.4) Defines coverage; everything else serves it
4 What's missing or broken? Coverage-gap list Unparseable formats, empty files, missing dates, unsupported languages
5 What's sensitive? Sensitive-content inventory PII, secrets, licensed material, HR/medical data — shapes cleaning and access rules
6 Who owns it and may we use it? Licence/permission record per source Legal exposure; also reveals which sources are unreachable
7 Who may see what? ACL requirements per source Drives metadata design (05.8) and leak prevention (Module 12)
8 How fresh must it be? Freshness SLA per source Drives batch vs incremental vs streaming (2.2)

5.2 Question 1: inventory it#

Counts, sizes, extensions, duplicates, date ranges — mechanically, with a script. Here is a complete, standard-library-only audit script. It walks a directory, counts files by extension and size, detects exact duplicates by SHA-256, guesses text vs binary by the null-byte heuristic, and reports per-folder breakdowns (files sitting loose in the root are bucketed under (root) so they don't masquerade as one-file "folders"):

python
# s5_2_audit_corpus.py — inventory a corpus directory (pure stdlib)
import hashlib
import sys
from collections import defaultdict
from pathlib import Path


def is_probably_text(data: bytes, sample: int = 8192) -> bool:
    """Null-byte heuristic on the first `sample` bytes of file content."""
    return b"\x00" not in data[:sample]


def audit(root: Path) -> dict:
    by_ext = defaultdict(lambda: [0, 0])   # ext -> [count, bytes]
    by_dir = defaultdict(lambda: [0, 0])   # top folder -> [count, bytes]
    hashes = defaultdict(list)             # sha256 -> [relpaths]
    mtimes = []
    text_files = binary_files = 0

    for p in sorted(root.rglob("*")):
        if not p.is_file():
            continue
        try:
            data = p.read_bytes()          # read once: sniff + hash share it
        except OSError:
            continue                        # phantom file: vanished mid-walk
        size = len(data)
        ext = p.suffix.lower() or "(none)"
        by_ext[ext][0] += 1
        by_ext[ext][1] += size
        rel = p.relative_to(root)
        top = rel.parts[0] if len(rel.parts) > 1 else "(root)"
        by_dir[top][0] += 1
        by_dir[top][1] += size
        mtimes.append(p.stat().st_mtime)
        if is_probably_text(data):
            text_files += 1
        else:
            binary_files += 1
        h = hashlib.sha256(data).hexdigest()
        hashes[h].append(str(rel))

    dups = {h: ps for h, ps in hashes.items() if len(ps) > 1}
    return dict(by_ext=by_ext, by_dir=by_dir, dups=dups, mtimes=mtimes,
                text=text_files, binary=binary_files)


def fmt_bytes(n: int) -> str:
    for unit in ("B", "KiB", "MiB", "GiB"):
        if n < 1024 or unit == "GiB":
            return f"{n} B" if unit == "B" else f"{n:.1f} {unit}"
        n /= 1024


def main(root: Path):
    r = audit(root)
    total = sum(c for c, _ in r["by_ext"].values())
    total_b = sum(b for _, b in r["by_ext"].values())
    print(f"AUDIT: {root}")
    print(f"files: {total}  ({r['text']} text-like, {r['binary']} binary-like)")
    print(f"total size: {fmt_bytes(total_b)}")
    if r["mtimes"]:
        import datetime
        lo = datetime.datetime.fromtimestamp(min(r["mtimes"])).date()
        hi = datetime.datetime.fromtimestamp(max(r["mtimes"])).date()
        print(f"mtime range: {lo} .. {hi}")
    print("\nby extension:")
    for ext, (c, b) in sorted(r["by_ext"].items(), key=lambda kv: -kv[1][1]):
        print(f"  {ext:<12} {c:>4} files  {fmt_bytes(b):>10}")
    print("\nby top-level folder:")
    for d, (c, b) in sorted(r["by_dir"].items()):
        print(f"  {d:<15} {c:>4} files  {fmt_bytes(b):>10}")
    print(f"\nexact duplicates (sha256): {len(r['dups'])} groups")
    for paths in r["dups"].values():
        print(f"  {paths[0]}  ==  {', '.join(paths[1:])}")


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path("data/corpus"))

Run it against the running corpus (Part 8 generates it). Output — real, captured from an actual run:

text
AUDIT: data/corpus
files: 14  (10 text-like, 4 binary-like)
total size: 210.2 KiB
mtime range: 2026-11-05 .. 2026-11-05

by extension:
  .png            3 files   202.0 KiB
  .pdf            2 files     5.2 KiB
  .html           4 files     1.4 KiB
  .docx           1 files      1018 B
  .jsonl          1 files       364 B
  .txt            2 files       276 B
  .csv            1 files        85 B

by top-level folder:
  contracts          4 files   202.7 KiB
  finance            1 files        85 B
  handbook           1 files     4.5 KiB
  help-centre        4 files     1.4 KiB
  policies           1 files      1018 B
  tickets            1 files       364 B
  transcripts        2 files       276 B

exact duplicates (sha256): 0 groups

Already this tiny audit tells you things: the contracts folder is 96% of the bytes (the PNG "scans"), the help centre is the only HTML source, and there are no exact duplicates — so dedup work here is about near-duplicates, which 05.5 covers. On a real corpus the same script surfaces the things that kill projects: a folder of 8,000 .msg files nobody knew about, 40% of "PDFs" that are actually scans (the text/binary split hints at this), or thousands of sync-conflict duplicates.

5.3 Question 2: sample and eyeball#

Numbers tell you what; only eyes tell you what it means. The method:

  1. Stratified sample: for each (folder × extension) group, take 3–10 files — more for formats you don't know, fewer for homogeneous ones. Aim for ~1% of files or ~50 files per stratum, whichever is larger, capped at what you can actually read.
  2. Open them in their native apps, not just extract text: look at the PDF page (is it a scan? two columns? a table?), the spreadsheet sheet tabs (hidden sheets? formulas?), the email thread (quoted history?).
  3. Fill a one-line-per-stratum note: "contracts/*.pdf — 60% born-digital invoices, 40% scans of signed agreements, one encrypted, dates in DD/MM/YYYY". These notes become the parser-selection evidence for 05.2–05.4.

5.4 The questions document and the coverage matrix#

Question 3 is the one freshers skip and seniors never do. Before ingestion, write down the questions the system must answer — 20–50 realistic user questions, in users' own words. Then build the coverage matrix: for each question, which source(s) contain the answer, in what format, how fresh it must be, and who may see it.

Worked example on the running corpus:

User question Answer lives in Format Freshness needed Audience
"What's the price of the Cordless Drill?" finance/pricing.csv + handbook/product-handbook.pdf CSV + PDF Daily (prices change) All staff
"What's our return policy?" help-centre/returns.html + policies/ HTML + DOCX Weekly Customers (public)
"What did Northwind agree to pay us?" contracts/vendor-agreement.pdf PDF (+scans) On change Finance only
"Why was order AC-2026-1044 delayed?" tickets/tickets.jsonl JSONL Hourly Support team
"What did we decide about autumn sourcing?" transcripts/*.txt Text On meeting Buying team

The matrix immediately exposes gaps: if "return policy" answers live in both the public help centre and an internal policy docx that contradict it, you have story three (1.1) waiting to happen — resolve which is authoritative now, not at debug time. It also sizes the ACL problem: contracts are finance-only, so their chunks need permission metadata before they can be embedded alongside public pages.

5.5 Questions 5–8: sensitivity, licences, permissions, freshness#

The last four audit questions are judgement calls, and they gate everything downstream:

  • Sensitive content (05.5 owns detection): scan samples for PII (names, emails, ID numbers, health/financial data), credentials (API keys pasted into docs are shockingly common), and confidential business data. Record where it lives — it decides whether chunks need redaction before embedding, and whether the source may go to a third-party model at all (02.9 Part 9 covers provider data handling; Module 12 goes deep).
  • Licences and terms: for every source, record who owns it, what licence/contract covers use, and whether AI processing is permitted. Internal docs you own are easy; scraped web content, licensed datasets and customer data each have terms. Not legal advice — flag anything ambiguous to whoever owns the risk.
  • Permissions: the audit must answer "can we even read all of it?" — service accounts, API scopes, site memberships. A corpus you can only half-read is a different product than the one you imagined; record the reachable fraction per source.
  • Freshness: per source, how stale is acceptable? A pricing CSV wants hourly; a handbook wants weekly; contracts change on signature. This feeds the rhythm decision (2.2) and the SLA you can promise users.

The audit's output is a short audit report (markdown is fine): the inventory tables, the sample notes, the questions document, the coverage matrix, and a go/no-go per source. File it next to the code — it is the first lineage artefact of the project.


Part 6: Lineage and provenance#

Deep-dive

6.1 The chain every chunk must carry#

Lineage is the answer to the question you will ask at 2 a.m.: "where did this text come from, and which version of our code produced it?" Every chunk in your index should be traceable backwards through every transformation:

flowchart LR
    S["Source object<br/>(bucket key / URL / row id)"] --> F["Fetch run<br/>(when, by which connector)"]
    F --> P["Parse run<br/>(parser + version, warnings)"]
    P --> C["Clean version<br/>(rules + version)"]
    C --> H["Chunk<br/>(strategy + config version, position)"]
    H --> E["Enrich<br/>(metadata + model versions)"]
    E --> V["Vector + index entry"]

Concretely, a chunk's metadata should let you answer: which file/URL/row did this come from; which version of that source (content hash, ETag, modified date); which page and bounding box inside it; which parser name and version produced the text; which cleaning rules and chunker config were applied; which embedding model wrote the vector. 05.8 designs the full DocumentMeta/ChunkMeta schema for exactly this; 05.9 records the run IDs that tie a whole batch together.

6.2 Why it earns its keep#

  • Citations: the UI can show "Product Handbook, page 14, §3.2" because the chunk remembers its page — the difference between a trustworthy answer and a suspicious one (Module 07).
  • Debugging: a wrong answer traces back through chunk → parse → source in minutes instead of days. Story one (1.1) is only diagnosable because the flattened table is visible in the parse output.
  • Re-processing: when you upgrade a parser or change chunking, lineage tells you exactly which chunks are stale and must be rebuilt — the foundation of incremental updates (05.9).
  • Compliance: a deletion request ("remove this customer's data") must reach raw files, parsed docs, chunks, vectors and caches — only possible if every artefact knows its source (Module 12).
  • Evaluation: Module 10A needs to know which documents an eval question targets; lineage provides the join key.

The rule of thumb: if you can't trace a chunk back to its source bytes, you haven't finished ingesting it. Store the raw bytes immutably (data/raw/), hash them, and let every downstream artefact point at the hash.


Part 7: Build vs buy#

7.1 The options landscape#

Ingestion tooling sits on a spectrum from "your code, your bugs" to "a vendor's black box". As of November 2026 the honest landscape:

Option Examples (verified on PyPI/docs, Nov 2026) What it gives you What it hides / costs
Hand-rolled (stdlib + focused libs) pathlib, httpx, csv, json, mailbox + per-format parsers Total control, no lock-in, you learn every failure mode You own every edge case; slowest to cover many formats
Document-parsing frameworks Docling 2.147.0, Unstructured 0.27.36, MarkItDown 0.1.9, LlamaParse (hosted), Mistral OCR (hosted), plus the open-weight OCR and document-VLM family in 05.4 One call → Markdown/JSON for many formats; layout-aware models Opaque internals, version churn, licence traps (PyMuPDF is AGPL/commercial — 05.2), per-page costs on hosted ones
Connector/ETL platforms Airbyte-style connectors, Fivetran-style ELT, managed crawlers (Firecrawl, Crawl4AI Cloud: 3.4) Hundreds of pre-built sources with sync state Another system to run; connector quirks you didn't choose; data leaves your perimeter
App frameworks' loaders LlamaIndex 0.14.25, LangChain 1.5.0 (langchain-community 0.4.2 is sunset and archived: prefer partner packages or your own loader, see 08F.4, 3.7), Haystack 3.4.1 SimpleDirectoryReader-style ingestion, node graphs, integrations They decide parsing defaults for you; upgrades can silently change output; you still need the audit
Vector DB built-in ingestion Managed "upload folder → index" features in Pinecone/Qdrant-cloud style services Zero pipeline code Least control over chunking/metadata/provenance — the things this module exists to teach
Managed document AI Cloud Document AI / Document Intelligence / Textract (pattern level; 05.4 covers) Best-in-class OCR/layout at scale Per-page pricing, vendor lock-in, documents leave your infra

7.2 What they give vs what they hide#

The frameworks are genuinely useful — nobody should hand-roll an HTML parser or a SharePoint delta sync from scratch. But they hide exactly the decisions this module teaches:

  • A loader that "handles PDFs" still has to choose which PDF engine, how to treat tables, and what metadata to keep — and its defaults will be wrong for some of your documents.
  • A managed indexer's chunking is a black box; when retrieval quality drops you can't inspect why.
  • Every framework adds a dependency surface that must be version-pinned, monitored and occasionally debugged through someone else's abstractions.

The mature position (and the one this module takes): use libraries for the mechanical parts — parsing engines, HTTP clients, format converters — and keep the pipeline's decisions (chunking, metadata, dedup, provenance, quality gates) in code you own and can test. That is also why 05.9 builds the pipeline in plain Python first and only then shows an orchestrator version.

7.3 When to hand-roll#

Hand-roll (or keep control of) when: the corpus is small-to-medium; formats are heterogeneous enough that no framework covers them all; correctness/provenance requirements are strict (regulated data, citations); or you're learning — which is always, in this module. Buy/use a framework when: you need 50 SaaS connectors on day one, your team has no data-engineering capacity, or time-to-first-index matters more than control. Most production systems end up hybrid: framework loaders for the boring 80% of sources, custom stages for the documents that matter.


Part 8: The module project and the running corpus#

8.1 Project layout#

Everything in this lesson lives in the data-pipeline project from Setup:

text
data-pipeline/
├── pyproject.toml          # deps + dependency-groups
├── .env                    # keys for later lessons (never committed)
├── data/
│   ├── raw/                # source bytes, immutable
│   ├── corpus/             # the running corpus (generated, Part 8.2)
│   ├── parsed/             # ParsedDocument JSONL
│   ├── chunks/             # chunk JSONL
│   └── exports/
├── scripts/
│   └── make_corpus.py      # generates data/corpus/
├── s3_2_list_and_download.py   # the runnable samples live at root,
├── s3_4_polite_fetch.py        # like Module 03 — each is self-contained
├── s3_4b_markdown_negotiation.py
├── s3_5_rendered_fetch.py
├── s3_6_read_mbox.py
├── s3_7_rss_feed.py
├── s4_3_row_to_text.py
└── s5_2_audit_corpus.py        # the Part 5 inventory script

Dependency groups (from Setup) keep installs lean: uv sync --group web for the fetch lessons, --group files for office formats, --group storage for the cloud SDKs, --group office-extra for the parsing front-doors, --group dev for pytest. A later lesson that adopts this layout adds its parser libraries to these groups and says so in its own Setup.

8.2 The running corpus: Acme#

To keep the module's lessons coherent, they share one fictional corpus: Acme, a power-tools company — the same company the sibling lessons' examples use — with an internal knowledge base and a customer-facing help site. It deliberately contains one of everything this module teaches:

Path Contents What it exercises
handbook/product-handbook.pdf 5-section catalogue/pricing handbook, text-layer PDF PDF parsing, headings, tables, structure-aware chunking (05.2, 05.6)
help-centre/*.html 4 help pages sharing one template (nav + footer) Boilerplate removal, HTML→text, metadata (05.3, 05.5)
tickets/tickets.jsonl Support tickets as JSON lines Semi-structured rows→text (4.3), entity-centric chunking
contracts/*.pdf, contracts/scan-*.png Vendor agreements: text PDFs + "scanned" images Scan detection, OCR routing, ACL metadata (05.2, 05.4, 05.8)
transcripts/*.txt Meeting transcripts with [HH:MM:SS] Speaker: turns Speaker turns, timestamps, time-window chunking (05.7)
finance/pricing.csv (+pricing.xlsx) Product/price/stock table Structured→text decision, wide-table handling (4.3, 4.4)
policies/remote-work-policy.docx Styled policy document OOXML parsing, heading styles (05.3)

make_corpus.py generates the whole thing with the standard library only — no dependencies, safe to run anywhere. It contains miniature writers for the three binary formats (a minimal valid PDF, a real .docx zip, a small PNG) so the corpus has genuine file types, not just .txt files with misleading names:

python
# scripts/make_corpus.py — generate the toy running corpus (pure stdlib)
import json
import zipfile
import zlib
import struct
import io
import random
from pathlib import Path

ROOT = Path("data/corpus")


def w(rel, text):
    p = ROOT / rel
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(text, encoding="utf-8")
    print(f"wrote {p}")


def wp(rel):
    """Parent dir for a binary file; the writer does the writing."""
    p = ROOT / rel
    p.parent.mkdir(parents=True, exist_ok=True)
    return p


# --- minimal file writers (real formats, toy content) ---

def write_pdf(path, lines):
    """Minimal single/multi-page PDF with a text layer."""
    def esc(s):
        return s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")

    objects = []
    n_pages = max(1, (len(lines) + 45) // 46)
    kids = " ".join(f"{4 + 2 * i} 0 R" for i in range(n_pages))
    objects.append(b"<< /Type /Catalog /Pages 2 0 R >>")
    objects.append(f"<< /Type /Pages /Kids [{kids}] /Count {n_pages} >>".encode())
    objects.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")

    for p in range(n_pages):
        chunk = lines[p * 46:(p + 1) * 46]
        stream_lines = ["BT", "/F1 11 Tf", "50 780 Td", "14 TL"]
        for ln in chunk:
            stream_lines.append(f"({esc(ln)}) Tj T*")
        stream_lines.append("ET")
        # latin-1 can't encode characters like "—": "replace" would turn
        # them into "?" in extracted text, so keep generated lines ASCII.
        stream = "\n".join(stream_lines).encode("latin-1", "replace")
        page_num = 4 + 2 * p
        objects.append(
            f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
            f"/Resources << /Font << /F1 3 0 R >> >> /Contents {page_num + 1} 0 R >>".encode()
        )
        objects.append(b"<< /Length " + str(len(stream)).encode()
                       + b" >>\nstream\n" + stream + b"\nendstream")

    out = io.BytesIO()
    out.write(b"%PDF-1.4\n")
    offsets = [0]
    for i, body in enumerate(objects, start=1):
        offsets.append(out.tell())
        out.write(f"{i} 0 obj\n".encode() + body + b"\nendobj\n")
    xref_pos = out.tell()
    out.write(f"xref\n0 {len(objects) + 1}\n".encode())
    out.write(b"0000000000 65535 f \n")
    for off in offsets[1:]:
        out.write(f"{off:010d} 00000 n \n".encode())
    out.write(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
              f"startxref\n{xref_pos}\n%%EOF\n".encode())
    path.write_bytes(out.getvalue())


def write_docx(path, paragraphs):
    """Minimal valid .docx: a zip of OOXML parts."""
    body = "".join(f'<w:p><w:r><w:t xml:space="preserve">{p}</w:t></w:r></w:p>'
                   for p in paragraphs)
    document = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
        f"<w:body>{body}</w:body></w:document>")
    content_types = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
        '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
        '<Default Extension="xml" ContentType="application/xml"/>'
        '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
        "</Types>")
    rels = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
        '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>'
        "</Relationships>")
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml", content_types)
        z.writestr("_rels/.rels", rels)
        z.writestr("word/document.xml", document)


def write_png(path, width=320, height=200, seed=0):
    """Small deterministic 'scan-like' PNG (grey noise + dark smudges)."""
    rng = random.Random(seed)
    raw = bytearray()
    for y in range(height):
        raw.append(0)
        for x in range(width):
            v = 200 + rng.randint(-30, 30)
            if 60 < y < 160 and (x * 7 + y * 13) % 23 == 0:
                v = 60
            raw += bytes((v, v, v))

    def chunk(tag, data):
        c = tag + data
        return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c))

    png = (b"\x89PNG\r\n\x1a\n"
           + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
           + chunk(b"IDAT", zlib.compress(bytes(raw)))
           + chunk(b"IEND", b""))
    path.write_bytes(png)


# --- the corpus itself ---

def main():
    lines = ["ACME PRODUCT HANDBOOK", ""]
    for section in range(1, 6):
        lines.append(f"SECTION {section}: CATALOGUE AND PRICING")
        for i in range(1, 12):
            lines.append(f"Item {section}-{i}: Acme Cordless Drill. "
                         f"Price: ${section * 10 + i}. SKU AC-{section}{i:02d}.")
        lines.append("")
    write_pdf(wp("handbook/product-handbook.pdf"), lines)
    print("wrote", wp("handbook/product-handbook.pdf"))

    for slug, title, body in [
        ("shipping", "Shipping Policy",
         "We ship worldwide within 2-5 business days. Free shipping over $75."),
        ("returns", "Returns and Refunds",
         "Unused items may be returned within 30 days for a full refund."),
        ("bit-sizes", "Bit Size Guide",
         "Match the bit to the screw head — metric and imperial sizes are marked on the packaging."),
        ("warranty", "Warranty",
         "All Acme products carry a two-year warranty against defects."),
    ]:
        w(f"help-centre/{slug}.html", f"""<!doctype html>
<html><head><title>{title} — Acme Help</title></head>
<body>
<nav><a href="/">Home</a> | <a href="/shipping">Shipping</a> | <a href="/returns">Returns</a></nav>
<h1>{title}</h1><p>{body}</p>
<footer>© Acme. All rights reserved.</footer>
</body></html>""")

    tickets = [
        {"id": "T-1001", "customer": "A. Okafor", "subject": "Drill housing cracked",
         "status": "open", "created": "2026-10-28"},
        {"id": "T-1002", "customer": "L. Fischer", "subject": "Wrong item delivered",
         "status": "resolved", "created": "2026-10-29"},
        {"id": "T-1003", "customer": "M. Tanaka", "subject": "Where is my order?",
         "status": "open", "created": "2026-10-30"},
    ]
    (ROOT / "tickets").mkdir(parents=True, exist_ok=True)
    with open(ROOT / "tickets/tickets.jsonl", "w", encoding="utf-8") as f:
        for t in tickets:
            f.write(json.dumps(t) + "\n")
    print("wrote", ROOT / "tickets/tickets.jsonl")

    for i in range(1, 4):
        write_png(wp(f"contracts/scan-{i:03d}.png"), seed=i)
        print("wrote", wp(f"contracts/scan-{i:03d}.png"))
    write_pdf(wp("contracts/vendor-agreement.pdf"),
              ["VENDOR AGREEMENT", "Acme and Northwind Supplies.",
               "Term: 24 months. Payment: net 30."])
    print("wrote", wp("contracts/vendor-agreement.pdf"))

    w("transcripts/2026-10-27-sourcing.txt",
      "[00:00:12] Priya: Let's review the autumn sourcing plan.\n"
      "[00:01:05] Marcus: Northwind can deliver by November 15.\n"
      "[00:02:30] Priya: Good. I'll update the purchase order.")
    w("transcripts/2026-10-30-pricing.txt",
      "[00:00:05] Dana: Competitor prices dropped 8 percent.\n"
      "[00:01:12] Marcus: We keep our prices; revisit in Q1.")

    w("finance/pricing.csv",
      "sku,name,price_usd,stock\n"
      "AC-101,Cordless Drill,129.00,45\nAC-102,Socket Set,79.00,112\n")
    try:
        import openpyxl
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.append(["sku", "name", "price_usd", "stock"])
        ws.append(["AC-101", "Cordless Drill", 129.00, 45])
        ws.append(["AC-102", "Socket Set", 79.00, 112])
        wb.save(wp("finance/pricing.xlsx"))
        print("wrote", wp("finance/pricing.xlsx"), "(openpyxl)")
    except ImportError:
        print("openpyxl not installed: skipped pricing.xlsx")

    write_docx(wp("policies/remote-work-policy.docx"),
               ["ACME — REMOTE WORK POLICY",
                "Employees may work remotely up to three days per week.",
                "All remote workers must use the company VPN."])
    print("wrote", wp("policies/remote-work-policy.docx"))
    print(f"corpus written under {ROOT}/")


if __name__ == "__main__":
    main()

Common misconceptions#

Misconception Reality
"The model will figure out the right answer from messy text." Models are fluent, not forensic. A flattened table produces a confident wrong association, not an error message. Structure must survive parsing.
"PDF is a document format." It's a page-description format: glyphs at coordinates. There's no paragraph, no reading order, no guaranteed table — that's why 05.2 exists.
"If the file has a .pdf extension, it's a PDF." Extensions lie constantly: .docx is a zip, a .csv can be UTF-16 semicolon-delimited, and a "PDF" can be a scan with no text layer. Detect by content when it matters.
"robots.txt is a law." It's a protocol for crawlers (RFC 9309). Ignoring it won't sue you, but it gets you blocked and can violate terms of service — and scraping paywalled/licensed content is a legal problem regardless.
"More data is always better." Duplicates, boilerplate and stale documents actively hurt: they flood retrieval, contradict fresh facts and leak across permissions. Audit before you ingest.
"LlamaIndex/LangChain ingestion replaces this module." Loaders cover the mechanical 80%; they still make chunking, metadata, dedup and provenance decisions for you — usually badly for your specific corpus. Use them, but own the decisions.
"Chunk first, clean later." Cleaning after chunking means chunks baked from dirty text stay dirty; every rule needs a reason and a test (05.5). The pipeline order is fixed: parse → clean → chunk.
"A database table should be chunked like a document." Rows have a schema; flattening them into prose loses the ability to query exactly. Choose row-as-document, template, entity-centric — or skip ingestion and use text-to-SQL (4.3, 4.4).
"Incremental ingestion is an optimisation you add later." It's an architecture decision: it needs a manifest, content hashes and delete propagation from day one. Bolting it on means re-deriving all of it (05.9).
"Sending the PDF to a multimodal model solves parsing." It solves some parsing, expensively and with hallucination risk on dense tables — and it bypasses provenance (no page-level text to cite). It's one tool in the toolbox, not the pipeline (03.6, 05.2).
"Headless browsers are just a faster httpx." They're 100× slower, heavy, detectable by anti-bot systems, and only for JS-rendered pages that have no API or plain-HTML alternative. Use them last.

Key takeaways#

  • LLM systems fail silently on bad data: wrong prices from flattened tables, stale policies outranking new ones, boilerplate flooding retrieval. The model is rarely the problem — the pipeline is.
  • Every source flows through nine stages: discover → fetch → parse → clean → chunk → enrich → embed → index → serve. This module owns the first six; Module 06 owns embed/index; Module 07 owns serve.
  • Choose the ingestion rhythm deliberately: full batch for small/static corpora, incremental batch (scheduled diff + manifest) as the production default, streaming only for seconds-level freshness.
  • Every source type has an access pattern: local walks, object-store list+download, SQL exports or CDC, polite web crawling (robots.txt RFC 9309, sitemaps, conditional requests, Playwright last), SaaS APIs with rate limits, email/chat exports, feeds. The SaaS table in 3.5 names verified SDKs.
  • The formats cheat sheet (4.1) is the module's most-referenced table: structure available, pitfalls, best parser class — per format.
  • On the web, try the cheapest honest route first: official API or feed, then a Markdown twin (/llms.txt, Accept: text/markdown), then plain httpx plus extraction, then a hosted or self-hosted LLM-ready crawler, and Playwright last. Hosted crawlers add a data-processing party and do not remove robots.txt or terms-of-service duties.
  • Structured data has three routes to text: row-as-document, template rendering, entity-centric documents — or no ingestion at all via text-to-SQL.
  • Audit before you build: inventory, sample-and-eyeball, the questions document, coverage matrix, sensitive content, licences, permissions, freshness. The runnable s5_2_audit_corpus.py does the mechanical half.
  • Every chunk must carry lineage back to source bytes, version, page and parsing run — it's what makes citations, debugging, re-processing and deletion requests possible.
  • Use libraries for mechanics, own the decisions: frameworks (LlamaIndex, LangChain, Haystack) and managed ingestion are tools, not replacements for understanding the pipeline.
  • The module shares one running corpus — Acme — generated by a pure-stdlib make_corpus.py; the sibling lessons' examples use the same company.

Terms introduced in this lesson#

Term One-line definition
Ingestion pipeline The nine-stage flow turning raw sources into retrievable, citable text: discover → fetch → parse → clean → chunk → enrich → embed → index → serve
Garbage in, garbage out The principle that system quality is bounded by input quality — made expensive by LLMs' fluent wrongness
ParsedDocument The structured intermediate representation (pages, blocks, tables, provenance) that parsing produces and later stages consume — defined fully in 05.2
Boilerplate Repeated template text (nav, footers, disclaimers) that carries no per-page meaning and floods retrieval if kept
Idempotency Running a stage twice on the same input yields the same output, not duplicates
Failure isolation One bad document fails alone; the run continues and reports it
Batch / incremental / streaming ingestion Whole-corpus re-runs / change-detected partial re-runs / event-driven per-item processing
Manifest / state store The record of what was ingested, its hashes and versions — the basis of incremental updates (05.9)
Watermark The "processed up to here" marker (timestamp, ID, feed date) for incremental sources
Tombstone A record that a source item was deleted, so its chunks can be removed
Change data capture (CDC) Reading a database's transaction log to learn inserts/updates/deletes in order
Delta query An API pattern returning only items changed since a token (SharePoint, Drive Changes)
robots.txt / Robots Exclusion Protocol The site-published file (RFC 9309) telling crawlers which paths they may fetch
Sitemap XML index of a site's URLs, often with lastmod dates — the polite discovery mechanism
Conditional request ETag/If-None-Match or Last-Modified/If-Modified-Since fetches that get 304 Not Modified for unchanged content
Headless browser A real browser driven by script (Playwright) for JS-rendered pages
Content negotiation The client states preferred representations in the Accept header (for example text/markdown) and the server answers with the best one it has, signalled by Content-Type and Vary: Accept
LLM-ready crawler A library or hosted service (Crawl4AI, Firecrawl, Jina Reader) that fetches pages, renders JavaScript and returns Markdown; its output is a parse result to be versioned and checked like any other
OOXML Office Open XML: .docx/.xlsx/.pptx as ZIP packages of XML (ISO/IEC 29500, ECMA-376)
Semi-structured data Data with real but inconsistent or nested structure (JSONL, emails, logs)
Row-as-document One database row → one retrievable document
Template rendering Turning row fields into a controlled natural-language document
Entity-centric document Grouping rows by the entity users ask about (customer → all their orders)
Text-to-SQL Letting the model write SQL queries against a live database instead of retrieving chunks
Corpus audit The pre-build investigation: inventory, sampling, questions, gaps, sensitivity, licences, ACLs, freshness
Questions document The list of user questions the system must answer — the audit's north star
Coverage matrix Questions × sources × format × freshness × audience — exposes gaps and contradictions
Stratified sample A sample taking files from every folder×format group, not just the biggest
Lineage / provenance The chain linking every chunk back to source bytes, version, page and processing run
Dependency group A named set of packages in pyproject.toml installed on demand (uv sync --group …)
Running corpus The shared fictional Acme document set the module's lessons use

All terms are also collected in the glossary.


Exercises#

  1. Audit a real folder. Run s5_2_audit_corpus.py on a directory you actually have (a Downloads folder, a project docs/, a photo export). Which findings would change an ingestion design? Write three sentences of "audit notes" as if for a real project.
  2. Extend the audit. Add a per-extension count vs byte share column and a "largest 10 files" list to s5_2_audit_corpus.py. Run it on data/corpus — does the picture change?
  3. Corpus generation. Run scripts/make_corpus.py, then inspect data/corpus/contracts/vendor-agreement.pdf and policies/remote-work-policy.docx with your OS's file inspector (or file/unzip -l on the command line). Confirm they are real formats, not renamed text.
  4. Rows to text. Modify s4_3_row_to_text.py to render tickets as entity-centric documents: group tickets by customer so each person gets one document listing all their tickets. Print the result for the toy corpus.
  5. Polite fetcher review. In s3_4_polite_fetch.py, the polite_get function recurses on 429/503 with no attempt cap. Add a max-attempts parameter and raise after 3 tries. What should the caller do with the exception?
  6. Questions document. Write 15 realistic questions an Acme support assistant must answer, then build the coverage matrix for them. Which questions have no source in the toy corpus? What would you add?
  7. Format detective. Take five files from your machine with misleading or missing extensions. Use filetype (or file(1)) to identify them by content. How often does the extension lie?
  8. Build vs buy memo. Your team must ingest 30 SaaS sources (Drive, Slack, Zendesk, Jira…) plus 5,000 PDFs, next quarter, with two engineers. Using Part 7, write a one-page recommendation: which parts hand-roll, which buy, and what the audit must answer first.
  9. Freshness decision. For each corpus folder in data/corpus, decide batch / incremental / streaming using the 2.2 decision flow. Justify each in one line.
  10. Markdown or HTML? Point s3_4b_markdown_negotiation.py at five documentation sites you may legally read, at a polite rate. For how many does fetch_best return markdown? For the others, extract with trafilatura (05.3) and compare the character counts and the first 20 lines. What would you record in lineage?
  11. Lineage sketch. For the ticket T-1002, write down the full lineage chain a chunk of it should carry: source identifier, content hash inputs, parse/clean/chunk versions, and what each is for.
Hints and worked answers
  1. Expect the most useful findings to be the extension mix, the share of binary-like files, the largest folders and any exact duplicates. Good audit notes name a decision, for example: "62% of bytes are .pdf: run the scan check of 05.2, 1.5 before choosing a parser."
  2. Add share = bytes / total_bytes and count_share = count / total_files per extension, and sorted(..., reverse=True)[:10] over (size, path) for the largest files. On the toy corpus the PNG scans dominate the bytes (about 96%) but not the file count, which is exactly the picture the table already shows.
  3. file data/corpus/contracts/vendor-agreement.pdf should report PDF document data; unzip -l data/corpus/policies/remote-work-policy.docx should list [Content_Types].xml, _rels/.rels and word/document.xml. A renamed text file would fail both.
  4. groupby on customer, then render one document per customer: a header line plus one line per ticket. The toy corpus has one ticket per customer, so also test with two tickets for one customer to see the grouping do its job.
  5. Add max_attempts: int = 3 and an attempt counter (a loop is clearer than recursion); after the last attempt raise RuntimeError(f"gave up on {url}"). The caller should record the URL and status in its run report (never retry forever), skip the document, and continue, as in the per-document isolation rule of 2.3.
  6. A good matrix names, for each question, the file, the format, the freshness and the audience. Typical gaps in the toy corpus: shipping cost by country (the help page only says "free shipping over $75"), employee benefits (no source at all) and how to make a warranty claim (the warranty page only states the two-year term).
  7. Run filetype.guess(path); it returns None for plain text formats (CSV, JSON, TXT), because they have no magic bytes. That is expected: use the extension plus a content sniff as the fallback (05.3, 11.1).
  8. A sound memo hand-rolls the pipeline decisions (chunking, metadata, provenance) and the PDF/scan path, buys or adopts connectors for the 30 SaaS sources, and starts with the audit questions on permissions (can a service account read everything?), freshness and licence. Two engineers cannot maintain 30 hand-written connectors; they can maintain a thin wrapper around a connector layer plus their own quality gates.
  9. Suggested answer: pricing.csv incremental (hourly, change signal is the file hash), tickets incremental or streaming (minutes), handbook, policies and contracts incremental with weekly or on-change runs, help-centre incremental via sitemap lastmod, transcripts batch after each meeting. Justify each in one line with the flow of 2.2.
  10. Typically only a minority of sites answer with text/markdown; most return HTML. Compare character counts (the Markdown twin is usually much shorter, because the chrome is gone) and read the first 20 lines of each. Record in lineage which representation you used, the Content-Type you received, and, for the extracted version, the tool name and version.
  11. A chunk of ticket T-1002 should carry: source (tickets/tickets.jsonl, line or id T-1002), source_hash (SHA-256 of the file bytes), the row template version, the cleaning version, the chunker version and config, and the embedding model name. Each field answers a "why is this chunk wrong?" question: which input, which code, which settings.

Check yourself#

  1. Name the nine stages of the ingestion pipeline and say which module owns stages 7–9.
  2. Why do LLM systems fail silently on bad data when traditional systems fail loudly?
  3. A product catalogue PDF parses to "all names, then all prices". What went wrong, and which lesson's techniques fix it?
  4. When is full-batch re-ingestion the right choice over incremental?
  5. What three things gate web crawling, and what RFC standardises robots.txt?
  6. Why is Playwright a last resort rather than the default web fetcher?
  7. What's the difference between "export to text then retrieve" and "text-to-SQL" for database data — and when do you choose each?
  8. A .docx file — what is it physically, and what does that imply for parsing?
  9. List the eight corpus-audit questions.
  10. Why must the audit happen before choosing parsers?
  11. What does lineage let you do that a chunk without provenance cannot?
  12. What do frameworks like LlamaIndex hide that this module insists you understand?
  13. Which running-corpus folder exercises OCR, and why is it only a stand-in?
  14. Your audit finds 8,000 .msg files nobody mentioned. What does that tell you about question 1 of the audit?
  15. A team wants to replace its crawler with a hosted Markdown API to save time. Name three checks before they do.

Further resources#


← Module 04: Prompt & Context Engineering | Module 05 overview | 05.2 — Parsing PDFs →

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