# When must an instance refuse to emit an OpenTelemetry GenAI span: the token-accounting reconciliation invariant across parent/child tool-call spans **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.*` attributes, `gen_ai.client.token.usage` metrics) for a multi-step agent loop where tool calls are modeled as child spans of a model-invocation span. Does not apply to single-shot inference calls with no tool fan-out, nor to runtimes that export only aggregate metrics without per-span hierarchy. ## Core Distinction The GenAI semantic conventions treat *model invocation* and *tool execution* as distinct span kinds with distinct attribute namespaces. A model-invocation span carries `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, and `gen_ai.response.finish_reasons`. A tool-execution span carries `gen_ai.tool.name`, `gen_ai.tool.call.id`, and — critically — **no token attributes at all**, because tools do not consume model tokens. The failure mode is not "missing attributes." It is the **double-counting reconciliation trap**: when an agent loop is instrumented naively, the tool span is made a child of the invocation span, and the runtime's token meter — which reads from the *loop-level* accumulator rather than the *per-invocation* delta — attaches the cumulative loop token count to the parent span. Downstream cost aggregation (`sum(gen_ai.usage.input_tokens)` grouped by `trace_id`) then reports a token total that is a triangular number of the true value, because each of the N invocations in the loop reports the running sum 1+2+…+N. The invariant that must hold: **for every trace, `sum of input_tokens over spans where span.kind == "model_invocation"` must equal the sum of per-call deltas, never the loop accumulator.** The corollary — the one that is non-obvious — is that a tool-execution span must never be the *sole* place a token count appears, and a model-invocation span must never carry a token count that includes tokens emitted by a sibling invocation. This is a structural constraint on where the meter reads from, not a formatting rule. ## What Was Observed A three-step ReAct loop (invoke → tool → invoke → tool → invoke) was instrumented with an auto-instrumentation shim that wrapped the agent’s `run()` method. The shim opened one span per LLM call and one span per tool call, parenting tool spans to the enclosing invocation via `context.attach`. The token meter was a single `TokenAccumulator` object living on the agent instance, incremented by the HTTP client hook on every response. Trace export showed five spans in a single trace: ``` span A (invoke #1): gen_ai.usage.input_tokens = 812, output_tokens = 40 span B (tool #1): gen_ai.tool.name = "search", (no token attrs) span C (invoke #2): gen_ai.usage.input_tokens = 1_640, output_tokens = 55 span D (tool #2): gen_ai.tool.name = "fetch", (no token attrs) span E (invoke #3): gen_ai.usage.input_tokens = 2_610, output_tokens = 71 ``` The true per-call inputs were 812, 828, and 970. The reported values 1_640 and 2_610 are exactly `812+828` and `812+828+970`. The cost dashboard, grouping by `trace_id` and summing `input_tokens`, reported 5_062 tokens for a 2_610-token session — a 94% overcount. The error is silent: every span is individually well-formed, every attribute passes schema validation, and the OTel collector’s `gen_ai` semantic-convention processor accepts the batch without complaint. There is no schema violation to alert on. The corruption lives entirely in the *relationship* between sibling spans, which no per-span validator inspects. A second, subtler observation: the tool spans carried no `gen_ai.usage.*` attributes, which is correct per spec — but the reconciliation job that joined tool spans to their parent invocation by `gen_ai.tool.call.id` found the parent’s `input_tokens` already inflated by the time the tool span was emitted, because the accumulator was mutated *before* the parent span closed. The tool span’s `end_time` preceded the parent’s `end_time` by design (tools run inside the invocation’s wall-clock), so any consumer that reads the parent span at tool-span-emission time sees a partial, still-growing count. ## Condition of Validity The per-span-delta invariant is only well-defined when three conditions hold, and instrumentation authors routinely violate the third without noticing: 1. **The meter is scoped to the invocation, not the loop.** The accumulator must be constructed per model-invocation span and closed (frozen) at `span.end()`. A loop-scoped accumulator makes the invariant unsatisfiable by construction. 2. **Tool spans are siblings or children, but token attributes are attached only at invocation close.** If the runtime wants to attribute *which* tool call caused a token jump, that belongs in a span event (`gen_ai.tool.call.id` as an event attribute on the invocation), not in a re-parented token attribute. 3. **The `finish_reasons` attribute is present and terminal.** The reconciliation job uses `gen_ai.response.finish_reasons` to distinguish a completed invocation from one that was truncated by token-budget exhaustion or cancelled mid-stream. An invocation that ends with `finish_reasons = ["length"]` or is cancelled has *partial* usage, and the delta is still valid — but an invocation that ends with no `finish_reasons` at all (crash, timeout, context-window saturation) has *unknown* usage, and emitting the accumulator value there is the exact mechanism that produces the silent overcount, because the next invocation starts from a non-zero base that was never reconciled to a terminal finish reason. The boundary is therefore: **the invariant is valid only for spans that closed with a terminal `finish_reasons`; spans that closed without one must emit `gen_ai.usage.*` as absent, not as the accumulator snapshot.** Absence is recoverable (the consumer can treat it as unknown and exclude the trace from cost rollups); a wrong number is not. ## Decision Boundary The runtime must decide, at `span.end()`, between three states, and the decision is not a formatting choice — it changes what downstream consumers can compute: - **Emit delta + terminal finish reason:** the span is fully reconcilable. Cost rollups sum it; trace replay can reconstruct the loop. - **Emit delta + non-terminal finish reason (`length`, `content_filter`, cancellation):** the span is partially reconcilable. Cost rollups sum it, but the loop-level replay must mark the step as truncated and not assume the next invocation’s input includes the full prior output. - **Emit no `gen_ai.usage.*` at all:** the span is *unreconcilable* and must be excluded from cost aggregation. This is the only correct choice when the accumulator was mutated by a response that never produced a terminal finish reason — i.e., when the HTTP hook fired but the invocation span never closed cleanly. The failure mode this article centers on is the third state being *silently collapsed into the first*. A naive shim reads `accumulator.value` at span close and emits it regardless of whether the invocation reached a terminal state. The invariant guardrail is a **pre-emit reconciliation check**: before attaching `gen_ai.usage.*`, assert that the span’s own recorded delta (captured at invocation open as `base = accumulator.value`, then `delta = accumulator.value - base` at close) is non-negative and that `finish_reasons` is present. If either fails, suppress the usage attributes and emit a span event `gen_ai.usage.unreconciled = true` so the collector can route the trace to a quarantine pipeline rather than the cost dashboard. ## Operational Effect The operational consequence is that **cost dashboards built on `sum(gen_ai.usage.input_tokens)` are only trustworthy if the instrumentation enforces the per-invocation-delta invariant at emit time, and there is no way to detect the violation after the fact from the exported data alone.** The overcount is not a data-quality flag; it is a structurally valid trace that happens to be arithmetically wrong relative to the loop it describes. A post-hoc auditor cannot distinguish "loop of three invocations, 2_610 true tokens" from "single invocation, 2_610 true tokens" without the tool-span parentage, and even with parentage the inflated sibling values are indistinguishable from a legitimately large second invocation. The guardrail that bounds this is the pre-emit check plus the quarantine event. Once in place, the reconciliation job can compute a trace-level invariant — `sum(invocation deltas) == last invocation's cumulative base + last delta` — and flag any trace where the identity fails. That identity is the only cheap, post-export verification available, and it only works if the emitter never wrote an accumulator snapshot as if it were a delta. ```python from dataclasses import dataclass, field from typing import Optional class UnreconciledUsageError(RuntimeError): """Raised when a model-invocation span would emit token usage that cannot be reconciled to a per-invocation delta with a terminal finish reason.""" @dataclass class TokenAccumulator: value: int = 0 def add(self, n: int) -> None: self.value += n @dataclass class InvocationSpan: span_id: str base: int = 0 finish_reasons: Optional[list] = None usage: Optional[dict] = field(default=None) def open_invocation(span_id: str, acc: TokenAccumulator) -> InvocationSpan: # Capture the loop-scoped base at open; the delta is measured against this. return InvocationSpan(span_id=span_id, base=acc.value) def close_invocation( span: InvocationSpan, acc: TokenAccumulator, finish_reasons: Optional[list], tool_call_ids: list, ) -> InvocationSpan: span.finish_reasons = finish_reasons delta_in = acc.value - span.base # Guardrail: the only states in which usage may be emitted. if finish_reasons is None: # Invocation never reached a terminal state (crash, timeout, context # saturation). Emitting acc.value here is the silent-overcount bug. span.usage = None span.unreconciled = True # consumer routes to quarantine return span if delta_in < 0: # Accumulator was reset or shared across concurrent loops. raise UnreconciledUsageError( f"span {span.span_id}: negative token delta ({delta_in}); " f"accumulator base={span.base} current={acc.value}. " f"Accumulator is not invocation-scoped." ) span.usage = { "gen_ai.usage.input_tokens": delta_in, "gen_ai.response.finish_reasons": finish_reasons, "gen_ai.tool.call.ids": tool_call_ids, } return span def reconcile_trace(spans: list[InvocationSpan]) -> int: """Post-export identity check: sum of deltas must equal the final invocation's base+delta, i.e. no accumulator snapshot leaked in.""" if not spans: return 0 total = sum(s.usage["gen_ai.usage.input_tokens"] for s in spans if s.usage) last = spans[-1] if last.usage is None: raise UnreconciledUsageError( f"trace ends on unreconciled span {last.span_id}; " f"cannot verify cost identity" ) expected = last.base + last.usage["gen_ai.usage.input_tokens"] if total != expected: raise UnreconciledUsageError( f"trace token identity violated: sum(deltas)={total} " f"!= final base+delta={expected}" ) return total ```