# Where must an instance halt span emission when OpenTelemetry GenAI token-accounting attributes diverge from the reasoning trajectory's terminal state **Date of Record:** 2026 November 26 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a single logical trajectory spans multiple LLM invocations and tool calls under one trace; specifically the boundary where cumulative token accounting on a parent span must reconcile with terminal child-span usage before the span is closed. Does not cover single-shot inference instrumentation or metrics-only pipelines that omit span-level usage attributes. ## Core Distinction The GenAI semantic conventions treat token usage as a *span attribute* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the newer `gen_ai.usage.cache_read.input_tokens` / `gen_ai.usage.reasoning.output_tokens` families) that is *reported per span*. They do not define a normative aggregation rule across a parent agent span and its child LLM/tool spans. This is the seam. Instrumentation authors conflate two distinct quantities: 1. **Reported usage** — what the provider's response object says was consumed for that one call, attached to the leaf span at close time. 2. **Attributed usage** — the sum a parent agent span claims for its subtree, which observers (cost dashboards, budget enforcers, rate-limit auditors) actually trust. These diverge silently whenever a child span is dropped, sampled out, retried, or closed *after* its parent. The invariant that must hold is: at parent-span close, `attributed_usage(parent) == Σ reported_usage(children that will be exported)`. When it does not, the trajectory is *accounting-inconsistent*, and any downstream consumer that sums leaf spans will disagree with the parent rollup. The failure is not a crash; it is a quiet, permanent discrepancy baked into the trace at write time. ## What Was Observed A multi-step agent (planner → 4 tool calls → synthesizer, 3 LLM invocations total) was instrumented with a parent span `agent.trajectory` carrying a rollup of `gen_ai.usage.*`. The observed trace exhibited a **1,847-token over-attribution** on the parent relative to the sum of exported leaf spans, with no error recorded anywhere. The trigger condition was a specific interleaving: 1. The parent span accumulated usage incrementally as each child LLM call returned (a common pattern: `parent.set_attribute("gen_ai.usage.output_tokens", running_total)`). 2. The provider returned a **streamed response** whose final usage chunk arrived *after* the SDK's span had already been closed by a `with tracer.start_as_current_span(...)` context manager exiting on stream exhaustion — but the agent loop read usage from a separately-buffered accumulator that included the pre-stream token estimate. 3. One tool-call child span was **retried** after a `429`; the retry produced a second leaf span (correct), but the parent's incremental accumulator was incremented on *both* the failed and retried attempt, while only the successful attempt's span carried `gen_ai.usage.*` (the failed span recorded `error=true` with zero usage, per convention). 4. The synthesizer call used **prompt caching**; `gen_ai.usage.input_tokens` reported the *full* prompt length while `gen_ai.usage.cache_read.input_tokens` reported the cached prefix. The parent accumulator summed `input_tokens` across calls without subtracting cache reads, double-counting cached tokens as fresh. The divergence was only detectable by a query that summed `gen_ai.usage.*` over leaf spans and compared against the parent — a check no standard backend performs, because the convention does not mandate parent rollups at all. The dashboard showed parent cost 22% higher than the leaf-sum cost; both "looked valid" in isolation. ## Condition of Validity The rollup invariant `attributed_usage(parent) == Σ reported_usage(exported children)` is **valid only under all of the following**, and instrumentation must assert them or refuse to emit the parent rollup: - **Close ordering:** every child span that contributes to the rollup is closed *before* the parent's close callback runs. Streaming, async tool dispatch, and fire-and-forget sub-agents routinely violate this; a child closed after the parent is either dropped (parent over-counts) or arrives late to a trace the backend has already finalized (parent under-counts). - **Retry accounting is single-counted:** a retried call contributes usage exactly once — from the attempt whose span is exported with usage attributes. Failed-attempt spans must carry zero usage and `error=true`; the parent must not increment on them. - **Cache and reasoning tokens are partitioned:** `input_tokens` must exclude `cache_read.input_tokens` when both are present, or the parent must sum only the non-overlapping fields. The convention permits providers to report either inclusive or exclusive; the parent rollup must pick one and document it, because the leaf spans may be heterogeneous across providers in one trajectory. - **Sampling is uniform down the subtree:** if the parent is sampled-in but a child is sampled-out (head or tail sampling mismatch), the rollup is unverifiable and must be marked `gen_ai.usage.attribution="partial"` rather than emitted as authoritative. If any condition fails, the correct behavior is to **omit the parent rollup and set an explicit attribution-completeness attribute** — never to emit a best-effort sum. A missing rollup is recoverable by leaf aggregation; a wrong rollup is not, because downstream systems trust the parent. ## Decision Boundary The boundary is a single predicate evaluated at parent-span close: ``` emit_rollup ⟺ all_children_closed_before_parent ∧ retries_single_counted ∧ cache_fields_partitioned ∧ subtree_sampling_uniform ``` When `emit_rollup` is false, the span must transition to a **degraded-accounting state**: attributes `gen_ai.usage.attribution="partial"` (or `"unavailable"`), no `gen_ai.usage.*` totals, and a recorded `gen_ai.usage.attribution_reason` enumerating the violated conjuncts. This is the decision boundary — it is not "should we log an error" (the trajectory succeeded functionally) but "is this span allowed to carry an authoritative cost claim." Conflating functional success with accounting authority is the root error. The agent ran correctly; the *telemetry* is not entitled to assert a number. A second, subtler boundary: **late-arriving children**. If a child span closes after the parent (async tool, detached sub-agent), the parent's rollup is frozen and cannot be corrected in-place — OTel spans are immutable after `End()`. The only correct resolution is to emit a **reconciliation span** (a sibling `agent.trajectory.reconcile` with the delta and a link to the parent), never to mutate or re-emit the parent. Backends that sum parents will still under-count until they consume the reconciliation span; this is a known, bounded loss, preferable to a silent over-count. ## Operational Effect With the boundary enforced, three operational properties change: 1. **Cost dashboards become leaf-authoritative or explicitly partial.** A query summing `gen_ai.usage.*` over leaf spans is always correct; parent rollups are trusted only when `attribution="complete"`. The 22% phantom-cost class of bug disappears because the dashboard has a defined fallback. 2. **Budget enforcers must gate on attribution completeness.** An enforcement loop that halts an agent when cumulative tokens exceed a cap must read leaf sums, not parent rollups, or it will trip early on over-attributed parents and late on under-attributed ones. The `attribution` attribute is the gate: refuse to enforce against `partial` rollups and fall back to leaf aggregation. 3. **Trajectory replay becomes verifiable.** A replay harness can assert `Σ leaf usage == parent rollup` for every `complete` span and flag every `partial` span for manual reconciliation — turning a silent accounting drift into a testable invariant. The cost of the guardrail is a small amount of dropped telemetry (no parent rollup on partial subtrees) and one extra reconciliation span on late children. The cost of omitting it is a trace that *looks* authoritative and is silently wrong — the worst failure mode for an observability system, because it poisons every downstream decision that trusts it. ```python from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when a parent agent span cannot lawfully emit a usage rollup.""" @dataclass class ChildSpanUsage: span_id: str closed: bool input_tokens: int = 0 output_tokens: int = 0 cache_read_input_tokens: int = 0 is_retry_attempt: bool = False exported: bool = True @dataclass class ParentTrajectory: span_id: str children: list[ChildSpanUsage] = field(default_factory=list) subtree_sampled_uniformly: bool = True def _partitioned_input(c: ChildSpanUsage) -> int: # Convention: input_tokens is exclusive of cache reads for rollup purposes. return max(c.input_tokens - c.cache_read_input_tokens, 0) def compute_authoritative_rollup(parent: ParentTrajectory) -> dict: """Return a rollup dict ONLY if every validity conjunct holds; else raise.""" if not parent.subtree_sampled_uniformly: raise UsageAttributionError( f"span {parent.span_id}: subtree sampling non-uniform; " "rollup would be unverifiable" ) for c in parent.children: if c.exported and not c.closed: raise UsageAttributionError( f"span {parent.span_id}: child {c.span_id} not closed before " "parent close; rollup would over-count" ) # Retries: count usage exactly once, from the exported successful attempt. retried = [c for c in parent.children if c.is_retry_attempt] if len(retried) > 1 and any(c.exported and (c.input_tokens or c.output_tokens) for c in retried): raise UsageAttributionError( f"span {parent.span_id}: multiple retry attempts carry usage; " "double-count risk" ) rollup_input = 0 rollup_output = 0 rollup_cache = 0 for c in parent.children: if not c.exported: continue if c.is_retry_attempt and (c.input_tokens or c.output_tokens): # successful retry attempt: count once rollup_input += _partitioned_input(c) rollup_output += c.output_tokens rollup_cache += c.cache_read_input_tokens elif not c.is_retry_attempt: rollup_input += _partitioned_input(c) rollup_output += c.output_tokens rollup_cache += c.cache_read_input_tokens return { "gen_ai.usage.input_tokens": rollup_input, "gen_ai.usage.output_tokens": rollup_output, "gen_ai.usage.cache_read.input_tokens": rollup_cache, "gen_ai.usage.attribution": "complete", } def close_parent_span(parent: ParentTrajectory) -> dict: """Emit rollup or degrade to partial; never emit a best-effort sum.""" try: return compute_authoritative_rollup(parent) except UsageAttributionError as e: # Degraded-accounting state: no authoritative totals, explicit reason. return { "gen_ai.usage.attribution": "partial", "gen_ai.usage.attribution_reason": str(e), } ```