# Under what conditions must an instance reconcile OpenTelemetry GenAI span attributes against the tool-call ledger before trusting token/cost correlation **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) and derives cost or budget accounting from those spans. Does not apply to runtimes that meter tokens at the provider SDK boundary and never re-derive them from span attributes. ## Core Distinction There are two distinct sources of truth in a traced agent runtime: the **execution ledger** (the ordered, causal record of tool invocations, their arguments, their raw responses, and the model calls that produced them) and the **telemetry stream** (the OTel spans emitted opportunistically as a side effect of execution). The GenAI semantic conventions describe the shape of the telemetry stream. They do not guarantee it is complete, ordered, or causally aligned with the ledger. The boundary failure is this: token and cost attributes on a span are **per-span aggregates over a token budget that is actually consumed per-request**, and tool-call attributes are **per-span annotations over an invocation that may be retried, cached, or fanned out**. When an agent loop retries a model call, replays a cached completion, or fans a single logical reasoning step across multiple physical requests, the sum of `gen_ai.usage.*` across emitted spans diverges from the tokens actually billed. The invariant that must hold before any cost correlation is trusted: > For every logical agent step L, the set of spans tagged with L's `gen_ai.tool.call.id` or step correlation ID must be exactly the set of physical provider requests that were billed for L, with no duplicates from retries, no omissions from dropped spans, and no double-counting from cache hits that emit usage but incur no marginal charge. When that invariant is violated, cost telemetry is *plausible but wrong* — it sums to a number, which is the worst failure mode because it passes every type check and dashboards happily render it. ## What Was Observed A multi-step agent executing a retrieval-augmented task emitted the following span sequence for a single logical tool-calling step. The step was a `gen_ai.operation.name = "chat"` call followed by a `gen_ai.tool.name = "search_docs"` invocation: ``` span A chat gen_ai.usage.input_tokens=1840 output_tokens=210 status=ERROR (429 rate limited) span B chat gen_ai.usage.input_tokens=1840 output_tokens=205 status=OK span C execute_tool gen_ai.tool.name=search_docs gen_ai.tool.call.id=call_9f2 span D chat gen_ai.usage.input_tokens=2410 output_tokens=180 status=OK span E chat gen_ai.usage.input_tokens=2410 output_tokens=180 status=OK (duplicate emission from retry wrapper) ``` Three separate divergences appear here, each invisible to a naive `sum(gen_ai.usage.input_tokens)`: 1. **Retry double-emission.** Span A failed with 429 but still reported `input_tokens=1840`. Depending on the provider, a rate-limited request may or may not have consumed input tokens (some providers count pre-flight tokenization, some do not). The runtime emitted usage on the failed span because the instrumentation hook fired before the status was known. The ledger recorded one billed attempt; telemetry recorded two. 2. **Duplicate span E.** A retry wrapper around the provider client re-emitted a span for a call that had already succeeded (span D). The ledger has one completion; telemetry has two identical usage records. 3. **Tool span without usage.** Span C carries `gen_ai.tool.name` and `gen_ai.tool.call.id` but no token attributes, which is correct per the conventions — but a cost correlator that joins tool calls to the following chat span by temporal adjacency will mis-attribute span D's 2410 input tokens to the *tool* rather than to the *reasoning step that consumed the tool result*. The tool call itself is free; the tokens belong to the model call that read its output. The summed telemetry reported 1840 + 1840 + 2410 + 2410 = 8500 input tokens. The ledger, reconciled against provider billing, showed 1840 (attempt A, billed) + 2410 (step D) = 4250 input tokens. The telemetry over-reported by 100%, and the over-report was *stable and repeatable* under load, which made it look like a real cost trend rather than a bug. ## Condition of Validity Cost correlation between GenAI spans and the execution ledger is valid only when all of the following hold: - **Span status is terminal before usage is read.** A span whose status is `ERROR` or `UNSET` at export time must not contribute to billed-token sums unless the provider's billing semantics confirm failed requests are charged. The instrumentation must not emit `gen_ai.usage.*` until the call outcome is known, or must mark such usage with an explicit `gen_ai.usage.cache_read_input_tokens=0` and a custom `billing.disposition` attribute distinguishing `billed`, `not_billed`, and `unknown`. - **Span identity is unique per physical request.** Retry wrappers must not re-emit spans for a request already traced. The `gen_ai.tool.call.id` and any step correlation ID must be propagated as span links or attributes such that a single logical step maps to a set of spans with cardinality equal to the number of physical billed requests. - **Tool spans and model spans are joined by causality, not adjacency.** A tool invocation span must carry the ID of the model call that *requested* it (parent) and the model call that *consumed* its result (a link or a downstream span attribute). Temporal adjacency is not a valid join key because concurrent tool calls and interleaved reasoning steps break it. - **Cache hits are distinguished from fresh tokens.** `gen_ai.usage.cache_read_input_tokens` (or the provider-equivalent) must be subtracted from marginal cost, not summed into it. A cache hit that reports full `input_tokens` and zero cache-read tokens will over-bill by the cache discount rate. ## Decision Boundary The operational decision is whether to trust the telemetry-derived cost or to fall back to ledger-derived cost. The boundary is crossed when any of these conditions is detected: | Condition | Telemetry trusted? | Action | |---|---|---| | All spans terminal, unique `tool.call.id`, no retry-wrapper duplicates | Yes | Use telemetry sum | | Any span with status `ERROR` carrying usage | No | Reconcile against ledger; mark `billing.disposition=unknown` | | Duplicate `tool.call.id` or repeated identical usage within one step | No | Deduplicate by physical request ID before summing | | Tool span with no linked consuming model span | Partial | Attribute zero cost to tool; do not join by adjacency | | Cache-read tokens absent but provider reports cache hits | No | Subtract cache discount from ledger; do not trust raw sum | The fallback path is always the ledger, because the ledger is the record of what the runtime *did*, while the telemetry is a record of what the runtime *reported about what it did*. When they disagree, the ledger wins, and the disagreement itself must be emitted as a reconciliation span so the divergence is observable rather than silent. ## Operational Effect The consequence of skipping reconciliation is not a crash — it is a **slow, load-correlated cost inflation** that appears precisely when the system is under stress (rate limits trigger retries, retries trigger duplicate spans, duplicates inflate cost). This means cost dashboards show the *worst* numbers exactly when the system is *most* degraded, which inverts the signal: operators see a cost spike and investigate the model or the prompts, when the actual cause is retry instrumentation emitting usage on failed spans. The guardrail is a reconciliation pass that runs at span-export time (or in a batch job over the trace store) and enforces the cardinality invariant: for each logical step, count physical billed requests from the ledger, count usage-bearing spans from telemetry, and if they differ, emit a `reconciliation.divergence` span with the delta and refuse to fold the telemetry cost into the authoritative total. Downstream cost aggregators must consume only reconciled totals, and unreconciled steps must surface as a distinct `cost_confidence=low` label rather than being silently averaged in. The deeper invariant: **telemetry is a lossy, best-effort projection of execution, and any derived quantity (cost, latency, token budget) inherits that lossiness.** Treating span attributes as authoritative is only safe when the projection is provably lossless for the quantity in question — which, for token/cost under retries, cache, and fan-out, it almost never is. ```python from dataclasses import dataclass, field from typing import Iterable class CostCorrelationError(RuntimeError): """Raised when telemetry-derived token/cost cannot be trusted against the ledger.""" pass @dataclass class Span: span_id: str operation: str status: str # "OK" | "ERROR" | "UNSET" tool_call_id: str | None = None input_tokens: int = 0 output_tokens: int = 0 cache_read_tokens: int = 0 billing_disposition: str = "unknown" # "billed" | "not_billed" | "unknown" @dataclass class LedgerEntry: logical_step_id: str physical_request_id: str billed_input_tokens: int billed_output_tokens: int def reconcile_step( step_id: str, spans: Iterable[Span], ledger: Iterable[LedgerEntry], ) -> dict: spans = [s for s in spans] ledger = [e for e in ledger if e.logical_step_id == step_id] # Invariant 1: no usage on non-terminal or error spans unless billing confirms. for s in spans: if s.status != "OK" and (s.input_tokens or s.output_tokens): if s.billing_disposition != "billed": raise CostCorrelationError( f"step {step_id}: span {s.span_id} emitted usage on status " f"{s.status} with billing_disposition={s.billing_disposition}; " f"telemetry cost is not trustworthy" ) # Invariant 2: cardinality of usage-bearing spans == physical billed requests. usage_spans = [s for s in spans if s.input_tokens or s.output_tokens] if len(usage_spans) != len(ledger): raise CostCorrelationError( f"step {step_id}: {len(usage_spans)} usage-bearing spans vs " f"{len(ledger)} billed ledger entries; duplicate or dropped spans suspected" ) # Invariant 3: cache reads must be subtracted, not summed. tel_in = sum(s.input_tokens - s.cache_read_tokens for s in usage_spans) tel_out = sum(s.output_tokens for s in usage_spans) led_in = sum(e.billed_input_tokens for e in ledger) led_out = sum(e.billed_output_tokens for e in ledger) if (tel_in, tel_out) != (led_in, led_out): raise CostCorrelationError( f"step {step_id}: telemetry ({tel_in},{tel_out}) != ledger " f"({led_in},{led_out}); refusing to fold telemetry cost into total" ) return { "step_id": step_id, "input_tokens": led_in, "output_tokens": led_out, "cost_confidence": "high", } ```