# Where must an instance reconcile OpenTelemetry GenAI span accounting when a retried tool call double-counts tokens across a re-parented span? **Date of Record:** 2026 November 28 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) where tool invocations are retried and the retry is re-parented under a new agent-turn span. Does not cover non-instrumented runtimes or pure inference servers without tool-call loops. ## Core Distinction The failure is not "tokens are miscounted." It is that the *unit of accounting* (a span) and the *unit of work* (an idempotent tool invocation) diverge under retry. OpenTelemetry GenAI conventions attach `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` to the span that *issued* the model call, and tool spans nest beneath the agent span that *decided* to call the tool. When a tool call fails (timeout, 5xx, schema mismatch) and the agent retries, a naive instrumentation layer emits a second `execute_tool` span. If the retry is issued after a new reasoning turn—common when the agent re-plans—the new span is parented to a *different* agent-turn span than the original attempt. The backend then aggregates two disjoint subtrees, each carrying a partial token delta, and the total `gen_ai.usage.*` sum no longer equals the tokens the model actually consumed for that logical task. The distinction that matters: a *retry* is a continuation of one logical operation; a *re-plan* is a new operation. Instrumentation that cannot tell them apart will either double-count (retry treated as new) or under-count (re-plan treated as retry and suppressed). ## What Was Observed A three-step agent (plan → `search_docs` tool → synthesize) hit a 30s tool timeout on `search_docs`. The runtime's retry policy re-issued the call inside a *fresh* agent turn because the planner re-ran to decide whether to retry or fall back. Trace shape on the wire: - Turn A span: `gen_ai.operation.name=chat`, input 1,840 / output 210 tokens. Child: `execute_tool search_docs` (attempt 1) → `error.type=timeout`, no usage attributes (correct: tool spans carry no model tokens). - Turn B span: `gen_ai.operation.name=chat`, input 1,910 / output 240 tokens (planner re-ran, larger prompt). Child: `execute_tool search_docs` (attempt 2) → success. - Turn C span: `gen_ai.operation.name=chat`, input 2,050 / output 380 tokens (synthesis). The logical task consumed three model calls, and the sum of `gen_ai.usage.input_tokens` = 5,800 is *correct at the span level*. The breakage surfaced downstream: the cost dashboard deduplicated on a `tool.call_id` attribute the runtime had *not* set, so it fell back to grouping by `gen_ai.conversation.id` and `gen_ai.agent.name`, then summed *tool-attempt* spans—which carried zero usage—against a per-attempt budget ceiling. The budget check passed while the actual token spend was 1.9× the ceiling because Turn A's tokens were attributed to a span subtree the budget query filtered out (`status.code=ERROR` excluded). The invariant that failed: **every token consumed by a model call must be attributable to exactly one non-excluded span, and retries must not create orphaned usage in error-status subtrees.** ## Condition of Validity The reconciliation rule holds only when three conditions are jointly true: 1. Each model call emits exactly one span with `gen_ai.usage.*` set, and that span's `status.code` reflects the *model call's* outcome—not the enclosing tool attempt's. A chat span that succeeded must not be marked ERROR because its child tool timed out. 2. Retries carry a stable correlation attribute (`gen_ai.tool.call.id` or equivalent) shared across attempts, so a consumer can collapse attempts without collapsing turns. 3. Re-parenting is *explicit*: when the runtime starts a new agent turn to re-plan, it must set `gen_ai.agent.turn.index` (or a parent-link attribute) so the two subtrees are joinable. If the runtime marks the Turn A chat span ERROR (because the overall turn failed), condition 1 breaks and usage is silently dropped from success-only aggregations. If no correlation id exists, condition 2 breaks and dedup is impossible. If re-parenting is implicit, condition 3 breaks and the trace is a forest, not a tree. ## Decision Boundary The instrumentation layer must choose, per retry, between two behaviors and encode the choice in span topology: - **Same-parent retry** (tool re-issued within the same agent turn, no re-plan): emit a new `execute_tool` span as a sibling under the *same* agent span, both sharing `gen_ai.tool.call.id`. Usage lives on the parent chat span only; the tool spans carry no `gen_ai.usage.*`. Aggregation sums chat spans, dedups tool spans by call id. - **Re-parented retry** (re-plan created a new turn): emit the new chat span as a *sibling* of the original under a shared `gen_ai.conversation.id`, both stamped with `gen_ai.agent.turn.index` and a shared `gen_ai.task.id`. The original chat span's status must stay `OK` (the model call succeeded even though the tool failed). Aggregation sums *all* chat spans under the task id, ignoring status. The boundary is crossed the moment a runtime retries a tool by re-entering the planner without stamping `gen_ai.task.id`. At that point the two chat spans are indistinguishable siblings and any status-filtered query loses one. ## Operational Effect With the invariant enforced, the budget ceiling query becomes `sum(gen_ai.usage.input_tokens + gen_ai.usage.output_tokens) group by gen_ai.task.id where gen_ai.operation.name=chat`—status-agnostic, retry-agnostic, and stable across re-parenting. Without it, the observed system under-reported spend by 1.9× and let a task exceed its ceiling undetected until a downstream batch job reconciled raw spans against the billing export three hours later. The guardrail is a span-topology validation at emit time: reject any chat span whose parent chain lacks a `gen_ai.task.id`, and reject any tool span carrying `gen_ai.usage.*` (tool spans must never own model tokens). ```python from dataclasses import dataclass, field from typing import Optional class SpanAccountingError(RuntimeError): pass @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation: str # "chat" | "execute_tool" status: str # "OK" | "ERROR" task_id: Optional[str] = None tool_call_id: Optional[str] = None input_tokens: int = 0 output_tokens: int = 0 def validate_span(span: GenAISpan, known_tasks: set[str]) -> None: if span.operation == "chat": if span.task_id is None or span.task_id not in known_tasks: raise SpanAccountingError( f"chat span {span.span_id} lacks a joinable gen_ai.task.id; " "re-parented retries will orphan usage" ) if span.input_tokens < 0 or span.output_tokens < 0: raise SpanAccountingError(f"negative usage on {span.span_id}") elif span.operation == "execute_tool": if span.input_tokens or span.output_tokens: raise SpanAccountingError( f"tool span {span.span_id} owns model tokens; " "usage must live on the issuing chat span" ) if span.tool_call_id is None: raise SpanAccountingError( f"tool span {span.span_id} missing gen_ai.tool.call.id; " "retry dedup impossible" ) else: raise SpanAccountingError(f"unknown operation {span.operation}") def reconcile_task_usage(spans: list[GenAISpan], task_id: str) -> int: total = 0 for s in spans: if s.operation == "chat" and s.task_id == task_id: # status-agnostic: a failed tool must not drop the chat span's usage total += s.input_tokens + s.output_tokens if total == 0: raise SpanAccountingError(f"no chat usage found for task {task_id}") return total ```