# Which invariants prevent span-level hallucination attribution from collapsing under GenAI semantic convention drift **Date of Record:** 2026 November 25 **Scope:** Applies to trace-based hallucination attribution pipelines that reconstruct an agent's reasoning from OpenTelemetry GenAI spans (`gen_ai.*` attributes) emitted by one or more LLM/tool runtimes. Does not apply to systems that attribute hallucination purely from the final output text without span reconstruction, nor to single-vendor traces where the emitter and the attribution consumer share a locked schema version. ## Core Distinction The failure is not "a span is missing an attribute." It is that *attribute semantics drift across the span tree while remaining individually well-formed*, so a conformance test that validates each span in isolation passes, yet the reconstructed reasoning graph attributes a hallucination to the wrong step. The distinction that matters: **schema validity is per-span and local; attribution correctness is cross-span and global.** GenAI semantic conventions version the *shape* of `gen_ai.*` attributes (e.g. `gen_ai.usage.input_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`) but do not version the *causal meaning* the attribution layer reads into them—which span is the "source" of a claim, which tool output "grounded" it, and whether a `gen_ai.completion` span's `index` is a logical turn or a physical retry. Concretely: a runtime that upgrades from one convention revision to the next may keep emitting `gen_ai.usage.input_tokens` but change whether it counts the system prompt, or may begin emitting a `gen_ai.tool.call` child span under a retried request where previously the retry produced a sibling span. Every span still validates. The attribution graph silently rewires: the hallucinated claim now traces to a tool span that was actually discarded by a retry, so the auditor blames the retrieval tool for a fabrication the model produced from its own prior context. ## What Was Observed A three-step agent (retrieve → reason → answer) emitted spans under a mixed fleet: two model runtimes on convention revision A and one on revision B. The attribution consumer built a directed graph by joining spans on `trace_id` and ordering by `start_time_unix_nano`, then walked backward from the answer span to the first span whose `gen_ai.completion` text contained the claim's n-gram. Observed failure trace: 1. Runtime B (revision B) emitted a retried reasoning call as a **new span with the same `gen_ai.request.model` and a re-used `start_time` truncated to millisecond resolution**, colliding with the original span's ordering key. 2. The attribution join, keyed on `(trace_id, start_time_unix_nano)`, produced a non-deterministic tie-break across the two colliding spans; on roughly 30% of replays the *discarded* retry span won. 3. The discarded retry had a `gen_ai.completion` containing a plausible-but-fabricated sentence (the model's first attempt before the retry corrected it). The n-gram walk matched the claim there, and the auditor attributed the hallucination to the retrieval tool that fed *that* attempt—not the model. 4. Per-span conformance testing reported 100% pass: every span had required attributes, correct types, valid enum values for `gen_ai.response.finish_reasons`. The drift was entirely in the *ordering key semantics* (millisecond truncation) and *retry topology* (sibling vs child), neither of which any per-span test can see. The replay discrepancy is the tell: identical trace bytes, different attribution verdicts across replays. That is the signature of a non-deterministic join, not a data-quality problem. ## Condition of Validity Attribution is only valid when three cross-span invariants hold simultaneously. They are *not* implied by per-span conformance and must be asserted separately. - **Total ordering invariant.** Every span in the trace carries a strictly monotonic, collision-free ordering key. `start_time_unix_nano` at millisecond resolution violates this the moment a retry re-uses a truncated timestamp. The guardrail is a per-runtime monotonic sequence attribute (e.g. a `gen_ai.sequence` or span-level `span_id` parent linkage) and a conformance test that *fails the trace* if any two spans share an ordering key. Ordering must be validated at trace granularity, not span granularity. - **Topology invariant.** Retry and fallback spans must be distinguishable from logical turns by structure, not by timestamp. A retried call must be a child of the retry-decision span (or explicitly flagged `gen_ai.retry=true` with a `retry_of` link), so the attribution walk can *exclude* superseded spans. If revision drift changes retry topology from sibling to child, the consumer must detect the topology shift before trusting the graph. - **Provenance invariant.** The n-gram match must be bounded to spans that are *causally upstream* of the answer span in the validated topology, and the matching span must be the *surviving* attempt. Attribution that matches against any span containing the n-gram is invalid whenever superseded spans remain in the trace. The condition of validity, stated as one sentence: **attribution is sound only over a trace whose ordering key is collision-free, whose retry topology is explicit and revision-stable, and whose match set is restricted to surviving causal ancestors.** ## Decision Boundary The boundary between "trust the reconstructed graph" and "refuse and re-derive" is crossed when any of the following is detected during conformance testing *before* attribution runs: - **Ordering collision:** two spans share `(trace_id, ordering_key)`. Decision: refuse attribution for that trace; do not tie-break by span_id lexicographic order (that reintroduces non-determinism). Emit a `TraceOrderingCollision` and quarantine. - **Topology ambiguity:** a span with `gen_ai.response.finish_reasons` present but no explicit retry linkage, while a sibling span exists with the same `gen_ai.request.model` and overlapping time range. Decision: treat as a superseded-attempt ambiguity; refuse and require the emitter to add `retry_of`. - **Convention revision skew within a trace:** spans from revision A and revision B in the same trace where the revision changes retry or usage semantics. Decision: pin the trace to the *lowest* revision's semantics for attribution, and log a skew warning; do not mix interpretations across the walk. Below the boundary (no collision, explicit topology, single revision) the graph is trusted. Above it, the pipeline must fail closed—attribution from an ambiguous graph is worse than no attribution, because it produces a confident wrong blame that propagates into the agent's episodic memory as a false lesson ("the retrieval tool hallucinates") and corrupts future retrieval policy. The non-obvious trap: teams add a *global* conformance test that re-validates each span, see 100% pass, and conclude the trace is trustworthy. Per-span pass is necessary but never sufficient. The boundary is crossed at the *trace* level, and only a trace-level invariant check catches it. ## Operational Effect When the three invariants are enforced, the operational effect is a shift from probabilistic blame to bounded blame. Attribution verdicts become replay-stable: identical trace bytes yield identical verdicts across N replays, and the auditor can certify a hallucination source with a confidence that is a property of the *graph*, not of a sampling seed. When the boundary is crossed and the pipeline fails closed, the agent's memory layer receives a `TraceAttributionRefused` record instead of a false causal edge—so the next cold start does not inherit a poisoned "tool is unreliable" prior. The cost is that some genuinely attributable hallucinations go unattributed during convention migrations; the benefit is that the attribution layer never writes a wrong lesson into episodic memory, which is the failure that compounds across sessions and is far harder to detect than a missing verdict. ```python import hashlib from dataclasses import dataclass from typing import Sequence class TraceAttributionRefused(RuntimeError): """Raised when a trace cannot be soundly attributed due to cross-span invariant violation.""" @dataclass(frozen=True) class Span: span_id: str trace_id: str ordering_key: int # monotonic, collision-free required convention_rev: str # e.g. "A" or "B" is_retry: bool retry_of: str | None completion_text: str finish_reasons: tuple[str, ...] def assert_attribution_invariants(spans: Sequence[Span]) -> None: if not spans: raise TraceAttributionRefused("empty trace: nothing to attribute") trace_ids = {s.trace_id for s in spans} if len(trace_ids) != 1: raise TraceAttributionRefused(f"multi-trace batch: {trace_ids}") # Ordering invariant: collision-free ordering key across the whole trace. keys = [s.ordering_key for s in spans] if len(keys) != len(set(keys)): dupes = sorted({k for k in keys if keys.count(k) > 1}) raise TraceAttributionRefused( f"ordering collision on keys {dupes}; refusing (tie-break is non-deterministic)" ) # Topology invariant: retries must be explicitly linked, not inferred by timestamp. by_id = {s.span_id: s for s in spans} for s in spans: if s.is_retry and (s.retry_of is None or s.retry_of not in by_id): raise TraceAttributionRefused( f"retry span {s.span_id} lacks resolvable retry_of={s.retry_of!r}" ) # Convention-revision skew invariant: refuse mixed-revision traces that # change retry/usage semantics rather than silently reinterpreting. revs = {s.convention_rev for s in spans} if len(revs) > 1: raise TraceAttributionRefused( f"mixed convention revisions {sorted(revs)} in one trace; " "pin to lowest revision or reject" ) def attribute_hallucination(spans: Sequence[Span], claim: str) -> tuple[str, str]: """Return (blamed_span_id, rationale). Raises if the graph is unsound.""" assert_attribution_invariants(spans) # Provenance invariant: match only surviving (non-superseded) causal ancestors. superseded = {s.retry_of for s in spans if s.is_retry and s.retry_of} survivors = [s for s in spans if s.span_id not in superseded] matches = [s for s in survivors if claim in s.completion_text] if not matches: raise TraceAttributionRefused( f"claim {claim!r} not found in surviving spans; cannot attribute" ) # Deterministic: earliest surviving match by ordering key. source = min(matches, key=lambda s: s.ordering_key) digest = hashlib.sha256(claim.encode()).hexdigest()[:12] return source.span_id, f"claim#{digest} matched surviving span {source.span_id}" ```