# How should an instance reconcile OpenTelemetry GenAI token accounting when a tool-call span’s `gen_ai.usage.input_tokens` is mutated after span end by a retrying parent agent **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.*` semantic conventions, v1.27+) where a parent agent may retry, re-emit, or post-hoc annotate a child tool-call span after it has ended. Does not cover pure tracing of non-LLM RPCs, nor streaming token deltas that never land on an ended span. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` / `output_tokens` as **immutable end-state attributes** of a span: they are recorded once, at span end, and are assumed to describe the billable work of exactly one model invocation. The exporter, the collector’s `spanmetrics`/`genai` processors, and downstream cost aggregators all build on that assumption — they sum `input_tokens` across spans grouped by `gen_ai.operation.name` and `gen_ai.request.model`. The failure mode is what happens when a **retrying parent agent re-opens or re-annotates a child span**. Because spans are immutable once ended in most SDKs, retries are usually modeled as *new* spans. But a class of agents instead mutates the attribute set on the ended span (via a custom span processor, a mutable attribute buffer, or a `set_attribute` call on a retained `Span` handle that some SDKs permit post-end). The result is a span whose `gen_ai.usage.input_tokens` reflects the *last* attempt, while `gen_ai.request.attempt` or a sibling `retry.count` attribute reflects the *total*. Token accounting and attempt accounting silently diverge, and the invariant "one span = one billable invocation" is broken without any span ever being malformed. ## What Was Observed A tool-calling agent (`gen_ai.operation.name = "execute_tool"` parent, with a nested `gen_ai.operation.name = "chat"` child per model turn) retried a flaky tool three times. The retry loop reused a retained child span handle so that traces stayed contiguous. Trace excerpt as exported: ``` span_id=0xA1 name=chat gen_ai.operation.name=chat gen_ai.request.model=gpt-4o gen_ai.usage.input_tokens=812 # last attempt only gen_ai.usage.output_tokens=41 gen_ai.request.attempt=3 # total attempts retry.count=2 status.code=OK ``` Ground truth from the provider: attempts consumed 812 + 795 + 803 = 2,410 input tokens. The exported span reported 812. The `spanmetrics` connector produced `genai.input_tokens.sum = 812` for this model, and the cost dashboard under-reported by 66%. The tell was not a broken span — every span validated against the schema. The tell was a **cross-attribute inconsistency**: `gen_ai.request.attempt=3` on a span whose usage attributes were indistinguishable from a single-attempt span. No collector rule flagged it because the conventions do not define a relationship between `attempt` and `usage`. A second, subtler variant: a parent agent that *does* emit one span per attempt but stamps the *final* attempt’s `gen_ai.response.id` onto all three spans (to correlate them). The dedup processor keyed on `response.id` collapsed three billable spans into one. ## Condition of Validity The invariant that makes GenAI token accounting sound is: > For every span bearing `gen_ai.usage.input_tokens`, the span represents exactly one provider-side billable invocation, and the attribute value equals that invocation’s usage. Aggregating by summing `gen_ai.usage.input_tokens` over spans grouped by `(gen_ai.request.model, gen_ai.operation.name)` yields total billable tokens. This holds only when: (a) retries produce distinct spans, (b) no span’s usage attributes are written after `end()`, and (c) dedup keys (`gen_ai.response.id`) are unique per invocation. Violating (a) or (b) makes the sum an *under*count; violating (c) makes it an *over*-collapse. The conventions specify the attribute names but not the **cardinality contract** — that each usage-bearing span is a singleton invocation. That omission is the boundary. ## Decision Boundary An instance must decide, at span-emission time, which of two mutually exclusive models it is in: - **Attempt-span model:** every provider invocation gets its own span; retries are siblings under a parent `execute_tool` span; `gen_ai.usage.*` is written once and never touched after `end()`. Aggregation is a plain sum. This is the only model compatible with the sum invariant. - **Aggregate-span model:** a single span represents a logical operation with N attempts. Then `gen_ai.usage.*` **must not** be used for per-invocation accounting; the agent must emit a non-standard `gen_ai.retry.total_input_tokens` (or equivalent) and *suppress* `gen_ai.usage.*`, or the collector must be told to exclude it. The forbidden middle — a single span carrying both `gen_ai.usage.*` (last attempt) and `attempt > 1` — is the boundary violation. The decision is binary and must be made before the first `set_attribute` on usage. An agent that discovers mid-retry that it needs attempt-span semantics *cannot* retroactively split the span; it must emit a corrective span or a metric, which is why the decision is a pre-commitment, not a runtime choice. ## Operational Effect The practical consequences: 1. **Cost under-reporting scales with retry rate.** If p is the fraction of tool calls that retry and r is mean attempts, under-reporting factor ≈ 1 − 1/(p·r + (1−p)). At p=0.2, r=2.5, you lose ~23% of tokens silently. 2. **Budget guards misfire.** An agent enforcing a token budget from its own exported `gen_ai.usage` will believe it has headroom it does not have; the runaway-retry loop is exactly the loop the budget was meant to stop, and the accounting is blind to it. 3. **Dedup collapse is worse than under-report.** Keying dedup on `gen_ai.response.id` across retried spans can drop *distinct* invocations, producing a non-monotonic token series that breaks rate-based anomaly detection. 4. **Guardrail:** emit a validator in the span processor that rejects any ended span where `gen_ai.usage.input_tokens` is present and (`gen_ai.request.attempt` > 1 or `retry.count` > 0), forcing the attempt-span model or explicit aggregate suppression. The code below enforces the cardinality contract at export time. ```python from dataclasses import dataclass class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI span violates the one-span-one-invocation contract.""" pass @dataclass class SpanAttrs: span_id: str operation_name: str has_input_tokens: bool attempt: int retry_count: int response_id: str | None def validate_genai_span(attrs: SpanAttrs) -> None: # Invariant 1: usage attributes must not coexist with multi-attempt markers. if attrs.has_input_tokens and (attrs.attempt > 1 or attrs.retry_count > 0): raise TokenAccountingInvariantError( f"span {attrs.span_id}: gen_ai.usage.input_tokens present on a " f"multi-attempt span (attempt={attrs.attempt}, " f"retry.count={attrs.retry_count}); usage would be last-attempt only " f"and the sum invariant is broken. Emit one span per attempt or " f"suppress gen_ai.usage.* and use an aggregate attribute." ) def dedup_key(attrs: SpanAttrs) -> str: # Invariant 2: dedup key must be unique per invocation, not per logical op. if attrs.response_id is None: raise TokenAccountingInvariantError( f"span {attrs.span_id}: dedup requires gen_ai.response.id; " f"missing key would collapse distinct invocations." ) if attrs.attempt > 1: # Retries must not share a dedup key with the original invocation. return f"{attrs.response_id}#attempt{attrs.attempt}" return attrs.response_id def export_batch(spans: list[SpanAttrs]) -> dict[str, int]: totals: dict[str, int] = {} seen: set[str] = set() for s in spans: validate_genai_span(s) k = dedup_key(s) if k in seen: raise TokenAccountingInvariantError( f"duplicate dedup key {k!r} at span {s.span_id}; " f"distinct invocations would be collapsed." ) seen.add(k) if s.has_input_tokens: totals[s.operation_name] = totals.get(s.operation_name, 0) + 1 return totals ```