# In what scenarios must an instance refuse to close a GenAI agent span when the token-accounting attributes disagree with the parent span's aggregated usage **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where child tool-call and LLM-invocation spans roll up into a parent agent span carrying aggregate `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to single-shot, non-nested LLM calls with no parent aggregation, nor to systems where usage is exported only as metrics (histograms) rather than span attributes. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span observations of a single model invocation*. They were never designed as a *conservation ledger* across a span tree. But agent runtimes inevitably use them that way: the parent agent span is the only place a billing pipeline, a budget enforcer, or a runaway-loop detector can read "how many tokens did this whole task cost." The failure mode is not that the numbers are wrong individually — each child span faithfully reports what its provider returned. The failure is that **the parent aggregate and the sum of children diverge**, and the span is closed anyway, silently emitting a parent record whose token counts are not reconcilable with its own subtree. This is a *continuity invariant* violation, not a bug in any single span: `parent.usage == Σ(children.usage)` is assumed by every downstream consumer that reconciles cost against trace topology, and nothing in the SDK enforces it at `span.end()`. ## What Was Observed An agent loop over a 14-step research task. The parent agent span opened with `gen_ai.operation.name = "invoke_agent"`. Each iteration produced one `chat` span (LLM call) and zero or more `execute_tool` spans. Three independent divergence sources were observed in a single trace: 1. **Retried model calls.** A `chat` span hit a 429, was retried inside the same logical step, and the retry succeeded. The runtime emitted *two* `chat` spans but the parent aggregator incremented usage only once — the retry's usage was dropped because the aggregator keyed on logical step ID, not span ID. Parent reported 41,200 input tokens; children summed to 58,900. 2. **Streaming truncation.** A `chat` span streamed and the client aborted after `finish_reasons = ["length"]` on a partial buffer. The provider's usage block arrived in the final chunk that was never read, so the child span closed with `gen_ai.usage.output_tokens` **absent** (not zero). The parent aggregator treated absent as zero. Child sum under-reported by ~3,100 output tokens. 3. **Tool-side model calls.** Two `execute_tool` spans internally invoked a *sub-agent* that made its own LLM calls, emitting grandchild `chat` spans. The parent aggregator walked only direct children, so those grandchild tokens appeared in the trace but in neither the parent's aggregate nor its direct-child sum. The trace was internally consistent at depth 1 and wrong at depth 2. In all three cases the parent span closed with `status = OK`. No diagnostic attribute flagged the mismatch. The billing reconciler downstream saw a parent claiming 41,200 tokens sitting atop a subtree summing to 58,900 and had no signal to distinguish "aggregator bug" from "provider misreporting" from "intentional sampling." ## Condition of Validity The conservation invariant `parent.usage == Σ(descendants.usage)` is only valid to *assert* when all of the following hold: - Every descendant span that consumes tokens is a descendant of the parent in the same trace (no cross-trace or linked-trace usage). - The parent aggregator's unit of accounting is the *emitted span*, not the *logical step* — i.e., retries emit distinct spans and each is counted. - Absent usage attributes are distinguishable from zero. The conventions permit omission; a reconciler must treat `attribute absent` as `UNKNOWN`, never coerced to `0`. - The aggregation walks the full descendant set, not just direct children, OR the runtime guarantees no grandchild LLM calls (sub-agents are forbidden or their usage is explicitly hoisted). When any condition fails, the invariant is *undefined*, not *violated* — and the correct behavior is to mark the parent span's accounting as non-authoritative rather than to assert equality. The dangerous middle ground is a runtime that half-satisfies the conditions (counts direct children, coerces absent-to-zero, drops retries) and then closes the span as if the invariant held. ## Decision Boundary The boundary is at `span.end()` on the parent agent span, and the decision is binary: **close with a reconciled, authoritative token ledger, or close with an explicitly non-authoritative ledger and a divergence diagnostic.** The runtime must refuse to close the parent as authoritative when: - `Σ(descendants) != parent.aggregate` beyond a tolerance (tolerance must be `0` for input tokens in non-sampled traces; output tokens may tolerate streaming-boundary slack only if the child span is marked `gen_ai.usage.output_tokens = ` explicitly, not silently zeroed). - Any descendant carries an absent usage attribute while the parent claims a complete aggregate. - Descendant depth exceeds the aggregator's walk depth. - A retry occurred at any step (retry usage must be either folded in with a `gen_ai.request.retry_count`-style attribute or emitted as separate counted spans — pick one and make the aggregator agree). When the boundary fires, the runtime must set a span attribute such as `gen_ai.usage.reconciliation = "divergent"` plus `gen_ai.usage.divergence_tokens = `, and must **not** set `status = OK` on the parent — use `status = ERROR` with a message, or a dedicated non-OK status code, so downstream billing treats the ledger as advisory. It must never emit a parent aggregate that contradicts its own subtree while claiming `OK`. ## Operational Effect Closing a divergent parent span as `OK` poisons every consumer that trusts trace topology. Budget enforcers that read parent aggregates under-count (retry drops) or over-count (double-folded retries) and either let a runaway loop run one more iteration or cut a healthy task. Cost reconcilers that walk the subtree and sum children get a different number than the parent and cannot tell which is authoritative, so they pick one arbitrarily — usually the parent, because it is the "task" record — and the error compounds across the billing period. Runaway-detection heuristics keyed on "parent token count exceeds threshold" miss the streaming-truncation case entirely because the truncated output tokens were never counted anywhere. The fix is not more accurate token counting; providers already report accurately. The fix is that the parent span's `end()` must be a *checkpoint that validates the conservation invariant over its subtree* and downgrades its own authority when the invariant is undefined. The following guard encodes the boundary: ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent GenAI agent span cannot be closed as an authoritative token ledger because its subtree does not reconcile.""" pass @dataclass class SpanUsage: span_id: str parent_id: Optional[str] depth: int input_tokens: Optional[int] # None == absent, NOT zero output_tokens: Optional[int] # None == absent, NOT zero is_retry: bool = False @dataclass class ParentLedger: span_id: str aggregate_input: int aggregate_output: int aggregator_walk_depth: int descendants: list[SpanUsage] = field(default_factory=list) def close_agent_span(ledger: ParentLedger, *, tolerance_input: int = 0) -> dict: """Validate the conservation invariant before allowing span.end(). Invariant: parent.aggregate == sum(descendants), where absent usage attributes are UNKNOWN and make the invariant undefined, not zero. """ # Condition 1: aggregator must walk the full descendant set. if any(d.depth > ledger.aggregator_walk_depth for d in ledger.descendants): raise UsageReconciliationError( f"span {ledger.span_id}: descendants exceed aggregator walk depth " f"{ledger.aggregator_walk_depth}; grandchild usage uncounted" ) # Condition 2: absent usage attributes cannot be coerced to zero. absent = [d.span_id for d in ledger.descendants if d.input_tokens is None or d.output_tokens is None] if absent: raise UsageReconciliationError( f"span {ledger.span_id}: descendants {absent} have absent usage " f"attributes (streaming truncation?); invariant undefined" ) # Condition 3: retries must be counted as distinct spans, not dropped. child_input = sum(d.input_tokens for d in ledger.descendants) child_output = sum(d.output_tokens for d in ledger.descendants) delta_in = ledger.aggregate_input - child_input delta_out = ledger.aggregate_output - child_output if abs(delta_in) > tolerance_input or delta_out != 0: # Do NOT return OK. Downgrade authority and surface the divergence. return { "status": "ERROR", "attributes": { "gen_ai.usage.reconciliation": "divergent", "gen_ai.usage.divergence_input_tokens": delta_in, "gen_ai.usage.divergence_output_tokens": delta_out, }, "authoritative": False, } return { "status": "OK", "attributes": {"gen_ai.usage.reconciliation": "exact"}, "authoritative": True, } ```