A retrieval adapter returns a document ID, a start offset and an end offset. The answer renderer loads the document and runs text[start:end]. The resulting snippet is readable, so the application displays it as evidence.
That slice can point to the wrong text. If the adapter counted UTF-8 bytes and the renderer slices a Python string, an accented character before the passage is enough to shift the selection.
I would make the offset unit a required field in a citation contract. Two integers without a coordinate system are insufficient evidence for a source highlight. The renderer should also check the exact text representation and refuse a quote that does not match.
The example here is an application-owned, offline fixture. It reproduces a coordinate mismatch, not a reported production incident or a defect in a particular RAG vendor. The repair verifies text selection. It does not establish that a selected passage supports an answer.
Reproduce the mismatch before changing the model
Python’s text-sequence documentation defines strings as sequences of Unicode code points. Encoding a string as UTF-8 produces a byte sequence. For an ASCII-only input, the positions happen to agree. That makes an English smoke test a poor way to discover this defect.
Use this small input instead:
text = "Café: deny. Next: allow."
raw = text.encode("utf-8")
start = raw.index(b"deny")
end = start + len(b"deny")
print(start, end)
print(repr(text[start:end]))
print(repr(raw[start:end].decode("utf-8")))
Executed output:
7 11
'eny.'
'deny'
The é occupies two bytes in UTF-8 and one code point in this Python string. The intended word begins at byte 7 but code-point position 6. Applying the byte range to text skips the d and includes the full stop. Nothing in this example raises an exception.
A reviewer might notice that particular error. Longer passages can be harder to inspect: the selection starts a little late, ends a little late, and still looks like a plausible excerpt. Whether a shifted passage changes the answer’s meaning depends on the source. The fixture proves incorrect selection, not a measured rate of harmful answers.
Changing the prompt cannot repair this adapter contract. The consumer needs to know how the producer counted.
Name the representation as well as the unit
The W3C Web Annotation Data Model provides a useful reference. Its text selectors use Unicode code points, with an inclusive start and exclusive end. Its separate Data Position Selector addresses byte positions. The specification also warns that text positions are brittle when a resource changes.
The download uses a smaller custom contract, not a complete W3C annotation implementation:
@dataclass(frozen=True)
class Citation:
document_id: str
representation_sha256: str
unit: str
start: int
end: int
exact: str
Here, representation_sha256 is the SHA-256 digest of the UTF-8 encoding of the extracted text. It is deliberately not the hash of the original PDF or HTML file. Offsets address the text that the extractor produced, so that is the representation the renderer must retrieve.
Suppose an ingestion pipeline strips HTML tags, decodes entities and changes line endings. A range calculated before those transformations cannot safely index the text after them. Either calculate offsets after the agreed extraction pipeline or keep an explicit mapping between representations. Naming the original file alone does not recover that mapping.
Unicode normalisation can also change positions. The displayed word Café can contain a single é code point or an e followed by a combining accent. The fixture changes its source to the decomposed form and verifies that the representation check rejects it. It does not silently normalise the renderer’s copy and reuse old offsets.
A production record should identify the extraction pipeline and source revision so that operators can retrieve the right representation. The minimal fixture receives the text directly and checks its digest. It has no document store, version lookup or migration process.
Reject a mismatch instead of returning a nearby passage
The resolver checks document identity and representation digest before it applies the range. It accepts only two explicit units: utf-8-byte and unicode-code-point. Unknown units fail. UTF-16 code units, for example, need their own deliberate conversion; the code does not guess what a foreign producer intended.
The range check requires actual integers, excludes empty selections and rejects negative, reversed or out-of-bounds ranges. These rules are the fixture’s contract. Python slicing alone is more permissive: it can accept negative positions and truncate an oversized end. That behaviour is convenient for ordinary sequence processing but can conceal a malformed citation.
For byte ranges, the relevant branch is:
source = text.encode("utf-8")
source[:citation.start].decode("utf-8", errors="strict")
source[:citation.end].decode("utf-8", errors="strict")
selected = source[citation.start:citation.end].decode(
"utf-8", errors="strict"
)
The two prefix decodes check that both boundaries fall between complete UTF-8 characters. The selected range then decodes strictly. A range through the middle of é raises an error rather than inserting a replacement character and continuing.
After selection, the resolver requires selected == citation.exact. In the example, changing the unit label to unicode-code-point while leaving the byte offsets unchanged produces eny.. The expected quote is deny, so the resolver rejects it.
This comparison is useful redundancy, with limits. If a producer supplies a wrong range and a matching wrong quote, both can pass. A repeated phrase can also match at the wrong occurrence. The expected quote must come from a trusted extraction path, and the application must retain enough source context to review the occurrence. None of these checks decides whether the passage entails the model’s answer.
The digest has a similar boundary. An attacker who can replace both the source text and the expected digest can make them agree. Retrieve the expected representation through trusted storage, enforce authorisation before resolving it, and protect the citation record according to the application’s threat model. A hash is not a signature or an access check.
Run the regression suite
Download and inspect rag-citation-offsets.py. It uses the Python standard library, requires Python 3.9 or later, and performs no file writes, network requests or model calls.
python3 rag-citation-offsets.py
python3 rag-citation-offsets.py --test
python3 -O rag-citation-offsets.py --test
The demonstration prints:
UTF-8 byte range: 7 11
Wrong str slice: 'eny.'
Verified quote: 'deny'
Ten tests check the readable-but-wrong slice, both supported units, a wrongly relabelled range, unknown units, changed representations, document identity, invalid ranges and types, multibyte boundaries, a supplementary Unicode character, and an incorrect expected quote. The checks use unittest and remain active under optimisation.
These tests cover source-coordinate resolution. They do not test PDF extraction quality, grapheme-cluster segmentation, browser highlighting or answer faithfulness. A valid code-point boundary can still split a visible grapheme cluster; the W3C guidance says selections should avoid doing that. If the interface highlights text, test that additional display requirement with its actual rendering engine.
The prefix decoding in this teaching implementation also does repeated work on long texts. For high-volume rendering, validate the representation once and build or reuse an appropriate boundary map. Keep the same failure behaviour and measure the implementation before optimising it.
Keep source selection inside the retrieval contract
A citation renderer is another reader of retrieved content. Apply the same permission checks described in RAG neighbour-expansion authorisation before loading source text, and avoid resolving an old citation against a silently replaced representation. The stale-chunk example covers a different ingestion defect: obsolete chunks remaining searchable after a document changes.
For the wider approach to tool contracts and review evidence, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add a non-ASCII prefix to one real citation fixture in your application. Record the producer’s unit, the exact extracted representation and the expected quote. Then pass that record through the actual renderer and compare the selected text before accepting its source highlight.