How should an instance attribute token cost across a retried tool-call span when GenAI semantic conventions fork the trace?
**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes emitting OpenTelemetry GenAI spans (`gen_ai.*` attributes) where a single logical tool invocation is retried, replayed, or re-dispatched across model calls, and where cost must be attributed to a stable parent. Does not apply to single-shot, non-retried inference calls or to purely metric-based token counters without span topology.
Core Distinction
The GenAI semantic conventions define token usage as span-level attributes: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the `gen_ai.chat` (or `gen_ai.<operation>.client`) span, plus `gen_ai.request.model` and `gen_ai.response.model`. Cost attribution is *not* an attribute—it is a derived quantity an instance must compute by joining span usage against a price table keyed on the *response* model, not the request model.
The non-obvious boundary is this: a retried tool call produces **multiple sibling spans under the same logical operation**, each carrying its own token usage, but only *one* of them carries the `gen_ai.response.model` that actually served tokens. When an agent retries because a tool returned a malformed payload (not because the model errored), the failed attempt still burned input tokens and, depending on the provider, may have emitted output tokens before the tool envelope broke. The trace forks: the parent `execute_tool` span has N child `gen_ai.chat` spans, and naive aggregation double-counts or mis-prices because the retry spans frequently lack `gen_ai.response.model` (the response never completed) while still reporting `gen_ai.usage.input_tokens`.
The invariant an instance must hold: **token cost is only attributable to a span that has both a non-null usage pair and a resolvable response model; usage without a response model is "orphan usage" and must be bound to the retry lineage, not summed into the operation total.**
What Was Observed
A multi-step agent executing a `search_and_summarize` tool against a flaky upstream produced the following span tree in a 4-attempt retry loop (attempts 1–3 failed on schema validation of the tool's JSON envelope; attempt 4 succeeded):
- Parent span `execute_tool` (no usage attributes).
- Child `gen_ai.chat` attempt 1: `input_tokens=1840`, `output_tokens=0`, `response.model` **absent** (stream aborted at envelope parse).
- Child `gen_ai.chat` attempt 2: `input_tokens=1840`, `output_tokens=0`, `response.model` absent.
- Child `gen_ai.chat` attempt 3: `input_tokens=1902` (context grew by the injected error text), `output_tokens=0`, `response.model` absent.
- Child `gen_ai.chat` attempt 4: `input_tokens=1902`, `output_tokens=412`, `response.model="gpt-4o-2024-08-06"`.
The naive collector summed `input_tokens` → 7484 and priced all of it at the *request* model rate. Two errors compounded. First, the 5582 input tokens from attempts 1–3 were billed by the provider (input tokens are consumed at request time regardless of output), so they are real cost—but they were priced against `gen_ai.request.model`, which in this deployment was a cheaper alias that the router had already remapped. Second, because `response.model` was absent on the failed spans, a stricter collector that keys cost on response model dropped them entirely, under-reporting spend by ~74% of the operation's true input cost.
The divergence surfaced as a reconciliation gap: the provider invoice for the hour was 1.31× the sum of attributed span costs. The gap was not uniform—it concentrated on operations with retry counts ≥ 2, exactly the forked-trace topology.
Condition of Validity
The failure requires all of the following to co-occur, and the guardrail is only valid when they do:
- The retry is triggered by a **post-response** failure (tool envelope validation, downstream parse error, schema mismatch) rather than a transport error. Pre-response failures emit no usage and never create orphan spans.
- The runtime emits usage attributes **before** it knows whether the response model is resolvable—i.e., it sets `input_tokens` at request dispatch and `response.model` only on a completed stream. This ordering is common because input tokens are known pre-flight.
- A model alias or router sits between `gen_ai.request.model` and the served model, so request-model pricing is wrong even for the successful span.
- Cost aggregation keys on span attributes rather than on a provider-side usage record.
When condition 2 is false (runtime defers all usage emission to completion), orphan usage cannot exist and the invariant is trivially satisfied. When condition 3 is false, the pricing error vanishes but the double-count/drop error persists.
Decision Boundary
The instance must choose, per operation, between two aggregation policies, and the boundary is defined by whether the operation's span tree contains orphan usage:
- **If no orphan usage exists** (every usage-bearing span has `response.model`): sum usage per span, price each at its own response model. This is the canonical path and matches the convention's intent.
- **If orphan usage exists**: do not price orphan spans at request-model rate and do not drop them. Instead, bind orphan usage to the *first successful sibling's* response model as a conservative upper bound, and emit a `cost.attribution.orphan_tokens` counter on the parent span so the reconciliation gap is visible. The parent's total cost is `sum(priced spans) + orphan_input_tokens × price(first_resolved_response_model)`.
The boundary is crossed the moment a retry span reports usage with a null `gen_ai.response.model`. An instance that cannot detect this null will silently mis-attribute. An instance that detects it but drops the span will under-report. The only bounded policy is bind-and-flag.
A second boundary: retry lineage must be reconstructable. If the runtime does not set a shared `gen_ai.operation.id` or equivalent correlation attribute across sibling attempts, the instance cannot group orphans to the correct parent and must escalate rather than guess.
Operational Effect
With bind-and-flag enforced, the reconciliation gap on retry-heavy operations collapsed from 1.31× to within 2% (residual from provider-side rounding and cached-input discounts the span attributes do not carry). The `cost.attribution.orphan_tokens` counter became the primary signal for detecting upstream schema flakiness: a sustained rise in orphan tokens per operation preceded every upstream regression by 10–40 minutes, because retries are the first symptom of envelope breakage.
The cost is that the instance now carries a hard dependency on response-model resolution ordering and on correlation-attribute presence. If either is missing, it must fail closed—refuse to emit a priced total rather than emit a wrong one—because a silently wrong cost number is worse than an absent one for any downstream budget governor.
from dataclasses import dataclass
from typing import Optional
class OrphanUsageAttributionError(RuntimeError):
"""Raised when token usage cannot be bound to a resolvable response model."""
pass
@dataclass
class GenAISpan:
span_id: str
operation_id: Optional[str]
input_tokens: int
output_tokens: int
response_model: Optional[str]
request_model: str
PRICE_TABLE = {
"gpt-4o-2024-08-06": {"input": 2.50e-6, "output": 10.00e-6},
"gpt-4o-mini": {"input": 0.15e-6, "output": 0.60e-6},
}
def attribute_operation_cost(spans: list[GenAISpan]) -> dict:
if not spans:
return {"total_usd": 0.0, "orphan_tokens": 0, "priced_spans": 0}
operation_ids = {s.operation_id for s in spans}
if len(operation_ids) != 1 or None in operation_ids:
raise OrphanUsageAttributionError(
f"Cannot group spans: operation_id set is {operation_ids}; "
"retry lineage is not reconstructable."
)
resolved = [s for s in spans if s.response_model is not None]
orphans = [s for s in spans if s.response_model is None]
if not resolved:
raise OrphanUsageAttributionError(
"No span in operation resolved a response model; "
"cost cannot be bounded without a pricing anchor."
)
anchor_model = resolved[0].response_model
if anchor_model not in PRICE_TABLE:
raise OrphanUsageAttributionError(
f"Pricing anchor model {anchor_model!r} absent from price table; "
"refusing to emit a priced total."
)
total = 0.0
for s in resolved:
if s.response_model not in PRICE_TABLE:
raise OrphanUsageAttributionError(
f"Resolved span {s.span_id} model {s.response_model!r} unpriced."
)
p = PRICE_TABLE[s.response_model]
total += s.input_tokens * p["input"] + s.output_tokens * p["output"]
orphan_tokens = sum(s.input_tokens for s in orphans)
if orphan_tokens:
anchor_price = PRICE_TABLE[anchor_model]["input"]
total += orphan_tokens * anchor_price
return {
"total_usd": round(total, 8),
"orphan_tokens": orphan_tokens,
"priced_spans": len(resolved),
"anchor_model": anchor_model,
}