# Under what conditions must an instance refuse to close an OpenTelemetry GenAI `execute_tool` span when the tool call's token accounting is reported asynchronously and out of band from the span's own lifecycle? **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic-convention spans (`gen_ai.operation.name=execute_tool`, `gen_ai.operation.name=chat`) where token usage for a tool-mediated model call is reported by a downstream billing/telemetry channel *after* the tool function returns. Does not apply to synchronous in-process wrappers where `gen_ai.usage.input_tokens` / `output_tokens` are known before `span.end()`. ## Core Distinction The distinction that matters here is between **span lifetime** (the interval during which an `execute_tool` span is open and mutable) and **usage attribution window** (the wall-clock window during which the authoritative token counts for the model calls *triggered by* that tool become available). In most GenAI instrumentation, these two windows are assumed coincident: you call the model, you get `usage`, you set attributes, you end the span. The OTel GenAI conventions reinforce this by defining `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as span attributes on the `chat` span — attributes are immutable after `span.end()`, and the SDK silently drops `set_attribute` calls on ended spans. The boundary condition arises when a tool call *fans out* into model invocations whose usage is metered by a separate system (a gateway, a proxy, a batch billing pipeline) that reports token counts on a different clock than the tool function's return. If the runtime closes the `execute_tool` span on function return, the usage attributes arrive late, target an ended span, and are silently discarded. The span exists; the tokens do not. Cost attribution, budget enforcement, and any downstream `gen_ai.usage.*` aggregation then under-count by exactly the fan-out volume — and the under-count is *not observable as an error*, because dropped-attribute-on-ended-span is a no-op, not an exception. ## What Was Observed A planner agent invokes `execute_tool` for a `search_and_summarize` tool. The tool internally fans out to three `chat` calls against a metered gateway, returns a summary string, and the runtime records: ``` gen_ai.operation.name = "execute_tool" gen_ai.tool.name = "search_and_summarize" gen_ai.tool.call.id = "call_01HX..." ``` The tool function returns in 840 ms. The span is ended at T+840 ms. The gateway's usage webhook fires at T+1.2 s to T+2.9 s, delivering `{call_id: "call_01HX...", input_tokens: 4211, output_tokens: 903}` per fan-out leg. The exporter attempts `span.set_attribute("gen_ai.usage.input_tokens", 4211)` against the ended span. The SDK's `Span.set_attribute` checks `self._end_time is not None` and returns without mutation. No warning is emitted at the default log level. The result is a trace where the `execute_tool` span is structurally complete, the child `chat` spans carry their own usage, but the *aggregate* attributed to the tool call — the number a cost dashboard or a per-tool budget guard reads — is zero. Worse: if the runtime's budget guard reads the `execute_tool` span's usage to decide whether to allow the next tool call, it will *never* see the spend, and the agent will loop past its budget ceiling until the outer turn budget trips. The non-obvious part: the failure is **silent and shaped like success**. Every span is present, every span has the required semantic-convention attributes for its operation type, and the trace validates against the GenAI schema. Only the *cross-span invariant* — that sum of `execute_tool` usage equals sum of descendant `chat` usage — is violated, and that invariant is not part of the schema. ## Condition of Validity The refusal-to-close rule is valid only under the conjunction of: 1. The tool call has a stable correlation key (`gen_ai.tool.call.id`) that the out-of-band usage reporter will echo back. 2. The reporter's delivery latency is bounded by a known `T_usage_max` (contractual SLA, not observed mean). 3. The runtime can hold the span open without blocking the agent's forward progress — i.e., the agent loop is not synchronously waiting on `span.end()` to proceed. If (1) fails, the late usage cannot be attributed and the correct behavior is to *drop* it with a counter increment, not to hold the span. If (2) fails, holding the span turns a silent under-count into an unbounded span leak. If (3) fails, holding the span serializes the agent behind a telemetry clock, which is strictly worse than under-counting. When all three hold, the correct invariant is: **an `execute_tool` span with `gen_ai.tool.call.id` set MUST NOT transition to ended until either (a) the usage report for that call id has been applied, or (b) `T_usage_max` has elapsed since function return.** The span is *closed-pending-usage*, not *ended*. ## Decision Boundary The boundary between "hold the span" and "close and accept under-count" is drawn at the point where the cost of a leaked span exceeds the cost of a mis-attributed token. Concretely: - **Hold** when the tool is on a metered path (its usage feeds a budget guard or a cost ledger) *and* `T_usage_max` is finite and short relative to the agent's per-turn wall-clock budget. - **Close** when the tool's usage is informational only (no guard reads it) — holding buys nothing and risks span accumulation under reporter outage. - **Close and emit a `gen_ai.usage.attribution_failed` counter** when the reporter's SLA is breached. This is the only case where a span should be ended with known-missing usage; the counter is what makes the under-count observable, converting a silent invariant violation into a monitored one. The trap to avoid: treating "the span ended cleanly" as "the usage was recorded." The schema does not enforce the sum invariant, so schema validation is not a substitute for the hold rule. ## Operational Effect With the hold rule in place, the `execute_tool` span's `end_time` becomes a function of the *slowest* telemetry channel, not the tool function. This propagates: parent spans cannot end until children end, so a single slow usage reporter delays the entire trace's flush. The mitigation is to mark held spans with `gen_ai.usage.pending=true` at function return and clear it on usage application, so that a trace-level flusher can force-end pending spans at `T_usage_max` with the attribution-failed counter set. The invariant preserved is: *every `execute_tool` span is either usage-complete or explicitly flagged incomplete — never silently zero.* ```python import time from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when an execute_tool span cannot be safely ended with known usage state.""" @dataclass class ToolSpan: call_id: str metered: bool returned_at: Optional[float] = None usage_applied: bool = False pending: bool = False ended: bool = False attributes: dict = field(default_factory=dict) T_USAGE_MAX = 3.0 # contractual SLA for out-of-band usage delivery, seconds def on_tool_return(span: ToolSpan, now: float) -> None: span.returned_at = now if span.metered and not span.usage_applied: span.pending = True span.attributes["gen_ai.usage.pending"] = True # Do NOT end the span here. It stays open-pending-usage. def apply_usage(span: ToolSpan, input_tokens: int, output_tokens: int) -> None: if span.ended: # Late usage on an ended span is the silent-drop failure mode. raise UsageAttributionError( f"usage for {span.call_id} arrived after span end; " f"would be silently dropped by SDK" ) span.attributes["gen_ai.usage.input_tokens"] = input_tokens span.attributes["gen_ai.usage.output_tokens"] = output_tokens span.usage_applied = True span.pending = False span.attributes.pop("gen_ai.usage.pending", None) def try_end(span: ToolSpan, now: float) -> str: if span.ended: raise UsageAttributionError(f"double-end on {span.call_id}") waited = now - (span.returned_at or now) if span.metered and not span.usage_applied: if waited < T_USAGE_MAX: # Hold: refuse to close, keep span open-pending-usage. return "held_pending_usage" # SLA breached: force-end but flag incomplete so under-count is observable. span.attributes["gen_ai.usage.attribution_failed"] = True span.ended = True return "ended_attribution_failed" span.ended = True return "ended_complete" ```