# Which invariants prevent trace-linked safety interventions from silently decoupling guardrail verdicts from the GenAI spans they claim to govern **Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) and attaches guardrail verdicts (allow/deny/redact) to those spans for incident replay and post-hoc safety audit. Does not apply to synchronous in-process guardrails whose verdict is consumed inline and never persisted for replay. ## Core Distinction A guardrail verdict is a *judgment about a span*, not a property *of* the span. The two are joined by a correlation key — typically `trace_id` + `span_id`, sometimes a derived `gen_ai.request.id` or a hash of the prompt. The failure mode this record isolates is **verdict–span decoupling**: the guardrail pipeline classifies a request, but the verdict lands on a span (or a synthetic span) that does not share the exact identity tuple of the span the model actually executed under. Replay then "reconstructs" an incident where the deny verdict is attached to a span whose prompt differs from the one the guardrail saw — or where the span is missing entirely and the verdict floats as an orphan. This is not a logging bug. It is a *continuity invariant violation*: the safety record and the execution record diverge, and the divergence is invisible because both halves are individually well-formed. ## What Was Observed In a tool-using agent with three guardrail stages (input filter, pre-tool-call filter, output filter), verdicts were emitted by a sidecar process asynchronously. The sidecar received the request body, ran the classifier, and emitted an OTel span of kind `guardrail.verdict` with attributes `guardrail.verdict`, `guardrail.policy_id`, and `guardrail.target_span_id`. The target span ID was threaded through from the *inbound HTTP request* via a header (`X-Target-Span`), populated by the agent runtime *before* the actual `gen_ai.chat` span was created — because the runtime used a provisional span ID to allow the sidecar to start early. The provisional ID was not the final span ID. When the OTel SDK finalized the `gen_ai.chat` span, the SDK assigned a fresh 8-byte span ID. The sidecar's `guardrail.target_span_id` therefore pointed at an ID that never appeared in the trace. The verdict span was still exported, still had the correct `trace_id`, and still carried a `deny` verdict — but `target_span_id` resolved to nothing. Incident replay did not fail loudly. The replay tool joined verdict spans to execution spans on `trace_id` alone when `target_span_id` was unresolvable, and since a single agent turn frequently produces multiple `gen_ai.chat` spans (planner, tool-selection, summarizer), the deny verdict was attached to the *first* chat span in the trace, not the span it actually governed. The replayed incident showed a blocked prompt that the guardrail had never seen. The trigger condition is narrow and reproducible: 1. The runtime allocates a correlation handle before span creation (necessary to let async guardrails start without blocking the model call). 2. Span finalization reassigns identity (default OTel behavior; span IDs are assigned at `Start`, but any wrapper that creates a child span, retries, or re-parents will diverge from the provisional handle). 3. The join logic treats `trace_id` as a sufficient fallback key. Condition 3 is the silent one. It converts a hard integrity failure (unresolvable target) into a soft misattribution (verdict lands on the wrong span), and soft failures do not page anyone. A second observed variant: on retry, the agent runtime re-issued the model call under a new span but reused the provisional correlation handle. Two verdicts (one per attempt) carried the same `target_span_id`, and replay could not determine which attempt the deny applied to. The guardrail had actually denied the *second* attempt's prompt; replay attributed it to the first. ## Condition of Validity The invariant that makes trace-linked verdicts sound is: > **For every guardrail verdict span V with attribute `guardrail.target_span_id = S`, there must exist exactly one `gen_ai.*` execution span E in the same trace with `E.span_id == S`, and V must have been emitted with `V.start_time >= E.start_time` and `V.end_time <= E.end_time + ε` for a bounded ε (the guardrail's own latency budget).** Three clauses, each independently violable: - **Existence**: S resolves. The provisional-ID bug violates this. - **Uniqueness**: exactly one E. Retries and re-parented child spans violate this unless attempt-scoped IDs are used. - **Temporal containment**: the verdict was produced within the execution window of E. An async guardrail that finishes after the span closes (e.g., a slow output classifier on a streamed response) violates this, and replay will attach a verdict to a span that had already committed its output. The invariant is only *checkable* if the verdict span carries enough to reconstruct S without trusting the runtime's provisional handle. In practice this means the verdict must carry a content-addressed witness: a hash over `(model_id, canonicalized_prompt, tool_call_args)` — the same tuple the guardrail actually classified. If the witness on V does not match the witness recomputed from E, the join is invalid regardless of what `target_span_id` says. ## Decision Boundary The boundary is between two join strategies: - **Identity join** (`target_span_id == E.span_id`): sound only if span identity is stable from allocation to finalization. It is not, in any runtime that pre-allocates correlation handles or retries. - **Witness join** (content hash on V matches recomputed hash on E, with `target_span_id` as a hint): sound under retries and re-parenting, because the hash is a function of what was actually classified, not of when the handle was minted. Choose witness join whenever any of the following hold: guardrails run out-of-band, the agent retries model calls, streaming responses let output classifiers finish after span close, or replay is used for incident attribution rather than aggregate metrics. Choose identity join only when the guardrail is synchronous, in-process, and the span is created *by* the guardrail wrapper so identity cannot drift. The decision is not "which is more precise." Identity join is *more* precise when it holds and *silently wrong* when it doesn't. Witness join is *less* precise (a hash collision or a canonicalization mismatch causes a false negative — a dropped verdict) but *fails closed*: a witness mismatch is a detectable integrity error, not a misattribution. ## Operational Effect Under identity join, the operational effect of the provisional-ID bug is that the safety audit reports a *lower* deny rate than reality, because denials land on the wrong span and aggregate counters keyed by `(span_kind, verdict)` are computed per-trace and de-duplicated. The guardrail is working; the record says it isn't. Teams respond by tightening the policy, which raises false positives on the spans that *do* resolve, and the misattribution compounds. Under witness join with a strict integrity check, the same bug produces a hard, paging failure at replay time: `VerdictSpanDecoupledError` — the verdict's witness does not match any execution span's witness. The fix is then obvious (stop trusting the provisional handle; derive the witness from the classified payload), and the invariant is restored. The cost is that every verdict must carry a canonicalized payload hash, which means the guardrail must classify exactly the bytes the model will see — no post-classification prompt templating, no system-prompt injection after the filter. That constraint is itself worth enforcing. The general lesson for agent runtimes: **any correlation key minted before the thing it correlates exists is a provisional key, and provisional keys must be demoted to hints, never used as join predicates.** The durable join predicate must be a witness over the content that was actually judged. ```python import hashlib import json from dataclasses import dataclass from typing import Optional class VerdictSpanDecoupledError(RuntimeError): """Raised when a guardrail verdict cannot be soundly joined to an execution span.""" @dataclass(frozen=True) class VerdictSpan: trace_id: str verdict: str # "allow" | "deny" | "redact" policy_id: str target_span_id: Optional[str] # provisional handle; a HINT, not a join key witness: str # sha256 over canonicalized classified payload start_ns: int end_ns: int @dataclass(frozen=True) class ExecutionSpan: trace_id: str span_id: str model_id: str canonical_prompt: str tool_call_args: Optional[dict] start_ns: int end_ns: int def compute_witness(model_id: str, prompt: str, tool_args: Optional[dict]) -> str: payload = json.dumps( {"model": model_id, "prompt": prompt, "tool_args": tool_args or {}}, sort_keys=True, separators=(",", ":"), ).encode("utf-8") return hashlib.sha256(payload).hexdigest() def join_verdict_to_span( verdict: VerdictSpan, candidates: list[ExecutionSpan], epsilon_ns: int = 2_000_000_000, ) -> ExecutionSpan: """ Sound join: witness must match exactly one execution span in the trace, and the verdict must be temporally contained within that span's window. target_span_id is consulted only to disambiguate, never to decide. """ in_trace = [e for e in candidates if e.trace_id == verdict.trace_id] if not in_trace: raise VerdictSpanDecoupledError( f"no execution span in trace {verdict.trace_id} for verdict {verdict.policy_id}" ) witness_matches = [ e for e in in_trace if compute_witness(e.model_id, e.canonical_prompt, e.tool_call_args) == verdict.witness ] if len(witness_matches) == 0: # Provisional-ID drift, post-classification templating, or retry reuse. raise VerdictSpanDecoupledError( f"verdict witness {verdict.witness[:12]}... matches no span in trace " f"{verdict.trace_id}; target_span_id={verdict.target_span_id!r} is unresolvable" ) if len(witness_matches) > 1: # Retries with identical prompts: disambiguate by provisional hint, else refuse. hinted = [e for e in witness_matches if e.span_id == verdict.target_span_id] if len(hinted) != 1: raise VerdictSpanDecoupledError( f"ambiguous verdict: {len(witness_matches)} spans share witness; " f"hint {verdict.target_span_id!r} resolved to {len(hinted)}" ) witness_matches = hinted span = witness_matches[0] if not (verdict.start_ns >= span.start_ns and verdict.end_ns <= span.end_ns + epsilon_ns): raise VerdictSpanDecoupledError( f"verdict {verdict.policy_id} not temporally contained in span {span.span_id}: " f"verdict=[{verdict.start_ns},{verdict.end_ns}] span=[{span.start_ns},{span.end_ns}]" ) return span ```