# When must an instance refuse to close an OpenTelemetry GenAI agent span: the token-accounting invariant that breaks under streaming tool-call fan-out **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for an `invoke_agent` span that fans out into `execute_tool` child spans and accumulates token usage across multiple model invocations. Does not apply to single-shot completion spans with no tool fan-out, nor to metrics-only instrumentation where span closure ordering is not load-bearing. ## Core Distinction The GenAI semantic conventions treat token accounting as *additive attributes on a span* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and treat tool calls as *child spans* linked by parent/child span context. What the conventions do **not** specify is the closure invariant: an `invoke_agent` span is only semantically valid if the sum of token attributes it reports equals the sum of token attributes reported by every model-invocation span it parents, *at the moment of closure*, and every tool-call child span it spawned has terminated with a recorded status. The failure mode is not "wrong numbers"—it is that the parent span closes and gets exported *before* late-arriving streaming usage chunks and orphaned tool spans reconcile, producing a trace that is internally inconsistent and, worse, non-reconcilable after export because the exporter is append-only. The distinction that matters: a **sampling/billing discrepancy** is a downstream analytics problem. A **closure-order violation** is a correctness problem at the trace level—the span is immutable once exported, so the invariant can never be repaired, only bounded by refusing to close. ## What Was Observed An orchestration agent (`invoke_agent`, span kind INTERNAL) runs a loop: model call → parse tool-call → `execute_tool` child span → tool returns → model call with tool result → … → final answer. Instrumentation used the streaming API, where `gen_ai.usage.output_tokens` arrives in the *final* stream chunk (`message_delta` / `usage` event), not at request time. Observed trace sequence (abbreviated), across three concurrent agent instances sharing one exporter batch: ``` t0 invoke_agent span START (instance A) t1 chat span START, model turn 1 t2 chat span END -> usage in=812 out=140 t3 execute_tool span START (tool_call_id=tc_1) t4 execute_tool span END status=OK t5 chat span START, model turn 2 t6 invoke_agent span END <-- closed here by loop-exit handler t7 chat span END (turn 2) -> usage in=1043 out=88 <-- arrives AFTER parent closed t8 execute_tool span START (tool_call_id=tc_2) <-- spawned by turn-2 parse, parent already closed t9 execute_tool span END status=OK ``` The parent `invoke_agent` span was closed at t6 because the agent's control loop considered the task complete (final answer assembled). But turn 2's usage chunk (t7) and its tool call (t8/t9) were emitted by an async stream consumer that had not yet drained. The exported parent span reported `input_tokens=812, output_tokens=140` — it silently omitted turn 2 entirely. The child spans at t7–t9 were exported with a `parent_span_id` pointing at a span the backend had already sealed, so they appear as orphaned descendants. Cost attribution under-counted by ~55%; more critically, the trace graph no longer satisfied "every child terminates before parent." The trigger condition is precise: **the agent loop's completion signal is driven by the semantic answer, while the telemetry completion signal is driven by stream-drain.** These are two different completion events, and the code that closes the span listens to the wrong one. It reproduces reliably whenever (a) streaming is used, (b) a tool call is parsed from a chunk that arrives after the loop's exit condition fires, or (c) the final usage chunk is deferred past the loop-exit branch. Concurrency across instances widens the window because the exporter batch flush is shared. ## Condition of Validity The closure invariant holds only under all of the following: 1. **Usage reconciliation before close.** The parent span's `gen_ai.usage.*` attributes must be written from an accumulator that is updated by every child model-invocation span's terminal usage event, and the parent must not close until the accumulator's expected-child-count equals observed-child-count. 2. **Tool-span quiescence.** Every `execute_tool` span spawned under the parent must have reached a terminal state (`OK`/`ERROR`, never `UNSET`) before the parent closes. An open tool span at parent-close time is a hard invariant violation, not a warning. 3. **Stream drain barrier.** The span-close path must await stream termination (or an explicit `usage` terminal event), not the agent's semantic "done." 4. **Single writer per accumulator.** Token accumulation must be serialized per parent span; concurrent child completions updating a shared dict without a lock produce lost updates that look identical to the omission above. If any of these is unenforced, the trace is *structurally* invalid even if each individual span is well-formed. The semantic conventions give you attribute names but not this barrier—you must impose it. ## Decision Boundary The operational question is: **when the agent's semantic loop says "done" but telemetry children are still live, does the instance close the span, or refuse and hold?** - **Close immediately** (current behavior): trace exported, invariant violated, unrecoverable. Acceptable only for spans marked non-authoritative (e.g., debug sampling) where cost reconciliation is out of scope. - **Refuse to close and raise**: the correct default for authoritative `invoke_agent` spans. The span is held open, a bounded wait is applied, and if children still haven't quiesced past the deadline, the close is *rejected* and the span is exported with an explicit `gen_ai.agent.closure_invariant_violated=true` attribute plus an error status, so downstream reconciliation can quarantine rather than silently trust it. - **Force-close with tombstone**: only when the deadline is exceeded and the process is shutting down; emit the partial span with the violation flag and a count of unresolved children. The boundary is not "how long do I wait" — it is "do I ever export a parent span whose child set is provably incomplete, and if so, do I mark it." Silent close is never on the correct side of the boundary. ## Operational Effect Enforcing the refusal changes three things downstream. First, cost and token dashboards become reconcilable: every `invoke_agent` span either sums correctly or carries the violation flag, so aggregation can exclude or correct rather than under-count invisibly. Second, orphaned tool spans disappear from the trace graph, because a parent that refuses to close keeps its span context live long enough for late tool spans to attach — or the whole subtree is quarantined together. Third, it surfaces a class of agent bugs that were previously masked as "telemetry noise": a loop that declares completion before draining its stream is a *reasoning-execution* bug (the agent may act on a truncated turn), and the closure invariant is the cheapest detector for it. The cost is latency on span export and the need for a bounded wait deadline to avoid holding spans forever under a wedged stream; the deadline must be shorter than the exporter's batch timeout or the barrier itself deadlocks the pipeline. The general lesson: OpenTelemetry GenAI conventions specify *what to record*, not *when closure is legal*. For stateful agents, the span is a small consistency contract over a distributed set of child events, and the instance must treat closure as a commit that can be rejected—not a fire-and-forget log line. ```python import threading import time from dataclasses import dataclass, field class SpanClosureInvariantError(RuntimeError): """Raised when an invoke_agent span is asked to close while its GenAI child spans (model invocations / tool calls) are not quiesced or token usage has not reconciled. Exporting here would violate the parent/child terminal-state and token-sum invariants.""" pass @dataclass class UsageAccumulator: input_tokens: int = 0 output_tokens: int = 0 expected_children: int = 0 completed_children: int = 0 open_tool_spans: int = 0 _lock: threading.Lock = field(default_factory=threading.Lock) def register_child(self) -> None: with self._lock: self.expected_children += 1 def record_model_usage(self, in_tok: int, out_tok: int) -> None: with self._lock: self.input_tokens += in_tok self.output_tokens += out_tok self.completed_children += 1 def tool_open(self) -> None: with self._lock: self.open_tool_spans += 1 def tool_close(self) -> None: with self._lock: self.open_tool_spans -= 1 def is_quiesced(self) -> bool: with self._lock: return ( self.completed_children == self.expected_children and self.open_tool_spans == 0 ) class AgentSpan: def __init__(self, name: str): self.name = name self.usage = UsageAccumulator() self._closed = False self._violation = False def close(self, deadline_s: float = 2.0, force: bool = False) -> None: if self._closed: raise SpanClosureInvariantError( f"span {self.name!r} closed twice" ) waited = 0.0 step = 0.01 while not self.usage.is_quiesced(): if force and waited >= deadline_s: # shutdown path: export partial but TOMBSTONE it self._violation = True self._export(violation=True) self._closed = True return if waited >= deadline_s: raise SpanClosureInvariantError( f"refusing to close {self.name!r}: " f"{self.usage.expected_children - self.usage.completed_children} " f"model children pending, {self.usage.open_tool_spans} tool spans open" ) time.sleep(step) waited += step self._export(violation=False) self._closed = True def _export(self, violation: bool) -> None: attrs = { "gen_ai.usage.input_tokens": self.usage.input_tokens, "gen_ai.usage.output_tokens": self.usage.output_tokens, "gen_ai.agent.closure_invariant_violated": violation, } # exporter call omitted; in production this is append-only _ = attrs def run_agent_turn(span: AgentSpan, stream_chunks, tool_invocations): span.usage.register_child() span.usage.register_child() # second model turn registered up-front for chunk in stream_chunks: if chunk.get("type") == "usage": span.usage.record_model_usage( chunk["input_tokens"], chunk["output_tokens"] ) if chunk.get("type") == "tool_call": span.usage.tool_open() tool_invocations.append(chunk["tool_call_id"]) # caller must close tool spans; if any remain open, close() rejects def close_agent_span_safely(span: AgentSpan, force: bool = False) -> None: try: span.close(deadline_s=2.0, force=force) except SpanClosureInvariantError: # do not swallow: propagate so orchestrator quarantines the trace raise ```