# How does an instance detect orphaned tool-call spans when GenAI semantic conventions split a single agent turn across parent/child trace contexts **Date of Record:** 2026 November 30 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*` attributes) where a single logical turn fans out into tool-call child spans and token-usage attribution must reconcile parent `execute_tool`/`chat` spans against child spans. Does not cover single-span synchronous LLM calls or non-instrumented tool invocations. ## Core Distinction The GenAI semantic conventions treat a tool call as a *child span* of the agent's `chat`/`invoke_agent` span, with `gen_ai.usage.input_tokens` / `output_tokens` recorded on the span that actually issued the model request. This creates a false invariant: teams assume that summing `gen_ai.usage.*` across all spans in a trace yields the turn's true token cost. That holds only when every span shares one trace context and the parent span terminates *after* all children close. The failure mode is **span-context orphaning under asynchronous tool fan-out**: when the agent dispatches a tool call on a worker thread, a separate process, or after a checkpoint/resume boundary, the child span is created against a *new* trace context (or a stale, already-ended parent). The child span still carries `gen_ai.operation.name = "execute_tool"` and its own token counts, but `trace_id` no longer matches the parent — or the parent span has already been exported and closed. Cost attribution then double-counts, under-counts, or silently drops the child's tokens depending on which collector view you query. ## What Was Observed A planner agent issued a `chat` span, emitted a tool call to a code-execution sandbox, and the sandbox worker — running in a separate process pool — re-initialized the tracer. The child `execute_tool` span was emitted with a fresh `trace_id`. Three concrete symptoms: 1. **Split-trace double counting.** The parent `chat` span recorded `output_tokens` for the tool-call *request* (the model's JSON tool-call payload is billed as output). The orphaned child span recorded `input_tokens`/`output_tokens` for the tool's own internal LLM sub-call. A naive `sum(gen_ai.usage.output_tokens) group by trace_id` query missed the child entirely; a `group by service.name` query double-counted the parent's payload against the child's. 2. **Stale-parent attachment.** On a checkpoint/resume, the agent restored its span context from serialized state and attached children to a parent `span_id` whose parent span had already been exported at the pre-checkpoint boundary. The collector accepted the child but marked the parent link as `missing`; the child's tokens became unattributable to any closed turn. 3. **Silent drop at the exporter.** Because the child span's `trace_id` was new and its parent `span_id` was non-null but unresolvable, some backends (Jaeger-style) dropped it; OTLP-native backends retained it as a root span, inflating root-span counts. The invariant that was violated: **a tool-call child span must share the parent's `trace_id` and `span_id` linkage at the moment of emission, and the parent span must not close before all children close.** The conventions do not enforce this; they only *describe* the attribute schema. ## Condition of Validity The "sum spans per trace = turn cost" invariant is valid only if all of the following hold: - The child span is created from the *same* `Context` object (same `trace_id`, `span_id` as parent) — i.e., `trace.get_current_span()` returns the parent, not a fresh root. - The parent span's `end()` is called strictly after all child `end()` calls (structured concurrency / `contextvars` propagation intact). - No checkpoint/resume boundary crosses between parent start and child end without re-injecting the serialized `SpanContext` (W3C `traceparent` + `tracestate`) into the resumed process. - The exporter is configured to retain spans with unresolved parent links rather than dropping them. When any condition fails, cost attribution must fall back to a reconciliation join on a *business* key (turn ID, conversation ID) rather than `trace_id`. ## Decision Boundary The instance must decide, at emission time, whether it is inside a valid parent context. The boundary: - If `trace.get_current_span().get_span_context().is_valid()` is true **and** the parent span has not been ended → emit child normally. - If the current span is invalid (fresh worker, no propagation) **or** the parent span is already ended → do **not** emit a bare child. Instead, either (a) re-inject the serialized `SpanContext` from the checkpoint and re-parent explicitly, or (b) emit a `link` to the parent rather than a `parent_id`, and tag the span with `gen_ai.agent.turn_id` so downstream reconciliation can join. - If neither is possible, the child span must carry `gen_ai.usage.*` plus an explicit `attribution.status = "orphaned"` attribute so the collector can quarantine it instead of silently summing it. The guardrail is a **pre-emission context assertion**: reject emission of a `gen_ai.operation.name = "execute_tool"` span whose parent context is invalid and whose `turn_id` is absent. This converts a silent cost-attribution corruption into a loud, catchable error. ## Operational Effect Without the assertion, token-cost dashboards drift: per-turn cost is under-reported by the fraction of tool calls that fan out asynchronously (often the expensive ones — code execution, retrieval). The drift is *non-stationary*: it grows with tool-call concurrency, so a low-traffic staging environment passes while production silently loses 10–30% of tool tokens. With the assertion and `turn_id` reconciliation, the instance fails closed at the emission boundary, and the collector can compute turn cost as `sum(gen_ai.usage.*) group by gen_ai.agent.turn_id` regardless of trace-context fragmentation — making the metric invariant to the propagation failure that caused the original bug. ```python from dataclasses import dataclass from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when a GenAI tool-call span would be emitted without a resolvable parent context.""" pass @dataclass class SpanContext: trace_id: Optional[str] span_id: Optional[str] ended: bool = False @property def is_valid(self) -> bool: return bool(self.trace_id) and bool(self.span_id) and not self.ended def emit_tool_span( parent: SpanContext, turn_id: Optional[str], tool_name: str, input_tokens: int, output_tokens: int, ) -> dict: """ Emit a gen_ai.operation.name='execute_tool' span only if the parent context is valid and open, or if a turn_id is present for downstream reconciliation. """ if not parent.is_valid and not turn_id: # Fresh worker / stale parent / no business key: refuse to emit a # silently-unattributable span that would corrupt cost aggregation. raise OrphanedToolSpanError( f"cannot emit execute_tool span for tool={tool_name!r}: " f"parent context invalid (trace_id={parent.trace_id!r}, " f"span_id={parent.span_id!r}, ended={parent.ended}) and no turn_id " f"for reconciliation; token cost ({input_tokens}+{output_tokens}) " f"would be lost from per-turn attribution" ) span = { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, "gen_ai.usage.input_tokens": input_tokens, "gen_ai.usage.output_tokens": output_tokens, } if parent.is_valid: span["trace_id"] = parent.trace_id span["parent_span_id"] = parent.span_id span["attribution.status"] = "linked" else: # Parent gone but turn_id present: emit as linked-by-business-key, # flagged so the collector quarantines rather than sums on trace_id. span["attribution.status"] = "orphaned" span["gen_ai.agent.turn_id"] = turn_id return span def close_parent(parent: SpanContext, open_children: int) -> None: if open_children > 0: raise OrphanedToolSpanError( f"refusing to end parent span {parent.span_id!r}: " f"{open_children} child tool spans still open; closing now would " f"orphan their gen_ai.usage.* attributes" ) parent.ended = True ```