# What happens when an instance emits OpenTelemetry GenAI spans whose tool-call attributes are re-parented across an async handoff, silently breaking token and cost attribution **Date of Record:** 2026 November 22 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) and where tool execution is dispatched asynchronously (thread pool, task queue, or remote worker) while the parent agent span remains open. Does not apply to fully synchronous single-threaded agent loops where the tool call completes within the lexical scope of the parent span. ## Core Distinction The GenAI semantic conventions treat a tool call as a *child* span of the agent's inference span, carrying `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name`, and — critically for accounting — the token and cost attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) that the *model* consumed to decide to call that tool. The invariant the conventions assume but do not enforce is **lexical span nesting equals causal attribution nesting**: the span that records "the model spent 812 output tokens emitting this tool call" must be nested under the span whose `trace_id`/`span_id` the cost aggregator walks. That invariant holds trivially in a synchronous loop. It breaks the moment a tool is dispatched to an async executor and the child span is created *there*, because OpenTelemetry's context propagation is thread-local (or task-local in `asyncio`). If the executor does not explicitly capture and re-attach the parent `Context`, the tool span is created with no parent — it becomes a **root span in a new trace**. The GenAI attributes are all still present and syntactically valid. Only the causal link is gone. ## What Was Observed A research agent using a `ThreadPoolExecutor(max_workers=8)` for tool dispatch emitted, per task, one `gen_ai.chat` span (the inference) and N `gen_ai.execute_tool` spans (the tool calls). The inference span carried `gen_ai.usage.output_tokens = 812` and a `gen_ai.request.model` attribute. The tool spans each carried their own `gen_ai.tool.name` and a *duplicate* copy of the model's usage attributes — because the instrumentation hook that recorded "tokens spent producing this call" ran inside the tool wrapper, reading from the shared response object. Downstream, the cost pipeline summed `gen_ai.usage.output_tokens` grouped by `trace_id`. Two failures compounded: 1. **Double counting.** The 812 output tokens appeared once on the `chat` span and N times on the tool spans (once per tool call in the batch). A single 812-token inference with 4 parallel tool calls reported 812 × 5 = 4,060 output tokens. Cost reports inflated ~5× on tool-heavy turns and ~1× on turns with no tools — so the error was *correlated with agent behavior*, not random, and did not average out. 2. **Orphaned root spans.** Because the executor threads did not re-attach the parent context, each `execute_tool` span started a fresh trace with a new `trace_id`. The cost aggregator's `GROUP BY trace_id` therefore saw the tool spans as separate traces with no `chat` parent, producing a long tail of "traces" that consisted of a single tool span and no inference — which the anomaly detector flagged as *cheap* traces, masking the inflation on the real traces. The net effect: aggregate spend looked plausible (the orphan traces dragged the mean down while the double-counted traces dragged it up), and per-trace cost was wrong in *both* directions simultaneously. No exception was raised. Every span validated against the semantic-convention schema. ## Condition of Validity The failure requires all of the following to co-occur: - Tool execution is dispatched across a context boundary (thread, process, task queue) rather than inline. - The instrumentation reads usage/token attributes from a shared response object at tool-span creation time rather than binding them to the inference span at inference-completion time. - The cost aggregator attributes usage by summing attributes over all spans in a trace, rather than by reading usage exclusively from `gen_ai.operation.name = "chat"` spans. - Parent context is not explicitly propagated into the executor (no `contextvars.copy_context()` or `trace.use_span(..., end_on_exit=False)` wrapping the dispatch). Remove any one condition and the failure does not manifest. This is why it survives code review: each individual component is correct in isolation. ## Decision Boundary The architectural guardrail is a **single-writer rule for usage attributes**: `gen_ai.usage.*` and cost attributes may be emitted by exactly one span per model invocation — the inference span — and must never be copied onto derived spans. Tool spans record *identity* (`gen_ai.tool.name`, `gen_ai.tool.call.id`) and *latency*, never *cost*. The second guardrail is **context capture at dispatch**: any handoff across a concurrency boundary must carry the OpenTelemetry `Context` explicitly, so the tool span is a true child. The runtime should assert at span-creation time that the span has a parent; a root-level `execute_tool` span is a detectable invariant violation, not a legal state. The decision boundary for operators: if you cannot guarantee single-writer usage attribution, then your cost aggregator must *filter by operation name* before summing — accepting that orphaned tool spans are then invisible to cost entirely, which is the lesser evil versus double counting. ## Operational Effect Without the guardrail, cost telemetry becomes behavior-correlated noise: accurate on simple turns, inflated on parallel-tool turns, and silently redistributed by orphan traces. Budget alarms fire late or not at all because the inflation is partially canceled by the orphan tail. The remediation is cheap — capture context at dispatch, bind usage only on the inference span, and add a startup assertion that no `execute_tool` span is a root — but the failure is invisible until someone reconciles against the provider's invoice and finds the discrepancy has a shape. ```python from dataclasses import dataclass class SpanAttributionError(RuntimeError): """Raised when a tool span violates the single-writer usage invariant.""" @dataclass class Span: operation_name: str parent_span_id: str | None attributes: dict def validate_tool_span(span: Span) -> None: # Invariant 1: a tool span must be a child of an inference span, never a root. if span.operation_name == "execute_tool" and span.parent_span_id is None: raise SpanAttributionError( f"tool span {span.attributes.get('gen_ai.tool.name')!r} has no parent; " "context was not propagated across the async handoff" ) # Invariant 2: usage/cost attributes are single-writer, on the chat span only. if span.operation_name == "execute_tool": leaked = [k for k in span.attributes if k.startswith("gen_ai.usage.")] if leaked: raise SpanAttributionError( f"tool span carries usage attributes {leaked}; " "these belong on the parent chat span and will double-count cost" ) def aggregate_cost(spans: list[Span]) -> int: total = 0 for span in spans: validate_tool_span(span) if span.operation_name == "chat": total += span.attributes.get("gen_ai.usage.output_tokens", 0) return total ```