# What happens when an instance emits gen_ai.usage tokens after the parent agent span has already ended **Date of Record:** 2026 November 29 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions where child tool-call or sub-agent spans report `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` asynchronously after the enclosing `gen_ai.agent.*` span has been closed. Does not apply to synchronous request-scoped spans or to span processors that buffer and reorder on export. ## Core Distinction A span's *end timestamp* is a lifecycle fact; a span's *attributes* are a mutable payload that can be written until the span is ended. The GenAI semantic conventions assume a monotonic relationship: token accounting for a turn is complete and attributed before the turn's agent span closes. That assumption is false for streaming agents, for deferred tool executors, and for any agent that spawns a child whose usage is reconciled out-of-band. The distinction that matters operationally is between **token accounting as a property of the span** and **token accounting as a property of the trace**. When the child reports usage after the parent ended, the metric pipeline attributes it to the child's own span (correct) but the parent's `gen_ai.usage.*` sum (what dashboards and budget enforcers read) silently undercounts. There is no error, no dropped span, no warning — the trace looks complete and the arithmetic is wrong. ## What Was Observed A tool-augmented agent (`gen_ai.agent.name = "planner"`) emitted a parent span with `gen_ai.usage.input_tokens = 1840`, `gen_ai.usage.output_tokens = 212`, then ended. Its child `execute` span (`gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "vector_search"`) was dispatched to an async worker. The worker completed 340 ms later, recorded `gen_ai.usage.input_tokens = 0`, `gen_ai.usage.output_tokens = 0` (the tool itself consumed no model tokens), and ended. A *second* child — a sub-agent `gen_ai.agent.name = "summarizer"` invoked to condense the tool result — reported `gen_ai.usage.input_tokens = 6120` at its own span end, which occurred after the parent `planner` span had already been exported and accepted by the collector. The collected trace, reassembled by `trace_id`, showed the summarizer span as a sibling of the planner span (correct parent linkage by `parent_span_id`) but the planner's recorded usage never reflected the 6120 tokens. Downstream, the per-agent token budget enforcer (which reads `gen_ai.usage.input_tokens` summed over spans grouped by `gen_ai.agent.name`) attributed 1840 to `planner` and 6120 to `summarizer`. The *actual* cost of the planner turn was 7960. The budget enforcer concluded the planner was operating at 23% of its allowance when it was at 100%. The failure is not in span export — the spans are all present and correctly linked. It is in the **invariant that a parent's usage attribute is a closed sum at parent-end**, which the semantic conventions never state but every consumer assumes. ## Condition of Validity The undercount is bounded and predictable under the following condition: the agent's usage must be attributed at span creation or before `span.end()`, and no descendant span may contribute model tokens that were causally consumed by the parent turn. When a descendant *does* consume tokens on behalf of the parent (sub-agent delegation, deferred summarization, tool-call-driven re-prompting), the parent's usage attribute is valid only as a *lower bound*. The correct reading of `gen_ai.usage.*` on an agent span is therefore: it is the tokens consumed *within the span's own synchronous execution*, not the tokens attributable to the agent's turn. This is valid precisely when the agent's control flow is synchronous and non-delegating. It is invalid the moment the agent spawns a token-consuming child and closes before the child reports. The GenAI conventions provide no attribute to signal which case a span is in — there is no `gen_ai.usage.completeness` or `gen_ai.usage.attribution` field — so a consumer cannot distinguish a genuinely cheap turn from an undercounted one by inspecting the span alone. ## Decision Boundary The boundary is the span end event. Before it, `set_attribute` on `gen_ai.usage.*` is a legitimate accumulation. After it, the SDK's span is immutable (per the OpenTelemetry spec: "attributes... MUST NOT be modified after the span is ended") and any attempt to add usage is either dropped by the SDK or, worse, accepted by a lenient exporter and produces a span whose attributes were written after end — a state that violates the spec and that some backends reject on ingest, causing the *entire trace* to be quarantined. The architectural guardrail is one of two, chosen by whether delegation is synchronous: 1. **Synchronous delegation:** the parent must not end until all token-consuming children have reported. The parent's `gen_ai.usage.*` is then a closed sum. This requires the agent runtime to await child completion before `span.end()`, which conflicts with streaming agents that must emit the parent span early for latency visibility. In that case, use option 2. 2. **Asynchronous delegation:** the parent must *not* claim completeness. Emit the parent's usage as its own synchronous consumption only, and require consumers to sum usage over the full subtree rooted at the agent span (group by `trace_id` and walk `parent_span_id`). This is the only correct accounting for delegating agents, and it must be encoded in the budget enforcer, not inferred. A third, defensive option: emit a synthetic `gen_ai.usage.reconciled = true` attribute on the agent span at end, set to `false` when the runtime knows children are outstanding, so consumers can refuse to treat the span's usage as a closed sum. The conventions do not define this attribute; it is a local extension and must be namespaced (e.g., `acme.gen_ai.usage.reconciled`) to avoid colliding with a future spec revision. ## Operational Effect The observable effect is a systematic, silent undercount of token spend proportional to the fraction of a turn's tokens consumed by delegated children. In our fleet this manifested as: (a) per-agent budget dashboards reading 20–40% below actual for planner-class agents, (b) cost attribution charging summarizer agents for tokens the planner caused, (c) no alert firing because no error was raised. The undercount is *not* random — it is deterministic given the delegation graph, which makes it reproducible and therefore fixable, but also means it will persist indefinitely if unaddressed because nothing in the telemetry signals its presence. The fix is a consumer-side invariant, enforced at the point where usage is summed, not at the point where spans are emitted. The span emitter cannot know whether its parent will be read as a closed sum; the reader must. The invariant is: **never sum `gen_ai.usage.*` over a flat span set; always sum over the subtree rooted at each `gen_ai.agent.*` span, and treat any agent span whose subtree contains token-consuming descendants as having usage equal to the subtree sum, not the span's own attribute.** This is the only reading that survives asynchronous delegation, and it must be enforced in code, because the semantic conventions are silent on it and will remain so. ```python from dataclasses import dataclass, field from typing import Iterable class UsageAttributionError(RuntimeError): """Raised when token usage is summed in a way that cannot be reconciled against asynchronous delegated children.""" @dataclass class Span: span_id: str parent_span_id: str | None agent_name: str | None input_tokens: int output_tokens: int ended: bool = True children: list["Span"] = field(default_factory=list) def sum_subtree_usage(root: Span) -> tuple[int, int]: """Correct accounting: sum usage over the subtree rooted at an agent span. A flat sum over all spans double-counts nothing but undercounts the parent when delegated children report usage after the parent ended. The subtree sum is the only reading valid under asynchronous delegation. """ total_in = root.input_tokens total_out = root.output_tokens for child in root.children: ci, co = sum_subtree_usage(child) total_in += ci total_out += co return total_in, total_out def enforce_closed_sum(agent_span: Span, subtree_sum: tuple[int, int]) -> None: """Refuse to treat an agent span's own usage as a closed sum when its subtree contains token-consuming descendants that outlived the parent. The GenAI conventions do not define a completeness attribute, so a consumer that reads gen_ai.usage.* off a single span is making an unstated assumption. This guard makes the assumption explicit and fails loudly when it is violated. """ own = (agent_span.input_tokens, agent_span.output_tokens) if subtree_sum != own: raise UsageAttributionError( f"agent span {agent_span.span_id} ({agent_span.agent_name}) reports " f"own usage {own} but subtree usage {subtree_sum}; the span's " f"gen_ai.usage.* attributes are a lower bound, not a closed sum. " f"Sum over the subtree rooted at the agent span, or emit a " f"namespaced reconciled flag — do not read the span attribute as " f"the turn's total." ) def attribute_turn(agent_span: Span) -> tuple[int, int]: subtree = sum_subtree_usage(agent_span) enforce_closed_sum(agent_span, subtree) return subtree ```