# Why does an instance lose tool-call attribution when OpenTelemetry GenAI spans are parented across an async tool boundary? **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions, v1.27+) where a tool call executes asynchronously and the tool span is created inside a different task/executor context than the parent `invoke_agent` span. Does not apply to fully synchronous single-threaded tool invocation, nor to runtimes that propagate `Context` explicitly through every await boundary. ## Core Distinction The GenAI semantic conventions define a *logical* parent-child relationship between `gen_ai.invoke_agent` → `gen_ai.execute_tool` spans, and they assume token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) aggregates along that logical tree. OpenTelemetry, however, propagates parentage through the *runtime `Context` object* — an implicit, task-local variable. The distinction that breaks operators is this: **span parentage is a property of the execution context, not of the logical agent tree.** When an agent dispatches a tool onto a thread pool, an `asyncio.create_task`, or an MCP client's callback loop, the child span is created against whatever `Context` is active *there* — frequently the root, an unrelated request, or a detached context with no `invoke_agent` parent. The result is a tool span that is logically a child of the agent but structurally an orphan, and token usage that never rolls up. This is not a sampling or exporter bug. It is a correct implementation of the tracing model being asked to represent an incorrect assumption about agent execution topology. ## What Was Observed A research agent (`gen_ai.invoke_agent`, span `A`) issued a `gen_ai.execute_tool` call to a code-interpreter tool. The tool ran on a `ThreadPoolExecutor` because the interpreter client was synchronous, wrapped in `asyncio.to_thread`. Three symptoms appeared together: 1. The tool span `T` was exported with `parent_span_id = null` (root), not `A`'s span ID. In Jaeger it appeared as a separate trace fragment. 2. `gen_ai.usage.output_tokens` on `A` was `0` for the turn where the tool produced 4,800 tokens of result, because the runtime attributed the tool's output tokens to `T`, which had no ancestor to aggregate into. 3. A downstream cost dashboard that summed `gen_ai.usage.*` per trace undercounted by roughly 30% on tool-heavy turns and overcounted on turns where the tool span landed in a *different* concurrent request's trace (context bleed). The trigger was precise: `asyncio.to_thread` copies the current `Context` at call time *only if* the runtime uses `contextvars.copy_context().run` — but many third-party synchronous tool clients reset or did not carry the context, and `opentelemetry-instrumentation-threading` was not installed. Without that instrumentation, the thread started with an empty context. The `Tracer.start_as_current_span("gen_ai.execute_tool")` inside the thread therefore saw no active span and became a root. ## Condition of Validity The invariant that must hold for correct GenAI attribution is: > **For every `gen_ai.execute_tool` span `T` logically issued by agent span `A`, `T.trace_id == A.trace_id` AND `T.parent_span_id == A.span_id` at export time, and every token counted on `T` must be reachable by summing the subtree rooted at `A`.** This invariant is *valid* only when one of the following holds at the moment `T` is created: - the tool executes on the same thread/task as `A` with `A`'s context active, or - the context is explicitly captured (`ctx = contextvars.copy_context()`) before dispatch and re-attached (`ctx.run(...)` or `otel_context.attach(ctx)`) inside the worker, or - threading/async instrumentation is installed and correctly propagates context. It is *invalid* — and silently so — whenever a worker boundary is crossed without explicit context capture. The failure is silent because OTel's default is to attach to the current context, and an empty context yields a valid, exportable, *wrong* span rather than an error. ## Decision Boundary The operator must decide, per tool-dispatch site, between two postures: - **Propagate:** capture and re-attach context across every worker boundary. Choose this when token accounting and trace-tree integrity feed billing, SLOs, or auditor replay. Cost: every async/thread dispatch site must be audited; one missed `attach` reintroduces orphaning. - **Reconcile:** allow structural orphaning but enforce a post-hoc join key. Stamp both `A` and `T` with a shared `gen_ai.agent.run_id` (or W3C `tracestate` entry) attribute, and reconcile token sums by `run_id` rather than by trace subtree. Choose this when tools are third-party and you cannot control their dispatch. The boundary is crossed when **any** tool span can be emitted from a context you do not own. At that point `Propagate` is unenforceable and `Reconcile` becomes mandatory. The dangerous middle state — assuming `Propagate` works while a single uninstrumented client orphans spans — is what produces the 30% undercount. ## Operational Effect Under the broken invariant, three operational consequences compound: 1. **Token accounting diverges from spend.** Summing `gen_ai.usage.*` per trace undercounts exactly on the turns where tools are most expensive (large retrieval results, long code outputs), biasing cost models toward cheap-looking tool use. 2. **Trace-tree integrity fails for replay.** An auditor reconstructing "what did the agent see when it decided X" walks `A`'s subtree and finds it empty of the tool result that actually drove the decision — the evidence is in an orphaned fragment. 3. **Context bleed corrupts attribution.** When two agent requests run concurrently on the same pool and context is not isolated, a tool span can attach to the *wrong* `invoke_agent` — attributing one agent's tool cost to another. This is the worst case: not missing data, but confidently wrong data. The guardrail is a validation pass that, before export (or in a collector processor), asserts the invariant above and either repairs parentage via the `run_id` join or emits a hard error. Silent orphaning must be converted to a loud failure, because the semantic convention's aggregation contract is only as good as the context propagation beneath it. ```python from dataclasses import dataclass from typing import Optional class GenAIAttributionError(RuntimeError): """Raised when a GenAI tool span violates the parentage/rollup invariant.""" pass @dataclass class SpanRecord: span_id: str parent_span_id: Optional[str] trace_id: str name: str run_id: Optional[str] input_tokens: int = 0 output_tokens: int = 0 def validate_tool_attribution(agent: SpanRecord, tool: SpanRecord) -> None: """ Enforce: tool span must be a structural child of the agent span in the same trace, OR carry a matching run_id for reconciliation. Otherwise the token rollup and trace-tree replay are silently wrong. """ if tool.name != "gen_ai.execute_tool": raise GenAIAttributionError( f"expected tool span, got {tool.name!r}" ) structurally_linked = ( tool.trace_id == agent.trace_id and tool.parent_span_id == agent.span_id ) reconcilable = ( tool.run_id is not None and agent.run_id is not None and tool.run_id == agent.run_id ) if not structurally_linked and not reconcilable: raise GenAIAttributionError( "tool span orphaned: trace_id=" f"{tool.trace_id} parent={tool.parent_span_id} " f"agent={agent.span_id} (trace {agent.trace_id}); " f"run_id tool={tool.run_id} agent={agent.run_id}. " "Token rollup and replay will be incorrect." ) if structurally_linked and tool.trace_id != agent.trace_id: # Defensive: cannot both be child and cross-trace. raise GenAIAttributionError( "inconsistent span record: parent set but trace_id differs" ) def rollup_tokens(agent: SpanRecord, tools: list[SpanRecord]) -> int: """Sum agent + verified tool tokens; refuse to roll up unverified tools.""" total = agent.input_tokens + agent.output_tokens for t in tools: validate_tool_attribution(agent, t) # raises on orphaning total += t.input_tokens + t.output_tokens return total ```