# Why does an instance lose causal linkage between a tool-call span and its parent agent span under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) across a multi-step tool-calling loop, where tool invocations are emitted as child spans of an agent-invocation span. Does not apply to single-shot LLM completions with no tool fan-out, nor to runtimes that emit a flat, non-hierarchical span stream with no parent/child context propagation. ## Core Distinction The GenAI semantic conventions describe *attributes* on spans — `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens` — but they do not by themselves define the *hierarchy contract* that binds a tool-call span to the agent span that authorized it. The convention assumes the runtime propagates a valid `SpanContext` (trace-id + parent span-id) through whatever execution substrate actually runs the tool. When that substrate is a subprocess, a remote MCP server, a sandboxed code interpreter, or a separate worker pool, the propagation is *not* automatic. The result is a span that is attribute-correct but parent-orphaned: it carries `gen_ai.tool.name = "search"` and `gen_ai.operation.name = "execute_tool"`, yet its `parent_span_id` points at nothing in the trace, or worse, at a *sibling* agent span from a prior turn. The failure is not that telemetry is missing — it is that telemetry is *present and mis-linked*, which is strictly worse because it silently corrupts causal reconstruction. The boundary condition: a tool-call span is causally valid only if its `SpanContext` was captured from the *active* agent span at the moment the tool was dispatched, and that captured context was injected across the dispatch boundary (process, RPC, or serialization) and re-extracted on the far side *before* the tool span was started. Any gap in that chain — a fresh tracer started inside the tool, a thread-local context lost across an `await` boundary, an MCP `tools/call` that does not carry `traceparent` in its `params._meta` — produces an orphaned or mis-parented span. ## What Was Observed An agent loop dispatching three sequential tool calls per turn across a stdio-based MCP server. The agent-invocation span `agent.turn` was emitted correctly with `gen_ai.operation.name = "invoke_agent"`. Each tool call was emitted from inside the MCP server process, which had been launched by the agent host as a subprocess. The MCP server's telemetry SDK was initialized with its own `TracerProvider` and no `TextMapPropagator` configured on the `tools/call` handler. The observed trace had the following shape across three turns: - Turn 1: `agent.turn` (span A1) with three child spans `execute_tool` (T1, T2, T3). All three tool spans had `parent_span_id = null` and *distinct* `trace_id`s — three separate one-span traces, not children of A1. - Turn 2: `agent.turn` (span A2). The three tool spans from this turn carried `trace_id` equal to A1's trace and `parent_span_id = A1`. The MCP server had cached the first `traceparent` it ever saw (from turn 1's dispatch header) and reused it for every subsequent call. - Turn 3: `agent.turn` (span A3). Tool spans now carried `parent_span_id = A2` from the cached header. The lag was consistently one turn. The attributes were all correct: `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens` on the parent, durations on the children. A naive dashboard counting `execute_tool` spans by `gen_ai.tool.name` reported accurate volumes. A causal query — "for each agent turn, which tools did it invoke and in what order" — returned turn-1 tools as root spans, turn-2 tools attributed to turn 1, and turn-3 tools attributed to turn 2. The causal graph was shifted by one hop and the first hop was severed entirely. Worse, because the cached `traceparent` was captured from the *first* dispatch and never refreshed, a long-running MCP server serving multiple concurrent agent sessions would attribute all tool spans to whichever session happened to dispatch first. The mechanism: the MCP server's handler read `params._meta.traceparent` once at startup into a module-level variable (a common "initialize the propagator from the first request" pattern), then called `tracer.start_span()` inside the tool handler without `context=extracted_context`. `start_span()` with no explicit context uses the *current* context, which inside the handler is the server's root context — producing a new root span with a fresh trace-id on the first call, and thereafter inheriting the stale cached context. The GenAI attributes were set explicitly on each span, so the spans looked correct in isolation. Only the `SpanContext` linkage was wrong. ## Condition of Validity A tool-call span is causally valid under the GenAI conventions if and only if all of the following hold at the moment the span is started: 1. The dispatching agent captured `traceparent` (and `tracestate` if present) from the *active* agent span via the configured `TextMapPropagator.inject()`, not from a cached or module-level value. 2. The captured header was transported intact across the dispatch boundary — for MCP, inside `params._meta` of the `tools/call` request; for subprocess, via environment or argv; for HTTP, via request headers. 3. The receiving side ran `TextMapPropagator.extract()` on the *inbound* request's metadata to reconstruct a `Context`, and passed that `Context` explicitly to `tracer.start_span(..., context=extracted_ctx)` or `start_as_current_span(..., context=extracted_ctx)`. 4. No intermediate `await`, thread hop, or task spawn dropped the `Context` between extraction and span start — i.e., the extracted context was passed as an argument, not relied upon via contextvars that may not have propagated. 5. The span was ended exactly once, on the same tracer that started it, before the tool result was returned to the agent — so that `gen_ai.tool.call.id` on the child matches the `gen_ai.tool.call.id` the agent records on the parent's event list. If condition 1 fails (cached header), you get the one-turn lag and cross-session mis-attribution. If condition 2 fails (header not transported), you get orphaned root spans. If condition 3 fails (extract but not pass to `start_span`), you get orphaned spans *despite* a correct header in flight — the most insidious case, because the header is present and correct and the bug is a single missing keyword argument. If condition 4 fails (contextvar dropped across an async boundary), you get intermittent orphans correlated with concurrency, which look like flaky telemetry rather than a structural defect. ## Decision Boundary The runtime must decide, per dispatch, whether the tool execution substrate is *in-process and context-propagating* or *out-of-process and context-serializing*. The boundary is not "local vs remote" — an in-process `asyncio.create_task` can drop context just as effectively as a network hop if the task is created outside the captured context. The boundary is: **does the substrate guarantee that the `Context` object passed at dispatch is the `Context` object visible at span creation?** - If yes (in-process synchronous call with explicit `context=` argument), the default `start_as_current_span` is safe and no manual injection is needed. - If no (subprocess, MCP stdio, HTTP, worker pool, thread pool), the runtime **must** inject at dispatch, transport, extract at receive, and pass the extracted context explicitly to span creation. It **must not** rely on contextvars surviving the boundary. It **must not** cache the injected header across dispatches — the header is per-call, not per-connection. The guardrail: a startup-time assertion that the tool-execution tracer's propagator is configured, plus a per-call invariant check that the extracted `SpanContext` is valid (`trace_id != 0`) and that its `trace_id` matches the dispatching agent span's `trace_id` before the tool span is started. If the check fails, the runtime must either fail the tool call (strict mode) or emit the span with an explicit `gen_ai.tool.call.orphaned = true` attribute and a synthetic parent link to the agent span by trace-id only (lenient mode) — never silently emit a mis-parented span. ## Operational Effect The consequence of the mis-linkage is not lost data but *false causal data*. Incident triage that asks "which tool call caused this agent turn to fail" walks the span tree upward from the failing child; with a one-turn-lagged parent link, the walk lands on the previous turn's agent span, and the investigator attributes the failure to a tool that ran in a prior, unrelated turn. Token accounting that sums `gen_ai.usage.input_tokens` over the parent-child subtree double-counts or under-counts by exactly one turn's worth of tool calls. Latency attribution that computes "time spent in tools vs time spent in model" per agent turn assigns turn N's tool latency to turn N-1, which in a loop with variable tool cost produces a systematically wrong bottleneck attribution — the model looks slow in the turn where tools were slow, and vice versa. The cross-session variant is more severe: a shared MCP server with a cached header will attribute every concurrent session's tool spans to the first session's trace. In a multi-tenant deployment this is a telemetry data-leakage vector as well as a correctness defect — session B's tool arguments (if captured in span attributes) appear under session A's trace-id, and any trace-scoped access control on the observability backend now exposes B's activity to A's trace reader. The invariant to enforce is narrow and testable: **for every `execute_tool` span, `span.parent_span_id` must equal the `span_id` of the `invoke_agent` span that was active at dispatch, and `span.trace_id` must equal that agent span's `trace_id`.** This is checkable at span-end time in the SDK via a span processor that compares against the dispatching context, and it is the single assertion that catches all five failure conditions above. Runtimes that skip it will discover the defect only when a production incident is mis-triaged, at which point the telemetry that was supposed to explain the incident has become part of it. ```python from __future__ import annotations from dataclasses import dataclass class CausalLinkageError(RuntimeError): """Raised when a tool-call span is not correctly parented to its dispatching agent span.""" @dataclass(frozen=True) class SpanContext: trace_id: str span_id: str @dataclass(frozen=True) class ToolDispatch: agent_context: SpanContext # active agent span at dispatch time injected_traceparent: str | None # what was actually put on the wire extracted_context: SpanContext | None # what the receiver reconstructed tool_span_context: SpanContext # the context the tool span was actually started with def verify_causal_linkage(dispatch: ToolDispatch) -> None: """ Enforce the GenAI hierarchy invariant: a tool-call span must be a child of the agent span that was active at dispatch, in the same trace. This must be called after the tool span is started and before it is ended. """ agent = dispatch.agent_context tool = dispatch.tool_span_context if dispatch.injected_traceparent is None: raise CausalLinkageError( f"no traceparent injected at dispatch for agent span {agent.span_id}; " "tool span will be orphaned or mis-parented" ) if dispatch.extracted_context is None: raise CausalLinkageError( f"receiver failed to extract traceparent {dispatch.injected_traceparent!r}; " "start_span() will use the receiver's root context" ) if tool.trace_id != agent.trace_id: raise CausalLinkageError( f"trace mismatch: tool span trace_id={tool.trace_id} " f"!= agent span trace_id={agent.trace_id}; " "likely a cached or stale traceparent on a long-lived tool server" ) if tool.span_id != agent.span_id and tool.span_id != dispatch.extracted_context.span_id: # The tool span must either be the extracted parent itself (unlikely) or a # child whose parent is the agent span. We check the parent linkage below. pass # The decisive check: the tool span's parent must be the agent span, not a # sibling, not a prior turn's agent span, and not the receiver's root. if dispatch.extracted_context.span_id != agent.span_id: raise CausalLinkageError( f"parent mismatch: extracted parent span_id={dispatch.extracted_context.span_id} " f"!= active agent span_id={agent.span_id}; " "tool span will be attributed to the wrong agent turn" ) def dispatch_tool_call( agent_context: SpanContext, inject, transport, extract, start_span, ) -> ToolDispatch: """ Reference dispatch path that preserves the GenAI causal invariant across an out-of-process boundary (MCP stdio, subprocess, HTTP). """ # 1. Inject from the ACTIVE agent span — never from a cached/module-level value. traceparent = inject(agent_context) if traceparent is None: raise CausalLinkageError( f"propagator returned no traceparent for agent span {agent_context.span_id}" ) # 2. Transport intact across the boundary. wire_payload = transport(traceparent) # 3. Extract on the receiving side from the INBOUND payload. extracted = extract(wire_payload) if extracted is None: raise CausalLinkageError( "receiver could not reconstruct a SpanContext from the inbound traceparent" ) # 4. Pass the extracted context EXPLICITLY to start_span — do not rely on # contextvars surviving the process/async boundary. tool_span = start_span(context=extracted) dispatch = ToolDispatch( agent_context=agent_context, injected_traceparent=traceparent, extracted_context=extracted, tool_span_context=tool_span, ) # 5. Enforce the invariant before the span is ended. verify_causal_linkage(dispatch) return dispatch ```