# When must an instance refuse to emit a terminal agent span: the OpenTelemetry GenAI parent-span completeness invariant under mid-tool-call token-budget exhaustion **Date of Record:** 2026 November 19 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.agent.*`) that emit one parent `invoke_agent` span per reasoning turn and child `execute_tool` spans per tool call. Does not apply to stateless single-shot completions with no tool dispatch, nor to telemetry backends that recompute cost from raw usage counters independent of span lifecycle. ## Core Distinction The GenAI semantic conventions treat a span as a *record of a completed unit of work*, closed by `span.end()` with a status of `OK` or `ERROR`. Cost and token telemetry (`gen_ai.usage.*`) are attributes stamped onto that span. The non-obvious boundary is this: **a span's usage attributes are only trustworthy if the span reached a terminal state that corresponds to an accounted-for model invocation.** An agent that exhausts its token budget mid-tool-call has already *consumed* input/output tokens for the reasoning turn that decided to call the tool, but the parent `invoke_agent` span has not yet received the tool result and therefore cannot compute its final `gen_ai.usage.output_tokens` aggregate. If the runtime "helpfully" ends the parent span at that moment to avoid a dangling span, it emits a terminal span whose usage counters are a *partial* sum — and every downstream cost rollup silently undercounts. The distinction that matters: a span that ends because work *finished* versus a span that ends because work was *abandoned* must not be indistinguishable in the exported record. ## What Was Observed A research agent looped over a document corpus, dispatching `execute_tool` spans for a `search` tool. The per-turn parent `invoke_agent` span carried `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from the model response. The runtime enforced a hard budget: when cumulative `output_tokens` exceeded 40,000, a supervisor raised `TokenBudgetExhausted` inside the tool-dispatch coroutine — *after* the model response had been received and its usage recorded, but *before* the `execute_tool` child span returned. The instrumentation's `finally` block called `parent_span.end()` unconditionally. The exported trace showed: - Parent `invoke_agent` span: status `OK`, `gen_ai.usage.output_tokens = 0` (the aggregate was computed from child tool spans, which never ran). - One orphaned `execute_tool` span with no `gen_ai.tool.call.id` linkage completing, status `UNSET`. - The model's actual 1,847 output tokens for that turn — already billed by the provider — present nowhere in the trace. Cost dashboards keyed on `sum(gen_ai.usage.output_tokens)` reported a 6% undercount across the run. Worse, the `OK` status made the abandonment invisible to the error-rate SLO, so the failure never triggered an alert. The trace looked *healthier* than the system was. ## Condition of Validity The invariant holds — and the failure is real — only when all of the following are true: 1. The parent span's usage attributes are *derived* from child work (tool results folded into a final aggregate) rather than stamped atomically from the model response at response-receipt time. 2. The abandonment trigger (budget, cancellation, timeout) can fire *between* model-response receipt and child-span completion — i.e., the token spend is already irreversible when the parent is torn down. 3. Downstream cost/error aggregation trusts span status and usage attributes as the source of truth, rather than reconciling against provider-side billing records. When usage is stamped atomically at response receipt (condition 1 false), the partial-sum problem vanishes and unconditional `end()` is safe. When the trigger can only fire before the model call (condition 2 false), there is nothing unaccounted to lose. The dangerous regime is precisely the intersection: *spend already incurred, aggregate not yet materialized, teardown path unaware of the distinction.* ## Decision Boundary The decision an instrumented runtime must make at teardown is not "end the span or leak it" but "which terminal state does this span's accounting support?" The boundary: - If the model response for the current turn was received and its usage recorded, the parent span MUST end with status `ERROR` (or a dedicated `gen_ai.agent.abandoned = true` attribute) and MUST carry the *received* usage for that turn, even though child tool spans are incomplete. Ending as `OK` with zeroed usage is a lie in two directions at once. - If the model response was never received, no usage was incurred, and `OK`/`ERROR` with zero usage is honest. - A parent span MUST NOT be ended as `OK` while any child `execute_tool` span it spawned is still open or was abandoned without a terminal status. The parent's terminal state is *bounded below* by its children's. The guardrail: teardown must consult whether irreversible spend occurred for the current turn, and if so, force the span into an explicitly-abandoned terminal state that carries the partial usage and sets an error status. The invariant is *no terminal `OK` span may have unaccounted irreversible token spend.* ## Operational Effect Enforcing the boundary converts a silent cost leak into a loud, traceable one. The abandoned turn now surfaces as an `ERROR` parent span carrying `gen_ai.usage.output_tokens = 1847` and `gen_ai.agent.abandoned = true`, so cost rollups stay accurate and the error-rate SLO correctly registers the budget exhaustion. The tradeoff is that `OK` no longer means "the agent was happy" — it means "every token this span claims is a token the span can prove it spent." Teams that skip this discover the discrepancy only during provider-invoice reconciliation, weeks later, with no trace to explain it. The invariant is cheap to enforce at teardown and expensive to reconstruct after the fact. ```python from dataclasses import dataclass, field from typing import Optional class UnaccountedSpendOnOkSpan(RuntimeError): """Raised when a parent agent span would terminate OK despite irreversible token spend.""" pass @dataclass class AgentSpan: name: str status: str = "UNSET" usage_output_tokens: int = 0 abandoned: bool = False open_children: list = field(default_factory=list) def teardown_parent_span( span: AgentSpan, *, turn_response_received: bool, tokens_billed_this_turn: int, child_spans: list, ) -> AgentSpan: """Close a parent invoke_agent span under the parent-completeness invariant.""" still_open = [c for c in child_spans if c.status in ("UNSET", "OK_PENDING")] if still_open: # Children bound the parent's terminal state below. span.status = "ERROR" span.abandoned = True span.usage_output_tokens = tokens_billed_this_turn return span if turn_response_received and tokens_billed_this_turn > 0: # Irreversible spend occurred; the span must carry it and not claim OK. span.status = "ERROR" span.abandoned = True span.usage_output_tokens = tokens_billed_this_turn return span if span.status == "OK" and span.usage_output_tokens == 0 and tokens_billed_this_turn > 0: raise UnaccountedSpendOnOkSpan( f"span {span.name!r} would end OK with {tokens_billed_this_turn} " f"billed tokens unaccounted; refusing teardown" ) span.status = "OK" span.usage_output_tokens = tokens_billed_this_turn return span ```