# Which invariants prevent OTel span-to-token-to-safety correlation from silently misattributing a safety event to the wrong generation **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per LLM generation, reconcile token counts from provider usage payloads against span attributes, and attach safety-event annotations (moderation flags, refusal markers, policy hits) to a specific generation. Does not apply to single-shot, un-instrumented inference or to batch jobs where each generation gets a dedicated trace with no fan-out. ## Core Distinction Observability correlation is not logging. A log line is a claim; a correlated trace is an *identity assertion* — that this token count, this span, and this safety annotation all describe the same LLM invocation. The failure mode here is not "the data was missing" but "the data was present and *plausibly wrong*." Three independent telemetry channels (OTel spans, provider token-usage payloads, safety-event annotations) each carry their own identity key, and each is produced at a different point in the generation lifecycle by a different subsystem with a different clock. The non-obvious boundary is this: **a safety event and a token-usage record can both be correctly emitted, both be correctly timestamped, and still be attributed to the wrong generation** because span identity is resolved by a key that is not stable across the retry/streaming boundary. The invariant that prevents this is *generation-scoped idempotency*: every artifact attached to a generation must carry a `generation_id` minted *before* the first token is requested and never reused across retries, and correlation must *fail closed* — an annotation whose `generation_id` does not resolve to exactly one span must be dropped and counted, never attached by nearest-timestamp heuristics. ## What Was Observed A streaming agent runtime emitted one OTel span per generation with `span_id` assigned at span start, and set `gen_ai.usage.input_tokens` / `output_tokens` at span end from the provider's final usage chunk. Safety annotations arrived asynchronously from a moderation sidecar keyed on a *request hash* (a hash of the serialized prompt + sampling params), not on `generation_id`. The moderation sidecar ran *after* the stream completed, with a p99 latency of ~1.8s. Trigger condition: the agent issued a generation, the response was flagged, and a retry fired within the moderation latency window. Because the retry used the *same* serialized prompt and sampling params (a deterministic retry), it produced the *same* request hash. The moderation sidecar's annotation for retry attempt #2 carried the identical hash as attempt #1. The correlation layer, keyed on request hash, resolved the flag to *both* spans — and because it attached to the first span it found, the safety event landed on the *successful* attempt while the token-usage record for the flagged, discarded attempt was orphaned. Observed trace shape after the incident: - Span A (attempt 1): `status=ERROR`, `output_tokens=0` (stream aborted on flag), no safety annotation. - Span B (attempt 2): `status=OK`, `output_tokens=412`, safety annotation `policy=harassment, severity=high`. - Provider usage ledger: 412 output tokens billed to attempt 2, 0 to attempt 1 — consistent with spans, *inconsistent with the annotation*, which says a high-severity harassment output was actually served to the user. The result: dashboards reported a served safety violation that never happened, incident response paged on a false positive, and — more dangerously — in the mirror case (retry also flagged, only one annotation emitted for the shared hash) a *real* served violation was suppressed because the annotation attached to the discarded attempt. ## Condition of Validity The correlation is valid only when all three hold: 1. **Identity is generation-scoped, not request-scoped.** The correlation key must be minted per attempt (`generation_id`), not derived from request content. Any key that is a function of the prompt, prompt hash, or sampling params is *not* unique across retries and is invalid for correlation. 2. **The annotation's timestamp is causally ordered against span end, not wall-clock-close.** A moderation annotation with `t_annotation > t_span_end` for a *different* span but within the same hash bucket must not be resolved by proximity. Resolution requires exact `generation_id` equality. 3. **Token accounting reconciles to the span that actually consumed the tokens.** `output_tokens` on a span must equal the provider usage record for that same `generation_id`; a mismatch is a correlation fault, not a billing discrepancy, and must be surfaced as such. When request-hash keying is in use (as it was), the invariant is violated by construction and the only safe posture is to treat the correlation as *unverified* — annotations attach to a hash bucket, not a generation, and must be reported as bucket-level, never generation-level. ## Decision Boundary The boundary is whether the correlation layer is allowed to *guess*. Two regimes: - **Fail-closed regime (required for safety events):** if `generation_id` on an annotation does not resolve to exactly one span with a matching `generation_id`, the annotation is quarantined with reason `unresolvable_generation`, counted, and *not* attached. A quarantined high-severity annotation is an incident signal in its own right; a silently-dropped one is not. - **Fail-open regime (permitted only for non-safety telemetry):** cost/token aggregates may be reconciled by best-effort nearest-timestamp join, because a misattributed token count corrupts a dashboard but does not corrupt a safety decision. The decision boundary is crossed the moment a safety annotation is joined using the same code path as cost telemetry. Safety correlation must be a *separate, stricter resolver* with its own failure semantics. If a single `correlate()` function serves both, the invariant cannot be enforced, because the two regimes require opposite behavior on unresolved keys. ## Operational Effect Enforcing generation-scoped identity and fail-closed safety correlation changes three things operationally: 1. **Retries become first-class spans with distinct identities.** A deterministic retry no longer collides with its predecessor; each attempt carries its own `generation_id` and its own annotation slot. The `request_hash` is retained only as a *grouping* attribute for cross-attempt analysis, never as a correlation key. 2. **Orphaned annotations become visible.** A quarantine counter (`safety_annotations_quarantined_total{reason="unresolvable_generation"}`) turns the previously silent suppression case into a monitored signal. A nonzero rate is a correlation-layer bug, not a model bug. 3. **Token-usage reconciliation becomes a correlation assertion.** `span.output_tokens != usage.output_tokens` for the same `generation_id` raises, because it means the span and the usage record disagree about which generation they describe — the earliest detectable symptom of the failure. ## Code ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class CorrelationInvariantError(RuntimeError): """Raised when a safety annotation cannot be bound to exactly one generation.""" @dataclass(frozen=True) class Span: generation_id: str request_hash: str # grouping only, NEVER a correlation key status: str # "OK" | "ERROR" output_tokens: int @dataclass(frozen=True) class UsageRecord: generation_id: str output_tokens: int @dataclass(frozen=True) class SafetyAnnotation: generation_id: Optional[str] request_hash: str policy: str severity: str @dataclass class CorrelationResult: attached: dict[str, list[SafetyAnnotation]] = field(default_factory=dict) quarantined: list[SafetyAnnotation] = field(default_factory=list) def correlate_safety_events( spans: list[Span], usage: list[UsageRecord], annotations: list[SafetyAnnotation], ) -> CorrelationResult: # Invariant 3: token accounting must reconcile per generation_id. usage_by_gen = {u.generation_id: u.output_tokens for u in usage} for s in spans: if s.generation_id not in usage_by_gen: raise CorrelationInvariantError( f"span {s.generation_id}: no usage record; correlation unverified" ) if usage_by_gen[s.generation_id] != s.output_tokens: raise CorrelationInvariantError( f"span {s.generation_id}: token mismatch " f"span={s.output_tokens} usage={usage_by_gen[s.generation_id]}" ) span_ids = {s.generation_id for s in spans} result = CorrelationResult() for ann in annotations: # Invariant 1: identity must be generation-scoped, not request-hash-scoped. if ann.generation_id is None: raise CorrelationInvariantError( f"annotation policy={ann.policy} has no generation_id; " f"request_hash={ann.request_hash} is not a valid correlation key" ) if ann.generation_id not in span_ids: # Invariant 2: fail closed. Never attach by nearest-timestamp heuristic. result.quarantined.append(ann) continue result.attached.setdefault(ann.generation_id, []).append(ann) return result ```