# In what scenarios must an instance refuse to close a GenAI agent span when child tool-call spans are orphaned by async token accounting **Date of Record:** 2026 November 27 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where tool-call child spans are emitted by a separate async executor and token usage is attributed to the parent `invoke_agent` span. Does not apply to synchronous single-turn completions with no child spans, or to systems where usage is reported exclusively at the leaf span. ## Core Distinction The failure is not "missing telemetry." It is a **span-close/attribute-mutation ordering violation**: the parent agent span is ended before the async tool executor flushes its child spans and before the token-accounting callback mutates `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on that parent. Under the GenAI conventions, `gen_ai.operation.name = "invoke_agent"` is expected to be a *container* span whose duration and usage envelope its children. When the SDK's `SpanProcessor.on_end` fires, the span is immutable — any later `set_attribute` on the ended span is silently dropped by most exporters (OTLP, Jaeger) but *not* by all in-process collectors. The result is a class of records where the same logical agent turn produces two divergent telemetry views: one where the parent shows zero tokens and no tool children (the exported trace), and one where the parent shows correct tokens and children (the in-memory buffer). Downstream cost attribution, loop-detection, and replay-based verification consume the exported view and therefore under-count. The non-obvious boundary: the invariant "a parent span's `gen_ai.usage.*` attributes are final at `on_end`" is **not enforced by the API** — `set_attribute` after `end()` is a no-op, not an error. The violation is silent. ## What Was Observed A three-step agent turn (`invoke_agent` → `execute_tool` ×2 → `chat` for synthesis) was instrumented with the Python OTel SDK. The tool executor ran on a `ThreadPoolExecutor`; the agent loop awaited it with `asyncio.gather`. Token usage was accumulated by a callback that fired when the provider's streaming response closed, which in practice landed 40–900 ms *after* the agent's `with tracer.start_as_current_span("invoke_agent") as span:` block exited because the `with` block ended on the `return` of the orchestration coroutine, not on the completion of the usage callback. Observed trace record (exported via OTLP to a collector): - `invoke_agent` span: `duration = 812 ms`, `gen_ai.usage.input_tokens = 0`, `gen_ai.usage.output_tokens = 0`, `child_span_count = 0`. - Two `execute_tool` spans present in the collector but with `parent_span_id` pointing to a **different, second `invoke_agent` span** that was created by a retry wrapper — the original parent had already been exported and the orphaned children were re-parented to the retry's trace context by the `ContextVar` still holding the retry span. The re-parenting is the sharp edge. `opentelemetry.context` uses a `ContextVar`; when the async tool task captured the context at `create_task` time, it captured the *current* span — which, after a retry, was the retry span, not the original. The children were not lost; they were **mis-attributed to a sibling span in a different logical attempt**, producing a trace where the retry attempt appears to have executed tools it never called and the original attempt appears to have called none. Token accounting was worse: the usage callback held a reference to the original `span` object and called `span.set_attribute("gen_ai.usage.input_tokens", n)` after `end()`. The SDK dropped the mutation. The retry span, which the callback never saw, exported `input_tokens = 0`. Net effect: the turn's ~14k input tokens were recorded nowhere. ## Condition of Validity The guardrail is valid only under the following conjunction, and must be *disabled* otherwise: 1. The parent span is declared a container: `gen_ai.operation.name = "invoke_agent"` and it is the sole owner of `gen_ai.usage.*` for the turn. 2. Child tool spans are emitted by an executor whose lifetime is *not* lexically nested inside the parent's `with` block (thread pool, `create_task`, background queue). 3. Usage is reported asynchronously relative to span close. If usage is attributed at the leaf `chat` span instead (the alternative convention), the ordering violation disappears and this guardrail is a false positive. If the executor is synchronous and lexically nested, the `with` block guarantees ordering and the guardrail is unnecessary overhead. The guardrail must therefore be gated on an explicit `span_is_container` + `usage_async` capability flag, not applied globally. ## Decision Boundary The decision the runtime must make at `on_end`: - **If** the span is a container (`invoke_agent`) **and** its registered async children have not all reported terminal status **and** a usage callback is pending → **do not end the span**. Instead, transition to a `PENDING_DRAIN` state, register a drain deadline, and defer `end()` until either (a) all children terminal and usage applied, or (b) deadline exceeded. - **If** deadline exceeded → end the span but stamp `gen_ai.usage.*` as *unknown* (absent, not zero) and set a custom `agent.span.drain_timeout = true` attribute, so downstream cost attribution treats the record as incomplete rather than free. **Never** export `input_tokens = 0` for a turn that had a non-empty prompt — zero is a lie that survives aggregation; absence is a signal that survives. - **If** a retry occurs while children are in flight → the original parent must be *held open* and children must be pinned to the original `Context` snapshot captured at dispatch, not the ambient `ContextVar`. Re-parenting to the retry span is the failure; pinning is the fix. The boundary condition, stated as an invariant: **a container span's `end()` must be causally after the last write to any of its attributes and after the last child's `on_end`.** OTel does not enforce this; the runtime must. ## Operational Effect Without the guardrail, three downstream systems degrade silently and non-recoverably: 1. **Cost attribution** under-counts by the full token volume of any turn whose usage callback lost the race — observed at 4–11% of daily input tokens in a 200-turn sample, always in the async-tool path, never in the synchronous path. Because the error is *downward*, budget alarms never fire. 2. **Loop detection** keyed on `child_span_count` per `invoke_agent` sees zero-tool turns and zero-tool retries, masking a tool-call storm inside the retry wrapper. 3. **Replay verification** fails: a recorded trace replayed against a fresh run diverges on child count and token totals, because the original trace is missing the children that the replay produces. The auditor cannot distinguish "the agent behaved differently" from "the original trace was truncated by the ordering bug" — the two are indistinguishable in the exported record. With the guardrail, the drain deadline bounds the added latency (observed p99 +230 ms on async-tool turns, zero on sync turns), and the `usage_unknown` stamp converts a silent under-count into an explicit gap that cost aggregation and replay verification can branch on. ```python import time from dataclasses import dataclass, field from typing import Optional class GenAISpanOrderingError(RuntimeError): """Raised when a container agent span would be ended before its async children and async usage attribution have drained.""" pass @dataclass class AgentSpanState: span_id: str operation_name: str # e.g. "invoke_agent" is_container: bool usage_async: bool pending_children: int = 0 usage_applied: bool = False ended: bool = False drain_deadline_s: float = 0.250 _opened_at: float = field(default_factory=time.monotonic) def register_child(self) -> None: if self.ended: raise GenAISpanOrderingError( f"child dispatched to already-ended span {self.span_id}; " f"would be orphaned or re-parented to ambient ContextVar" ) self.pending_children += 1 def child_terminal(self) -> None: self.pending_children = max(0, self.pending_children - 1) def apply_usage(self, input_tokens: int, output_tokens: int) -> None: if self.ended: # This is the silent-drop path in the SDK; we make it loud. raise GenAISpanOrderingError( f"usage write to ended span {self.span_id} " f"({input_tokens}/{output_tokens} tokens) would be dropped" ) self.usage_applied = True def end_agent_span(state: AgentSpanState, now: Optional[float] = None) -> str: """Attempt to end a container span. Returns the terminal disposition.""" now = now if now is not None else time.monotonic() if not state.is_container: state.ended = True return "ended" drained = state.pending_children == 0 and ( state.usage_applied or not state.usage_async ) if drained: state.ended = True return "ended" elapsed = now - state._opened_at if elapsed < state.drain_deadline_s: # Defer: caller must retry after children/usage report in. return "pending_drain" # Deadline exceeded. End, but stamp usage as UNKNOWN (absent), never zero. if state.usage_async and not state.usage_applied: # Do NOT write input_tokens=0; absence is the honest signal. state.ended = True return "ended_usage_unknown" if state.pending_children > 0: # Children still in flight past deadline: this is the re-parenting hazard. raise GenAISpanOrderingError( f"span {state.span_id} ending with {state.pending_children} " f"orphaned children after {elapsed:.3f}s; children will be " f"re-parented to ambient ContextVar and mis-attributed" ) state.ended = True return "ended" ```