# Under what conditions must an instance refuse to close a GenAI agent span when the token-accounting child spans disagree with the parent's `gen_ai.usage.*` attributes **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and tool-call child spans) where a parent agent span aggregates token counts from one or more LLM or tool child spans. Does not apply to single-shot, single-span inference calls with no child spans, nor to runtimes that emit only metrics without spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes of the span that performed the inference*. They do not specify how a parent agent span that fans out to N child LLM calls should reconcile its own usage attributes against the sum of its children. This is the gap. The distinction that matters operationally is between **accounting as a leaf fact** versus **accounting as an aggregate invariant**. A leaf LLM span reports what the provider returned on its `usage` object — that number is authoritative and immutable. A parent agent span that wraps a multi-step reasoning loop is reporting something else: a *derived* total that must equal the sum of its children's leaf reports, or the trace is lying about cost, and any downstream budget enforcement, rate limiting, or chargeback computed from that trace inherits the lie. The non-obvious failure is not "the numbers are wrong." It is that **the parent span can close successfully with a token total that is smaller than the sum of its children**, and the OpenTelemetry span lifecycle has no mechanism to reject this. A span is closed when `span.end()` is called. There is no post-condition, no consistency check, no cross-span invariant enforced by the SDK. The trace exports cleanly. The accounting is silently wrong. The failure surfaces hours later when a cost dashboard reports a per-agent total that is 40% under the provider invoice, and no one can tell which spans lied. ## What Was Observed Consider a planner-executor agent that, for a single user request, issues: 1. One planning LLM call (child span `plan`, `input_tokens=820`, `output_tokens=210`). 2. Three tool-call spans, each of which internally makes an LLM call to summarize the tool result before returning it to the executor (`tool_1`, `tool_2`, `tool_3`, each with its own `gen_ai.usage.*` — e.g. `input_tokens=1450/1380/1510`, `output_tokens=95/102/88`). 3. One final synthesis LLM call (child span `synthesize`, `input_tokens=2900`, `output_tokens=640`). The parent `invoke_agent` span is supposed to carry the aggregate. In the observed failure, the parent closed with `input_tokens=3720`, `output_tokens=850` — exactly the planning and synthesis calls, nothing else. The trigger condition was a code path where the aggregation helper iterated over `span.children` filtered by `gen_ai.operation.name == "chat"`. The three tool spans had `gen_ai.operation.name == "execute_tool"`, and their *nested* inference spans were two levels deep, not direct children. The aggregator only summed direct children. The tool-nested LLM usage — 4340 input tokens and 285 output tokens — was dropped entirely. The trace is structurally valid: every span has a parent, no orphans, timestamps are monotonic, the parent span's duration brackets all children. The GenAI attributes are present and syntactically correct on every span. The only defect is numerical: `parent.gen_ai.usage.input_tokens < sum(descendant.gen_ai.usage.input_tokens)`. This is invisible to the OTel collector, to any span processor, and to any validator that checks schema conformance rather than cross-span arithmetic. A second, subtler variant was observed in the same system: when a tool call *retried* internally (the tool span was re-emitted after a transient failure), the retry's inference span was a sibling of the original under the tool span, and the aggregator — which deduplicated by `gen_ai.operation.name` — kept only the last one. The retried tokens were counted once instead of twice. This is the same invariant violation (parent < descendants) reached by a different mechanism: deduplication keyed on operation name rather than on span identity. ## Condition of Validity The invariant that must hold for a GenAI agent trace to be trustworthy for accounting is: > For every span `S` with `gen_ai.operation.name == "invoke_agent"` (or any span that declares itself an aggregate over descendants), and for the set `D` of all descendant spans carrying `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`: > `S.gen_ai.usage.input_tokens >= sum(d.input_tokens for d in D)` and likewise for output tokens, **with equality required when `S` performs no inference of its own**. The ">=" rather than "==" is deliberate: an agent span may legitimately perform its own inference (the planner call may be *on* the parent span rather than a child), in which case the parent's total exceeds the descendant sum by exactly its own leaf usage. The equality case is the one that must be enforced when the parent is a pure aggregator, because that is the case where any discrepancy is definitionally a bug. The condition of validity breaks in three concrete ways, all observed: - **Depth truncation.** Aggregation walks direct children only, missing grandchildren (tool-nested inference). Violates equality by the full grandchild sum. - **Identity collapse.** Deduplication or `set`-based accumulation keyed on a non-unique attribute (`gen_ai.operation.name`, `gen_ai.request.model`) collapses distinct inference calls into one bucket. Violates equality by the sum of the collapsed duplicates. - **Late-arriving spans.** In asynchronous tool execution, a tool's inference span may end *after* the parent agent span has already called `span.end()`. The aggregator, running at parent-close time, sees an incomplete child set. Violates equality by the sum of all spans that ended post-close. The third is the one that cannot be fixed by a better summation function, because it is a **lifecycle ordering race**, not an arithmetic error. The parent closed before its descendants finished. OTel permits this — spans are closed independently — but the GenAI accounting invariant does not survive it. ## Decision Boundary The decision boundary is: **at what point does the parent span commit its usage attributes, and what does it do when the committed value cannot be proven equal to the descendant sum?** Two policies are defensible, and the choice must be explicit in the runtime: 1. **Strict aggregation with deferred close.** The parent span does not call `span.end()` until all descendant spans have ended (tracked via a reference count or a structured-concurrency join). At close, the aggregator sums the full descendant set, and if the parent performed no inference of its own, it asserts equality. If equality fails, the span is closed with `status = ERROR` and an `otel.status_description` naming the discrepancy, and the runtime raises. This is correct but requires the runtime to own the join, which conflicts with fire-and-forget tool dispatch. 2. **Provisional aggregation with explicit uncertainty.** The parent closes with whatever it can observe and sets a boolean attribute `gen_ai.usage.aggregate_complete = false` when it knows descendants may be outstanding. Downstream accounting must treat `false` as "do not use for chargeback." This is honest but pushes the correctness burden onto every consumer of the trace. The boundary condition that decides between them is whether the runtime can guarantee descendant completion before parent close. Synchronous tool execution: yes, use policy 1. Asynchronous or streaming tool execution with detached inference: no, policy 1 will deadlock or hang the parent, and policy 2 is mandatory. What must **never** happen — and what was observed — is the implicit third policy: close the parent with a best-effort sum, emit no completeness flag, and let the trace look authoritative. That is the failure mode this record exists to prevent. ## Operational Effect The downstream effects of a silently under-counted agent span are not confined to dashboards: - **Budget enforcement under-fires.** A per-agent token budget computed from span aggregates will permit more real spend than configured, because the trace reports less than the provider bills. The gap is proportional to tool-nested inference volume, which grows with tool count — so the under-count is worst exactly for the most expensive agents. - **Anomaly detection false-negatives.** A detector keyed on "agent token usage exceeded 3σ" will not fire on a runaway loop whose tokens are hidden in grandchild spans. - **Replay divergence.** When an agent is replayed from a checkpoint, the replayed trace's aggregates are compared against the original for verification. If the original under-counted due to depth truncation and the replay (run after a refactor that fixed the aggregator) counts correctly, the two traces disagree on cost despite identical behavior — and the verification layer flags a false regression. The guardrail is a **post-export reconciliation pass**: before a trace is admitted to the accounting store, walk each `invoke_agent` span, sum its full descendant usage, and reject the trace if the parent under-reports. This is cheap (one tree walk per trace) and catches all three failure variants, because all three manifest as the same inequality. It does not require the runtime to be correct; it requires the runtime to be *checkable*. The following enforces the invariant at the point of parent-span close, with an explicit escape for the asynchronous case: ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI agent span closes with usage that cannot equal the sum of its descendant inference spans.""" @dataclass class SpanNode: span_id: str operation_name: str input_tokens: Optional[int] = None output_tokens: Optional[int] = None children: list["SpanNode"] = field(default_factory=list) aggregate_complete: bool = True def _descendant_usage(node: SpanNode) -> tuple[int, int]: """Sum input/output tokens over all descendants that carry usage.""" total_in = total_out = 0 for child in node.children: if child.input_tokens is not None: total_in += child.input_tokens if child.output_tokens is not None: total_out += child.output_tokens sub_in, sub_out = _descendant_usage(child) total_in += sub_in total_out += sub_out return total_in, total_out def close_agent_span(node: SpanNode, performs_own_inference: bool) -> None: """Validate the GenAI aggregate invariant before allowing the span to close. - Pure aggregator (performs_own_inference=False): parent usage MUST equal descendant sum exactly. - Self-inferring parent: parent usage MUST be >= descendant sum. - Asynchronous runtimes that cannot join descendants MUST set aggregate_complete=False; the invariant is then skipped but the trace is marked non-authoritative for accounting. """ if node.operation_name != "invoke_agent": return if not node.aggregate_complete: # Honest uncertainty: caller declared descendants may be outstanding. return desc_in, desc_out = _descendant_usage(node) parent_in = node.input_tokens or 0 parent_out = node.output_tokens or 0 if performs_own_inference: if parent_in < desc_in or parent_out < desc_out: raise TokenAccountingInvariantError( f"span {node.span_id}: self-inferring parent reports " f"in={parent_in}/out={parent_out} but descendants sum to " f"in={desc_in}/out={desc_out}; parent under-reports. " f"Likely depth truncation or identity collapse in aggregator." ) else: if parent_in != desc_in or parent_out != desc_out: raise TokenAccountingInvariantError( f"span {node.span_id}: pure-aggregator parent reports " f"in={parent_in}/out={parent_out} but descendants sum to " f"in={desc_in}/out={desc_out}; equality violated by " f"delta_in={parent_in - desc_in}, delta_out={parent_out - desc_out}. " f"Check for deduplication keyed on gen_ai.operation.name, " f"direct-children-only summation, or post-close descendant spans." ) ```