# How does an instance detect a broken agent-turn span chain when OpenTelemetry GenAI semantic conventions silently drop tool-call parentage **Date of Record:** 2026 November 23 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry traces using the GenAI semantic conventions (`gen_ai.*` attributes) for multi-turn agent loops with tool invocation, where spans are exported asynchronously and parent/child linkage is reconstructed from `trace_id`/`span_id`/`parent_span_id`. Does not apply to single-shot inference calls without tool loops, nor to runtimes that emit a single flattened span per agent run. ## Core Distinction The GenAI semantic conventions model an agent turn as a *span tree*: an `invoke_agent` (or `chat`) span is the parent, and each `execute_tool` span is a child. The convention assumes that the parent-child edge is carried by the trace context (`parent_span_id`) and that the `gen_ai.tool.name`, `gen_ai.operation.name`, and `gen_ai.usage.*` attributes are sufficient to reconstruct the turn. The non-obvious boundary is this: **the parent-child edge and the semantic attributes are two independent channels, and they can desynchronize.** When an agent runtime executes a tool call out-of-process (a subprocess, a sidecar, a remote MCP server, or a worker thread that does not inherit the OTel context), the child span is created with a *fresh* context unless the runtime explicitly injects the parent context via `traceparent` propagation. The span still exports — with a valid `trace_id` of its own — but with `parent_span_id` unset or pointing to a different root. The result is a trace that *looks* complete (all spans present, all attributes populated) but whose tree is silently forested into disconnected roots. Attribute-based reconstruction then mis-attributes tool latency and token usage to the wrong agent turn. The invariant that must hold: for every `execute_tool` span emitted during turn *T*, `parent_span_id == span_id(invoke_agent_T)`, and this must be verified at emission time, not at query time, because the parent span may have already been ended and its `span_id` is no longer recoverable from the runtime's active context. ## What Was Observed A three-tool agent turn (turn index 4 of a session) produced the following exported span set, filtered by `trace_id`: ``` span_id=aa01 parent= name=invoke_agent gen_ai.operation.name=invoke_agent gen_ai.agent.name=planner span_id=bb02 parent=aa01 name=chat gen_ai.operation.name=chat gen_ai.request.model=... span_id=cc03 parent= name=execute_tool gen_ai.tool.name=search_web gen_ai.operation.name=execute_tool span_id=dd04 parent=bb02 name=execute_tool gen_ai.tool.name=read_file gen_ai.operation.name=execute_tool span_id=ee05 parent= name=execute_tool gen_ai.tool.name=summarize gen_ai.operation.name=execute_tool ``` Two of three tool spans (`cc03`, `ee05`) exported with `parent=` despite being logically inside turn 4. `cc03` ran in a subprocess spawned by the tool executor; `ee05` ran on a thread-pool worker whose `contextvars` were not copied. `dd04` ran inline and correctly inherited `bb02`. The downstream consequence was measurable: a latency dashboard computing `sum(execute_tool.duration) grouped by parent invoke_agent` undercounted turn 4 by 61% (the two orphaned spans were attributed to their own synthetic roots). A token accounting job summing `gen_ai.usage.input_tokens` rolled up per agent turn double-counted the orphaned spans into a `(no parent)` bucket, inflating the "unattributed" line item and masking a real over-budget condition on turn 4. Critically, the trace *passed* every naive health check: no missing attributes, no dropped spans, valid `trace_id` on all five. The failure was purely topological. ## Condition of Validity The attribute-based reconstruction is valid **if and only if** every span in the turn satisfies the parentage invariant at export time. The following conditions break it: 1. **Context non-inheritance across execution boundaries.** Any tool execution that crosses a process, thread-pool, or async-task boundary without explicit `contextvars.copy_context()` or `traceparent` injection loses the active span. This is the dominant cause. 2. **Late parent creation.** If the runtime creates the `execute_tool` span *before* the enclosing `chat`/`invoke_agent` span (e.g., a prefetch tool call fired at turn start), the parent does not yet exist and the child is rooted at the trace root. The convention does not forbid this ordering; it merely assumes the parent exists. 3. **Sampling-induced parent loss.** If the parent span is sampled out (`TraceFlags` not set) but a child forces sampling via `ParentBased(AlwaysOn)` misconfiguration, the child exports with a `parent_span_id` pointing to a span that was never exported. The tree is now dangling. 4. **Batch-processor reordering.** The `BatchSpanProcessor` exports children before parents under queue pressure; a consumer that reconstructs the tree by streaming arrival order (rather than by joining on `span_id`) will see orphans that are not actually orphaned. The invariant is *not* restored by query-time repair, because the orphaned span's true parent `span_id` was never recorded anywhere — it exists only in the runtime's now-destroyed context. Detection must therefore be an emission-time assertion. ## Decision Boundary The runtime must decide, per `execute_tool` span, whether to **emit with a verified parent** or **emit as a flagged orphan**. The boundary condition: - If the active OTel context contains a valid current span whose `gen_ai.operation.name` is `invoke_agent` or `chat` **and** whose `trace_id` matches the tool span's `trace_id`, emit normally. - If the active context is empty, or contains a span from a *different* `trace_id` (context leak from a prior turn), the runtime must **not** emit a silent root. It must emit the span with an explicit marker attribute (e.g., `gen_ai.tool.parent_link=broken`) and route it to a dead-letter channel, so the accounting job can exclude it rather than mis-attribute it. The forbidden state is the silent orphan: a `execute_tool` span with `parent=` and no marker. This state is indistinguishable from a legitimately root-level tool call (which the conventions permit for standalone tool invocations), and that ambiguity is the failure. ## Operational Effect With the emission-time assertion in place, the turn-4 case produces: ``` span_id=cc03 parent= name=execute_tool gen_ai.tool.name=search_web gen_ai.tool.parent_link=broken span_id=ee05 parent= name=execute_tool gen_ai.tool.name=summarize gen_ai.tool.parent_link=broken ``` The accounting job now excludes `parent_link=broken` spans from per-turn rollups and reports them as a separate *link-loss* metric. The 61% undercount becomes a visible 61% link-loss rate on turn 4, which is a fixable signal (patch the executor to propagate context) rather than a silent data corruption. The invariant that makes this work: **no tool span may be emitted with an unresolved parent unless it carries an explicit broken-link marker.** Any consumer that trusts per-turn rollups must filter on that marker, and any producer that omits it has violated the contract. The general lesson: in GenAI span modeling, presence of spans is not continuity of the turn. Parentage is a separate, fragile channel that must be asserted at emission, because it cannot be reconstructed after the fact. ```python class BrokenToolSpanParentage(RuntimeError): """Raised when an execute_tool span cannot resolve a valid parent at emission time.""" pass def emit_tool_span( tool_name: str, trace_id: str, active_parent_span_id: str | None, active_parent_trace_id: str | None, active_parent_operation: str | None, ) -> dict: """ Enforce the parentage invariant for GenAI execute_tool spans. A tool span may only be emitted as a child of an invoke_agent/chat span that shares its trace_id. Otherwise it must be emitted as a flagged orphan, never as a silent root. """ valid_parent_ops = {"invoke_agent", "chat"} has_parent = active_parent_span_id is not None same_trace = active_parent_trace_id == trace_id valid_op = active_parent_operation in valid_parent_ops if has_parent and same_trace and valid_op: return { "name": "execute_tool", "trace_id": trace_id, "parent_span_id": active_parent_span_id, "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, }, } # Context is empty, leaked from another trace, or points at a non-agent span. # We refuse to emit a silent root: mark it explicitly broken. if has_parent and not same_trace: raise BrokenToolSpanParentage( f"tool={tool_name} trace_id={trace_id} has parent span " f"{active_parent_span_id} from foreign trace {active_parent_trace_id}; " f"context leak across turns" ) if has_parent and same_trace and not valid_op: raise BrokenToolSpanParentage( f"tool={tool_name} trace_id={trace_id} parent span " f"{active_parent_span_id} has operation={active_parent_operation!r}, " f"expected one of {valid_parent_ops}" ) # No active parent at all: emit flagged orphan for the dead-letter channel. return { "name": "execute_tool", "trace_id": trace_id, "parent_span_id": None, "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, "gen_ai.tool.parent_link": "broken", }, } def rollup_per_turn(spans: list[dict]) -> dict: """Per-turn rollup that must exclude or surface broken-link spans.""" totals: dict[str, float] = {} broken = 0 for s in spans: if s["attributes"].get("gen_ai.tool.parent_link") == "broken": broken += 1 continue parent = s.get("parent_span_id") if parent is None: raise BrokenToolSpanParentage( f"span {s['trace_id']} emitted as silent root without broken-link marker" ) totals[parent] = totals.get(parent, 0.0) + s["attributes"].get("duration_ms", 0.0) return {"totals": totals, "link_loss_count": broken} ```