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.
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 Architecture | Unit Indexed (Search) | Unit Returned (Prompt Context) | Optimal Document Profile |
|---|---|---|---|
| Fixed Token Window + Overlap | Fixed 400–600 tokens (15% overlap) | Same token window | Homogeneous prose transcripts, unstructured emails |
| Structure-Aware Header / AST Split | Clean heading section or complete AST class/function | Same atomic logical block with breadcrumbs | API docs, RFC specifications, TypeScript/Python codebases |
Parent-Child (Small-to-Big) | Compact 150–250 token child slice + heading prefix | Full 800–1,400 token parent procedure/section | Compliance manuals, SOP runbooks, financial disclosures |
| Dual-Index Table Serialization | Concise 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.
pythonimport hashlibfrom dataclasses import dataclass@dataclass(frozen=True)class ChunkUnit:chunk_id: strparent_id: strbreadcrumb: strtext_for_embedding: strraw_text: strtoken_estimate: intdef 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:returnparent_text = "\n".join(section_lines).strip()if not parent_text:returnbreadcrumb = " > ".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 = 0for 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], ptokselse:buf.append(para)buf_tokens += ptoksif 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 makesAPI Keys,TLS Certs, andDB Passwordsindistinguishable 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
512vs1024based on blog rules instead of measuringRecall@20over 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.
Why might a production RAG ingestion pipeline index small child chunks for vector search while returning larger parent sections to the model?