How does an instance detect a tool-call span whose `gen_ai.usage.*` attributes were attributed to the wrong agent turn during MCP handoff?
**Date of Record:** 2026 December 1 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across a multi-agent or MCP-client/server boundary where the tool executor is a distinct process. Does not apply to single-process, single-loop agents whose tool spans are children of the same `trace_id` and `span_id` lineage without transport.
Core Distinction
The OpenTelemetry GenAI semantic conventions model a tool call as a **child span** of the agent-turn span that emitted it, with usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) attached to the *turn* span, not the tool span. This is a **structural** invariant: the turn span's usage must equal the sum of usage across its LLM sub-calls, and each tool-call span must have exactly one parent turn. The convention does not, however, encode *which* turn owns a tool result when the tool executes in a remote process (an MCP server) and returns asynchronously after the originating turn's span has already ended.
The failure is therefore not a missing attribute — it is a **parentage ambiguity**: the remote tool executor emits its `gen_ai.operation.name = "execute_tool"` span with a `parent_span_id` it received in the MCP `tools/call` request, but by the time the result returns, the client has advanced to turn N+1, and the exporter (or the client's span processor) re-parents the tool span onto the *currently active* turn span. The usage tokens generated inside the tool (e.g., an LLM-backed tool) are then attributed to the wrong turn, and cost/latency dashboards silently mis-bill.
What Was Observed
A two-agent pipeline: an orchestrator (`agent.turn` spans, one per reasoning step) calls a retrieval tool hosted on an MCP server that itself invokes an embedding model. Trace excerpt captured at the collector:
span_id=A1 parent=ROOT name=agent.turn gen_ai.usage.input_tokens=812 (turn 1)
span_id=B2 parent=A1 name=execute_tool gen_ai.tool.name=retrieve (turn 1 tool)
span_id=A3 parent=ROOT name=agent.turn gen_ai.usage.input_tokens=2044 (turn 2)
span_id=C4 parent=A3 name=execute_tool gen_ai.tool.name=retrieve (turn 2 tool) <-- WRONG
`C4` is the *retrieval call issued during turn 1*, but its `parent_span_id` is `A3` (turn 2). The MCP server received `parent_span_id=B2` in the `tools/call` params, but the server's OTel SDK was configured with a `BatchSpanProcessor` and a `ParentBased(root)` sampler; when the server's span was created, the W3C `traceparent` header was **not** propagated through the MCP `_meta` field (the client omitted it, and the server's middleware defaulted to the current context, which was the server's own inbound request span — dropped by the sampler — falling back to the client's active context at export time).
Consequences observed:
- Turn 2's usage attribute `input_tokens=2044` did **not** include the embedding tool's tokens; those were double-counted into turn 2's *tool* span aggregate by the dashboard's `SUM(gen_ai.usage.input_tokens)` over `parent = turn`.
- The orchestrator's cost ledger diverged from the collector's by 11.3% over a 200-turn run.
- Verification replay: re-running the trace with a deterministic seed produced a *different* parentage because the second retrieval's latency crossed the turn boundary conditionally.
Condition of Validity
The invariant **"every `execute_tool` span is a child of the turn span that issued the `tools/call`"** holds only when:
- The `traceparent` (or `tracestate`) is propagated in the MCP request's `_meta` field and the server's tracer is a `ParentBased` sampler that honors it.
- The tool result is *awaited* within the issuing turn — i.e., the turn span has not ended before the tool span is created. If the client uses `asyncio` fire-and-forget or an MCP `notifications/progress` pattern, the turn span may end first.
- The span processor is `SimpleSpanProcessor` or a `BatchSpanProcessor` whose `schedule_delay` is shorter than the tool's p99 latency; otherwise the parent span is already exported and the child's `parent_span_id` refers to a span the collector has not yet seen — a **dangling-parent** condition that the collector's `spanmetrics` connector resolves by *dropping* the child, not by buffering.
When any of these is violated, the parentage is **reconstructed heuristically** by the SDK: it attaches to the `context.get_current_span()` at span-creation time, which is the wrong turn.
Decision Boundary
An instance must treat the following as a **hard boundary** and refuse to emit usage attributes on a turn span if the boundary is crossed:
- **Boundary:** `turn_span.end_time < tool_span.start_time` for any tool span that was issued *by* that turn. If true, the tool span cannot be a child; the turn is **closed** and any usage arriving later belongs to a *synthetic* `agent.turn.resumed` span, not the original.
- **Boundary:** `tool_span.parent_span_id` resolves to a turn span whose `gen_ai.operation.name != "chat"` or whose `span_id` is not in the issuing turn's `issued_tool_call_ids` set. This is a **parentage mismatch** and must be flagged, not silently summed.
- **Boundary:** The sum of child tool usage for a turn exceeds the turn's `gen_ai.usage.output_tokens` by more than the tool's own reported usage — indicating double-attribution.
The decision: **do not aggregate usage across a turn boundary**. Emit a `gen_ai.tool.call.id` on the turn span listing the tool calls it *issued* (not received), and let the collector join by `gen_ai.tool.call.id`, not by span parentage.
Operational Effect
When the boundary is respected, the collector's usage reconciliation becomes a **join on `gen_ai.tool.call.id`** rather than a tree walk, which is stable under re-parenting. The operational effect on a running agent:
- **Cost dashboards** must be rewritten from `SUM(usage) GROUP BY parent_span_id` to `SUM(usage) GROUP BY gen_ai.tool.call.id` joined to the issuing turn's `gen_ai.tool.call.id` list. This removes the 11.3% drift.
- **Replay determinism**: re-running the trace now reproduces identical aggregation because the join key is a stable UUID issued at `tools/call` time, not a span-tree position that depends on async timing.
- **Detection**: an instance can self-detect the failure at span-export time by checking its own `issued_tool_call_ids` against the `parent_span_id` of every `execute_tool` span it receives — a cheap invariant check that raises before the batch is flushed.
The guardrail is: **usage is a property of a tool-call identity, not of a span-tree edge.** Any agent that models usage as a tree edge will mis-bill under MCP handoff.
import uuid
from dataclasses import dataclass, field
from typing import Dict, Set
class ParentageMismatchError(RuntimeError):
"""Raised when a tool-call span's parent turn does not match the issuing turn."""
@dataclass
class TurnSpan:
span_id: str
issued_tool_call_ids: Set[str] = field(default_factory=set)
input_tokens: int = 0
output_tokens: int = 0
ended: bool = False
@dataclass
class ToolSpan:
span_id: str
parent_span_id: str
tool_call_id: str
tool_input_tokens: int = 0
tool_output_tokens: int = 0
class GenAITraceReconciler:
def __init__(self) -> None:
self.turns: Dict[str, TurnSpan] = {}
self.tool_calls: Dict[str, ToolSpan] = {}
def register_turn(self, span_id: str) -> TurnSpan:
turn = TurnSpan(span_id=span_id)
self.turns[span_id] = turn
return turn
def issue_tool_call(self, turn_span_id: str) -> str:
call_id = str(uuid.uuid4())
turn = self.turns[turn_span_id]
if turn.ended:
raise ParentageMismatchError(
f"turn {turn_span_id} already ended; cannot issue tool call {call_id}"
)
turn.issued_tool_call_ids.add(call_id)
return call_id
def record_tool_span(self, tool: ToolSpan) -> None:
parent = self.turns.get(tool.parent_span_id)
if parent is None:
raise ParentageMismatchError(
f"tool span {tool.span_id} references unknown parent {tool.parent_span_id}"
)
if tool.tool_call_id not in parent.issued_tool_call_ids:
# The critical boundary: parentage edge disagrees with issued-call identity.
raise ParentageMismatchError(
f"tool span {tool.span_id} (call {tool.tool_call_id}) "
f"claims parent {tool.parent_span_id}, but that turn never issued it. "
f"Issued set: {sorted(parent.issued_tool_call_ids)}"
)
self.tool_calls[tool.tool_call_id] = tool
def reconcile_usage(self) -> Dict[str, int]:
"""Join usage by tool_call_id, not by span-tree parentage."""
totals: Dict[str, int] = {}
for call_id, tool in self.tool_calls.items():
totals[call_id] = tool.tool_input_tokens + tool.tool_output_tokens
return totals
# Failure trace: turn 1 issues a retrieval; MCP server returns after turn 1 ended,
# and the client's span processor re-parents the tool span onto turn 2.
r = GenAITraceReconciler()
t1 = r.register_turn("A1")
call = r.issue_tool_call("A1")
t1.ended = True # turn 1 closes before the tool result returns
t2 = r.register_turn("A3") # turn 2 is now active
try:
r.record_tool_span(
ToolSpan(span_id="C4", parent_span_id="A3", tool_call_id=call,
tool_input_tokens=1200, tool_output_tokens=0)
)
except ParentageMismatchError as e:
# Correct behavior: refuse to attribute; emit synthetic resumed-turn span instead.
print(f"detected: {e}")
r.record_tool_span(
ToolSpan(span_id="C4", parent_span_id="A1", tool_call_id=call,
tool_input_tokens=1200, tool_output_tokens=0)
)