How does an instance detect a broken GenAI trace link when OpenTelemetry span propagation silently drops the parent context and token accounting becomes double-counted?

**Date of Record:** 2026 December 2 **Scope:** Applies to multi-agent systems where each LLM invocation and tool call emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`), and where agent-to-agent handoffs propagate trace context via `traceparent`/`tracestate`. Does not cover single-process, single-span instrumentation without cross-agent handoff, nor non-OTel tracing backends.

Core Distinction

A GenAI span is *structurally valid* (correct attributes, well-formed IDs) yet *semantically orphaned* when its parent context is dropped at an agent boundary. The distinction that matters: **trace correctness is not the same as span correctness.** A downstream agent can emit perfectly conformant `gen_ai.chat` and `gen_ai.tool` spans — correct `gen_ai.usage.input_tokens`, correct `gen_ai.tool.name`, correct `gen_ai.operation.name` — while the `traceparent` it received was either absent, regenerated, or carried a stale `span-id`. The result is a trace that *looks* complete per-span but is *disconnected* per-trace, and token accounting that double-counts the same completion across two roots.

The invariant that breaks: **every child span's `parent_span_id` must resolve to a span that exists in the same trace, and the sum of `gen_ai.usage.output_tokens` across all spans in a trace must equal the tokens actually billed for that logical task.** Both halves fail together when propagation is lost, because the orphaned subtree is re-rooted and its tokens are counted twice — once under the original root, once under the new one.

What Was Observed

An orchestrator agent (Agent A) invokes a sub-agent (Agent B) over an HTTP-based A2A transport. Agent A emits a `gen_ai.chat` span with `trace_id=T`, `span_id=S_A`, and serializes W3C context into the outbound request headers. Agent B's runtime uses an async worker pool; the inbound request is accepted by a gateway coroutine, then dispatched to a worker. The gateway extracts `traceparent` into a context variable, but the worker pool is created with a *fresh* `Context` rather than inheriting the gateway's. Agent B's first span therefore starts with no parent: the SDK mints a new `trace_id=T'` and `span_id=S_B0`. Every subsequent span under Agent B — including its `gen_ai.tool` spans and its own nested `gen_ai.chat` calls — is correctly parented to `S_B0` but lives in trace `T'`, not `T`.

Symptoms, in the order they surface:

  1. **Two roots, one task.** The backend shows trace `T` (Agent A, terminating at the outbound call) and trace `T'` (Agent B, complete but rootless relative to A). Neither trace alone reconstructs the task.
  2. **Token double-count.** Agent A's span records `gen_ai.usage.output_tokens` for the *planning* completion that decided to call B. Agent B's span records its own completion tokens. Because the traces are separate, a naive per-trace aggregation bills both to the same logical request when the operator joins on task ID — and if the operator instead sums across *all* traces touched by the task, the shared prompt prefix (Agent A's context, re-sent to B) is counted in both `input_tokens` fields. The true cost is neither sum.
  3. **Tool-call attribution drift.** `gen_ai.tool.name` spans emitted by B appear under `T'` with no ancestry linking them to the `gen_ai.chat` span in `T` that *requested* the tool. The causal edge "A decided → B called tool X" is unrecoverable from the trace alone.
  4. **Late-arriving parent.** In some runs the gateway *did* propagate correctly but the worker's span was created before the context was attached (a race between span creation and context binding). The span lands in `T'` but a *later* span in the same worker lands in `T` — a single agent's spans split across two traces.

The failure is intermittent and load-correlated: under low concurrency the worker inherits the gateway context by accident (same thread, synchronous path); under load the pool spins up a fresh context and the link severs. This is why it passes staging and fails production.

Condition of Validity

The guardrail only holds under an explicit, checkable condition. For a GenAI trace to be trustworthy for token accounting and causal reconstruction, **all of the following must be true at span emission time**:

If any of these is unverifiable from the emitted attributes, the trace is *structurally suspect* and must not be used for billing or causal claims.

Decision Boundary

The boundary is whether the system **trusts the transport to preserve context** or **verifies context at the receiver before emitting**.

The decision boundary is crossed the moment the receiver's first span is created: after that, the damage is baked into the trace store and cannot be repaired by attribute edits, only by re-joining with a task-ID sidecar. Therefore the check must be **pre-emission and synchronous**, not a post-hoc trace validator.

Operational Effect

When the guardrail is in place, the operational consequences are concrete:

The cost is one synchronous context check per handoff — negligible against the completion it precedes, and the only point at which the invariant can still be enforced.

from dataclasses import dataclass
from typing import Optional


class TracePropagationError(RuntimeError):
    """Raised when a GenAI span would be emitted with a severed or duplicated trace link."""
    pass


@dataclass
class InboundContext:
    trace_id: Optional[str]
    parent_span_id: Optional[str]
    task_id: str


def begin_agent_span(ctx: InboundContext, is_task_root: bool) -> dict:
    """
    Guardrail executed BEFORE creating the first span in a receiving agent.

    Enforces two invariants:
      1. A non-root agent span must carry a resolvable parent in the same trace.
      2. The resulting span's trace_id must equal the inbound traceparent trace_id.
    """
    if not is_task_root:
        if not ctx.trace_id or not ctx.parent_span_id:
            raise TracePropagationError(
                f"Severed trace link for task {ctx.task_id!r}: "
                f"trace_id={ctx.trace_id!r}, parent_span_id={ctx.parent_span_id!r}. "
                "Refusing to re-root; emitting would double-count tokens and orphan tool spans."
            )

    # Simulate span creation; in production this is tracer.start_span(...)
    emitted_trace_id = ctx.trace_id or "NEWLY_MINTED"

    if not is_task_root and emitted_trace_id != ctx.trace_id:
        raise TracePropagationError(
            f"Trace ID drift on task {ctx.task_id!r}: "
            f"inbound trace_id={ctx.trace_id!r} but span would emit under {emitted_trace_id!r}. "
            "Async worker likely inherited a fresh Context instead of the gateway's."
        )

    return {
        "trace_id": emitted_trace_id,
        "parent_span_id": ctx.parent_span_id,
        "gen_ai.task.id": ctx.task_id,
        "gen_ai.task.root": is_task_root,
    }


def account_completion_tokens(
    span: dict,
    input_tokens: int,
    output_tokens: int,
    cache_read_tokens: int = 0,
    already_counted_in_task: bool = False,
) -> dict:
    """
    Enforces the token-accounting invariant: a completion's tokens are recorded
    exactly once per task. Re-sent shared prefixes must be tagged as cache reads,
    never added as fresh input_tokens.
    """
    if already_counted_in_task:
        raise TracePropagationError(
            f"Double-count guard tripped for task {span.get('gen_ai.task.id')!r}: "
            "this completion was already attributed under another span in the same task. "
            "Check for a severed trace link that caused re-rooting."
        )

    if cache_read_tokens > input_tokens:
        raise TracePropagationError(
            f"Invalid token accounting on task {span.get('gen_ai.task.id')!r}: "
            f"cache_read_tokens={cache_read_tokens} exceeds input_tokens={input_tokens}."
        )

    span["gen_ai.usage.input_tokens"] = input_tokens
    span["gen_ai.usage.output_tokens"] = output_tokens
    span["gen_ai.usage.cache_read_tokens"] = cache_read_tokens
    return span