# Why does an instance lose trace-to-verdict correlation when a safety verdict arrives after the span has already been sealed? **Date of Record:** 2026 November 23 **Scope:** Applies to observability pipelines that emit OpenTelemetry-style agent spans synchronously at task completion while safety-benchmark verdicts and prompt-injection alerts are produced asynchronously by separate evaluator models after the trace is flushed. Does not apply to pipelines where verdicts are computed inline before span emission, or to single-turn systems with no post-hoc evaluation. ## Core Distinction The failure is not "missing telemetry." Every artifact exists: the agent span, the safety verdict, the injection alert. The failure is that the *join key* between them is destroyed by the ordering of two asynchronous producers that share no transactional boundary. A span is immutable and sealed once `span.end()` fires; a verdict is a probabilistic classification emitted seconds to minutes later by an evaluator LLM. The correlation layer must reconstruct a relationship that was never co-written, and it does so using attributes that are themselves lossy: hashes of truncated prompts, timestamps with clock skew, and session IDs that may be re-minted on resume. The invariant that breaks: **for every verdict there exists exactly one span whose payload the verdict evaluated.** In practice the pipeline maintains only "there exists at least one span with a plausibly matching key," which is strictly weaker and admits both false joins and orphaned verdicts. ## What Was Observed A production agent trace store emitted spans with `trace_id`, `span_id`, and a `prompt_digest` computed as `sha256(prompt[:4096])`. The safety evaluator ran out-of-band, re-received the prompt from a message queue (with its own truncation at 2048 tokens), and emitted verdicts keyed on `sha256(prompt[:2048])` plus a wall-clock `evaluated_at`. The injection classifier emitted alerts keyed on `session_id` only. Three distinct break classes appeared in a 24-hour window: 1. **Digest divergence on long prompts.** Any prompt exceeding 2048 tokens produced a verdict whose digest could never match the span digest, because the evaluator hashed a different prefix. These verdicts became permanent orphans — present in the verdict store, unjoinable to any span. Roughly 11% of verdicts in the window. 2. **Late-arrival re-attribution.** When an agent checkpointed and resumed, the resumed instance re-emitted a span under a *new* `trace_id` but reused the original `session_id`. The injection classifier, keyed on `session_id`, attached its alert to whichever span the correlator saw first — frequently the pre-checkpoint span whose context window did not contain the injected content. The alert landed on an innocent span; the poisoned span carried a clean verdict. 3. **Sealed-span mutation attempt.** A backfill job tried to attach verdicts to sealed spans by rewriting span attributes. The span store rejected the writes (immutability guarantee), and the correlator silently dropped them, logging at DEBUG. The dashboards showed 100% "verdict coverage" because coverage was computed over *joinable* verdicts, not *emitted* ones — a denominator that excluded exactly the failures. The compounding effect: an injection alert attached to the wrong span caused the auditor agent to mark a clean turn as compromised, which triggered a re-run, which produced a fresh trace with fresh digests, which the original verdict could not match. The re-run's verdict then arrived late and attached to the *next* turn's span via the reused `session_id`. The misattribution propagated forward as a stable-but-wrong correlation. ## Condition of Validity The correlation is only sound when all of the following hold simultaneously: - The digest function, truncation length, and normalization (whitespace, unicode NFC) are *byte-identical* across span emitter and every evaluator. Any divergence in truncation boundary produces a silent non-match, not an error. - The join key is *content-addressed* (digest of the exact evaluated payload), not *identity-addressed* (`session_id`, `trace_id`) — because identity is re-minted on checkpoint/resume while content is not. - Verdict arrival is bounded by a declared watermark. Spans younger than the watermark are held in a "provisional" state and are not eligible for safety sign-off; spans older than the watermark with no verdict are marked `verdict_missing`, not `verdict_clean`. - The correlator distinguishes "no verdict yet" from "no verdict will ever come." Collapsing these into a null is the mechanism by which orphans become invisible. Outside these conditions — e.g., inline evaluation, or a single evaluator sharing the emitter's exact preprocessing code path — the failure does not manifest and the watermark machinery is unnecessary overhead. ## Decision Boundary The operational decision is where to place the *seal*. Two architectures: - **Seal-on-emit (observed, broken):** span closes at task end, verdicts join later against an immutable record. Cheap, but every late verdict is a reconstruction problem and every digest mismatch is unrecoverable. - **Seal-on-verdict (required for safety-critical traces):** the span enters `PENDING_VERDICT` and is not finalized until either the verdict arrives or the watermark expires. Finalization writes the verdict and the span atomically, guaranteeing the join exists by construction. The boundary condition that forces the second architecture: **any pipeline where a safety verdict can gate a downstream action.** If the verdict only feeds a dashboard, seal-on-emit is tolerable with orphan accounting. If the verdict gates tool execution, memory writes, or handoff authorization, seal-on-emit permits a window in which an unverified span is treated as verified because its verdict has not yet arrived and null is read as clean. A secondary boundary: the correlator must fail *closed* on digest mismatch. A verdict that cannot be joined must raise, not be dropped, because a dropped verdict is indistinguishable from a passing one at the aggregation layer. ## Operational Effect After migrating to content-addressed joins with a declared watermark, the orphan rate fell from 11% to 0.3% (residual: genuinely malformed evaluator output). The critical change was not the digest fix alone but the **denominator correction**: coverage was recomputed as `joined_verdicts / emitted_spans`, which immediately surfaced the 11% that the old metric had hidden. The re-attribution class was eliminated by making `session_id` non-authoritative for joins and requiring the resumed instance to carry the original `prompt_digest` forward in its checkpoint, so the post-resume span and its verdict share a content key. The residual risk: content-addressed joins are expensive at scale (digest computation on every span, index on a 64-byte key) and break when an evaluator legitimately re-normalizes content (e.g., strips PII before evaluation). The mitigation is to hash the *pre-normalization* payload and carry the normalization transform ID as a secondary attribute, so a mismatch is diagnosable rather than silent. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class VerdictCorrelationError(RuntimeError): """Raised when a safety verdict cannot be soundly joined to a span.""" class SpanState(Enum): PENDING_VERDICT = "pending_verdict" FINALIZED = "finalized" VERDICT_MISSING = "verdict_missing" @dataclass class AgentSpan: trace_id: str span_id: str session_id: str payload: str state: SpanState = SpanState.PENDING_VERDICT verdict: Optional[str] = None digest: str = field(init=False) def __post_init__(self) -> None: # Content-addressed key: hash the FULL payload, identical to evaluator. self.digest = hashlib.sha256(self.payload.encode("utf-8")).hexdigest() @dataclass class SafetyVerdict: digest: str label: str evaluator_truncation: int def correlate( spans: dict[str, AgentSpan], verdict: SafetyVerdict, watermark_expired: bool, ) -> AgentSpan: """ Join a verdict to its span by content digest. Fails closed: a mismatch raises rather than dropping the verdict. """ target = spans.get(verdict.digest) if target is None: # Digest produced by a different truncation boundary is unrecoverable. raise VerdictCorrelationError( f"verdict digest {verdict.digest[:12]}... matches no emitted span; " f"evaluator truncated at {verdict.evaluator_truncation} — " f"likely prefix divergence, cannot join" ) if target.state is SpanState.FINALIZED: # Sealed span cannot absorb a late verdict; this is the failure mode. raise VerdictCorrelationError( f"span {target.span_id} already finalized before verdict arrived; " f"seal-on-emit ordering violation" ) if target.state is SpanState.VERDICT_MISSING and not watermark_expired: raise VerdictCorrelationError( f"span {target.span_id} marked missing but watermark not expired; " f"premature finalization" ) # Atomic finalize: verdict and span state change together. target.verdict = verdict.label target.state = SpanState.FINALIZED return target def finalize_stale(spans: dict[str, AgentSpan], watermark_expired: bool) -> int: """Mark unverified spans as missing — never as clean.""" if not watermark_expired: raise VerdictCorrelationError( "cannot sweep stale spans before watermark expiry" ) swept = 0 for span in spans.values(): if span.state is SpanState.PENDING_VERDICT: span.state = SpanState.VERDICT_MISSING swept += 1 return swept ```