# Under what conditions must an instance refuse to emit a single agent span when OpenTelemetry GenAI token accounting diverges from tool-call attribute cardinality **Date of Record:** 2026 November 21 **Scope:** Applies to any LLM agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) across a multi-step tool-calling loop, where a parent agent span aggregates child tool spans. Does not apply to single-shot completions with no tool calls, nor to runtimes using proprietary tracing schemas that never reconcile span-level token counts against a parent aggregate. ## Core Distinction The GenAI semantic conventions treat *token usage* and *tool-call attributes* as orthogonal telemetry: usage counters live on the model-invocation span (`gen_ai.operation.name = "chat"`), while tool identity lives on the tool-execution span (`gen_ai.operation.name = "execute_tool"`). This orthogonality is correct at the schema level but creates a false invariant at the *aggregation* level. The `gen_ai.usage.input_tokens` value on a parent agent span is conventionally expected to equal the sum of its child chat spans, and the count of child `execute_tool` spans is expected to equal the number of tool calls the model emitted. Neither equality is enforced by the spec, and under retry, streaming, or partial-failure conditions the two diverge silently. The distinction that matters operationally: a span tree that is *structurally valid* (all required attributes present, parent/child links intact) can still be *semantically corrupt* (token totals that double-count retried prompts, or tool-call spans whose count exceeds the tool calls actually billed). The boundary condition is the point at which this corruption cannot be repaired by downstream recomputation and must be refused at emission. ## What Was Observed A three-step agent loop (plan → search → summarize) was instrumented per the conventions. The model invocation for step 2 was retried once after a 503 from the provider. The runtime emitted two `chat` spans for step 2 — the aborted request and the successful retry — each carrying its own `gen_ai.usage.input_tokens` (1,840 and 1,910 respectively). The parent agent span aggregated both, reporting 3,750 input tokens for a step that was billed once at 1,910. Simultaneously, the aborted attempt had already emitted one `execute_tool` span (the model produced a tool call before the transport error surfaced on the stream close), and the retry produced a second `execute_tool` span with the *same* `gen_ai.tool.call.id`. The parent span therefore advertised three tool calls across two logical steps, and the token total was inflated 96%. Downstream cost dashboards read the parent aggregate; the provider invoice read 1,910 + the other two steps. The reconciliation delta was attributed to "cache misses" for eleven days before the retry spans were located. The failure is not that retries happen — it is that the spec gives no attribute to mark a span as superseded, so an aggregator cannot distinguish "two independent calls" from "one call attempted twice." ## Condition of Validity The invariant holds — a parent agent span may be emitted with aggregated usage — only when all three of the following are true at emission time: 1. **Attempt multiplicity is explicit.** Every `chat` span carries a runtime-local attribute (e.g. `agent.attempt.index`, not a GenAI convention key, since the spec has none) so that aggregation can select `max(attempt.index)` per logical step rather than summing. 2. **Tool-call identity is unique per logical call.** `gen_ai.tool.call.id` must be stable across retries of the same logical call — if the runtime regenerates the id on retry, the two `execute_tool` spans become indistinguishable from two genuine calls and the cardinality invariant is unrecoverable. 3. **Streaming completion is atomic with usage attribution.** If a `chat` span is closed on transport error *before* `gen_ai.usage.output_tokens` is populated, the span must be marked as aborted (status `ERROR`) and excluded from the parent aggregate, not counted with zero output tokens. When any of these fails, the correct action is to emit the child spans (they are evidence) but to *withhold the parent aggregate* — emit the agent span with usage attributes absent rather than present-and-wrong. An absent attribute is recoverable by a downstream join; a wrong aggregate is not, because it is indistinguishable from a correct one. ## Decision Boundary The runtime must decide, per agent span, between three emissions: - **Emit aggregate** — all child chat spans share a consistent `attempt.index` lineage, every `execute_tool` span has a unique `call.id`, and no child is in `ERROR` with missing usage. Sum is safe. - **Emit without aggregate** — retries detected (multiple `attempt.index` for one step) or an aborted chat span with null usage. Child spans carry the truth; the parent omits `gen_ai.usage.*`. Dashboards must be built to tolerate the null. - **Refuse and raise** — the divergence is *structural*: a tool span exists whose `call.id` matches no tool call in any chat span's emitted tool-call list (orphan tool execution), or the count of `execute_tool` spans exceeds the max tool-call count across attempts for that step. This indicates the runtime's own bookkeeping is inconsistent — a bug, not a transport artifact — and emitting anything propagates the corruption into the trace store where it becomes indistinguishable from real activity. The boundary is not "is the number wrong" (you often cannot know) but "can the number be wrong in a way that is *unattributable*." Orphan tool spans and cardinality overflow are unattributable; retry double-counting is attributable once `attempt.index` exists. ## Operational Effect Runtimes that adopt the three-part validity condition recover cost reconciliation automatically: the aggregator selects one attempt per step and the invoice matches. Runtimes that skip it — the common case, because the GenAI conventions do not mention retries at all — produce traces that are internally consistent (valid parent/child trees, all required attributes) yet systematically over-report tokens and tool calls by the retry rate. At a 4% retry rate this is a silent 4% cost overstatement that never triggers an alert, because nothing in the trace is *malformed*. The refusal path matters most: an orphan tool span is the only signal that the agent executed a tool the model never requested in any recorded attempt — the signature of a state-handoff bug or a prompt-injection-induced tool call — and suppressing the parent aggregate is what forces an operator to look at the child spans instead of trusting the rollup. ```python class GenAISpanAggregationError(RuntimeError): """Raised when agent-span token/tool accounting cannot be safely aggregated.""" pass def emit_agent_span(step: dict, chat_spans: list, tool_spans: list) -> dict: attempts = {s["agent.attempt.index"] for s in chat_spans} call_ids = [t["gen_ai.tool.call.id"] for t in tool_spans] # Structural corruption: duplicate or orphan tool-call identity. if len(call_ids) != len(set(call_ids)): raise GenAISpanAggregationError( f"duplicate gen_ai.tool.call.id across retries in step {step['id']}: " f"{call_ids} — tool-call identity not stable across attempts" ) emitted_calls = {c for s in chat_spans for c in s.get("tool_calls", [])} orphans = [cid for cid in call_ids if cid not in emitted_calls] if orphans: raise GenAISpanAggregationError( f"orphan execute_tool spans {orphans} in step {step['id']}: " f"tool executed but no chat span requested it — refusing to emit aggregate" ) aborted = [s for s in chat_spans if s.get("status") == "ERROR" and s.get("gen_ai.usage.output_tokens") is None] if len(attempts) > 1 or aborted: # Attributable divergence: emit children, withhold parent aggregate. return { "gen_ai.operation.name": "invoke_agent", "agent.step.id": step["id"], "agent.aggregate_withheld": True, "agent.withhold_reason": "retry_or_aborted_attempt", } return { "gen_ai.operation.name": "invoke_agent", "agent.step.id": step["id"], "gen_ai.usage.input_tokens": sum(s["gen_ai.usage.input_tokens"] for s in chat_spans), "gen_ai.usage.output_tokens": sum(s["gen_ai.usage.output_tokens"] for s in chat_spans), } ```