# When must an instance re-derive cost attribution from raw token events because OTel GenAI span attributes are lossy across a retry boundary **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic conventions (`gen_ai.*` span attributes and `gen_ai.tool.call` / token-usage events) and reconcile those telemetry records against a billing or quota ledger after a mid-call retry, fallback, or provider failover. Does not apply to single-shot, non-retried LLM calls where one span maps one-to-one to one provider response. ## Core Distinction The GenAI semantic conventions were designed to describe *a model interaction*, not *a billing transaction*. A span attribute such as `gen_ai.usage.input_tokens` is an observation of the tokens the provider reported for that one response; it is not a ledger entry, and it carries no field that says "this response was billed." When an agent retries a tool call or fails over between providers, the runtime produces *multiple* spans for what the caller considers *one* logical step, and the convention gives you no canonical way to say which of those spans were actually charged. The failure mode is not that the numbers are wrong — each span's token counts are individually accurate — but that the *set of spans that constitute billable reality* is not recoverable from span attributes alone. Cost attribution silently double-counts or drops tokens at the retry seam. The non-obvious boundary: the convention's `gen_ai.usage.*` attributes are defined per-span, but the semantic unit of cost is per-*successful provider response that was accepted into context*. These two units diverge exactly at retry, timeout, and fallback boundaries, and nothing in the span schema marks the divergence. ## What Was Observed An agent executing a multi-tool task issued a `gen_ai.tool.call` span for a retrieval tool, then a chat span to a primary provider. The primary provider returned HTTP 429 after streaming 1,842 prompt tokens had already been consumed server-side (the provider bills prompt tokens on a rate-limited request that reached inference). The runtime's retry layer caught the 429, waited, and re-issued the identical chat request to the same provider, which succeeded with `gen_ai.usage.input_tokens = 1,842`, `gen_ai.usage.output_tokens = 310`. Telemetry contained: - Span A (failed attempt): `gen_ai.system = "provider_x"`, `gen_ai.request.model = "…"`, `gen_ai.usage.input_tokens = 1842`, status `ERROR`, `otel.status_code = ERROR`. - Span B (retry): identical attributes, status `OK`. The cost-attribution job summed `gen_ai.usage.input_tokens` across all spans with `otel.status_code = OK`. It recorded 1,842 input tokens. The provider's invoice recorded 3,684 input tokens — both attempts were billed because both reached inference. The 429 did not prevent prompt processing; it only prevented the response from being returned. Two secondary observations compounded this: 1. A separate failover path (primary → secondary provider) emitted a span on the *secondary* provider with `gen_ai.system` changed but the parent `gen_ai.tool.call` span unchanged. The attribution job grouped by `gen_ai.tool.call` span ID and therefore attributed the secondary provider's tokens to the primary provider's cost center. 2. When the runtime's retry layer used a *fresh* trace context (a known anti-pattern in some agent frameworks that spawn a new root span per retry), the retry span had no parent link to the failed attempt. There was no attribute, event, or link connecting the two, so no post-hoc reconciliation could even discover that a retry had occurred. The root cause is a mismatch between the convention's *observability* intent and the operator's *accounting* intent. The convention records what the model did; the operator needs to know what the wallet did. These coincide except at exactly the boundaries — retry, timeout-after-partial-consumption, fallback, and speculative/hedged calls — where money is spent but no successful response is recorded. ## Condition of Validity The invariant "sum of `gen_ai.usage.*` over `OK` spans equals billed tokens" holds **only if** every billed provider request corresponds to exactly one span and every non-billed request corresponds to zero spans. This is violated whenever any of the following is true: - A request reaches provider inference but the response is not accepted (429, 5xx after prompt processing, client-side timeout after the provider began generating, streaming abort mid-response). The provider may bill prompt tokens and partial output tokens; the span is marked `ERROR` and excluded from `OK` sums. - A retry or fallback produces a second span for the same logical step. If both spans are `OK` (e.g., a hedged request where the loser is cancelled after both were billed), both are summed and the step is over-counted. - A retry is emitted under a detached trace context, making the retry invisible to parent-based reconciliation. - Provider-side caching (prompt caching, context caching) returns `gen_ai.usage.input_tokens` that does not equal billed input tokens because cached tokens are billed at a different rate — the convention has no standard attribute distinguishing cached from uncached input tokens in all versions, so a single scalar cannot be priced. Under any of these, the span-attribute-derived cost is a *lower or upper bound*, not an equality, and the direction of error depends on the failure class: error-span exclusion under-counts; hedged-success double-counting over-counts. ## Decision Boundary An instance must **re-derive cost from raw token events plus request-lifecycle evidence** — not from span-attribute sums — when the following predicate holds: > The runtime's retry/fallback layer can emit more than one provider request per logical agent step, **and** any provider in the path bills on request-received rather than response-delivered. When that predicate is false (single-attempt-per-step, response-delivered billing), summing `gen_ai.usage.*` over `OK` spans is sound and should be preferred for its simplicity. When the predicate is true, the runtime must, at minimum, propagate a stable `agent.step.id` (a logical-step identifier distinct from the span ID) onto every attempt span, mark each attempt with an explicit `gen_ai.request.attempt_index` and a `provider.billed_on_receipt` boolean, and carry the failed attempt's usage attributes even when `otel.status_code = ERROR`. Reconciliation then sums over *all* attempt spans for a step, keyed by `agent.step.id`, and prices each by its own `gen_ai.system` — never by the parent tool-call span's provider. If the runtime cannot guarantee `agent.step.id` propagation across retries (e.g., retries occur in a separate process that mints a new trace), the instance must fall back to the provider's own usage/billing API as the source of truth and treat OTel spans as diagnostic only. This is the hard boundary: **OTel GenAI spans are authoritative for latency and token *observation*, never for cost *attribution* across a retry boundary.** ## Operational Effect Without the re-derivation, three concrete degradations occur: 1. **Quota drift.** Per-tenant token quotas computed from `OK`-span sums drift monotonically below actual consumption on any tenant whose traffic hits rate limits. The drift is proportional to the 429 rate, so it is invisible in low-traffic testing and appears as a sudden overage in production under load — precisely when rate limits fire. 2. **Cost-center misattribution under failover.** Because the parent `gen_ai.tool.call` span retains the primary provider's identity, secondary-provider spend is booked to the primary's cost center. Finance reconciliation against provider invoices shows a persistent imbalance that looks like a provider billing error but is a telemetry join error. 3. **Unreconcilable retries.** With detached trace contexts, the retry count itself is unknown; the runtime cannot even compute the correction factor. The only recovery is to re-ingest provider invoice line items and join them to spans by request ID — which requires the runtime to have recorded the provider's request ID as a span attribute (`gen_ai.response.id` where available, or a custom `provider.request.id`), a field frequently dropped by SDK auto-instrumentation. The guardrail is architectural: the retry layer and the telemetry layer must share a logical-step identifier that survives retries, and the attribution job must be written against that identifier with an explicit policy for `ERROR` spans that consumed tokens. The invariant to enforce is: *for every logical step, the sum of usage across all attempt spans, priced per attempt's provider, equals the sum of provider-billed line items for that step.* Any deviation is a reconciliation failure that must halt the attribution batch rather than silently emit a number. ```python class CostAttributionDivergence(RuntimeError): """Raised when OTel GenAI span-derived cost cannot be reconciled to billed usage.""" pass def attribute_cost_from_spans(step_id: str, attempt_spans: list[dict], billed_tokens: int) -> dict: """ Re-derive logical-step cost from ALL attempt spans (including ERROR spans that consumed tokens), keyed by a stable agent.step.id, priced per attempt's own gen_ai.system. Refuses to emit a number if the derivation cannot be reconciled to billed usage. """ if not attempt_spans: raise CostAttributionDivergence( f"step {step_id}: no attempt spans found; cannot attribute cost" ) derived = 0 providers = set() for span in attempt_spans: if span.get("agent.step.id") != step_id: raise CostAttributionDivergence( f"step {step_id}: span {span.get('span_id')} carries mismatched " f"agent.step.id={span.get('agent.step.id')!r}; retry context detached" ) # ERROR spans that reached inference still consumed tokens; include them. consumed = (span.get("gen_ai.usage.input_tokens", 0) + span.get("gen_ai.usage.output_tokens", 0)) if span.get("otel.status_code") == "ERROR" and consumed == 0: # Genuinely zero-consumption failure (e.g., connection refused): skip. continue derived += consumed providers.add(span.get("gen_ai.system")) if len(providers) > 1 and not all( s.get("provider.billed_on_receipt") is not None for s in attempt_spans ): raise CostAttributionDivergence( f"step {step_id}: multi-provider failover without billed_on_receipt " f"flag; per-provider pricing cannot be applied" ) if derived != billed_tokens: raise CostAttributionDivergence( f"step {step_id}: derived {derived} tokens from {len(attempt_spans)} " f"attempt span(s) but provider billed {billed_tokens}; " f"span attributes are lossy across the retry boundary" ) return {"step_id": step_id, "tokens": derived, "providers": sorted(providers)} ```