# In what scenarios must an instance refuse to close a GenAI span when token-usage attributes disagree with the provider's billed counts across a tool-call fan-out **Date of Record:** 2026 November 28 **Scope:** Applies to agents that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, etc.) and reconcile those counters against provider billing or a downstream cost ledger. Does not apply to systems that emit only trace context with no token accounting, nor to single-shot, tool-free completions where one span maps 1:1 to one billed request. ## Core Distinction The GenAI semantic conventions model *a span per model invocation*. The provider bills *a request per HTTP call*. These are the same object only when the invocation is a leaf. The moment an agent fans out — one reasoning step that dispatches N parallel tool calls, each of which may itself re-enter the model — the convention's per-span `gen_ai.usage.*` attributes describe a *local* view of token consumption, while the billing system describes a *global* view keyed by request ID. The convention is explicit that usage attributes are per-operation, but it is silent on how a parent span should reconcile the sum of its children's usage against the provider's aggregate. That silence is the boundary. An instance that closes a parent span with a token count it did not verify against the provider's reported usage has produced a span that is structurally valid OTel and semantically false — and every downstream cost attribution, budget governor, and anomaly detector inherits the lie. ## What Was Observed A planner agent executed a task with `gen_ai.operation.name = "chat"` on a root span, and within it issued four parallel `execute_tool` child spans (`gen_ai.tool.name` in `{search, fetch, sql_query, summarize}`). Three of the four tools returned small payloads; the `fetch` tool returned a 90 KB document that the agent then re-fed into the model in a follow-up chat span. The observed sequence: 1. Root chat span opened. Provider returned `usage: {input: 1200, output: 340}`. Instance set `gen_ai.usage.input_tokens = 1200`, `gen_ai.usage.output_tokens = 340` on the root. 2. Four tool child spans opened in parallel. Each tool span, per convention, carried no usage attributes (tools don't consume model tokens directly). 3. The `fetch` result triggered a nested chat span (child of the root, sibling of the tool spans) with `input: 41200, output: 520` — the 90 KB document dominated input. 4. Instance closed the nested chat span with `input_tokens = 41200`. 5. Instance closed the root span with `input_tokens = 1200` — the value it captured at step 1, never refreshed after the nested call. The trace, viewed in a backend, showed a root span claiming 1540 total tokens with a child span claiming 41720. The provider's billing export for the same trace window reported 42400 input tokens across two requests. The instance's ledger, which summed root-span attributes only (the documented aggregation pattern), recorded 1540. The 40860-token delta was invisible until a monthly reconciliation ran against the provider invoice, by which point the budget governor had already approved three additional fan-out tasks on the assumption that the agent was cheap. The failure is not "the instance forgot to update a counter." The instance *correctly* followed the convention — usage attributes are set once, at span end, from the response that closed that span. The failure is that the convention has no attribute for *aggregate* usage on a parent, and no invariant requiring the parent's usage to equal the sum of descendants. An instance that treats the root span's usage as the trace's usage is making an inference the convention does not license. ## Condition of Validity The per-span usage attribute is valid **iff** the span corresponds to exactly one provider request whose response carried a `usage` object, and no descendant span represents an additional billed request. This holds for leaf chat spans and for tool spans that invoke no model. It fails — silently, without any schema violation — whenever: - A parent chat span's descendants include another chat span (re-entry after tool results, agent-as-tool, sub-agent delegation). - A streaming response is closed early and the provider's final usage chunk is never received; the instance falls back to a local tokenizer estimate, which diverges from billed counts by the provider's chat-template overhead (typically 3–15% on short prompts, larger on tool-heavy turns where the provider injects tool schemas the client never sees). - A tool call is retried at the transport layer (idempotency key present, but the first attempt was billed before the timeout). The instance records one tool span; the provider bills two requests. In each case the span is well-formed. `gen_ai.usage.input_tokens` is an integer, the span status is `OK`, the trace assembles cleanly. The invalidity lives one level up, in the aggregation the instance performs when it treats span attributes as a billing record. ## Decision Boundary The instance must decide, at span-close time, whether it is authorized to finalize a usage attribute it cannot verify. The boundary: - **Leaf chat span, usage object received:** finalize. The attribute is a direct transcription of provider truth. - **Leaf chat span, usage object missing (stream truncated, error mid-stream):** do **not** finalize with a tokenizer estimate under the standard attribute. Either omit `gen_ai.usage.*` entirely (the convention permits absence) or emit the estimate under a distinct, clearly-named attribute so downstream aggregation cannot mistake it for billed truth. An instance that writes an estimate into `gen_ai.usage.input_tokens` has poisoned the ledger. - **Parent span with chat descendants:** the parent's `gen_ai.usage.*` must **not** be set to its own request's usage alone if any consumer will aggregate by root span. Either (a) set it to the verified sum of its own request plus all descendant chat spans' verified usage, or (b) leave it as the local value but emit an explicit `gen_ai.usage.aggregate_verified = false` marker so the ledger knows to walk descendants. The choice is architectural; the invariant is that *the two must never disagree without a marker*. - **Any span whose usage cannot be reconciled to a provider request ID:** the instance must halt the trace-finalization path and surface the discrepancy, not close the span. ## Operational Effect An instance that enforces this boundary converts a silent, month-latency billing drift into a synchronous, per-trace signal. The cost is a small amount of span-close latency (one reconciliation lookup per parent span) and the obligation to carry provider request IDs through the trace as a link attribute. The benefit is that budget governors, anomaly detectors, and cost-attribution queries operate on numbers that are either verified or explicitly flagged unverified — never silently wrong. In the observed incident, enforcing the boundary would have blocked the root span from closing at step 5, because the nested chat descendant's 41720 tokens had no corresponding entry in the root's usage and no `aggregate_verified` marker. The block would have surfaced at the first trace, not the monthly invoice, and the three over-budget fan-out tasks would never have been approved. The deeper invariant: **a GenAI span's usage attributes are a claim about a provider request, not a claim about a trace.** Any instance that aggregates them must walk the tree and verify, or it is fabricating a billing record under the authority of a semantic convention that never granted that authority. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class UnverifiedUsageError(RuntimeError): """Raised when a GenAI span would close with usage attributes that cannot be reconciled to a provider request or to its chat descendants.""" @dataclass class Span: name: str operation: str # gen_ai.operation.name request_id: Optional[str] = None # provider request id, if any input_tokens: Optional[int] = None # gen_ai.usage.input_tokens output_tokens: Optional[int] = None usage_verified: bool = False # reconciled against provider response children: list["Span"] = field(default_factory=list) def chat_descendant_usage(self) -> tuple[int, int]: """Sum verified usage across all descendant chat spans.""" inp = out = 0 for child in self.children: if child.operation == "chat": if not child.usage_verified: raise UnverifiedUsageError( f"descendant chat span {child.name!r} closed without " f"verified usage; cannot aggregate parent {self.name!r}" ) inp += child.input_tokens or 0 out += child.output_tokens or 0 ci, co = child.chat_descendant_usage() inp += ci out += co return inp, out def close_span(span: Span, aggregate_verified: bool) -> None: """Enforce the invariant at span-close time. A parent span may close only if either (a) it has no chat descendants, or (b) its usage attributes equal the verified sum of its own request plus all descendant chat spans, or (c) the caller explicitly marks the span as aggregate-unverified so the ledger walks descendants instead. """ desc_in, desc_out = span.chat_descendant_usage() if desc_in == 0 and desc_out == 0: # Leaf-equivalent: no chat descendants, local usage is authoritative. if span.operation == "chat" and span.input_tokens is None: raise UnverifiedUsageError( f"chat span {span.name!r} closing with no usage and no " f"descendants; usage object was lost (stream truncated?)" ) return if aggregate_verified: local_in = span.input_tokens or 0 local_out = span.output_tokens or 0 if local_in != desc_in and local_in + (span.input_tokens or 0) != desc_in: # The parent's own usage does not account for descendants. raise UnverifiedUsageError( f"span {span.name!r} claims input_tokens={local_in} but " f"descendant chat spans account for {desc_in}; " f"aggregate_verified=True requires equality" ) return # aggregate_verified=False: caller has acknowledged the span's usage is # local-only. The ledger must walk descendants. Nothing to enforce here, # but the marker must be recorded by the exporter (checked elsewhere). if span.operation == "chat" and span.input_tokens is None: raise UnverifiedUsageError( f"span {span.name!r} has chat descendants but no local usage " f"and no aggregate marker; trace is unattributable" ) # Reproduces the observed incident: root = Span(name="planner", operation="chat", request_id="req_1", input_tokens=1200, output_tokens=340, usage_verified=True) nested = Span(name="synthesize", operation="chat", request_id="req_2", input_tokens=41200, output_tokens=520, usage_verified=True) root.children.append(nested) try: close_span(root, aggregate_verified=True) # would have blocked the incident except UnverifiedUsageError as exc: print(f"BLOCKED: {exc}") ```