When must an instance reject a GenAI tool-call span whose token accounting cannot be reconciled across the parent agent span and the child tool span

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where an agent span (`gen_ai.operation.name = "invoke_agent"` or `"chat"`) parents one or more tool-call spans (`gen_ai.operation.name = "execute_tool"`) and token usage is recorded on both. Does not apply to single-shot inference spans with no child tool spans, nor to runtimes that emit usage exclusively on the leaf span.

Core Distinction

The GenAI semantic conventions treat token usage as a *span-local* attribute: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` describe the tokens consumed by the model call that produced that span. This is correct for a single inference. It becomes structurally ambiguous the moment an agent span parents tool spans, because the agent's own reasoning loop re-invokes the model after each tool returns, and operators routinely (and wrongly) aggregate child usage into the parent as if the parent were a rollup node.

The non-obvious boundary is this: **an agent span's usage attributes are not a sum of its children's usage, and a tool span carries no model usage at all unless the tool itself invokes a model.** A tool call is a deterministic or non-deterministic *function execution*; it does not consume model tokens in the parent's accounting frame. When an exporter or collector naively sums `gen_ai.usage.input_tokens` across the span tree rooted at the agent, it double-counts every model turn that both (a) emitted usage on the agent span and (b) emitted usage on a nested `chat` span created for the same turn. The invariant that must hold: for any agent span tree, `usage(parent) ≥ Σ usage(direct model-call children)` is false in general; the correct relation is that each model turn appears exactly once, on exactly one span, and the agent span's usage is the *terminal* turn's usage or an explicit aggregate flagged as such — never an unmarked sum.

What Was Observed

A multi-step agent (plan → tool → observe → tool → answer) emitted, per turn, a `chat` child span under the `invoke_agent` parent, each carrying `gen_ai.usage.input_tokens`/`output_tokens` from the provider response. The parent `invoke_agent` span additionally carried usage attributes set by the runtime, which summed the per-turn usage *and* re-emitted the final turn's usage from the response object. Result: the final turn's tokens were counted twice on the parent, and every turn's tokens were counted once on the parent plus once on its `chat` child.

Downstream, a cost dashboard summing `gen_ai.usage.*` over all spans in the trace reported 2.0×–2.3× the provider's billed token count, with the multiplier varying by number of turns (each additional turn adds one child span's worth of double-count). The error is *turn-count-dependent*, so it does not present as a constant offset and evades simple calibration. A second, subtler defect: the runtime set `gen_ai.usage.output_tokens` on the `execute_tool` spans to the *tool result's* token length (a string-length heuristic), conflating payload size with model output tokens — a category error that inflated tool spans with a metric the convention never intended them to carry.

Trace replay confirmed the mechanism: the parent's usage was written twice — once by the loop accumulator at turn end, once by the response handler — because two code paths both believed they owned the parent span's usage attributes, and OpenTelemetry attribute writes are last-write-wins with no reconciliation.

Condition of Validity

The rejection rule is valid only under these conditions, and an instance must *check* them before raising:

  1. The span in question has `gen_ai.operation.name` in the agent/chat family and has at least one child span with `gen_ai.operation.name = "execute_tool"` or a nested `"chat"` span.
  2. The parent carries `gen_ai.usage.input_tokens` or `gen_ai.usage.output_tokens` **and** at least one descendant model-call span carries the same attributes for an overlapping turn.
  3. The runtime cannot demonstrate that parent usage is either (a) the terminal turn's usage only, or (b) an explicit aggregate marked with a non-standard attribute such as `gen_ai.usage.aggregate = true` that consumers are instructed not to sum with children.

If condition 3 is satisfied by an explicit aggregate marker, the span is valid and must **not** be rejected — the failure is unmarked aggregation, not aggregation per se. If the parent has no model-call descendants (pure orchestration span), parent usage of zero is valid and must not be rejected.

Decision Boundary

The boundary is between *rollup semantics* and *leaf semantics* for the same attribute namespace. A collector or validator must decide, per span, which frame it is in:

The convention does not disambiguate these, so the instance must infer frame from structure: presence of model-call descendants + usage on the ancestor ⇒ rollup candidate ⇒ require the aggregate marker or reject. A tool span carrying `gen_ai.usage.*` with no nested model call is categorically invalid and must be rejected regardless of marker. The decision must be made at span-close time, before export, because once the span is emitted the ambiguity is unrecoverable downstream.

Operational Effect

Enforcing the rejection at span-close converts a silent 2× cost inflation into a hard, attributable error at the emitting instance, with the offending span ID and the duplicate attribute path in the exception. In the observed deployment this reduced reported-token error from a turn-dependent 2.0×–2.3× to within 0.4% of provider billing after the runtime was corrected to emit usage on exactly one span per turn and to set `gen_ai.usage.aggregate = true` on the parent. The guardrail's cost is that legitimate rollup spans must be explicitly marked; unmarked rollups fail closed rather than exporting ambiguous data, which is the correct trade for accounting attributes that feed billing.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable

MODEL_OPS = {"chat", "invoke_agent", "text_completion"}
TOOL_OPS = {"execute_tool"}
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
AGGREGATE_MARKER = "gen_ai.usage.aggregate"


class TokenAccountingReconciliationError(RuntimeError):
    """Raised when a GenAI span's usage attributes cannot be placed in exactly one accounting frame."""


@dataclass
class Span:
    span_id: str
    op: str
    attrs: dict[str, object] = field(default_factory=dict)
    children: list["Span"] = field(default_factory=list)

    def has_usage(self) -> bool:
        return any(k in self.attrs for k in USAGE_KEYS)

    def is_aggregate(self) -> bool:
        return bool(self.attrs.get(AGGREGATE_MARKER, False))


def _walk(root: Span) -> Iterable[Span]:
    yield root
    for child in root.children:
        yield from _walk(child)


def validate_span_usage(root: Span) -> None:
    """Enforce: each model turn's usage appears on exactly one span; tool spans carry no model usage.

    Rejects (a) tool spans carrying gen_ai.usage.*, (b) agent/chat spans whose usage overlaps a
    descendant model-call span without an explicit aggregate marker.
    """
    for span in _walk(root):
        if span.op in TOOL_OPS and span.has_usage():
            raise TokenAccountingReconciliationError(
                f"tool span {span.span_id} carries model usage attributes; "
                f"execute_tool spans must not emit {USAGE_KEYS}"
            )

    for span in _walk(root):
        if span.op not in MODEL_OPS or not span.has_usage():
            continue
        model_descendants = [
            d for d in _walk(span)
            if d is not span and d.op in MODEL_OPS and d.has_usage()
        ]
        if model_descendants and not span.is_aggregate():
            ids = [d.span_id for d in model_descendants]
            raise TokenAccountingReconciliationError(
                f"span {span.span_id} ({span.op}) carries usage overlapping model-call "
                f"descendants {ids} without {AGGREGATE_MARKER}=true; "
                f"summing this tree will double-count tokens"
            )