# Why does an instance lose tool-call lineage when OpenTelemetry GenAI span attributes cross an async agent handoff? **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the `gen_ai.*` semantic conventions (operation name, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`, `gen_ai.request.model`) and that propagate context across asynchronous or deferred tool-call boundaries (queue-based executors, MCP servers, sub-agent delegation). Does not apply to single-process, synchronous, single-span chains where the LLM call and tool execution share one uninterrupted `Context`. ## Core Distinction The failure is not "missing telemetry." It is **attribute-level lineage breakage under context detachment**. OpenTelemetry's `gen_ai` conventions assume that a tool-call span is a *child* of the LLM span that emitted the call, so that `gen_ai.tool.name`, `gen_ai.tool.call.id`, and the parent's `gen_ai.usage.*` token counters can be read together as one coherent record. That assumption holds only while the active `Context` carries the parent `SpanContext`. When an agent defers a tool call — serializes the call into a queue payload, hands it to a remote MCP server, or spawns a sub-agent — the child span is created in a *fresh* context. The tool span is still exported, still valid, and still attributed to the right trace **if** the trace ID was manually re-injected. But the parent-child *link* and the inherited `gen_ai` attributes are severed. The result is a span that looks healthy in isolation and is unlinkable in aggregate. The non-obvious part: token accounting does **not** fail at the point of export. It fails at the point of *reconstruction*. Each span reports its own `gen_ai.usage.input_tokens`, and the collector faithfully sums them. But the tool-call span, detached from its parent, cannot be attributed to the LLM invocation whose prompt produced it. Cost-per-tool-call silently collapses to zero or double-counts, depending on whether the backend joins on `trace_id` alone or on parent span ID. ## What Was Observed A sub-agent delegation flow produced the following trace shape after a deferred tool call: - Parent span `S_llm` (kind=CLIENT, `gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=8412`, `gen_ai.usage.output_tokens=203`) closes normally and exports. - The agent serializes a tool call `{name: "search_docs", call_id: "call_7f3a"}` into a job payload. The payload carries `trace_id` but **not** the parent `span_id` and **not** the propagated `gen_ai.request.model`. - A worker dequeues the job, starts a new root `Context` (no remote parent), and emits `S_tool` (kind=INTERNAL, `gen_ai.tool.name=search_docs`, `gen_ai.tool.call.id=call_7f3a`) as its own trace root — or, worse, as a child of an unrelated worker span. - `S_tool` carries no `gen_ai.usage.*` (correct — tools don't consume LLM tokens) but also no pointer to `S_llm`. Observed downstream effects across three collector configurations: 1. **Join on `trace_id` only:** `S_tool` is orphaned into a separate trace because the worker's `trace_id` differs. Tool-call count per LLM invocation = 0. The agent looks like it reasoned without acting. 2. **Manual `trace_id` re-injection, no `span_id`:** `S_tool` lands in the correct trace but as a *sibling* of `S_llm`, not a child. Cost attribution by parent span ID attributes `search_docs` to no LLM call. Token totals are correct at trace level, wrong at operation level. 3. **Re-injection with stale model attribute:** The worker copied `gen_ai.request.model` from a *previous* job (a shared mutable payload struct), so `S_tool` reports `gpt-4o` while `S_llm` reports `claude-3-5-sonnet`. Model-level dashboards now show tool calls for a model that never invoked them. In all three, no span was dropped, no exporter error was raised, and every span passed schema validation. The breakage was purely relational and only detectable by a join that expected a parent-child edge. ## Condition of Validity The `gen_ai` tool-call lineage invariant holds **if and only if** the tool span's `SpanContext` is created with the LLM span as its explicit parent, and all inherited `gen_ai.*` attributes that the convention treats as ambient (`gen_ai.request.model`, `gen_ai.system`, `gen_ai.conversation.id`) are carried in the handoff payload rather than read from process-global state. This validity condition fails under any of: - **Context detachment** — the tool call crosses a process, queue, or `await` boundary where the active `Context` is not propagated (missing `traceparent`/`tracestate` in the payload, or a worker that calls `start_as_current_span` without `context=`). - **Ambient-state inheritance** — the worker reads `gen_ai.request.model` from a mutable struct or thread-local instead of the payload, so concurrent jobs cross-contaminate. - **Partial propagation** — `trace_id` is forwarded but `span_id` is not, producing sibling spans that pass validation but break parent-based joins. It does **not** fail (and this article does not apply) when the LLM call and tool execution are synchronous within one `Context`, or when the backend joins strictly on `gen_ai.tool.call.id` and the call ID is propagated intact. ## Decision Boundary The boundary is **whether the handoff payload is treated as the sole source of `gen_ai` ambient attributes, or whether the receiving context is allowed to reconstruct them from local state.** - If the payload carries `traceparent` (full `SpanContext`, including `span_id`) **and** a frozen snapshot of `gen_ai.request.model` / `gen_ai.system` / `gen_ai.conversation.id`, the tool span is a valid child and token accounting reconstructs correctly. Proceed. - If the payload carries only `trace_id`, or omits the ambient attributes, the tool span is structurally orphaned. **Do not export it as a tool-call span** — either attach it via an explicit `Link` to the LLM span (and mark the backend join accordingly) or reject the handoff at the boundary. - If the worker reads any `gen_ai.*` ambient attribute from anything other than the payload, treat the span as untrustworthy and quarantine it before export. The invariant to enforce: *a `gen_ai` tool-call span must have exactly one parent `gen_ai` LLM span, and every ambient `gen_ai.*` attribute on it must originate from the handoff payload, not from worker-local state.* Violating either clause yields a span that validates but cannot be joined. ## Operational Effect The consequence is **silent cost and behavior misattribution, not telemetry loss**. Because every span is individually well-formed, standard schema validators and exporter health checks pass. The corruption surfaces only in aggregate queries: cost-per-invocation drops, tool-call-per-reasoning-step ratios go to zero, and model-level breakdowns split a single logical operation across phantom models. An auditor replaying the trace to verify "did the agent actually call the tool it claimed?" gets an ambiguous answer — the call exists but is unattributable. The guardrail is a handoff-time assertion, not a collector-time repair. Enforce it where the deferred call is serialized: require `traceparent` with a non-null `span_id`, require a frozen ambient-attribute snapshot, and refuse to enqueue a job whose tool-call payload cannot reconstruct its parent. Reconstructing lineage after export is unreliable because the parent `SpanContext` is gone and only heuristic joins remain. ```python import re from dataclasses import dataclass, field from typing import Optional TRACEPARENT_RE = re.compile( r"^(?P[0-9a-f]{2})-(?P[0-9a-f]{32})-(?P[0-9a-f]{16})-(?P[0-9a-f]{2})$" ) AMBIENT_GENAI_ATTRS = ("gen_ai.request.model", "gen_ai.system", "gen_ai.conversation.id") class GenAiLineageError(RuntimeError): """Raised when a deferred tool-call handoff cannot reconstruct its parent gen_ai span.""" @dataclass class ToolCallHandoff: tool_name: str call_id: str traceparent: Optional[str] ambient_attrs: dict = field(default_factory=dict) def build_tool_span_context(handoff: ToolCallHandoff, worker_local_model: str) -> dict: """Validate a deferred gen_ai tool-call handoff before span creation. Returns the attributes to stamp on the tool span, or raises if lineage cannot be reconstructed from the payload alone. """ if not handoff.traceparent: raise GenAiLineageError( f"tool call {handoff.call_id!r} has no traceparent; " "span would be orphaned from its parent gen_ai LLM span" ) match = TRACEPARENT_RE.match(handoff.traceparent) if not match: raise GenAiLineageError( f"malformed traceparent for tool call {handoff.call_id!r}: {handoff.traceparent!r}" ) # span_id == all-zero means the parent was explicitly invalidated; a tool # call cannot have an invalid parent and still be a valid child. if match.group("span_id") == "0" * 16: raise GenAiLineageError( f"tool call {handoff.call_id!r} has a null parent span_id; " "cannot establish gen_ai parent-child edge" ) missing = [a for a in AMBIENT_GENAI_ATTRS if a not in handoff.ambient_attrs] if missing: raise GenAiLineageError( f"tool call {handoff.call_id!r} missing ambient gen_ai attributes {missing}; " "worker-local state must not be used to fill them" ) # Guard against ambient-state contamination: the payload's model must be # the authority, and any worker-local model is ignored by construction. payload_model = handoff.ambient_attrs["gen_ai.request.model"] if payload_model != worker_local_model: # Not fatal on its own, but the divergence must be recorded, not # silently resolved in favor of the worker's mutable state. handoff.ambient_attrs["gen_ai.lineage.model_divergence"] = worker_local_model return { "trace_id": match.group("trace_id"), "parent_span_id": match.group("span_id"), "gen_ai.tool.name": handoff.tool_name, "gen_ai.tool.call.id": handoff.call_id, **handoff.ambient_attrs, } ```