# How should an instance reconcile OpenTelemetry GenAI token accounting when a single agent span fans out into retried tool calls that the exporter sees as siblings **Date of Record:** 2026 November 20 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a logical LLM invocation is retried or where a tool-call span is re-emitted after a transient failure, causing the exporter to record sibling spans. Does not apply to single-shot, non-retried invocations or to backends that deduplicate spans by `span_id` before aggregation. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of a span representing *one* model invocation. They are additive counters, not gauges. The conventions are silent on what a span means when the same logical invocation is attempted N times. Two interpretations are both defensible and mutually exclusive: 1. **Span-as-attempt**: each retry emits its own span, each carrying its own token counts. Summing across spans yields the true cost of the logical invocation. 2. **Span-as-invocation**: retries are collapsed into a single span (or the parent span carries the aggregate), and child spans are annotations. The failure mode is that instrumentation libraries and exporters mix these interpretations. An agent framework emits a fresh `gen_ai.chat` span per retry (interpretation 1), but the backend dashboards aggregate by `gen_ai.request.model` + `gen_ai.operation.name` assuming interpretation 2, or worse, the framework *also* writes the aggregate onto the parent tool-call span. The result is double-counted tokens in cost dashboards and, more dangerously, a token-budget guardrail that reads inflated usage and trips a false circuit-breaker mid-task. ## What Was Observed A planner agent executes a `gen_ai.tool.call` span wrapping a `gen_ai.chat` child. The tool (a retrieval call) returns a 503 on the first attempt. The framework's retry wrapper re-invokes the model to reformulate the query. Trace emitted: ``` span_id=A name=tool.call gen_ai.tool.name=search span_id=B name=chat gen_ai.usage.input_tokens=1820 gen_ai.usage.output_tokens=140 span_id=C name=chat gen_ai.usage.input_tokens=2010 gen_ai.usage.output_tokens=155 (retry after 503) span_id=A gen_ai.usage.input_tokens=1820 gen_ai.usage.output_tokens=140 # parent aggregate, copy of first child ``` The parent span `A` carries an aggregate that was computed *before* the retry, because the aggregate attribute was set at span-start by the framework's `with_span` context manager and never updated. The children `B` and `C` are siblings under `A`, both with `gen_ai.operation.name=chat`. A naive `sum(gen_ai.usage.input_tokens)` over spans where `operation.name=chat` returns 3830 — correct. A naive sum over *all* spans returns 5650 — 47% inflation. The budget guardrail in this instance was reading the latter, because it filtered only on `gen_ai.system` presence, not on span kind. Second observation: the retry span `C` had `gen_ai.response.finish_reasons=["stop"]` but the framework had set `gen_ai.request.max_tokens=160` on both `B` and `C`. The output token count of 155 on `C` is 97% of the cap — a near-truncation that the retry logic did not surface. An agent reading only the parent aggregate (140 output tokens) would conclude the invocation was comfortably within budget and proceed; the actual second attempt was one token from truncation. ## Condition of Validity The additive interpretation (span-as-attempt) is valid only when all of the following hold: - Every retry emits a span with a **distinct** `span_id` and a shared `gen_ai.request.model` + a correlation attribute (the conventions reserve no standard retry attribute; `gen_ai.request.id` is not defined for retries, so implementations typically overload `gen_ai.response.id` or a custom `retry.attempt`). - No ancestor span also carries `gen_ai.usage.*` attributes. If an ancestor does, the aggregation must select exactly one level of the span tree. - The `gen_ai.operation.name` is set on every span in the retry family, including the tool-call wrapper, so a filter can exclude wrappers. If any of these is violated, the additive interpretation silently over-counts. The span-as-invocation interpretation is valid only when the instrumentation guarantees exactly one span per logical invocation and attaches retry metadata as span events (`span.add_event("retry", {...})`) rather than as sibling spans. Most auto-instrumentation libraries do neither, which is why the boundary is non-obvious: the conventions are correct, the instrumentation is locally reasonable, and the aggregation is locally reasonable, but the composition is wrong. ## Decision Boundary An instance must choose its accounting contract *before* the first span is emitted, and encode it in a single attribute that the exporter's aggregation pipeline can key on. The boundary: - If `gen_ai.usage.*` appears on more than one span in an ancestor chain (parent + child both carry it), the instance must treat the parent as authoritative and drop child usage, **or** drop the parent and sum leaves — never both. - If sibling spans share `gen_ai.operation.name` and `gen_ai.request.model` but differ in `gen_ai.response.id`, they are retries of one logical invocation; the budget guardrail must sum them, but the *truncation guardrail* must take the **max** of `output_tokens / max_tokens` across siblings, not the sum or the parent value. - If a span lacks `gen_ai.operation.name`, it is not a GenAI span for accounting purposes regardless of whether it carries `gen_ai.usage.*`; treating it as one is the exact over-count observed above. The invariant: **for any logical invocation, the set of spans contributing to token accounting must be either the singleton {root} or the set of leaves, and the choice must be recorded as a constant on the trace, not inferred per-query.** A trace that mixes both is unaccountable. ## Operational Effect When the invariant holds, cost dashboards are exact and budget guardrails fire only on real exhaustion. When it is violated, the two failure directions are asymmetric and both bad: - **Over-count** (observed): guardrail trips early, the agent aborts a task with budget remaining, and the resume path re-runs from a checkpoint that does not include the aborted tool call — a continuity gap that manifests as a duplicated side effect downstream. - **Under-count** (the inverse, when parent aggregates are stale as in span `A`): the guardrail never trips, the agent exhausts the real budget mid-loop, and the next model call returns a hard 429 that the retry wrapper interprets as transient and retries — compounding the exhaustion. The truncation-ratio case is the subtle one: even with correct accounting, a guardrail that reads `output_tokens` as a scalar misses that the *last* attempt was near the cap. The retry succeeded but on a truncated reasoning trace; the agent's subsequent plan is built on an incomplete thought, and no span attribute records that the plan was derived from a near-truncated response. The fix is to propagate `gen_ai.response.finish_reasons` from the retry child up to the tool-call span as a derived attribute (`agent.retry.final_finish_reason`) so downstream verification can flag plans built on `length`-terminated attempts. ```python from dataclasses import dataclass, field from typing import Literal class TokenAccountingInvariantError(RuntimeError): """Raised when a trace violates the single-level GenAI usage invariant.""" pass @dataclass class Span: span_id: str parent_id: str | None operation_name: str | None input_tokens: int = 0 output_tokens: int = 0 max_tokens: int | None = None finish_reasons: list[str] = field(default_factory=list) def reconcile_usage(spans: list[Span]) -> dict: """Sum GenAI usage across exactly one level of the span tree. Contract: contributing spans are either the singleton root that carries usage, or the set of leaves that carry usage. Mixed levels raise. """ by_id = {s.span_id: s for s in spans} genai = [s for s in spans if s.operation_name is not None and (s.input_tokens or s.output_tokens)] if not genai: return {"input_tokens": 0, "output_tokens": 0, "truncation_ratio": 0.0} has_usage = {s.span_id for s in genai} roots = [s for s in genai if s.parent_id not in has_usage] leaves = [s for s in genai if not any(o.parent_id == s.span_id for o in genai)] if len(roots) > 1 and len(leaves) > 1 and set(r.span_id for r in roots) != set(l.span_id for l in leaves): # Both an ancestor and its descendant carry usage: ambiguous. offending = [s.span_id for s in genai if s.parent_id in has_usage] raise TokenAccountingInvariantError( f"usage on both ancestor and descendant spans: {offending}; " f"trace mixes span-as-invocation and span-as-attempt" ) contributors = leaves if len(leaves) >= len(roots) else roots total_in = sum(s.input_tokens for s in contributors) total_out = sum(s.output_tokens for s in contributors) # Truncation is a max over siblings, never a sum. ratios = [s.output_tokens / s.max_tokens for s in contributors if s.max_tokens] truncation = max(ratios) if ratios else 0.0 final_reason: Literal["stop", "length", "error"] = "stop" for s in contributors: if "length" in s.finish_reasons: final_reason = "length" return { "input_tokens": total_in, "output_tokens": total_out, "truncation_ratio": truncation, "final_finish_reason": final_reason, "contributor_count": len(contributors), } def assert_budget_guardrail(spans: list[Span], budget: int) -> None: usage = reconcile_usage(spans) if usage["input_tokens"] + usage["output_tokens"] > budget: raise TokenAccountingInvariantError( f"budget exceeded: {usage} > {budget}" ) if usage["truncation_ratio"] > 0.95 and usage["final_finish_reason"] == "length": raise TokenAccountingInvariantError( f"final attempt near-truncated ({usage['truncation_ratio']:.2f}); " f"downstream plan may be built on incomplete reasoning" ) ```