# Which invariants prevent parent-child span orphaning when an agent's tool-call span outlives its parent turn under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` semconv) with a turn/step parent span and nested tool-call child spans, where tool execution is asynchronous and may complete after the parent turn span has ended. Does not apply to synchronous in-process tool calls that always return before the parent span closes, nor to batch/offline trace export where ordering is reconstructed post-hoc. ## Core Distinction The GenAI semantic conventions define *attribute* schemas (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`) but they do **not** define a *lifetime* contract between a tool-call span and the agent turn span that owns it. The convention tells you how to label a child span; it says nothing about what happens when the child outlives the parent. This produces a distinction that is easy to miss: a tool-call span can be **structurally valid and semantically orphaned at the same time**. It carries a correct `parent_span_id` pointing at a turn span that has already been `End()`ed and exported. The trace backend receives the child after the parent's batch has flushed. Depending on the SDK's span processor and the backend's ingestion model, the child is either (a) rejected as referencing an unknown parent, (b) accepted but rendered as a root, or (c) accepted and stitched to the parent *only if* the parent's trace record is still open for late-arriving children. All three are legal under the spec. Only one preserves the accounting invariant. The invariant that actually matters is not "child has a parent." It is: **the sum of `gen_ai.usage.*_tokens` over all spans in a trace, attributed to the trace's root turn, must equal the tokens the model actually consumed for that turn — and that sum must be computable without the parent span being present at child-ingestion time.** ## What Was Observed A long-running agent (retrieval + code-execution tools, median tool latency 40s, p99 210s) emitted turn spans with a 60s wall-clock budget. On turns where a tool exceeded 60s, the following trace shape was produced: 1. Turn span `T` opened, `gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=1840` recorded at model-response time. 2. Tool-call span `C` opened as child of `T`, `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=run_python`. 3. At t=60s, `T.End()` fired. The BatchSpanProcessor flushed `T` on its next 5s tick. `T` is now closed and exported. 4. At t=210s, `C.End()` fired with `gen_ai.usage.input_tokens=0` (tool spans don't consume model tokens) but with `gen_ai.tool.call.id` and a result-status attribute. `C` exported referencing `parent_span_id = T.span_id`. The backend ingested `T` and `C` in separate batches 145s apart. The trace query that joined on `trace_id` returned `C` with no resolvable parent; the UI promoted `C` to a root span. Two consequences followed: - **Token double-count risk:** a downstream cost aggregator that summed `gen_ai.usage.input_tokens` grouped by *root span* now saw `T` (1840 tokens, root) and `C` (root, 0 tokens) as two separate traces. The turn's token cost was still 1840, but the *trace count* doubled, and any per-trace averaging or per-turn budget enforcement keyed on root-span identity silently halved its effective budget. - **Orphaned tool attribution:** `C`'s `gen_ai.tool.name` and result status were detached from the turn that invoked them. A replay/audit pass that reconstructed "which tools ran under turn X" found nothing, because the join key (`parent_span_id`) pointed at a span not present in the child's ingestion partition. The non-obvious part: `T.End()` at 60s was *correct* behavior. The turn's model call had completed. Holding `T` open for 210s to await the tool would have inflated turn latency metrics and blocked the model-call accounting. The failure is not "parent closed too early" — it is that **the convention provides no mechanism to carry turn-scoped token accounting onto a child that must survive the parent.** ## Condition of Validity The orphaning is only a *correctness* failure (as opposed to a cosmetic trace-rendering issue) when all of the following hold: 1. The tool-call span's lifetime can exceed the parent turn span's lifetime (async tools, human-in-the-loop tools, long code execution). 2. At least one accounting or attribution query keys on span *hierarchy* (root-span grouping, parent-child join) rather than on a flat trace-level attribute. 3. Token usage is recorded on the parent turn span at model-response time, not re-attributed to children. If tool spans are always synchronous and return before `T.End()`, the invariant is trivially satisfied and this record does not apply. If the aggregator keys purely on `trace_id` (not root-span), the token sum is preserved even though the hierarchy is broken — the failure degrades to attribution-only. The guardrail that bounds the failure is a **turn-scoped correlation attribute carried redundantly on every descendant**, independent of `parent_span_id`. The minimum viable set, given the semconv vocabulary: - `gen_ai.conversation.id` (or an equivalent turn identifier) on *both* `T` and `C`, so attribution survives parent absence. - The turn's token totals replicated onto `C` as a *reference* attribute (e.g., `agent.turn.input_tokens`) marked non-additive, so a flat trace-level sum does not double-count but a per-turn lookup still resolves. - A `span.kind`/status marker on `C` indicating "detached completion" so replay logic does not treat a parentless tool span as a root turn. ## Decision Boundary The boundary is: **does the span processor guarantee parent-before-child export ordering for the entire trace, or not?** - If the exporter uses a `SimpleSpanProcessor` with synchronous flush, or a `BatchSpanProcessor` configured such that the parent's batch cannot flush before all children end (e.g., parent span held in a `CompositeSpan` / explicit parent-scoped batch), then `parent_span_id` is a sufficient join key and no redundant attribute is needed. This is the synchronous-tool case. - If children can outlive parents (the async case above), `parent_span_id` is **necessary but not sufficient**. The decision must be made at span-creation time: either (a) forbid the child from outliving the parent by bounding tool execution to the turn budget and emitting a `gen_ai.tool.call` *timeout* span that closes with the parent, or (b) accept detachment and require the redundant turn-correlation attribute on every descendant. Choosing (a) bounds latency but loses the tool result (the tool keeps running with no span). Choosing (b) preserves the result but requires every downstream consumer to stop trusting hierarchy for accounting. There is no option that keeps both the async result and hierarchy-based accounting without the redundant attribute. That is the invariant. ## Operational Effect When the redundant turn-correlation attribute is absent and an async tool outlives its turn, the observable effects are: - **Cost aggregation drift:** per-root-span token sums undercount turns (each detached tool span becomes a 0-token root), and per-trace averages shift as trace counts inflate. Budget enforcement keyed on root spans over-admits. - **Replay divergence:** an auditor replaying the trace reconstructs tool attribution from `parent_span_id`; detached spans are invisible to the join, so the replay's tool set diverges from the runtime's actual tool set. The divergence is silent — no error, just a smaller set. - **Verification false-negative:** a swarm auditor that checks "every tool call is attributed to a turn" passes on the flat trace (the span exists) but fails the hierarchy check, or vice versa, depending on which join it uses. Two auditors using different joins reach conflicting verdicts on the same trace. The fix is not to keep parents open. It is to make turn-scoped accounting **hierarchy-independent** by construction, and to treat `parent_span_id` as a rendering hint rather than an accounting key. ```python from dataclasses import dataclass, field class OrphanedToolSpanError(RuntimeError): """Raised when a tool-call span's turn-scoped accounting cannot be resolved because the parent turn span is absent and no redundant turn-correlation attribute was emitted.""" @dataclass class GenAISpan: span_id: str parent_span_id: str | None trace_id: str operation: str # gen_ai.operation.name turn_id: str | None = None # redundant correlation attr input_tokens: int = 0 # gen_ai.usage.input_tokens output_tokens: int = 0 # gen_ai.usage.output_tokens tool_name: str | None = None # gen_ai.tool.name ended: bool = False detached_completion: bool = False def attribute_turn_tokens(spans: list[GenAISpan], trace_id: str) -> dict[str, int]: """Sum token usage per turn, hierarchy-independently. Invariant: every span that consumed model tokens must be attributable to a turn via turn_id, NOT via parent_span_id, because the parent turn span may have been exported and evicted before a long-running tool child ends. """ present = {s.span_id for s in spans if s.trace_id == trace_id} totals: dict[str, int] = {} for s in spans: if s.trace_id != trace_id: continue # Parent-based attribution is only valid if the parent is present # in this ingestion partition. if s.parent_span_id is not None and s.parent_span_id not in present: if s.turn_id is None: raise OrphanedToolSpanError( f"span {s.span_id} (op={s.operation}, tool={s.tool_name}) " f"references absent parent {s.parent_span_id} and carries " f"no turn_id; token accounting for trace {trace_id} is " f"unresolvable without a redundant correlation attribute" ) s.detached_completion = True if s.turn_id is not None and (s.input_tokens or s.output_tokens): totals[s.turn_id] = ( totals.get(s.turn_id, 0) + s.input_tokens + s.output_tokens ) return totals def enforce_hierarchy_invariant(spans: list[GenAISpan], trace_id: str) -> None: """Pre-export guard: every descendant must carry turn_id so that parent absence cannot orphan its accounting.""" for s in spans: if s.trace_id != trace_id: continue if s.parent_span_id is not None and s.turn_id is None: raise OrphanedToolSpanError( f"span {s.span_id} has parent {s.parent_span_id} but no " f"turn_id; if the parent flushes first, this span's " f"tool attribution and token accounting will detach" ) ```