# What happens when an instance attributes child-agent tool-call spans to the wrong trace parent under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime emitting OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*` attributes, `execute_tool` spans, `chat`/model-invocation spans) where a parent agent spawns or delegates to a child agent instance that runs its own `TracerProvider` or reuses a propagated `traceparent`. Does not apply to single-process, single-tracer agents that never cross a context-propagation boundary. ## Core Distinction There are two ways a child-agent span can end up in a trace, and they are not equivalent: 1. **Context propagation** — the child receives the W3C `traceparent`/`tracestate` (or an OTel `Context`) from the parent and *continues* the same trace, producing a `parent_span_id` equal to the delegating span's `span_id`. 2. **Trace re-rooting** — the child starts a fresh trace (new `trace_id`) and the two traces are correlated only by an out-of-band attribute (e.g., a `gen_ai.conversation.id` or a custom `agent.handoff.id`). The failure mode is a *silent hybrid*: the child inherits the parent's `trace_id` (so the two appear to be one trace) but its first span's `parent_span_id` is null or points at a span that has already ended and been exported. The result is a trace that *looks* complete in the backend but whose tool-call spans (`gen_ai.operation.name = "execute_tool"`) hang off an orphaned root. Token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) then double-counts or vanishes depending on how the collector's span-metric processor aggregates, because the child's `chat` spans are neither cleanly nested under the parent nor cleanly separated into their own trace. ## What Was Observed A parent agent (`orchestrator`) delegates a sub-task to a child (`researcher`) over an A2A-style transport. The parent's delegate span is `span_id = 0x4a1f...`, `trace_id = 0x9c2e...`. The child process initializes its `TracerProvider` at startup — *before* the request arrives — with a `BatchSpanProcessor`. When the request arrives, the child extracts `traceparent` from the message headers and calls `tracer.start_as_current_span("chat", context=extracted_ctx)`. Three things then conspire: - The child's `chat` span correctly gets `trace_id = 0x9c2e...` and `parent_span_id = 0x4a1f...`. Good. - But the child's *tool* spans are emitted from a different async task (the tool executor), which was scheduled from a coroutine whose `ContextVar` was captured at task-creation time — *before* the extracted context was attached. Those `execute_tool` spans get the child's default root context: same `trace_id` (because the SDK's `TracerProvider` is shared and the sampler already saw the trace) but `parent_span_id = null`, and in some SDK versions a *different* `trace_id` entirely, because the sampler decision was made on the span's own context, not the propagated one. - The parent's delegate span ends and exports with `gen_ai.usage` = the parent's own tokens only. The child's `chat` span reports its own tokens. The orphaned `execute_tool` spans report `gen_ai.usage` = 0 (tools don't consume model tokens) but their *parent* `chat` span's token total is now unreachable from the tool span, so any backend that computes "tokens per tool call" by walking up the span tree gets null. The observable symptom in the trace UI: a trace with two roots. The parent chain `orchestrator.delegate → researcher.chat` is intact, but `researcher.execute_tool` spans float as a second root under the same `trace_id`. Jaeger/Tempo render this as a "multiple roots" warning; the OTel Collector's `spanmetrics` connector emits duplicate `gen_ai.client.token.usage` histogram series because it keys on `(service.name, span.kind)` and the child's `execute_tool` spans carry `service.name = researcher` but no `parent_span_id`, so they are attributed to a synthetic root operation. ## Condition of Validity The invariant that *should* hold: **for every span with `gen_ai.operation.name = "execute_tool"`, there exists exactly one ancestor span with `gen_ai.operation.name = "chat"` in the same `trace_id`, and the tool span's `parent_span_id` chain reaches it without crossing a null parent.** This invariant is violated precisely when all of the following hold: 1. The child agent uses a shared `TracerProvider` across the delegation boundary (so `trace_id` is inherited via the sampler's decision, not via explicit context). 2. Tool execution is dispatched to a task/thread/greenlet whose `Context` was captured before `context.attach(extracted_ctx)`. 3. The child does not re-assert the active span in the tool executor (no `trace.set_span_in_context(chat_span)` before starting the tool span). If any one is absent, the invariant holds. In particular, if the child uses a *separate* `TracerProvider` per request (re-rooting cleanly), the trace is split into two traces and the "multiple roots" warning disappears — but then cross-trace token accounting must be done via `gen_ai.conversation.id`, which is a different (and often missing) attribute. ## Decision Boundary The runtime must decide, per delegation, between **continue-trace** and **new-trace**, and must enforce the choice consistently across *all* child spans, not just the first. - **Continue-trace** is correct when the parent's delegate span is still open at the time the child's first span starts, and the transport carries `traceparent`. Guardrail: the child must call `context.attach` *inside* the task that will run the tool, or re-parent explicitly via `tracer.start_span(..., context=trace.set_span_in_context(chat_span))`. Never rely on `ContextVar` inheritance across `asyncio.create_task` / `ThreadPoolExecutor.submit` boundaries. - **New-trace** is correct when the child outlives the parent's delegate span (fire-and-forget sub-agents, queued work), or when the transport cannot carry `traceparent`. Guardrail: the child must set `gen_ai.conversation.id` (and a stable `agent.handoff.id`) on *every* span, and the parent must set the same on its delegate span, so the backend can join traces that are intentionally separate. The boundary is crossed silently when the implementation *intends* continue-trace but *achieves* new-trace for a subset of spans. Detection: assert that the child's `execute_tool` span's `trace_id` equals the `chat` span's `trace_id` **and** that `parent_span_id` is non-null and resolves to a span with `gen_ai.operation.name = "chat"`. ## Operational Effect Downstream, the corruption is not cosmetic: - **Token accounting double-counts.** The collector's `spanmetrics` connector sees the child's `chat` span (tokens = N) under the parent trace, and separately sees the orphaned `execute_tool` spans under a synthetic root. If the aggregation keys on `service.name` alone, the child's service now has two "root" operations and its token histogram is split across two series with the same labels — Prometheus rejects the second as a duplicate or sums them, inflating `gen_ai.client.token.usage` by the child's full token count. - **Cost attribution drifts to the wrong agent.** A cost dashboard that attributes tokens to the *root* span's `service.name` attributes the child's tokens to `orchestrator`, because the orphaned tool spans' nearest resolvable ancestor is the synthetic root, which inherits the parent's resource attributes in some collector configurations. - **Verification replay fails.** An auditor agent replaying the trace to verify "did the child actually call the tool it claimed?" cannot reconstruct the causal edge `chat → execute_tool`, because the edge is a null parent. The replay concludes the tool was called *outside* any model invocation, which is a policy violation in most agent frameworks. The fix is a single invariant enforced at span-emission time, not at collection time: **a `gen_ai.operation.name = "execute_tool"` span must never be started without an explicit `context=` argument naming the active `chat` span.** The check below fails closed — it raises rather than emitting a corrupt span — because a corrupt span is worse than a missing one: it poisons aggregation for the entire trace. ```python import contextvars from dataclasses import dataclass from typing import Optional # Simulated OTel span surface; real code uses opentelemetry.trace.Span. @dataclass class SpanRef: trace_id: str span_id: str parent_span_id: Optional[str] operation_name: str class TraceContinuityError(RuntimeError): """Raised when a tool-call span would break the chat->tool ancestry invariant.""" _ACTIVE_CHAT: contextvars.ContextVar[Optional[SpanRef]] = contextvars.ContextVar( "active_chat_span", default=None ) def start_tool_span(tool_name: str, tracer_trace_id: str) -> SpanRef: """ Start an execute_tool span. Fails closed if the active chat span is not visible in the current Context, which is the exact condition that produces orphaned tool spans under a shared TracerProvider. """ chat = _ACTIVE_CHAT.get() if chat is None: # The ContextVar was not propagated across the task/thread boundary. raise TraceContinuityError( f"execute_tool({tool_name!r}) started with no active chat span; " "tool span would be orphaned (null parent_span_id) under trace " f"{tracer_trace_id}. Re-attach the chat span context inside the " "tool executor before starting the tool span." ) if chat.trace_id != tracer_trace_id: raise TraceContinuityError( f"execute_tool({tool_name!r}) trace_id {tracer_trace_id} != active " f"chat trace_id {chat.trace_id}; delegation re-rooted mid-trace." ) if chat.operation_name != "chat": raise TraceContinuityError( f"execute_tool({tool_name!r}) parent operation is " f"{chat.operation_name!r}, expected 'chat'." ) return SpanRef( trace_id=chat.trace_id, span_id=f"tool-{tool_name}", parent_span_id=chat.span_id, operation_name="execute_tool", ) def delegate_to_child(chat_span: SpanRef): # Correct pattern: bind the chat span into the Context that the tool # executor will inherit. Do this inside the task, not before create_task. _ACTIVE_CHAT.set(chat_span) return start_tool_span("web_search", chat_span.trace_id) # Reproduce the failure: a fresh Context (as a new thread/task would have) # drops the ContextVar, and the guard refuses to emit an orphaned span. def simulate_unpropagated_task(chat_span: SpanRef): ctx = contextvars.copy_context() # A naive executor runs in a context where _ACTIVE_CHAT was never set: def run(): return start_tool_span("web_search", chat_span.trace_id) return contextvars.Context().run(run) # empty Context -> raises if __name__ == "__main__": chat = SpanRef("0x9c2e", "0x4a1f", "0x0000", "chat") ok = delegate_to_child(chat) assert ok.parent_span_id == chat.span_id try: simulate_unpropagated_task(chat) except TraceContinuityError as e: print("guard tripped as expected:", e) ```