Skip to content

Chunking: semantic, recursive and overlapping windows through one document

15 min reading

Compare semantic, recursive and overlapping chunk boundaries using the facts a question requires.

Page details

GenAI · Lesson 12 of 45 · 2 / 2.1

Sources · 15 min reading · 31 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Trace the complete RAG pipeline; explain what naive and advanced change. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind can trace a retrieved passage to a policy revision. Maya notices that a returned fragment states the general rule while its exception appears in the next fragment. Dev proposes more overlap; Priya asks whether the resulting units preserve the relationship.

Maya: “The quoted sentence is correct, but it leaves out the exception.”

Dev: “I can change the split boundaries or repeat some text between windows.”

Priya: “Inspect what a question needs together before deciding which boundary works.”

You will compare recursive, semantic and overlapping splits, then check their final token boundaries against questions requiring a rule and its qualifier. A chunk is a retrieval unit whose completeness depends on the task, not just its length.

Which relationships must survive the split?

A recursive-character strategy tries a hierarchy of separators, such as paragraph boundaries, then smaller text boundaries, splitting further when a piece exceeds the selected budget. It is not the same as finding semantic topic changes. A semantic-boundary strategy needs a declared signal for a meaningful break; neither method guarantees that the exception required by a question stays with the rule. LangChain's recursive-splitter documentation gives a concrete separator-based implementation.

Hypothetical scenario. With a chosen 100-token document, 40-token windows and ten-token overlap, a stride is 40 − 10 = 30. Windows beginning at 0, 30 and 60 cover intervals [0,40), [30,70) and [60,100). They process 40 + 40 + 40 = 120 tokens, including 20 repeated tokens. These are supplied boundaries, not actual segmentation output. Check whether a rule and exception survive the final tokenizer-based split, rather than inferring correctness from the overlap size.

Hypothetical scenario. A return-policy exception falls across two chunks, leaving the assistant with only the rule.

In short. Split at meaningful document boundaries. Retain qualifiers with the rule they modify.

A passage can lose the rule it belongs to

Hypothetical scenario. An equipment handbook has a section headed “Weekend loans.” Its first paragraph allows a camera loan through Monday. A later paragraph excludes devices awaiting inspection. Search returns the allowance without the exception, and an assistant answers a question about a camera awaiting inspection as though the general rule applied.

The source was present. The failure arose in how the source became retrieval units and how selected units became answer context. Document chunking is the decision about those boundaries: which material is indexed together, which relationships survive splitting, and which surrounding material can be recovered after a match.

By the end of this chapter, you should be able to compare fixed windows with structural units, calculate overlap overhead, and explain why a small searchable child and a larger displayed parent require separate budgeting and access checks. The prerequisite is the retrieval pipeline, rather than an embedding implementation.

Treat a chunk as a source interval with dependencies

Hypothetical scenario. A policy exception refers to a heading and a table on the preceding page. A fixed-size split retains the sentence but loses those dependencies. Chunk identity must carry document revision, source interval, parser/splitter version and any parent relationship required to interpret it.

Treat a chunk as a source interval with dependencies
ArtifactConcrete evidenceDecision boundary
Child chunksource interval and revisionTraceable wording
Parent relationheading/table/section identityNeeded interpretation
Transform versionparser and splitter policyRebuild compatibility
Split with lineage: Source section → Child intervals.Split with lineage: Source section → Child intervals. Source section to Child intervals: split with lineage; Child intervals to Context assembly: restore required relationships.Source sectionChild intervalsContext assemblysplit with lineagerestore required relationships
Split with lineage: Source section → Child intervals. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Overlap increases repeated positions, not independent evidence. Two overlapping chunks quoting the same sentence should not count as two independent confirmations. Recursive and semantic splitting can preserve different boundaries, but both need evaluation on the actual answer tasks. Rechunking changes child identities and must retire obsolete children coherently; merely adding new chunks leaves duplicate or conflicting candidates.

Equal lengths do not create independent meaning

A fixed-size window is easy to specify and produces a predictable maximum text length under a chosen tokenizer. It does not know where a definition ends, whether a table header belongs to several rows, or which exception qualifies a statement. Splitting a sentence is an obvious problem; splitting its reference to an earlier subject can be less obvious.

Paragraph boundaries are useful evidence about structure, but they are not perfect semantic boundaries. A paragraph beginning “These restrictions also apply…” depends on earlier text. A section may be too large for the chosen processing allowance. Structure-aware splitting still needs a policy for oversized units and references across sections.

