# Why does an instance emit a valid gen_ai.operation.name span with gen_ai.usage.* attributes that silently under-bill a retried tool-call fan-out? **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans per model invocation and per tool execution, where cost/usage is reconstructed downstream by summing `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on spans bearing `gen_ai.operation.name`. Does not apply to runtimes that meter at the HTTP transport layer or that bill from provider-side invoices independent of span emission. ## Core Distinction The GenAI semantic conventions describe *per-span* attributes: a single `chat` span carries `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and a `gen_ai.operation.name` of `chat`, `execute_tool`, `embeddings`, etc. They do **not** define a parent-level rollup attribute, a deduplication key, or a retry ordinal. The distinction that matters operationally is between **span-observability semantics** (what happened on this one call) and **cost-accounting semantics** (what should be charged and to whom). The convention is precise about the former and silent about the latter, and a naive cost pipeline that treats the sum of usage attributes over all spans as the bill is therefore *convention-compliant and wrong*. The boundary condition is the retried tool-call fan-out: one logical agent step that, under provider rate-limiting or a schema-validation retry, emits N sibling `chat` spans each with full `gen_ai.usage.*` attributes but no shared identity, so the rollup double-counts and the retry ordinal is unrecoverable from the span set. ## What Was Observed An agent executing a `plan → tool-call → observe` loop against a function-calling model. The tool call to `search_index` intermittently returned a 429 from the provider; the runtime's retry wrapper re-issued the *entire* model call (not just the tool), producing a second `chat` span. Each span was individually well-formed: - `gen_ai.operation.name = "chat"` - `gen_ai.system = "openai"` (or the vendor equivalent) - `gen_ai.request.model = "…"` - `gen_ai.usage.input_tokens = 3120`, `gen_ai.usage.output_tokens = 486` - `gen_ai.response.finish_reasons = ["tool_calls"]` - `gen_ai.tool.name = "search_index"` on the child `execute_tool` span The trace showed a clean parent `invoke_agent` span with two `chat` children, each with a `execute_tool` grandchild. Downstream, the cost aggregator summed `gen_ai.usage.input_tokens` across all `chat` spans and reported 6240 input tokens for a step that the provider billed once at 3120 (the retried attempt's tokens were *not* billed because the first call was rejected at the gateway before tokenization — or, in the worse variant, *were* billed and the aggregator is correct by accident). The two variants are indistinguishable from the span set alone, because the convention has no attribute that says "this span's usage was charged" versus "this span's usage was discarded." The failure trace: 1. Model call attempt 1 emits `chat` span S1 with full usage attributes; provider rejects at gateway (429). S1 is exported with `status.code = ERROR` but **usage attributes retained**, because the runtime populated them from the request estimate before the response arrived. 2. Retry wrapper re-issues; attempt 2 emits `chat` span S2 with the same `gen_ai.request.model` and near-identical usage, `status.code = OK`. 3. Both S1 and S2 are children of the same `invoke_agent` span. Neither carries `gen_ai.retry.ordinal`, `gen_ai.attempt`, or a stable `gen_ai.conversation.id`-derived dedup key — the convention defines none of these. 4. Cost aggregator sums S1 + S2. On the "gateway-rejected" path this over-bills by 100%; on the "billed-then-retried" path it is correct. The aggregator cannot tell which path it is on. The subtlety: S1's usage attributes are *estimates* (pre-flight token count), not provider-reported counts, because the response never arrived. The convention does not distinguish estimated from reported usage. `gen_ai.usage.input_tokens` on an error span is a guess wearing the same attribute name as a measured value. ## Condition of Validity The "sum usage over spans" rollup is valid only when *all three* hold: 1. **No retried model calls within a logical agent step** — i.e., the runtime either does not retry `chat` calls, or retries at a layer that does not emit a new `chat` span. 2. **Usage attributes are populated only from provider responses**, never from pre-flight estimates, so an error span carries no usage. 3. **No fan-out**: the model is not called concurrently for the same logical step (e.g., self-consistency sampling, best-of-N, or parallel tool-call resolution that re-invokes the model). In any agent that retries on 429/503, samples N times, or fans out tool calls with per-call model re-invocation, at least one condition fails. The invariant that must be *added* on top of the convention is: **every `chat` span that contributes to cost must carry a dedup key and a provenance flag distinguishing measured from estimated usage.** The convention supplies the attribute namespace but not the key; the runtime must mint it. ## Decision Boundary The boundary is not "should I retry" — retries are mandatory for reliability. The boundary is **where the usage attribute is written and whether the span is exportable as a cost-bearing span**: - If the runtime writes `gen_ai.usage.*` at span *start* from an estimate, then an error span is a cost span and the aggregator must filter `status.code = OK` *and* the runtime must not retry within the same logical step without a dedup key. This is the fragile branch. - If the runtime writes `gen_ai.usage.*` only at span *end* from the provider response, then error spans carry no usage and the sum is correct *unless* the provider bills for the rejected call (rate-limit rejections usually don't; malformed-response rejections sometimes do). - The safe branch: write usage at end from the response, tag every span with a runtime-minted `agent.step.id` and `agent.attempt.ordinal`, and have the aggregator take *max* usage per `(agent.step.id)` rather than *sum* — because at most one attempt per step is actually billed. The decision boundary is therefore: **sum is correct only across distinct `agent.step.id`; within a step, take the billed attempt, not the sum of attempts.** The convention does not encode `agent.step.id`; it must be added as a non-standard attribute, and the aggregator must be taught to prefer it over raw span summation. ## Operational Effect Consequences of getting this wrong, in order of severity: 1. **Silent over-billing of 2–N× on retry-heavy agents.** Rate-limited agents (the ones most likely to retry) are exactly the ones whose cost dashboards inflate. The inflation correlates with provider instability, so it looks like "costs went up when the provider got flaky" — which is half-true and misleads capacity planning. 2. **Estimated-usage contamination.** Error spans carrying pre-flight estimates inflate input-token counts without any provider charge. Because the attribute name is identical to measured usage, no downstream filter can separate them. 3. **Fan-out under-attribution.** In best-of-N sampling, N `chat` spans per step are all genuinely billed, but they share no `agent.step.id`, so per-step cost is unrecoverable and per-decision cost (the thing you actually want to optimize) is invisible. 4. **Replay divergence in audit.** A verification agent replaying the trace to reconstruct spend will sum spans and disagree with the provider invoice; the discrepancy is not a bug in either — it is the convention's silence about retry semantics surfacing at audit time. The guardrail is a runtime-layer cost-span contract: mint `agent.step.id` (stable across retries), `agent.attempt.ordinal` (monotonic within step), and `gen_ai.usage.source ∈ {estimated, reported}`; write usage at end from the response; and make the aggregator group by `agent.step.id` and select the `reported` attempt with the highest ordinal, falling back to sum only when `agent.step.id` is absent. This is a strict superset of the GenAI conventions, not a violation of them — the conventions define the leaf attributes; the runtime must define the tree. ```python from dataclasses import dataclass, field from typing import Optional class CostRollupInvariantError(RuntimeError): """Raised when a span set cannot be rolled up to a defensible cost figure.""" @dataclass class GenAiSpan: span_id: str operation_name: str # gen_ai.operation.name status_code: str # "OK" | "ERROR" input_tokens: Optional[int] = None # gen_ai.usage.input_tokens output_tokens: Optional[int] = None # gen_ai.usage.output_tokens usage_source: Optional[str] = None # "estimated" | "reported" | None agent_step_id: Optional[str] = None # runtime-minted, NOT in the convention attempt_ordinal: Optional[int] = None # runtime-minted, NOT in the convention def rollup_step_cost(spans: list[GenAiSpan]) -> dict[str, tuple[int, int]]: """ Group chat spans by agent.step.id and select the billed attempt per step. Refuses to sum across attempts, and refuses estimated-usage spans as billable. """ chat_spans = [s for s in spans if s.operation_name == "chat"] if not chat_spans: return {} # Invariant 1: every cost-bearing span must declare usage provenance. unprovenanced = [s for s in chat_spans if s.usage_source is None] if unprovenanced: raise CostRollupInvariantError( f"{len(unprovenanced)} chat span(s) lack gen_ai.usage.source; " "cannot distinguish estimated from reported usage. " f"span_ids={[s.span_id for s in unprovenanced]}" ) # Invariant 2: within a step, attempts must be ordered; otherwise dedup is undefined. by_step: dict[str, list[GenAiSpan]] = {} for s in chat_spans: key = s.agent_step_id or f"__unkeyed__:{s.span_id}" by_step.setdefault(key, []).append(s) result: dict[str, tuple[int, int]] = {} for step_id, attempts in by_step.items(): if len(attempts) > 1 and any(a.attempt_ordinal is None for a in attempts): raise CostRollupInvariantError( f"step {step_id!r} has {len(attempts)} attempts but at least one " "lacks agent.attempt.ordinal; retry dedup is undefined. " "Summing would double-count." ) billed = [a for a in attempts if a.usage_source == "reported"] if not billed: # All attempts were estimated (e.g., every attempt errored pre-response). # Zero billable usage is the defensible answer; do not guess. result[step_id] = (0, 0) continue chosen = max(billed, key=lambda a: a.attempt_ordinal or 0) result[step_id] = (chosen.input_tokens or 0, chosen.output_tokens or 0) return result def reconcile_against_invoice(rolled: dict[str, tuple[int, int]], invoice_in: int) -> None: total_in = sum(v[0] for v in rolled.values()) if total_in != invoice_in: raise CostRollupInvariantError( f"span-derived input tokens ({total_in}) disagree with provider invoice " f"({invoice_in}); likely a retry path billed by the provider but not " "tagged with agent.attempt.ordinal, or a fan-out step missing agent.step.id." ) ```