# What happens when an instance emits OpenTelemetry GenAI spans for an agent turn but the tool-call events are recorded on a child span that outlives the parent's token-accounting boundary **Date of Record:** 2026 November 25 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a single logical agent turn is modeled as a parent span with token-usage attributes and tool invocations are modeled as child spans/events. Does not apply to flat single-span-per-LLM-call instrumentation or to systems where tool execution is fully synchronous and in-process within the parent span's lifetime. ## Core Distinction The GenAI semantic conventions attach cost and token attribution to the *span that called the model*: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and (in newer drafts) `gen_ai.usage.cost.*` live on the inference span. Tool-call telemetry — `gen_ai.tool.name`, `gen_ai.tool.call.id`, request/response payloads — is conventionally emitted as a child span or a span event *under* the agent turn. The distinction that matters: **the token-accounting boundary and the tool-execution boundary are not the same boundary.** A model call ends the moment the response is returned; the tool span it triggered can run for seconds or minutes afterward, and may emit *additional* model calls (retries, sub-agent delegation, self-correction) that each carry their own usage attributes. When the parent agent span is closed on the "model returned" edge rather than the "all tool descendants drained" edge, usage emitted by late descendants is either orphaned onto a sibling context, double-counted against the parent, or silently dropped by the exporter's span-closure ordering. The invariant that fails is an *accounting closure invariant*: `sum(usage over all spans in the trace subtree) == sum(usage attributed to the logical agent turn)`. It holds only if the parent span's end timestamp dominates every descendant that carries `gen_ai.usage.*`. ## What Was Observed A multi-step agent (planner → tool-executor → critic) instrumented with a parent `invoke_agent` span and child `execute_tool` spans. On a run where the planner issued a `search` tool call and the tool-executor, upon receiving a low-quality result, internally issued a *second* model call to reformulate the query, the following trace shape was produced: - Parent span `invoke_agent` closed at T+1.2s with `gen_ai.usage.input_tokens=840`, `output_tokens=210`. - Child span `execute_tool` (search) opened at T+1.1s, closed at T+4.8s. - Grandchild span `chat` (reformulation) opened at T+2.0s, closed at T+3.4s, carrying `gen_ai.usage.input_tokens=310`, `output_tokens=64`. The grandchild's usage was *not* reflected in the parent's attributes (the parent had already closed), and the collector's tail-sampling processor — configured with a per-trace token budget — evaluated the trace at parent-close time, before the grandchild span arrived, and therefore admitted the trace under budget. The grandchild's 374 tokens landed in the backend but were attributed to a trace whose parent span had no corresponding usage, breaking per-turn cost rollups by roughly 30% on this workload. In a second variant, the exporter's batching caused the grandchild to be flushed *before* the parent (out-of-order span arrival due to the child being on a faster network path), and a downstream rollup that summed `gen_ai.usage.*` by `parent_span_id` produced a negative residual on the parent and a positive orphan on the grandchild — a classic double-entry imbalance that surfaced as a cost-attribution drift alert. The mechanism is not "spans arrive late." It is that **the parent span's lifetime is defined by the control-flow return of the agent's top-level function, while the accounting scope of the turn is defined by the transitive closure of model calls reachable from that turn.** These two closures diverge whenever a tool call is (a) asynchronous, (b) internally recursive into the model, or (c) retried after the parent has returned. The GenAI conventions do not define a parent-close barrier over descendants; they only define attribute placement. So the divergence is legal under the spec and invisible to a validator that checks attribute presence rather than subtree closure. ## Condition of Validity The accounting closure invariant holds if and only if all three of the following are true at parent-span close: 1. **Drain condition:** every descendant span carrying any `gen_ai.usage.*` attribute has already ended (its end timestamp ≤ parent end timestamp), or the parent's usage attributes are computed by an aggregator that reads the completed subtree rather than being set inline at parent close. 2. **Sampling condition:** the tail-sampling decision for the trace is deferred until the subtree is drained, or the sampler is configured to treat `gen_ai.usage.*`-bearing spans as decision-critical so late arrivals force re-evaluation. 3. **Attribution condition:** the rollup key is the *root* span of the turn, not the immediate parent of each usage-bearing span, so a grandchild's usage is attributed to the turn rather than to its `execute_tool` parent (which has no usage of its own and would otherwise be the sink). If any one fails, the invariant is violated even though every individual span is well-formed and every attribute is present. This is the non-obvious part: **spec conformance at the span level does not imply conformance at the trace level.** A validator that walks spans and asserts `gen_ai.usage.input_tokens` is an integer will pass a trace that is 30% under-attributed. The condition is *not* valid when tool execution is fully synchronous and in-process (drain is trivial), or when the agent framework already implements a structured-concurrency scope (e.g., a nursery/task-group) that joins all descendants before the parent returns. In those cases the boundary collapse cannot occur and the invariant is vacuous. ## Decision Boundary The operational decision is where to place the parent span's end edge. Three placements are possible, and each has a distinct failure signature: - **Close on model-return (control-flow edge).** Cheapest, matches most framework auto-instrumentation. Fails the drain condition whenever any tool descendant emits usage. Symptom: under-attribution proportional to the fraction of turns with recursive/async tool calls. - **Close on subtree-drain (structured-concurrency edge).** Requires the agent runtime to join all tool tasks before returning from the turn handler. Fails the sampling condition if the tail sampler still decides at first-span-close. Symptom: correct attribution but traces admitted/rejected on stale budget. - **Close on aggregator-flush (post-hoc edge).** Parent usage attributes are written by a batch job that reads the completed subtree. Fails the attribution condition if the rollup keys on immediate parent rather than turn root. Symptom: orphaned usage on tool spans, negative residuals on agent spans. The boundary rule: **choose the edge that matches your sampler's decision point, and make the other two conditions explicit invariants rather than assumptions.** If you cannot join tool tasks (common with fire-and-forget tool dispatch), you must move the sampler decision to aggregator-flush and key the rollup on turn root — you cannot keep the cheap control-flow edge and expect closure. ## Operational Effect The practical consequence is a *silent, workload-dependent cost-attribution error* that is correlated with agent behavior rather than with infrastructure health. Traces look healthy; span counts are normal; latency percentiles are fine. The only signal is a slow divergence between `sum(gen_ai.usage.*)` over the trace and the ground-truth token meter of the model provider, and that divergence grows with the fraction of turns that contain recursive tool calls, retries, or async dispatch. Because the error is one-sided (under-attribution on the parent, orphan on the descendant), it does not cancel and cannot be detected by symmetry checks. The guardrail is a **closure assertion at export time**: for every trace root, assert that the set of usage-bearing spans is exactly the set of spans whose `parent_span_id` chain reaches the root *and* whose end timestamp ≤ root end timestamp; any usage-bearing span with end > root end is a boundary escape and must either re-parent the root's end or be reported as an accounting exception. This converts an invisible drift into a loud, per-trace invariant violation that a sampler or cost pipeline can act on. ```python from dataclasses import dataclass, field class AccountingClosureViolation(RuntimeError): """Raised when a trace's usage-bearing spans escape the turn's accounting boundary.""" @dataclass class SpanRecord: span_id: str parent_span_id: str | None end_ns: int usage_tokens: int = 0 # >0 iff span carries gen_ai.usage.* attributes is_root: bool = False def assert_accounting_closure(spans: list[SpanRecord]) -> int: """Verify the turn-root dominance invariant and return attributed token total. Invariant: every usage-bearing span in the trace subtree must end at or before its turn root's end timestamp. Violations are boundary escapes. """ roots = [s for s in spans if s.is_root] if len(roots) != 1: raise AccountingClosureViolation( f"expected exactly one turn root, found {len(roots)}" ) root = roots[0] # Build child adjacency to compute the subtree reachable from the root. children: dict[str, list[SpanRecord]] = {} by_id = {s.span_id: s for s in spans} for s in spans: if s.parent_span_id is not None: children.setdefault(s.parent_span_id, []).append(s) subtree: list[SpanRecord] = [] stack = [root] while stack: cur = stack.pop() subtree.append(cur) stack.extend(children.get(cur.span_id, [])) seen = {s.span_id for s in subtree} orphans = [s for s in spans if s.span_id not in seen] if orphans: raise AccountingClosureViolation( f"usage-bearing spans outside turn root subtree: " f"{[s.span_id for s in orphans if s.usage_tokens > 0]}" ) escapes = [ s for s in subtree if s.usage_tokens > 0 and s.end_ns > root.end_ns ] if escapes: raise AccountingClosureViolation( "accounting boundary escape: usage-bearing descendants end after " f"turn root {root.span_id} (root_end={root.end_ns}): " f"{[(s.span_id, s.end_ns, s.usage_tokens) for s in escapes]}" ) return sum(s.usage_tokens for s in subtree) ```