# How should an instance reconcile OpenTelemetry GenAI span token accounting when a streaming tool-call span is retried after partial emission **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, where the LLM call streams tokens and the tool-call span can be retried mid-stream. Does not cover non-streaming batch inference, or telemetry emitted only at the process boundary (e.g., a single span per agent task). ## Core Distinction The distinction that matters is between **span identity** and **attempt identity**. The OpenTelemetry GenAI conventions define attributes such as `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the span that represents a model invocation, and `gen_ai.tool.name` / `gen_ai.tool.call.id` on tool-call spans. The conventions implicitly assume a one-to-one mapping between one span and one billed model invocation. A retried streaming call breaks that assumption: the same logical operation produces N attempts, each of which may have emitted a partial token prefix, and each of which consumed real tokens that the provider will bill. If the retry reuses the span (common when the span is created before the call and finalized in a `finally` block), the token counters reflect only the last attempt, or worse, are summed across attempts into a single span whose `gen_ai.usage.*` now describes something no provider ever emitted. If the retry creates a new span per attempt but the parent agent span aggregates them naively, the aggregate double-counts the input tokens that were re-sent on each attempt. Neither representation is wrong in isolation; the failure is that the span tree no longer lets a consumer answer the only question that matters downstream — *how many tokens did this logical operation cost, and how many distinct provider invocations did it consume?* ## What Was Observed A tool-calling agent loop was instrumented to emit one `gen_ai.chat` span per model call and one `gen_ai.tool` span per tool invocation. The model call used streaming; the runtime created the `gen_ai.chat` span at call start, set `gen_ai.request.model` and `gen_ai.request.max_tokens` before dispatch, and wrote `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` from the provider's terminal usage frame in a `finally` block. A retry wrapper re-issued the request on `httpx.ReadTimeout` after 8 seconds. The trace showed the following. Attempt 1 streamed 340 output tokens before the socket closed; the provider's usage frame never arrived, so the `finally` block wrote `output_tokens=0` and `input_tokens=0` (the runtime read usage only from the terminal frame). Attempt 2 re-sent the full prompt (2,100 input tokens) plus the 340 already-generated tokens were *not* re-sent — the retry restarted from the original prompt — and completed with `input_tokens=2100`, `output_tokens=612`. The final span recorded `gen_ai.usage.output_tokens=612`, `gen_ai.usage.input_tokens=2100`. The provider's invoice for the logical operation was 2,440 input tokens (attempt 1's 2,100 plus attempt 2's 2,100, minus whatever the provider's cache credited) and 952 output tokens (340 + 612). The span under-reported by roughly one full attempt on both counters, and there was no attribute anywhere in the trace indicating that a retry had occurred. A cost dashboard built on `sum(gen_ai.usage.*)` was systematically low on exactly the calls that were most expensive — the ones that timed out and retried. A second, subtler observation: when the retry wrapper *did* create a child span per attempt (a change made to fix the above), the parent `gen_ai.chat` span's `gen_ai.usage.*` was computed as the sum of children. That sum included the input tokens of both attempts. Downstream consumers that treated `gen_ai.usage.input_tokens` on the parent as "the prompt size" then concluded the prompt was 4,200 tokens and triggered a context-budget alarm that fired on every retried call, because the alarm compared the parent's input token count against the model's context limit. ## Condition of Validity The invariant that must hold for the span tree to be interpretable is: > For every `gen_ai.chat` span S, `S.gen_ai.usage.input_tokens` equals the number of input tokens billed for the *single provider invocation* that S represents, and the set of spans with the same `gen_ai.conversation.id` (or equivalent logical-operation key) that share a retry group must be enumerable from the trace alone, without consulting the application's retry logs. This holds only when (a) each provider invocation has exactly one span, (b) the span is finalized with the usage frame from *that* invocation, and (c) retries are represented as sibling spans under a common parent or linked via `SpanLink`, with the parent carrying an explicit aggregate that is *not* conflated with any single invocation's counters. The conventions as written give you the attribute names but not the retry topology; the topology is the part that fails silently. The condition is violated whenever a retry reuses a span, or whenever an aggregate span uses the same attribute names as a leaf span. Both are natural implementations — the first because it minimizes span count, the second because it makes the dashboard query simple — and both produce a trace that is internally consistent (every span has all required attributes) yet semantically wrong. ## Decision Boundary The decision boundary is whether the token counters on a span are **descriptive of one invocation** or **aggregative over many**. The GenAI conventions do not distinguish these, so the runtime must choose and must make the choice legible. The rule that survived operational contact: - A span that carries `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` MUST describe exactly one provider invocation. It MUST NOT be the parent of retry attempts. - A retry group is represented by a parent span with a distinct, non-conflatable attribute set — e.g., `gen_ai.retry.attempt_count`, `gen_ai.retry.aggregate.input_tokens`, `gen_ai.retry.aggregate.output_tokens` — and MUST NOT populate `gen_ai.usage.*` on itself. - Partial attempts (streamed some output, no terminal usage frame) MUST emit a span with `gen_ai.usage.output_tokens` set to the count observed from the stream's own token events, or an explicit `gen_ai.usage.output_tokens.partial=true` marker if the count is unknown. Zero is a lie; absence is honest. - Every retried attempt MUST carry `gen_ai.retry.attempt_index` and the parent MUST carry the total, so that `sum(gen_ai.usage.*)` over leaf spans equals the billed total and `sum(gen_ai.retry.aggregate.*)` over parents equals the logical-operation total. The two sums answer different questions and must not be equal. The boundary is crossed the moment a consumer cannot tell, from the trace alone, whether a given `gen_ai.usage.input_tokens` value is one prompt or the sum of five. ## Operational Effect Enforcing the boundary changes three things. First, cost dashboards must sum leaf spans, not parent spans; the parent's `gen_ai.retry.aggregate.*` is for latency and retry-rate analysis, not billing. Second, context-budget alarms must read `gen_ai.usage.input_tokens` only from leaf spans, since only a leaf's value is a prompt size. Third, and most important, the trace becomes replayable: given a trace, an auditor can reconstruct exactly which prompt bytes were sent on which attempt, which is the precondition for detecting prompt-injection state poisoning that survives a retry — if attempt 1's streamed prefix contained an injected instruction and attempt 2 re-sent a *modified* prompt, the two leaf spans' `gen_ai.request.*` differ, and that difference is the evidence. A conflated span erases it. The residual risk is that the conventions will evolve to standardize retry attributes, and runtimes that invented their own (`gen_ai.retry.*` here) will need a migration. That is acceptable; silent under-counting is not. ```python class GenAiSpanAccountingError(RuntimeError): """Raised when a GenAI span tree cannot be reconciled to billed token totals.""" def reconcile_retry_group(leaf_spans: list[dict], parent: dict) -> dict: """ Reconcile a retry group of gen_ai.chat leaf spans against its parent. Each leaf must describe exactly one provider invocation. Returns aggregate dict; raises on any invariant violation. """ if not leaf_spans: raise GenAiSpanAccountingError("retry group has no leaf spans; cannot reconcile") for i, leaf in enumerate(leaf_spans): if "gen_ai.usage.input_tokens" not in leaf: raise GenAiSpanAccountingError( f"leaf {i} missing gen_ai.usage.input_tokens; " "partial attempts must emit an explicit partial marker, not omit the field" ) if leaf.get("gen_ai.retry.attempt_index") != i: raise GenAiSpanAccountingError( f"leaf {i} has attempt_index {leaf.get('gen_ai.retry.attempt_index')}; " "attempt indices must be contiguous from 0" ) # A leaf that carries aggregate attributes is a conflated span. if any(k.startswith("gen_ai.retry.aggregate.") for k in leaf): raise GenAiSpanAccountingError( f"leaf {i} carries aggregate attributes; " "aggregates belong on the parent only" ) # Parent must NOT carry gen_ai.usage.* — that would conflate one invocation with many. if any(k.startswith("gen_ai.usage.") for k in parent): raise GenAiSpanAccountingError( "parent span carries gen_ai.usage.*; " "parent must use gen_ai.retry.aggregate.* to stay distinguishable from a leaf" ) agg_input = sum(leaf["gen_ai.usage.input_tokens"] for leaf in leaf_spans) agg_output = sum(leaf.get("gen_ai.usage.output_tokens", 0) for leaf in leaf_spans) if parent.get("gen_ai.retry.aggregate.input_tokens") != agg_input: raise GenAiSpanAccountingError( f"parent aggregate input_tokens={parent.get('gen_ai.retry.aggregate.input_tokens')} " f"!= sum of leaves={agg_input}; trace will under- or over-report billing" ) if parent.get("gen_ai.retry.aggregate.output_tokens") != agg_output: raise GenAiSpanAccountingError( f"parent aggregate output_tokens={parent.get('gen_ai.retry.aggregate.output_tokens')} " f"!= sum of leaves={agg_output}" ) return { "attempt_count": len(leaf_spans), "billed_input_tokens": agg_input, "billed_output_tokens": agg_output, "prompt_size_tokens": leaf_spans[-1]["gen_ai.usage.input_tokens"], # last attempt's prompt } ```