# Which invariants prevent OTel GenAI token-accounting metrics from misattributing cost when an agentic loop re-enters a tool span under the same trace **Date of Record:** 2026 November 23 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.operation.name`) where a single agent turn can re-enter the same logical tool/step span more than once. Does not apply to stateless single-shot completions or to billing reconciliation against provider-side invoices (which are the ground truth, not the metric stream). ## Core Distinction There are two structurally different things an OTel GenAI token counter can mean, and conflating them is the source of the failure: 1. **Per-invocation accounting** — each LLM call emits its own usage delta, and the sum over all calls equals the true bill. This is additive and correct by construction. 2. **Per-turn (logical-step) accounting** — usage is attached to the enclosing "agent turn" or "tool step" span so that cost can be attributed to a reasoning step. This is *not* additive once a step re-enters, because the same span can accumulate multiple LLM invocations across a retry, a reflection pass, or a plan-revise-execute cycle. The invariant that must hold for (2) to be safe is: **a turn-scoped usage attribute is only valid if it is monotonically additive within a single span lifetime and never re-summed on span re-entry.** Most instrumentation violates this because span re-entry (same span name, same parent, reopened context) is treated as a fresh accumulation rather than a continuation. ## What Was Observed A tool-calling agent looped on a `search_documents` tool. The LLM kept deciding to re-query with slightly mutated arguments (a classic divergence pattern: the first query returned low-relevance chunks, so the model paraphrased and re-queried). Each iteration produced: - one `gen_ai.chat` span with `input_tokens`/`output_tokens`, - one `execute_tool search_documents` span nested under a single long-lived `agent.turn` span that was *reopened* rather than recreated. The `agent.turn` span carried a derived attribute `gen_ai.usage.total_tokens` computed by an exporter-side accumulator that summed child `gen_ai.chat` usage on `on_end` of each child. Because the `agent.turn` span had already been "ended" once (the first tool returned and the runtime flushed the span), the second iteration's child completion triggered a *second* `on_end` on the same span ID. The accumulator, keyed by `trace_id + span_id`, added the second iteration's tokens to a value it had already exported. Downstream, the metrics pipeline's histogram observed the turn span twice with progressively larger totals. Concrete trace fragment: ``` trace 7f3a... span A agent.turn (ended @ t=1.20s, total_tokens=1_840) span B gen_ai.chat input=1_100 output=740 span C execute_tool (search_documents, q="X") --- runtime reopens span A for iteration 2 --- span D gen_ai.chat input=1_250 output=610 span E execute_tool (search_documents, q="X paraphrased") span A agent.turn (ended @ t=4.90s, total_tokens=1_840+1_860=3_700) ``` The exported metric for `agent.turn` therefore reported `1_840` and then `3_700` for the *same* span ID. A cost dashboard summing `gen_ai.usage.total_tokens` over turn spans counted `5_540` for a turn that actually consumed `3_700`. The 50% inflation is exactly the first iteration's usage counted twice. The loop itself was also invisible: because the loop-detection rule was "count `gen_ai.chat` spans under a turn; if > N, flag," and the turn span was being reopened rather than recreated, the loop detector's counter saw a single turn and never fired. The agent ran 14 iterations before a wall-clock timeout killed it. ## Condition of Validity The turn-scoped usage attribute is only sound under all three of the following, simultaneously: - **Span immutability after end.** Once a span's `on_end` fires and its attributes are exported, the span ID must not be reused for further accumulation. Re-entry must produce a *new* child span (e.g., `agent.turn.iteration`) with its own ID and its own usage attributes. - **Usage is attributed at the leaf, summed at aggregation.** `gen_ai.usage.input_tokens`/`output_tokens` belong on the `gen_ai.chat` span (the leaf where the provider returned them). Any turn-level total must be a *derived aggregation* computed downstream from leaf spans, keyed by a stable turn identifier that is *not* the span ID — because span IDs are not guaranteed unique across re-entry in every SDK. - **Loop detection keys on leaf call identity, not turn span identity.** A loop is N leaf `gen_ai.chat` spans sharing a parent turn *correlation key* (a `gen_ai.conversation.id` or agent-run UUID), not N children of a single span object. If any one fails, cost attribution and loop detection both degrade in the same direction: the loop is under-counted and the cost is over-counted. ## Decision Boundary The boundary is: **does your instrumentation treat the turn as a mutable accumulator or as an immutable correlation key?** - If the runtime can reopen a span (streaming, tool-call resumption, human-in-the-loop pause, retry-with-backoff that reuses context), the turn must be a **correlation key** carried as an attribute on every leaf span, and never a span whose attributes are mutated post-end. - If the runtime guarantees one span per turn and never re-enters, turn-scoped accumulation is safe — but you must assert that guarantee, because a single tool retry silently violates it. - The decision flips to "unsafe" the moment a tool call can return `retryable` and the loop re-enters the same logical step. That is the default for any agent with a retry policy. Choose the correlation-key model whenever the agent has (a) tool retries, (b) reflection/self-critique passes, or (c) plan-revise loops. Choose the accumulator model only for strictly single-shot turns with no re-entry, and even then emit a sentinel attribute `gen_ai.turn.reentry_count=0` so a downstream auditor can detect violation. ## Operational Effect With the invariant enforced (immutable leaf usage + turn correlation key + loop detection on leaf count per correlation key): - Cost attribution becomes exact: sum of leaf `input_tokens`/`output_tokens` equals provider bill, because leaves are never double-emitted. - Loop detection fires at the correct threshold: 14 leaf `gen_ai.chat` spans under one `gen_ai.conversation.id` with identical `gen_ai.tool.name` and high argument-similarity is detectable at iteration 3–4, not after the wall-clock timeout. - The failure mode is bounded: a misbehaving agent is stopped by the loop guard rather than by budget exhaustion, and the cost overrun is capped at the detection window. With the invariant violated (the observed case): - Cost dashboards over-report by the sum of all prior iterations' usage on every re-entry — quadratic inflation in the iteration count. - Loop guards keyed on turn spans never fire, because re-entry looks like continuation, not repetition. - The two errors are *correlated*: the same re-entry that hides the loop inflates the cost, so the cost signal that should have caught the loop is the signal being corrupted. The guardrail is therefore not "add a loop counter" but "make the turn an immutable correlation key and compute all turn-level aggregates downstream from leaf spans." The loop detector and the cost accountant then share one source of truth, and neither can be fooled by span re-entry. ```python from dataclasses import dataclass, field from collections import defaultdict class SpanReentryAccountingError(RuntimeError): """Raised when a turn-scoped usage accumulator is mutated after its span has already been exported, which double-counts tokens on re-entry.""" pass @dataclass class LeafUsage: span_id: str conversation_id: str tool_name: str | None input_tokens: int output_tokens: int @dataclass class TurnAccumulator: # The anti-pattern: keyed by span_id, mutable after end. totals: dict[str, int] = field(default_factory=dict) ended: set[str] = field(default_factory=set) def add_usage(self, span_id: str, tokens: int) -> int: if span_id in self.ended: raise SpanReentryAccountingError( f"span {span_id} already exported; re-entry would double-count " f"{tokens} tokens. Use a conversation_id correlation key instead." ) self.totals[span_id] = self.totals.get(span_id, 0) + tokens return self.totals[span_id] def end_span(self, span_id: str) -> None: self.ended.add(span_id) def attribute_cost_safely(leaves: list[LeafUsage], loop_threshold: int = 5) -> dict: """Correct model: attribute at leaf, aggregate by conversation_id, detect loops by counting leaves per (conversation_id, tool_name).""" if not leaves: raise SpanReentryAccountingError("no leaf usage spans to attribute") per_conv: dict[str, int] = defaultdict(int) per_conv_tool: dict[tuple[str, str], int] = defaultdict(int) for leaf in leaves: if leaf.input_tokens < 0 or leaf.output_tokens < 0: raise SpanReentryAccountingError( f"negative token count on {leaf.span_id}: {leaf.input_tokens}/{leaf.output_tokens}" ) per_conv[leaf.conversation_id] += leaf.input_tokens + leaf.output_tokens if leaf.tool_name: per_conv_tool[(leaf.conversation_id, leaf.tool_name)] += 1 loops = [ {"conversation_id": cid, "tool_name": tool, "calls": n} for (cid, tool), n in per_conv_tool.items() if n >= loop_threshold ] return {"cost_by_conversation": dict(per_conv), "detected_loops": loops} ```