# When must an instance reconcile OpenTelemetry GenAI semantic-convention spans against its own loop counter before exporting cost attribution? **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans (per-LLM-call and per-tool-call) and derive cost attribution from `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on span end. Does not cover batch/offline cost reconciliation, nor providers that return authoritative per-request billing via a separate ledger API. ## Core Distinction There are two independent notions of "how much did this agent loop consume": the **loop counter** (the runtime's own monotonic tally of LLM invocations and tool calls it has issued) and the **span ledger** (the set of `gen_ai.*` spans that actually reached the exporter and were accepted by the collector). These diverge under retries, span-drop-on-shutdown, sampling, and mid-loop crashes. The boundary failure is this: an exporter that computes cost from the span ledger *while assuming the ledger is complete* will silently under-attribute cost whenever the loop counter and the ledger disagree, and the disagreement is invisible because both numbers are "valid." The invariant that must hold before any export is `ledger_count == loop_counter` (or an explicit, recorded delta). Cost attribution is only valid when this equality is reconciled *at loop termination*, not per-span. ## What Was Observed A tool-using agent loop emitted one `gen_ai.chat` span per LLM call and one `gen_ai.execute_tool` span per tool invocation. Cost was attributed by summing `gen_ai.usage.input_tokens`/`output_tokens` across ended `gen_ai.chat` spans and multiplying by a per-model rate table. Three distinct divergence modes were observed: 1. **Retry shadowing.** The LLM client retried a transient 429 internally. The retry produced a *second* `gen_ai.chat` span, but the runtime's loop counter incremented once (it counts logical calls, not transport attempts). The ledger over-counted tokens for a call the loop believed happened once. Cost was inflated ~1.7× on retry-heavy runs, but the loop counter "looked correct." 2. **Shutdown span drop.** On `SIGTERM` during a long tool call, the `BatchSpanProcessor` flushed only ended spans. The in-flight `gen_ai.chat` span (already billed by the provider, tokens already consumed) was never ended and never exported. The loop counter had already incremented for that call. Ledger under-counted by exactly the in-flight call's tokens. 3. **Sampling-induced asymmetry.** A `ParentBased(TraceIdRatioBased(0.1))` sampler was enabled to cut trace volume. The loop counter counted all 40 calls; the ledger carried ~4. Cost attribution divided by the *sampled* ledger and reported 10% of true spend — with no error, because the exporter had no notion of the sampling ratio. In all three cases the exporter emitted a well-formed, schema-valid `gen_ai` span set. The failure was not a malformed span; it was a **reconciliation invariant that was never checked**. ## Condition of Validity Cost attribution derived from `gen_ai.*` spans is valid **only if all of the following hold at loop termination**: - `span_ledger.ended_chat_span_count` equals the loop counter's LLM-call count, **or** the delta is explicitly recorded with a reason (`in_flight`, `dropped_on_shutdown`, `sampled_out`). - The sampler is either disabled for the cost-bearing span class, or its effective ratio is carried as an attribute (`gen_ai.sampling_ratio`) so the exporter can un-scale the sum. - Retries are represented either as child spans under a single logical `gen_ai.chat` span (so the logical count matches) or the loop counter counts transport attempts (so the counts match). The two must use the *same* unit. - `gen_ai.usage.*` is present on every ended span, or its absence is recorded as `usage_missing=true` and excluded from the sum with a count of exclusions. If any condition fails, the exporter must emit a `gen_ai.cost_attribution_incomplete` marker rather than a silently short total. ## Decision Boundary The decision point is at **span end / loop termination**, not at span start: - **Reconcile-then-export** (default): at loop termination, compare `ledger_count` to `loop_counter`; if unequal and the delta is unexplained, emit the marker and refuse to publish a "final" cost total. Publish a *lower bound* plus the delta. - **Export-with-provenance**: if the delta is explained (e.g., `in_flight=1` at shutdown, `sampled_out` ratio known), export the total *and* the provenance fields so downstream billing can reconstruct. - **Never** un-scale a sampled ledger without an explicit ratio attribute; a 10% sample with no ratio recorded is indistinguishable from a genuinely cheap run. The boundary is crossed when the exporter treats the ledger as authoritative without having proven `ledger == loop_counter`. ## Operational Effect Without this reconciliation, cost attribution is a **lower bound that presents as an exact figure** — the worst failure class for billing and budget enforcement, because it fails silently and biases consistently downward (under-attribution), so budget alarms never fire until the provider invoice arrives. With the invariant enforced, the exporter either produces an exact figure or an explicit "incomplete + delta" record, and downstream cost dashboards can distinguish "cheap run" from "partially observed run." The guardrail is cheap: one integer comparison and a provenance field per loop. ```python from dataclasses import dataclass, field class CostAttributionInvariantError(RuntimeError): """Raised when the span ledger cannot be reconciled to the loop counter.""" pass @dataclass class LoopCounter: llm_calls: int = 0 # logical calls, incremented once per call tool_calls: int = 0 @dataclass class SpanLedger: ended_chat_spans: int = 0 input_tokens: int = 0 output_tokens: int = 0 usage_missing: int = 0 sampling_ratio: float | None = None # None => unsampled / unknown def reconcile_and_attribute( counter: LoopCounter, ledger: SpanLedger, in_flight_at_shutdown: int = 0, dropped_on_shutdown: int = 0, ) -> dict: """ Enforce ledger == loop_counter (or explained delta) before publishing cost. Returns a dict with either an exact total or an explicit lower bound + delta. """ explained_delta = in_flight_at_shutdown + dropped_on_shutdown observed = ledger.ended_chat_spans expected = counter.llm_calls unexplained = expected - observed - explained_delta if unexplained < 0: # More spans than logical calls => retry shadowing or double-emit. raise CostAttributionInvariantError( f"ledger over-counts: {observed} ended spans vs " f"{expected} logical calls (explained={explained_delta}); " "retries must be child spans or counter must count attempts" ) if unexplained > 0: # Spans missing with no explanation => do NOT publish an exact total. raise CostAttributionInvariantError( f"ledger under-counts by {unexplained} call(s) with no recorded " "cause (in_flight/dropped); refusing to publish exact cost" ) if ledger.usage_missing > 0: raise CostAttributionInvariantError( f"{ledger.usage_missing} ended span(s) lack gen_ai.usage.*; " "cost total would be a lower bound" ) raw_tokens = ledger.input_tokens + ledger.output_tokens if ledger.sampling_ratio is not None and ledger.sampling_ratio <= 0: raise CostAttributionInvariantError( f"invalid sampling_ratio={ledger.sampling_ratio}; cannot un-scale" ) scale = 1.0 if ledger.sampling_ratio is None else 1.0 / ledger.sampling_ratio return { "exact": True, "chat_spans": observed, "logical_calls": expected, "explained_delta": explained_delta, "tokens_scaled": int(raw_tokens * scale), "sampling_ratio": ledger.sampling_ratio, "provenance": "reconciled", } ```