# Where must an instance refuse to close a GenAI agent span when `gen_ai.usage.output_tokens` is a post-hoc estimate rather than a counted emission **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions, where token accounting for a span is derived from a tokenizer estimate, a provider-reported aggregate, or a streaming delta-sum rather than a single authoritative count at span end. Does not apply to batch/offline telemetry reconciliation, nor to non-LLM tool spans that carry no `gen_ai.usage.*` attributes. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *span-terminal* attributes: they describe the whole invocation and are conventionally written once, at `End()`, on the span that models the model call. This is fine for a single request/response. It is not fine for an agent turn, because an agent turn is a *tree*: a parent `invoke_agent` span wrapping N child `chat` spans, each of which may itself wrap tool-call spans, and each of which may be retried, streamed, or partially cancelled. The non-obvious boundary is this: **the moment a child span's usage attribute is an estimate, the parent span's aggregate usage attribute is no longer additive over its children.** A parent that sums child estimates and then writes its own `gen_ai.usage.output_tokens` produces a number that is internally inconsistent with the sum its own children report. Downstream cost attribution, budget enforcement, and any auditor that re-derives parent usage from child spans will disagree with the parent's own attribute. The invariant that must hold is: > For any agent span S with children C₁…Cₙ that each carry `gen_ai.usage.*`, `S.gen_ai.usage.*` must equal Σ `Cᵢ.gen_ai.usage.*` **or** S must be explicitly marked as non-authoritative for usage. The convention has no field for "this is an estimate." That absence is the failure surface. ## What Was Observed A tool-augmented agent ran a three-step turn: `invoke_agent` → `chat` (plan) → `execute_tool` → `chat` (synthesize). The runtime emitted spans in this order, with these usage values at `End()`: - `chat#1` (plan): `output_tokens=412`, counted from the provider's `usage.completion_tokens` field. - `execute_tool`: no usage attribute (correct — it is a tool span). - `chat#2` (synthesize): `output_tokens=318`, but the provider returned a *streamed* response and the SDK did not surface a final usage block; the runtime fell back to `len(tokenizer.encode(accumulated_text))`, yielding 318. - `invoke_agent` (parent): `output_tokens=730`, computed as 412 + 318. The discrepancy surfaced on the next turn. A budget-enforcement layer read the parent span, saw 730, and reserved that against the tenant's daily quota. But the provider's own billing webhook reported 412 + 341 = 753 for the same two calls — the tokenizer estimate for `chat#2` was 23 tokens low because the accumulated text included a tool-result JSON fragment that the runtime's tokenizer split differently than the provider's. The parent span said 730. Its children summed to 730. The provider said 753. **Both the parent and the children were internally consistent and externally wrong.** The span tree was a closed, self-consistent lie. Because the parent's usage matched its children's sum, no invariant check fired. The error was invisible until the billing webhook arrived, hours later, and by then the quota had already been under-reserved for that turn and every turn in the same session. The second observation: on a retried `chat` span (provider 429, then success), the runtime emitted *two* child spans under the same parent — the failed attempt and the successful retry — and both carried `output_tokens`. The failed attempt carried `output_tokens=0` (correct, nothing generated), but the retry carried the full count. The parent summed to the retry's count. This happened to be right, but only because the failed span emitted zero. Had the failed attempt emitted a partial estimate (it streamed 40 tokens before the 429), the parent would have double-counted. ## Condition of Validity The additivity invariant holds only when **all** of the following are true: 1. Every child span's `gen_ai.usage.*` is sourced from the same authority (provider-reported, not mixed provider + tokenizer estimate). 2. No child span is a retry or a partial/cancelled attempt whose usage overlaps another child. 3. The parent's usage is computed *after* all children have ended, not incrementally as children report. 4. The span tree is complete — no child span was dropped by sampling, export failure, or a `SpanProcessor` that filters by attribute. Condition 4 is the sharpest. A `ParentBased` sampler or an attribute-filtering exporter can drop a child `chat` span while keeping the parent. The parent's usage attribute then exceeds the sum of its *exported* children, and any auditor re-deriving usage from the exported tree sees a deficit. This is not a bug in the sampler — it is the sampler doing its job — but it converts the parent usage attribute from a fact into an unfalsifiable claim. The invariant is therefore **conditional on export completeness**, which the span itself cannot assert. There is no `gen_ai.usage.complete` boolean in the convention. That is the gap. ## Decision Boundary An instance must **refuse to write a parent `gen_ai.usage.*` attribute** — and must instead emit the span with usage omitted and a diagnostic event attached — when any of the following hold at `End()` time: - **Mixed provenance:** at least one child's usage came from a tokenizer estimate while another came from provider-reported counts. Summing across provenance classes is the 730-vs-753 failure above. - **Retry overlap:** two or more child spans share a `gen_ai.request.id` or a retry correlation attribute, and more than one carries nonzero `output_tokens`. - **Incomplete children:** the runtime knows it launched K child calls but fewer than K child spans reached `End()` (a cancelled or timed-out child that never closed). The parent cannot sum what it cannot see. - **Streamed-without-final-usage:** a child `chat` span ended without a provider usage block and fell back to estimation. The parent may still emit its own usage, but only if it propagates a `gen_ai.usage.estimated=true` marker (a non-standard attribute, but the only honest option) so downstream consumers can distinguish authoritative from derived. The boundary is *not* "never estimate." Estimation is often the only signal available. The boundary is "never let an estimate masquerade as a counted aggregate inside a tree that consumers will treat as additive." ## Operational Effect When the guardrail fires, the parent span is exported with `gen_ai.operation.name=invoke_agent` but **no** `gen_ai.usage.*` attributes, plus a span event `genai.usage.aggregation_skipped` carrying `reason` and the per-child provenance map. Downstream cost attribution then falls back to summing authoritative child spans and *excluding* estimated ones from quota reservation — over-reserving slightly rather than under-reserving silently. The billing reconciliation job, which already runs against provider webhooks, becomes the sole authority for estimated spans, and its corrections are applied as a delta rather than a re-write. The cost of this rule is that some parent spans carry no usage and dashboards show gaps. The benefit is that the gaps are *visible* and attributable, rather than filled with a self-consistent number that is wrong by 3% and undetectable until the invoice arrives. In agent systems where a single turn can spawn dozens of child calls and a session can run for hours, a 3% silent under-count compounds into a quota breach that the enforcement layer never saw coming. The general principle: **an aggregate attribute is a claim about its parts; a claim about parts you cannot fully observe must be withheld, not approximated.** The GenAI conventions give you no way to mark an aggregate as approximate, so the only correct move at the boundary is to omit it. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageProvenance(Enum): PROVIDER_REPORTED = "provider_reported" TOKENIZER_ESTIMATE = "tokenizer_estimate" STREAM_DELTA_SUM = "stream_delta_sum" @dataclass class ChildUsage: span_id: str output_tokens: int provenance: UsageProvenance request_id: Optional[str] = None ended: bool = True class UsageAggregationError(RuntimeError): """Raised when a parent GenAI span cannot honestly aggregate child usage.""" @dataclass class ParentUsageDecision: emit_usage: bool output_tokens: Optional[int] reason: Optional[str] = None estimated: bool = False def aggregate_parent_usage( expected_children: int, children: list[ChildUsage], ) -> ParentUsageDecision: ended = [c for c in children if c.ended] if len(ended) < expected_children: raise UsageAggregationError( f"parent launched {expected_children} child calls but only " f"{len(ended)} ended; refusing to emit additive usage over an " f"incomplete tree" ) provenances = {c.provenance for c in ended if c.output_tokens > 0} if len(provenances) > 1: raise UsageAggregationError( f"mixed usage provenance {sorted(p.value for p in provenances)}; " f"summing across provenance classes yields a self-consistent " f"but externally wrong aggregate" ) seen_requests: dict[str, int] = {} for c in ended: if c.request_id is not None and c.output_tokens > 0: seen_requests[c.request_id] = seen_requests.get(c.request_id, 0) + 1 overlapping = [rid for rid, n in seen_requests.items() if n > 1] if overlapping: raise UsageAggregationError( f"retry overlap on request(s) {overlapping}: more than one child " f"with nonzero output_tokens shares a request id; parent sum " f"would double-count" ) total = sum(c.output_tokens for c in ended) if provenances == {UsageProvenance.PROVIDER_REPORTED}: return ParentUsageDecision(emit_usage=True, output_tokens=total) if not provenances: return ParentUsageDecision(emit_usage=True, output_tokens=0) return ParentUsageDecision( emit_usage=True, output_tokens=total, reason="all children estimated; parent marked non-authoritative", estimated=True, ) def end_agent_span( expected_children: int, children: list[ChildUsage], strict: bool = True, ) -> ParentUsageDecision: try: return aggregate_parent_usage(expected_children, children) except UsageAggregationError: if strict: raise # non-strict mode: withhold usage, attach diagnostic event, do not fake a number return ParentUsageDecision( emit_usage=False, output_tokens=None, reason="aggregation_skipped", ) ```