# In what scenarios must an instance refuse to close an agent span when OpenTelemetry GenAI tool-call attributes are still unresolved **Date of Record:** 2026 November 24 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`), where tool calls are delegated asynchronously. Does not cover synchronous single-shot completions with no tool delegation, nor non-OTel tracing backends. ## Core Distinction The distinction that matters is between **span completion** and **attribute finality**. The OpenTelemetry GenAI conventions treat a span as a closed record once `span.end()` is called: attributes are immutable thereafter, and the exporter flushes whatever it captured. But an agent's tool-call lifecycle is *not* aligned with its span lifecycle. A model emits a `tool_call` in one inference turn; the tool executes in a separate process with its own latency distribution; the result is folded back into a *subsequent* inference turn. The GenAI conventions model this as a parent span (`gen_ai.operation.name = "chat"` or `"execute_tool"`) carrying `gen_ai.tool.name`, `gen_ai.tool.call.id`, and token counts. The failure mode is: **the span is ended before the tool result (and its token accounting) is known**, producing a record that is syntactically valid, schema-conformant, and semantically false. This is not a crash. It is a silent accounting and attribution corruption that only surfaces downstream in cost reconciliation or replay. ## What Was Observed A multi-tool agent loop emitted, per turn, a `chat` span whose child `execute_tool` span carried `gen_ai.tool.name`. When the tool backend (a vector-retrieval service) had a P99 latency exceeding the model client's own timeout, the runtime's `finally` block called `span.end()` on the parent `chat` span after the model turn returned but *before* the tool child span resolved. Observed consequences, in order: 1. The parent `chat` span exported with `gen_ai.usage.output_tokens` populated but the child `execute_tool` span still `IN_PROGRESS`. The OTel SDK's `BatchSpanProcessor` does not block on child completion — it exports per-span on `end()`. 2. The child span later ended and exported *after* its parent, violating the causal ordering assumption many trace UIs and cost aggregators rely on. The tool span appeared as an orphan with a `parent_span_id` pointing at an already-exported parent. 3. Token/cost instrumentation that summed `gen_ai.usage.*_tokens` across the trace double-counted nothing but *under-counted* the tool-result ingestion turn, because that turn's tokens were attributed to a span that had already been finalized with the pre-tool counts. 4. On retry (the tool timed out, so the runtime re-issued the call), a *second* `execute_tool` span with the *same* `gen_ai.tool.call.id` was emitted. The convention does not mandate uniqueness enforcement, so the trace now contained two tool spans with identical call IDs and divergent outcomes — one `ERROR`, one `OK`. The invariant that broke: **a GenAI agent span's token and tool attributes must be a closed, causally ordered record of a single logical step.** Ending the parent early severed the record from the step it claimed to describe. ## Condition of Validity The guardrail is only meaningful under a specific condition: the tool call is **asynchronous relative to the span that names it**, and the span carries attributes (`gen_ai.usage.*`, `gen_ai.tool.call.id`, `gen_ai.tool.name`) that are only fully known once the tool resolves. When the tool is synchronous and inline (result available before the model turn returns), the naive `end()`-in-`finally` pattern is correct and this article does not apply. The boundary is crossed the moment tool execution is decoupled from the inference turn — which is the default for any agent that runs tools in a sandbox, a remote MCP server, or a separate worker. A second validity condition: the runtime must be the *sole* authority that closes the span. If a framework auto-closes spans via context-manager exit, the runtime cannot honor this invariant without overriding the framework's lifecycle. Mixed ownership of span termination is the precondition for the silent corruption. ## Decision Boundary The decision the runtime must make, per span, is binary and must be made *before* `end()` is reachable: - **Close now** only if every attribute the span is contractually required to carry is already set and no child tool span it names is still `IN_PROGRESS`. This is the synchronous case. - **Defer close** if any of: `gen_ai.tool.call.id` is set but the corresponding `execute_tool` span has not ended; `gen_ai.usage.output_tokens` is a provisional estimate pending a streaming completion; or a retry is in flight for the same call ID. The non-obvious part: deferral is not "wait indefinitely." A deferred span must carry a **bounded deadline** tied to the tool's own timeout plus one scheduling quantum. If the deadline passes without resolution, the runtime must close the span with an explicit `error.type = "tool_result_unresolved"` and a *sentinel* token count (not zero, not the pre-tool count) so that downstream cost reconciliation can distinguish "no tokens" from "tokens unknown." Zero is a lie; the sentinel is a truth-claim about ignorance. The boundary is therefore: **an agent span may be closed unresolved only if it is closed with an explicit unresolved marker.** Closing it silently — which is what the `finally`-block pattern does — is the failure. ## Operational Effect Enforcing deferred-close-with-sentinel changes three things operationally: 1. **Trace watermarks shift.** Parent spans now end at or after their children, restoring causal ordering. Cost aggregators that previously summed finalized spans now see a small tail of spans that carry `tool_result_unresolved`; these must be excluded from per-token cost sums and reported separately, or the cost total will read low by exactly the unresolved fraction. 2. **Retry deduplication becomes mandatory.** Because the convention permits duplicate `gen_ai.tool.call.id` across retries, the runtime must emit a `gen_ai.tool.call.attempt` (or equivalent) discriminator, or downstream replay will merge two divergent outcomes into one. Without it, the trace is schema-valid and operationally unreadable. 3. **Span cardinality is bounded, not unbounded.** The deadline prevents the "never-close" degenerate case where a hung tool leaks open spans until the collector drops them. The sentinel close converts a leak into a countable, attributable event. The invariant to hold: **a GenAI agent span is a claim about a completed logical step; it must not be finalized while any attribute it names is still in flight, and when it must be finalized unresolved, it must say so in-band.** ```python import time from dataclasses import dataclass, field from typing import Optional class UnresolvedSpanError(RuntimeError): """Raised when a span is closed while a named tool call is still in flight.""" pass @dataclass class ToolCallState: call_id: str attempt: int = 1 resolved: bool = False outcome: Optional[str] = None @dataclass class AgentSpan: operation: str attributes: dict = field(default_factory=dict) pending_tool_calls: dict = field(default_factory=dict) closed: bool = False unresolved_marker: Optional[str] = None def close_span(span: AgentSpan, deadline_s: float, start_ts: float) -> None: """Close an agent span only when all named tool calls are resolved, or the bounded deadline has elapsed (in which case mark unresolved).""" if span.closed: raise UnresolvedSpanError(f"span {span.operation} already closed") in_flight = [c for c in span.pending_tool_calls.values() if not c.resolved] elapsed = time.monotonic() - start_ts if in_flight and elapsed < deadline_s: # Contract violation: caller tried to finalize before resolution # and before the deadline. Refuse rather than emit a false record. raise UnresolvedSpanError( f"cannot close span {span.operation}: " f"{len(in_flight)} tool call(s) unresolved " f"({[c.call_id for c in in_flight]}) and deadline not reached" ) if in_flight: # Deadline elapsed: close with an explicit unresolved marker so # downstream cost reconciliation can distinguish unknown from zero. span.unresolved_marker = "tool_result_unresolved" span.attributes["error.type"] = "tool_result_unresolved" span.closed = True def run_agent_step(span: AgentSpan, tool_latency_s: float, deadline_s: float) -> None: start = time.monotonic() # simulate async tool still pending at the moment the runtime wants to end span.pending_tool_calls["call-7"] = ToolCallState(call_id="call-7") # runtime attempts to finalize immediately (the buggy pattern): close_span(span, deadline_s=deadline_s, start_ts=start) ```