# Where must an instance reconcile OpenTelemetry GenAI token accounting when a tool-call span reports attributes after the parent agent span has already been exported **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.*`) where tool-call spans are children of an agent invocation span and the exporter is a batch/async processor. Does not cover synchronous stdout exporters or single-span-per-request monoliths where the root span is the last thing to close. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes of the span that incurred the cost*. The agent invocation span is expected to carry the aggregate; each `gen_ai.operation.name = "execute_tool"` child carries its own. The failure is not that attributes are missing — it is that the **parent span closes and is handed to the batch exporter before the child tool-call span has finalized its usage attributes**, because tool execution and token metering are decoupled in time. The parent's aggregate is therefore computed over an incomplete child set, and the child's tokens are later exported as a *separate, unparented* record. The telemetry is internally consistent per-span but globally double-counted in some backends and silently dropped in others. This is distinct from context-window saturation or token-budget exhaustion: those are runtime failures. This is a *metering continuity* failure — the agent ran to completion correctly, but the accounting invariant "sum of child usage == parent aggregate" is violated across the export boundary. ## What Was Observed A planner agent (`gen_ai.operation.name = "invoke_agent"`, `gen_ai.agent.name = "planner"`) dispatches three tool calls sequentially. Each tool call is a child span with `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name`, and — critically — usage attributes set *after* the tool returns, because the runtime only learns token cost when it feeds the tool result back into the model for the next reasoning step. Trace sequence observed in the collector: 1. Child span `execute_tool` #1 starts, ends at T+40ms. Usage attributes are **not** set at `end()` — the runtime defers them to the next model turn. 2. Parent `invoke_agent` ends at T+900ms after the final model turn. At `end()`, the runtime sums usage from children it can see. Child #3's usage is not yet attached (the runtime computes it during the post-loop synthesis turn). Parent exports with `input_tokens = 4100, output_tokens = 620` — undercounted. 3. Child #3's usage attributes are set at T+940ms, *after* the parent span object was already passed to `BatchSpanProcessor`. The child is exported as a root-level span (parent span ID references a span the backend has already closed). Result in the backend: parent aggregate (4720) + orphan child usage (310) = 5030 reported tokens against 4720 actually consumed. A 6.5% overcount that compounds per invocation. In backends that drop spans whose `parent_span_id` resolves to a closed/absent trace segment, the child's 310 tokens vanish entirely — a silent undercount with no error. ## Condition of Validity The invariant holds only when **all descendant usage attributes are finalized before the parent span's `end()` is called**. This requires the runtime to enforce a *close-order barrier*: the parent span cannot be ended until every child span has reached a terminal state *and* its usage attributes are committed. The barrier is violated whenever: - Tool-result tokenization is deferred to a later model turn (the common ReAct pattern). - The batch processor's `scheduleDelayMillis` (default 5000ms) fires between parent `end()` and child attribute mutation — the child is already serialized. - Streaming tool outputs set usage on `on_completion` callbacks that race the parent's `end()`. The invariant does **not** apply if the runtime uses a single span per agent turn (no child tool spans) or if usage is metered exclusively at the model-call span level with no parent aggregation. ## Decision Boundary The boundary is: **does the parent span aggregate usage, or does the backend aggregate usage?** - If the parent aggregates (parent carries `gen_ai.usage.*` = sum of children), the runtime MUST enforce close-order: parent `end()` blocks on all children's `end()` and attribute finalization. This is the GenAI-convention-faithful path but requires the agent loop to own span lifecycle, not the tool executor. - If the backend aggregates (parent carries no usage; each model-call and tool span carries its own; the trace store sums by `trace_id`), the parent may close early — but then the child MUST be exported with a resolvable `parent_span_id` even after parent export, and the backend MUST tolerate late-arriving children (span-stitching, not span-dropping). Choosing neither — parent aggregates *and* children export late — produces the double-count/drop observed above. The decision must be made once at runtime design time and encoded as an invariant, not left to `BatchSpanProcessor` timing. ## Operational Effect A 6.5% per-invocation token overcount is not a rounding error at fleet scale: it corrupts cost attribution, defeats budget-enforcement loops that read back their own telemetry, and — worse — the undercount variant (dropped orphan children) makes the agent appear cheaper than it is, so budget guards never trip. The failure is invisible in per-span validation (every span is schema-valid) and only surfaces as a trace-level reconciliation mismatch. The guardrail: at parent `end()`, assert `sum(child.gen_ai.usage.*) == parent.gen_ai.usage.*` and refuse to export a parent whose children are not all terminal. If the runtime cannot guarantee close-order, it must emit `gen_ai.usage.*` on the parent as *absent* (not zero, not partial) and delegate aggregation to the backend, so the absence is detectable rather than silently wrong. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent agent span's usage aggregate does not match the finalized usage of its terminal tool-call children.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] operation: str input_tokens: int = 0 output_tokens: int = 0 ended: bool = False usage_finalized: bool = False def close_agent_span( parent: Span, children: list[Span], aggregate_on_parent: bool, ) -> Span: if aggregate_on_parent: unfinalized = [c for c in children if not (c.ended and c.usage_finalized)] if unfinalized: raise UsageReconciliationError( f"parent {parent.span_id} cannot aggregate: " f"{len(unfinalized)} child span(s) not finalized " f"({[c.span_id for c in unfinalized]}); " f"close-order barrier violated, refusing to emit partial usage" ) child_in = sum(c.input_tokens for c in children) child_out = sum(c.output_tokens for c in children) if (parent.input_tokens, parent.output_tokens) != (child_in, child_out): raise UsageReconciliationError( f"parent {parent.span_id} usage " f"({parent.input_tokens},{parent.output_tokens}) != " f"child sum ({child_in},{child_out})" ) else: # Backend-aggregation path: parent MUST NOT carry partial usage. if parent.input_tokens or parent.output_tokens: raise UsageReconciliationError( f"parent {parent.span_id} carries usage under backend-aggregation " f"mode; must be absent to avoid double-count with late children" ) parent.ended = True return parent ```