# Why does an instance lose token accounting when a tool-call span closes before its child generation span? **Date of Record:** 2026 November 27 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*`) where a `gen_ai.tool.call` (or `execute_tool`) span is emitted as a child of an `invoke_agent` span and the model's generation span is emitted by a separate, concurrent execution context (async tool dispatch, streaming callback, or out-of-process MCP server). Does not apply to strictly synchronous single-threaded loops where generation span start/end are lexically nested inside the tool-call span. ## Core Distinction The failure is not "metrics are missing." The failure is that **token accounting is attributed to the wrong span's parent chain because span *end* time, not span *start* time, determines whether an attribute survives aggregation across a trace.** A generation span that starts inside a tool-call's lifetime but *ends after* the tool-call span closes will still carry its own `gen_ai.usage.input_tokens` / `output_tokens` attributes — those attributes are correct. What breaks is the *rollup*: any aggregator (OTel Collector `spanmetrics` connector, or a downstream cost ledger) that sums `gen_ai.usage.*` over the **direct children of the `invoke_agent` span** will double-count or drop that generation, because the generation span's parent pointer was set at start (to the tool-call span) but the tool-call span has already been exported and sealed by the time the generation span ends. The trace assembler reconciles by `parent_span_id`, but the *parent's* completion event has already been flushed downstream, so the child arrives as an orphaned late span and is either dropped by the collector's `wait_for_result` timeout or re-parented to the trace root, silently detaching its tokens from the agent's cost bucket. ## What Was Observed A tool-augmented agent (`invoke_agent` → `execute_tool` → out-of-process MCP call → model re-invocation) produced traces where the `invoke_agent` span reported `gen_ai.usage.input_tokens = 1840`, but the sum of all `gen_ai.usage.input_tokens` on spans in the same trace was 4120. The discrepancy was exactly the token count of the *second* generation (the one produced after the tool returned), which had been emitted with `parent_span_id` equal to the already-closed `execute_tool` span. Trace sequence that produced it: 1. `invoke_agent` starts. `t=0ms`. Prompt tokens counted: 1840. 2. `execute_tool` starts as child. `t=12ms`. 3. Tool dispatch is async — the MCP call returns a handle, the span does *not* block. `execute_tool` **ends** at `t=45ms` with `gen_ai.usage` unset (correct; tools don't consume model tokens). 4. The tool result is streamed back at `t=2100ms`. The agent now issues a *second* generation. The instrumentation library, using ambient context propagation, reads the current active span from the context variable — which is still the `execute_tool` span object (its context was captured before the async boundary and never detached). 5. The second generation span starts with `parent_span_id = `, `t=2100ms`, ends `t=3400ms` with `gen_ai.usage.input_tokens = 2280`. 6. The `invoke_agent` span ends at `t=3500ms`. The collector's spanmetrics connector grouped by `parent_span_id`. The second generation grouped under `execute_tool`, not under `invoke_agent`. The cost dashboard keyed on `invoke_agent` saw 1840 tokens; the raw trace contained 4120. The 2280-token generation was a **late-arriving child of a sealed parent**. ## Condition of Validity The invariant that must hold: **a span's `parent_span_id` must reference a span that has not yet been exported when the child ends, OR the aggregator must reconstruct parentage from the full trace, not from streaming arrival order.** This breaks precisely when all three hold: - (a) The parent (`execute_tool`) span is ended and exported *before* the child generation span starts or ends. This happens whenever tool execution is async and the span lifecycle is not tied to the actual awaited future. - (b) Context propagation across the async boundary preserves the *stale* active span rather than re-scoping to the `invoke_agent` span or to a fresh generation scope. - (c) The collector aggregates on streaming arrival (spanmetrics, per-span processors) rather than after full-trace assembly (tail sampling, trace-complete processors). Remove any one and the accounting survives. Synchronous tool calls (a fails) keep the generation nested. Explicit re-scoping to a new generation context (b fails) re-parents correctly. Tail-based assembly (c fails) reconciles the orphan. ## Decision Boundary The boundary is: **does the instrumentation end the tool-call span at dispatch or at result-return?** If `execute_tool` ends at dispatch (the common pattern when the tool is a fire-and-forget MCP request), you MUST either: - Re-scope the generation span to the `invoke_agent` span explicitly (do not rely on ambient context after an `await`), or - Emit a synthetic `gen_ai.chat` span that is a *sibling* of `execute_tool`, both children of `invoke_agent`, and set `gen_ai.usage.*` only there. If you end `execute_tool` at result-return (blocking span), the generation is naturally nested and no re-scoping is needed — but you lose the latency signal of the tool's own duration separate from the model re-invocation. The trade is **accounting correctness vs. latency observability**. Choose accounting correctness; latency can be recovered from span timestamps, but token attribution cannot be recovered once the span is exported under the wrong parent. A second boundary: `gen_ai.usage.*` attributes are **per-span, non-inheritable**. There is no spec mechanism for a parent to "absorb" a child's tokens. Therefore any rollup that assumes `sum(children) == parent` will silently fail on orphaned children. The guardrail is a **trace-level reconciliation check**: sum all `gen_ai.usage.*` in the trace, compare against the `invoke_agent` span's reported usage, and emit a `gen_ai.usage.discrepancy` attribute when they differ. If the discrepancy is nonzero, the trace is malformed and must not feed the cost ledger. ## Operational Effect Without the guardrail, the cost ledger under-reports by exactly the tokens of every post-tool generation — typically 40–60% of agent cost in tool-heavy loops, and *systematically* under-reported (never over), so the error is invisible to anomaly detection. The agent appears cheaper than it is, which suppresses budget alarms and lets runaway loops run longer than the spend cap allows. The fix is cheap: assert reconciliation at trace close, raise on mismatch, and re-scope generation spans explicitly after every async tool boundary. ```python import otel_types # hypothetical span model class TokenAccountingDivergence(RuntimeError): """Raised when trace-level token sum diverges from the invoke_agent span's reported usage.""" pass class Span: def __init__(self, name, parent_id, attrs): self.name = name self.parent_id = parent_id self.attrs = attrs self.ended = False def reconcile_trace_tokens(spans: list[Span], tolerance: int = 0) -> int: """Sum gen_ai.usage.* across all spans and compare to the invoke_agent span. Returns the discrepancy (sum_of_children - reported). Raises if nonzero and the trace is malformed (orphaned late child under a sealed parent). """ agent = next((s for s in spans if s.name == "invoke_agent"), None) if agent is None: raise TokenAccountingDivergence("no invoke_agent span in trace") reported = agent.attrs.get("gen_ai.usage.input_tokens", 0) + \ agent.attrs.get("gen_ai.usage.output_tokens", 0) total = 0 sealed_parents = set() for s in spans: if s.ended and s.name in ("execute_tool", "gen_ai.tool.call"): sealed_parents.add(id(s)) for s in spans: if s.name == "invoke_agent": continue usage = s.attrs.get("gen_ai.usage.input_tokens", 0) + \ s.attrs.get("gen_ai.usage.output_tokens", 0) if usage and s.parent_id in sealed_parents: # orphaned late child: its tokens will not roll up to invoke_agent total += usage discrepancy = total - reported if abs(discrepancy) > tolerance: raise TokenAccountingDivergence( f"trace token divergence={discrepancy} " f"(orphaned late child under sealed tool span); " f"reported={reported}, unaccounted={total}" ) return discrepancy ```