In what scenarios must an instance reconcile a safety verdict that arrives after the OTel GenAI span it governs has already been exported and sealed

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (e.g. `gen_ai.*` attributes on `chat`/`execute_tool` spans) and correlates them post-hoc with asynchronous safety/policy verdicts produced by a separate classifier, guardrail service, or human-in-the-loop reviewer. Does not apply to synchronous inline guardrails that block a call before the span closes.

Core Distinction

The failure is not "a safety verdict was missed." It is that the verdict and the span describe the *same logical event* but are produced under two incompatible consistency models: the span is **append-only and terminal at export**, while the verdict is **mutable and late-binding**. Observability systems assume a span is immutable once the exporter flushes it to the collector; safety systems assume a verdict can attach to any trace ID at any time, including minutes later after an async judge model finishes reasoning. The boundary condition is the window between span export and verdict arrival—and the correlation key that must survive that window.

The non-obvious part: the join key is usually the `trace_id`, but the verdict is scoped to a *specific generation within that trace* (one `chat` span among many). A trace can contain three tool calls, two model invocations, and one injected document. A verdict of "unsafe: prompt injection in retrieved context" must bind to the exact `gen_ai.completion.0` span whose input carried the poisoned chunk—not the root span, not the trace. When the verdict arrives after export, the correlation must re-identify that span by a stable secondary key (span ID + a content hash), because the exporter may have already dropped, sampled, or rewritten attributes.

What Was Observed

A retrieval-augmented agent executed a task: `retrieve → chat(model) → execute_tool(send_email) → chat(model)`. Spans were emitted with `gen_ai.operation.name`, `gen_ai.request.model`, and a `trace_id`. The exporter used a batch processor with a 5-second flush and **head-based sampling at 20%**. The async safety judge—a separate model scoring the retrieved context—completed 40 seconds after the trace closed and emitted a verdict keyed only to `trace_id` with label `injection_suspected`.

Three distinct breakages surfaced:

  1. **Sampling asymmetry.** The trace was *not* sampled (80% chance), so no spans existed in the backend. The verdict arrived, referenced a `trace_id` with no spans, and the correlation job silently wrote a "verdict-without-trace" orphan row. The safety signal was recorded but never *attached* to the generation it governed—the audit trail showed a verdict floating with no observable cause.
  1. **Span ambiguity.** When the trace *was* sampled, the verdict carried no span ID. The correlator, forced to pick, bound the verdict to the root span. Downstream, the dashboard showed the injection flag on the agent's top-level operation, not on the `chat` span whose input was poisoned. An incident responder reading the trace concluded the *final* model call was compromised and rolled back the wrong component.
  1. **Attribute rewrite.** The exporter had truncated `gen_ai.prompt` attributes to 1024 chars for cost control. The verdict's evidence pointer was a content hash of the *full* prompt. The correlator could not match the hash against the truncated attribute, so it fell back to `trace_id`-only matching—reintroducing ambiguity (2) for the subset of spans where truncation occurred.

The invariant that was violated: **a verdict must be correlatable to the exact generation span it evaluates, independent of sampling decisions and attribute truncation.** Neither the span nor the verdict alone can guarantee this; it requires a shared, export-surviving join key.

Condition of Validity

The correlation is valid only when all of the following hold:

If any condition fails, the correlation degrades to `trace_id`-only matching, which is valid only when the trace contains exactly one generation span. That is the degenerate case, not the general one.

Decision Boundary

The operator must decide, at verdict-arrival time, between two policies:

The boundary is severity-dependent: low-severity verdicts may tolerate `trace_id`-only binding with a confidence penalty; high-severity verdicts (injection, exfiltration, policy-block) must never bind without span-scoped resolution. Binding a high-severity verdict to the wrong span is worse than leaving it unbound, because it produces a *confident wrong* audit record.

Operational Effect

With the invariant enforced, the failure trace becomes:

  1. Agent emits `chat` span with `gen_ai.input.digest = sha256(canonical_input)` computed pre-truncation, plus `trace_id`/`span_id`.
  2. Sampler is configured tail-based with a verdict-pending hold: traces flagged `safety.pending=true` are retained for a TTL (e.g. 10 min) exceeding the judge's p99 latency.
  3. Judge returns verdict `{trace_id, span_id, digest, label, severity}`.
  4. Correlator resolves `span_id` → span, verifies `digest` matches the span's `gen_ai.input.digest`. On match: attach, mark adjudicated. On mismatch or missing span: route to quarantine, emit `safety.verdict.unbound` metric, page if severity ≥ high.

The measurable effects: orphan-verdict rate drops from "silently lost" to a tracked metric; mis-binding rate (verdict on wrong span) goes to zero because digest mismatch forces quarantine rather than fallback; and the audit trail preserves both the original suspicion and its later clearance as separate, ordered records.

The residual risk is TTL exhaustion—a judge slower than the retention window still yields an unbound verdict. That is acceptable *only* because it is now visible as a metric rather than an invisible drop.

import hashlib
from dataclasses import dataclass
from typing import Optional


class VerdictBindingError(RuntimeError):
    """Raised when a safety verdict cannot be bound to its governing span."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    input_digest: Optional[str]   # sha256 over canonical pre-truncation input
    retained: bool = True


@dataclass
class Verdict:
    trace_id: str
    span_id: Optional[str]
    digest: Optional[str]
    label: str
    severity: str  # "low" | "high"


def canonical_digest(raw_input: str) -> str:
    # Canonicalize BEFORE truncation/redaction so the digest is stable.
    return hashlib.sha256(raw_input.strip().encode("utf-8")).hexdigest()


def bind_verdict(verdict: Verdict, span_index: dict[str, Span]) -> Span:
    """
    Bind a late-arriving verdict to the exact generation span it governs.
    Enforces: span-scoped key + digest match, or quarantine. Never falls
    back to trace_id-only binding for high-severity verdicts.
    """
    key = f"{verdict.trace_id}:{verdict.span_id}" if verdict.span_id else None
    span = span_index.get(key) if key else None

    if span is None or not span.retained:
        # Span sampled out, expired, or never identified.
        if verdict.severity == "high":
            raise VerdictBindingError(
                f"High-severity verdict {verdict.label} for trace "
                f"{verdict.trace_id} has no resolvable span; quarantining "
                f"(digest={verdict.digest}). Do not bind to root."
            )
        # Low severity: quarantine with confidence penalty, still no root bind.
        raise VerdictBindingError(
            f"Low-severity verdict {verdict.label} unbound for trace "
            f"{verdict.trace_id}; recorded to quarantine queue."
        )

    if verdict.digest is None or span.input_digest is None:
        raise VerdictBindingError(
            f"Missing digest on verdict or span for {key}; cannot verify "
            f"content identity, refusing ambiguous bind."
        )

    if verdict.digest != span.input_digest:
        # Attribute truncation or tampering: digest mismatch.
        raise VerdictBindingError(
            f"Digest mismatch for {key}: verdict={verdict.digest[:12]} "
            f"span={span.input_digest[:12]}; content identity unverified."
        )

    return span


def record_verdict(verdict: Verdict, span_index: dict[str, Span]) -> str:
    try:
        span = bind_verdict(verdict, span_index)
        return f"bound:{span.span_id}:{verdict.label}"
    except VerdictBindingError as exc:
        # Append-only quarantine; never overwrite prior records.
        return f"quarantined:{verdict.trace_id}:{verdict.label}:{exc}"