# In what scenarios must an instance treat cross-agent trace correlation as a hard invariant rather than a best-effort join, when token metrics and safety events arrive out-of-band from the orchestration graph? **Date of Record:** 2026 December 3 **Scope:** Applies to observability pipelines that reconstruct causal execution graphs for multi-agent LLM orchestrations by joining three asynchronous streams: span/trace events (parent-child edges), token accounting counters (per-call, emitted by the model gateway), and safety/policy events (emitted by a separate moderation or guardrail service). Does not apply to single-agent, single-stream telemetry where trace ID is a first-class field on every record and no join is required. ## Core Distinction The distinction is between **correlation as enrichment** and **correlation as a causal invariant**. In enrichment mode, a missing or ambiguous join degrades a dashboard: a token count shows up unattributed, a safety flag floats without a parent. The pipeline tolerates it and the system keeps running. In invariant mode, the correlation edge *is* the fact being asserted — "agent B's tool call consumed these tokens and triggered this safety event under the authority delegated by agent A." If the join is wrong, the pipeline does not produce a less-detailed truth; it produces a *confidently wrong* causal claim, and downstream consumers (budget enforcement, incident attribution, safety escalation, replay-based auditing) act on it. The non-obvious part: the three streams do not share a clock, do not share an identity namespace, and are produced by three different processes with three different failure modes. Token counters are emitted by the inference gateway, which sees a request but not the agent graph. Safety events are emitted by a guardrail sidecar that may fire *after* the span it pertains to has already been closed and exported. Span events are emitted by the orchestrator, which knows the graph but not the token or safety payloads. The join key that seems obviously correct — trace ID — is frequently *not* present on the safety stream, because the guardrail is often a shared service that sees a prompt/response pair and nothing about which agent in the graph produced it. ## What Was Observed A three-agent orchestration (planner → executor → auditor) with a shared guardrail sidecar. The executor made a tool call whose response was flagged by the guardrail as a prompt-injection attempt. The trace exported by the orchestrator showed the executor span closing normally at T+0. The safety event arrived at the collector at T+340ms, carrying only a hash of the prompt and a `session_id` — no span ID, no trace ID. The token counter for the executor's model call arrived at T+80ms carrying the gateway's own `request_id`. The pipeline's join logic matched the safety event to the *auditor* span, because the auditor was the only open span at T+340ms sharing the session. The resulting trace asserted that the auditor had triggered a prompt-injection safety event. The auditor's own verification logic, reading this trace on the next cycle, concluded it was compromised and escalated a false positive to the planner, which re-planned and re-executed the task. Token spend for the incident was attributed to the auditor, not the executor, so the executor's budget guard never tripped. The failure trace: 1. Guardrail fires on executor's tool response at T+0, emits event with `session_id` only. 2. Orchestrator closes executor span at T+0, exports span with `span_id`, `trace_id`, `session_id`. 3. Gateway emits token counter at T+80ms with `request_id`, `session_id`. 4. Guardrail event reaches collector at T+340ms. 5. Join on `session_id` + "nearest open span" selects auditor span (T+0 to T+900ms). 6. Trace now asserts: auditor → safety event, auditor → token spend. 7. Auditor reads trace, self-reports compromise, triggers re-plan. The root cause is not a bug in any single component. Each stream is correct in isolation. The failure is that the pipeline applied a *temporal-nearest* join heuristic to a stream that carries no causal identity, and the heuristic is only valid when at most one span is open per session. In multi-agent graphs, concurrent spans are the norm, not the exception. ## Condition of Validity The nearest-open-span heuristic is valid only under the conjunction: (a) at most one span per session is open at any instant, (b) the safety stream's emission latency is bounded below the minimum inter-span gap, and (c) no span is re-parented after emission. Condition (a) fails by construction in any orchestration with parallel branches. Condition (b) fails whenever the guardrail is a shared service with queueing (observed p99 latency 340ms vs. 80ms inter-span gap in the incident). Condition (c) fails whenever an orchestrator retries a span and re-parents the retry under the original parent. The correct invariant is: **a safety or token event may be attributed to a span only if the event carries a span-scoped identity that was minted by the same process that minted the span, or if the event's `produced_by` lineage can be reconstructed from the span's own tool-call record.** Absent that, the event must be attributed to the *trace* (a set of spans) with an explicit `attribution: ambiguous` marker, never to a single span. The pipeline must refuse to fabricate a single-span edge. This means the guardrail sidecar must be given the current span ID (or a signed capability token wrapping it) at request time, and must echo it in the event. If the guardrail is a black-box shared service that cannot be modified, the orchestrator must record the guardrail call as an explicit child span of the calling agent's span, so that the safety event's arrival time window is bounded by a span the orchestrator itself opened. The invariant is: *the join key must be minted upstream of the join, not inferred at join time.* ## Decision Boundary The boundary is between **degraded attribution** and **false causal assertion**. When an out-of-band event arrives with no span-scoped identity and more than one span is open in its session window, the pipeline has exactly two correct options: - Attribute to the trace with `attribution: ambiguous`, and surface the ambiguity to every consumer that would otherwise act on a single-span edge. - Reject the event into a quarantine stream that requires manual or replay-based reconciliation. It must *not* pick the nearest span. The decision rule is mechanical: `if event.span_id is None and count(open_spans(session, event.arrival_window)) > 1: mark_ambiguous()`. The window must be computed from the event's *emission* time, not arrival time, and emission time must be carried by the event or reconstructed from the guardrail's own logs — arrival time is useless because collector queueing adds arbitrary skew. The secondary boundary: even when exactly one span is open, attribution is only safe if the event's emission time falls within that span's `[start, end]` interval with margin for clock skew. A span that closed at T+0 and an event emitted at T+340ms cannot be attributed to it by proximity; the event must be attributed to whatever span was open at emission time, or marked ambiguous. Proximity-in-arrival-time is the wrong clock. ## Operational Effect With the invariant enforced, the incident trace reads: executor span → tool call → guardrail span (child, opened by orchestrator) → safety event `attribution: exact`, and token counter → executor span `attribution: exact` via gateway `request_id` echoed into the span. The auditor's trace shows no safety event. Budget guard trips on the executor, not the auditor. No false-positive re-plan. The cost is that the orchestrator must open explicit child spans around every out-of-band call (guardrail, gateway accounting hook), which increases span volume roughly 2x for tool-heavy agents. This is the price of a join key that is minted upstream rather than inferred downstream. Pipelines that refuse to pay it are not running observability; they are running a heuristic that produces plausible-looking causal graphs which are wrong precisely in the concurrent, multi-agent, high-stakes cases where the graph matters most. ```python from dataclasses import dataclass from typing import Optional class AmbiguousAttributionError(RuntimeError): """Raised when an out-of-band event cannot be safely attributed to a single span.""" @dataclass class Span: span_id: str trace_id: str session_id: str start_ms: int end_ms: Optional[int] # None while open @dataclass class OutOfBandEvent: kind: str # "safety" | "token" session_id: str emission_ms: int span_id: Optional[str] # None if the producer did not echo a span-scoped identity def attribute_event(event: OutOfBandEvent, spans: list[Span]) -> str: """ Attribute an out-of-band event to a span only under the hard invariant: a span-scoped identity minted by the span's producer, OR exactly one span open at the event's *emission* time with margin for clock skew. Never use arrival-time proximity. Never fabricate a single-span edge when multiple spans are open in the emission window. """ if event.span_id is not None: for s in spans: if s.span_id == event.span_id: return s.span_id raise AmbiguousAttributionError( f"event {event.kind} cites span_id={event.span_id!r} not present in session " f"{event.session_id!r}; upstream identity was minted but not reconciled" ) # No span-scoped identity: fall back only if exactly one span is open at emission time. SKEW_MS = 50 open_at_emission = [ s for s in spans if s.session_id == event.session_id and s.start_ms - SKEW_MS <= event.emission_ms and (s.end_ms is None or event.emission_ms <= s.end_ms + SKEW_MS) ] if len(open_at_emission) == 1: return open_at_emission[0].span_id if len(open_at_emission) == 0: raise AmbiguousAttributionError( f"event {event.kind} at emission_ms={event.emission_ms} has no open span " f"in session {event.session_id!r}; cannot attribute, quarantine for replay" ) raise AmbiguousAttributionError( f"event {event.kind} at emission_ms={event.emission_ms} has " f"{len(open_at_emission)} concurrent open spans in session " f"{event.session_id!r} ({[s.span_id for s in open_at_emission]}); " f"refusing nearest-span heuristic — mark attribution ambiguous" ) ```