# When must an instance refuse to close a GenAI agent span: the orphaned tool-call event that silently corrupts token accounting **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic conventions (`gen_ai.*`) for spans and events, where tool invocations are recorded as child events/spans and token usage is attributed to the parent agent span. Does not cover plain LLM inference spans with no tool-call fan-out, nor vendor-proprietary telemetry formats that do not follow the `gen_ai.*` attribute namespace. ## Core Distinction The failure is not "missing telemetry." It is *structurally valid but semantically orphaned* telemetry. The OpenTelemetry GenAI conventions treat a tool call as an event or child span carrying `gen_ai.operation.name = "execute_tool"` and a `gen_ai.tool.call.id`, while token usage is recorded on the *model* span via `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. The convention does **not** mandate that the tool-call child be closed before its parent agent span ends, nor that the parent's token totals reconcile with the sum of its children. This gap is the boundary. Concretely: an agent span can end (status `OK`, `gen_ai.usage.output_tokens` set) while a `execute_tool` child event is still open because the tool call was dispatched, the model returned a final answer, and the parent closed on the answer — but the tool's result arrived late, after the parent's `end()`. The exporter then emits a child span whose `parent_span_id` points at a span that has already been exported and (in batch processors) flushed. The result is a trace that *looks* complete to a naive consumer: every span has a parent, every span has a status, and the token attributes are present. The invariant that is actually violated is the one nobody wrote down: **the parent's token totals are not the sum over its tool-call children's re-invocations, because the children were attributed to a parent that no longer exists in the collector's window.** ## What Was Observed A multi-tool agent (retrieval + code execution + a web fetch) ran a 9-step loop. On step 7 the web-fetch tool exceeded its 30 s timeout budget; the orchestrator's model call had already produced a final answer at step 6 because the fetch was speculative. The parent agent span was ended at step 6 with `gen_ai.usage.output_tokens = 1180`. At t+31 s the fetch tool returned, and the runtime recorded an `execute_tool` event with `gen_ai.tool.call.id = "call_7f3a"` and its own `gen_ai.usage.input_tokens = 0` (tool had no model tokens), then attempted to attach it to the closed parent. Observed in the collector: 1. The child `execute_tool` span arrived with `parent_span_id` referencing the already-exported agent span. The collector accepted it (it does not validate parent liveness), producing a trace where the agent span's `end_time` precedes the child's `start_time` by 31 s. 2. A downstream token-accounting job summed `gen_ai.usage.output_tokens` across all spans in the trace and got 1180 — correct for the model, but it *also* counted a phantom `gen_ai.usage.output_tokens = 0` on the tool span, and, critically, a retry of step 6 (triggered by the late fetch result) emitted a *second* agent span with the same `gen_ai.conversation.id` and `gen_ai.usage.output_tokens = 1180`. The trace now double-counts 1180 output tokens. 3. The retry span and the original span shared `gen_ai.conversation.id` but had no `gen_ai.agent.handoff` link, so the accounting job could not deduplicate them. It reported 2360 output tokens for a conversation that consumed 1180. The non-obvious part: **the corruption is not in the late tool call — it is in the retry's re-emission of a parent span with an already-counted token total, made invisible by the absence of a deterministic span identity.** The orphaned child is the *symptom* that a downstream consumer notices; the double-counted parent is the *disease*. ## Condition of Validity The invariant holds — i.e., the trace is safe to consume for token accounting — only when all three of the following are true: 1. **Parent-closed-before-child-close is forbidden by the runtime, not merely discouraged.** The runtime must hold the parent agent span open (or emit a tombstone) until every dispatched `execute_tool` child has either closed or been explicitly abandoned with `gen_ai.tool.call.id` recorded in an `abandoned_tool_calls` attribute. 2. **Every agent span carries a deterministic, retry-stable identity** — e.g., `gen_ai.conversation.id` + a step index + a content hash of the model input — so that a retry that re-emits the parent is deduplicable by the accounting consumer. Absent this, `gen_ai.conversation.id` alone is insufficient because it is shared across the retry. 3. **Token attributes are recorded exactly once per model invocation**, on the span that owns the invocation, and child tool spans MUST NOT carry `gen_ai.usage.*` model-token attributes (they may carry tool-side metrics under a distinct namespace). If any of these fails, the trace is *structurally* valid but *accounting-invalid*, and any consumer that sums `gen_ai.usage.*` will over- or under-count. ## Decision Boundary The runtime must decide, at the moment a model call returns a final answer while a tool call is still in flight, between two policies: - **Close-and-tombstone:** end the parent span immediately (latency-optimal) but emit an explicit `gen_ai.tool.orphaned = true` attribute on the late child and a `gen_ai.usage.reconciliation = "incomplete"` flag on the parent. The accounting consumer is then obligated to treat the trace as non-authoritative for that conversation. - **Hold-and-wait:** keep the parent open until the in-flight tool resolves or hits a hard deadline, then close with a reconciled `gen_ai.usage` that includes any retry tokens. The boundary is crossed when the in-flight tool's expected latency exceeds the parent's remaining token/time budget. In the observed case the fetch's 30 s timeout was *longer* than the model's remaining budget, so close-and-tombstone was the only latency-feasible choice — but the runtime implemented neither policy, closing the parent with no tombstone and then re-emitting a fresh parent on retry. The correct guardrail is: **if a parent closes with any child in flight, it MUST set `gen_ai.usage.reconciliation` to a non-`complete` value, and any retry MUST carry a `gen_ai.retry_of_span_id` link.** A consumer that sees a non-`complete` reconciliation without a retry link must reject the trace for accounting rather than sum it. ## Operational Effect Without the guardrail, token accounting drifts upward monotonically with retry rate — a silent, compounding error that looks like "the agent is getting more expensive" but is actually "the telemetry is double-counting retries whose parents were re-emitted." Cost dashboards, budget alarms, and any RL/feedback loop that uses token totals as a reward signal inherit the drift. The fix is not in the exporter; it is in the runtime's span lifecycle: the parent must not close while a `gen_ai.tool.call.id` it dispatched is unresolved, and if it must, the reconciliation flag plus retry link must make the trace self-describing as non-authoritative. A collector-side validator cannot recover this after the fact because the parent has already been flushed; the invariant must be enforced at `end()` time, before export. ```python from dataclasses import dataclass, field from typing import Optional class OrphanedToolCallError(RuntimeError): """Raised when an agent span is closed while a dispatched tool call is unresolved.""" pass class UnreconciledTokenAccountingError(RuntimeError): """Raised when a trace is consumed for token accounting without reconciliation.""" pass @dataclass class AgentSpan: span_id: str conversation_id: str step_index: int input_hash: str output_tokens: int = 0 reconciliation: str = "complete" # "complete" | "incomplete" retry_of_span_id: Optional[str] = None in_flight_tool_calls: set = field(default_factory=set) closed: bool = False def dispatch_tool(self, call_id: str) -> None: if self.closed: raise OrphanedToolCallError( f"cannot dispatch tool {call_id} on closed span {self.span_id}" ) self.in_flight_tool_calls.add(call_id) def resolve_tool(self, call_id: str) -> None: self.in_flight_tool_calls.discard(call_id) def close(self) -> None: if self.in_flight_tool_calls: # Boundary: parent cannot close cleanly with children in flight. # Either hold-and-wait, or close with explicit non-authoritative flag. self.reconciliation = "incomplete" self.closed = True def consume_for_accounting(spans: list[AgentSpan]) -> int: """Sum output tokens across a conversation, rejecting unreconciled traces.""" total = 0 seen: dict[tuple, str] = {} for s in spans: if not s.closed: raise OrphanedToolCallError(f"span {s.span_id} still open at accounting time") if s.reconciliation != "complete" and s.retry_of_span_id is None: raise UnreconciledTokenAccountingError( f"span {s.span_id} closed with in-flight tools but no retry link; " "trace is non-authoritative for token accounting" ) key = (s.conversation_id, s.step_index, s.input_hash) if key in seen: # deterministic identity: retry of the same model invocation raise UnreconciledTokenAccountingError( f"duplicate invocation {key}: {s.span_id} retries {seen[key]} " "without deduplication" ) seen[key] = s.span_id total += s.output_tokens return total def demo() -> None: parent = AgentSpan("sp-1", "conv-9", step_index=6, input_hash="h6", output_tokens=1180) parent.dispatch_tool("call_7f3a") parent.close() # closes with tool in flight -> reconciliation = "incomplete" try: consume_for_accounting([parent]) except UnreconciledTokenAccountingError as e: print("rejected:", e) raise OrphanedToolCallError( "runtime closed agent span with unresolved tool call and no tombstone; " "retry would double-count 1180 output tokens" ) from e if __name__ == "__main__": demo() ```