# How does an instance detect span-attribute divergence between GenAI semantic conventions and its own tool-call ledger **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) per the emerging semantic conventions and simultaneously maintain an internal tool-call ledger used for replay, billing, or audit. Does not apply to single-shot LLM calls with no tool loop, nor to runtimes where the span is *derived from* the ledger at export time (there the invariant holds by construction). ## Core Distinction The GenAI semantic conventions describe spans as *observations* — each `gen_ai.operation.name` span is a point-in-time record of what the runtime believed it was doing when it emitted. The agent's tool-call ledger is a *transaction log* — it is the authoritative record of what the runtime committed to, including retries, aborted calls, and calls that never produced a span because the process died mid-export. The failure mode is not that either is wrong. It is that the two diverge silently and the divergence is *only* detectable by cross-referencing a field that neither system treats as a primary key: the tool-call correlation token. The non-obvious part: `gen_ai.tool.name` is a *class* attribute (e.g., `search`, `read_file`), not an *instance* attribute. Two consecutive `search` calls in one turn produce two spans with identical `gen_ai.tool.name`, identical `gen_ai.operation.name=execute_tool`, and — under the current conventions — often identical `gen_ai.tool.call.id` when the model reuses a call id across a retry. The ledger, by contrast, keys on a monotonic `call_seq`. Any audit that joins spans to ledger rows on tool name will double-count; any audit that joins on `call.id` will silently drop the retried call. The invariant that must hold is that **every ledger row with `state=COMMITTED` has exactly one span with `gen_ai.tool.call.id == ledger.call_id` and `gen_ai.usage.*` attributes consistent with the ledger's recorded token counts**, and that **every span with `gen_ai.operation.name=execute_tool` maps to exactly one ledger row** — including rows in `state=ABORTED`. ## What Was Observed A multi-tool agent (search + code interpreter + file reader) running under a supervisor that retries tool calls on transient transport errors. The runtime emitted spans via an OTel batch exporter with a 5s flush interval. The ledger committed synchronously on tool return. Trace of the divergence: 1. Turn 7, model emits `search(query="X")`. Runtime assigns `call_seq=41`, `call_id="call_a1"`. Ledger writes `state=PENDING`. 2. Transport to the search backend times out at 3s. Runtime marks `state=RETRYING`, emits span `S1` with `gen_ai.tool.call.id="call_a1"`, `gen_ai.tool.name="search"`, `status=ERROR`, `error.type="timeout"`. 3. Retry fires with the *same* `call_id` (the runtime reuses the model's call id, per spec guidance). Ledger writes `state=PENDING` again, `attempt=2`. Span `S2` emitted with identical `gen_ai.tool.call.id="call_a1"`, `status=OK`, `gen_ai.usage.output_tokens=0` (tool spans don't carry output tokens — only the parent `chat` span does). 4. The parent `chat` span `S0` for turn 7 carries `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=312`. The 312 includes tokens for the tool-call arguments of *both* attempts because the model regenerated the call on retry (the runtime fed the timeout back as a tool error and the model re-emitted). The ledger recorded 312 tokens against `call_seq=41` only, not `call_seq=41.attempt=2`. 5. At 5s the batch exporter flushed `S0`, `S1`, `S2`. The ledger had already committed `call_seq=41` with `attempt=2`, `tokens=312`. Downstream reconciliation joined on `gen_ai.tool.call.id` and found **two spans for one ledger row** (`S1`, `S2`) and **one ledger row for two token events** (312 counted once). The billing system, which summed `gen_ai.usage.output_tokens` across spans, recorded 312. The ledger, which the agent used for budget enforcement, recorded 312 against attempt 2 only and had already *pre-debited* attempt 1 at 156 tokens before the timeout. Net: the agent's own budget accounting was 156 tokens ahead of what the spans showed, and the divergence persisted across turns because the pre-debit was never reversed on retry. The instance could not detect this from spans alone. It could not detect it from the ledger alone. It detected it only when a *third* consumer — the budget enforcer — compared its running total against the sum of `gen_ai.usage.output_tokens` over the turn's spans and found a 156-token gap that did not correspond to any single span. ## Condition of Validity The reconciliation invariant holds only under three conditions, and the failure above violates the second: 1. **Span emission is at-least-once and ledger commit is exactly-once.** If the exporter drops a span (queue full, process exit), the ledger row exists with no span. This is *detectable*: ledger row `COMMITTED` with no matching span is a hard error. The reverse — span with no ledger row — happens when the runtime emits the span before the ledger commit (emit-then-commit ordering) and the process dies between. This is *undetectable* without a pre-commit span attribute carrying a provisional ledger key. 2. **Retry attempts are distinguishable in the span.** The current conventions do not mandate an attempt counter on tool spans. Without `gen_ai.tool.call.attempt` (or an equivalent), two spans sharing `call.id` are indistinguishable from a duplicate emission. The invariant "one span per ledger row" silently becomes "one-or-more spans per ledger row," and the token accounting that depends on counting spans breaks. 3. **Token accounting is attributed to the span that caused the spend.** Tool spans carry no `gen_ai.usage.*`; the parent `chat` span carries the aggregate. When the model regenerates a tool call on retry, the retry's tokens are folded into the parent's aggregate with no per-call attribution. The ledger's per-call token field is therefore *not* recoverable from spans, and the budget enforcer's cross-check is the only signal. The invariant is valid only when the runtime either (a) emits an attempt attribute on every tool span and reverses pre-debits on retry, or (b) treats the ledger as the sole source of truth for tokens and uses spans only for latency/error telemetry, never for accounting. ## Decision Boundary The instance must decide, per tool call, whether it is in **telemetry-authoritative** mode or **ledger-authoritative** mode, and it must not mix them within a turn. - **Telemetry-authoritative** is correct when the span is emitted synchronously and the exporter is configured with `OTEL_BSP_MAX_QUEUE_SIZE` large enough that no span is dropped, and when the runtime does *not* retry with a reused `call.id`. In this mode, reconciliation is a simple join and divergence is a hard error. - **Ledger-authoritative** is correct whenever retries with reused call ids are possible, whenever the exporter is batched with a flush interval that can outlive the turn, or whenever the model can regenerate a call. In this mode, spans are *not* used for token accounting; the ledger is, and the reconciliation check is inverted: the instance asserts that the sum of `gen_ai.usage.output_tokens` over the turn's spans is **≥** the ledger's committed tokens (spans may over-count due to retries, never under-count due to drops), and flags any turn where spans < ledger as a dropped-span event. The boundary is crossed the moment the runtime retries a tool call with a reused `call.id`. Before that, telemetry-authoritative is safe. After, it is not, and the instance must flip its reconciliation direction or it will under-count spend by exactly the pre-debited amount of each failed attempt. ## Operational Effect An instance that does not detect this boundary will, over a long session, drift its budget accounting monotonically in the direction of retries: every timed-out-then-retried tool call leaves a pre-debit that spans never confirm. The drift is silent because both subsystems report success — the ledger committed, the spans exported. The only observable is a growing gap between the budget enforcer's running total and the sum of span tokens, and that gap is indistinguishable from legitimate in-flight spend until the turn closes. The guardrail is a per-turn reconciliation assertion that runs at turn boundary (not per span), compares ledger committed tokens against span-summed tokens with the direction chosen by the retry policy in force, and raises on violation. It must run *before* the next turn's pre-debit, or the drift compounds across turns and the assertion fires on a turn that did not cause the gap. ```python from dataclasses import dataclass from enum import Enum from typing import Iterable class SpanLedgerDivergence(RuntimeError): """Raised when GenAI span token accounting and the tool-call ledger disagree in a direction that cannot be explained by in-flight retries.""" class ReconciliationMode(Enum): TELEMETRY_AUTHORITATIVE = "telemetry_authoritative" LEDGER_AUTHORITATIVE = "ledger_authoritative" @dataclass(frozen=True) class SpanRecord: call_id: str tool_name: str output_tokens: int attempt: int | None # None means the runtime did not emit an attempt attribute @dataclass(frozen=True) class LedgerRow: call_id: str call_seq: int committed_tokens: int pre_debited_tokens: int # tokens charged before the call returned def reconcile_turn( spans: Iterable[SpanRecord], ledger: Iterable[LedgerRow], mode: ReconciliationMode, ) -> None: span_by_call: dict[str, list[SpanRecord]] = {} for s in spans: span_by_call.setdefault(s.call_id, []).append(s) ledger_by_call = {row.call_id: row for row in ledger} for call_id, rows in span_by_call.items(): if len(rows) > 1 and any(r.attempt is None for r in rows): # Multiple spans for one call id with no attempt attribute: # indistinguishable from duplicate emission. Cannot reconcile. raise SpanLedgerDivergence( f"call_id={call_id!r} has {len(rows)} spans but no attempt " f"attribute; retry vs duplicate emission is undecidable" ) if mode is ReconciliationMode.TELEMETRY_AUTHORITATIVE: for call_id, row in ledger_by_call.items(): matching = span_by_call.get(call_id, []) if len(matching) != 1: raise SpanLedgerDivergence( f"ledger call_id={call_id!r} seq={row.call_seq} expected " f"exactly one span, found {len(matching)}" ) if matching[0].output_tokens != row.committed_tokens: raise SpanLedgerDivergence( f"call_id={call_id!r} span tokens={matching[0].output_tokens} " f"!= ledger committed={row.committed_tokens}" ) else: # LEDGER_AUTHORITATIVE span_total = sum(s.output_tokens for s in spans) ledger_total = sum(r.committed_tokens for r in ledger) pre_debit_total = sum(r.pre_debited_tokens for r in ledger) # Spans may over-count (retries regenerate tokens) but must never # under-count below the ledger's committed total. A shortfall means # the exporter dropped spans and the ledger is the only truth. if span_total < ledger_total: raise SpanLedgerDivergence( f"span token sum={span_total} < ledger committed={ledger_total}; " f"dropped spans suspected (pre-debit total={pre_debit_total})" ) # Pre-debits from failed attempts must be reversed on retry; if they # were not, the ledger overstates committed spend relative to spans. unreversed = pre_debit_total - sum( r.pre_debited_tokens for r in ledger if r.committed_tokens == 0 ) if unreversed > 0 and span_total > ledger_total + unreversed: raise SpanLedgerDivergence( f"span sum={span_total} exceeds ledger+pre-debit by " f"{span_total - ledger_total - unreversed}; " f"pre-debit reversal missing on retried calls" ) ```