A retrieved passage can contain every word in the source and still omit the exception that changes the answer. One way this happens is deduplication: two chunks share most of their text, so the retrieval pipeline drops one before constructing the context. If the discarded chunk contains the only sentence about an exception, a concise context becomes an incomplete one.
Consider a fictional policy with two overlapping chunks:
chunk A: Applications close Friday. The fee is $20.
chunk B: Applications close Friday. The fee is $20. Veterans pay no fee.
Treating B as a duplicate of A leaves a confident answer of "$20" for a veteran. Both chunks are useful evidence, and B contains a qualifying sentence absent from A. A similarity threshold alone cannot decide which passage is safe to discard.
Keep source spans through retrieval
A chunk should carry at least a document identifier, a version identifier, and its source interval. In the example below, intervals are half-open character offsets into the same canonical extracted text: [start, end). Page numbers and bounding boxes can also be stored for citations, but page numbers alone do not describe overlap within a page.
The choice of coordinate system matters. Offsets into OCR output cannot safely be compared with offsets into a separately normalized Markdown file. Unicode normalization, collapsed whitespace, or removing page headers can all shift positions. Generate chunk offsets after choosing the canonical text, and retain a mapping back to the page if the UI needs page-level evidence. Reprocessing a document should create a new version identifier; offsets from different versions are not interchangeable.
Merge overlap before the token budget
For chunks from the same document version, a simple baseline is to merge overlapping or adjacent source intervals and then slice the original text. That preserves the complete union of the retrieved spans without repeating their shared characters.
from dataclasses import dataclass
@dataclass(frozen=True)
class Hit:
doc: str
version: str
start: int
end: int
def merge_hits(hits):
ordered = sorted(hits, key=lambda h: (h.doc, h.version, h.start, h.end))
merged = []
for h in ordered:
if not (0 <= h.start < h.end):
raise ValueError(f"invalid interval: {h}")
if (merged and (h.doc, h.version) == (merged[-1].doc, merged[-1].version)
and h.start <= merged[-1].end):
prev = merged[-1]
merged[-1] = Hit(prev.doc, prev.version, prev.start, max(prev.end, h.end))
else:
merged.append(h)
return merged
def render(hits, documents):
passages = []
for h in merge_hits(hits):
text = documents[(h.doc, h.version)]
if h.end > len(text):
raise ValueError(f"interval exceeds source: {h}")
passages.append(text[h.start:h.end])
return passages
source = "Applications close Friday. The fee is $20. Veterans pay no fee."
cut = source.index(" Veterans")
hits = [Hit("policy", "v1", 0, cut), Hit("policy", "v1", 0, len(source))]
assert render(hits, {("policy", "v1"): source}) == [source]
assert "Veterans pay no fee." in render(hits, {("policy", "v1"): source})[0]
print(render(hits, {("policy", "v1"): source})[0])
This example uses Python string indices, measured in Unicode code points, not UTF-8 bytes or tokens. Keep that convention consistent when you persist offsets. The code also handles a contained interval, identical intervals, and intervals that touch at a boundary. It does not merge a gap: even a short missing span may contain a condition.
Merging is only appropriate when the document and version match. Two reports can repeat the same sentence while assigning it different dates or definitions. Keep them as separate evidence even when their text is identical. Likewise, avoid applying offsets from an older PDF extraction to a newer extraction.
Ranking and budget still need decisions
The code sorts spans by source location, so it deliberately loses retrieval rank. A production implementation can retain the best score and the original hit IDs for each merged span, then rank merged passages before packing them. Preserve the contributing IDs and page mappings so that a citation can be traced back after merging.
Long chains of overlapping hits can produce a passage larger than the model's available context. Split those passages at sentence or structural boundaries, and keep the relevant qualifiers with the statement they modify. If a hard limit forces truncation, record that the passage was truncated and evaluate the resulting answer against the full source. Deduplication cannot guarantee that the retriever found the exception in the first place.
A practical regression fixture includes both orderings of the hits, a fully contained span, adjacent spans, a real gap, and the same offsets from different document versions. Check the actual rendered context, not just the number of returned chunks. For the policy example, the assertion should check that the veteran exception reaches the model alongside the fee. For real documents, add a question whose correct answer depends on that qualifier and verify its citation against the source page.
This complements the row-level citation check: source intervals help assemble context, while page and region metadata help a reader find the evidence in the original PDF.
Top comments (1)
The merge step is the right fix for the dedup problem — but it has one upstream assumption worth pinning down: the canonical extracted text is complete. The merge faithfully preserves the union of the retrieved spans, so if the exception sentence never made it into the canonical text, no merge can bring it back.
That's the failure I keep hitting in PDF extraction: a scanned page routed per-file instead of per-page, or a 90°-rotated page read at recall 0.00 with default layout analysis (0.00 → 1.00 with detect_vertical=True on one fixture), and the 'Veterans pay no fee' sentence is silently absent before chunking even starts.
One check that closes the loop: a per-page char-count assertion on the canonical text before chunking — every page must clear a floor (I use 50 chars/page, 200 for image-heavy pages), and any page below it gets routed to OCR instead of being indexed as empty. Then the merge step operates on text you have verified exists.
One more: where the same interval comes from two extraction paths (text layer vs OCR), a disagreement between them is itself a signal — worth keeping as a low-confidence flag rather than silently taking the longer span.