Practical technical guides / AI engineering: retrieval

Overlapping Chunks Fill Top-k With the Same Passage: Merge by Source Span First

Overlapping chunks put the same text in top-k several times; in a synthetic test a quarter of the context repeated. Merge hits by source span and refill the budget.

By Sandeep Belgavi · Published 2026-11-27

Overlapping chunks put the same text in top-k several times; in a synthetic test a quarter of the context repeated. Merge hits by source span and refill the budget.

Overlap helps indexing and hurts the context

Chunk overlap exists for a good reason. If a fact straddles a chunk boundary, a window that repeats the last part of the previous chunk keeps the sentence whole in at least one chunk, and retrieval can find it. Common defaults reflect this. The base TextSplitter in LangChain's text splitters takes chunk_size=4000 and chunk_overlap=200, measured with len, so in characters by default. LlamaIndex's SentenceSplitter uses a default chunk size of 1024 tokens and a default overlap of 200 tokens, about a fifth of each chunk.

The cost appears at query time. A query that matches one region of one document matches every overlapping chunk that covers that region. Take the top k by score and several of the k are neighbours that share text. The model then reads the same sentences two or three times, and the context budget you set aside for k distinct pieces of evidence holds fewer than k. Exact-text de-duplication does not catch it, because overlapping chunks are not identical; they share a suffix and a prefix.

This guide measures the effect on a small synthetic corpus, shows a merge-by-span step that removes it, and explains when to apply it.

A reproducible measurement

The companion example chunk_span_merge uses four short help articles for the fictional Belgavi's Book Store: a returns policy, a shipping guide, gift-card rules and a damaged-item checklist. It splits them into 360-character windows with 120 characters of overlap, a third of each chunk, moving each boundary back to a space so words are not cut. A deterministic lexical scorer stands in for the retriever, so every number is reproducible; it is not a claim about any embedding model.

For the query "refund for a damaged book that was returned", the plain top 6 is:

RankDocumentCharactersScore
1returns-policy0 to 3561.134
2returns-policy726 to 10490.802
3returns-policy244 to 6000.775
4damaged-items-checklist0 to 3550.620
5returns-policy481 to 8390.504
6damaged-items-checklist238 to 3640.213

Four of the six hits are consecutive windows of the returns policy, and their spans overlap pairwise. The context holds 1,874 characters, but only 1,413 of them are distinct: 24.6 percent of the context is repeated text. Only two of the four documents appear. And exact-text de-duplication keeps all six chunks, because no two are identical.

Merge hits by source span

The fix is to treat a hit as a span of a source document, not as an opaque chunk. Keep the document ID and the start and end offsets in the chunk metadata at indexing time, which most splitters can do. At query time:

  1. Retrieve a deeper candidate pool than you will use, for example four times k.
  2. Group candidates by document and sort each group by start offset.
  3. Merge candidates whose spans overlap or touch into one passage covering the union, and give it the best score of its parts.
  4. Fill the context budget with merged passages in score order.
# Author: Sandeep Belgavi. Excerpt from chunk_span_merge/example.py
def merge_spans(hits):
    """Merge hits from the same document whose spans overlap or touch; keep the best score."""
    by_doc = defaultdict(list)
    for h in hits:
        by_doc[h['doc']].append(h)
    merged = []
    for doc, hs in by_doc.items():
        hs.sort(key=lambda h: h['start'])
        cur = dict(hs[0], parts=1)
        for h in hs[1:]:
            if h['start'] <= cur['end']:
                cur['end'] = max(cur['end'], h['end']); cur['score'] = max(cur['score'], h['score']); cur['parts'] += 1
            else:
                merged.append(cur); cur = dict(h, parts=1)
        merged.append(cur)
    return sorted(merged, key=lambda m: (-m['score'], m['doc'], m['start']))

The merged passage text is cut from the source document by offset, not glued together from chunks, so it reads as one continuous excerpt without the repeated seams.

With the same character budget as the plain top 6, the merged context holds three passages: the first 1,049 characters of the returns policy as one excerpt, the damaged-item checklist, and the gift-card rules. It uses 1,760 characters, all distinct. The freed budget brought in a third document, and it is relevant: the gift-card rules say that a refund for an order paid with a gift card goes back to the gift card, which matters for a refund question.

Choices that change the result

Merging changes the unit of evidence, so a few decisions need care.

Cap the merged passage length. Merging can chain: if every window of a long document matches, the union is the whole document. Set a maximum passage length, and when a merged span exceeds it, keep the highest-scoring sub-span around the best part instead.

Decide whether to merge only overlapping spans or also nearby ones. The example merges spans that overlap or touch. Merging spans separated by a small gap, say one sentence, produces more readable excerpts at the cost of including text that did not match. Choose the gap from your chunk size, and record it.

Keep citations exact. If answers cite sources, a merged passage should carry its document ID and character range so a citation points at the excerpt the model saw. Keep the list of original chunk IDs as well, so evaluation can still be computed per chunk.

Re-rank after merging, not before. If you use a cross-encoder or model-based re-ranker, run it on merged passages. Scoring overlapping chunks separately gives the same text several chances to win, which is the bias you are removing.

Measuring it on your own index

The measurement is cheap and does not need labelled data. For a sample of real queries, take the top k as you do today and compute two numbers: the share of context characters (or tokens) that are repeated, using the span union per document, and the number of distinct documents. Then compute the same after merging at the same budget. If the repeated share is near zero, your overlap is small relative to how spread out your hits are, and merging will change little. If it is in the tens of percent, as in this fixture, merging gives you budget back for free.

Then check that answers do not get worse. Run your existing retrieval evaluation, recall at k per chunk or per document, and your answer-quality checks, on both variants. Merging should not lower recall for document-level relevance, since it keeps every document a chunk came from, but it can move a borderline chunk out of the budget. Watch for that on queries whose answer depends on a short, low-scoring passage.

Budgets in tokens, and where the step belongs

The example measures characters to stay dependency-free, but the budget that matters is tokens. Repeated text costs tokens on every request, so the saving shows up directly in input token counts and, for long contexts, in latency. When you measure on your own system, count with the tokenizer of the model that reads the context, and compare the token count of the plain top k with that of the merged context at the same number of distinct documents.

Place the merge step after retrieval and any metadata filtering, and before re-ranking and prompt assembly. If you run hybrid retrieval, fuse the lexical and vector rankings first, then merge spans on the fused candidates; merging each ranking separately and fusing afterwards can count the same region twice under two slightly different spans. If the pipeline caches retrieved contexts, cache the merged result, since that is what the model sees and what citations refer to.

When not to merge

If your chunks never overlap, there is nothing to merge; exact or near-duplicate detection across documents is a different problem. If documents are tiny, retrieving whole documents may be simpler than chunking at all. And if a downstream step expects fixed-size chunks, for example a model with a strict per-passage limit, merging breaks that contract unless you cap passage length at the same size.

Limits of this guide

The corpus is four synthetic articles and the retriever is a lexical stand-in, so the 24.6 percent figure describes this fixture only; it shows the mechanism, not a typical rate. The splitter defaults are read from the LangChain text splitters source and the LlamaIndex SentenceSplitter source on their main branches; check the versions you pin.

Primary references and authorship

Sources checked 2026-11-27. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/chunk_span_merge. Views are my own and do not represent any employer, past or present.