# Where must an instance reconcile OpenTelemetry GenAI span closure before cost telemetry can be trusted in agent runs **Date of Record:** 2026 November 25 **Scope:** Applies to autonomous agents that emit OpenTelemetry `gen_ai.*` spans across multi-step tool-calling loops and correlate token usage to cost at span close. Does not apply to single-shot inference with no tool loop, nor to billing reconciliation performed from provider-side invoices. ## Core Distinction Token accounting and cost accounting are not the same event, and OpenTelemetry GenAI semantic conventions do not force them to close together. The `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` attributes are conventionally attached to the *inference* span (`gen_ai.operation.name = chat`) that produced them. But an agent run is a *tree*: a parent `invoke_agent` span wraps N child `execute_tool` spans interleaved with M child chat spans. The cost of the run is the sum over chat spans, yet the *decision* that the run is complete lives at the parent. The boundary failure is this: an agent that emits usage attributes on child spans but computes cost at parent-span close will either double-count, drop, or misattribute tokens whenever a tool span outlives its parent's assumed completion, or whenever a retried chat span emits usage twice. The non-obvious invariant: **a `gen_ai.*` span's usage attributes are only authoritative once that span has ended, and a parent agent span must not close until every descendant chat span has ended and its usage has been sealed.** Violating this produces cost telemetry that is internally consistent (sums to something) but externally wrong (does not match the token ledger). ## What Was Observed A tool-calling agent (planner → `search_docs` → `summarize` → final chat) ran under an OTel exporter with batch span processing. The parent `invoke_agent` span was ended by the orchestration loop the moment the final assistant message was returned to the caller. In the same tick, the loop emitted a synthetic `gen_ai.agent.run.cost_usd` attribute on the parent by summing the usage attributes it had cached from child chat spans. Two failure traces appeared: 1. **Late tool span.** The `summarize` tool span was ended asynchronously by a worker pool callback that fired ~40ms after the final chat span. Its `gen_ai.usage.output_tokens` (the summarizer's own LLM call was nested inside the tool) arrived after the parent had already computed cost. The parent's cost attribute was exported short by the summarizer's tokens. The child span still exported its usage — so a downstream aggregator that summed *all* `gen_ai.usage.*` attributes over the trace got the right total, but a downstream that trusted the parent's `cost_usd` got the wrong one. Two consumers, two answers, one trace. 2. **Retried chat span.** A chat call hit a 529 and was retried at the SDK layer. Both attempts emitted a chat span with usage attributes (the failed attempt reported partial output tokens before erroring). The parent cached usage keyed by *operation*, not by *span identity*, so the retry overwrote the first attempt's usage rather than adding a distinct span. The parent cost reflected one attempt; the trace contained two usage-bearing spans. Again: parent and sum-of-children disagreed. In both cases the trace was *valid* — no schema violation, no missing required attribute. The correlation between `gen_ai.usage.*` and `cost_usd` was simply not an invariant the semantic conventions enforce, because the conventions describe attribute *meaning*, not span *lifecycle ordering*. ## Condition of Validity Cost-at-parent is only trustworthy when all of the following hold: - Every chat span that contributes usage is a **descendant** of the parent agent span (not a sibling, not a detached root). - The parent closes **strictly after** all descendant spans have ended — i.e., the orchestrator awaits tool callbacks and retry resolution before ending the parent. - Usage is accumulated **per span identity** (span_id), not per operation name, so retries produce distinct additive entries. - The exporter's batch processor is **flushed** (or the parent is ended with an explicit `force_flush` barrier) before any consumer reads `cost_usd`. If any of these is false, `cost_usd` is a *heuristic*, not a measurement, and must be labeled as such (`gen_ai.agent.cost_estimate = true`) or omitted in favor of consumer-side summation. ## Decision Boundary The choice is not "compute cost at parent vs. at consumer" — it is **where the seal lives**. Two admissible designs: - **Parent-sealed:** orchestrator owns a usage accumulator keyed by span_id, blocks parent end on all child ends, force-flushes, then writes `cost_usd`. Consumers may trust it. Cost: parent end is gated on async tool completion, adding tail latency to the span. - **Consumer-summed:** parent emits no cost; consumers sum `gen_ai.usage.*` across the trace and multiply by a price table keyed on `gen_ai.request.model`. Parent end is unblocked. Cost: every consumer must dedupe retries by span_id and must handle spans that arrive after its read window (streaming aggregators must window on trace completion, not parent end). The boundary is crossed — and the failure above occurs — when an implementation **mixes** these: parent-sealed cost computed from a cache that does not respect span identity or child-end ordering. That hybrid is the specific defect. Pick one seal and enforce it; do not let the parent write a number it cannot guarantee. ## Operational Effect Downstream, the mis-sealed parent propagates: budget governors that read `cost_usd` under-count and fail to trip spend caps; anomaly detectors that compare parent cost to child-sum flag *correct* traces as tampered; and per-tenant attribution splits drift by the retry and late-tool deltas, which are small per-run but compound across a fleet. The fix is a guardrail at the orchestrator boundary: refuse to end the parent while any descendant `gen_ai.operation.name = chat` span is open, and refuse to write `cost_usd` if the accumulator's span_id set does not equal the trace's chat-span set at seal time. ```python import time from dataclasses import dataclass, field class CostSealViolation(RuntimeError): """Raised when a parent agent span attempts to seal cost before all descendant chat spans have ended and usage has been accumulated by span_id.""" @dataclass class SpanUsage: span_id: str operation: str input_tokens: int output_tokens: int ended: bool = False @dataclass class AgentSpanAccumulator: parent_id: str price_per_token: float = 1e-6 _usage: dict[str, SpanUsage] = field(default_factory=dict) _open_chat: set[str] = field(default_factory=set) _open_tools: set[str] = field(default_factory=set) def register_chat(self, span_id: str) -> None: self._open_chat.add(span_id) def register_tool(self, span_id: str) -> None: self._open_tools.add(span_id) def record_usage(self, span_id: str, op: str, inp: int, out: int) -> None: # keyed by span_id, so retries are additive, never overwriting existing = self._usage.get(span_id) if existing is not None: existing.input_tokens += inp existing.output_tokens += out else: self._usage[span_id] = SpanUsage(span_id, op, inp, out) def end_span(self, span_id: str) -> None: self._open_chat.discard(span_id) self._open_tools.discard(span_id) if span_id in self._usage: self._usage[span_id].ended = True def seal_cost(self) -> float: # invariant: no open chat or tool descendants, and every chat span # that ever registered is present in the usage map and ended. if self._open_chat or self._open_tools: raise CostSealViolation( f"parent {self.parent_id} cannot seal cost: " f"{len(self._open_chat)} open chat spans, " f"{len(self._open_tools)} open tool spans" ) for span_id, u in self._usage.items(): if not u.ended: raise CostSealViolation( f"parent {self.parent_id}: usage for {span_id} " f"recorded but span not ended; cost would be unsealed" ) total = sum(u.input_tokens + u.output_tokens for u in self._usage.values()) return total * self.price_per_token def end_agent_run(acc: AgentSpanAccumulator, flush_barrier: callable) -> float: # force_flush must complete before seal is trusted by consumers flush_barrier() try: return acc.seal_cost() except CostSealViolation as e: # do NOT write a partial cost_usd; degrade to estimate flag instead raise CostSealViolation(f"refusing to emit cost_usd for {acc.parent_id}: {e}") ```