# Which invariants prevent GenAI span attribute collapse when an agent's tool-call tree is re-emitted across retries **Date of Record:** 2026 November 28 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical invocation may be retried, re-planned, or replayed by a supervisor, and where downstream token accounting is derived by summing span attributes. Does not apply to single-shot, non-retried inference calls or to traces where no retry/replay layer exists. ## Core Distinction The failure is not that spans go missing. It is that a *logical* agent invocation and a *physical* span emission decouple under retry. When an agent's execution loop retries a tool call or re-plans a step, the OpenTelemetry SDK re-emits a new span with the same `gen_ai.operation.name` and often the same logical identity (same `gen_ai.tool.name`, same parent `gen_ai.conversation.id`), but with fresh `SpanId`, fresh `StartTimeUnixNano`, and — critically — a fresh set of `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` values that represent the *whole* re-attempted call, not the delta. The distinction that matters: **span-level attributes are per-emission facts, but cost and token budgets are per-logical-invocation facts.** The GenAI conventions define attribute semantics at the span level. Nothing in the convention defines a correlation key that lets a collector deduplicate re-emissions of the same logical step. So any consumer that aggregates by summing `gen_ai.usage.*` across spans will double-count every retried step, and the error compounds multiplicatively with retry depth. ## What Was Observed A three-step agent (plan → retrieve → synthesize) ran under a supervisor that retried any tool call returning a transient error up to N=3 times. The retrieve step failed twice on a rate-limit before succeeding on the third attempt. Trace shape emitted: - `invoke_agent` root span, `gen_ai.usage.input_tokens=1850`, `output_tokens=210`. - `execute_tool` child span #1 (`gen_ai.tool.name=vector_search`), attempt 1, `status=ERROR`, `input_tokens=0`, `output_tokens=0` (failed before model call). - `execute_tool` child span #2, attempt 2, `status=ERROR`, `input_tokens=0`, `output_tokens=0`. - `execute_tool` child span #3, attempt 3, `status=OK`, `input_tokens=640`, `output_tokens=95`. - `chat` child span for synthesize, `input_tokens=2100`, `output_tokens=430`. The aggregation job summed every `gen_ai.usage.input_tokens` under the root and reported 4590 input tokens. The actual billed input was 1850 (root, which already includes the retrieve and synthesize prompt assembly) — the child spans were re-reporting slices of the same prompt budget that the root already counted. Two independent errors stacked: 1. **Retry re-emission without a dedup key.** Attempt 1 and 2 produced spans indistinguishable from attempt 3 except by `SpanId` and timestamp. A downstream consumer keyed on `(conversation.id, tool.name)` saw three distinct tool invocations where there was one logical step. 2. **Parent/child token double-counting.** The `invoke_agent` root's `input_tokens` already reflected the full prompt; the child `chat` and `execute_tool` spans each re-reported their own prompt slices. Summing across the tree counted the same tokens twice. The compounding is the sharp part: with retry depth `d` and a naive tree-sum aggregator, reported input tokens ≈ `actual × (1 + d_retried) + (child_overlap × depth)`. The error is not additive noise; it scales with retry count, which scales with upstream flakiness, which is highest exactly when you most need the accounting to be right. ## Condition of Validity The invariant that must hold for tree-sum token accounting to be correct is: > **For every logical agent invocation, exactly one span in the emitted tree carries the authoritative `gen_ai.usage.*` totals for that invocation, and no other span in the tree reports tokens that are a subset of those totals.** This invariant is *not* stated in the GenAI semantic conventions, because the conventions are written for single-emission spans and do not model retry. It is a property the agent runtime must enforce, not one the SDK provides. The conventions give you `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.conversation.id`, and `error.type` — but no `gen_ai.attempt.index`, no `gen_ai.logical_step.id`, and no `gen_ai.usage.is_authoritative` marker. Without those, the tree is ambiguous. The condition of validity therefore decomposes into three enforceable sub-invariants: - **Attempt identity:** every re-emission of a logical step carries a stable `gen_ai.step.id` (or equivalent custom attribute) identical across attempts, plus a monotonically increasing `gen_ai.attempt.index`. Deduplication keys on `(step.id)` and keeps the highest `attempt.index` that succeeded, or the last attempt if all failed. - **Token authority:** exactly one span per `step.id` is marked `gen_ai.usage.authoritative=true` — the one whose usage reflects the full cost of that step. Child spans that re-report slices set `authoritative=false` and are excluded from summation. - **Failure accounting:** errored attempts with zero tokens are still emitted (for latency and error-rate, which *should* count per attempt) but must be tagged so token aggregation skips them while error aggregation includes them. The two aggregations key on different attributes — this is the part naive pipelines get wrong. ## Decision Boundary The boundary where this bites is: **retry depth > 0 AND a consumer that aggregates token usage by summing across the span tree.** Below that boundary — no retries, or a consumer that reads only the root span's usage — the ambiguity is latent and harmless. The decision is whether to enforce the invariant at emission time or at collection time: - **Emission-time enforcement** (agent runtime stamps `step.id`, `attempt.index`, `authoritative`): correct, but requires every agent framework in the fleet to cooperate. A single framework that omits `step.id` poisons the trace. - **Collection-time reconstruction** (collector infers logical steps by grouping on `(parent.span_id, gen_ai.tool.name, gen_ai.request.model)` and timestamps): works without framework cooperation, but is heuristic — two genuinely distinct calls to the same tool under the same parent within a short window are indistinguishable from a retry. This heuristic fails silently on legitimate parallel tool calls. The boundary condition: if the agent can issue the same tool concurrently under one parent (parallel fan-out), collection-time reconstruction is *unsound* and emission-time stamping is *mandatory*. If the agent is strictly sequential, collection-time grouping is sound enough to bound the error. The operational decision is to detect fan-out capability in the agent and escalate to mandatory stamping when it exists. ## Operational Effect The observable effect of missing the invariant is a token-accounting drift that is *correlated with system health*: when the upstream tool is flaky, retries spike, and reported cost inflates precisely during the incident you are trying to diagnose. Budget alarms fire on phantom spend; chargeback reports over-attribute to the flaky dependency; and capacity planning over-provisions because the reported p99 token cost is a retry artifact, not a workload fact. The guardrail that bounds it: emit `gen_ai.step.id` and `gen_ai.attempt.index` as first-class span attributes from the agent runtime, mark exactly one span per step `gen_ai.usage.authoritative=true`, and make the accounting pipeline refuse to sum non-authoritative usage. The pipeline must treat an un-stamped span in a retry-capable agent as a hard error, not a default — because the default (sum everything) is the failure. A trace that cannot prove its token authority is a trace whose cost numbers are unverified, and unverified cost numbers in an agent fleet are worse than no numbers, because they get acted on. ```python from dataclasses import dataclass, field from typing import Optional class UnauthoritativeUsageError(RuntimeError): """Raised when token aggregation encounters a span whose usage authority is ambiguous.""" @dataclass class GenAISpan: span_id: str parent_span_id: Optional[str] operation_name: str # gen_ai.operation.name step_id: Optional[str] # gen_ai.step.id (custom; required for retry-capable agents) attempt_index: Optional[int] # gen_ai.attempt.index input_tokens: int # gen_ai.usage.input_tokens output_tokens: int # gen_ai.usage.output_tokens authoritative: Optional[bool] # gen_ai.usage.authoritative status: str = "OK" def aggregate_authoritative_input_tokens(spans: list[GenAISpan], retry_capable: bool) -> int: """ Sum input tokens across a span tree, enforcing the token-authority invariant. Invariant: for each logical step, exactly one span is authoritative; only authoritative spans contribute to the sum. In retry-capable agents, a span missing step_id / attempt_index / authoritative is an accounting hazard and must not be silently summed. """ seen_steps: dict[str, GenAISpan] = {} total = 0 for span in spans: if retry_capable: if span.step_id is None or span.attempt_index is None or span.authoritative is None: raise UnauthoritativeUsageError( f"Span {span.span_id} ({span.operation_name}) in a retry-capable agent " f"is missing step_id/attempt_index/authoritative; token accounting is unverifiable." ) # Keep the highest successful attempt per logical step. prior = seen_steps.get(span.step_id) if prior is None or span.attempt_index > prior.attempt_index: seen_steps[span.step_id] = span if span.authoritative is True: total += span.input_tokens if retry_capable: for step_id, chosen in seen_steps.items(): if chosen.authoritative is not True: raise UnauthoritativeUsageError( f"Logical step {step_id} has no authoritative usage span after " f"attempt resolution (best attempt {chosen.attempt_index}, status {chosen.status})." ) return total def verify_trace(spans: list[GenAISpan], retry_capable: bool) -> int: try: return aggregate_authoritative_input_tokens(spans, retry_capable) except UnauthoritativeUsageError: raise except Exception as exc: # defensive: never let a malformed trace pass as valid raise UnauthoritativeUsageError(f"Trace verification failed: {exc}") from exc ```