# Which invariants prevent OpenTelemetry GenAI span attribution from silently mispricing agent tool-call trees under concurrent retries **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic conventions (`gen_ai.*`) for reasoning steps, tool calls, and token/cost metrics, where tool calls may be retried concurrently or replayed by an outer supervisor. Does not apply to single-shot, single-threaded inference calls with no retry or fan-out topology. ## Core Distinction The failure is not "missing spans" or "wrong token counts." It is **double-attributed cost with single-attributed latency**: a retried tool call produces two child spans that both carry the *same* `gen_ai.usage.input_tokens` / `output_tokens` and the same `gen_ai.usage.cost` attributes, but only one of them is linked by `trace_id`+`span_id` to the parent reasoning step that actually consumed the result. The discarded attempt (the one whose output the agent ignored) still emits usage, so a naive backend that sums `gen_ai.usage.*` across all spans in a trace overcounts billed tokens by the retry factor, while a latency backend that reads only the *linked* span undercounts wall-clock time. The invariant that prevents this is: **usage attributes MUST be emitted exactly once per physically-billed model invocation, and the span carrying that usage MUST be the span whose output is (or would be) consumed by a downstream parent.** Retries are separate billable invocations, so they legitimately emit separate usage — but they must be distinguishable from the *consumed* invocation by an explicit status/outcome attribute, not inferred from span nesting. ## What Was Observed A supervisor agent fans out three tool calls (`search`, `fetch`, `summarize`) to a worker pool. Each tool call is an LLM-backed sub-agent that emits a `gen_ai` span. The `fetch` tool intermittently returns a timeout; the runtime's retry policy re-invokes it. Trace replay showed: - The `fetch` operation emitted 2 spans: `fetch.attempt=0` (status `error`, `gen_ai.usage.input_tokens=1840`, `output_tokens=210`, `cost=0.0041`) and `fetch.attempt=1` (status `ok`, identical usage attributes, `cost=0.0041`). - The parent `summarize` span's `gen_ai.usage` did **not** include either — the supervisor passed the fetched text as a plain string, so the sub-agent's usage lived only on the child spans. - A cost dashboard summing all `gen_ai.usage.cost` in the trace reported `0.0041 × 2` for `fetch`, i.e., 100% overcount on that operation. - A latency dashboard reading the *consumed* span reported `fetch` duration as the successful attempt only, dropping the failed attempt's 2.3 s — so the trace's reported wall-clock was 2.3 s shorter than reality, and the retry amplification (why the run was slow) was invisible. The non-obvious part: the **failed** attempt is the one that consumed the most input tokens (it included the full retry-context preamble), so the overcount was not a clean 2× — it was `1.0× + 1.7×` on that operation. ## Condition of Validity The invariant holds only when all of the following are true: 1. Every physically-billed invocation emits a span with `gen_ai.operation.name` set (e.g., `chat`, `execute_tool`) and a **stable** `gen_ai.usage.*` set. If the runtime batches token accounting at the parent (aggregating child usage into the parent span and emitting nothing on children), the double-count disappears but the *attribution* moves to the wrong span — and a retry then silently inflates the parent. 2. Retries are marked with an outcome attribute the backend can filter on. The GenAI conventions do not standardize a `gen_ai.retry.*` namespace; the operational requirement is that the runtime emits *some* machine-readable discriminator (e.g., `gen_ai.tool.call.retry_count`, or span status `ERROR` + a `retryable` attribute) that lets the cost aggregator select "consumed only." 3. The consumer linkage is explicit. If the agent passes tool output as an opaque string, there is no span link from `summarize` to the *specific* `fetch` attempt; the backend cannot reconstruct which attempt was consumed. A `Span.add_link()` from the consuming span to the consumed attempt is the only reliable signal. 4. The clock domain is shared. If retries run on different workers with unsynchronized clocks, the failed attempt's duration cannot be attributed to the parent's wall-clock; the trace's critical path is understated regardless of usage correctness. ## Decision Boundary The boundary is: **does the runtime retry inside the span, or as sibling spans?** - *Retry inside the span* (loop within one `gen_ai` span, incrementing an attempt attribute): usage is summed correctly by construction, but the span's latency now hides retry amplification and the status attribute must reflect the *final* attempt, not the first. This is safe for cost, unsafe for diagnosis. - *Retry as sibling spans* (each attempt its own span): correct for diagnosis, but requires the outcome discriminator and the consumption link, or cost double-counts and latency undercounts. The failure occurs exactly at the crossover: a runtime that switches from in-span retry to sibling-span retry (common when a retry policy is lifted from the tool client to the agent supervisor) without adding the discriminator or the link. The spans look structurally valid — every span is well-formed, every attribute is present — and the corruption is purely in the aggregation semantics. ## Operational Effect The downstream effect is a **cost/latency divergence that is invisible in any single trace but systematic across a fleet**: high-retry operations (flaky tools, rate-limited endpoints) get overcounted in cost and undercounted in latency, so the agent's *slowest* paths look *cheapest*. Capacity planning under-provisions the retry-heavy tools, and cost attribution blames the wrong sub-agent. The guardrail is a conformance check at trace ingest: assert that for every `gen_ai` span with `status=ERROR` and a `retryable` attribute, either (a) a sibling span with the same `gen_ai.operation.name` and a later start time exists and is linked from a parent, or (b) the span is explicitly excluded from cost aggregation. Reject traces that violate it rather than silently summing them. ```python class GenAiAttributionError(RuntimeError): """Raised when a trace violates the single-attribution invariant for gen_ai usage.""" def validate_usage_attribution(spans: list[dict]) -> None: """ Enforce: every gen_ai span carrying usage must be either (a) the sole span for its operation in the trace, or (b) a retry sibling that is explicitly linked from a consuming parent. Otherwise cost aggregation will double-count. """ by_op: dict[str, list[dict]] = {} for s in spans: op = s.get("attributes", {}).get("gen_ai.operation.name") if op and "gen_ai.usage.input_tokens" in s.get("attributes", {}): by_op.setdefault(op, []).append(s) for op, group in by_op.items(): if len(group) == 1: continue # Multiple billable spans for one operation: require a consumption link # from a parent to exactly one of them, and a retry discriminator on the rest. consumed = [s for s in group if s.get("consumed_by_parent_span_id")] if len(consumed) != 1: raise GenAiAttributionError( f"operation {op!r} has {len(group)} billable spans but " f"{len(consumed)} consumption links; cost will be misattributed" ) for s in group: if s is consumed[0]: continue if not s.get("attributes", {}).get("gen_ai.tool.call.retry_count"): raise GenAiAttributionError( f"operation {op!r} has an unlinked billable span " f"span_id={s.get('span_id')!r} without a retry discriminator; " "it will be summed into cost alongside the consumed attempt" ) ```