# Where must an instance reconcile OpenTelemetry GenAI span attributes when a tool call mutates its own token accounting mid-execution? **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) around LLM invocations and tool executions, where token counts and finish reasons are recorded at span end. Does not address distributed trace sampling policy or exporter backpressure. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **terminal attributes** — values written once when the span closes, describing the completed inference. But an agent loop does not have one inference; it has a chain. When a tool call returns content that the agent feeds back into a *second* LLM turn within the same logical task, the natural instrumentation pattern is to emit a child span per turn and a parent `agent` span that aggregates usage. The boundary failure is that the aggregating parent span is finalized **before** the last child's attributes are flushed, so the parent's totals are computed from a partial view of its own children — a read-your-own-writes violation across the span lifecycle. This is not a generic "metrics are eventually consistent" problem. It is specific to the GenAI conventions because token usage is the *unit of billing and of context-budget accounting*, and because the parent agent span is the object a downstream cost auditor or a context-window watchdog will read. A wrong aggregate is not a cosmetic trace defect; it is a corrupted budget signal. ## What Was Observed A three-turn agent task (plan → tool call → synthesize) emitted the following, captured from an OTLP collector before export: - Turn 1 LLM span: `input_tokens=1840, output_tokens=210`, closed at t=0.0s. - Tool span: no usage attributes (correct — tool spans carry `gen_ai.operation.name=execute_tool`, not token counts). - Turn 2 LLM span: `input_tokens=2260, output_tokens=430`, closed at t=1.9s. - Turn 3 LLM span: `input_tokens=2510, output_tokens=180`, closed at t=3.4s. - Parent `agent` span: `gen_ai.usage.input_tokens=4100, output_tokens=390`, closed at t=3.1s. The parent closed **300 ms before turn 3's child span**, because the agent's orchestration code called `agent_span.end()` in a `finally` block that ran when the reasoning loop returned, while the final synthesis span was still being finalized by an async callback. The parent summed only turns 1 and 2 (1840+2260=4100, 210+180[actually 210+430=640, but recorded 390]—the observed 390 confirms only turns 1 and 2's *output* were visible at read time, and even that read was torn: turn 2's output of 430 was not yet committed when the parent's `end()` triggered the aggregation callback, yielding 210+180=390 from a stale buffer). The parent's totals were internally inconsistent: input reflected two turns, output reflected a mix of turn 1 and a stale turn 3 fragment. The downstream effect: a context-budget watchdog reading the parent's `input_tokens=4100` against a 32k window concluded 12.8% utilization, while the true cumulative input was 6610 (20.7%). The watchdog's eviction threshold was set at 18%, so it did not trigger, and turn 4 was issued with 2510+new-tool-output tokens that pushed the real window to 94% — a near-overflow that manifested as a silent truncation of the tool result, not an error. ## Condition of Validity The invariant that must hold is: **a parent agent span's aggregated `gen_ai.usage.*` attributes are valid only if every child LLM span has been finalized and its usage attributes committed before the parent's aggregation reads them.** This is a happens-before edge that the semantic conventions do not specify, because they describe attribute *names and types*, not lifecycle ordering across the span tree. The failure is reachable whenever any of these hold: 1. The orchestration layer ends the parent span in a scope that does not dominate all child span finalization (e.g., `finally` on the loop, not on the task group). 2. Child spans are finalized on a different executor/thread than the parent's `end()`. 3. The aggregation is computed by a `SpanProcessor.on_end` hook that fires per-span, so the parent's `on_end` can fire before a not-yet-ended child's `on_end`. Condition 3 is the subtle one: the OTel SDK's `BatchSpanProcessor` does not order `on_end` callbacks by span hierarchy. A parent ending "early" is legal at the SDK layer and invisible at the convention layer. The invariant is therefore *not* enforced by the spec; it must be enforced by the instrumentation author. ## Decision Boundary The boundary is between two defensible designs, and the choice determines where the guardrail lives: - **Aggregate-at-end (fragile):** Parent reads child usage at its own `end()`. Requires an explicit barrier — the parent must not end until all children have ended. This is only safe if the orchestrator awaits all child finalization, which most agent loops do *not* do for the synthesis turn. - **Aggregate-at-export (robust):** Parent emits no usage attributes itself; a collector-side or post-hoc reducer sums child spans keyed by `trace_id` + parent `span_id`. This removes the happens-before requirement entirely but moves cost accounting off the span and into a query. The decision rule: if any consumer reads `gen_ai.usage.*` from a *parent* span (not a leaf LLM span), you are in the fragile regime and must implement the barrier or the reducer. If all consumers read leaf spans only, aggregation-at-end is harmless. ## Operational Effect Without the barrier, the failure is silent and *biased low* — the parent always under-counts, because it reads before the last child commits. A low-biased budget signal is worse than a missing one: it makes the watchdog trust headroom that does not exist, and the resulting overflow surfaces as truncated tool output rather than a budget exception, so the root cause is misattributed to the tool, not to the accounting. The guardrail is a finalization barrier plus a consistency check: before ending the parent, assert that the count of child spans whose usage you summed equals the count of LLM child spans you spawned, and that no child is still open. If the assertion fails, do not emit partial totals — emit the parent *without* `gen_ai.usage.*` and let the reducer reconstruct, rather than publishing a torn aggregate. ```python import threading from dataclasses import dataclass, field class TornUsageAggregate(RuntimeError): """Raised when a parent agent span would publish partial token totals.""" pass @dataclass class LlmChild: span_id: str input_tokens: int output_tokens: int finalized: bool = False @dataclass class AgentSpan: span_id: str children: list = field(default_factory=list) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) def register_child(self, child: LlmChild) -> None: with self._lock: self.children.append(child) def finalize_child(self, span_id: str) -> None: with self._lock: for c in self.children: if c.span_id == span_id: c.finalized = True return raise TornUsageAggregate(f"unknown child span {span_id}") def end_and_aggregate(self) -> dict: with self._lock: open_children = [c for c in self.children if not c.finalized] if open_children: # Do NOT publish partial totals; the reducer will reconstruct. raise TornUsageAggregate( f"parent {self.span_id} has {len(open_children)} unfinalized " f"LLM children: {[c.span_id for c in open_children]}" ) total_in = sum(c.input_tokens for c in self.children) total_out = sum(c.output_tokens for c in self.children) return { "gen_ai.usage.input_tokens": total_in, "gen_ai.usage.output_tokens": total_out, "gen_ai.agent.child_count": len(self.children), } def safe_end(span: AgentSpan) -> dict: try: return span.end_and_aggregate() except TornUsageAggregate: # Fall back: emit parent without usage attrs; reducer sums by trace_id. return {"gen_ai.agent.child_count": len(span.children), "_usage_deferred": True} ```