# What happens when an instance emits safety-signal spans after its trace root has already been closed: orphaned span correlation in agent observability **Date of Record:** 2026 November 22 **Scope:** Applies to agent observability pipelines that correlate spans to a trace root by `trace_id` and finalize cost/latency/safety aggregates at root-close time. Does not apply to streaming aggregation systems that recompute trace-level attributes continuously from a durable span store. ## Core Distinction The distinction that matters here is between *span emission order* and *span causal order*. In a single-process LLM call, the safety classifier runs inline and its verdict span is emitted before the parent span closes. In an agentic system, safety evaluation is often asynchronous and decoupled: a moderation model, a policy engine, or a post-hoc auditor inspects the tool output or the final answer *after* the execution span has returned and the trace root has been marked complete. The safety-signal span is causally part of the trace but temporally arrives after the trace's aggregation window has closed. Observability backends that treat "root span closed" as "trace is finalizable" will silently drop, misattribute, or double-count these late spans. The failure is not a crash. It is a correlation error: the cost, latency, and safety attributes that downstream consumers read no longer describe the same execution that produced them. ## What Was Observed A multi-tool agent trace for a single user turn exhibited the following sequence: 1. Root span `agent.turn` opened at T0 with `trace_id=abc123`. 2. Child spans for `llm.plan`, `tool.search`, `tool.fetch`, `llm.synthesize` emitted between T0 and T0+4.2s. 3. At T0+4.2s the root span closed. The aggregator computed `total_cost=0.041 USD`, `p99_latency=4200ms`, `safety_verdict=null`, and flushed the trace record to the cold store. 4. At T0+6.8s the asynchronous safety classifier emitted span `safety.judge` with `trace_id=abc123`, `parent_id=root`, `verdict=block`, `category=prompt_injection_reflected`. 5. The aggregator received `safety.judge` for an already-finalized trace. Depending on configuration it either (a) dropped the span as orphaned, (b) created a *new* trace record keyed by `abc123` with only the safety span and `total_cost=0`, or (c) appended the span but did not recompute the trace-level `safety_verdict`. In case (a), the blocked content was served and logged as clean. In case (b), the cost dashboard showed a zero-cost trace and the safety dashboard showed a block with no associated latency — the two views could not be joined. In case (c), the span existed but the denormalized `safety_verdict` attribute on the root remained `null`, so any query filtering `safety_verdict=block` missed it. The latency skew is the subtle part: the async judge itself took 2.6s of wall time (a 1.4s queue delay plus a 1.2s model call). If the backend naively recomputed `trace_duration = max(span.end) - min(span.start)`, the trace latency would jump from 4200ms to 6800ms — attributing queue and classification time to the *user-facing* turn. The agent did not get slower; the observability record did. ## Condition of Validity The invariant that must hold for correct correlation is: > For every span `s` with `s.trace_id = t`, either `s` is ingested before `t` is finalized, or the finalization of `t` is *reversible* and any trace-level attribute derived from `s` is recomputed on late arrival. This invariant holds trivially when safety evaluation is synchronous and inline. It breaks when any of the following are true: - The safety judge is a separate model call with its own queue (typical for moderation endpoints under load). - The safety signal is produced by a *different agent instance* in a multi-agent swarm and propagated via A2A or a message bus, so its arrival is bounded only by transport, not by the producer's execution. - The trace root closes on the *last execution span*, but the trace's semantic completeness depends on a span that is not in the execution critical path. The condition of validity is therefore: **trace finalization must be gated on a causal-completeness predicate, not on root-span closure.** Root-span closure is a necessary but not sufficient signal that all causally-descendant spans have been accounted for. ## Decision Boundary The decision boundary is where you choose between two finalization strategies: **Strategy A — Close-on-root.** Finalize the trace when the root span ends. Cheap, low-latency dashboards, but requires that every causally-relevant span be a synchronous descendant of the root. Any async safety, audit, or cost-reconciliation span violates this and must be handled by a side channel (e.g., a separate `safety_events` table joined by `trace_id` at query time). This is correct *only if* no trace-level attribute is derived from late spans. **Strategy B — Close-on-quiescence.** Finalize the trace after a bounded quiet period `Q` following the last observed span, or after an explicit `trace.complete` sentinel span is emitted by the orchestrator. Cost and latency attributes are computed over execution spans only; safety attributes are computed over all spans and written as a separate, versioned attribute set. This is correct for async safety but introduces a finalization latency of `Q` and requires that the orchestrator actually emit the sentinel — which it will not if the agent process crashes mid-turn. The boundary condition that decides between them is the **maximum causal lag** `L_max` between the last execution span and the last causally-descendant span. If `L_max` is bounded and small (inline classifiers), Strategy A with a small `Q` is safe. If `L_max` is unbounded (async moderation queues, cross-instance swarm auditors), Strategy A is unsound and you must either adopt Strategy B or split the attribute surface so that safety attributes are never denormalized onto the execution trace root. The trap is a hybrid: close-on-root for latency, but denormalize safety onto the root "when it arrives." That is Strategy A with a correctness bug, because the root is already immutable in the cold store. ## Operational Effect The observable effects, in order of severity: 1. **Safety blind spot under load.** The async judge's queue delay grows with load, so `L_max` grows exactly when safety matters most. Orphaned safety spans cluster during traffic spikes — the system is least safe, and least observable, at peak. 2. **Cost/latency misattribution.** If late spans are folded into duration or token accounting, p99 latency and cost-per-turn inflate by the judge's queue time. Teams then optimize the wrong thing (the agent) when the regression is in the observability pipeline's finalization logic. 3. **Unjoinable dashboards.** Cost, latency, and safety views keyed by `trace_id` but built from different finalization passes produce records that cannot be joined without a full re-scan. Incident response loses the ability to answer "was the expensive turn also the blocked turn?" 4. **Replay divergence.** Verification replay (re-running the trace from logged spans) will produce a different `safety_verdict` than the original if the original dropped the late span — so the replay "disagrees" with production for reasons that are purely a correlation artifact, not a model nondeterminism. The guardrail is to make safety attributes *first-class and independently keyed*, never denormalized onto an immutable execution root, and to gate trace finalization on an explicit completeness sentinel rather than root closure. The code below encodes the guardrail: a finalizer that refuses to seal a trace whose causal-completeness predicate is unmet, and raises rather than silently dropping the late span. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class OrphanedSafetySpanError(RuntimeError): """Raised when a safety-signal span arrives for a trace that was already sealed under close-on-root finalization, making correlation unsound.""" pass @dataclass class Span: span_id: str trace_id: str name: str start_ms: int end_ms: int is_safety_signal: bool = False verdict: Optional[str] = None @dataclass class TraceRecord: trace_id: str sealed: bool = False execution_spans: List[Span] = field(default_factory=list) safety_spans: List[Span] = field(default_factory=list) total_cost_usd: float = 0.0 execution_latency_ms: int = 0 safety_verdict: Optional[str] = None class TraceFinalizer: """Seals traces only when the causal-completeness predicate is met. Invariant: a trace may be sealed only if every causally-descendant span (including async safety signals) has been ingested, OR the orchestrator has emitted an explicit completeness sentinel. """ def __init__(self, expected_safety_signal: bool = True): self.expected_safety_signal = expected_safety_signal self._traces: Dict[str, TraceRecord] = {} def ingest(self, span: Span) -> TraceRecord: rec = self._traces.setdefault(span.trace_id, TraceRecord(span.trace_id)) if rec.sealed: # Late arrival after seal: the correlation is already broken. raise OrphanedSafetySpanError( f"span {span.span_id} ({span.name}) arrived for sealed trace " f"{span.trace_id}; safety_verdict={rec.safety_verdict!r} is now " f"stale and cannot be reconciled without trace re-open" ) if span.is_safety_signal: rec.safety_spans.append(span) else: rec.execution_spans.append(span) return rec def try_seal(self, trace_id: str) -> TraceRecord: rec = self._traces[trace_id] if not rec.execution_spans: raise OrphanedSafetySpanError( f"trace {trace_id} has no execution spans; cannot derive latency" ) # Causal-completeness predicate: do not seal until the expected # async safety signal has landed, otherwise the root is immutable # before the verdict that describes it exists. if self.expected_safety_signal and not rec.safety_spans: raise OrphanedSafetySpanError( f"trace {trace_id} sealed prematurely: expected safety signal " f"not yet ingested; sealing now would denormalize a null verdict" ) # Latency is computed over execution spans ONLY, so async judge # queue time is never attributed to the user-facing turn. rec.execution_latency_ms = ( max(s.end_ms for s in rec.execution_spans) - min(s.start_ms for s in rec.execution_spans) ) verdicts = [s.verdict for s in rec.safety_spans if s.verdict] rec.safety_verdict = "block" if "block" in verdicts else ( verdicts[0] if verdicts else None ) rec.sealed = True return rec ```