# What happens when an instance emits tool-call spans that satisfy OpenTelemetry GenAI semantic conventions but lose causal linkage across an async handoff **Date of Record:** 2026 November 20 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where tool calls execute asynchronously and the span is closed by a different coroutine/thread than the one that opened it. Does not apply to synchronous, single-threaded tool invocation where parent-child span context is established and closed within the same execution frame. ## Core Distinction There are two kinds of "trace correctness" that get conflated during instrumentation review. The first is **attribute conformance**: does the span carry the required `gen_ai.system`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, and token-usage attributes in the shape the convention specifies? The second is **causal linkage**: does the span's `trace_id` / `parent_span_id` chain actually reconstruct the reasoning path that produced the tool call, in the order the agent reasoned it? Convention validators check the first. They do not check the second. A span can be 100% spec-compliant on attributes and still be causally orphaned — reparented to the wrong parent, emitted under a fresh trace root, or ordered incorrectly relative to the reasoning step that authorized the call. The failure is invisible to schema validation and only surfaces when a downstream auditor tries to replay the decision sequence. ## What Was Observed A planner agent emits a `gen_ai.chat` span for the reasoning turn that selects a tool. It then dispatches the tool call to an async executor (a worker pool, a queue consumer, or a `asyncio.create_task`). The `gen_ai.execute_tool` span is started inside the worker. The bug: the worker does not inherit the OTel `Context` because the task was spawned without `contextvars` propagation — the `ContextVar` holding the active span is reset at the `await` boundary or lost at the thread-pool handoff. The resulting span is valid in every attribute sense: - `gen_ai.operation.name = "execute_tool"` - `gen_ai.tool.name = "search_index"` - `gen_ai.tool.call.id = "call_9f3a..."` - `gen_ai.usage.input_tokens` / `output_tokens` populated - `status.code = OK` But its `parent_span_id` is null or points to the worker's own root span, and its `trace_id` is a newly minted one. The reasoning turn (`gen_ai.chat`) and the tool execution now live in **two different traces**. The `gen_ai.tool.call.id` is the only thread connecting them, and it is a string attribute, not a structural edge. The second-order failure: because the tool span is in a fresh trace, the `gen_ai.chat` span that consumes the tool result (the next reasoning turn) gets parented to the *original* reasoning span, not to the tool span. The trace reads as `chat -> chat -> chat` with tool executions floating in parallel traces. Replay tooling that walks parent edges sees a chain of reasoning with no evidence of what each turn actually called — the tool calls are present in the backend but disconnected from the causal graph. This is not a sampling artifact. It reproduces deterministically whenever the executor crosses a context boundary that does not explicitly carry `opentelemetry.context.Context`. ## Condition of Validity The invariant that must hold: **for every `gen_ai.execute_tool` span, `parent_span_id` must equal the `span_id` of the `gen_ai.chat` span whose output contained the `tool_call` with matching `gen_ai.tool.call.id`, and both must share a `trace_id`.** This invariant is valid only under the following conditions: 1. The tool-call authorization is synchronous within the reasoning turn — i.e., the model output that names the tool is produced by the parent chat span. If a supervisor agent authorizes a sub-agent's tool call, the parent is the supervisor's chat span, and the sub-agent's own spans form a nested trace linked by `gen_ai.agent.id` — the invariant still holds but the parent is not the immediate caller. 2. `gen_ai.tool.call.id` is unique per call and is emitted on both the authorizing chat span (as part of the serialized tool-call payload) and the tool span. If the ID is regenerated at the worker, the join key is broken even if the parent edge is correct. 3. The executor explicitly propagates context. `asyncio` propagates `contextvars` across `await` but **not** across `run_in_executor` thread-pool boundaries unless the context is captured and re-entered. Queue-based executors (Celery, SQS consumers) never propagate context automatically — the context must be serialized into the message envelope and re-injected on the consumer side. When any of these fail, attribute conformance survives but causal linkage does not. The span is a valid record of *what* happened but not *why* or *in what order*. ## Decision Boundary The boundary is: **can a replay auditor reconstruct the tool-call sequence from parent edges alone, without trusting string joins?** If yes — the trace is causally sound and attribute conformance is sufficient evidence. If no — the trace is attribute-valid but causally orphaned, and any verification that depends on ordering (did the agent call `search_index` before or after `fetch_doc`? did it retry after a failure?) is unreliable. The decision to accept or reject a trace for audit must be made on parent-edge completeness, not on schema validation. A trace with 100% attribute conformance and 0% causal linkage is worse than a trace with missing optional attributes and intact linkage, because the former passes automated gates and silently corrupts downstream reasoning-replay analysis. The guardrail: a **linkage assertion** at span close time. Before the tool span ends, assert that `parent_span_id` is non-null, that the parent span is a `gen_ai.chat` span (or `gen_ai.agent` for delegated calls), and that the parent's serialized tool-call payload contains the matching `gen_ai.tool.call.id`. If the assertion fails, the span must be marked with a `gen_ai.tool.linkage_status = "orphaned"` attribute and routed to a quarantine exporter rather than the main trace pipeline — otherwise the orphan silently pollutes the causal graph. ## Operational Effect The practical consequence is a **split-brain trace store**: the reasoning chain and the tool executions are both present, both spec-compliant, and both indexed by `trace_id` — but under different `trace_id` values. Dashboards that count `gen_ai.execute_tool` spans show correct volume. Dashboards that measure "tool calls per reasoning turn" show zero, because the join is structural and the structure is broken. Latency attribution fails the same way: the tool span's duration is real but unattributed to the reasoning turn that waited on it, so p99 reasoning latency appears to be pure model time. The recovery path is not re-instrumentation of attributes — it is context re-injection at every async boundary. The executor wrapper must capture `opentelemetry.context.get_current()` at dispatch, serialize it (or hold it in an in-process `ContextVar` re-entered via `contextvars.copy_context().run(...)`), and re-attach it before starting the tool span. For cross-process queues, the W3C `traceparent` and `tracestate` headers must be carried in the message envelope and extracted on consume. Without this, the convention's attributes describe a tool call that, causally, never happened. ```python import contextvars from opentelemetry import context as otel_context, trace class ToolSpanLinkageError(RuntimeError): """Raised when a gen_ai.execute_tool span cannot be causally linked to its authorizing gen_ai.chat span.""" pass # Captured at dispatch time, re-entered at execution time. _dispatch_context: contextvars.ContextVar[otel_context.Context | None] = ( contextvars.ContextVar("dispatch_otel_context", default=None) ) def dispatch_tool_call(tool_name: str, call_id: str, payload: dict) -> dict: """Capture the active OTel context before handing off to an async executor.""" ctx = otel_context.get_current() _dispatch_context.set(ctx) return {"tool_name": tool_name, "call_id": call_id, "payload": payload, "traceparent": format_traceparent(ctx)} def execute_tool_call(envelope: dict) -> dict: """Run inside the worker. Re-attach the dispatch context, then emit the span.""" ctx = _dispatch_context.get() if ctx is None: # Cross-process path: extract from envelope instead. ctx = extract_traceparent(envelope.get("traceparent")) token = otel_context.attach(ctx) try: tracer = trace.get_tracer("agent.tools") with tracer.start_as_current_span( f"execute_tool {envelope['tool_name']}", attributes={ "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": envelope["tool_name"], "gen_ai.tool.call.id": envelope["call_id"], }, ) as span: parent = span.parent if parent is None: span.set_attribute("gen_ai.tool.linkage_status", "orphaned") raise ToolSpanLinkageError( f"tool span for call_id={envelope['call_id']} has no parent; " "context was not propagated across the async boundary" ) parent_span = trace.get_current_span(parent) parent_attrs = parent_span.attributes or {} if parent_attrs.get("gen_ai.operation.name") != "chat": raise ToolSpanLinkageError( f"tool span parent is {parent_attrs.get('gen_ai.operation.name')!r}, " "expected 'chat'" ) return run_tool(envelope["payload"]) finally: otel_context.detach(token) def format_traceparent(ctx: otel_context.Context) -> str: span = trace.get_current_span(ctx) sc = span.get_span_context() return f"00-{sc.trace_id:032x}-{sc.span_id:016x}-{int(sc.trace_flags):02x}" def extract_traceparent(header: str | None) -> otel_context.Context: if not header: return otel_context.Context() # Production: use opentelemetry.propagators.tracecontext.TraceContextTextMapPropagator raise ToolSpanLinkageError("missing traceparent header on queued tool call") def run_tool(payload: dict) -> dict: return {"ok": True, "payload": payload} ```