Why does an instance of an agent span misattribute child tool-call tokens under OpenTelemetry GenAI semantic conventions when the parent span closes before the tool executor emits its usage event?

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*` attributes) where a parent `invoke_agent` span wraps one or more `execute_tool` child spans and token usage is recorded via `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to flat, single-span LLM instrumentation or to runtimes where tool spans are emitted by a separate process that shares the parent's span context by reference (remote parent) rather than in-process.

Core Distinction

The failure is not "tokens are lost." It is "tokens are attributed to the wrong span, and the attribution is silently *plausible*." Under the GenAI conventions, token usage is a span-level attribute, not an event, and the OTel SDK permits setting attributes only while a span is `RECORDING`. When an agent framework closes the parent `invoke_agent` span before a deferred tool executor finishes and reports its `gen_ai.usage.*` values, the SDK does not error — it drops the attribute set on the already-ended child span and the accounting rolls up to whatever span was active at emission time, typically the *next* sibling tool span or the enclosing agent span of the following turn. The result is a trace that sums to the correct global total but distributes it across the wrong nodes, defeating per-tool cost attribution and per-agent budget enforcement.

The boundary condition is precise: **the parent span's `end()` must not precede any child's usage-attribute emission, and the child must still be `RECORDING` when its own usage is set.** Both are violated by the common pattern of a fire-and-forget tool call whose usage is reported asynchronously.

What Was Observed

A three-tool agent turn (`search`, `fetch`, `summarize`) emitted a trace where:

The trace total matched the billing total to within 2 tokens. Only the *distribution* was wrong. The `fetch` tool executor was async: it called `span.end()` on its own span, then awaited the model-side tokenizer, then attempted `span.set_attribute("gen_ai.usage.input_tokens", n)`. The SDK accepted the call (no exception) but the span was `NOT_RECORDING`, so the attribute was discarded. Meanwhile the *next* tool span (`fetch`) had already started and was the active `Context` current span, so the delayed attribute write landed on it via the framework's ambient-span helper.

Two invariant violations compounded:

  1. **Lifecycle ordering:** child `end()` preceded attribute emission.
  2. **Ambient context leak:** the framework used `trace.get_current_span()` rather than a captured `Span` handle, so late writes targeted whichever span was current at emission time, not the originating span.

Condition of Validity

The misattribution is *observable and reproducible* only when all of the following hold:

When the tool executor is synchronous and reports usage inside the `with` block, the invariant holds trivially and the failure does not manifest. This is why unit tests with mocked synchronous tools pass while production traces drift.

Decision Boundary

The architectural guardrail is a **usage-emission contract**: every span that models a billable unit must have its `gen_ai.usage.*` attributes set *before* `end()`, and must be addressed by a captured `Span` handle, never by ambient context. Concretely:

The decision boundary is between **in-process deferred accounting** (buffer + flush before end) and **cross-process accounting** (new span + link). Mixing them — deferred in-process writes to an ended span — is the exact configuration that produces silent misattribution. Choose one; the conventions support both, but only if the lifecycle is honored.

Operational Effect

Without the guardrail, three downstream systems degrade:

  1. **Per-tool cost attribution** inverts: expensive tools appear cheap, cheap tools appear expensive, because late writes land on the next sibling. Budget alerts fire on the wrong tool.
  2. **Per-agent token budgets** computed by summing child spans remain correct in aggregate, masking the defect until a per-tool circuit breaker (e.g., "abort if `fetch` exceeds 8 K input tokens") fails to trip on the actual offending tool.
  3. **Verification replay** diverges: a replay that re-executes tools in a different completion order produces a different attribution map for identical inputs, so trace-diff regression tests are non-deterministic and get disabled.

The fix is cheap and local — capture the handle, assert recording, flush before end — but it is invisible to tests that use synchronous mocks, which is why it survives to production. The invariant to encode: *a span's usage attributes are a precondition of its termination, not a postcondition of its work.*

from opentelemetry import trace
from opentelemetry.trace import Span, Status, StatusCode


class UsageEmissionAfterEndError(RuntimeError):
    """Raised when gen_ai.usage.* attributes are written to a non-recording span."""


class ToolUsageBuffer:
    """Buffers GenAI usage for a tool span and flushes before end().

    Enforces the invariant: usage attributes are set while the span is
    RECORDING, addressed by a captured handle, never by ambient context.
    """

    def __init__(self, span: Span):
        self._span = span
        self._pending: dict[str, int] = {}
        self._flushed = False

    def record_input(self, tokens: int) -> None:
        if self._flushed:
            raise UsageEmissionAfterEndError(
                "input tokens recorded after flush; span already ended"
            )
        self._pending["gen_ai.usage.input_tokens"] = (
            self._pending.get("gen_ai.usage.input_tokens", 0) + tokens
        )

    def record_output(self, tokens: int) -> None:
        if self._flushed:
            raise UsageEmissionAfterEndError(
                "output tokens recorded after flush; span already ended"
            )
        self._pending["gen_ai.usage.output_tokens"] = (
            self._pending.get("gen_ai.usage.output_tokens", 0) + tokens
        )

    def flush_and_end(self) -> None:
        if self._flushed:
            return
        if not self._span.is_recording():
            # The span was ended elsewhere; writing now would silently drop
            # or land on the ambient current span. Refuse.
            raise UsageEmissionAfterEndError(
                f"cannot flush usage to span {self._span.get_span_context().span_id:#x}: "
                "span is not recording (ended before usage emission)"
            )
        for key, value in self._pending.items():
            self._span.set_attribute(key, value)
        self._span.set_status(Status(StatusCode.OK))
        self._flushed = True
        self._span.end()


def execute_tool(tracer: trace.Tracer, name: str, fn, *args):
    """Run a tool with usage buffered and flushed before span end."""
    with tracer.start_as_current_span(f"execute_tool {name}") as span:
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", name)
        buffer = ToolUsageBuffer(span)
        try:
            result, input_tokens, output_tokens = fn(*args)
            buffer.record_input(input_tokens)
            buffer.record_output(output_tokens)
        except Exception as exc:
            span.record_exception(exc)
            span.set_status(Status(StatusCode.ERROR, str(exc)))
            raise
        finally:
            # Flush inside the `with` block, while span is still RECORDING.
            buffer.flush_and_end()
        return result