# In what scenarios must an instance refuse to close a GenAI agent span on token-accounting reconciliation failure **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes, `gen_ai.operation.name`, `gen_ai.usage.input_tokens`/`output_tokens`) where a single logical agent turn fans out across multiple model calls and tool calls under one parent span. Does not apply to single-shot, single-span LLM invocations with no nested tool execution, nor to pure trace-export pipelines that never aggregate usage locally. ## Core Distinction The GenAI semantic conventions treat token usage as an *attribute of a span*, not as a *ledger that must balance*. This is the entire trap. A `gen_ai.chat` span carries `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` describing *that one model call*. A parent agent span (`gen_ai.operation.name = "invoke_agent"` or `"execute_tool"` wrappers) is expected to carry the aggregate. The convention does not specify a reconciliation invariant between child usage and parent aggregate—it only specifies the field names. The failure mode is that an instance treats span closure as a fire-and-forget telemetry event, closes the parent span with a *computed* aggregate, and that aggregate silently diverges from the sum of the children because of retries, streamed partial responses, and cache-token accounting that the child spans report under different attribute keys. The non-obvious boundary: **the parent span's usage aggregate must be derived from a committed child ledger, not from the instance's own running counter.** The running counter in the agent loop and the child spans' recorded usage are two independent observations of the same tokens, and they drift. Closing the parent span on the counter is the bug. ## What Was Observed A tool-using agent loop under a single `invoke_agent` parent span, with N child `gen_ai.chat` spans and M child `gen_ai.execute_tool` spans. The instance maintained `self.total_input_tokens` incremented after each model response. On each iteration it also opened and closed a child chat span with the provider's reported usage. Three concrete divergences were observed: 1. **Retry double-count in the child, single-count in the parent.** The transport layer retried a `gen_ai.chat` call after a 429. The retried call succeeded; the *failed* attempt had already emitted a child span with `gen_ai.usage.input_tokens = 0` but the successful retry emitted a *second* child span with the full prompt tokens. The instance's running counter incremented once (it only counts on success). Parent aggregate = counter = 1× prompt. Sum of child spans = 1× prompt (the failed span reported 0). These happened to agree here—but only because the failed attempt reported zero. When the provider bills a failed attempt (some do, on streaming timeouts after first token), the failed child span reports nonzero input tokens, and now child-sum exceeds parent-counter. The parent span under-reports relative to its own children: an auditor replaying the trace sees a parent that does not account for tokens its children claim were spent. 2. **Streamed partial responses.** On a stream that aborted mid-response after emitting tokens, the child span recorded `output_tokens` from the final usage chunk that never arrived—so it recorded whatever the instance's local tokenizer estimated, while the parent counter recorded the provider's billed usage from a separate metrics endpoint. Two tokenizers, two numbers, one trace. 3. **Cache-token attribute mismatch.** The provider reported cached input tokens under `gen_ai.usage.input_tokens_details.cached_tokens` (or the vendor-specific `gen_ai.usage.cache_read_input_tokens`). The instance's counter added *all* input tokens including cached, while the child span, following the convention's intent, recorded only non-cached input in `gen_ai.usage.input_tokens` and cached separately. Parent > child-sum by exactly the cached delta. A downstream cost-attribution job that reads parent usage for billing and child usage for cache-hit analysis produced two irreconcilable reports from the same trace. In all three, the parent span was closed with `status = OK` and no indication that its usage attribute was not the sum of its children. ## Condition of Validity The invariant holds—and the instance is *required* to reconcile before closing—only when all of the following are true: - The parent span is a *usage-aggregating* span, i.e. it declares `gen_ai.operation.name` of `invoke_agent` (or otherwise semantically owns the children's consumption), and - At least one child span under it carries any `gen_ai.usage.*` attribute, and - The runtime has a way to enumerate committed child spans before parent closure (an in-process span processor, or a buffered exporter that has not yet flushed). If the parent span does not own usage (e.g. a pure `execute_tool` span whose children are unrelated), or if children are exported asynchronously and cannot be enumerated at parent-close time, the invariant is *not enforceable* and the correct behavior is to *omit* the parent aggregate attribute entirely rather than emit an unreconciled one. An absent attribute is honest; a wrong aggregate is poisoning. The invariant is explicitly *not* "parent must equal child sum to the token." Retries and cache accounting make exact equality impossible across providers. The enforceable invariant is directional and bounded: the parent aggregate must be `>=` the sum of non-cached child input tokens and `>=` the sum of child output tokens, and the residual must be *attributable* to a named cause (retries, cache, estimation). If the residual is negative or unattributable, reconciliation has failed. ## Decision Boundary The instance must distinguish three outcomes at parent-close time: - **Reconciled:** parent aggregate derived from child ledger, residual non-negative and attributable. Close span `OK`, emit aggregate with a `gen_ai.usage.reconciliation = "child_ledger"` style marker (vendor extension) so auditors know the provenance. - **Unreconcilable but bounded:** residual non-negative but cause unknown, or child enumeration unavailable. Close span `OK` but *omit* the parent usage aggregate, or emit it with an explicit `reconciliation = "unverified"` marker. Do not fabricate. - **Reconciliation failure:** residual negative (children claim more than parent), or child ledger internally inconsistent (e.g. a child reports output tokens exceeding its own `max_tokens`), or the parent counter and child ledger disagree in sign. This is the boundary: **the instance must not close the span as `OK`.** It must close with `status = ERROR`, set `error.type = "token_accounting_reconciliation_failure"`, and record the residual and the offending child span IDs as span events. The turn's output may still be returned to the user—the model's answer is not invalidated by a telemetry defect—but the trace must carry the defect so that cost attribution and audit replay do not silently inherit a corrupt aggregate. The subtle part: this is a *telemetry-layer* refusal, not a *task-layer* refusal. The agent's answer is fine. What must not happen is the span closing green while carrying a number that lies. A green span is a claim of internal consistency; a negative residual falsifies that claim. ## Operational Effect Without this boundary, the failure is silent and compounding. Cost dashboards that sum parent `gen_ai.usage.input_tokens` across agent spans under-report by the retry and cache deltas; a 3% cache-hit rate on a long-running agent fleet becomes a 3% systematic under-billing that no per-span check catches because every individual span is well-formed. Trace-based debugging of "why did this turn cost 40k tokens" fails because the parent aggregate, the child sum, and the provider invoice are three different numbers and the trace records only the least trustworthy one. With the boundary enforced, reconciliation failures surface as a countable error class (`token_accounting_reconciliation_failure`) in the trace backend, which is exactly where an SRE can alert on it. The residual and offending child IDs as span events make the failure *replayable*: an auditor can re-sum the children and confirm the parent's refusal was correct. And because the task output is still returned, the guardrail costs no task success—it only costs the honesty of one attribute, which is the correct thing to spend. The invariant to encode: **a usage-aggregating parent span may close `OK` only if its aggregate is provably `>=` the sum of its committed children's usage and the residual is attributable; otherwise it must close `ERROR` with the residual recorded.** The instance that closes green on an unreconciled negative residual has emitted a trace that lies about its own consistency, and every downstream consumer of that trace inherits the lie. ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingReconciliationError(RuntimeError): """Raised when a usage-aggregating GenAI parent span cannot be closed consistently with its committed child spans.""" pass @dataclass class ChildUsage: span_id: str input_tokens: int # non-cached, per gen_ai.usage.input_tokens cached_input_tokens: int # gen_ai.usage.input_tokens_details.cached_tokens output_tokens: int @dataclass class ParentAggregate: input_tokens: int output_tokens: int provenance: str # "child_ledger" | "unverified" | "omitted" def reconcile_parent_usage( parent_span_id: str, counter_input: int, counter_output: int, children: list[ChildUsage], attributable_residual: Optional[str] = None, ) -> ParentAggregate: """ Decide whether a usage-aggregating parent span may close OK. Invariant: parent aggregate must be >= sum(child non-cached input) and >= sum(child output), with any positive residual attributable to a named cause (retry, cache, estimation). A negative residual is a hard failure. """ if not children: # No committed child ledger: cannot reconcile. Be honest, do not fabricate. return ParentAggregate(counter_input, counter_output, provenance="unverified") child_input = sum(c.input_tokens for c in children) child_output = sum(c.output_tokens for c in children) input_residual = counter_input - child_input output_residual = counter_output - child_output if input_residual < 0 or output_residual < 0: offenders = [ c.span_id for c in children if c.input_tokens < 0 or c.output_tokens < 0 ] raise TokenAccountingReconciliationError( f"parent span {parent_span_id}: negative usage residual " f"(input_residual={input_residual}, output_residual={output_residual}); " f"children claim more than parent counter. Offending children: {offenders}. " f"Span must close ERROR with error.type=" f"'token_accounting_reconciliation_failure'." ) if (input_residual > 0 or output_residual > 0) and attributable_residual is None: # Positive residual but no named cause: emit unverified, never claim OK-with-ledger. return ParentAggregate(counter_input, counter_output, provenance="unverified") return ParentAggregate(counter_input, counter_output, provenance="child_ledger") ```