Right Document, Wrong Chunk
Most RAG tutorials stop at: split, embed, retrieve top-K. Works fine on a README. Point the same pipeline at a 200-page regulation, a pile of clinical notes, or an RFC. Retrieval looks fine. Recall@5 is fine. MRR is fine. Users still complain.
Often it isn’t the wrong document. It’s the chunk: Article 17 cut in half, two RFC sections welded together, a table header orphaned from its rows. The model gets text that sort of matches the query and sort of doesn’t contain the answer. Right document. Wrong chunk. Standard metrics mostly won’t flag that.
The gap between documents and spans
Recall@K asks: did we surface the right source? That’s the right question for a big messy web corpus.
It’s the wrong bottleneck for a lot of enterprise RAG. Legal, regulated industries, specs — you might have tens or hundreds of documents, not millions. The GDPR shows up. The question is whether the span stuffed into the prompt actually holds the answer, or a splice of two unrelated sections.
I ran into this while building retrieval evaluation tooling. Two chunking strategies, both “great” on document-level scores. Same top-line numbers. The retrieved strings were not the same story at all.
What fixed-size chunking misses
RecursiveCharacterTextSplitter walks a separator list — \n\n first — and in clean text that often tracks real boundaries. Blank line between sections? You’ll usually get a sane break. It’s smarter than naive character windows.
What it still doesn’t know: that a newline inside a long article is not the same as a boundary between articles. That overlap measured in characters can slice mid-sentence. That a table header belongs with its data rows. That a section titled “Definitions” is a coherent unit that shouldn’t be split across chunks.
Whitespace is a structural proxy — a cheap signal that correlates with where topics change. It’s a real proxy. It’s also a weak one, because it can’t distinguish between layout whitespace and semantic boundaries.
On structured documents — anything with articles, numbered sections, hierarchical headings — the actual boundary markers are sitting right there in the text.
chunkweaver
chunkweaver splits text at structural boundaries instead of character counts. Stdlib-only core, no dependencies.
pip install chunkweaverfrom chunkweaver import Chunker
from chunkweaver.presets import LEGAL_EUchunker = Chunker(
target_size=1024,
overlap=2,
overlap_unit="sentence",
boundaries=LEGAL_EU,
)chunks = chunker.chunk(regulation_text)
Three layers of splitting, applied in order:
Regex boundaries. You specify where sections start — ^Article\s+\d+, ^##, ^Section\s+\d+\.\d+. Seven built-in presets cover EU and US legal, SEC filings, FDA labels, RFCs, markdown, and chat logs. These are starting points; most production deployments add domain-specific patterns on top.
Heuristic detectors. HeadingDetector scores lines using casing, length, whitespace patterns, and positional signals. TableDetector identifies tabular regions by delimiter density and column alignment. These handle documents where you don’t know the structure upfront — or where the structure is implicit rather than marked by clean patterns.
Fallback splitting. When a section exceeds target_size, it falls back to paragraph, sentence, or word boundaries. Never mid-sentence. Overlap is in sentences, not characters.
These layers compose. Boundaries from regex, heuristics, and external annotations are merged, deduplicated, and applied in a single pass. A table detected by TableDetector stays intact even when surrounded by regex-driven splits.
Hierarchical splitting
Not all boundaries are equal. In EU regulation, a CHAPTER boundary is stronger than a Section boundary, which is stronger than an Article boundary. chunkweaver models this:
from chunkweaver.presets import get_presetboundaries = get_preset("legal-eu", leveled=True)
# Returns [(pattern, level), ...] — level 0 is strongestThe chunker splits only as deep as needed. If a chapter fits in one chunk, it stays whole. If it doesn’t, it splits at the next level down. This preserves semantic coherence at the broadest level possible instead of fragmenting everything to the finest grain.
Seven presets have leveled variants: legal-eu, legal-us, financial, fda-label, rfc, academic, and markdown.
Domain customization
Presets are convenient defaults, not the point. The actual value is that every aspect of chunking is configurable per domain:
Get Oleksii Aleksapolskyi’s stories in your inbox
Join Medium for free to get updates from this writer.
Sentence patterns. The default sentence splitter uses [.!?]\s+(?=[A-Z"(]), which works for English prose. For Cyrillic text (Serbian, Montenegrin, Russian), accented Latin (Spanish, French), or CJK, swap in a different pattern:
from chunkweaver.sentences import SENTENCE_END_PERMISSIVE, SENTENCE_END_CJKchunker = Chunker(
target_size=1024,
boundaries=LEGAL_EU,
sentence_pattern=SENTENCE_END_PERMISSIVE, # handles non-ASCII capitals
)Keep-together regions. Tell the chunker that certain patterns must not be split — table headers with their data, clinical labels with their content:
chunker = Chunker(
target_size=1024,
keep_together=[r"^(Assessment|Plan|HPI):.*(\n(?! \S).*)*"],
)Annotation ingestion. If your PDF extractor (Unstructured, Docling, Azure Document Intelligence) already knows where sections and tables are, pass SplitPoint and KeepTogetherRegion directly instead of re-discovering structure with regex. The chunker doesn’t care how the annotations were produced.
ML detectors. The BoundaryDetector ABC accepts any class that returns SplitPoint or KeepTogetherRegion annotations. Regex, heuristic scoring, or a trained classifier — same interface. The repo includes example ML detectors: a GradientBoosting heading detector for OCR-damaged legal text (0.97 F1 vs 0.76 for the heuristic on held-out CV), and a clinical section detector for notes where abbreviated styles break pattern matching.
from chunkweaver import Chunker
from my_detectors import TrainedHeadingDetectorchunker = Chunker(
target_size=1024,
detectors=[TrainedHeadingDetector("model.joblib")],
)The architecture is intentionally open here. The hard problem in production chunking is boundary detection on messy, real-world documents — OCR artifacts, inconsistent formatting, mixed languages. Regex and heuristics cover the common cases. For the rest, you can plug in whatever works for your data.
Diagnostics
Chunking is configuration, and configuration needs feedback.
--recommend analyzes a document and suggests configuration — which preset, which detectors, what target size. It scores every built-in preset against the text, runs a dry-run chunk, and prints a ready-to-use snippet:
chunkweaver --recommend contract.txt--inspect evaluates the result after chunking — size distribution, fallback ratio, orphan headings, near-miss boundaries that almost qualified as splits, and actionable suggestions:
chunkweaver contract.txt --preset legal-eu --inspectAdd --llm-audit for per-chunk coherence scoring via GPT-4o-mini. Both commands support --format json for CI pipelines.
This is the feedback loop that matters: recommend a config, chunk, inspect the result, adjust. Not guessing and hoping.
The benchmark
I ran this on GDPR, EU AI Act, CCPA, and eight RFCs. 11 documents, 58 queries, ~600-character target size. LLM-as-judge (gpt-4o-mini) rated each retrieved chunk as full, partial, or insufficient.
Against naive 600-char fixed windows: chunkweaver wins 15 to 4, 39 ties. Binomial p = 0.019. Doc-clustered permutation p = 0.015.
Against LangChain RCTS: 11 to 4, 43 ties. Binomial p = 0.119. A trend, not significant at this sample size. RCTS’s paragraph heuristic captures some structural signal, which narrows the gap.
I’m not going to oversell the RCTS result. But the mechanism is clear: when the chunker knows where the boundaries are, it stops cutting through them. The gain is proportional to how much structure the document has and how poorly whitespace proxies for it.
A note on scope: this tested rule-based strategies. Embedding-based semantic chunkers (LlamaIndex’s SemanticSplitter, Unstructured’s layout-aware pipeline) solve a related but distinct problem and comparing them is a separate experiment.
Full methodology, reproduction scripts, and raw judge output: benchmark/
Where it fits
chunkweaver is strongest on documents designed to be navigable — legal text, financial filings, clinical notes, RFCs, technical standards, annotated PDFs. The more structure a document has, the more there is to exploit. On domains like these, a single preset change can move retrieval quality measurably.
On free-form prose where paragraphs are the only structure, the advantage over RCTS narrows. That’s a domain boundary, not a deficiency — if paragraphs already track topics, there’s nothing better to split on.
It takes text in and puts chunks out. Any extractor that produces markdown feeds straight into it. It doesn’t embed, doesn’t store, doesn’t retrieve. It handles the split, then hands off to whatever pipeline comes next.
If Recall@K is pinned near 1.0 and people still report wrong answers, look at what text entered the prompt — not only which document name came back.








