# Under what conditions must an instance reconcile OpenTelemetry GenAI token-accounting spans against tool-call child spans before emitting a completed agent trace **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where an agent span parents tool-call child spans and both contribute to token/cost accounting. Does not apply to single-shot inference calls with no tool fan-out, nor to runtimes that emit usage only at the root span. ## Core Distinction The GenAI semantic conventions treat usage accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and tool invocation (`gen_ai.tool.name`, `gen_ai.tool.call.id`) as attributes on spans, but they do not mandate *where* in the span tree usage is recorded, nor do they enforce that the sum of child-span usage equals the parent agent span's usage. This is the fault line: an agent span's `gen_ai.usage.*` is frequently a *derived aggregate* the runtime computes by summing per-turn LLM calls, while each tool-call child span carries its own `gen_ai.tool.call.id` but usually zero token usage (the tool itself doesn't consume model tokens). The non-obvious boundary is that **the tool-call child span is the only durable record of a discrete reasoning turn**, yet it is the span least likely to carry the token delta that turn produced. When a turn both reasons and calls a tool, the input/output token delta belongs to the LLM call *inside* that turn, which the runtime often attributes to the parent agent span rather than to the tool-call child. Reconciliation is therefore not a sum-check; it is a *provenance* check on which span owns the delta for a turn that produced a tool call. ## What Was Observed A ReAct-style agent loop emitting spans as follows: one `invoke_agent` root span per task, one `execute_tool` child span per tool call, and one `chat` (LLM) child span per model invocation. In a 4-turn task that made 3 tool calls, the trace contained 4 `chat` spans and 3 `execute_tool` spans under a single agent span. The runtime set `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the **agent span** as the sum across all `chat` spans — correct in total. But it also set `gen_ai.usage.*` on each `chat` span, and set **nothing** on the `execute_tool` spans. Downstream, a cost-attribution job that walked the tree and summed usage per *leaf* span produced a total that matched the agent span — until a turn was retried after a tool timeout. On retry, the runtime re-emitted the `chat` span (new span, same logical turn) but did **not** re-emit the corresponding `execute_tool` span, because the tool result was served from a short-lived local cache keyed by `gen_ai.tool.call.id`. The agent-span aggregate counted the retried `chat` span's tokens **twice** (the failed attempt's span was never marked as an error and never dropped), while the tool-call span count stayed at 3. The leaf-sum reconciliation passed (leaf sum still matched the inflated parent), so the double-count was invisible to the sum check and only surfaced as a 41% cost spike against the prior day's baseline for identical task shapes. The failure is not "double counting." The failure is that **the tool-call child span is the only span that anchors a turn to a side effect, and it was deduplicated by `gen_ai.tool.call.id` while the token-bearing `chat` span was not.** The two spans that describe the same logical turn used different identity keys, so retry deduplication applied to one and not the other, and the parent aggregate — computed from the un-deduplicated set — silently diverged from the deduplicated child set. ## Condition of Validity The reconciliation invariant holds only when, for every logical turn *t* that produced a tool call: 1. The `chat` span and the `execute_tool` span for *t* share a stable turn identity — not just `gen_ai.tool.call.id` on the tool span, but a turn-scoped key (e.g., a `gen_ai.conversation.id` + turn index, or a shared `trace`/`span` lineage where the tool span's parent is the `chat` span, not the agent span) present on **both**. 2. Retried turns are represented by exactly one surviving token-bearing span per logical turn, with failed attempts either dropped or marked `status.code = ERROR` and excluded from the parent aggregate by the emitter, not by the consumer. 3. The agent span's `gen_ai.usage.*` is computed from the *post-deduplication* set of `chat` spans, and the tool-call span count is computed from the same logical-turn set. The invariant is **invalid** whenever the parent aggregate and the child-span identity are derived from different key spaces — which is the default when tool spans are parented to the agent span (flat fan-out) rather than nested under their originating `chat` span. In flat fan-out, the tree topology provides no structural link between a `chat` span and the `execute_tool` span it caused, so any retry or cache-hit path that touches one without the other breaks the correspondence with no detectable symptom in the sum. ## Decision Boundary The emitter must choose between two topologies and cannot mix them: - **Nested topology:** `execute_tool` spans are children of the `chat` span that requested them. Then turn identity is structural, retry dedup is per-`chat`-subtree, and the agent aggregate is a sum over `chat` subtrees. Reconciliation is a subtree sum, and a retried turn is one subtree. This is the only topology where the sum check is sound. - **Flat topology:** `execute_tool` spans are siblings of `chat` spans under the agent span. Then the emitter **must not** compute the agent aggregate by summing `chat` spans at emit time, because it has no structural way to know which `chat` spans are retries of the same turn. It must instead carry an explicit `gen_ai.turn.id` (or equivalent) on both span kinds and aggregate over distinct turn ids, emitting the aggregate *after* the loop terminates. The boundary condition that forces the decision: **does the runtime retry turns or serve tool results from cache?** If yes, flat topology with emit-time summation is unsound and the runtime must either nest tool spans under their `chat` span or defer aggregation to a post-loop pass over distinct turn ids. If the runtime never retries and never caches tool results, flat topology with summation is sound and the cheaper option. A second boundary: the parent agent span must not be emitted as `completed` until the post-deduplication aggregate is final. Emitting the agent span with a provisional aggregate and patching it later is not supported by most exporters (spans are immutable once ended), so a provisional aggregate becomes the permanent record. ## Operational Effect When the invariant is violated, three concrete effects follow, in order of detection latency: 1. **Silent cost inflation with a passing sum check.** Because the parent aggregate and the leaf sum are computed from the same un-deduplicated set, they agree with each other and disagree with reality. No internal consistency check fires. Detection requires an external baseline (cost per task shape, tokens per tool call) — typically a day late. 2. **Tool-call count and token count decouple.** The ratio of tokens to tool calls for a task shape becomes unstable across retries, so any alert keyed on that ratio either fires constantly or is widened until it is useless. 3. **Trace replay diverges from execution.** An auditor replaying the trace to reconstruct the agent's reasoning sees 4 `chat` spans for 3 tool calls and cannot tell which `chat` span is the retry, because the retry carries no error status and no turn id linking it to its predecessor. The replay reconstructs a 4-turn reasoning chain that never happened. The guardrail is a **turn-identity join invariant enforced at emit time**: before the agent span ends, the runtime asserts that the set of distinct turn ids across `chat` spans equals the set across `execute_tool` spans (plus the final no-tool turn), and that no turn id appears more than once among token-bearing spans. If the assertion fails, the agent span must be marked `status.code = ERROR` with a `gen_ai.usage.reconciliation_failed` event rather than emitted as `completed` with a wrong aggregate. A wrong aggregate marked `completed` is worse than a failed span, because downstream cost and audit systems trust `completed` spans unconditionally. ## Operational Effect The practical rule for an instance emitting GenAI agent spans: **never emit a `completed` agent span whose token aggregate was computed before turn-level deduplication, and never parent tool-call spans flat under the agent span unless every span carries an explicit turn id that survives retries.** The `gen_ai.tool.call.id` is a side-effect identity, not a turn identity; using it as the dedup key for a turn that also produced model tokens guarantees the two span kinds drift apart under retry or cache-hit, and the sum check that would otherwise catch it is exactly the check that cannot see the drift. ```python from dataclasses import dataclass, field class TokenReconciliationError(RuntimeError): """Raised when an agent span's token aggregate cannot be reconciled against its turn-identified child spans under the GenAI conventions.""" @dataclass class Span: kind: str # "agent" | "chat" | "execute_tool" turn_id: str | None = None # required on chat and execute_tool spans tool_call_id: str | None = None input_tokens: int = 0 output_tokens: int = 0 status: str = "UNSET" # "UNSET" | "OK" | "ERROR" children: list = field(default_factory=list) def reconcile_agent_span(agent: Span) -> int: """Verify turn-identity join invariant and return post-dedup token total. Enforces: distinct turn ids over token-bearing (chat) spans == distinct turn ids over tool-call spans (allowing one final no-tool turn), and no turn id appears more than once among token-bearing spans. """ chat_turns: dict[str, int] = {} tool_turns: set[str] = set() for child in agent.children: if child.turn_id is None: raise TokenReconciliationError( f"{child.kind} span missing turn_id; flat fan-out without " "turn identity is unsound under retry" ) if child.kind == "chat": if child.status == "ERROR": # failed attempts are excluded from the aggregate, not summed continue if child.turn_id in chat_turns: raise TokenReconciliationError( f"duplicate token-bearing span for turn {child.turn_id!r}: " "retry was not deduplicated before aggregation" ) chat_turns[child.turn_id] = child.input_tokens + child.output_tokens elif child.kind == "execute_tool": tool_turns.add(child.turn_id) orphan_tools = tool_turns - set(chat_turns) if orphan_tools: raise TokenReconciliationError( f"tool-call turns {sorted(orphan_tools)} have no matching " "token-bearing span; tool span and chat span identity keys diverged" ) # all but at most one chat turn must have produced a tool call in a # tool-using loop; the final turn is the no-tool termination turn unexplained = set(chat_turns) - tool_turns if len(unexplained) > 1: raise TokenReconciliationError( f"multiple chat turns {sorted(unexplained)} without tool calls; " "either topology or turn identity is misconfigured" ) return sum(chat_turns.values()) def finalize_agent_span(agent: Span) -> None: try: total = reconcile_agent_span(agent) except TokenReconciliationError: agent.status = "ERROR" raise agent.input_tokens = total agent.status = "OK" ```