FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Ingestion and Chunking

How parsing normalization segmentation metadata and updates create retrievable units.

Freshness: current•16 min read•Retrieval and Knowledge Systems

Key Learning Outcomes

  • ✓Design an ingestion contract
  • ✓Choose chunk boundaries
  • ✓Preserve provenance
Full Technical Reference Document

Mental model

Ingestion transforms governed multi-format source files (PDFs, Markdown docs, HTML tables, code repositories, SQL records) into versioned retrievable units while preserving document headings, table column context, code symbol boundaries, and access-control scope—so retrieval finds crisp spans without losing surrounding structural meaning.

Governed source & ACL extraction
Layout-aware parse (tables/AST)
Structure-bound chunk segmentation
Prepend header breadcrumbs & parent ID
Versioned dual BM25 + vector upsert
Conceptual teaching model synthesized from:Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksIntroduction to Information Retrieval

Learning outcomes

  • Replace destructive fixed-character window chunkers with structure-aware Markdown, PDF-layout, and Tree-sitter AST boundaries.
  • Implement parent-child (small-to-big) indexing that matches small precise child spans while supplying full parent context at generation time.
  • Preserve immutable lineage metadata (doc_id, revision, acl_groups, breadcrumbs) cleanly across incremental updates and deletes.

Theory

Naive fixed-size 512-token sliding chunkers destroy production RAG accuracy at the data layer long before any embedding model runs: they sever markdown headings from bullet lists, cut SQL migration tables across arbitrary vertical splits where child chunks retain numbers without column headers, and shatter Python functions mid-loop so neither half carries its signature or docstring. Modern ingestion separates retrieval precision cleanly from generator context:

Chunking ArchitectureUnit Indexed (Search)Unit Returned (Prompt Context)Optimal Document Profile
Fixed Token Window + OverlapFixed 400–600 tokens (15% overlap)Same token windowHomogeneous prose transcripts, unstructured emails
Structure-Aware Header / AST SplitClean heading section or complete AST class/functionSame atomic logical block with breadcrumbsAPI docs, RFC specifications, TypeScript/Python codebases
Parent-Child (Small-to-Big)Compact 150–250 token child slice + heading prefixFull 800–1,400 token parent procedure/sectionCompliance manuals, SOP runbooks, financial disclosures
Dual-Index Table SerializationConcise LLM/schema summary (for vector matching)Verbatim Markdown/HTML table (for exact values)Product pricing matrices, benchmark sheets, lab panels

Crucially, prepending a lightweight contextual breadcrumb (Document > Section > Subsection) onto every indexed chunk embedding ([Kubernetes Runbook > OOMKilled Diagnostics > Pod Cgroup Limits]) eliminates pronoun ambiguity when a section repeatedly mentions "this threshold" without repeating the module name in every paragraph.

python
import hashlib
from dataclasses import dataclass
​
@dataclass(frozen=True)
class ChunkUnit:
chunk_id: str
parent_id: str
breadcrumb: str
text_for_embedding: str
raw_text: str
token_estimate: int
​
def split_markdown_with_breadcrumbs(
doc_id: str,
markdown: str,
max_child_tokens: int = 220,
) -> list[ChunkUnit]:
"""Segment Markdown along H2/H3 structure, linking small child search units to parent sections."""
chunks: list[ChunkUnit] = []
h2, h3 = "", ""
section_lines: list[str] = []
​
def flush_section() -> None:
if not section_lines:
return
parent_text = "\n".join(section_lines).strip()
if not parent_text:
return
breadcrumb = " > ".join(p for p in (doc_id, h2, h3) if p)
parent_id = hashlib.sha256(f"{doc_id}:{breadcrumb}".encode()).hexdigest()[:16]
paragraphs = [p.strip() for p in parent_text.split("\n\n") if p.strip()]
buf: list[str] = []
buf_tokens = 0
for idx, para in enumerate(paragraphs):
ptoks = max(1, len(para.split()))
if buf and buf_tokens + ptoks > max_child_tokens:
joined = "\n\n".join(buf)
cid = hashlib.sha256(f"{parent_id}:{idx}:{joined[:40]}".encode()).hexdigest()[:20]
chunks.append(ChunkUnit(cid, parent_id, breadcrumb, f"[{breadcrumb}]\n{joined}", joined, buf_tokens))
buf, buf_tokens = [para], ptoks
else:
buf.append(para)
buf_tokens += ptoks
if buf:
joined = "\n\n".join(buf)
cid = hashlib.sha256(f"{parent_id}:tail:{joined[:40]}".encode()).hexdigest()[:20]
chunks.append(ChunkUnit(cid, parent_id, breadcrumb, f"[{breadcrumb}]\n{joined}", joined, buf_tokens))
​
for line in markdown.splitlines():
if line.startswith("## "):
flush_section()
h2, h3 = line[3:].strip(), ""
section_lines = [line]
elif line.startswith("### "):
flush_section()
h3 = line[4:].strip()
section_lines = [line]
else:
section_lines.append(line)
flush_section()
return chunks

Trade-offs

Smaller child chunks (150–250 tokens) produce sharper semantic cosine vectors because dense embeddings avoid dilution across multi-topic sections, improving Recall@20 on targeted fact lookups cleanly—yet supplying isolated 150-token fragments straight into an LLM prompt frequently drops caveats or step pre-conditions sitting two paragraphs away. Parent-child retrieval resolves this tension by searching on crisp child embeddings while hydrating the deduplicated parent section into the prompt context, at the cost of storing a parent document lookup table and budgeting carefully against larger parent token footprints so 5 parent hits do not overflow smaller context budgets.

Failure modes and misconceptions

  • Tearing Tables Across Fixed Token Slices: Splitting a 40-row pricing matrix mid-table orphans numeric figures away from currency units and plan tier headers, driving confident number hallucinations.
  • Omitting Document Breadcrumbs on Embeddings: Embedding a bare paragraph "Must be rotated every 90 days" with zero metadata makes API Keys, TLS Certs, and DB Passwords indistinguishable in vector space.
  • Skipping Scanned PDF / OCR Verification: Feeding corrupted OCR column-interleaved PDF text straight into ingestion creates permanently unfindable gibberish chunks unless extraction quality heuristics quarantine dirty files.
  • Static Chunking Tuning Without Evals: Guessing chunk size 512 vs 1024 based on blog rules instead of measuring Recall@20 over real domain golden queries.

Decision scenario

A developer platform indexes 40,000 Markdown product docs, OpenAPI specifications, and multi-page troubleshooting runbooks. Users frequently ask specific CLI flag questions yet also need full multi-step rollback procedures intact without truncated prerequisites. Design a parent-child breadcrumb ingestion schema and validation check.

Reflect before revealing the guide

Why might a production RAG ingestion pipeline index small child chunks for vector search while returning larger parent sections to the model?

Prerequisites & Related Concepts (5)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next