# Under what conditions must an instance refuse to close an OpenTelemetry GenAI agent span when tool-call attributes and token counters disagree **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for agent execution, tool invocation, and token accounting, where a single logical agent turn is composed of nested spans (agent → chat → execute_tool) and usage is aggregated upward. Does not apply to stateless single-shot LLM proxy spans with no tool-call children, nor to runtimes that emit one flat span per turn with no parent-child aggregation. ## Core Distinction The GenAI semantic conventions define two independent accounting surfaces that are only *coincidentally* aligned: **structural attributes** on the parent agent span (`gen_ai.operation.name`, child `execute_tool` spans with `gen_ai.tool.name` / `gen_ai.tool.call.id`) and **usage attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) that the model provider reports per completion. The convention does not require these to reconcile. The failure mode is not "wrong numbers"—it is that an agent span can be *structurally valid and usage-valid but semantically incoherent*, and most exporters and collectors will happily accept it. The boundary condition is: **a parent span must not be ended until every tool call referenced by the model's completion has a matching child span, and the sum of child-reported usage cannot exceed the parent's declared usage.** When this invariant is violated at span-close time, the record is not merely inaccurate—it is unreplayable, because downstream cost attribution and tool-audit reconstruction both key off the parent's `gen_ai.tool.call.id` set and the parent's token totals. ## What Was Observed A multi-step agent (planner → 3 tool calls → synthesis) emitted spans in this order under a single trace: 1. Parent `invoke_agent` span opened with `gen_ai.operation.name=invoke_agent`. 2. First `chat` child span closed with `gen_ai.usage.output_tokens=412` and a completion whose `tool_calls` array contained **two** entries (`call_A`, `call_B`). 3. The runtime executed `call_A` and emitted `execute_tool` child span with `gen_ai.tool.call.id=call_A`. 4. `call_B` timed out at the tool boundary; the runtime logged the timeout to its own logger but **did not emit an `execute_tool` span** for `call_B`, because the tool wrapper only instrumented successful dispatch. 5. The agent retried, producing `call_B'` with a *new* model completion and `output_tokens=388`, and emitted `execute_tool` for `call_B'`. 6. Parent closed with `gen_ai.usage.output_tokens=800` (412 + 388) and only two `execute_tool` children (`call_A`, `call_B'`). The span tree is structurally valid: every span has required attributes, parent/child links are intact, usage sums arithmetically. But `call_B`—a tool call the model actually requested and was billed for—has **no span**. The parent's declared output tokens include the tokens spent generating the `call_B` invocation, yet no child span accounts for the execution attempt. A downstream auditor reconstructing "what tools did this agent call" from spans alone will conclude two calls; the model's own completion record says three. The discrepancy is invisible to the collector because OpenTelemetry has no cross-span referential integrity check on `gen_ai.tool.call.id`. The second observed variant is the inverse: a runtime that emits `execute_tool` spans for *every* dispatch attempt, including retries, but keeps the parent's `output_tokens` at the *first* completion's value (412), because the retry's usage was recorded on a sibling span that was later orphaned when the parent context was re-entered. Here the parent under-reports usage by 388 tokens while the child set over-reports tool calls relative to the parent's completion. Both directions break replay. ## Condition of Validity The invariant holds only when all of the following are true at the moment `span.end()` is called on the agent span: - **Referential completeness:** the set of `gen_ai.tool.call.id` values across all `execute_tool` descendant spans is a superset of the `tool_calls[].id` set emitted by every `chat` completion within the agent's scope. Any requested-and-billed call must have a span, even if the span status is `ERROR` with an exception event for the timeout. - **Usage monotonicity:** `parent.output_tokens >= Σ(child chat output_tokens)` and `parent.input_tokens >= Σ(child chat input_tokens)`, where the sum covers *all* chat completions, including retries and the failed attempt. - **Single-writer discipline:** exactly one component (the agent runtime's span manager) mutates the parent's usage attributes; child spans never write to the parent. When any of these fails, the span must be closed with `status=ERROR` and an explicit `gen_ai.agent.accounting_invariant_violation` event—not silently emitted as `OK`. The condition of validity is *not* "the numbers are correct"; it is "the numbers are reconcilable from the span tree alone." A span that is wrong but internally consistent can be repaired by replay; a span that is internally inconsistent cannot. ## Decision Boundary The decision an instance must make at span-close time is binary and must be resolved *before* `end()`: - **Close as OK** only if referential completeness and usage monotonicity both hold. This is the case where the tool wrapper instruments dispatch attempts (including failures) uniformly, and usage is written once by the span manager after all children have ended. - **Close as ERROR with a violation event** if either check fails. Do not "fix" the numbers by padding usage or synthesizing missing tool spans—synthesized spans fabricate `gen_ai.tool.call.id` values that never appeared in any completion, which is worse than a gap because it makes the record look complete. - **Defer close** (hold the span open, emit a `gen_ai.agent.pending_reconciliation` event) only if the runtime has an out-of-band completion log it can reconcile against within a bounded window. Deferral is bounded by the exporter's batch timeout; an unbounded deferral produces a span that is dropped at flush and the entire turn vanishes from the trace. The boundary is sharp: the moment the parent span is exported, the record is frozen. There is no post-hoc repair path in the OpenTelemetry data model for a span that has been flushed—only a new span or an out-of-band correction event, neither of which restores replayability. ## Operational Effect The practical consequence is that **token accounting and tool-call auditing must be validated as a joint invariant at the emitter, not at the collector.** Collectors see well-formed spans and have no basis to reject them; the GenAI conventions provide no schema-level constraint linking `gen_ai.usage.*` to child `gen_ai.tool.call.id` cardinality. An agent that instruments only successful tool dispatch will systematically under-count tool calls relative to billed tokens whenever a tool fails—and tool failures are exactly the events an audit most needs to see. An agent that instruments every dispatch but writes usage once per completion will systematically over-count child calls relative to parent usage on retry. The guardrail is a span-manager-level reconciler that runs in `end()`: intersect the completion's `tool_calls` set against the child span set, compare usage sums, and fail closed. This costs one set comparison and two integer comparisons per agent turn. The alternative—reconciling in a downstream pipeline—requires joining spans against provider completion logs that may be retained for different windows or not at all, and cannot distinguish a genuinely missing span from a span that was sampled out. ## Enforcement Sketch The reconciler below is the minimum viable guardrail. It assumes the runtime has already collected child span records before the parent closes, which is the only ordering that makes the invariant checkable. ```python from dataclasses import dataclass, field class GenAiAccountingInvariantViolation(RuntimeError): """Raised when an agent span's tool-call set and usage totals do not reconcile.""" pass @dataclass class SpanRecord: name: str tool_call_id: str | None = None output_tokens: int = 0 input_tokens: int = 0 @dataclass class AgentSpan: requested_tool_call_ids: set[str] = field(default_factory=set) # from every chat completion children: list[SpanRecord] = field(default_factory=list) declared_input_tokens: int = 0 declared_output_tokens: int = 0 status: str = "UNSET" def close_agent_span(span: AgentSpan) -> None: emitted_ids = {c.tool_call_id for c in span.children if c.tool_call_id} missing = span.requested_tool_call_ids - emitted_ids if missing: span.status = "ERROR" raise GenAiAccountingInvariantViolation( f"requested tool calls without execute_tool spans: {sorted(missing)}" ) child_out = sum(c.output_tokens for c in span.children) child_in = sum(c.input_tokens for c in span.children) if child_out > span.declared_output_tokens or child_in > span.declared_input_tokens: span.status = "ERROR" raise GenAiAccountingInvariantViolation( f"usage overrun: declared out={span.declared_output_tokens} " f"child out={child_out}; declared in={span.declared_input_tokens} " f"child in={child_in}" ) span.status = "OK" ```