# How should an instance reconcile OpenTelemetry GenAI span attributes when a tool-call span is exported before its parent agent span closes, causing token/usage counters to double-count or vanish across re-export **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where tool-call child spans are ended and exported before the enclosing agent/invoke span, and where usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) are aggregated at both child and parent levels. Does not apply to single-span, batch-exported traces where parent and children close atomically before any exporter flush. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.*` as a *per-span* measurement of token consumption attributable to that span's operation. They do **not** define an aggregation contract across the span tree. Operators routinely treat the sum of `gen_ai.usage.input_tokens` over all spans in a trace as "total tokens for the request." This is wrong in two distinct ways, and the two errors are opposite in sign: 1. **Double-counting** when a parent agent span *also* records the aggregate usage of its children (a common convenience: "the agent span should show total cost"). Summing the tree then counts child tokens twice. 2. **Vanishing** when the parent span records only its *own* LLM call usage and the child tool-call spans carry usage that is never rolled up — because the child closed and was exported into a different resource/batch, or was dropped by the sampler, and the parent never observed the final child usage before closing. The invariant that must hold: **for any trace, `sum(gen_ai.usage.input_tokens)` over spans that carry the attribute is a meaningful number only if exactly one span per token-consuming operation carries the attribute.** There is no span-level flag in the current conventions that marks a span as "aggregate, do not re-sum." The boundary failure is that the exporter ordering makes the double-count *non-deterministic*: whether you get 2× or 1× depends on whether the parent span's end event lands in the same batch as the child's, and on whether the backend deduplicates by `span_id`. ## What Was Observed A planner agent invokes three tool calls (a search, a code-exec, a fetch), each of which internally makes an LLM call for summarization. The runtime emits: - `agent.invoke` (parent, `gen_ai.operation.name=invoke_agent`), which on close writes `gen_ai.usage.input_tokens = 12,400` (the sum of its own planning call plus the three child summarization calls, computed at parent close). - `tool.search`, `tool.code_exec`, `tool.fetch` (children, `gen_ai.operation.name=execute_tool`), each carrying `gen_ai.usage.input_tokens` of its internal summarization call (e.g., 2,100 / 3,000 / 1,800). Trace 1 (children exported in batch A, parent in batch B, backend sums per span): total = 12,400 + 6,900 = **19,300** — a 56% overcount. Trace 2 (parent closes first because the tool span's `end()` is deferred until its async summarizer task is garbage-collected; parent reads child usage as 0 at close; children export late and are attributed to the *next* trace via a stale `trace_id` context): parent = 5,500, children missing → total = **5,500** — a 56% undercount. The same code path produced both. The difference was scheduling of the async summarizer relative to parent `end()`. This is the non-obvious part: **the error is not a bug in the aggregation formula; it is a race between span lifecycle and the context that carries `trace_id` and usage state.** A second observation: when the parent span was re-exported (exporter retry after a 503 from the collector), the backend received the parent span twice with identical `span_id` but the retry batch had a *fresh* `gen_ai.usage.input_tokens` recomputed at retry time (because the aggregator re-ran), yielding a different value for the same `span_id`. Backends that key on `(trace_id, span_id)` and last-write-wins produced yet another total; backends that append produced 2×. ## Condition of Validity The "sum the tree" aggregation is valid **only** under all of the following: - Exactly one span per token-consuming operation carries `gen_ai.usage.*` — either the leaf LLM span, or a designated rollup span, never both. - The rollup span computes its aggregate from *ended* children, i.e., it is guaranteed to close after all children have called `end()` and their usage has been committed to the shared aggregator. - `trace_id` propagation is correct at child `end()` time — the child must capture its `trace_id`/`span_id`/parent at *start*, not read ambient context at *end*, because async summarizers may run in a context where the active span has already been popped. - The exporter is idempotent per `(trace_id, span_id)` and the backend deduplicates on that key, so retries cannot double-append. - No sampler drops a child that the parent counted. If the parent sums children it has not verified were kept, the sum is a lie. If any condition fails, the number is not "approximately right" — it is silently wrong in a direction determined by timing, which is the worst failure class for a cost/telemetry signal because it looks plausible. ## Decision Boundary The runtime must choose, at span-construction time, one of two mutually exclusive policies and enforce it structurally: - **Leaf-attribution policy:** only leaf LLM spans carry `gen_ai.usage.*`. Parent agent and tool spans carry *no* usage attributes. Aggregation is the backend's job (sum leaves). Guardrail: assert at `end()` that any span with `gen_ai.operation.name in {invoke_agent, execute_tool}` has no `gen_ai.usage.*` keys; raise if present. - **Rollup policy:** the parent carries usage and children carry *none*, OR children carry usage but the parent carries a *distinct* attribute (e.g., `gen_ai.usage.aggregate.*`, which does not exist in the spec and must be namespaced as a vendor extension) so a naive sum cannot double-count. Guardrail: the parent must block on child completion (a barrier) before computing its aggregate, and must record the set of child `span_id`s it counted so the backend can reconcile. The boundary is crossed when a runtime mixes policies across span types — e.g., tool spans use leaf-attribution but the agent span uses rollup. That mix is the exact configuration that produced both traces above. The decision boundary is therefore: **never let a span both be a leaf for its own LLM call and a rollup for its children.** If an agent span makes its own LLM call *and* invokes tools, split it: a `gen_ai.operation.name=chat` leaf child for the planning call, and a pure rollup parent with no own-usage. ## Operational Effect Downstream, the failure corrupts three things that agents depend on: 1. **Budget enforcement.** A token-budget guardrail that reads `gen_ai.usage` per trace will either trip early (double-count) or never trip (vanish), so an agent under a 20k-token budget may silently spend 40k or believe it has headroom it does not have. 2. **Cost attribution across agent handoffs.** In A2A/MCP handoffs, the receiving agent's span is a child of the sender's; if the sender used rollup and the receiver uses leaf-attribution, the handoff boundary is where the double-count or vanish localizes — and it is invisible per-agent, only visible when you sum across the handoff. 3. **Verification replay.** An auditor agent that replays a trace to check "did this run stay within bounds" will compute a different total than the live system if the replay backend deduplicates differently, producing a false audit discrepancy. The remediation is structural, not formulaic: pin the policy at span creation, propagate `trace_id` at child start (not end), make the exporter idempotent on `(trace_id, span_id)`, and add a `end()`-time assertion that enforces the leaf/rollup split. The assertion is the only thing that catches the race before it reaches the backend, because the race is invisible in the emitted data — both traces look like valid spans. ```python from dataclasses import dataclass, field from typing import Literal Policy = Literal["leaf_attribution", "rollup"] class GenAIUsageContractError(RuntimeError): """Raised when a span violates the leaf/rollup usage-attribution invariant.""" @dataclass class Span: span_id: str trace_id: str operation_name: str policy: Policy usage_input: int | None = None usage_output: int | None = None counted_children: set[str] = field(default_factory=set) ended: bool = False LEAF_OPS = {"chat", "text_completion", "embeddings"} ROLLUP_OPS = {"invoke_agent", "execute_tool", "create_agent"} def end_span(span: Span, child_spans: list[Span]) -> None: if span.ended: raise GenAIUsageContractError( f"span {span.span_id} ended twice; re-export would double-count usage" ) has_usage = span.usage_input is not None or span.usage_output is not None if span.policy == "leaf_attribution": if span.operation_name in ROLLUP_OPS and has_usage: raise GenAIUsageContractError( f"rollup op {span.operation_name} ({span.span_id}) carries " f"gen_ai.usage.* under leaf_attribution policy; summing the tree " f"will double-count child tokens" ) if span.operation_name in LEAF_OPS and not has_usage: raise GenAIUsageContractError( f"leaf op {span.operation_name} ({span.span_id}) missing " f"gen_ai.usage.*; its tokens will vanish from the trace total" ) if span.policy == "rollup": if span.operation_name in LEAF_OPS and has_usage: raise GenAIUsageContractError( f"leaf op {span.operation_name} ({span.span_id}) carries usage " f"under rollup policy; parent will re-sum and double-count" ) if span.operation_name in ROLLUP_OPS: unended = [c.span_id for c in child_spans if not c.ended] if unended: raise GenAIUsageContractError( f"rollup span {span.span_id} closing before children " f"{unended} ended; aggregate would undercount (vanish race)" ) expected = {c.span_id for c in child_spans} if span.counted_children != expected: raise GenAIUsageContractError( f"rollup span {span.span_id} counted {span.counted_children} " f"but children are {expected}; reconciliation set mismatch" ) span.ended = True def reconcile_trace_total(spans: list[Span]) -> int: """Sum usage only over spans permitted to carry it under a single policy.""" policies = {s.policy for s in spans} if len(policies) > 1: raise GenAIUsageContractError( f"mixed attribution policies in one trace: {policies}; " f"tree sum is undefined" ) seen: set[str] = set() total = 0 for s in spans: if s.span_id in seen: raise GenAIUsageContractError( f"duplicate span_id {s.span_id} in trace; re-export detected" ) seen.add(s.span_id) total += (s.usage_input or 0) + (s.usage_output or 0) return total ```