Mental model
Explainability highlighting attaches a visible mark to the exact text span that activated a rule, classifier, or reviewed evidence record. A trustworthy mark is bound to one immutable text revision, carries a user-facing reason, and remains meaningful without color. The span points to evidence; by itself it does not prove that a probabilistic model relied causally on those words.
Think of a highlight as a compact provenance record rendered in place. It should answer three questions: which text was examined, which rule or evidence source selected it, and what the person can do with that explanation. In a deterministic keyword rule, “the phrase ‘wire transfer’ matched rule R-17” is a defensible statement. A model attribution method may instead say that a span received a high score under a named analysis; that score is not the same as a rule firing or a causal proof.
The record and the prose must travel together. If the assistant edits a sentence after classification, a numeric range can still point somewhere while silently referring to different words. Bind each range to the exact displayed text revision, verify that slicing those offsets yields the recorded phrase, and suppress the mark if the check fails. This turns a decorative effect into evidence a reviewer can reproduce.
Learning outcomes
- Describe the text revision and offset contract that makes a trigger highlight reproducible.
- Calculate the portion of a response covered by overlapping evidence spans without double-counting.
- Choose accessible rendering and recovery behavior when evidence is stale, ambiguous, or crowded.
Theory
Represent a trigger as a record containing a stable rule identifier and version, a source revision, start and end offsets, the matched text, and a concise explanation approved for the audience. The offsets use one declared indexing convention. JavaScript strings use UTF-16 code units, while other services may return Unicode code points or UTF-8 byte offsets; mixing these conventions shifts ranges around emoji and some accented text. Convert at the boundary, then compare the exact slice to the supplied phrase.
This record also forms a small provenance chain: the displayed response revision is the entity being explained, the versioned rule is the activity that evaluated it, and the trigger record is the resulting evidence. W3C PROV describes these entity, activity, and result relationships as a portable way to express provenance. Keeping the identifiers lets an auditor distinguish a real rule result from a stale annotation copied onto edited prose.
For several overlapping triggers, collect every start and end boundary, sort the boundaries, and partition the response into adjacent segments. Attach every trigger that fully covers each segment. This preserves two reasons that overlap on the same words instead of arbitrarily hiding one. The renderer can produce ordinary text nodes for unmarked segments and semantic mark elements for marked segments, with a nearby disclosure or details control that exposes the reason. It should never inject a matched phrase as HTML.
Coverage describes how much text is visually marked, not how convincing the explanation is. For a response of length (L), let ([s_i,e_i)) denote each half-open span in the declared offset unit. The union counts shared positions only once:
If a 1,200-code-unit response has spans ([180,205)), ([198,220)), and ([740,770)), the first two overlap by 7 units. Their union covers 40 units, and the third covers 30, so the marked coverage is (70/1200 = 0.0583), or 5.83%. Counting each interval separately would report 77 units and overstate the visible area. A high coverage number still says nothing about whether the selected rule was appropriate; measure false positives and reviewer agreement separately.
The interaction should explain the classification at the moment a person needs to judge or correct it. Microsoft Research’s Human-AI Interaction guidelines support making system behavior understandable and giving people useful control. For visual encoding, WCAG 2.2 Success Criterion 1.4.1 says color must not be the only means of conveying information. Pair a tint with an underline, icon, explicit “matched evidence” label, or text explanation. W3C’s ARIA Authoring Practices provide established interaction patterns for disclosure controls; prefer native disclosure behavior or follow a matching pattern instead of inventing keyboard behavior.
Implementation sketch
The segmenter below rejects stale revisions and invalid ranges before creating renderable pieces. Sorting rule identifiers makes overlapping evidence stable between renders. A production renderer can use the returned trigger list for a keyboard-accessible reason panel and can log a correction without storing the whole response in analytics.
typescripttype TriggerEvidence = {sourceRevision: string;start: number;end: number;matchedText: string;ruleId: string;reason: string;};type TextSegment = {start: number;end: number;text: string;triggers: TriggerEvidence[];};export function segmentTriggerEvidence(source: string,sourceRevision: string,evidence: TriggerEvidence[],): TextSegment[] {const boundaries = new Set<number>([0, source.length]);for (const item of evidence) {if (item.sourceRevision !== sourceRevision) {throw new Error("Trigger evidence belongs to a different text revision.");}if (!Number.isInteger(item.start) || !Number.isInteger(item.end) ||item.start < 0 || item.end > source.length || item.start >= item.end) {throw new RangeError("Trigger offsets are outside the response.");}if (source.slice(item.start, item.end) !== item.matchedText) {throw new Error("Trigger offsets no longer identify the recorded phrase.");}boundaries.add(item.start);boundaries.add(item.end);}const offsets = Array.from(boundaries).sort((a, b) => a - b);const segments: TextSegment[] = [];for (let index = 0; index < offsets.length - 1; index += 1) {const start = offsets[index];const end = offsets[index + 1];const triggers = evidence.filter((item) => item.start <= start && item.end >= end).sort((left, right) => left.ruleId.localeCompare(right.ruleId));segments.push({ start, end, text: source.slice(start, end), triggers });}return segments;}const response = "A refund requires a receipt.";const evidence: TriggerEvidence = {sourceRevision: "reply-r7",start: 2,end: 8,matchedText: "refund",ruleId: "refund-policy-v3",reason: "The refund review policy matched this phrase.",};const parts = segmentTriggerEvidence(response, "reply-r7", [evidence]);const markedPart = parts.find((part) => part.start === 2 && part.end === 8);console.assert(markedPart?.text === "refund");console.assert(markedPart?.triggers[0]?.ruleId === "refund-policy-v3");
Trade-offs
Exact ranges make review faster because a person can inspect the evidence beside the relevant words. The same precision can disclose a sensitive rule or imply more certainty than the system has. Keep internal rule identifiers and thresholds server-side; expose a reviewed explanation such as “This request matched our transfer-safety check.” For probabilistic explanations, name the method and avoid wording that attributes a model’s decision to one phrase unless the method supports that claim.
More matches provide coverage but compete for attention. A response containing dozens of overlapping marks becomes a heat map, not a readable explanation. Group adjacent spans from the same rule, preserve separate reasons where they differ, and summarize the count before expanding details. If an interface caps visible annotations, make that cap explicit and provide a way to inspect omitted items. Do not silently discard evidence to make the response look cleaner.
Streaming adds latency and revision complexity. A rule can highlight an append-only prefix if the displayed prefix and revision are stable, but post-generation normalization, citation insertion, or user edits invalidate downstream offsets. Waiting for a committed sentence makes explanation less immediate but more accurate. The right choice depends on whether the interface can preserve stable segment identities while new text arrives.
Failure modes and misconceptions
A stale range is the most dangerous visual failure because the interface can make false evidence look precise. A normalization pass that changes a curly quote, collapses whitespace, or inserts a citation shifts later offsets. Store the revision alongside the evidence and check both revision and matched text before rendering. When either check fails, remove the mark and show that the explanation needs refreshing; guessing a nearby phrase is worse than an absent highlight.
Offset unit disagreement creates less obvious drift. UTF-8 byte positions and Unicode code-point positions are not JavaScript string indexes. Define UTF-16 offsets for browser-facing records or convert from the producer’s unit using a tested boundary map. Include emoji, combining marks, repeated phrases, and right-to-left text in fixtures. Repeated words require offsets, not a search for the first matching substring.
Color-only emphasis can disappear in grayscale, low-contrast themes, forced-colors mode, or for people with color-vision differences. Keep the words readable, add a second visual cue, and expose an explanation through a control operable by keyboard. Announcing every token as it streams can overwhelm assistive technology; announce a concise completed summary and let the person inspect details.
Finally, a highlighted trigger is not automatically a faithful explanation of a model decision. A deterministic policy engine can point to a literal match. A classifier’s salient span is conditional on the attribution method and the input; correlated words may score highly without being the sole cause. State the source of the evidence and its limits so users do not mistake a useful clue for a guarantee.
Decision scenario
A support assistant streams a 900-character answer and runs a transfer-risk rule over the completed response. The rule selects “send the funds today,” but a cleanup step later replaces two spaces and inserts a citation before that phrase. Its stored offsets now point into different text even though the old range still fits inside the response.
The service should bind the trigger record to the pre-cleanup revision and refuse to render it against the post-cleanup text. Re-run the rule on the final revision, verify the matched slice, and emit a new evidence record. If the rule cannot be re-evaluated, present the answer without the old mark and offer a plain explanation that evidence is being refreshed. In the audit event, keep the rule version, revision identifiers, and outcome; avoid retaining the full answer unless the product’s data policy permits it.
For release, test offset integrity after normalization, overlapping triggers, keyboard access to reasons, and non-color rendering in both light and dark themes. Track the rate of stale evidence and user corrections alongside task success. A lower stale rate is meaningful only if the rule still catches the intended cases; otherwise the interface may merely be suppressing useful explanations.