# When must an instance reconcile OpenTelemetry GenAI span attributes against a token-budget ledger, and why does late-arriving usage telemetry silently double-count agent cost? **Date of Record:** 2026 December 3 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) for tool calls and LLM invocations, where token/cost usage is attributed to a parent agent span and reconciled against an external budget ledger. Does not apply to stateless single-shot inference with no budget enforcement or to systems that read usage directly from the provider response without a span layer. ## Core Distinction The GenAI semantic conventions treat a span as a *record of an operation*: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, and `gen_ai.operation.name` describe what a single LLM call consumed. A budget ledger treats a span as a *transaction*: it must be counted exactly once, against exactly one owner, before the next call is authorized. These two contracts diverge at the span *lifecycle boundary*. A span is created (start) synchronously but finalized (end + attributes) asynchronously — often after the client has already returned the response to the agent loop. Streaming responses make this worse: the provider may report usage in a terminal chunk, or only in a follow-up accounting API, minutes later. The invariant that must hold is **idempotent, single-owner attribution**: every token recorded in the ledger corresponds to exactly one `gen_ai.usage.*` attribute set on exactly one span, and re-delivery of that span's export never increments the ledger again. The non-obvious failure is that the conventions specify *what* attributes mean but not *when* they become authoritative. A runtime that debits the ledger optimistically at span start (using an estimate) and then also debits on span export (using the real `gen_ai.usage` values) double-counts every call. There is no schema violation, no dropped span, no error — the telemetry is perfectly well-formed and the ledger is wrong. ## What Was Observed A tool-using agent loop over a 40-minute session, emitting one `gen_ai.chat` span per LLM call and one `gen_ai.execute_tool` child span per tool invocation. Budget enforcement debited an estimate of `prompt_tokens + max_tokens` at span start to gate the next call. The OTel BatchSpanProcessor exported spans on a 5s schedule; a downstream reconciler read `gen_ai.usage.input_tokens`/`output_tokens` off each exported span and debited the ledger again. Trace of one call: 1. Agent calls model → span `chat-7` created, `gen_ai.usage.input_tokens` not yet set (usage unknown until response). 2. Budget guard debits `estimate=8192` against ledger; remaining budget drops below threshold. 3. Response returns with `usage.prompt_tokens=6120, completion_tokens=740`. Attributes set on the span object. 4. Span ends; BatchSpanProcessor queues it. 5. ~5s later the span is exported. Reconciler sees `gen_ai.usage.input_tokens=6120` and debits `6860` more. 6. Net debit for one call: `8192 + 6860 = 15052` vs actual `6860`. Ledger overcounted by ~2.2×. Under sustained load the agent hit its budget cap after ~40% of the expected calls, then began refusing tool calls — while the provider dashboard showed only ~40% of the cap consumed. The divergence was invisible in traces (every span was correct) and only surfaced by comparing ledger balance to provider invoice. A second variant appeared with streaming: the terminal usage chunk arrived after the span had already been ended by a timeout path, so `gen_ai.usage.*` was never set. The reconciler saw a span with *no* usage attributes and treated it as zero-cost — undercounting. Same root cause: the runtime had no single authority deciding when a span's usage is final and whether it has been counted. ## Condition of Validity The double-count only manifests when all of the following hold: - Usage is debited at more than one lifecycle point (estimate-at-start **and** actual-at-export), or the same exported span is delivered more than once (BatchSpanProcessor retries, collector fan-out, at-least-once export). - The `gen_ai.usage.*` attributes are populated *after* span start (i.e., any real provider call — usage is never known before the response). - Budget enforcement and telemetry reconciliation are separate components with no shared dedup key. If usage is known synchronously and debited exactly once (no estimate path), or if the ledger keys on span identity with idempotent upsert semantics, the failure does not occur. Note that "we only debit on export" is *not* sufficient: export is at-least-once, and a retried batch re-delivers the same span. ## Decision Boundary The boundary is **whether the span's usage attributes are final and whether that finality is recorded**. Concretely: - If `gen_ai.usage.input_tokens` is set on the span object before `span.end()`, the span is the authoritative usage record — the ledger must debit from it, keyed by `(trace_id, span_id)`, with idempotent semantics. The optimistic estimate at start must be a *reservation*, released on reconciliation, never a debit. - If the span ends before usage is known (streaming timeout, provider error, terminal chunk lost), the span must be marked incomplete — e.g., `gen_ai.usage.input_tokens` absent plus an explicit `agent.usage.finalized=false` attribute — and the ledger must treat it as *unresolved*, not zero. Unresolved spans go to a reconciliation queue that queries the provider's accounting API; they are never silently counted as 0. The invariant: **a ledger entry exists iff a span carries `agent.usage.finalized=true`, and the entry's key is the span identity.** No estimate ever becomes a debit; no span without finalization ever becomes a zero. ## Operational Effect Without this invariant, cost telemetry is internally consistent (every span validates against the conventions) but externally wrong in a load-dependent, silent way: overcounting under high call rates (double-debit), undercounting under timeout/streaming paths (missing usage). Budget guards then either trip early and starve the agent, or never trip and let spend run unbounded — both while dashboards look healthy because they read the same spans the ledger mis-read. With the invariant, the estimate-at-start becomes a reservation with a TTL; reconciliation is an idempotent upsert keyed on `(trace_id, span_id)`; unfinalized spans are quarantined rather than zeroed. The ledger and the provider invoice converge within one reconciliation interval, and the failure mode degrades to a bounded, visible reservation overhang instead of a silent multiplier. ```python from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when a span's GenAI usage cannot be attributed exactly once to the ledger.""" @dataclass class GenAISpan: trace_id: str span_id: str # gen_ai.usage.* are absent until the provider response is parsed. input_tokens: Optional[int] = None output_tokens: Optional[int] = None finalized: bool = False # agent.usage.finalized @dataclass class BudgetLedger: balance: int # idempotency: one entry per span identity; reservations are separate. debits: dict = field(default_factory=dict) reservations: dict = field(default_factory=dict) def reserve(self, span: GenAISpan, estimate: int) -> None: # Reservation never becomes a debit; it only gates the next call. self.reservations[span.span_id] = estimate def reconcile(self, span: GenAISpan) -> None: key = (span.trace_id, span.span_id) if not span.finalized: # Do NOT treat as zero. Quarantine for provider accounting lookup. self.reservations.pop(span.span_id, None) raise UsageAttributionError( f"span {key} exported without finalized usage; " f"route to reconciliation queue, not zero-cost" ) if span.input_tokens is None or span.output_tokens is None: raise UsageAttributionError( f"span {key} finalized=true but gen_ai.usage.* missing" ) if key in self.debits: # Re-delivery of an already-counted span: idempotent no-op. return cost = span.input_tokens + span.output_tokens self.debits[key] = cost self.balance -= cost # Release the reservation now that actual usage is authoritative. self.reservations.pop(span.span_id, None) def on_span_export(ledger: BudgetLedger, span: GenAISpan) -> None: """Called by the exporter/reconciler for every delivered span.""" ledger.reconcile(span) ```