Retrieval granularity changes what the system can present as evidence. Anthropic describes adding chunk-specific context before indexing, a concrete way to supply context that an isolated chunk can lose. A broad unit and a narrow unit create different retrieval and context-budget decisions; neither establishes one universally correct token count.

Keep a path from each child to its source

Separate the source document, a logical section, and an indexed child passage. They may coincide for a small document, but need not. A child should retain its document identifier, source revision, section path, and a location that lets the application recover the original evidence. If text extraction changes, offsets into the earlier extraction may no longer identify the same text.

Search small passages and recover bounded source context A versioned document contains a weekend section with an allowance and exception. Search indexes child passages, while references to the parent section allow the application to recover both clauses. The expanded section is permission checked and counted against the context budget. Document revision RWeekend: allowance+ inspection exceptionIndexed childrenC1: allowance; C2: exceptionBoth retain parent + revisionRecover permitted parentdeduplicate + count tokensA match locates evidence.Expansion supplies context.

One design searches smaller children and expands a match to a parent section for generation. That can preserve a qualifying clause without making the entire document the search unit. It also adds a second selection decision: how much parent context to fetch, how overlapping parents are deduplicated, and whether the requester may see all of it.

Preserve headings and table labels when they carry meaning. A row containing only a number and a device name may be ambiguous without its column headers and unit. Where a table cannot be represented faithfully as isolated text, choose a retrieval representation that keeps the relevant relationship or return the source for inspection.

Daniel Ford's Contextual Retrieval report at Anthropic describes adding explanatory context before indexing chunks. That is distinct from recovering original surrounding text after retrieval. Generated context is a derived aid that can itself be wrong; retain the original passage and evaluate the effect rather than treating the generated addition as a new authoritative source.

Derive the overlap bill before choosing a window

Hypothetical scenario. A single extracted document has exactly 1,000 tokens under the indexing tokenizer. Choose a maximum window W = 300 tokens and overlap O = 50 tokens. The stride is W − O = 250 tokens. Start the first window at token 1, start each later window one stride after the previous start, and stop when a window reaches the end. Do not create redundant windows after full coverage.

WindowInclusive token positionsStored tokens
C11–300300
C2251–550300
C3501–800300
C4751–1,000250

The four windows cover the original 1,000 distinct positions. Stored passage lengths sum to 300 + 300 + 300 + 250 = 1,150 tokens. The three adjacent overlaps each repeat 50 positions: 3 × 50 = 150 repeated tokens. Overhead relative to the original is 150/1,000 = 15%. This is a token-volume calculation, not a prediction of a provider's bill or physical index size.

Under this stop-at-coverage policy, for N > W the number of windows is 1 + ceil((N − W)/(W − O)). Here it is 1 + ceil(700/250) = 1 + 3 = 4. For a nonempty document with N ≤ W, one window suffices. Require 0 ≤ O < W so the stride is positive; decide separately how empty documents are handled.

Now change overlap to 100. Stride becomes 200, starts are 1, 201, 401, 601, and 801, and lengths are 300, 300, 300, 300, and 200. Total passage volume is 1,400 tokens, so overhead is (1,400 − 1,000)/1,000 = 40%. More overlap is not free, and the change alone provides no measured evidence of improved answers.

Suppose three retrieved children map to parent sections of 600, 600, and 500 tokens. The first two refer to the same parent. Fetching the two distinct parents supplies 600 + 500 = 1,100 source tokens, before references, separators, and other request material. Counting three child windows would underestimate the actual expanded context; counting the same parent twice would waste it.

In the wild: Chunking Documents: How Splits and Overlap Hide or Reveal the Answer

Daniel Ford's Contextual Retrieval report at Anthropic: Contextual Retrieval adds generated explanatory context before indexing chunks.

Different questions need different evidence spans

A lookup for one device identifier may need a short local passage. A question asking how exceptions change a general rule may require multiple sections. Chunk size should be tested against the collection's question types, preserving enough context to support a complete answer without hiding useful distinctions in unrelated text.

Overlap can protect relationships near a boundary, but it cannot guarantee that a distant definition or exception appears with every dependent statement. A parent link, explicit cross-reference, or targeted follow-up retrieval may be more appropriate. All add complexity and need failure cases.

Changing chunk boundaries also changes the units being evaluated. A relevance set labeled against old chunk IDs cannot simply be reused as though IDs still refer to identical evidence. Preserve source-level answer-support locations and map them to each candidate segmentation. Compare final support as well as retrieval metrics; avoid declaring success merely because larger chunks make more results count as relevant.

