Under what conditions must an instance refuse to close a GenAI agent span whose tool-call children were emitted by a different tracer provider than the parent

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) where tool invocations may be instrumented by a separately-initialized `TracerProvider` (vendor SDK, sidecar collector, or subprocess worker). Does not apply to single-provider, single-process agents where parent and child share one global provider by construction.

Core Distinction

The GenAI semantic conventions define a *schema* for attributes (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, etc.) but they do **not** define a *closure contract*: the invariant that a parent `invoke_agent` span may only be ended after every `execute_tool` child it logically spawned has been ended, and that the token accounting on the parent reflects the sum of children. This is left to the SDK's `SpanProcessor` lifecycle.

The failure mode is not "missing spans." It is **orphaned accounting**: a parent agent span that ends, flushes, and is exported with `gen_ai.usage.output_tokens` set to the LLM's final completion count, while a tool-call child span — emitted through a *different* provider — is still open, has not yet recorded its own `gen_ai.usage` attributes, and will later be exported as a root span under a fresh `trace_id` because its parent `SpanContext` was never propagated across the provider boundary. The result is a trace that *looks* complete (parent has a status, has token counts, has a duration) but silently under-reports cost and loses the causal edge between the agent decision and the tool effect.

The distinction that matters: **a span is not closed when it is ended; it is closed when its accounting is reconciled.** The OTel SDK conflates these. The GenAI conventions assume them equal. They are not equal across provider boundaries.

What Was Observed

A two-hop agent (planner → executor) using the Anthropic SDK instrumented via `opentelemetry-instrumentation-anthropic` (provider A, initialized in-process) delegating tool execution to a sandboxed Python worker instrumented via a separately-installed `opentelemetry-sdk` (provider B, initialized in the child process, configured to export to the same collector endpoint).

Trace sequence observed at the collector:

  1. `invoke_agent` span `A` (provider A) opens. `gen_ai.operation.name=invoke_agent`, `gen_ai.request.model=claude-...`.
  2. `chat` span `A.1` (provider A) opens and closes around the LLM call. `gen_ai.usage.input_tokens=4820`, `gen_ai.usage.output_tokens=310`. Closes cleanly.
  3. Agent decides to call `execute_sql`. It sends the tool request to the worker over a pipe and **awaits the result**.
  4. Worker (provider B) opens `execute_tool` span `B.1`. Because `TraceContext` propagation was configured only on the parent's HTTP egress, not on the pipe's JSON envelope, `B.1` has **no parent**. It becomes a root span with its own `trace_id`.
  5. Worker returns the tool result. Parent receives it.
  6. Parent issues a second `chat` span `A.2` with `gen_ai.usage.input_tokens=5100`, `gen_ai.usage.output_tokens=140`.
  7. Parent ends `invoke_agent` span `A`. Exported with `gen_ai.usage.output_tokens=140` — the *last call's* count, not the sum, because the runtime attributed usage to the span that was open at the moment of measurement, not the agent span.
  8. `B.1` flushes ~40ms later to the same collector under a different `trace_id`.

Downstream cost dashboards summed `gen_ai.usage.output_tokens` over `invoke_agent` spans and reported ~31% of actual spend. The gap was not random: it was exactly the tokens consumed in tool-result ingestion rounds, which by construction occur *after* the first `chat` span closes and *before* the agent span closes, so they were attributed to neither.

A second, subtler artifact: `B.1` carried `gen_ai.tool.name=execute_sql` and `gen_ai.tool.call.id` matching the parent's request, but no `gen_ai.agent.id` or parent linkage. An auditor replaying the trace could not prove the tool call belonged to agent `A` rather than to an unrelated concurrent agent — the `tool.call.id` is a UUID that the parent also holds, but the convention does not require the parent to record it as an attribute, only to *use* it in the protocol. So the correlation key existed in the wire protocol and was dropped at the telemetry boundary.

Condition of Validity

The naive "end the span and let the exporter sort it out" behavior is only valid under a conjunction of conditions that are rarely all true in agent systems:

  1. **Single provider.** Parent and all logically-child spans are created by the same `TracerProvider` instance, so `SpanContext` propagation is in-process and cannot be dropped by a serialization boundary.
  2. **Synchronous child completion.** Every tool call completes before the agent span's `end()` is invoked. True for sequential ReAct; false for any agent that fires tool calls speculatively, in parallel, or in a detached worker whose result is consumed on a later turn.
  3. **Usage attribution at the agent span.** The runtime must accumulate `gen_ai.usage.*` onto the *agent* span, not only onto per-call `chat` spans. The conventions permit either; only the former makes the parent self-describing.
  4. **Propagation across every transport.** `traceparent` must be injected into the tool-call envelope (pipe, queue message, subprocess argv, MCP `_meta`), not merely into HTTP headers. Agent runtimes routinely instrument HTTP and forget stdio/pipes/MCP.
  5. **Collector-side reconciliation is possible.** Either the parent records `gen_ai.tool.call.id` as an attribute, or the collector correlates by session. Absent both, orphaned children are unrecoverable.

When any one condition fails, the span's ended state is a *lie about closure*. The trace is structurally incomplete in a way the schema cannot express, because the schema has no `gen_ai.pending_children` or `gen_ai.accounting.reconciled` attribute to mark the gap.

