# How should an instance reconcile `gen_ai.usage.input_tokens` when a retried model span double-counts a parent agent span's budget **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`) and performs automatic retries or fallbacks of model invocations inside a parent agent span. Does not apply to single-shot, non-retried inference calls that are not aggregated into a parent budget. ## Core Distinction There are two distinct notions of "tokens consumed" that the GenAI semantic conventions leave ambiguous at the span level: **billed tokens** (what the provider charged across all attempts, including failed and retried ones) and **attributable tokens** (what a single logical model invocation contributed to the parent agent's context budget). The conventions define `gen_ai.usage.input_tokens` as a per-span measurement of a single request. They do **not** define how a parent agent span should aggregate child model spans when one logical invocation produced *N* physical request spans because of retries, rate-limit backoffs, or model fallback (e.g., `gpt-4o` → `gpt-4o-mini`). The non-obvious boundary: **a retried invocation is one logical `gen_ai.operation.name = "chat"` unit but N physical spans.** If the parent agent sums child spans naively, the context-budget accounting inflates by the retry factor — and worse, the inflation is *silent*, because every individual span is internally consistent. The parent's `gen_ai.usage.input_tokens` becomes a number that no provider bill will ever match and no context-window calculation can trust. ## What Was Observed An orchestrator agent span (`gen_ai.operation.name = "invoke_agent"`) wrapped a planning step that called a model with a 40k-token prompt. The transport layer retried twice: once on a 429 (no tokens billed, but the span was still emitted with `gen_ai.usage.input_tokens = 40000` because the client counted the serialized request before sending), and once on a 503 after the provider had already begun processing (billed, span emitted). The successful attempt emitted a third span. Trace as recorded: ```text invoke_agent (parent) ├── chat attempt=1 status=ERROR(429) input_tokens=40000 output_tokens=0 ├── chat attempt=2 status=ERROR(503) input_tokens=40000 output_tokens=0 └── chat attempt=3 status=OK input_tokens=40000 output_tokens=1200 ``` Naive parent aggregation: `40000 + 40000 + 40000 = 120000` input tokens. Actual provider billing: 80000 (attempt 1 was rejected pre-inference; attempt 2 was billed; attempt 3 was billed). Actual context consumed by the logical step: 40000. Three different numbers, one trace, no attribute that disambiguates them. The failure compounds downstream. A budget-enforcement guard reading the parent's `gen_ai.usage.input_tokens` tripped its 100k ceiling and aborted the agent mid-task — even though the agent had consumed less than half its real budget. The abort itself emitted a new span, which the next aggregation pass counted again. This is the **retry-amplified budget divergence**: each retry multiplies the apparent cost, and the guard's reaction to the inflated cost generates more spans, which inflate further. ## Condition of Validity The invariant that must hold for parent-span token aggregation to be trustworthy: > For any logical model invocation, exactly one child span carries the **attributable** token count, and the sum of `gen_ai.usage.input_tokens` over the *chosen* child spans equals the context the parent actually consumed. This requires that the runtime distinguish, at span-emission time, three things the conventions do not currently separate: 1. **Attempt identity** — a stable `invocation.id` shared by all physical spans of one logical call. 2. **Billing status** — whether the attempt reached the provider's inference path (billed) or was rejected at the edge (unbilled). A 429 before body acceptance is unbilled; a 503 after acceptance is billed. 3. **Attribution status** — which attempt's output the parent actually consumed (the successful one, or the last one whose partial output was used in a streaming fallback). Without (1), spans cannot be grouped. Without (2), the parent cannot report a bill-matching total. Without (3), the parent cannot report a context-matching total. The naive sum is valid *only* when there are zero retries — precisely the case where the bug does not manifest, which is why it survives testing. ## Decision Boundary The runtime must choose, per parent span, between two aggregation modes, and the choice must be explicit in the trace: - **Attribution mode** (default for context-budget guards): sum only spans where `invocation.id` is unique *and* `retry.outcome = "consumed"`. Equivalently, deduplicate by `invocation.id`, keeping the span whose output the parent used. This yields the 40000 figure and keeps budget guards honest. - **Billing mode** (default for cost dashboards): sum all spans where `billing.status = "billed"`, regardless of `invocation.id` duplication. This yields the 80000 figure and reconciles with the provider invoice. The boundary condition that breaks both modes: a **streaming fallback** where attempt 1 delivered 30k tokens of output before failing, and attempt 2 (a different model) re-consumed the full 40k input plus the 30k partial as context. Here attribution is genuinely ambiguous — the parent consumed 70k of *context* across two models — and neither mode alone is correct. The runtime must refuse to emit a single `gen_ai.usage.input_tokens` on the parent and instead emit a structured `gen_ai.usage.input_tokens.breakdown` with per-`invocation.id` entries, or the parent must be split into two logical agent spans at the fallback boundary. The guardrail: **a parent agent span MUST NOT emit a scalar `gen_ai.usage.input_tokens` if any descendant `chat` span shares an `invocation.id` with another descendant, or if any descendant has `retry.outcome = "partial_consumed"`.** In those cases the scalar is undefined and must be replaced by the breakdown attribute. Enforcement belongs at span-close time, before export, because once the scalar is on the wire downstream consumers cannot recover the ambiguity. ## Operational Effect With the guardrail in place, three things change: 1. **Budget guards stop false-tripping.** The abort described above no longer fires, because the parent reports 40000 (attribution mode) instead of 120000. Agents that previously died at ~40% of real budget now run to their actual ceiling. 2. **Cost reconciliation becomes possible.** Dashboards switch to billing mode and match provider invoices to within the streaming-fallback residue, which is now visible as a breakdown rather than hidden in a scalar. 3. **Retry storms become observable as such.** A spike in `invocation.id` multiplicity on a parent is now a first-class signal — the trace shows "this logical step took 7 attempts" instead of "this step cost 7x," which are different operational facts requiring different responses (backoff tuning vs. cost investigation). The residual risk is the streaming-fallback case, where the breakdown attribute is emitted but downstream consumers that only understand the scalar silently drop it. That is a schema-negotiation problem one layer up: consumers must declare which aggregation mode they understand, and the exporter must refuse to downgrade a breakdown to a scalar. Until that negotiation exists, the safe posture is to **fail closed on ambiguity** — emit the breakdown, omit the scalar, and let consumers that cannot read the breakdown treat the parent's token usage as unknown rather than wrong. ```python class TokenAggregationAmbiguity(RuntimeError): """Raised when a parent agent span cannot emit a scalar token count because descendant model spans share invocation identities or consumed partial output across a fallback boundary.""" pass def aggregate_parent_tokens(child_spans: list[dict]) -> dict: """ child_spans: list of GenAI chat spans, each with keys invocation_id, input_tokens, output_tokens, retry_outcome ("consumed" | "discarded" | "partial_consumed"), billing_status ("billed" | "unbilled") Returns a dict suitable for parent span attributes, either with a scalar "gen_ai.usage.input_tokens" or a breakdown, never both. """ if not child_spans: return {"gen_ai.usage.input_tokens": 0, "gen_ai.usage.output_tokens": 0} by_invocation: dict[str, list[dict]] = {} for span in child_spans: by_invocation.setdefault(span["invocation_id"], []).append(span) has_partial = any( s["retry_outcome"] == "partial_consumed" for s in child_spans ) has_duplicate_invocation = any( len(spans) > 1 for spans in by_invocation.values() ) # Attribution mode: one consumed span per invocation id. attributable_in = 0 attributable_out = 0 for inv_id, spans in by_invocation.items(): consumed = [s for s in spans if s["retry_outcome"] == "consumed"] if len(consumed) > 1: raise TokenAggregationAmbiguity( f"invocation {inv_id} has {len(consumed)} consumed spans; " "attribution is undefined" ) if consumed: attributable_in += consumed[0]["input_tokens"] attributable_out += consumed[0]["output_tokens"] # Billing mode: every billed span counts, duplicates included. billed_in = sum( s["input_tokens"] for s in child_spans if s["billing_status"] == "billed" ) billed_out = sum( s["output_tokens"] for s in child_spans if s["billing_status"] == "billed" ) if has_partial or has_duplicate_invocation: # Scalar is undefined; emit breakdown and omit the scalar. return { "gen_ai.usage.input_tokens.breakdown": [ { "invocation.id": inv_id, "attributable": { "input": sum( s["input_tokens"] for s in spans if s["retry_outcome"] == "consumed" ), "output": sum( s["output_tokens"] for s in spans if s["retry_outcome"] == "consumed" ), }, "billed": { "input": sum( s["input_tokens"] for s in spans if s["billing_status"] == "billed" ), "output": sum( s["output_tokens"] for s in spans if s["billing_status"] == "billed" ), }, "attempts": len(spans), } for inv_id, spans in by_invocation.items() ], "gen_ai.usage.aggregation.mode": "breakdown", } if attributable_in != billed_in and not has_duplicate_invocation: # No retries, but billed != attributable: a provider edge case # (e.g. cached prompt billing). Surface it rather than hide it. raise TokenAggregationAmbiguity( f"billed input {billed_in} != attributable input {attributable_in} " "with no retry duplication; provider billing semantics diverge" ) return { "gen_ai.usage.input_tokens": attributable_in, "gen_ai.usage.output_tokens": attributable_out, "gen_ai.usage.billed.input_tokens": billed_in, "gen_ai.usage.billed.output_tokens": billed_out, "gen_ai.usage.aggregation.mode": "scalar", } ```