Expansion can undo a careful search filter

Hypothetical scenario. Public handbook passages and restricted maintenance notes share a container in the source system. The retriever filters correctly to a public child, but the parent-expansion function returns the entire container, including staff notes. The search filter worked and the assembled request still contains unauthorized text.

The repair belongs at the expansion boundary. Recover only the permitted logical source unit; check the revision and current access rule before material leaves that boundary. If the parent mixes access levels, it cannot be treated as an indivisible safe expansion merely because one child was accessible. Reindexing into permission-consistent units may simplify the design.

Review caches and traces too: preventing a generated disclosure after private text entered a log does not reverse that disclosure. Test permission changes and mixed-access parents explicitly. This scenario describes a possible failure, not a documented incident or a claim about any named product.

Four shortcuts that obscure the decision

“A standard window size is optimal.” A default is a baseline. It does not establish performance on your documents, tokenizer, or question distribution.

“Overlap repairs every split.” It duplicates a local span. It cannot restore every relationship across a long document, and can consume selection slots with near-duplicate evidence.

“Semantic boundaries are objective.” A segmentation model introduces another decision process. Judge whether its units preserve the evidence your tasks require, including tables, exceptions, and references.

“The parent is just a larger version of the child.” Expansion changes what is disclosed and how much context is supplied. Permissions, revision matching, deduplication, and budgets must apply to the expanded material.

Use structure where it helps explain a result

Start with units a reviewer can inspect, such as sections bounded by reliable headings, plus a declared fallback for oversized sections. Fixed windows remain a useful baseline when the extraction has little trustworthy structure. Keep enough source provenance to show why each result was selected and what context was added.

Compare a small set of alternatives using questions that cross boundaries, refer to headings, need table labels, or depend on exceptions. Hold other retrieval settings fixed where possible. If changing segmentation also changes embeddings and ranking, the comparison measures the combined change.

Do not add a hierarchy merely because a diagram looks sophisticated. For a short document, direct retrieval or supplying the complete permitted text may be adequate. For an exact structured record, retaining its fields and relationships may matter more than splitting prose.

Limits of Chunking Documents: How Splits and Overlap Hide or Reveal the Answer

There is no universal chunk size independent of document structure, task and context budget. Context added during indexing and context expanded during serving affect different artifacts. Evaluate source coverage, retrieval and final support separately when changing the unit.

Test the child chunk boundary

Overlap improves recall but answer support is counted twice for one sentence. What changes?

Reveal the design reasoning

Deduplicate evidence at the source interval or claim level and preserve parent context. Evaluate coverage separately from independent support; repeated text does not strengthen authority.

Decision: Choose boundaries by task evidence and migrate child sets by source revision.

Check yourself: reason about the boundary

A 650-token document uses W = 250 and O = 50 under the chapter's stopping policy. How many windows and how much passage volume?

Stride is 250 − 50 = 200. Windows are 1–250, 201–450, and 401–650: three windows of 250 tokens. Total volume is 750, so 100 positions are repeated and overhead is 100/650, approximately 15.4%. The count formula gives 1 + ceil((650 − 250)/200) = 3.

Two highly ranked children come from the same parent. Does returning both prove that two independent sources support the answer?

No. They share provenance and may repeat the same evidence. Deduplicate parent expansion and preserve both child locations if useful. Independent corroboration requires an actual source relationship analysis; the number of retrieval hits does not establish it.

A short allowance is always retrieved, but its exception appears several sections away. Is doubling local overlap a sufficient repair?

Not established. Inspect the evidence relationship and recover the needed exception through an explicit source link, appropriate parent, or additional retrieval. Then test complete answer support and context usage. A larger local overlap may still miss the exception and introduce duplicate material.

Northwind decision log

Split at meaningful document boundaries.
Retain qualifiers with the rule they modify.
Evaluate complete evidence rather than chunk length alone.

Go deeper into units and lost context

Check the mechanism in this lesson

Do ten overlap tokens guarantee that every policy exception stays with its rule?

Compare the explanation

No. Overlap establishes repeated coverage, not semantic completeness. Inspect where the rule and exception fall under the final tokenizer-based split and test representative questions that require both.

Carry the decision forward

Northwind has units whose boundaries can be evaluated. Page 13 asks how to find their vectors efficiently, and what relevant evidence approximation might leave outside the candidate set.