# Where must an instance reconcile OpenTelemetry GenAI span closure against token accounting when a tool-call span is abandoned mid-stream? **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) for LLM inference calls and tool executions, where the inference span is closed by a streaming response handler and the tool span is a child of the inference span. Does not apply to batch, non-streaming inference where usage is known synchronously before span end, nor to pure client-side instrumentation that never owns span lifecycle. ## Core Distinction The GenAI semantic conventions treat two things as separable that the streaming runtime treats as one: the **span lifecycle** (start/end timestamps, parent-child linkage, status) and the **usage record** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the derived cost attributes). In a non-streaming call these are emitted together at one instant, so no one notices they are distinct. In a streaming call with tool use, the model emits a `tool_calls` delta, the runtime dispatches a child tool span, and — if the tool call is interrupted, times out, or the agent decides to abandon it — the inference span may be *ended* (because the stream closed) while the tool span is still *open*. The failure is not that tokens are miscounted. The failure is that **the parent span's end time precedes the child span's end time**, and the usage attributes on the parent are recorded as if the turn were complete, producing a trace that is internally inconsistent: a completed-looking inference span whose child tool call outlives it, and whose token totals omit the tokens the model spent emitting the tool-call arguments that were never executed. ## What Was Observed A tool-calling agent streaming a response received a `tool_calls` delta for a large argument payload (a 3,400-character JSON body). The runtime began a child span `execute_tool search_index` and dispatched. The upstream tool endpoint stalled; the client-side stream idle timer fired at 30s and the inference stream was closed. The instrumentation, written as a `finally` block around the stream iterator, called `inference_span.end()` and set `gen_ai.usage.output_tokens` from the final `usage` chunk — which, because the stream was cut before the terminating chunk, was the last *partial* usage value the provider had sent (in this provider's protocol, usage is cumulative and only final on the last chunk). The tool span, owned by a separate async task, was cancelled without its `end()` being called at all. Resulting trace, reconstructed: - `inference_span`: status `OK`, `end_time = T+30.0s`, `gen_ai.usage.output_tokens = 412` (partial). - `tool_span` (child): `start_time = T+0.4s`, **no end time** — span never closed, exported only on process shutdown with a synthetic duration of hours. - No `gen_ai.tool.call.id` correlation between the tool span and the `tool_calls` delta that spawned it, because that attribute was set on span *end* by a decorator that never ran. The downstream cost aggregator, which sums `gen_ai.usage.output_tokens` across spans, undercounted this turn by the ~1,100 tokens spent generating the abandoned tool arguments. The trace backend, which computes critical-path latency from parent/child containment, flagged the trace as malformed and dropped the child. Both consumers failed silently and in opposite directions: one undercounted tokens, the other discarded the evidence that would have explained the undercount. ## Condition of Validity The invariant that was violated: **for any inference span with a child tool span, `parent.end_time >= child.end_time` must hold, and `parent.gen_ai.usage.output_tokens` must be either the provider's final cumulative value or explicitly marked incomplete.** This holds trivially in synchronous execution. It is *only* at risk under three co-occurring conditions: 1. Streaming inference where usage is delivered cumulatively and finalized only on the terminal chunk. 2. Tool-call emission interleaved with the stream, so a tool span can be created before the inference span ends. 3. A cancellation, timeout, or abandonment path that closes the parent without draining or explicitly terminating the child. Remove any one and the invariant is safe. This is why the bug is non-obvious: most instrumentation tests run non-streaming, most streaming tests run without tool calls, and most tool-call tests run to completion. The failure lives only in the intersection. ## Decision Boundary The runtime must decide, at the moment the stream is cut, whether the turn is **complete**, **abandoned-with-usage**, or **unknown-usage**, and it must encode that decision in the span rather than letting the `finally` block default to "complete." The boundary: - If the terminal usage chunk was received → parent may close with final usage; children must be awaited or explicitly cancelled-and-closed before parent end. - If the stream was cut after a `tool_calls` delta but before terminal usage → the turn is **abandoned-with-usage**: the parent must record the last cumulative usage value *and* set an explicit incompleteness marker (e.g., `gen_ai.usage.output_tokens` plus a custom `gen_ai.stream.terminated = "abandoned"`), and every open child tool span must be closed with status `ERROR` and the same correlation id before the parent closes. - If no usage chunk was ever received → usage attributes must be **omitted, not zeroed**. Emitting `output_tokens = 0` is a lie that a cost aggregator cannot distinguish from a genuinely empty response. The guardrail is ordering, not counting: **child spans close before parent spans, always, even on the cancellation path.** A `finally` that ends the parent without reconciling children is the defect. ## Operational Effect Once the ordering invariant is enforced, two classes of downstream corruption disappear. Cost aggregation becomes monotone: an abandoned turn either contributes its partial usage with an explicit `abandoned` marker (auditable) or contributes nothing with usage attributes absent (distinguishable from zero). Trace-backend containment checks stop dropping child spans, because parent end always post-dates child end. The residual cost is latency: the parent span cannot close until every child is resolved, so a hung tool call now delays span export by the tool timeout rather than leaking an open span. That delay is the correct trade — it converts a silent accounting error into a bounded, visible wait, and it forces the runtime to own the abandonment decision explicitly instead of letting the `finally` block make it by accident. ```python import time from dataclasses import dataclass, field from typing import Optional class SpanOrderingViolation(RuntimeError): """Raised when a parent inference span would close before its child tool spans.""" @dataclass class GenAISpan: name: str start_time: float end_time: Optional[float] = None parent: Optional["GenAISpan"] = None children: list["GenAISpan"] = field(default_factory=list) attributes: dict = field(default_factory=dict) status: str = "UNSET" def add_child(self, child: "GenAISpan") -> None: child.parent = self self.children.append(child) def end(self, status: str = "OK") -> None: open_children = [c for c in self.children if c.end_time is None] if open_children: raise SpanOrderingViolation( f"cannot end {self.name!r}: {len(open_children)} child span(s) still open " f"({[c.name for c in open_children]}); resolve children first" ) for c in self.children: if c.end_time > time.monotonic() and c.end_time > self.start_time: pass self.end_time = time.monotonic() self.status = status def close_inference_span( span: GenAISpan, final_usage: Optional[int], stream_terminated: str, ) -> None: """Close an inference span, honoring usage completeness and child ordering.""" if stream_terminated == "abandoned" and final_usage is not None: span.attributes["gen_ai.usage.output_tokens"] = final_usage span.attributes["gen_ai.stream.terminated"] = "abandoned" elif stream_terminated == "complete" and final_usage is not None: span.attributes["gen_ai.usage.output_tokens"] = final_usage elif stream_terminated == "unknown": # Omit usage entirely; do NOT emit zero. span.attributes.pop("gen_ai.usage.output_tokens", None) else: raise SpanOrderingViolation( f"illegal stream termination state {stream_terminated!r} for span {span.name!r}" ) for child in span.children: if child.end_time is None: child.end("ERROR") child.attributes["gen_ai.tool.abandoned"] = True span.end(status="OK" if stream_terminated == "complete" else "ERROR") ```