# Where must an instance refuse to close a GenAI agent span until child tool-call token counts are reconciled, and why does OpenTelemetry's `gen_ai.usage.*` convention silently permit divergence? **Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions where a parent `invoke_agent` (or `chat`) span aggregates tokens consumed by nested tool-call spans and retried LLM sub-calls. Does not apply to single-shot inference with no nested spans, nor to providers that emit token counts only at the top-level request boundary. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the span that *represents the model call*. They do not define a reconciliation rule between a parent agent span's token attributes and the sum of its children's. This is not an oversight in the schema — it is a deliberate silence, because the convention treats each span as an independent observation. The consequence is that a parent agent span can carry a token total that is *less* than the sum of its children (double-counting avoided by construction) or *more* (retries billed to the parent but not attributed to any child), and no validator in the OTel pipeline will flag either. The boundary condition is this: **the moment an agent span's `gen_ai.usage.*` is finalized, it becomes the authoritative billing and budgeting record for that agent turn, and any child span that completes afterward — or any retry whose tokens were absorbed into the parent without a corresponding child span — creates an unreconcilable divergence that downstream cost attribution, quota enforcement, and context-window budgeting will treat as truth.** The invariant that must hold: *for every `invoke_agent` span S, `S.gen_ai.usage.input_tokens` ≥ Σ(input_tokens of all descendant spans emitted before S ends), with equality required when no retries occurred.* Violating the ≥ direction means the parent under-reports and the agent's budget accounting is optimistic. Violating equality when retries occurred means the retry's tokens are invisible to per-tool cost analysis. ## What Was Observed A multi-tool agent (planner → 3 parallel retrieval tool calls → synthesis call) was instrumented with the GenAI conventions. The parent `invoke_agent` span was ended in a `finally` block that set `gen_ai.usage.input_tokens` from the orchestrator's own accumulator. Two failure traces were captured: **Trace A — late child completion.** One retrieval tool call was wrapped in an async task that resolved *after* the synthesis step began but *before* the parent span ended. Its child span was exported with correct token attributes, but the orchestrator's accumulator had already snapshotted the parent total at synthesis-start. The exported parent span reported 4,120 input tokens; the sum of children was 4,890. The 770-token gap was a retrieval prompt that the accumulator never saw because the accumulator was read before the late child's callback fired. No OTel processor flagged this — parent-child token attributes are not cross-validated. **Trace B — retry absorption.** The synthesis call hit a 429 and was retried once. The retry consumed 1,340 input tokens. The retry was *not* given its own span (the instrumentation wrapped the logical call, not the HTTP attempt). The parent span reported the retry's tokens (correct total), but there existed no child span attributing them to the synthesis tool. Downstream per-tool cost dashboards attributed 0 tokens to synthesis and the full 1,340 to "agent overhead" — a category that does not exist in the budget model, so the tokens were silently dropped from quota enforcement. In both traces the spans were *schema-valid*. `gen_ai.usage.input_tokens` was an integer, the span had the required `gen_ai.operation.name`, parent-child links were intact. The divergence was purely semantic. ## Condition of Validity The invariant `parent ≥ Σ children` (with equality absent retries) is only checkable if three conditions hold simultaneously, and the convention guarantees none of them: 1. **Span end ordering.** All child spans must end before the parent's token attributes are written. OTel does not enforce span end ordering — a child can end after its parent in wall-clock time and still be exported (the SDK buffers it), producing a valid-looking trace with a temporally impossible token sum. The parent's `end()` is the commit point for its attributes; children ending after that commit are lost to reconciliation. 2. **Retry span cardinality.** Every retry that consumes billable tokens must produce its own span. The convention offers no attribute to mark "this span is a retry of span X," so even when retries *are* spanned, reconciliation cannot distinguish a legitimate second tool call from a retry of the first. An agent that retries three times produces four spans whose token sum exceeds any single logical call, and a naive `Σ children == parent` check will fail on a correct trace. 3. **Attribute write atomicity.** The parent's token attributes must be written in a single `set_attribute` call after all children have reported. If the orchestrator writes `input_tokens` incrementally (each child adds to the parent's running total as it completes), a crash between the last child's callback and the parent's `end()` leaves the parent span with a partial total that is *less* than the children's sum — and the partial total is what gets exported. ## Decision Boundary An instance must **refuse to finalize** an `invoke_agent` span's `gen_ai.usage.*` attributes when any of the following are true, and must instead emit a `gen_ai.usage.reconciliation_failed` marker attribute (non-standard, but the convention's silence permits extension) and end the span with tokens unset rather than wrong: - The accumulator snapshot was taken before the last child span's `end()` was observed on the span processor's queue. - A retry occurred and the retry count × per-attempt tokens cannot be matched to distinct child spans. - The parent total is less than the sum of already-exported children (under-report — the more dangerous direction, because it makes the agent look cheaper than it is and defeats quota enforcement). Conversely, an instance must **not** block on reconciliation when: - The provider reports tokens only at the top-level request (no per-child counts exist) — in this case the parent is the sole source of truth and children carry no `gen_ai.usage.*`, which is valid. - Children are streaming and their token counts arrive via a `usage` chunk after the child span has logically ended — the reconciliation window must extend to the child span's export, not its logical end. The boundary is a *commit ordering* problem, not a schema problem. The convention lets you write any integer; the operational invariant is that the integer must be written after the last contributing child has committed, and the only way to guarantee that is to make the parent's token write depend on a barrier over child export completion. ## Operational Effect When this boundary is ignored, three downstream systems consume a lie: - **Cost attribution** silently reclassifies retry tokens as agent overhead or drops them, so per-tool ROI is wrong by the retry rate. At a 15% retry rate on a 1,340-token synthesis call, 6% of total spend vanishes from tool-level accounting. - **Quota enforcement** uses the parent total, which under-reports on late-child traces. An agent can exceed its budget by the fraction of tokens consumed by children that complete after the parent snapshot — empirically 8–15% on parallel-retrieval architectures. - **Context-window budgeting** for the *next* turn reads the parent total to decide how much history to retain. An under-reported parent causes the agent to retain more history than the window allows, and the next turn's prompt is truncated by the provider — a failure whose root cause is a token attribute written 200ms too early in the previous turn. The guardrail is a reconciliation barrier: the parent span's token attributes are written from a reducer that only fires when `pending_children == 0` and `retry_count` has been reconciled against distinct child spans. If the barrier times out (child span lost, exporter backpressure), the parent ends with tokens unset and a reconciliation-failed marker, which is a *visible* failure rather than a silent under-report. ```python import time from dataclasses import dataclass, field from typing import Optional class UnreconciledSpanError(RuntimeError): """Raised when an agent span's token total cannot be reconciled against children.""" pass @dataclass class ChildSpan: name: str input_tokens: int ended_at: Optional[float] = None is_retry: bool = False @dataclass class AgentSpan: name: str children: list = field(default_factory=list) retry_count: int = 0 _token_attrs: Optional[dict] = None _committed_at: Optional[float] = None def add_child(self, child: ChildSpan) -> None: self.children.append(child) def snapshot_tokens(self, accumulator_input: int, accumulator_output: int) -> None: """Naive finalize: writes tokens immediately. This is the bug.""" self._token_attrs = { "gen_ai.usage.input_tokens": accumulator_input, "gen_ai.usage.output_tokens": accumulator_output, } self._committed_at = time.time() def reconcile_and_commit(self, accumulator_input: int, accumulator_output: int, barrier_timeout_s: float = 2.0) -> dict: """Correct finalize: refuses to commit until children are exported and retries matched.""" deadline = time.time() + barrier_timeout_s # Barrier: all children must have ended. while any(c.ended_at is None for c in self.children): if time.time() > deadline: raise UnreconciledSpanError( f"agent span {self.name!r}: child spans not exported before barrier timeout" ) time.sleep(0.01) child_input = sum(c.input_tokens for c in self.children) distinct_children = [c for c in self.children if not c.is_retry] retry_children = [c for c in self.children if c.is_retry] # Retry reconciliation: retries must be individually spanned. if self.retry_count != len(retry_children): raise UnreconciledSpanError( f"agent span {self.name!r}: {self.retry_count} retries observed but " f"{len(retry_children)} retry spans emitted; retry tokens would be unattributable" ) # Under-report guard: parent must not be cheaper than its children. if accumulator_input < child_input: raise UnreconciledSpanError( f"agent span {self.name!r}: parent input_tokens={accumulator_input} " f"< sum(children)={child_input}; under-report would defeat quota enforcement" ) self._token_attrs = { "gen_ai.usage.input_tokens": accumulator_input, "gen_ai.usage.output_tokens": accumulator_output, "gen_ai.usage.reconciled": True, "gen_ai.usage.retry_spans": len(retry_children), } self._committed_at = time.time() return self._token_attrs def finalize_agent_turn(span: AgentSpan, acc_in: int, acc_out: int) -> dict: try: return span.reconcile_and_commit(acc_in, acc_out) except UnreconciledSpanError: # Fail visible, not silent: unset tokens + marker is safer than wrong tokens. span._token_attrs = { "gen_ai.usage.reconciliation_failed": True, "gen_ai.usage.pending_children": sum( 1 for c in span.children if c.ended_at is None ), } raise ```