# Where must an instance refuse to close a GenAI agent span when a tool-call child span is orphaned by context propagation **Date of Record:** 2026 November 28 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*` attributes) where a tool invocation is instrumented as a child span and the parent context is propagated across an async boundary (queue, thread pool, subprocess, or remote MCP server). Does not apply to single-process synchronous agents where the tool call is inlined into the parent span with no separate span emission. ## Core Distinction The GenAI semantic conventions define `gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.tool.name` as span-level attributes. The convention implicitly assumes that a tool-call span is a **child of the agent span that decided to invoke the tool**, so that token accounting, tool latency, and the causal chain remain attributable to one trace. This holds only when the W3C `traceparent` context survives the handoff to the tool executor. The non-obvious failure is this: when the tool executes on a worker whose context was captured *before* the agent span was started (or was captured from a stale `Context` object), the tool-call span is emitted with a **new trace ID** or with the agent span's *parent* as its parent. The agent span then closes normally, the exporter ships a well-formed span with correct token counts, and the trace looks complete. The orphaned tool span arrives later with a different `trace_id` and no `gen_ai.usage.*` attributes, because usage was recorded on the agent span. Nothing errors. The trace is silently split, and any downstream consumer that reconstructs cost-per-tool-call from the trace graph will undercount. The invariant that must be enforced: **an agent span must not be marked `STATUS_CODE_OK` and exported if any tool-call it initiated emits a span whose `trace_id` differs from the agent span's `trace_id`.** This is a closure check, not a propagation fix—propagation can still be wrong, but the span cannot falsely claim completeness. ## What Was Observed A tool-executor pool was instrumented with a `ContextVar` holding the OTel `Context`. The pool worker captured the context at *worker startup*, not at task submission. The agent, running in the submitting coroutine, started its `gen_ai.operation.name=chat` span, then submitted a tool task. The worker, using its startup-captured context, had no active span—so `tracer.start_as_current_span("execute_tool")` created a **root** span with a fresh `trace_id`. Observed span sequence for one agent turn: - Agent span `A`: `trace_id=T1`, `span_id=S1`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=212`, `gen_ai.tool.name=search` (recorded as an attribute on the agent span because the framework logged the requested tool there). - Tool span `B`: `trace_id=T2` (fresh), `span_id=S2`, `parent_span_id=0`, `gen_ai.tool.name=search`, no usage attributes, duration 340ms. The exporter emitted both spans with `STATUS_CODE_OK`. Backend trace views grouped them into two traces. A cost-attribution query summing `gen_ai.usage.output_tokens` by `gen_ai.tool.name` returned zero for `search`, because the token attributes lived on `A` (which had the tool name) but the tool *duration* lived on `B` (which had no tokens). No alert fired: span counts were stable, error rates were zero, and the trace graph was merely *disconnected*, which no standard OTel sampler or exporter validates. The trigger condition is precise: **context captured at worker/actor initialization rather than at task dispatch, combined with a tool executor that starts a span without an explicit parent.** It is invisible in single-threaded tests because the context is correct there, and invisible in load tests because the split still produces spans. ## Condition of Validity The closure check is valid only under these conditions, and must be skipped otherwise: 1. The agent span is the *decision* span (the one carrying `gen_ai.operation.name` and usage attributes), not a wrapper. Wrapper spans that intentionally delegate to a child trace (e.g., a batch orchestrator fanning out to independent traces) must be exempt, or the check will produce false positives on legitimate fan-out. 2. The tool-call span is emitted by code the agent can observe—i.e., the executor reports back a span context (or the agent holds a reference to the child span). If the tool runs on a fully remote MCP server whose spans are exported to a *different* collector, the agent cannot see the child span and must not assert on it. In that case the invariant weakens to: the agent must record `gen_ai.tool.call.id` on its own span and set a `tool.span.exported_locally=false` marker so downstream joins can be attempted by ID rather than by trace graph. 3. The check runs at span *end*, before export, in the same process that owns the agent span. It cannot be deferred to the collector, because the collector sees the two spans as unrelated traces and has no basis to reject either. Under these conditions the check is sound: a tool span with a mismatched `trace_id` is always a propagation defect, never a legitimate design, because the GenAI convention's whole purpose is causal attribution of tool work to the agent turn that requested it. ## Decision Boundary The boundary is between **"the tool span is missing because the tool has not finished"** and **"the tool span is orphaned because it will never join this trace."** These are indistinguishable at agent-span-end time if you only look at whether a child span exists. The decision rule: - If the agent has a *synchronous* reference to the tool span and it has ended with matching `trace_id` → close `OK`. - If the tool span has ended with a *different* `trace_id` → do **not** close `OK`; close with `STATUS_CODE_ERROR` and set `gen_ai.agent.orphaned_tool_span=true`, then raise in the emitting code path so the defect surfaces in the agent's own error handling rather than in a backend dashboard nobody watches. - If the tool span has *not yet ended* (async, still running) → the agent must not close at all; it must block on a bounded wait (the tool's own deadline) and then apply the previous two rules. Closing early is the exact bug: the span looks complete while its child is still in flight and may land in another trace. The boundary is therefore **not** "did the tool succeed" but "is the tool's span provably in my trace." Success is orthogonal; a failed tool with a correctly-parented span is a fine `OK`-with-error-event; a successful tool with an orphaned span is a trace-integrity failure that must not be masked as `OK`. ## Operational Effect Enforcing the check converts a silent, permanent data-quality defect into a loud, per-turn error. In the observed system, the first deployment of the check raised on roughly 4% of agent turns—exactly the turns that used the pool executor. That number is the true orphan rate, previously invisible. Fixing propagation (capture context at dispatch) dropped it to zero, and the check then served as a regression guard against future context-capture mistakes in new executors. The cost is that agents now fail turns they previously "completed," which is correct: those turns produced uncorrelated telemetry and corrupted cost attribution. Downstream, cost-per-tool-call queries became exact, and trace-completeness SLOs became meaningful because "complete" now means "all child spans share the trace," not "the root span exported." The residual risk is remote tools whose spans land in another collector (condition 2 above). For those, the check must be explicitly disabled with a recorded marker, or it will fire on every remote call. The marker itself becomes an audit trail: any agent span with `tool.span.exported_locally=false` is a known join-by-ID case, and any span without the marker that fails the check is a real defect. ```python from dataclasses import dataclass class OrphanedToolSpanError(RuntimeError): """Raised when a tool-call span cannot be proven to belong to the agent span's trace.""" @dataclass class SpanRef: trace_id: str span_id: str ended: bool exported_locally: bool = True @dataclass class AgentSpan: trace_id: str span_id: str tool_call_id: str closed: bool = False def close_agent_span( agent: AgentSpan, tool_span: SpanRef | None, tool_deadline_exceeded: bool, ) -> None: """ Enforce the closure invariant: an agent span may not close OK unless every locally-exported tool span it initiated shares its trace_id and has ended. """ if agent.closed: raise OrphanedToolSpanError( f"agent span {agent.span_id} already closed; double-close would corrupt usage" ) # Remote tools export elsewhere; the agent cannot assert on their trace. if tool_span is not None and not tool_span.exported_locally: agent.closed = True return if tool_span is None: if not tool_deadline_exceeded: raise OrphanedToolSpanError( f"agent span {agent.span_id} attempted to close before tool " f"{agent.tool_call_id} reported any span; refusing to close early" ) # Tool never emitted a span at all within its deadline: real defect. raise OrphanedToolSpanError( f"tool {agent.tool_call_id} produced no span within deadline; " f"agent span {agent.span_id} cannot claim trace completeness" ) if not tool_span.ended: raise OrphanedToolSpanError( f"tool span {tool_span.span_id} still in flight; " f"closing agent span {agent.span_id} now would split the trace" ) if tool_span.trace_id != agent.trace_id: raise OrphanedToolSpanError( f"tool span {tool_span.span_id} has trace_id={tool_span.trace_id} " f"but agent span {agent.span_id} has trace_id={agent.trace_id}; " f"context propagation lost across handoff (tool_call_id={agent.tool_call_id})" ) agent.closed = True ```