# In what scenarios must an instance refuse to close an OpenTelemetry agent span when GenAI token attributes are non-additive across tool-call retries **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for an agent turn containing one or more tool calls, where the runtime performs internal retries, fan-out, or model re-invocation beneath a single logical agent span. Does not apply to single-shot, single-tool-call spans with no retry or fan-out semantics, nor to spans where token accounting is delegated entirely to a downstream billing pipeline that tolerates overcounting. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the newer `gen_ai.usage.*` sub-namespace) as *per-invocation* counters describing a single model call. They are not defined as aggregable across a span tree in a way that guarantees additive conservation. The distinction that matters operationally is between **a span that represents one model invocation** and **a span that represents an agent turn that internally contains N model invocations plus M tool executions**. When a runtime collapses retries and tool-loop iterations into a single agent span and then sums child token attributes into the parent, the resulting parent counter is *descriptively plausible but arithmetically wrong* the moment any child is retried, because retried invocations emit their own token attributes that were already partially billed, already partially cached, or already partially discarded by the model provider. The invariant that breaks is **token conservation under retry**: the sum of `gen_ai.usage.input_tokens` over all spans in a trace must equal the tokens actually billed to the principal. Retries violate this invariant in three independent ways: (1) failed-then-retried calls are billed twice by some providers and once by others (prompt-cache hits, partial streaming aborts), so a naive sum overcounts; (2) cache-read tokens (`gen_ai.usage.cache_read.input_tokens` under provider extensions) are reported on the retry but the original call's cache-miss tokens remain on the first span, so the trace contains both the miss and the hit; (3) tool-call fan-out where the model is re-invoked per tool result produces a *chain* of spans whose input tokens each include the accumulated conversation, meaning the sum is quadratic in loop depth, not linear. ## What Was Observed A three-tool agent turn (search → fetch → summarize) with one retry on the fetch tool. The runtime emitted: - `agent.turn` (parent, `gen_ai.operation.name=invoke_agent`) - `llm.call.1` (`gen_ai.operation.name=chat`, input=1840, output=210) - `tool.fetch.attempt1` (errored, `error.type=TimeoutError`, no token attrs) - `tool.fetch.attempt2` (succeeded) - `llm.call.2` (input=3120, output=180) — this input includes the full prior conversation plus the tool result - `llm.call.3` (input=4010, output=95) — again includes accumulated context The exporter, configured with a span processor that sums child `gen_ai.usage.input_tokens` into the parent on span end, wrote `agent.turn` with `input_tokens = 1840 + 3120 + 4010 = 8970`. The provider's billing record for the same turn showed 4,410 input tokens — because the provider's prompt cache served 3,900 of those tokens at cache-read rates and the runtime's span processor had no attribute to distinguish cache-read input from fresh input. The trace was internally consistent (sum of children equals parent) and externally wrong by a factor of 2.03. A second observation: when the runtime retried `tool.fetch` and the retry succeeded, the *agent span* was closed with `status=OK`, but the errored attempt-1 span carried `error.type=TimeoutError` and was exported as a child with `status=ERROR`. Any downstream SLO computation that counts `status=ERROR` spans in the trace as failures marked the turn as failed *and* marked it as succeeded, depending on whether the query joined on parent or child status. The parent status and the child status disagreed because the semantics of "agent turn succeeded" (it did, after retry) and "this span errored" (it did) are both true but not composable. A third observation, the sharpest: on a streaming abort mid-`llm.call.2`, the provider emitted a partial usage record (`output_tokens=0`, `input_tokens` reported as the full prompt). The runtime, seeing a non-zero input, treated the call as billable and included it in the parent sum. The provider's billing, however, did not charge for the aborted stream. The trace overcounted by 3,120 tokens — a full prompt's worth — on a call that produced zero output and zero charge. ## Condition of Validity The naive parent-sum is valid **only** under all of the following: 1. Every child model span is a *fresh* invocation with no prompt-cache hit, **or** the runtime carries `gen_ai.usage.cache_read.input_tokens` and the aggregator subtracts it from the billed total. 2. No child was retried after a partial-stream abort, **or** aborted-stream spans are tagged with a distinguishing attribute (e.g., `gen_ai.response.finish_reasons=["aborted"]`) and excluded from the sum. 3. Tool-call loops are represented as *sibling* spans under the agent span, not as a *chain* where each subsequent call re-includes the prior context — because in the chain case, the input tokens of call N include the input tokens of call N-1, and summing them double-counts the prefix. 4. The agent span's `status` is set by an explicit turn-level state machine, not by propagating child status. When any of these fails — and in any agent with retries, fan-out, or streaming, at least one will — the parent token attributes are not a billing record and must not be treated as one. They are a *trace-shape descriptor* at best. ## Decision Boundary The boundary is: **does the runtime have a ground-truth per-turn token ledger independent of the span tree?** - If **yes**, the span tree's parent token attributes should be reconciled against the ledger before export; mismatches are a signal of a retry/fan-out accounting bug, and the span should be closed with an explicit `gen_ai.usage.reconciliation_status=MISMATCH` attribute rather than silently exported. - If **no**, the runtime must **not** sum child token attributes into the parent. It must either (a) leave parent token attributes unset and require consumers to sum leaves with the caveats above, or (b) emit a separate `gen_ai.usage.aggregate` event (not attribute) carrying the summed value plus a `method=naive_sum` qualifier so consumers know it is not billing-grade. The refusal case — the one this record exists to name — is: **an instance must refuse to close an agent span as `status=OK` with populated parent token attributes when any child span in its subtree carries `status=ERROR` or `gen_ai.response.finish_reasons` containing `aborted`, unless the runtime has explicitly reconciled the parent sum against a turn ledger and recorded the reconciliation outcome.** Closing in that state produces a trace that is simultaneously green and red, and a token count that is simultaneously plausible and wrong. Both are worse than a missing attribute. ## Operational Effect The effect of getting this wrong is not a crash. It is a *silent divergence between the observability plane and the billing plane* that compounds. Cost dashboards built from span sums drift upward relative to invoices by the retry rate and the cache-hit rate — typically 15–40% in agents with tool loops. SLOs built from child `status` overcount failures by the retry rate. Incident responders who trust the trace see a turn that "succeeded but errored" and lose an hour reconciling. The correct posture is to treat GenAI token attributes on agent spans as **non-authoritative unless a reconciliation attribute is present**, and to make the span processor fail closed — refuse to emit the parent sum — when the subtree contains a retried or aborted child. The guardrail is a span-close precondition, not a post-hoc query fix, because post-hoc fixes require the very ground truth the trace was supposed to provide. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Iterable class SpanAccountingError(RuntimeError): """Raised when an agent span cannot be closed with a valid token sum.""" class FinishReason(str, Enum): STOP = "stop" LENGTH = "length" ABORTED = "aborted" ERROR = "error" @dataclass class ChildSpan: name: str input_tokens: int = 0 output_tokens: int = 0 cache_read_input_tokens: int = 0 status: str = "OK" # "OK" | "ERROR" finish_reasons: tuple[FinishReason, ...] = () retried: bool = False @dataclass class AgentSpan: name: str children: list[ChildSpan] = field(default_factory=list) ledger_input_tokens: int | None = None # ground truth, if available def _naive_input_sum(self) -> int: # Naive sum: what a span processor would compute by default. return sum(c.input_tokens for c in self.children) def _billed_input_estimate(self) -> int: # Best-effort: drop aborted streams, subtract cache reads. total = 0 for c in self.children: if FinishReason.ABORTED in c.finish_reasons: continue total += c.input_tokens - c.cache_read_input_tokens return total def close(self) -> dict[str, object]: has_error_child = any(c.status == "ERROR" for c in self.children) has_aborted_child = any( FinishReason.ABORTED in c.finish_reasons for c in self.children ) has_retry = any(c.retried for c in self.children) naive = self._naive_input_sum() estimate = self._billed_input_estimate() # Guardrail: refuse to close as OK with a populated sum when the # subtree contains an errored, aborted, or retried child and no # ledger reconciliation has been recorded. if (has_error_child or has_aborted_child or has_retry) and self.ledger_input_tokens is None: raise SpanAccountingError( f"agent span {self.name!r} has retried/errored/aborted children " f"(error={has_error_child}, aborted={has_aborted_child}, " f"retry={has_retry}) and no ledger reconciliation; " f"naive_sum={naive} vs billed_estimate={estimate}" ) if self.ledger_input_tokens is not None and naive != self.ledger_input_tokens: # Reconciliation mismatch: emit but tag, do not silently pass. return { "gen_ai.usage.input_tokens": self.ledger_input_tokens, "gen_ai.usage.reconciliation_status": "MISMATCH", "gen_ai.usage.naive_sum": naive, } return { "gen_ai.usage.input_tokens": self.ledger_input_tokens if self.ledger_input_tokens is not None else estimate, "gen_ai.usage.reconciliation_status": "OK" if self.ledger_input_tokens is not None else "UNRECONCILED", } def emit_agent_turn(span: AgentSpan) -> dict[str, object]: return span.close() ```