# In what scenarios must an instance refuse to finalize a GenAI span when its `gen_ai.usage.*` token totals disagrees with the sum of child tool-call spans **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for a parent reasoning turn and one or more child tool-call spans, where token accounting is aggregated across the turn. Does not apply to single-shot, tool-free completions, nor to spans emitted by a shared collector that recomputes usage downstream. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes of a single inference call span*. When an agent executes a multi-step reasoning loop — one LLM turn that fans out into N tool calls, each of which may itself trigger a nested LLM turn — the runtime faces a choice that the spec does not resolve: - **Attribution accounting:** the parent span records only the tokens of *its own* completion; child spans record theirs. - **Aggregate accounting:** the parent span records the *sum* of all descendant token usage, so a single span answers "what did this turn cost?" Both are defensible. The failure mode is that a runtime can silently do *both* — write aggregate totals onto the parent while also emitting children with their own totals — and downstream cost dashboards then double-count. Worse, when a child span is dropped (sampling, exporter backpressure, span-limit eviction), the parent's aggregate total no longer reconciles with the observable children, and the lineage graph becomes *arithmetically inconsistent*: `parent.usage ≠ Σ(child.usage) + orphaned_usage`. That inconsistency is the boundary. It is not a metrics bug; it is a loss of the invariant that makes the trace tree a trustworthy ledger. ## What Was Observed During a 14-hour soak of a ReAct-style agent (parent turn → up to 7 parallel tool calls, each tool wrapping its own 1–2 LLM sub-calls), the following trace was captured: - Parent span `gen_ai.usage.input_tokens = 48,912`, `output_tokens = 6,103`. - Six child tool-call spans present, each with their own `gen_ai.usage.*`. - The seventh child span was absent — evicted by the SDK's `max_span_attributes`/span-count limit under peak fan-out, and *not* marked as dropped. - Sum of the six surviving children: `input = 41,004`, `output = 5,220`. - Residual: `7,908` input / `883` output tokens attributed to the parent but to no observable child. The parent's `gen_ai.operation.name = "chat"` and its aggregate totals made it look like a single inference call that consumed 48k input tokens — impossible for a model with a 32k context window. A cost-attribution job flagged it as a context-window overrun and paged on-call. The actual cause was an aggregate total masquerading as a single-call attribute, minus one evicted child. A second, subtler observation: when the runtime *retried* a failed tool call (transient 503 from a downstream tool), the retried child span carried a fresh `gen_ai.usage.*`, but the parent's aggregate was computed *before* the retry landed and was never reconciled. The parent total was therefore *lower* than the sum of children — the opposite direction of error, and one that a naive `parent ≥ Σchildren` sanity check would not catch. ## Condition of Validity The reconciliation invariant holds only under three jointly satisfied conditions: 1. **Single accounting mode per trace.** The runtime must commit, at span-creation time, to either attribution or aggregate mode, and record that choice in a span attribute (e.g., `gen_ai.usage.aggregation = "self" | "subtree"`). Mixing modes across a trace is the root cause; the invariant cannot be checked without knowing which mode is in force. 2. **Child completeness is observable.** Every child span that contributed to the parent's aggregate must be either present in the exported trace *or* explicitly counted in a `gen_ai.usage.dropped_spans` / `gen_ai.usage.unattributed_tokens` attribute. Eviction without a tombstone is the silent failure. 3. **Aggregate is finalized after children.** The parent's `usage.*` attributes must be set on `span.end()`, after all children have ended (or been marked dropped). Setting them at completion-of-own-completion, before tools return, is what produces the retry-mismatch direction of error. If any condition is unmet, the parent's `gen_ai.usage.*` is not a valid ledger entry and must not be consumed by cost or capacity systems. ## Decision Boundary The boundary is a single predicate evaluated at `span.end()` of the parent turn span: ``` finalize_ok ⟺ mode == "self" ∨ ( mode == "subtree" ∧ parent.input == Σ(children.input) + unattributed.input ∧ parent.output == Σ(children.output) + unattributed.output ∧ dropped_spans == 0 ∨ unattributed explicitly set ) ``` When `finalize_ok` is false, the runtime has two legal moves and one illegal one: - **Legal — degrade to attribution:** rewrite the parent's `gen_ai.usage.*` to its own-completion-only values and set `gen_ai.usage.aggregation = "self"`. The trace remains internally consistent; the aggregate is lost but the ledger is sound. - **Legal — seal with tombstone:** keep the aggregate, set `gen_ai.usage.unattributed.input_tokens` / `.output_tokens` to the residual, and set `gen_ai.usage.aggregation = "subtree"`. Downstream consumers can now reconcile `parent = Σchildren + unattributed` exactly. - **Illegal — export as-is:** emit the aggregate total with no mode marker and no tombstone. This is the observed failure. It produces a span that is *plausible* per-attribute and *false* in aggregate, which is the worst class of telemetry defect because it passes schema validation. The illegal move is what most SDKs do by default, because the GenAI conventions define `gen_ai.usage.*` as per-call attributes and say nothing about multi-span aggregation. The spec's silence is the gap; the runtime must close it. ## Operational Effect Concretely, a runtime that enforces `finalize_ok` at parent `span.end()` gains three properties: 1. **Cost dashboards stop double-counting.** Aggregate-mode parents are marked, so the cost job sums *either* subtree roots *or* leaves, never both. 2. **Context-window alarms stop false-firing.** A `chat` span with `input_tokens > model_context_window` becomes a hard signal of a mislabeled aggregate, not a spurious overrun page. 3. **Retry accounting is exact.** Because the parent total is finalized after children end, a retried child's usage is included in the residual and surfaced via `unattributed.*` rather than silently lost or double-added. The cost is one comparison per parent span end and one new attribute pair. The failure it prevents — a trace tree whose arithmetic does not close — is not recoverable downstream, because the orphaned tokens have no span to attach to once the trace is exported. ```python from dataclasses import dataclass, field from typing import Literal class SpanUsageReconciliationError(RuntimeError): """Raised when a parent GenAI span's aggregate usage cannot be reconciled against its observable child spans at finalize time.""" @dataclass class Usage: input_tokens: int = 0 output_tokens: int = 0 def __add__(self, other: "Usage") -> "Usage": return Usage(self.input_tokens + other.input_tokens, self.output_tokens + other.output_tokens) @dataclass class GenAISpan: name: str usage: Usage = field(default_factory=Usage) aggregation: Literal["self", "subtree"] = "self" unattributed: Usage | None = None dropped_spans: int = 0 children: list["GenAISpan"] = field(default_factory=list) def finalize_parent(parent: GenAISpan, *, strict: bool = True) -> None: """Enforce the finalize_ok invariant on a parent turn span. Legal outcomes: - aggregation == 'self': nothing to reconcile. - aggregation == 'subtree' with exact reconciliation, or with an explicit unattributed tombstone covering the residual. Illegal outcome (raises): - aggregation == 'subtree' whose totals do not close against children and no tombstone was set. """ if parent.aggregation == "self": return child_total = Usage() for c in parent.children: child_total = child_total + c.usage residual_in = parent.usage.input_tokens - child_total.input_tokens residual_out = parent.usage.output_tokens - child_total.output_tokens if residual_in == 0 and residual_out == 0 and parent.dropped_spans == 0: return if parent.unattributed is not None: if (parent.unattributed.input_tokens == residual_in and parent.unattributed.output_tokens == residual_out): return raise SpanUsageReconciliationError( f"span {parent.name!r}: unattributed tombstone " f"({parent.unattributed.input_tokens},{parent.unattributed.output_tokens}) " f"does not match residual ({residual_in},{residual_out}); " f"tombstone was set before all children ended" ) if not strict: # degrade to attribution mode parent.aggregation = "self" return raise SpanUsageReconciliationError( f"span {parent.name!r}: subtree aggregate " f"({parent.usage.input_tokens},{parent.usage.output_tokens}) " f"does not reconcile with {len(parent.children)} children " f"({child_total.input_tokens},{child_total.output_tokens}); " f"residual ({residual_in},{residual_out}), " f"dropped_spans={parent.dropped_spans}. " f"Set gen_ai.usage.unattributed.* or degrade to aggregation='self'." ) # --- reproduction of the observed failure --- parent = GenAISpan( name="agent.turn", usage=Usage(input_tokens=48_912, output_tokens=6_103), aggregation="subtree", ) for i in range(6): parent.children.append(GenAISpan( name=f"tool.call[{i}]", usage=Usage(input_tokens=6_834, output_tokens=870), )) # seventh child evicted; dropped_spans never incremented — the silent case finalize_parent(parent) # raises SpanUsageReconciliationError ```