# What happens when an instance emits tool-call spans with attributes that satisfy the OTel GenAI semantic conventions individually but violate span-tree cardinality invariants across a retry chain **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) for tool invocations and that retry, replay, or re-enter tool calls within a single logical agent turn. Does not apply to single-shot inference spans with no tool loop, nor to backends that aggregate cost purely from billing exports rather than span attributes. ## Core Distinction The GenAI semantic conventions define *per-span* attribute contracts: a span with `gen_ai.operation.name = "execute_tool"` should carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, and token/cost attributes where applicable. They do **not** define a *tree-level* invariant over how many such spans may exist per logical agent turn, nor how token attributes compose when a tool call is retried. The failure boundary lives precisely in that gap: every span is locally valid and schema-conformant, yet the *aggregate* over the span tree double-counts tokens and mis-attributes tool latency because the retry relationship is invisible to the collector. This is not a schema-validation failure. A strict OTel validator passes every span. The corruption is emergent at the aggregation layer, where cost normalization and tool-success-rate computation consume the tree as if it were a DAG of unique operations. ## What Was Observed An agent executing a `search_documents` tool hit a transient 503 on the first attempt, retried with identical arguments, and succeeded on the second. The runtime emitted: - Span A: `execute_tool`, `gen_ai.tool.name=search_documents`, `gen_ai.tool.call.id=call_7f3a`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=0`, status `ERROR`, exception event `503`. - Span B: `execute_tool`, `gen_ai.tool.name=search_documents`, `gen_ai.tool.call.id=call_7f3a` (the runtime reused the logical call ID across the retry), `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=0`, status `OK`. Both spans are children of the same `invoke_agent` span. The collector's cost normalizer summed `gen_ai.usage.input_tokens` across all `execute_tool` spans under the agent span and reported **3680 input tokens** for a turn that actually consumed 1840 tool-side tokens (the failed attempt never reached the model's tool-result ingestion). Simultaneously, the tool-success-rate dashboard, which counts `execute_tool` spans by status, reported a **50% failure rate** for a tool that failed once and succeeded once — arithmetically defensible per-span, operationally wrong per-call. The inverse pathology appeared in a different deployment: a runtime that *did* mint fresh `gen_ai.tool.call.id` values per retry caused the cost normalizer's dedup-by-call-id logic to treat each retry as a distinct billable tool invocation, inflating tool-call counts by the retry factor and, in one case, exceeding the per-turn token budget guard because the guard read the inflated aggregate. So the invariant violated is: **for a given `(agent_span_id, gen_ai.tool.call.id)` pair, the summed `gen_ai.usage.*` attributes must equal the actual resource consumption of the logical call, and the call must be counted exactly once in success-rate denominators.** Neither the reused-call-id nor the fresh-call-id strategy satisfies both halves. The conventions are silent on which to pick, and each choice breaks a different downstream consumer. ## Condition of Validity The boundary is only reachable when all of the following hold: 1. The agent runtime performs in-turn retries (or replay/hedged execution) of tool calls rather than surfacing the failure to the model as a tool result. 2. Token usage is attributed at the `execute_tool` span level rather than exclusively at the parent `invoke_agent` / `chat` span. When usage lives only on the parent inference span, retries of the tool span do not perturb the token aggregate — the failure collapses. 3. A downstream consumer aggregates across the span tree by `gen_ai.tool.call.id` (dedup) or by span count (success rate) without a retry-discriminating attribute. Remove any one condition and the double-count or the miscount disappears. This is why the bug survives code review: the runtime author sees conformant spans, the dashboard author sees conformant spans, and the interaction is only observable in the joined aggregate. ## Decision Boundary The guardrail is a **retry-discriminating attribute plus an aggregation contract**, not a schema change. Concretely: - Emit `gen_ai.tool.call.id` as the *logical* call identity (stable across retries) and add a non-standard-but-namespaced `agent.retry.attempt` integer (0-indexed) on each attempt span. The logical ID preserves call identity; the attempt ordinal makes retries explicit. - Cost normalization MUST sum `gen_ai.usage.*` over **attempt 0 only** for tool-side token accounting when the runtime attributes tool tokens per attempt, OR sum over all attempts and treat the logical call's consumption as the sum — but the choice must be declared and enforced by the consumer, not left to whichever attribute happens to be present. - Success-rate computation MUST count logical calls (`count(distinct gen_ai.tool.call.id)`), classifying a call as failed only if its **terminal attempt** (highest `agent.retry.attempt`) has `ERROR` status. Intermediate `ERROR` attempts are retry signal, not failure signal. - The per-turn token budget guard MUST read the parent `invoke_agent` span's usage, never the summed child tool spans, because child sums are retry-sensitive. The boundary decision is: *does the consumer treat the span tree as a set of unique operations or as a log of attempts?* The GenAI conventions permit both readings; the runtime must disambiguate via the attempt attribute before any aggregator is allowed to run. ## Operational Effect Without the guardrail, three coupled failures propagate: cost dashboards over-report tool tokens by the retry factor (silent budget drift), success-rate SLOs under-report reliability (false alerting on flaky-but-recovering tools), and any agent that reads its own telemetry to self-tune retry aggressiveness enters a feedback loop — it sees inflated failure rates, retries more, inflates further. The attempt-ordinal attribute severs all three by making the retry relationship first-class in the span tree, so aggregation can be defined on logical calls rather than on physical spans. The invariant to encode in the collector and in any agent that introspects its own traces: **a logical tool call is one unit of cost and one unit of success, regardless of how many spans it emitted.** ```python from dataclasses import dataclass class ToolSpanCardinalityError(RuntimeError): """Raised when tool-call spans under an agent turn violate the logical-call / attempt-ordinal invariant required for correct token and success-rate aggregation.""" @dataclass(frozen=True) class ToolSpan: agent_span_id: str tool_call_id: str # logical call identity, stable across retries attempt: int | None # agent.retry.attempt; None == attribute missing status: str # "OK" | "ERROR" input_tokens: int output_tokens: int def aggregate_turn(spans: list[ToolSpan]) -> dict: if not spans: return {"cost_tokens": 0, "logical_calls": 0, "failed_calls": 0} by_call: dict[str, list[ToolSpan]] = {} for s in spans: if s.attempt is None: raise ToolSpanCardinalityError( f"tool span for call {s.tool_call_id!r} on agent " f"{s.agent_span_id!r} is missing agent.retry.attempt; " "aggregation cannot distinguish retries from distinct calls" ) by_call.setdefault(s.tool_call_id, []).append(s) cost_tokens = 0 failed_calls = 0 for call_id, attempts in by_call.items(): ordinals = sorted(a.attempt for a in attempts) if ordinals != list(range(len(attempts))): raise ToolSpanCardinalityError( f"call {call_id!r} has non-contiguous attempt ordinals " f"{ordinals}; expected 0..{len(attempts) - 1}. " "A gap means a span was dropped and cost is under-counted." ) # Cost: sum attempt-0 only per declared accounting contract. base = next(a for a in attempts if a.attempt == 0) cost_tokens += base.input_tokens + base.output_tokens # Success: terminal attempt decides the logical call outcome. terminal = max(attempts, key=lambda a: a.attempt) if terminal.status != "OK": failed_calls += 1 return { "cost_tokens": cost_tokens, "logical_calls": len(by_call), "failed_calls": failed_calls, } ```