# How does an instance detect that its GenAI span accounting has diverged from the tool-call reality it reports? **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) around LLM invocations and tool calls, where a parent agent span aggregates child `execute_tool` spans and token usage is attributed per span. Does not apply to single-shot inference services with no tool-call fan-out and no cross-span aggregation. ## Core Distinction The GenAI semantic conventions define two *independent* accounting surfaces on the same span tree: **structural attributes** (span nesting, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, parent/child linkage) and **quantitative attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and per-tool `gen_ai.tool.call.*` counters). These two surfaces are produced by different code paths — the tracer emits structure; the tokenizer/billing layer emits quantities — and nothing in the spec forces them to reconcile. The non-obvious invariant is this: **a parent agent span's `gen_ai.usage.*` totals are a *claim about the sum of its children*, but the children are emitted asynchronously and may be dropped, retried, or duplicated by the exporter.** The span is therefore internally consistent (it is a well-formed span with valid attributes) while being *externally inconsistent* with the child spans it purports to summarize. An agent cannot detect this by validating any single span. It can only detect it by reconciling the parent's declared totals against the reconstructed child set — and that reconstruction is exactly what the exporter's own lossiness breaks. This is distinct from a token-budget exhaustion failure (the agent *knows* it ran out) and distinct from context-window saturation (the model sees a truncated prompt). Here the agent believes its accounting is correct; the divergence is silent and lives in the telemetry, not the reasoning loop. ## What Was Observed A multi-tool agent loop (planner → 3 parallel `execute_tool` children → synthesis) emitted the following on a normal run: - Parent span `agent.turn` with `gen_ai.usage.input_tokens=11842`, `gen_ai.usage.output_tokens=590`. - Three child spans `execute_tool` with `gen_ai.tool.name ∈ {search, fetch, calc}`, each carrying `gen_ai.tool.call.id`. - The synthesis step re-invoked `fetch` with a *new* `gen_ai.tool.call.id` because the first fetch returned a partial result and the planner retried. The retry is the trigger. Two failure traces were observed depending on exporter timing: **Trace A — child dropped, parent retains total.** The first `fetch` child span ended in `ERROR` status and was sampled out by a tail-sampling processor configured to keep only `OK` tool spans. The parent's `output_tokens` still counted the planner's re-planning tokens for the retry, but the *structural* child that justified those tokens no longer exists in the exported trace. Reconstructing `sum(child.usage) ≠ parent.usage`. The delta (≈ 1,400 input tokens) is unattributable: no child span explains it. **Trace B — child duplicated, parent undercounts.** The `fetch` child span was exported twice: once on completion and once on a batch-flush retry after a collector 503. Both copies carry the same `gen_ai.tool.call.id` but distinct `span_id`s. A naive reconciler that sums child `input_tokens` now *over*-counts by one fetch, making `sum(child) > parent`. The agent's own accounting says it used fewer tokens than the trace claims it used. In both traces every individual span passed schema validation. `gen_ai.operation.name` was present, `gen_ai.tool.call.id` was well-formed, usage attributes were integers. The divergence existed only in the *relation* between spans, and the relation was corrupted by sampling (Trace A) and by at-least-once delivery (Trace B) — neither of which the GenAI conventions constrain. ## Condition of Validity The invariant "parent `gen_ai.usage.*` equals the reconciled sum of child usage" holds **only if all three of the following are true**: 1. **No child is sampled out independently of its parent.** Tail-sampling decisions must be made on the *root* of the agent turn and applied to the whole subtree. Per-span sampling on `execute_tool` spans violates this, because the parent's token total was computed before sampling and is not recomputed. 2. **`gen_ai.tool.call.id` is unique per logical invocation and stable across retries of the *same* invocation.** A planner that mints a fresh `call.id` for a semantic retry (Trace A) is correct per spec but breaks the reconciler's ability to distinguish "retry of fetch" from "second fetch." The reconciler must key on `call.id`, not on `tool.name`, or it will merge distinct invocations. 3. **The exporter provides at-least-once with idempotent dedup on `(trace_id, span_id)`.** Without dedup, batch-flush retries (Trace B) inflate child sums. The GenAI conventions say nothing about delivery semantics; this is inherited from the OTLP transport and must be asserted separately. When any condition fails, the parent span is a *lossy summary*, and any downstream consumer — a billing reconciler, a cost dashboard, a self-auditing agent — that treats it as exact will drift. The agent itself cannot know which condition failed from the span data alone; it can only detect *that* a divergence exists. ## Decision Boundary The agent runtime should treat the parent/child accounting relation as **advisory, not authoritative**, and must run a reconciliation check at turn close. The boundary: - If `|parent.usage − sum(dedup(child.usage))| / parent.usage ≤ ε` (ε ≈ 0.02 for tokenizer jitter), the parent total is trusted and the turn is sealed. - If the delta exceeds ε **and** the child set is structurally complete (every `gen_ai.tool.call.id` referenced by the planner's plan is present exactly once), the divergence is a *tokenizer/retry accounting* issue: seal the turn but flag `accounting_divergence=true` and record the delta as an unattributed bucket. - If the delta exceeds ε **and** the child set is structurally incomplete (a planned `call.id` is missing from exported spans), the turn must **not** be sealed. This is the Trace A condition: the agent cannot certify its own cost or its own tool-call history. The runtime must either force-flush and re-query the collector for the missing `call.id`, or mark the turn `unverifiable` and refuse to use its token totals for budget carry-forward into the next turn. The critical guardrail: **never reconcile by adjusting the parent to match children or vice versa.** Both are evidence; the divergence is the signal. Rewriting either side destroys the only record that the accounting broke. ## Operational Effect An agent that carries forward a corrupted token total into its next turn will mis-budget: it believes it has more (Trace B) or fewer (Trace A) tokens remaining than reality. In Trace B the agent under-reports spend and over-runs its budget silently; in Trace A it over-reports and truncates reasoning it could have afforded. Both are self-inflicted, both are invisible to the model, and both compound across turns because the carry-forward is the mechanism by which the error propagates. The architectural fix is to make the reconciliation check a *precondition* for budget carry-forward, not a post-hoc dashboard query. The agent must be able to answer, at turn close, "is my declared usage structurally supported by my exported tool-call spans?" — and when the answer is no, it must degrade to a conservative budget estimate (assume the higher of parent and reconciled-child totals) rather than trust either. The following guard implements the turn-close reconciliation and raises on the unverifiable condition rather than silently sealing. ```python from dataclasses import dataclass, field from typing import Iterable EPSILON = 0.02 # tokenizer jitter tolerance class UnverifiableAccountingError(RuntimeError): """Raised when a turn's token accounting cannot be reconciled to its tool-call spans.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # gen_ai.operation.name tool_call_id: str | None # gen_ai.tool.call.id input_tokens: int output_tokens: int @dataclass class Turn: parent: Span children: list[Span] = field(default_factory=list) planned_call_ids: set[str] = field(default_factory=set) def reconcile(turn: Turn) -> dict: # Dedup children on (span_id) to absorb at-least-once export retries (Trace B). seen: dict[str, Span] = {} for c in turn.children: seen.setdefault(c.span_id, c) children = list(seen.values()) # Structural completeness: every planned call.id must appear exactly once. present = [c.tool_call_id for c in children if c.tool_call_id] missing = turn.planned_call_ids - set(present) duplicated_calls = {cid for cid in present if present.count(cid) > 1} child_in = sum(c.input_tokens for c in children) child_out = sum(c.output_tokens for c in children) parent_total = turn.parent.input_tokens + turn.parent.output_tokens child_total = child_in + child_out delta = abs(parent_total - child_total) ratio = delta / parent_total if parent_total else 0.0 if ratio <= EPSILON: return {"status": "sealed", "delta": delta} if missing or duplicated_calls: # Trace A (missing) or Trace B (duplicated logical call): cannot certify. raise UnverifiableAccountingError( f"turn {turn.parent.span_id} accounting unverifiable: " f"missing_call_ids={sorted(missing)} " f"duplicated_calls={sorted(duplicated_calls)} " f"delta_tokens={delta} ratio={ratio:.3f}" ) # Structurally complete but delta too large: tokenizer/retry drift. return {"status": "sealed", "delta": delta, "accounting_divergence": True} def carry_forward_budget(turn: Turn, budget: int) -> int: try: result = reconcile(turn) except UnverifiableAccountingError: # Conservative: assume the larger of parent vs reconciled-child spend. spent = max( turn.parent.input_tokens + turn.parent.output_tokens, sum(c.input_tokens + c.output_tokens for c in turn.children), ) return budget - spent spent = turn.parent.input_tokens + turn.parent.output_tokens return budget - spent ```