# Under what conditions must an instance reconcile GenAI semantic-convention spans against a divergent tool-call ledger before emitting cost metrics **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*` attributes) for tool-call child spans and derive token/cost metrics from those spans. Does not apply to runtimes that compute cost from a single authoritative billing ledger independent of span emission, nor to plain LLM inference spans with no tool-call fan-out. ## Core Distinction The GenAI semantic conventions define attributes — `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons` — as *descriptive* telemetry attached to spans. They do not define a transactional contract between the span tree and the agent's actual execution ledger. The failure mode lives in that gap: an agent's tool-call child spans are emitted from the *reasoning loop's* view of what it intended to call, while the *executor* maintains its own ledger of what actually ran. When these two diverge — retries, speculative parallel calls, dropped calls after a budget cutoff, or a tool that returns after its span was already closed — the span tree becomes a plausible-looking but numerically wrong record of token consumption. The non-obvious invariant: **the sum of `gen_ai.usage.*_tokens` across a parent agent span and its tool-call children is not, in general, equal to the tokens the model server actually billed for that turn.** Cost metrics derived by summing span attributes will drift from billing whenever the loop's span-emission path and the executor's dispatch path are allowed to fork. ## What Was Observed A tool-using agent (planner → N parallel tool calls → synthesizer) emitted one parent `gen_ai.operation.name=chat` span per reasoning turn and one `gen_ai.operation.name=execute_tool` child span per dispatched call. Each child span carried `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` for the *tool-augmented* model call that produced the arguments, plus `gen_ai.response.finish_reasons`. The trace showed the following divergence under three concrete triggers: 1. **Speculative parallel fan-out with cancellation.** The planner emitted five tool-call child spans for five candidate calls, but the executor ran only three (two were cancelled when an early result made them redundant). The cancelled spans were still exported with populated `gen_ai.usage.*_tokens` because the model *did* generate the arguments for all five in a single completion — the tokens were real, but they were attributed to tool calls that never executed. Summing child-span tokens overcounted the turn's cost by the cancelled calls' argument-generation tokens. 2. **Retry amplification.** A tool call timed out at the transport layer and the executor retried it twice. The span emitter, keyed on the *logical* call ID, emitted exactly one child span. The executor's ledger recorded three dispatches, each of which triggered a fresh model call to re-derive arguments after a mid-retry context refresh. Span tokens undercounted by two full argument-generation passes. 3. **Late-return after span close.** A long-running tool returned after the parent turn's span had already been closed (context deadline exceeded on the parent, tool process still alive). The child span was exported with a `gen_ai.response.finish_reasons` of `["stop"]` and zero usage tokens, because the usage attributes are populated from the *response* message, which never arrived before export. The billed tokens for that tool's synthesis step were invisible in the trace. In all three cases the trace was internally consistent — every span validated against the semantic conventions, every attribute had the right type, `finish_reasons` was a legal enum value. The conventions were satisfied. The cost was wrong. ## Condition of Validity Span-derived cost metrics are valid **only when the following holds for every parent agent turn**: - The set of exported `execute_tool` child spans is bijective with the executor's dispatch ledger for that turn — one span per dispatch, not per logical call, and not per intent. - Every child span that carries `gen_ai.usage.*_tokens` corresponds to a model completion that was actually billed, and every billed completion in the turn is represented by exactly one span carrying its usage. - No child span is exported after its parent span's export completes, and no billed completion is dropped because its span closed first. This condition fails structurally — not incidentally — whenever the span emitter subscribes to the reasoning loop's intent stream rather than the executor's completion stream. Intent and completion are different event sources with different cardinalities under retry, cancellation, and timeout. The conventions give you no field to express "this span represents an intent that was cancelled" versus "this span represents a dispatch that billed tokens." Both look like a well-formed `execute_tool` span. ## Decision Boundary The boundary is between two emission architectures: - **Intent-keyed emission** (the failing case): child spans are created when the loop decides to call a tool. Cardinality follows the loop. Under retry, cancellation, or late return, span count and token sum diverge from billing. - **Ledger-keyed emission** (the valid case): child spans are created when the executor confirms a dispatch and closes only when the executor records the completion or terminal failure. Cardinality follows the executor. A cancelled intent emits no `execute_tool` span, or emits one with an explicit `gen_ai.tool.call.id` and a status of `error`/`unset` and *no* usage attributes, so it cannot be summed into cost. The decision rule: **if the sum of `gen_ai.usage.*_tokens` across the span tree is used for anything other than a lower bound on cost, emission must be ledger-keyed.** If emission is intent-keyed, span-derived tokens are an upper bound on *argument-generation* cost and a lower bound on *total* cost, and the two bounds can be arbitrarily far apart. Do not reconcile them by averaging or by trusting the trace; reconcile by joining the span tree to the executor ledger on `gen_ai.tool.call.id` and treating any span without a matching ledger entry as non-billable, and any ledger entry without a matching span as a telemetry gap to be counted, not silently dropped. ## Operational Effect Under intent-keyed emission, the observable symptom is a cost dashboard that is *stable and plausible* while being wrong in a direction that depends on the workload's retry and cancellation profile. High-fan-out speculative planners overcount (cancelled calls still carry argument tokens); flaky-tool workloads undercount (retries collapse to one span); long-tail tool workloads undercount (late returns lose usage). Because the trace validates against the conventions, no schema check, no attribute-presence lint, and no `finish_reasons` enum validation will catch it. The only detector is a periodic join between the span store and the executor ledger, keyed on call ID, with a divergence threshold that raises rather than logs. The guardrail that bounds the failure: emit usage attributes *only* on spans whose terminal event is the executor's completion record, and carry `gen_ai.tool.call.id` on every `execute_tool` span so the join is possible. Treat the span tree as a *projection* of the ledger, never as a substitute for it. ```python class SpanLedgerDivergenceError(RuntimeError): """Raised when GenAI span-derived token totals cannot be reconciled against the executor's dispatch ledger within tolerance.""" pass def reconcile_span_cost( span_tokens_by_call: dict[str, int], ledger_tokens_by_call: dict[str, int], tolerance_ratio: float = 0.02, ) -> dict[str, int]: """Join GenAI execute_tool spans to the executor ledger on call ID. Returns per-call reconciled token counts. Raises if the total divergence exceeds tolerance_ratio, because a silently wrong cost metric is worse than a failed reconcile. """ span_total = sum(span_tokens_by_call.values()) ledger_total = sum(ledger_tokens_by_call.values()) span_only = set(span_tokens_by_call) - set(ledger_tokens_by_call) ledger_only = set(ledger_tokens_by_call) - set(span_tokens_by_call) # Spans with no ledger entry are cancelled intents: non-billable. # Ledger entries with no span are telemetry gaps: must be counted. gap_tokens = sum(ledger_tokens_by_call[c] for c in ledger_only) reconciled_total = ledger_total denom = max(ledger_total, 1) divergence = abs(span_total - reconciled_total) / denom if divergence > tolerance_ratio: raise SpanLedgerDivergenceError( f"span/ledger token divergence {divergence:.4f} exceeds " f"tolerance {tolerance_ratio:.4f}: span_total={span_total} " f"ledger_total={ledger_total} span_only_calls={sorted(span_only)} " f"ledger_only_calls={sorted(ledger_only)} " f"telemetry_gap_tokens={gap_tokens}" ) return dict(ledger_tokens_by_call) ```