# Under what conditions must an instance refuse to close an OpenTelemetry GenAI agent span when child tool-call spans report token usage that exceeds the parent's recorded `gen_ai.usage.*` totals **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.tool.name`) for a parent agent-invocation span with one or more child tool-call spans, where token accounting is aggregated at close time. Does not apply to single-span, single-call instrumentation with no nested tool spans, nor to runtimes that delegate accounting entirely to a downstream billing pipeline that tolerates negative residuals. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes of the span that performed the model call*. They do **not** define a parent-child aggregation rule. The conventions are, by design, per-span. What most agent runtimes actually implement, however, is a *rollup*: the parent agent span carries a total, and each child tool span carries its own slice, and the invariant "parent total ≥ Σ child slices" is assumed to hold. That invariant is false in three routine cases: (1) the parent's own reasoning tokens are billed but never attributed to any child, so the sum of children is strictly less than the parent — this is the *expected* direction; (2) a retried tool call emits two child spans for one logical call, inflating the child sum above the parent's single count; (3) a child span that fails mid-call still reports usage from the partial response, while the parent, having caught the exception, records zero for that branch. Case (2) and (3) produce a **negative residual** — Σ children > parent — and a naive exporter that computes `parent - Σ children` for a "reasoning overhead" metric will emit a negative token count, which most backends silently coerce to zero or reject, corrupting dashboards and, worse, the cost-attribution join. The boundary condition is therefore not "does the parent exceed the children" but **"is the residual non-negative, and if not, which span is authoritative?"** The GenAI conventions do not answer this; the runtime must. ## What Was Observed An agent invocation span `invoke_agent` was opened with `gen_ai.operation.name=invoke_agent`, `gen_ai.request.model=gpt-4o`. During execution it issued three tool calls: - `get_weather` — succeeded, `gen_ai.usage.input_tokens=812`, `gen_ai.usage.output_tokens=44`. - `search_docs` — first attempt timed out at the HTTP layer *after* the model had already generated a 1,200-token tool-call argument blob; the runtime retried. The first attempt's span was closed with `status=ERROR` but its `gen_ai.usage.output_tokens=1200` was still recorded (the tokens were spent). The retry succeeded with `input_tokens=1900`, `output_tokens=61`. - `summarize` — raised inside the tool; the parent caught it and recorded zero usage for the branch, but the child span had already flushed `output_tokens=310` before the exception propagated. Parent close computed: ``` input = 812 + 1900 + 0 = 2712 (parent's own turn: 3050) output = 44 + 1200 + 61 + 310 = 1615 (parent's own turn: 1180) ``` The parent's *own* model turn — the tokens it spent deciding to call tools and then composing the final answer — was 3050 input / 1180 output. The rollup `parent_total - Σ children` yielded `input_residual = +338` (plausible reasoning overhead) but `output_residual = -435` (impossible). The exporter wrote `gen_ai.usage.output_tokens=-435` on a derived `agent.reasoning_overhead` span. The backend's OTLP receiver accepted the int64, the cost pipeline multiplied by a negative rate, and the daily spend for that tenant decreased by $0.0031. The anomaly detector fired on the *next* day, not the current one, because the negative was absorbed into a rolling mean. The retry double-count (case 2) and the failed-child flush (case 3) are the two mechanisms. Neither is a bug in OTel; both are consequences of treating a per-span convention as an aggregation contract. ## Condition of Validity The rollup invariant `parent_total ≥ Σ child_usage` holds **only** when all of the following are true simultaneously: 1. Every child span corresponds to exactly one logical model call — no retries emit duplicate usage, or retries are explicitly tagged (`gen_ai.request.retry_count` or a custom `tool.attempt`) and deduplicated before summation. 2. A child span that terminates in `ERROR` either (a) suppresses its `gen_ai.usage.*` attributes entirely, or (b) is flagged so the aggregator knows its usage is *included in the parent's catch-path accounting* rather than additive. 3. The parent's own model turn is recorded on the parent span *and* the aggregation formula subtracts only children whose usage is disjoint from the parent's turn — i.e., children that performed a *separate* model call, not children whose tokens were already counted in the parent's `output_tokens`. Condition 3 is the non-obvious one. In many runtimes the parent's `output_tokens` *already includes* the tool-call argument tokens it generated to invoke the tool. If the child span then re-reports those same tokens as its own `input_tokens` (because the tool received them as arguments), the sum double-counts. The GenAI conventions do not forbid this; they are silent. The invariant requires the runtime to declare, per span, whether its usage is *inclusive* (counted in an ancestor) or *additive* (a fresh model call). Absent that declaration, the residual is undefined. ## Decision Boundary At parent-span close, compute `residual = parent_total - Σ child_usage` separately for input and output. - If `residual ≥ 0` for both: emit the residual as `agent.reasoning_overhead` (or omit it), close the span. This is the expected path. - If `residual < 0` for either: **do not close the span with the computed totals.** The parent's recorded `gen_ai.usage.*` is authoritative (it reflects what the model provider billed); the child sum is advisory. Emit a `gen_ai.usage.discrepancy` event on the parent span carrying `{input_residual, output_residual, child_span_ids}`, clamp the derived overhead metric to zero, and mark the parent `status=ERROR` with `error.type=UsageRollupDiscrepancy` so the anomaly is visible in trace search, not buried in a metric. The boundary is not "refuse to export." It is "refuse to *derive* a negative quantity and refuse to let the negative propagate into cost joins." The parent span still exports with its authoritative totals; only the derived residual is suppressed and the discrepancy is surfaced as a first-class event. ## Operational Effect Clamping the residual to zero without the event hides a real accounting error: the retry double-count means a tenant is being charged twice for one logical tool call, and the failed-child flush means a tenant is charged for a call that produced no usable output. Surfacing `UsageRollupDiscrepancy` with the residual magnitude lets the billing reconciliation job flag the exact trace, and lets the runtime team distinguish retry inflation (case 2, fixable by dedup) from error-path inflation (case 3, fixable by suppressing usage on `ERROR` children or by moving the flush after the success check). The invariant to enforce: **a span's `gen_ai.usage.*` attributes are per-span facts; any aggregate derived from them must be validated for non-negativity before emission, and a violation is a span-level error event, not a silent clamp.** The GenAI conventions give you the attributes; they do not give you the rollup. The rollup is the runtime's contract, and it must be checked at the boundary where children meet parent. ```python from dataclasses import dataclass, field from typing import Optional class UsageRollupDiscrepancy(RuntimeError): """Raised when child tool-call usage exceeds the parent agent span's totals.""" def __init__(self, parent_id: str, input_residual: int, output_residual: int, child_ids: list[str]): self.parent_id = parent_id self.input_residual = input_residual self.output_residual = output_residual self.child_ids = child_ids super().__init__( f"span {parent_id}: input_residual={input_residual} " f"output_residual={output_residual} across {len(child_ids)} children" ) @dataclass class SpanUsage: span_id: str input_tokens: int output_tokens: int status: str = "OK" # "OK" | "ERROR" inclusive: bool = False # True if tokens already counted by an ancestor @dataclass class ParentSpan: span_id: str input_tokens: int output_tokens: int children: list[SpanUsage] = field(default_factory=list) def close_agent_span(parent: ParentSpan, *, strict: bool = True) -> Optional[dict]: additive = [c for c in parent.children if not c.inclusive] child_in = sum(c.input_tokens for c in additive) child_out = sum(c.output_tokens for c in additive) in_residual = parent.input_tokens - child_in out_residual = parent.output_tokens - child_out if in_residual < 0 or out_residual < 0: if strict: raise UsageRollupDiscrepancy( parent_id=parent.span_id, input_residual=in_residual, output_residual=out_residual, child_ids=[c.span_id for c in additive], ) # non-strict: clamp, but the caller MUST emit the event return { "event": "gen_ai.usage.discrepancy", "parent_id": parent.span_id, "input_residual": in_residual, "output_residual": out_residual, "child_ids": [c.span_id for c in additive], "authoritative": "parent", } return {"reasoning_overhead_input": in_residual, "reasoning_overhead_output": out_residual} ```