# When must an instance refuse to close an OpenTelemetry GenAI agent span: the tool-call attribute cardinality invariant and token-accounting double-count boundary **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) where a single agent invocation fans out into N tool calls that each carry their own token cost and may be retried, replayed, or merged by a parent. Does not apply to single-shot inference spans with no tool fan-out, and does not cover trace-context propagation or sampling decisions. ## Core Distinction The GenAI conventions define token usage as a property of an *operation*, not of a *span tree*. A `chat` span reports `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` for the model round-trip it wraps. A `execute_tool` span reports tool arguments and results but is explicitly *not* supposed to carry model token usage — yet in practice the agent loop that drives the tool call is itself a model round-trip (the model decided to call the tool, and its reasoning tokens were spent producing the call). The boundary that matters is not "child vs parent" but "which span owns the tokens that produced the tool-call decision." The failure is non-obvious because both choices are individually defensible. If the parent `invoke_agent` span sums all descendant `chat` spans, and each `chat` span that emitted a tool call is *also* counted as a `execute_tool` child with its own usage attributes (a common instrumentation shortcut), the aggregate is double-counted by exactly the number of tool-call turns. The span tree looks structurally valid, the attributes are individually correct, and the sum is wrong. This is an invariant violation that no schema validator catches because each span is conformant in isolation. ## What Was Observed A three-turn agent loop (plan → tool call → synthesize) emitted the following, instrumented by a runtime that attached usage to both the model span and the tool span: - `invoke_agent` (root): `gen_ai.usage.input_tokens=0`, `output_tokens=0` (root carries no usage; correct per convention — usage lives on leaf operations). - Turn 1 `chat` span: input 1,200, output 340. This turn emitted a tool call. - Turn 1 `execute_tool` span: input 1,200, output 340 — the instrumentation re-attached the *originating* model's usage to the tool span "for correlation." - Turn 2 `chat` span: input 1,900 (1,200 + 340 + tool result), output 210. - Turn 3 `chat` span: input 2,400, output 180. The backend's cost aggregator, which sums `gen_ai.usage.input_tokens` across all spans in the trace (the natural implementation, since leaf operations are supposed to be the only carriers), computed input = 1,200 + 1,200 + 1,900 + 2,400 = 6,700. The true model input consumption was 1,200 + 1,900 + 2,400 = 5,500. The 1,200-token discrepancy is exactly the re-attached tool-span usage. On a 40-turn agent trace with a 4,000-token system prompt re-sent each turn, the overcount reached 156,000 input tokens — a 39× inflation of the reported prompt cost against a true 4,000-token prompt. The second observation: the `execute_tool` span's `gen_ai.tool.call.id` was a fresh UUID generated at emit time, while the `chat` span that produced the call recorded the model's `tool_call_id` in its output message. The two IDs did not match, so the trace could not be de-duplicated by call ID even if the aggregator had tried. The correlation key that would have made the double-count detectable was itself broken by the instrumentation. ## Condition of Validity The invariant that must hold: **for any trace, `sum(gen_ai.usage.input_tokens over spans where gen_ai.operation.name in {chat, text_completion, embeddings}) == true model input consumption`**, and **no span with `gen_ai.operation.name == execute_tool` may carry `gen_ai.usage.*` attributes.** This is valid only when: 1. Usage attributes appear exclusively on operation spans that represent an actual model round-trip (`chat`, `text_completion`, `embeddings`, `generate_content`). 2. Tool spans carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.description`, and argument/result payloads — never usage. 3. The `gen_ai.tool.call.id` on the tool span equals the `tool_call_id` in the originating chat span's output, so any aggregator can join and detect re-attachment. 4. Retried tool calls (a tool span re-emitted after a timeout) reuse the same `gen_ai.tool.call.id` and do not spawn a second usage-bearing span. The invariant is *invalid* — and the instance must refuse to close the trace as conformant — when any `execute_tool` span carries a non-zero `gen_ai.usage.input_tokens` or `output_tokens`, or when a tool span's `call.id` does not resolve to a `tool_call_id` present in some chat span's output within the same trace. ## Decision Boundary At span-close time, the emitting instance must evaluate a single predicate before finalizing the span: - If `operation.name == execute_tool` and (`usage.input_tokens > 0` or `usage.output_tokens > 0`): **do not emit usage; raise and drop the attributes**, because the usage belongs to the parent chat span and re-attaching it guarantees downstream double-counting. - If `operation.name == execute_tool` and `tool.call.id` is not present in the set of `tool_call_id`s observed in any sibling chat span's output: **the tool span is orphaned** — it represents either a retry that lost its correlation or a fabricated call. Emit it with `gen_ai.tool.call.id` preserved but flag it; do not let it participate in usage aggregation. - If `operation.name == chat` and the span emitted one or more tool calls: usage **must** be recorded here, and only here, for the turn that produced the calls. The tool spans are children for structure, not for accounting. The boundary is sharp: the moment an `execute_tool` span acquires usage attributes, the trace's token total becomes a function of tool-call count rather than model consumption, and every downstream cost, budget, and rate-limit decision derived from it is wrong by a factor proportional to fan-out. ## Operational Effect An agent that violates this invariant does not fail loudly. It produces conformant-looking spans, passes schema validation, and silently inflates cost attribution. The operational consequences compound: - **Budget enforcement misfires.** A token-budget guard that reads aggregated trace usage will trip at ~1/N of the true budget on an N-tool-call turn, halting agents that have consumed a fraction of their allowance. Conversely, if the guard reads only the root span (which carries zero usage per convention), it never trips at all. - **Retry storms become invisible.** Because retried tool spans reuse or regenerate call IDs inconsistently, the double-count masks the retry count — a tool that times out and retries three times appears as one call with 4× usage rather than four calls, hiding the latency/error signal that should have triggered a circuit breaker. - **Cross-instance handoff corrupts accounting.** When a child agent receives a baton and re-emits the parent's tool spans into its own trace (a common A2A state-transfer shortcut), the usage is counted once per instance. A three-hop handoff inflates the same tool turn's cost by 3×, and no single instance observes the full trace to detect it. The guardrail is architectural, not advisory: usage attributes are write-once at the operation span, tool spans are usage-free by construction, and the `tool.call.id` ↔ `tool_call_id` join is enforced at emit time with a hard failure that prevents the span from closing into a conformant trace. The instance must treat a usage-bearing tool span as a trace-integrity violation, not a cosmetic one. ```python from dataclasses import dataclass, field class GenAISpanInvariantError(RuntimeError): """Raised when a span would violate the GenAI token-accounting invariant.""" pass @dataclass class Span: operation_name: str attributes: dict = field(default_factory=dict) tool_call_ids_seen: set = field(default_factory=set) def close_span(span: Span) -> Span: usage_keys = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") has_usage = any(span.attributes.get(k, 0) for k in usage_keys) if span.operation_name == "execute_tool" and has_usage: raise GenAISpanInvariantError( f"execute_tool span carries usage attributes {span.attributes}; " "usage belongs to the originating chat span and re-attaching it " "double-counts every tool-call turn in trace aggregation." ) if span.operation_name == "execute_tool": call_id = span.attributes.get("gen_ai.tool.call.id") if call_id is None: raise GenAISpanInvariantError( "execute_tool span missing gen_ai.tool.call.id; cannot join " "to originating chat span, orphaned tool call." ) if call_id not in span.tool_call_ids_seen: raise GenAISpanInvariantError( f"execute_tool span call.id={call_id} does not resolve to any " "tool_call_id in sibling chat span output; retry or fabricated " "call — must not participate in usage aggregation." ) return span def aggregate_input_tokens(spans: list[Span]) -> int: total = 0 for s in spans: if s.operation_name in ("chat", "text_completion", "embeddings"): total += s.attributes.get("gen_ai.usage.input_tokens", 0) return total ```