# Which invariants prevent trace-context collapse when A2A handoff spans are re-parented across agent runtimes **Date of Record:** 2026 November 21 **Scope:** Applies to multi-agent systems emitting OpenTelemetry-style traces where an orchestrator agent invokes a remote agent over an A2A/MCP transport and the receiving agent runtime starts a new trace root instead of continuing the caller's `trace_id`/`span_id`. Does not cover single-process agent loops, nor transports that natively propagate W3C `traceparent` headers end-to-end without re-serialization. ## Core Distinction There are two semantically different things a "handoff span" can mean, and GenAI semantic conventions conflate them: 1. **A causal child span** — the remote agent's work is a descendant of the caller's span, sharing one `trace_id`. Correct when the remote call is synchronous and the caller blocks on the result. 2. **A linked root span** — the remote agent's work is an independent trace that *references* the caller via a span `link` (or `gen_ai.agent.handoff.parent_trace_id` attribute). Correct when the remote agent is long-lived, queues the task, retries independently, or fans out to further agents after the caller has already returned. The failure mode is not "missing trace propagation." It is **silent re-parenting**: the receiving runtime accepts the inbound context, emits a span that *looks* like a child (it carries `gen_ai.agent.name`, the handoff attributes, even the parent span ID as a string attribute), but assigns a fresh `trace_id` because its local sampler or context-injection middleware did not recognize the inbound `traceparent`. The trace graph is now two disjoint DAGs that a naive backend will render as one only if it joins on the string attribute — which most do not. The result is that causality is *present in the data but absent from the index*, and every downstream query (`trace duration`, `time-to-first-token across the handoff`, `error propagation rate`) silently undercounts. ## What Was Observed An orchestrator agent (`planner`) calls a specialist agent (`retriever`) over an A2A JSON-RPC endpoint. The planner emits a client span `gen_ai.agent.invoke` with `trace_id=T1`, `span_id=S1`. The A2A request payload includes a `metadata.trace` object carrying `traceparent` as a JSON field — not as an HTTP header, because the A2A spec models transport metadata as a body field. The retriever's runtime uses an OTel SDK whose `TextMapPropagator` only inspects HTTP headers on inbound requests. Its HTTP server middleware extracts `traceparent` from headers (absent), finds nothing, and starts a new root: `trace_id=T2`, `span_id=S2`, with `parent_span_id=null`. The retriever then reads `metadata.trace.traceparent` *after* span creation — too late — and dutifully writes `gen_ai.agent.handoff.parent_trace_id=S1` as a **span attribute**. Three observable consequences: - The backend trace list shows two traces of ~equal duration. Handoff latency (planner-send → retriever-first-token) is not computable as a parent-child delta; it must be reconstructed by joining on the string attribute, which no standard OTel query does. - Sampling diverges. The planner is sampled at 10% (head-based); the retriever's fresh root is sampled independently. Roughly 90% of handoffs produce a retriever trace with **no** corresponding planner trace, so error-rate dashboards computed per-trace disagree between the two services by up to 10×. - Error attribution inverts. When the retriever fails, its span has `status=ERROR` but `parent_span_id=null`. Alerting rules keyed on "root span error" fire on the retriever as if it were the entry point, paging the wrong on-call. The non-obvious part: the system *appeared* correctly instrumented. Every span had the right GenAI semantic attributes (`gen_ai.operation.name`, `gen_ai.agent.id`, `gen_ai.usage.input_tokens`). The convention compliance was 100%. The *graph* was wrong. ## Condition of Validity The re-parenting failure is bounded by a single invariant that must hold at the receiving runtime **before the first span is created**: > For any inbound agent-to-agent request carrying a handoff context, the receiving runtime MUST resolve the effective parent (`trace_id`, `span_id`, `trace_flags`) from *all* transport surfaces the protocol permits — headers **and** body metadata — prior to instantiating its root span, and MUST either (a) continue the inbound trace as a child, or (b) explicitly declare a new root and emit a span `link` to the caller. It MUST NOT do neither. This invariant is falsifiable: given an inbound request, inspect the receiver's first emitted span. Either `span.parent_span_id == inbound.span_id` (case a), or `span.links` contains an entry with `trace_id == inbound.trace_id` (case b). If neither holds, the invariant is violated and the trace graph is corrupt regardless of attribute completeness. The condition is *not* satisfied by "we set the parent trace ID as an attribute." Attributes are not edges. Observability backends index edges; they do not synthesize them from strings without an explicit join rule. ## Decision Boundary The choice between continuing (a) and linking (b) is governed by the caller's lifetime relative to the callee's: - **Continue as child** when the caller blocks on the response and the callee's lifetime is strictly nested within the caller's span. This preserves the single-`trace_id` invariant that makes duration and error-propagation queries correct. - **Link as new root** when the callee outlives the caller (async queue, retry-after-caller-exit, long-running agent that fans out) or when the callee may be invoked by multiple callers and must not inherit a single parent. Here a shared `trace_id` would create a span whose parent has already ended, breaking the "parent ends after child" invariant that Gantt-style trace UIs assume. The boundary is crossed the moment the caller's span can end before the callee's. A synchronous A2A call with a 30s timeout stays in (a). The same call routed through a durable task queue that acks immediately and executes later must be (b), even though the wire format is identical. Instrumentation that hardcodes one branch will be wrong for the other; the runtime must decide per-invocation based on whether it awaits the result inline. ## Operational Effect Once the invariant holds, three downstream properties become computable that were previously silently broken: - **Handoff latency** is the child span's start minus parent span's end, or for linked roots, the link timestamp delta. Both are index-level operations. - **Sampling coherence** requires that a continued child inherits `trace_flags` from the parent's `traceparent`, so the entire handoff chain is sampled-or-not as a unit. Linked roots may sample independently, but the link records the caller's sampling decision so backends can backfill. - **Error attribution** keys on the true root. A retriever failure under a continued trace is a *child* error, attributed up the chain to the planner that initiated the handoff, not to the retriever as an entry point. The guardrail is a pre-span assertion in the receiver's request-handling middleware: resolve effective parent context from every declared transport surface, and refuse to start a span until the continue-or-link decision is recorded. The code below encodes that assertion and the two legal outcomes. ```python from dataclasses import dataclass, field from typing import Optional class TraceContextCollapseError(RuntimeError): """Raised when an inbound A2A handoff would produce a span with neither a parent edge nor an explicit link to the caller — the silent re-parenting failure that corrupts the agent call graph.""" @dataclass class InboundHandoff: trace_id: str span_id: str trace_flags: int # Transport surfaces the A2A/MCP spec permits for context carriage. header_traceparent: Optional[str] = None body_metadata_traceparent: Optional[str] = None @dataclass class EmittedSpan: trace_id: str span_id: str parent_span_id: Optional[str] = None links: list = field(default_factory=list) def _parse_traceparent(tp: Optional[str]) -> Optional[tuple]: if not tp: return None parts = tp.split("-") if len(parts) != 4 or len(parts[0]) != 2 or len(parts[1]) != 32 or len(parts[2]) != 16: return None return parts[1], parts[2], int(parts[3], 16) def resolve_effective_parent(inbound: InboundHandoff) -> tuple: """Resolve parent from ALL declared transport surfaces before span creation. Header wins over body only if both are present and agree; disagreement is itself a protocol violation.""" from_header = _parse_traceparent(inbound.header_traceparent) from_body = _parse_traceparent(inbound.body_metadata_traceparent) if from_header and from_body and from_header != from_body: raise TraceContextCollapseError( f"Conflicting traceparent across surfaces: header={from_header} body={from_body}" ) resolved = from_header or from_body if resolved is None: raise TraceContextCollapseError( "Inbound handoff declares no resolvable traceparent on any surface" ) return resolved def start_receiver_span( inbound: InboundHandoff, *, callee_outlives_caller: bool, new_span_id: str, ) -> EmittedSpan: """Enforce the continue-or-link invariant. Never start a span that is neither a child nor a link of the caller.""" parent_trace_id, parent_span_id, parent_flags = resolve_effective_parent(inbound) if not callee_outlives_caller: # Continue: child span, inherited trace_id and flags. span = EmittedSpan( trace_id=parent_trace_id, span_id=new_span_id, parent_span_id=parent_span_id, ) else: # Link: independent root that references the caller. span = EmittedSpan( trace_id=f"fresh-{new_span_id}", span_id=new_span_id, parent_span_id=None, links=[{"trace_id": parent_trace_id, "span_id": parent_span_id, "flags": parent_flags}], ) # Post-condition assertion: the invariant must be observable in the span. is_child = span.parent_span_id == parent_span_id and span.trace_id == parent_trace_id is_linked = any( l["trace_id"] == parent_trace_id and l["span_id"] == parent_span_id for l in span.links ) if not (is_child or is_linked): raise TraceContextCollapseError( f"Span {span.span_id} is neither child nor link of caller " f"{parent_trace_id}/{parent_span_id}; trace graph would collapse" ) return span ```