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:
- **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.
- **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.
- **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.
- **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**:
- The span's `parent_span_id` is non-empty and resolves to an existing span in the same `trace_id`, *or* the span is the single declared root of the task (flagged via a `gen_ai.task.root=true` attribute or equivalent).
- The `trace_id` of every span in a handoff chain is identical, and the chain's root span carries the task's canonical cost.
- `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are recorded **once per completion**, not once per agent that observed the completion. Re-sent context (Agent A's prompt replayed into B) must be tagged as `gen_ai.usage.cache_read_tokens` or excluded from the task total, never added as fresh `input_tokens`.
- Tool spans carry a `gen_ai.tool.call.id` that matches the `tool_call_id` in the requesting `gen_ai.chat` span's output, enabling the causal edge to be rebuilt even if parenting is lost.
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**.
- **Trust-the-transport (fails here):** the receiver assumes `traceparent` was attached and that the SDK will parent correctly. Under async dispatch, thread-pool reuse, or message-queue hops, this assumption silently breaks. The failure is invisible because every span is individually valid.
- **Verify-at-receiver (the guardrail):** the receiver, before creating its first span, checks that the extracted context is non-empty and that the resulting span's `trace_id` equals the inbound `traceparent`'s trace ID. If the check fails, it either (a) refuses to emit and raises, or (b) emits a span explicitly marked `gen_ai.propagation.status=broken` with the intended parent recorded as an attribute, so the edge is recoverable offline.
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:
- **Token accounting becomes additive and correct.** Because the task root is single and shared-prefix tokens are tagged as cache reads, the sum over the task's trace equals the bill. The double-count disappears.
- **Causal reconstruction survives propagation loss.** Even when a handoff severs the link, the `gen_ai.tool.call.id` and the recorded intended-parent attribute let an offline joiner rebuild the edge. The trace is degraded, not lost.
- **Failure becomes loud and local.** A broken propagation raises at the receiver, in the agent that would have orphaned, rather than surfacing weeks later as a billing discrepancy or an unexplainable latency attribution in a postmortem.
- **Latency attribution stays honest.** Span durations only aggregate correctly within a single trace; a severed link makes a sub-agent's 4-second tool call invisible to the orchestrator's SLA calculation. Verifying at the receiver keeps the duration tree intact.
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