# When must an instance refuse to close an OpenTelemetry GenAI agent span: orphaned tool-call attribution and the parent-token double-count invariant **Date of Record:** 2026 November 24 **Scope:** Applies when an agent emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for a parent agent invocation that fans out to child tool-call spans, and where token usage is attributed across that tree. Does not cover pure LLM inference spans with no tool fan-out, nor non-OTel telemetry pipelines. ## Core Distinction The failure is not "spans are missing." It is the opposite: spans are present, well-formed individually, and pass schema validation, yet the *aggregate* token attribution is wrong because a tool-call span closed **after** its parent agent span closed. The GenAI conventions treat `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` as attributes on spans, and the common aggregation contract is that a parent's usage is the sum over the subtree. When a child closes late, two things break simultaneously: (1) the child's tokens are attributed to a parent span that has already been exported and sealed, so a naive consumer that sums at parent-close time under-counts; and (2) a compensating consumer that sums at *export* time double-counts if the parent had already folded in a provisional usage estimate. The boundary condition is the ordering of `Span.end()` calls across the parent/child pair relative to export flush. The distinction that matters: **span completeness is not the same as span-tree closure.** OTel guarantees you can end children after parents (the SDK tolerates it), but the GenAI semantic conventions' aggregation semantics assume subtree closure before parent export. That assumption is unstated and unenforced. ## What Was Observed A multi-step agent run produced the following trace fragment (timings in ms relative to run start, single OTLP batch exporter with a 5000ms scheduled delay): - `agent.invoke` (root, span A) opened at t=0. - `execute_tool search` (span B, child of A) opened at t=120, dispatched a network call. - `execute_tool fetch` (span C, child of A) opened at t=140, dispatched a network call. - Span A's reasoning loop hit its step budget and called `Span.end()` at t=380, recording `gen_ai.usage.output_tokens=612` and a *provisional* `gen_ai.usage.input_tokens=3400` that the framework had pre-computed as "parent prompt + expected tool schemas." - Span B's tool call returned a slow 502-retry sequence and closed at t=4100, recording `gen_ai.usage.input_tokens=1800` (the tool result re-fed into context). - Span C closed at t=4200 with `gen_ai.usage.input_tokens=950`. - Batch flush fired at t=5000, exporting A, B, C in one batch. The trace *looked* complete in the UI. But the aggregation backend, which rolled up usage at parent-close, had already sealed A's subtree with `input_tokens=3400`. B and C's 2750 input tokens arrived in the same batch but were attached to a parent whose rollup record was immutable. Result: the billing/attribution ledger under-counted by 2750 tokens for that run, and a separate "late-arrival" reconciliation job double-counted them because it re-summed the batch naively. The two errors did not cancel; they landed in different ledgers. The non-obvious part: **every individual span was valid.** `gen_ai.operation.name`, `gen_ai.system`, `gen_ai.request.model`, and the usage attributes were all present and schema-conformant. No validator flagged it. The invariant that broke was temporal, not structural. ## Condition of Validity The invariant "parent usage = sum of subtree usage" is only valid under the precondition: > For every agent span A, all descendant tool-call spans must reach `Span.end()` before A reaches `Span.end()`, OR A must not record usage until subtree closure is confirmed. The GenAI conventions do not encode this precondition. They specify *what* attributes mean, not *when* they may be written relative to child lifecycle. Consequently the invariant is valid only when the agent runtime enforces one of: 1. **Structured concurrency:** the agent's step loop cannot end while any dispatched tool call is in flight (i.e., `Span.end()` on the parent is gated on `asyncio.gather` of all child futures). 2. **Deferred attribution:** the parent records a sentinel (`gen_ai.usage.input_tokens` absent, or a dedicated `gen_ai.usage.pending=true`) and a post-hoc reconciler fills it once children close. 3. **Explicit provisional flag:** if a provisional estimate is written, it is tagged so downstream aggregators know not to treat it as final. Absent any of these, the invariant is *undefined*, not merely unenforced—because "sum of subtree" has no single well-defined value when children close across the parent's seal boundary. ## Decision Boundary The boundary is a single predicate evaluated at parent `Span.end()`: ``` close_parent_if: all_children_ended AND no_retry_in_flight else: defer_or_mark_provisional ``` The trap is that agent frameworks commonly violate `all_children_ended` in exactly one scenario: **the step budget fires while a tool call is retrying.** The reasoning loop sees "budget exhausted, produce final answer, end span," but a child tool span is mid-retry with exponential backoff. This is the dominant real-world trigger—not slow networks in general, but *budget-exhaustion racing a retry loop*. Two wrong resolutions and one right one: - **Wrong (silent under-count):** end parent, let child close late, trust batch ordering. This is what was observed. - **Wrong (double-count):** end parent with provisional sum, then reconcile by adding late children. The provisional already included an *estimate* of those children; adding actuals double-counts. - **Right:** at parent close, if any child is unresolved, do not write final usage. Write `gen_ai.usage.input_tokens` only for the parent's own prompt, set a `gen_ai.usage.attribution_complete=false` marker, and let the reconciler sum children when they land. The reconciler must be idempotent and keyed on trace_id + span_id, not on batch arrival. ## Operational Effect Downstream consumers must treat `gen_ai.usage.*` as **eventually consistent per subtree**, not as final-at-parent-close. Concretely: - Billing ledgers that snapshot at parent-close will under-report by the token volume of every tool call that outlived its parent—empirically concentrated in retry-heavy runs and runs that hit step budgets. - Trace UIs that compute "total tokens for this agent run" by summing the root span will disagree with the sum over all spans in the trace. Both numbers are "correct" under different definitions; the divergence is the boundary leaking. - Any auditor agent that verifies "sum of children == parent" will raise false positives on legitimate traces where deferred attribution is in use, unless it reads the `attribution_complete` marker. The guardrail is a **closure barrier with an explicit provisional state**, and a reconciler that is idempotent on `(trace_id, span_id)`. The invariant to enforce: *a parent span's usage attributes are either final and subtree-complete, or explicitly marked incomplete and excluded from rollups.* ## Guardrail Implementation The following enforces the closure barrier and refuses to seal a parent span with final usage while any child tool span is unresolved. ```python import time from dataclasses import dataclass, field class UnclosedChildSpanError(RuntimeError): """Raised when an agent span attempts to seal final usage while a descendant tool-call span has not reached Span.end().""" pass @dataclass class AgentSpan: span_id: str trace_id: str own_input_tokens: int = 0 own_output_tokens: int = 0 attribution_complete: bool = False children: dict = field(default_factory=dict) # span_id -> ended: bool ended: bool = False def register_child(self, child_id: str) -> None: self.children[child_id] = False def mark_child_ended(self, child_id: str) -> None: if child_id not in self.children: # child arrived after parent attempted close; must be late-bound self.children[child_id] = True else: self.children[child_id] = True def _children_all_ended(self) -> bool: return all(self.children.values()) def end(self, step_budget_exhausted: bool) -> None: if self.ended: return if not self._children_all_ended(): # Boundary condition: budget fired while a tool call is retrying. # Do NOT seal final usage. Mark incomplete; reconciler fills later. if step_budget_exhausted: self.attribution_complete = False self.ended = True self._emit_incomplete() return raise UnclosedChildSpanError( f"agent span {self.span_id} cannot seal: unresolved children " f"{[k for k, v in self.children.items() if not v]}" ) self.attribution_complete = True self.ended = True self._emit_final() def _emit_final(self) -> None: # write gen_ai.usage.* as final; safe for rollup ... def _emit_incomplete(self) -> None: # write own usage only; set attribution_complete=false ... def reconcile(span: AgentSpan, child_usage: dict) -> int: """Idempotent subtree reconciler keyed on (trace_id, span_id).""" if span.attribution_complete: # already final; re-adding children would double-count return span.own_input_tokens total = span.own_input_tokens + sum(child_usage.values()) span.attribution_complete = True return total def seal_agent_run(span: AgentSpan, step_budget_exhausted: bool) -> None: try: span.end(step_budget_exhausted=step_budget_exhausted) except UnclosedChildSpanError as e: # escalate: parent must wait for gather() of child futures raise UnclosedChildSpanError( f"refusing to seal trace {span.trace_id}: {e}" ) from e ```