Decision Boundary

The boundary is this: **an agent span may be ended only when (a) every tool-call it initiated has returned a terminal result or been explicitly abandoned, and (b) the accumulated `gen_ai.usage.*` on the span equals the sum of usage recorded on its `chat` children plus any usage the tool layer reported.**

If the runtime cannot establish (a) — because a tool call was dispatched to a worker whose completion it does not synchronously observe — it must not end the span. It must either:

The decision boundary is *not* "did the tool succeed." A failed tool call that returned an error is fully reconciled — it has a terminal result. The boundary is "do we have a terminal observation of every child we spawned." A timeout is not a terminal observation; it is an absence of one, and must be recorded as such.

The second half of the boundary concerns attribution. If the runtime ends the span with `gen_ai.usage.output_tokens` equal only to the last `chat` call, it has violated the invariant that the agent span's usage is the *aggregate*. The correct behavior is to sum across all `chat` children at `end()` time — which requires the runtime to buffer per-call usage on the agent span rather than emitting it only on the leaf. If the runtime cannot buffer (e.g., it streams and discards), it must set `gen_ai.usage.output_tokens` to the *maximum observed*, not the last observed, and mark the span degraded. Last-write-wins is the specific bug: it is silent, plausible-looking, and under-reports by exactly the number of turns.

Operational Effect

The practical consequence is that **token-accounting dashboards built on `invoke_agent` spans are systematically low for any agent that makes more than one LLM call per span**, and the deficit scales with turn count, not with model or workload. The bias is not noise; it is a deterministic function of the agent's control-flow shape. Agents that do tool-result ingestion (the majority) under-report; agents that make one call and stop (rare) do not. This makes cross-agent cost comparison invalid: a single-call classifier and a ten-turn ReAct agent will appear to have similar per-span costs even when the latter is 10× more expensive.

The second effect is **audit unrecoverability**. Because the orphaned tool span lands under a different `trace_id`, no amount of collector-side joining recovers the causal edge unless the parent recorded `gen_ai.tool.call.id`. The GenAI conventions define this attribute but do not require it on the parent, only on the tool span. An auditor cannot prove that tool call `X` was executed on behalf of agent `A` rather than agent `B` running concurrently in the same fleet. In a multi-tenant system this is a compliance gap, not just an observability gap.

The guardrail is a **closure barrier** at the runtime layer: the agent's `end_span` path must consult a per-span child registry, refuse to end while any child is `PENDING`, and on deadline expiry end in `ERROR` with an explicit `pending.count`. The registry must be keyed by `gen_ai.tool.call.id` and populated at dispatch time, not at completion time — otherwise a child that never completes is invisible. And the tool-call envelope, whatever its transport (pipe, queue, MCP `_meta`, subprocess env), must carry `traceparent` and `tracestate`; the propagation layer, not the instrumentation layer, is where this belongs, because instrumentation is per-SDK and propagation is per-transport, and it is the transport that is forgotten.

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class UnreconciledToolChildrenError(RuntimeError):
    """Raised when an agent span is asked to end while tool-call children
    it dispatched have not produced a terminal observation."""


@dataclass
class ToolCallRecord:
    call_id: str
    dispatched_at: float
    terminal: bool = False
    usage_output_tokens: int = 0


@dataclass
class AgentSpanClosureBarrier:
    span_id: str
    deadline_s: float = 30.0
    children: Dict[str, ToolCallRecord] = field(default_factory=dict)
    accumulated_output_tokens: int = 0
    last_call_output_tokens: int = 0

    def dispatch_tool(self, call_id: str) -> None:
        self.children[call_id] = ToolCallRecord(
            call_id=call_id, dispatched_at=time.monotonic()
        )

    def observe_tool_completion(self, call_id: str, output_tokens: int) -> None:
        rec = self.children.get(call_id)
        if rec is None:
            raise UnreconciledToolChildrenError(
                f"completion for unknown tool call {call_id!r} on span {self.span_id!r}"
            )
        rec.terminal = True
        rec.usage_output_tokens = output_tokens
        self.accumulated_output_tokens += output_tokens

    def record_chat_usage(self, output_tokens: int) -> None:
        # Buffer on the agent span; do NOT rely on last-write-wins.
        self.accumulated_output_tokens += output_tokens
        self.last_call_output_tokens = output_tokens

    def end_span(self) -> dict:
        now = time.monotonic()
        pending = [c for c in self.children.values() if not c.terminal]
        if pending:
            expired = [c for c in pending if now - c.dispatched_at > self.deadline_s]
            if expired:
                # Cannot reconcile: end degraded, do not silently drop.
                return {
                    "otel.status_code": "ERROR",
                    "otel.status_description": "unreconciled_tool_children",
                    "gen_ai.tool.pending.count": len(pending),
                    "gen_ai.usage.output_tokens": self.accumulated_output_tokens,
                    "gen_ai.usage.output_tokens.lower_bound": True,
                }
            raise UnreconciledToolChildrenError(
                f"span {self.span_id!r} has {len(pending)} pending tool children "
                f"within deadline; cannot end"
            )
        return {
            "otel.status_code": "OK",
            "gen_ai.usage.output_tokens": self.accumulated_output_tokens,
        }