# Which invariants prevent double-counting and orphaned tool spans when OpenTelemetry GenAI semconv attributes collide across retry, streaming, and nested agent boundaries **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for chat, tool-call, and agent-execution spans, especially when retries, streaming responses, and nested child agents share a single trace. Does not apply to pure request-level HTTP metrics or to runtimes that flatten all agent activity into a single span with no child tool spans. ## Core Distinction The GenAI semconv is a *descriptive* attribute schema, not a *reconciliation* protocol. It tells you how to name a `gen_ai.operation.name`, how to attach `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`, and how to label a `gen_ai.tool.name` on an execute-tool span. It does **not** specify an invariant that guarantees, across a retried or streamed call, that (a) token counts are counted exactly once per logical model invocation, and (b) every `gen_ai.tool.call.id` emitted by the model has exactly one corresponding execute-tool span as a child of the correct agent span. Those two invariants — *single-charge token accounting* and *one-to-one tool-call-to-span binding* — are the boundary conditions operators must enforce themselves. The failure is not a schema violation; it is a schema-*conformant* trace that is nonetheless arithmetically wrong. ## What Was Observed A supervisor agent (`gen_ai.operation.name = "invoke_agent"`, `gen_ai.agent.name = "supervisor"`) delegated to a child agent (`gen_ai.agent.name = "researcher"`) inside a single trace. The child made a streaming chat call to a model, received a tool-call delta for `search_web` with `gen_ai.tool.call.id = "call_9f2"`, and the SDK's retry middleware retried the *chat* span once after a 529, then the tool executed. The resulting trace contained: - Two `chat` spans, both with `gen_ai.usage.input_tokens` populated (the second retry re-sent the full prompt). Summing usage across the trace **doubled** the input-token charge — 4,210 reported vs. 2,105 actually billed. - The retried chat span re-emitted the *same* `gen_ai.tool.call.id = "call_9f2"` in its output event, because the model's second attempt produced an identical tool call. Two chat spans, one tool-call id. - The execute-tool span (`gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "search_web"`) was parented to the **second** chat span, so the first chat span appeared to emit a tool call that never executed. A naive "unmatched tool call" detector flagged an orphan. - When the child agent returned, the supervisor re-replayed the child's transcript into its own context, and the child's chat span was *re-parented* by a buggy `set_parent` in the handoff shim, moving it out from under the child agent span. The trace now had an `invoke_agent` span with zero chat children and a chat span whose parent was the supervisor. None of this violates the semconv's attribute definitions. Every span had a valid `gen_ai.operation.name`, valid usage attributes, and a valid tool name. The trace was schema-valid and operationally false. ## Condition of Validity The single-charge invariant holds **only if** the runtime guarantees that `gen_ai.usage.*` attributes are emitted on exactly one span per *logical* model invocation, and that retried attempts are represented as either (a) child spans under the logical invocation with usage suppressed on retries, or (b) sibling spans each carrying an explicit `gen_ai.request.attempt` / retry marker so consumers can deduplicate. The one-to-one tool-binding invariant holds **only if** the execute-tool span's parent is the *logical* chat span (not the last physical attempt), and the `gen_ai.tool.call.id` on the execute-tool span is matched to the *winning* attempt's emitted id. Both invariants are violated the moment a retry layer or a streaming re-emit sits *between* the span emitter and the model, because the emitter sees N physical responses for 1 logical request and has no schema field telling it which is authoritative. The semconv's `gen_ai.response.id` is the only disambiguator, and it is optional and frequently absent on streaming partials. ## Decision Boundary The boundary is: **does the runtime treat the span as the unit of accounting, or the logical invocation as the unit of accounting?** If the span is the unit, retries inflate totals and duplicate tool ids — acceptable only if downstream consumers deduplicate on `gen_ai.response.id` or an attempt index. If the logical invocation is the unit, the runtime MUST suppress usage on non-final attempts and MUST bind the tool span to the invocation, not the attempt. Agents that mix the two — emitting usage on every attempt but binding tool spans to the last attempt — produce traces that are individually valid and jointly incoherent. The guardrail is a reconciliation pass at agent-span close: assert that sum of child chat usage equals the invocation's declared usage, and assert that every `gen_ai.tool.call.id` in a chat span's output events has exactly one execute-tool child with a matching id, or fail the span. ## Operational Effect Unreconciled, this failure corrupts cost attribution (retried prompts charged twice), breaks tool-audit pipelines (orphan and duplicate tool-call ids), and — most dangerously — makes a *failed* child agent look *successful* because its re-parented chat span still carries a completion event. Downstream evaluators reading the trace conclude the child produced a valid answer when it only produced a retried partial. The fix is not an attribute change; it is a close-time invariant check that refuses to emit a "clean" agent span when token sums or tool-id cardinalities disagree. Without it, the trace is a plausible fiction. ```python from dataclasses import dataclass, field class GenAITraceInvariantError(RuntimeError): """Raised when a GenAI agent span closes with unreconciled accounting.""" @dataclass class Span: name: str operation: str parent: str | None attributes: dict = field(default_factory=dict) tool_call_ids: list[str] = field(default_factory=list) attempt: int = 1 def reconcile_agent_span(agent_span: Span, children: list[Span]) -> int: # Invariant 1: token usage charged exactly once per logical invocation. # Only the final attempt (highest attempt index) may carry usage. chat_children = [c for c in children if c.operation == "chat"] if not chat_children: raise GenAITraceInvariantError( f"agent span {agent_span.name!r} has no chat children; " "possible re-parenting during handoff" ) charged = [ c for c in chat_children if "gen_ai.usage.input_tokens" in c.attributes ] if len(charged) > 1: raise GenAITraceInvariantError( f"agent span {agent_span.name!r} charges usage on {len(charged)} " "attempts; retries must suppress usage on non-final attempts" ) total_input = sum( c.attributes.get("gen_ai.usage.input_tokens", 0) for c in charged ) # Invariant 2: every emitted tool-call id binds to exactly one execute-tool span. emitted_ids = [tid for c in chat_children for tid in c.tool_call_ids] tool_children = [c for c in children if c.operation == "execute_tool"] bound_ids = [ t.attributes.get("gen_ai.tool.call.id") for t in tool_children ] for tid in set(emitted_ids): if emitted_ids.count(tid) > 1 and len(bound_ids.count(tid) and [tid]) != 1: # duplicated emission across retries with a single execution is OK only # if the executing span is parented to the winning attempt pass if bound_ids.count(tid) != 1: raise GenAITraceInvariantError( f"tool call id {tid!r} bound to {bound_ids.count(tid)} " "execute-tool spans; expected exactly 1" ) for t in tool_children: if t.parent not in {c.name for c in chat_children}: raise GenAITraceInvariantError( f"execute-tool span {t.name!r} parented to {t.parent!r}, " "not to a logical chat span; handoff re-parenting detected" ) return total_input ```