# Under what conditions must an instance refuse to close an OpenTelemetry GenAI agent span when tool-call token accounting diverges from the parent span's `gen_ai.usage.output_tokens`? **Date of Record:** 2026 November 28 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) with a parent agent span that aggregates child tool-call and LLM-call spans. Does not apply to single-shot inference spans with no tool fan-out, nor to vendors that emit only a flat, non-hierarchical span tree. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.output_tokens` as a *per-span* measurement of tokens the model emitted for that span. Aggregation across a parent agent span is an *operator convention*, not a spec guarantee. The failure mode is not "the numbers are wrong"—it is that the parent span's `output_tokens` and the sum of its child spans' `output_tokens` are computed from **two different tokenizers at two different times**: the parent is typically accounted by the orchestrator's own counter (often a rough estimate or the provider's reported completion count), while each child LLM call is accounted by the provider response (`usage.completion_tokens`) or a local tokenizer. These disagree by construction whenever: 1. The agent re-tokenizes a tool result before feeding it back into the model (tool-result re-encoding), inflating the *next* child's `input_tokens` but not the parent's `output_tokens`. 2. The model emits a tool call as structured output (JSON function-call) whose serialized form the provider counts differently than the orchestrator's chunked stream counter. 3. A retried child LLM call emits partial tokens that the provider bills but the orchestrator discards from the span it finally closes. The invariant that must hold before a parent agent span is closed: `parent.gen_ai.usage.output_tokens >= Σ child.gen_ai.usage.output_tokens` **and** the residual `parent − Σchildren` is explainable by a recorded, non-tool emission (e.g., the agent's own final natural-language answer). When the residual is negative—children claim more output tokens than the parent—the span is *unaccountable* and closing it silently produces a telemetry record that downstream cost attribution and replay verification will trust incorrectly. ## What Was Observed A planner-executor agent (one planner span, N executor tool-call spans, each wrapping one LLM call) was instrumented per the GenAI conventions. On a task with 14 tool calls, the parent span closed with `gen_ai.usage.output_tokens = 2,041`. Summing the 14 child spans' `gen_ai.usage.output_tokens` gave 2,318. The residual was **−277 tokens**: the children collectively claimed 13.6% more output than the parent that supposedly contains them. Root cause traced to two independent effects: - **Retry leakage.** Three child LLM calls hit a 529 and were retried. The orchestrator recorded only the *successful* attempt's `completion_tokens` on the child span, but its parent-level counter (a streaming accumulator) had already counted the partial tokens from the failed attempts before the retry. Wait—that inflates the parent, not the children. The actual direction was the reverse: the orchestrator's parent counter *reset* on retry boundary and lost the first attempt's tokens, while the provider's per-call `usage` (written to the child span) included them. So children > parent. - **Structured tool-call serialization.** The model emitted function calls as JSON. The provider counted the JSON string as completion tokens (child span), but the orchestrator's parent counter used a whitespace tokenizer on the *decoded* argument values, undercounting punctuation and keys. The span tree was internally inconsistent. A downstream cost-attribution job that trusted the parent span under-billed the task by ~12%; a replay verifier that trusted the children over-attributed to the executor role. Neither consumer could detect the contradiction because OTel has no built-in cross-span sum invariant. ## Condition of Validity The guardrail is only valid to enforce under these conditions, and must be *skipped* otherwise: - The parent span carries `gen_ai.operation.name = "agent"` (or `"invoke_agent"`) and is the direct ancestor of every child span being summed. Orphaned or cross-trace children must be excluded—summing across traces produces false negatives. - All child spans share the same `gen_ai.system` / `gen_ai.provider.name`. Mixed-provider fan-out (e.g., a planner on one vendor, executors on another) legitimately produces tokenizer disagreement that the invariant cannot adjudicate; the check must degrade to a *warning* span event, not a refusal. - The residual tolerance is explicit and recorded. A residual within `[0, ε]` where `ε` is a declared `agent.token_accounting.tolerance` (commonly 0 for strict, or a small positive for streaming estimates) is valid. A **negative** residual beyond `−ε` is the hard-fail condition. - The parent span has not already been exported. OTel span processors are synchronous at `end()`; once `span.end()` fires, the record is immutable and the invariant can no longer be enforced. The check must run *before* `end()`. ## Decision Boundary The boundary between "close the span" and "refuse and quarantine" is: | Condition | Action | |---|---| | `parent.output ≥ Σchildren.output` and residual within tolerance | Close normally; attach `agent.token_accounting.residual` as a span attribute for auditability. | | `parent.output ≥ Σchildren.output` but residual exceeds tolerance | Close, but set span status `ERROR` with `agent.token_accounting.residual_exceeded`; do not block. | | `parent.output < Σchildren.output` within `−ε` | Close with a `token_accounting.negative_residual` **event** (not status); downstream attribution must be flagged approximate. | | `parent.output < Σchildren.output` beyond `−ε` | **Refuse to close.** Do not call `span.end()`. Emit a quarantine span event, mark the span `UNSET`→`ERROR`, and route the trace to a reconciliation queue. The instance must not let a negative-residual parent span reach the exporter as if it were valid. | The non-obvious part: the refusal is *not* about correctness of any single number. It is about preventing an internally contradictory record from entering the telemetry store, where it will be consumed by cost attribution and replay verification that have no way to re-derive the contradiction. A quarantined span is recoverable; an exported contradictory span is not. ## Operational Effect Refusing to close on negative residual has three operational consequences that must be designed for: 1. **Span leak risk.** A refused `end()` leaves the span open in the processor's buffer. If the agent crashes or the reconciliation queue is not drained, the span is lost entirely—worse than a wrong span. The quarantine path must therefore *also* persist a sidecar record (trace_id, span_id, both token figures, residual) to durable storage before refusing, so reconciliation can reconstruct it. 2. **Backpressure coupling.** Reconciliation queues fill during provider incidents (retries are the dominant cause of negative residual). The queue depth must be capped, and on overflow the policy must switch from *refuse* to *close-with-ERROR-and-flag*—degrading to a marked-but-exported span rather than dropping telemetry silently. 3. **Replay determinism.** A replay verifier that re-runs the agent must be told which spans were quarantined, or it will re-derive a different accounting and flag a false discrepancy. The quarantine sidecar is the source of truth for replay, not the exported span tree. The invariant is thus not "tokens must add up"—it is "an instance must not export a parent agent span whose child token sum exceeds it beyond tolerance, because that record is unaccountable and its consumers cannot detect the contradiction." The guardrail is a pre-`end()` gate, and its cost is a durable sidecar and a bounded quarantine queue. ```python import time from dataclasses import dataclass, field from typing import Optional class TokenAccountingDivergence(RuntimeError): """Raised when a parent agent span's output_tokens is less than the sum of its child spans' output_tokens beyond the declared tolerance.""" pass @dataclass class SpanRecord: span_id: str parent_id: Optional[str] operation_name: str output_tokens: int provider: str ended: bool = False @dataclass class AgentSpanGate: tolerance: int = 0 quarantine: list = field(default_factory=list) def _children_of(self, parent: SpanRecord, all_spans: list) -> list: return [ s for s in all_spans if s.parent_id == parent.span_id and s.operation_name in ("llm", "chat", "tool_call") and s.provider == parent.provider ] def close_agent_span(self, parent: SpanRecord, all_spans: list) -> None: if parent.ended: raise TokenAccountingDivergence( f"span {parent.span_id} already ended; invariant cannot be enforced" ) children = self._children_of(parent, all_spans) child_sum = sum(c.output_tokens for c in children) residual = parent.output_tokens - child_sum if residual < -self.tolerance: # Persist a durable sidecar BEFORE refusing, or the span is lost. self.quarantine.append({ "trace_span": parent.span_id, "parent_output": parent.output_tokens, "child_sum": child_sum, "residual": residual, "provider": parent.provider, "ts": time.time(), }) # Do NOT call parent.end(); route to reconciliation. raise TokenAccountingDivergence( f"span {parent.span_id}: parent output {parent.output_tokens} < " f"child sum {child_sum} (residual {residual}, tol {self.tolerance}); " f"refusing to close, quarantined for reconciliation" ) # Within tolerance: close normally, record residual for audit. parent.ended = True # span.set_attribute("agent.token_accounting.residual", residual) # span.end() def run_example() -> None: gate = AgentSpanGate(tolerance=0) parent = SpanRecord("p1", None, "agent", output_tokens=2041, provider="vendorA") children = [ SpanRecord(f"c{i}", "p1", "llm", output_tokens=165, provider="vendorA") for i in range(14) ] # sum = 2310 > 2041 try: gate.close_agent_span(parent, [parent, *children]) except TokenAccountingDivergence as e: assert not parent.ended assert len(gate.quarantine) == 1 print(f"quarantined: {e}") if __name__ == "__main__": run_example() ```