Build snippets from the correct source revision, escape text safely and keep private spans out of previews.
Search snippets: highlighting, offsets and safe evidence previews
A snippet is a provenance claim
A search result preview tells a reader why a passage matched. Its words must come from the same authorized source revision as the link and citation. Reconstructing a snippet from a model summary can make the result appear to contain text it never held. Preserve source offsets during source extraction, together with document ID, revision and field name. Render the original passage around a matched span; label transformed text when OCR or normalization means the display differs from the source.
Choose a window that retains the qualifier
A 30-character window around a matched number may omit its unit, negation or date. Expand to a sentence, table row or bounded section when structure is available. Limit output length, then mark truncation. For a query about a pressure limit, showing only the number is misleading if the next sentence says it applies only during startup. The claim support check should inspect the full evidence, not a clipped snippet. A preview is navigation help, not proof by itself.
Escape before adding markup
Source documents may contain HTML, scripts or text that looks like tags. Escape source text first, then insert only controlled highlighting markup around measured spans. Offset units matter: byte offsets, Unicode code-point indices and UTF-16 units are different. If the highlighter measures one representation and the renderer slices another, a match can move into the wrong word or break an encoded character. A safe renderer either uses offsets in its own string representation or converts them explicitly.
Redact under the current permission scope
A result can be searchable without every field being previewable. Mask personal data, secrets and restricted spans before selecting or rendering windows; highlight offsets then need recalculation against the redacted text. Cache previews only with a permission scope and source revision, and invalidate them when a document is deleted or access changes. Redaction is not achieved by hiding markup with CSS: the private text must never be sent to the browser. Permission-aware caching covers the same revocation boundary.
Evaluate both safety and usefulness
Judge whether a preview contains the answer-bearing phrase, relevant unit and limiting condition; also test whether it contains any restricted span. Include OCR artifacts, right-to-left text, emoji and strings such as angle brackets in the corpus. Compare snippet usefulness and render latency at a fixed window budget. Generating broad previews for every candidate before top-K selection can waste work; fetch and render only results that survive ranking. OCR layout changes what a nearby text window actually means.
Worked contract
from html import escape
def highlighted_preview(source_text: str, match_start: int,
match_end: int, radius: int = 47) -> str:
if not 0 <= match_start < match_end <= len(source_text):
raise ValueError("invalid match span")
if not 0 <= radius <= 160:
raise ValueError("invalid radius")
start = max(0, match_start - radius)
end = min(len(source_text), match_end + radius)
before = escape(source_text[start:match_start])
matched = escape(source_text[match_start:match_end])
after = escape(source_text[match_end:end])
return ("…" if start else "") + before + "<strong>" + matched + "</strong>" + after + ("…" if end < len(source_text) else "")
passage = "Pump P-47: <script> is literal text. Seal limit is 28 kPa."
start = passage.index("28 kPa")
preview = highlighted_preview(passage, start, start + len("28 kPa"))
assert "<script>" not in preview
assert "<script>" in preview
assert "<strong>28 kPa</strong>" in previewPerformance and operating cost
For a selected preview window of W characters, escaping and concatenation take O(W) time and O(W) space. Locating a match can be O(N) in an N-character passage without stored offsets; the example's index call has that cost. Index-time term vectors or stored offsets trade storage and ingest work for faster highlighting. Apply redaction before this function; escaped private text is still private text. The example emits controlled strong tags only after escaping source characters.
Common Mistakes
- Inserting raw source text into HTML and highlighting it afterward.
- Using offsets from a normalized or redacted string against the original source.
- Showing a numeric hit without its unit or limiting condition.
- Caching a preview beyond a permission change or document revision.
Validation drill
Annotate 37 result previews across HTML-like text, OCR and restricted fields. Require the answer span plus qualifier in allowed previews, zero leaked restricted spans and correct source revision after an update.
