# Which invariants prevent span-parentage orphaning when an agent handoff crosses a process boundary mid-tool-call **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems that propagate W3C `traceparent`/`tracestate` via OpenTelemetry GenAI semantic conventions (`gen_ai.*`) across agent handoffs where the receiving agent executes tool calls in a separate process or sandbox. Does not cover single-process agents, in-process thread handoffs, or cases where the entire tool-call chain stays within one OTel SDK lifetime. ## Core Distinction The failure I am isolating is *not* lost spans, dropped attributes, or token-accounting drift. It is **span-parentage orphaning at handoff**: the outgoing agent closes its `gen_ai.agent.invoke` span and emits `gen_ai.tool.call` child spans whose `parent_span_id` points at a span that the receiving process never received a live reference to. The trace *looks* complete in the collector because the exporter batched the parent before the child was created — but the child's context propagation carries a `traceparent` whose `span-id` is the *outgoing* agent's invoke span, not the handoff span. When the receiving agent executes the tool call, the OTel SDK in the new process either (a) creates a root span because the parent context was never injected into the handoff envelope, or (b) creates a child of a span that has already ended, which violates the "parent must be alive at child creation" invariant that OTel's `SpanProcessor` and most backends assume. The distinction that matters operationally: **a trace can be structurally valid (all span IDs resolvable) yet semantically orphaned (the causal edge between handoff and tool execution is missing or reversed in time).** Backends that reconstruct causality from `parent_span_id` will silently reorder or drop the tool-call edge, and token accounting attributed to `gen_ai.agent.invoke` will not roll up into the handoff span. ## What Was Observed A two-agent pipeline: `planner` (agent A) invokes `executor` (agent B) via an A2A-style HTTP handoff. Agent A wraps the handoff in a span `gen_ai.agent.invoke` with attributes `gen_ai.agent.name=planner`, `gen_ai.operation.name=invoke_agent`, and `gen_ai.usage.input_tokens=1840`. The handoff envelope includes the task payload and a `traceparent` header. Agent B receives the request, starts a new span `gen_ai.agent.invoke` with `gen_ai.agent.name=executor`, and then makes three tool calls, each wrapped in `gen_ai.tool.call` spans with `gen_ai.tool.name` and `gen_ai.usage.input_tokens`/`output_tokens`. Observed in the collector: 1. Agent A's `gen_ai.agent.invoke` span has `end_time` = T+120ms. 2. Agent B's `gen_ai.agent.invoke` span has `start_time` = T+118ms, `parent_span_id` = agent A's invoke span ID (correct — this is the handoff edge). 3. Agent B's first `gen_ai.tool.call` span has `start_time` = T+340ms, `parent_span_id` = agent A's invoke span ID (wrong — should be agent B's invoke span ID). 4. Agent B's second and third tool-call spans have `parent_span_id` = agent B's invoke span ID (correct). The first tool call is orphaned onto a span that ended 220ms before the tool call started. The collector's trace view shows the first tool call as a sibling of the agent B invoke span rather than a child. Token rollup for agent B's invoke span undercounts by the first tool call's tokens (312 input, 88 output). The trace *is* accepted by the backend; no error is raised. The trigger condition: agent B's SDK was initialized with a `CompositePropagator` that included `TraceContextPropagator`, but the handoff envelope's `traceparent` was extracted into a `Context` object that was *not* passed to the first tool-call's `start_as_current_span`. The first tool call was created inside a `with tracer.start_as_current_span(...)` block that had no explicit `context=` argument, so it attached to the *ambient* context — which, at that moment, was the extracted handoff context containing agent A's span as the active span. Only after the first tool call completed did agent B's code enter a `context.attach()` block that made agent B's own invoke span active. ## Condition of Validity The invariant that prevents orphaning is: **the receiving agent's `gen_ai.agent.invoke` span must be made the active context before any `gen_ai.tool.call` span is created, and the handoff `traceparent` must be consumed only to establish the *parent* of the invoke span, not to seed the ambient context for tool calls.** Formally, for any handoff from agent A to agent B: - `parent(span_invoke_B) = span_invoke_A` (handoff edge preserved) - `parent(span_tool_B_i) = span_invoke_B` for all `i` (tool calls are children of the receiving agent's invoke span, not the sending agent's) - `start_time(span_tool_B_i) >= start_time(span_invoke_B)` and `end_time(span_tool_B_i) <= end_time(span_invoke_B)` (temporal containment) - `span_invoke_A.end_time` may be before or after `span_invoke_B.start_time` (the handoff edge is causal, not temporal) The condition fails when the extracted handoff context is used as the *ambient* context rather than as an explicit parent argument. This is non-obvious because `TraceContextPropagator.extract()` returns a `Context` that is conventionally passed directly to `start_as_current_span(context=...)` — but if the receiving agent's code does `ctx = propagator.extract(carrier); token = context.attach(ctx)` and then later creates the invoke span *inside* that attached context, the invoke span becomes a child of agent A's span (correct), but the attach is never detached before the tool calls, so the tool calls inherit agent A's span as their parent via the still-attached context. The invariant holds only if the attach is scoped to the invoke-span creation and detached before tool execution, *or* if the invoke span is explicitly made current for the tool-call scope. ## Decision Boundary The boundary between "safe handoff" and "orphaned tool call" is whether the receiving agent's SDK detaches the extracted handoff context before entering the tool-execution loop. In practice: - **Safe:** `with tracer.start_as_current_span("gen_ai.agent.invoke", context=extracted_ctx):` — the invoke span is created as a child of the handoff context, and the `with` block's implicit `use_span` makes the invoke span the current span for the duration of the block, including tool calls. The extracted context is not attached to the ambient context. - **Unsafe:** `token = context.attach(extracted_ctx); invoke_span = tracer.start_span(...); ... tool_span = tracer.start_as_current_span(...)` without `context.detach(token)` between invoke-span creation and tool-span creation. The tool span's parent is resolved from the ambient context, which still holds agent A's span. - **Also unsafe:** `invoke_span = tracer.start_span(..., context=extracted_ctx); invoke_span.end(); tool_span = tracer.start_as_current_span(...)` — the invoke span is ended before the tool call, so the tool call is a child of a closed span. Some SDKs will still record it; the backend will show a child with `start_time > parent.end_time`, which is the temporal-containment violation. The decision boundary is *not* about whether the handoff context is propagated — it always is in a correct A2A implementation. It is about **whether the propagated context is used as a parent (scoped) or as ambient (unscoped)**. The two are indistinguishable in the trace until you inspect the first tool call's `parent_span_id` against the receiving agent's invoke span ID. ## Operational Effect When orphaning occurs, three downstream effects compound: 1. **Token rollup undercounts.** Backends that sum `gen_ai.usage.input_tokens` over the subtree of `gen_ai.agent.invoke` (agent B) will miss the orphaned tool call's tokens. In the observed case, agent B's reported usage was 312+88 tokens short — a 14% undercount against the actual tool-call cost. Budget enforcement based on `gen_ai.agent.invoke` subtree sums will under-provision. 2. **Causality inversion in trace views.** The first tool call appears as a sibling of agent B's invoke span, and its start time is *after* agent A's invoke span ended. Trace viewers that render a waterfall will show the tool call as a detached root-level span adjacent to the handoff, making it look like agent A executed the tool call after ending its invoke span. Incident responders reading the trace will misattribute the tool call to agent A. 3. **Auditor replay divergence.** If a verification agent replays the trace to check that every `gen_ai.tool.call` has a `gen_ai.agent.invoke` ancestor with matching `gen_ai.agent.name`, the orphaned tool call fails the check and the replay reports a spurious "tool call without agent" violation. This is a false positive that masks the real invariant violation (the missing detach). The guardrail that bounds this: **a post-handoff trace validator that asserts, for every `gen_ai.tool.call` span, that its `parent_span_id` resolves to a `gen_ai.agent.invoke` span whose `gen_ai.agent.name` matches the receiving agent and whose `[start_time, end_time]` interval contains the tool call's interval.** This is a structural check that does not require the collector to understand token semantics — it only requires span parentage and temporal containment. It catches the orphan at export time, before the trace is admitted to the backend. ```python from dataclasses import dataclass from typing import Optional class SpanParentageOrphanError(RuntimeError): """Raised when a gen_ai.tool.call span is not a temporal child of the receiving agent's gen_ai.agent.invoke span after a handoff.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] name: str start_ms: int end_ms: int agent_name: Optional[str] = None tool_name: Optional[str] = None def validate_handoff_tool_parentage( spans: list[Span], receiving_agent: str, ) -> None: """Assert every gen_ai.tool.call span is a child of the receiving agent's invoke span and is temporally contained within it. The invariant: parent(tool_call) == invoke_span(receiving_agent) AND start(tool_call) >= start(invoke) AND end(tool_call) <= end(invoke). """ by_id = {s.span_id: s for s in spans} invoke_spans = [ s for s in spans if s.name == "gen_ai.agent.invoke" and s.agent_name == receiving_agent ] if len(invoke_spans) != 1: raise SpanParentageOrphanError( f"expected exactly one invoke span for agent {receiving_agent!r}, " f"found {len(invoke_spans)}" ) invoke = invoke_spans[0] tool_spans = [s for s in spans if s.name == "gen_ai.tool.call"] if not tool_spans: return for tool in tool_spans: parent = by_id.get(tool.parent_span_id or "") if parent is None: raise SpanParentageOrphanError( f"tool {tool.tool_name!r} (span {tool.span_id}) has unresolvable " f"parent {tool.parent_span_id!r}" ) if parent.span_id != invoke.span_id: raise SpanParentageOrphanError( f"tool {tool.tool_name!r} (span {tool.span_id}) parents onto " f"{parent.name!r} ({parent.span_id}), not the receiving agent's " f"invoke span ({invoke.span_id}) — handoff context was left " f"attached as ambient" ) if tool.start_ms < invoke.start_ms or tool.end_ms > invoke.end_ms: raise SpanParentageOrphanError( f"tool {tool.tool_name!r} (span {tool.span_id}) interval " f"[{tool.start_ms},{tool.end_ms}] not contained in invoke " f"interval [{invoke.start_ms},{invoke.end_ms}] — parent span " f"ended before child began" ) # Reproduction of the observed failure: agent A's invoke span ended at 120ms; # agent B's invoke span runs 118..900ms; the first tool call orphaned onto # agent A's span and started at 340ms. observed = [ Span("A1", None, "gen_ai.agent.invoke", 0, 120, agent_name="planner"), Span("B1", "A1", "gen_ai.agent.invoke", 118, 900, agent_name="executor"), Span("T1", "A1", "gen_ai.tool.call", 340, 410, tool_name="search"), # orphan Span("T2", "B1", "gen_ai.tool.call", 420, 500, tool_name="fetch"), Span("T3", "B1", "gen_ai.tool.call", 510, 600, tool_name="summarize"), ] try: validate_handoff_tool_parentage(observed, receiving_agent="executor") except SpanParentageOrphanError as exc: # Expected: T1 parents onto A1, not B1. assert "T1" in str(exc) or "search" in str(exc) ```