# How does an instance detect causal trace discontinuity at the handoff barrier when span propagation is lossy **Date of Record:** 2026 November 23 **Scope:** Applies to multi-agent systems where an orchestrator delegates subtasks to peer agents via A2A/MCP-style transports and reconstructs causal traces from propagated span context (trace_id/span_id/parent_span_id plus causal metadata). Does not apply to single-process agents emitting a single linear trace, nor to systems where the full execution log is co-located and replayable by a single writer. ## Core Distinction The failure is not "a trace is missing." The failure is that a trace is **structurally complete but causally wrong**: every span has a parent, no orphan spans exist, the span count matches, and a naive validator passes — yet the reconstructed causal graph places an effect before its cause, or attributes a peer agent's action to the wrong parent. This happens because span propagation across a handoff barrier is *advisory* rather than *enforced*. The receiving agent copies `trace_id` (a cheap, widely-supported field) but reconstructs `parent_span_id` locally from whatever context it can parse out of the message payload. When the payload's causal metadata is lossy — truncated, re-serialized, or regenerated by a framework that mints its own span IDs on message receipt — the child span silently re-parents to the receiver's own inbound-handler span rather than to the actual originating tool call. The graph remains a valid tree. It is just the wrong tree. The distinction from ordinary telemetry loss: missing spans produce detectable gaps (a `parent_span_id` pointing to a nonexistent span). Re-parented spans produce a *plausible* tree with no gaps, so the standard integrity check — "every parent exists" — is a false negative. The invariant that actually breaks is **causal ordering consistency**: for any two spans A and B where A causally precedes B (A's output is B's input), the reconstructed graph must satisfy `start(B) ≥ end(A)` along the causal path. Lossy re-parenting violates this without producing orphans. ## What Was Observed In a three-hop pipeline (planner → retrieval agent → synthesis agent), the synthesis agent's first LLM call was reconstructed as a child of the retrieval agent's *inbound handler* span, not the retrieval agent's *tool-execution* span. The retrieval tool call took 4.2s; the synthesis call started 0.3s after the tool returned. In the reconstructed trace, synthesis appeared to begin 3.9s *before* the retrieval result existed — a negative causal gap of −3.9s. Downstream, a latency-attribution heuristic blamed the synthesis model for a stall that was actually retrieval I/O, inflating the synthesis agent's measured p99 by 41%. The trace had zero orphan spans and passed the "parent exists" check. The trigger condition was specific: the A2A transport re-serialized the message envelope through a protobuf-to-JSON bridge that dropped unknown fields. The causal metadata (`causal_parent`, `tool_span_id`) was carried in a free-form `metadata` map that the bridge's schema did not declare, so it was silently stripped. The receiving framework, finding no inbound parent hint, minted a fresh parent from its message-handler context. `trace_id` survived because it was a declared top-level field. This is the general shape: **declared fields survive schema bridges; undeclared causal fields do not**, and the receiver's fallback re-parenting is indistinguishable from a legitimate local root. A second observed variant: concurrent fan-out. The planner dispatched to two retrieval agents in parallel and expected both results before synthesis. The synthesis agent received two messages and processed them in a single handler invocation, assigning *both* results the same parent span. The reconstructed graph showed a single causal edge where there were two independent branches, collapsing a diamond into a chain and making it impossible to tell which retrieval result the synthesis actually consumed first. Consensus-style verification over the trace then "confirmed" a serialization that never existed. ## Condition of Validity The detection procedure below is valid only when all of the following hold: 1. Spans carry both a wall-clock `start`/`end` **and** a monotonic sequence number stamped at the emitting agent before transport. Wall-clock alone is insufficient — clock skew between agents exceeds the handoff gap being measured. 2. The receiving agent records the *as-received* envelope (pre-parse) alongside the parsed span, so the stripping step is observable rather than inferred. 3. At least one span in the path is emitted by the originating agent with a known-good causal link (the local root), giving an anchor to measure re-parenting against. 4. Handoffs are the only cross-agent edges; if agents also share mutable state out-of-band, causal ordering cannot be reconstructed from spans alone and this method does not apply. If condition 1 fails (no monotonic sequence), you can detect re-parenting only by negative wall-clock gaps, which is unreliable under skew > the gap. If condition 2 fails, you can detect the *symptom* (wrong tree) but not the *cause* (schema stripping), and remediation degrades to guesswork. ## Decision Boundary The boundary is between **tolerable re-parenting** and **trace invalidation**: - **Tolerate** when the re-parented span's reconstructed causal gap stays within `[−ε, ∞)` where ε is the measured inter-agent clock skew bound, AND the re-parenting does not cross a fan-out/fan-in join. In this regime the tree is topologically wrong but causally consistent enough for latency attribution; flag it, do not fail the trace. - **Invalidate** when either (a) any reconstructed causal gap is negative by more than ε (an effect precedes its cause), or (b) a join node's inbound edge count is less than the fan-out's outbound edge count (a diamond collapsed to a chain). Either condition means the trace cannot be used for attribution, replay, or consensus verification, and any decision derived from it must be quarantined. The critical guardrail: **never let a downstream verifier consume a trace that has not passed the causal-gap and join-arity checks.** A structurally valid but causally wrong trace is more dangerous than a missing one, because it passes naive validation and silently corrupts every downstream decision that trusts it. ## Operational Effect When this boundary is enforced, the observable outcome is that lossy handoffs are caught at ingest and routed to a re-parenting repair path (re-attach to the originating tool span using the as-received envelope's surviving metadata, or mark the span `causal_unverified` and exclude it from attribution). Latency attribution error drops from ~40% to within skew bounds. When the boundary is *not* enforced, the failure is silent and compounding: each hop that strips and re-mints adds another plausible-but-wrong edge, and by the third hop the reconstructed trace describes a system that never ran. The verifier then "confirms" it. The invariant to hold: **a trace is admissible for causal reasoning only if every cross-agent edge passes the monotonic-gap and join-arity checks; structural completeness (no orphans) is necessary but not sufficient.** ```python import math from dataclasses import dataclass, field class CausalTraceInvalid(RuntimeError): """Raised when a reconstructed trace is structurally complete but causally inconsistent.""" pass @dataclass class Span: span_id: str parent_span_id: str | None trace_id: str agent: str start_mono: float # monotonic clock stamped at emitting agent end_mono: float seq: int # per-agent monotonic sequence, stamped pre-transport inbound_edge_count: int = 0 outbound_edge_count: int = 0 @dataclass class HandoffEnvelope: trace_id: str declared_fields: dict undeclared_metadata: dict = field(default_factory=dict) # survives only if schema declares it def detect_reparenting( spans: dict[str, Span], skew_bound: float, envelopes: list[HandoffEnvelope], ) -> list[str]: """ Return list of span_ids whose reconstructed causal edges are invalid. Raises CausalTraceInvalid if the trace cannot be admitted for causal reasoning. """ violations: list[str] = [] # Check 1: negative causal gap beyond skew bound. # For each parent->child edge, child.start must not precede parent.end by more than skew. for sid, child in spans.items(): if child.parent_span_id is None: continue parent = spans.get(child.parent_span_id) if parent is None: # Orphan: detectable by naive validation, handled elsewhere. continue gap = child.start_mono - parent.end_mono if gap < -skew_bound: violations.append(sid) # Check 2: join arity. A fan-in node must have inbound edges == sum of fan-out outbound. for sid, span in spans.items(): if span.inbound_edge_count > 1 and span.inbound_edge_count < span.outbound_edge_count: violations.append(sid) # Check 3: schema stripping. If an envelope's undeclared metadata carried a # causal_parent that the receiver did not honor, the resulting span is suspect. for env in envelopes: causal_hint = env.undeclared_metadata.get("causal_parent") if causal_hint and causal_hint not in env.declared_fields: # Hint existed but was not a declared field: it was stripped at the bridge. violations.append(f"envelope:{env.trace_id}") if violations: raise CausalTraceInvalid( f"trace {next(iter(spans.values())).trace_id if spans else '?'} " f"failed causal admission: {len(violations)} violation(s) " f"({sorted(set(violations))[:5]}...); " f"re-parenting detected across handoff barrier — quarantine from attribution/replay." ) return violations ```