# Under what conditions must an instance refuse to emit a completed agent span when nested tool-call token telemetry violates the GenAI semantic-convention parent-sum invariant **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the `gen_ai.*` semantic conventions where a parent `invoke_agent` (or `execute_tool` wrapper) span aggregates `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` from child LLM and tool spans. Does not apply to flat, single-span-per-request instrumentation where no parent/child token aggregation occurs, nor to runtimes that emit spans only at the edge (gateway) and never observe per-call usage. ## Core Distinction There are two different things an agent runtime can mean by "the span is done": the *execution* is done, and the *telemetry record* is internally consistent. These normally coincide. They diverge at exactly one boundary — when a parent span's aggregated `gen_ai.usage.*` counters do not equal the sum of its children's counters, because a child was dropped, retried, deduplicated, or emitted from a different process than the one that closed the parent. The failure is not "telemetry is missing." Missing telemetry is a known, tolerated condition (sampling, exporter backpressure). The failure is *telemetry that is present, well-formed, and wrong in a way that silently corrupts the cost attribution tree*. A parent `invoke_agent` span that reports `input_tokens=12000` while its surviving children sum to `9000` is not degraded telemetry — it is a fabricated accounting record, and downstream cost reconciliation, budget enforcement, and replay-based verification will all trust it. The invariant at stake is the **parent-sum invariant**: for any span carrying aggregated `gen_ai.usage.*`, the value must equal the sum over the child spans actually referenced in the trace, or the span must not be marked complete with those values. ## What Was Observed A tool-using agent (planner → N parallel tool calls → synthesis) instrumented with a hand-rolled OTel wrapper. On the happy path, the parent `invoke_agent` span closed with `gen_ai.usage.input_tokens` and `output_tokens` summed from the planner call and the synthesis call. Tool spans (`execute_tool`) carried their own `gen_ai.usage.*` because the tool implementation itself made an internal LLM call (a summarizer, a re-ranker, a query-rewriter). The parent did **not** include tool-span usage in its sum — it only summed the two spans it "owned." Three concrete observations: 1. **The double-count / under-count divergence.** When the tool's internal LLM call succeeded, the tool span carried `input_tokens=3400`. The parent reported `12000`. The trace tree, summed honestly, was `15400`. Cost dashboards fed from parent spans under-reported by 28%; a second dashboard fed from a leaf-span rollup over-reported because it also counted the planner's retried attempt (see below). Neither matched the provider invoice. 2. **Retry duplication.** The planner call hit a 429, was retried at the SDK layer, and *both* attempts emitted a span with the same `gen_ai.request.model` and full `usage`. The parent summed only the successful attempt. The leaf rollup summed both. The parent-sum invariant held against the *successful child only* — a definitional choice that was never written down and differed between the two teams reading the same trace. 3. **Orphaned close.** The synthesis call was dispatched to a worker process. The parent span, held in the orchestrator, was closed by a timeout guard 200ms before the worker's child span arrived. The parent closed with `status=OK` and stale usage. When the child span landed, it referenced a `parent_span_id` that was already exported as complete. The collector accepted it; the trace became a parent with token counts that could never be reconciled because the child arrived after the parent's immutable close. The common thread: every one of these produced a span that passed schema validation, passed the OTel SDK's own consistency checks, and was *semantically false*. The `gen_ai.usage.*` conventions define attribute names and types; they do not define an aggregation contract. That gap is the boundary. ## Condition of Validity The parent-sum invariant is only meaningful — and the refusal to emit is only justified — under a specific set of conditions. State them explicitly, because outside them the correct behavior is to emit with a degraded-quality marker, not to refuse. The invariant holds, and refusal is required, **if and only if all of the following are true**: - The parent span declares aggregated usage. If the parent carries only `gen_ai.operation.name` and no `gen_ai.usage.*`, there is nothing to reconcile; emit freely. - The runtime can enumerate the child spans it intends to aggregate. A parent that legitimately aggregates "all descendants discovered at export time" (async, fire-and-forget) cannot enforce the invariant synchronously and must instead defer to a post-hoc reconciler. Refusal at close time is only correct for *synchronous* parent-child token ownership. - The set of children is **closed** at parent-close time. If any child is still in flight, the parent-sum is undefined, not violated. The correct action is to not close the parent, not to close it with a partial sum. - Retries are attributed to a stable logical call identity. If the runtime cannot distinguish "attempt 1 failed, attempt 2 succeeded" from "two distinct calls," the sum is ambiguous and the invariant cannot be evaluated. This requires a `gen_ai.request.id` or equivalent logical-call key propagated to both attempts. If any of these conditions fails, the runtime is in a regime where the invariant is *undefined*. Emitting a span there is not a violation — it is a different contract (best-effort usage), and it must be labeled as such via an explicit attribute so downstream consumers do not treat it as authoritative. ## Decision Boundary The decision boundary is not "does the sum match." It is **"can the runtime prove the sum is closed and stable before the parent span becomes immutable."** Concretely, at the moment the orchestrator is about to call `span.end()` on a parent carrying aggregated usage, it must evaluate: - `expected_children` — the set of logical call IDs the parent committed to aggregating, recorded at dispatch time. - `observed_children` — the set of child spans actually received, keyed by logical call ID. - `usage_sum(observed_children)` — the reconciled total. The boundary conditions: | Condition | Action | |---|---| | `expected == observed` and sum is stable | Emit parent with aggregated usage. Invariant holds. | | `expected ⊋ observed` (child still in flight) | **Do not close.** Extend deadline or downgrade to best-effort with `gen_ai.usage.reconciled=false`. | | `expected ⊋ observed` (child permanently lost) | Close, but set `gen_ai.usage.reconciled=false` and `gen_ai.usage.missing_children=`. Never emit a clean sum. | | `observed ⊋ expected` (unexpected child, e.g. duplicate retry) | Reconcile by logical call ID before summing. If ambiguous, refuse. | | Sum computed but a child arrived after close | Refuse to have closed; this is the orphaned-close failure. | The sharp edge: the runtime must treat *"child arrives after parent close"* as a **refusal condition**, not a race to be tolerated. The parent span's usage attributes are immutable once exported. A late child does not retroactively fix the parent; it creates an unreconcilable trace. The guardrail is a **close barrier**: the parent's `end()` is gated on a barrier that all `expected_children` have either reported or been declared lost. This is the same structure as a structured-concurrency scope, applied to telemetry rather than execution. The invariant, stated as a rule the runtime can enforce: > A parent span carrying `gen_ai.usage.*` may transition to `STATUS_OK` only if, at the barrier, `usage_sum(observed_children) == declared_usage` and `observed_children == expected_children`. Otherwise it transitions to `STATUS_ERROR` with `gen_ai.usage.reconciled=false`, or it does not transition at all. ## Operational Effect When this invariant is enforced, three things change operationally, and one thing gets harder. **Cost attribution becomes auditable.** Every parent span's usage is either provably equal to its children's sum or explicitly flagged as unreconciled. Downstream cost pipelines can partition on `gen_ai.usage.reconciled` and route unreconciled spans to a reconciliation queue rather than silently averaging them into the invoice. The 28% under-report in the observation above becomes a labeled 28% gap, not a silent one. **Replay-based verification gains a ground truth.** When an auditor agent replays a trace to verify an agent's behavior, it can trust that a clean parent span's token counts are the true sum. Without the invariant, replay verification of token-budget compliance is unsound — the auditor may "verify" a run that stayed under budget while the actual provider bill shows it did not. **Retry accounting is forced to be explicit.** The logical-call-ID requirement means retries cannot be silently double-counted or silently dropped. The runtime must decide, once, whether a retried call's usage is attributed to the logical call (sum of attempts) or the successful attempt (last-wins), and encode that decision in the trace. Ambiguity becomes a build-time error, not a dashboard discrepancy discovered a month later. **The cost: parent spans can hang.** The close barrier means a lost child blocks parent close until the deadline fires. This is the correct trade — a hung span is visible and bounded by the deadline; a falsely-closed span is invisible and unbounded in its downstream damage. The deadline must be short enough that hung spans are rare and long enough that legitimate slow children (a tool making its own LLM call) are not falsely declared lost. This is a tuning parameter, and it must be tuned against the tool-latency distribution, not guessed. The boundary condition, in one line: **the parent-sum invariant is enforceable exactly when the runtime owns synchronous closure of a known child set, and the correct response to a violated invariant is to refuse the clean close, not to emit a plausible number.** ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Set class UnreconciledUsageError(RuntimeError): """Raised when a parent span carrying gen_ai.usage.* cannot prove its aggregated counters equal the sum over its closed child set.""" @dataclass class ChildUsage: logical_call_id: str input_tokens: int output_tokens: int arrived: bool = True @dataclass class AgentSpan: name: str declared_input_tokens: int = 0 declared_output_tokens: int = 0 expected_children: Set[str] = field(default_factory=set) observed_children: Dict[str, ChildUsage] = field(default_factory=dict) closed: bool = False def register_child(self, usage: ChildUsage) -> None: if self.closed: # Orphaned-close failure: a child arrived after the parent was # exported as complete. The parent's usage attributes are now # immutable and can never be reconciled. raise UnreconciledUsageError( f"child {usage.logical_call_id!r} arrived after parent " f"{self.name!r} was closed; parent usage is unreconcilable" ) if usage.logical_call_id not in self.expected_children: # Unexpected child (e.g. duplicate retry span). Must be reconciled # by logical call id before it may contribute to the sum. raise UnreconciledUsageError( f"child {usage.logical_call_id!r} not in expected set " f"{sorted(self.expected_children)}; reconcile by logical call id" ) self.observed_children[usage.logical_call_id] = usage def close(self) -> None: """Close the parent span, enforcing the parent-sum invariant.""" missing = self.expected_children - set(self.observed_children) if missing: # Do not emit a clean sum over a partial child set. Either the # child is still in flight (do not close) or it is lost (close # with reconciled=false). Here we refuse the clean close. raise UnreconciledUsageError( f"parent {self.name!r} cannot close: children {sorted(missing)} " f"still in flight or lost; refusing to emit clean usage sum" ) summed_input = sum(c.input_tokens for c in self.observed_children.values()) summed_output = sum(c.output_tokens for c in self.observed_children.values()) if (summed_input, summed_output) != ( self.declared_input_tokens, self.declared_output_tokens, ): raise UnreconciledUsageError( f"parent {self.name!r} declared " f"(in={self.declared_input_tokens}, out={self.declared_output_tokens}) " f"but children sum to (in={summed_input}, out={summed_output})" ) self.closed = True def emit_agent_span(span: AgentSpan) -> AgentSpan: span.close() return span ```