# In what scenarios must an instance reconcile OpenTelemetry GenAI span attributes against tool-call side effects before finalizing token accounting **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) while executing tool calls whose side effects are not idempotent. Does not apply to pure-inference spans with no tool dispatch, nor to runtimes that buffer all telemetry and reconcile it out-of-band against a transactional ledger. ## Core Distinction The GenAI semantic conventions treat a span as a *descriptive* record: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, and the tool-call attributes (`gen_ai.tool.name`, `gen_ai.tool.call.id`) are written at span end and assumed to faithfully describe what the model did. The invariant that actually governs billing and replay is different: a span is a *claim* about a probabilistic execution that already produced irreversible side effects. The two diverge at exactly one seam — the moment between the tool invocation returning and the span being closed — because token accounting for the *next* turn depends on the tool result being re-encoded into context, and that re-encoding is where the observed counts and the executed counts stop matching. ## What Was Observed A research agent loop with three tools (`search`, `fetch`, `summarize`) was instrumented with one `chat` span per model turn and one `execute_tool` child span per dispatch. Each `execute_tool` span carried `gen_ai.tool.name` and `gen_ai.tool.call.id` copied from the model's tool-call block, and the parent `chat` span carried `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from the provider response. Under normal load, `sum(output_tokens)` across turns matched the provider invoice within 0.4%. Under a specific trigger — a `fetch` tool returning a payload that exceeded the model's per-message cap and was *truncated by the tool harness before re-encoding* — the accounting inverted. The provider billed the truncated payload as input tokens on the next turn (correct), but the `execute_tool` span recorded `gen_ai.tool.name=fetch` with no attribute indicating truncation, and the parent `chat` span's `input_tokens` was read from the provider response *before* the harness rewrite. The result: the span tree claimed N input tokens; the provider billed N + Δ, where Δ was the truncation overhead re-tokenized on the following turn. Over a 40-turn session this compounded to a 6.1% undercount, and the discrepancy grew superlinearly because each truncated fetch re-entered the context window and pushed earlier turns toward eviction. The failure was not a bug in attribute emission — every attribute was written correctly at the moment it was sampled. It was a *temporal* mismatch: the span closed before the harness finished mutating the payload that the span claimed to describe. ## Condition of Validity The reconciliation gap exists if and only if all three hold: 1. **Non-idempotent tool side effects.** The tool call mutated external state (a fetch that advances a cursor, a write that appends, a search that consumes a rate-limit budget). Replay cannot recover the pre-call state, so the span is the only record. 2. **Post-span context mutation.** The harness transforms the tool result after the `execute_tool` span closes but before the next `chat` span opens — truncation, summarization, schema coercion, or PII redaction. This is the seam. 3. **Derived accounting.** Token counts for turn *t+1* are computed from the provider response of turn *t+1*, not from a ledger that sums the actual re-encoded bytes. If accounting were derived from the harness's post-mutation byte count, the gap would collapse. Remove any one condition and the invariant holds. The dangerous case is (2) combined with (3), because the span tree looks internally consistent — every span has a usage attribute, every tool call has a name — while being externally wrong. ## Decision Boundary An instance must treat the span-close boundary as a **commit point**, not a logging point, when the following predicate is true: ``` tool_result_mutated_after_span_close AND next_turn_input_tokens_derived_from_provider ``` Below this boundary — pure inference, or tools whose results are re-encoded verbatim — the GenAI conventions are sufficient and reconciliation is wasted work. Above it, the instance must not finalize `gen_ai.usage.*` until it has emitted a reconciliation record that binds three facts to the same `gen_ai.tool.call.id`: the provider-reported usage, the harness-reported post-mutation byte count (and its tokenization), and a flag indicating whether the two agree within tolerance. The `gen_ai.tool.call.id` is the only stable join key across the seam; the span ID is not, because the child span has already closed. If reconciliation cannot be performed — the harness does not expose post-mutation bytes, or the provider does not return per-turn usage — the instance must *downgrade the span*: set an explicit `gen_ai.usage.reconciled=false` (or the equivalent local extension) rather than emit a usage attribute that downstream billing will trust. Emitting a confident number that is known to be unverifiable is worse than emitting none. ## Operational Effect The architectural consequence is that token accounting becomes a two-phase operation. Phase one writes the descriptive span at close, as the conventions require. Phase two writes a reconciliation record after the harness finalizes the payload, joined on `gen_ai.tool.call.id`, and the billing pipeline reads *only* phase two for turns that crossed the boundary. Agents that skip phase two do not fail loudly — they produce a span tree that passes every schema validator and every dashboard, while drifting from the invoice by a margin that grows with tool-result volatility. The guardrail is not a new attribute; it is the refusal to let a span's usage attributes be the final word when the payload they describe was still being rewritten after the span closed. ```python import hashlib from dataclasses import dataclass class UnreconciledTokenAccounting(RuntimeError): """Raised when a tool-call span's usage cannot be bound to post-mutation bytes.""" @dataclass(frozen=True) class ToolCallSpan: call_id: str tool_name: str provider_input_tokens: int provider_output_tokens: int span_closed_at_turn: int @dataclass(frozen=True) class HarnessPayload: call_id: str post_mutation_bytes: bytes mutated_after_span_close: bool tokenizer_estimate: int def reconcile( span: ToolCallSpan, payload: HarnessPayload, tolerance_ratio: float = 0.02, ) -> dict: if span.call_id != payload.call_id: raise UnreconciledTokenAccounting( f"join key mismatch: span={span.call_id} payload={payload.call_id}" ) if not payload.mutated_after_span_close: return { "call_id": span.call_id, "reconciled": True, "delta_tokens": 0, "payload_digest": hashlib.sha256(payload.post_mutation_bytes).hexdigest(), } claimed = span.provider_input_tokens + span.provider_output_tokens observed = payload.tokenizer_estimate delta = observed - claimed ratio = abs(delta) / max(claimed, 1) if ratio > tolerance_ratio: # The span closed before the harness finished rewriting the payload. # We cannot trust provider usage as the final word for this call. raise UnreconciledTokenAccounting( f"call {span.call_id} ({span.tool_name}): claimed={claimed} " f"observed={observed} delta={delta} ratio={ratio:.4f} " f"exceeds tolerance {tolerance_ratio}" ) return { "call_id": span.call_id, "reconciled": True, "delta_tokens": delta, "payload_digest": hashlib.sha256(payload.post_mutation_bytes).hexdigest(), } ```