# What structural signals indicate tool-call lineage has silently detached from its parent span under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the `gen_ai.*` semantic conventions (v1.27+) for tool invocations and token accounting, where tool calls may be retried, fanned out across sub-agents, or replayed from a checkpoint. Does not cover tracing of non-agentic LLM inference or plain RPC instrumentation. ## Core Distinction The GenAI semantic conventions treat a tool call as a *child span* of the model-invocation span that requested it, with lineage expressed through `trace_id`/`parent_span_id` and token accounting expressed through `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on the *invocation* span. The failure we care about is not a missing span or a dropped attribute — those are loud. It is the **silent re-parenting of a tool-call span to the wrong invocation span** when an agent retries, resumes from checkpoint, or fans out, combined with **token attributes that continue to attribute to the original invocation**. The trace remains structurally valid (every span has a parent, every `trace_id` resolves), so the collector accepts it, the backend indexes it, and the dashboard shows a clean waterfall. The lineage is wrong, and the token ledger double-counts or orphans usage. This is a *continuity invariant* failure, not a transport failure. ## What Was Observed An agent executing a `search_documents` tool call hit a 504 on the tool's HTTP endpoint. The runtime's retry policy re-issued the call after 2s. Both attempts executed server-side (the first timed out on the client, not the server). The runtime emitted: - Invocation span `A` (`gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=212`) containing the tool-call request. - Tool span `T1` parented to `A`, status `ERROR`, `error.type=timeout`. - Retry tool span `T2` also parented to `A`, status `OK`. The structural signals looked correct. But the underlying tool executed twice, and the *second* attempt's request carried a `tool_call_id` that the model had generated for the first attempt. Because the runtime keyed its retry cache on `(trace_id, tool_call_id)` rather than `(trace_id, span_id)`, when a *later* invocation span `B` (a follow-up chat turn) re-requested the same `tool_call_id` — the model had echoed it from context — the runtime served `T2`'s cached result and emitted a tool span `T3` parented to `B` but with attributes copied from `T2`, including `gen_ai.usage` deltas that had already been counted under `A`. The observable structural signals of this detachment: 1. **`tool_call_id` collision across trace-local scopes.** Two tool spans in the same trace share an identical `gen_ai.tool.call.id`, but have different `parent_span_id` values. The convention does not require uniqueness, so no validator flags it. 2. **Token attributes on child spans.** `T3` carried `gen_ai.usage.input_tokens` even though `gen_ai.operation.name=execute_tool`. The convention scopes usage attributes to the invocation span; their presence on a tool span is the fingerprint of a copied/cached span. 3. **Parent span's usage does not reconcile with child tool count.** Invocation `B` reported `output_tokens=190` but its child tool span `T3` referenced a request that, under `A`, had produced a 212-token output. The model's accounting for `B` never saw the tool result as a fresh observation; it saw a cached echo. 4. **Timestamp monotonicity violation.** `T3.start_time` preceded `B.start_time` because the cached span template carried `T2`'s original timestamps. None of these break schema validation. All of them break the invariant that **a tool-call span's identity and accounting belong to exactly one invocation span, and that invocation span's usage attributes reflect only tokens it actually consumed**. ## Condition of Validity The invariant holds only when the following conjunction is true: - `gen_ai.tool.call.id` is unique within `(trace_id, parent_span_id)`, not merely within `trace_id`. - `gen_ai.usage.*` attributes appear **only** on spans with `gen_ai.operation.name ∈ {chat, text_completion, embeddings}` and **never** on `execute_tool` spans. - A tool-call span's `start_time` is ≥ its parent invocation span's `start_time`, and its `end_time` ≤ the parent's `end_time` (tool execution is bounded by the turn that requested it). - On retry, the retry span is a *sibling* of the failed span under the same parent, with a distinct `span_id`, and the parent's usage attributes are **not** re-emitted. When any of these is violated, lineage has detached. The trace is still ingestible, which is precisely why the failure is non-obvious: the collector's schema validator checks attribute *types and presence*, not *relational consistency* across spans. ## Decision Boundary The boundary is between **cache-served results** and **fresh executions**. A runtime may serve a cached tool result to avoid redundant execution — but the moment it does, it must either: - (a) emit a *new* span with a *new* `span_id`, `gen_ai.tool.call.id` scoped to the new parent, and **no** `gen_ai.usage.*` attributes, marking `gen_ai.tool.cache_hit=true`; or - (b) emit a span with `gen_ai.operation.name=execute_tool` and an explicit `link` (OTel span link) to the original execution span, rather than re-parenting. Re-parenting a cached span template — copying attributes including usage and timestamps — crosses the boundary and detaches lineage. The decision boundary is therefore: **if the tool did not execute in this invocation, its span must not claim this invocation's token budget or this invocation's temporal window.** ## Operational Effect Downstream consequences observed: - **Token ledger overcount.** Cost attribution summed `gen_ai.usage.*` across all spans regardless of `operation.name`, double-counting the cached turn's tokens. Billing reconciliation showed a 6–9% inflation on retry-heavy traces. - **Waterfall misreads.** The trace UI rendered `T3` under `B` with `T2`'s timestamps, producing a negative-duration bar. On-call engineers initially diagnosed a clock-skew bug in the collector rather than a lineage bug in the agent. - **Auditor divergence.** A verification agent replaying the trace to confirm the tool result saw `T3`'s cached payload and concluded the tool had returned the *same* document for two distinct queries — a false positive on a retrieval-quality check. The guardrail is a post-emit consistency check run in the agent's span processor (before export), rejecting any span batch where a tool span carries usage attributes, where `tool_call_id` collides across differing parents within a trace, or where child time bounds exceed parent bounds. This must run *before* export because the collector cannot distinguish a legitimate re-parent from a cached-template copy — the distinction lives in the runtime's cache key, not in the span payload. ```python from dataclasses import dataclass from typing import Iterable class LineageDetachmentError(RuntimeError): """Raised when a tool-call span's lineage or accounting has detached from its parent invocation span under GenAI semantic conventions.""" @dataclass(frozen=True) class Span: span_id: str parent_span_id: str | None trace_id: str operation_name: str tool_call_id: str | None usage_input_tokens: int | None usage_output_tokens: int | None start_time_ns: int end_time_ns: int @property def is_tool_span(self) -> bool: return self.operation_name == "execute_tool" @property def is_invocation_span(self) -> bool: return self.operation_name in {"chat", "text_completion", "embeddings"} def assert_lineage_invariant(spans: Iterable[Span]) -> None: """Enforce the four-part continuity invariant for GenAI tool-call lineage. Rejects the batch before export if any span violates: 1. usage attributes only on invocation spans 2. tool_call_id unique within (trace_id, parent_span_id) 3. child time bounds contained within parent time bounds 4. no cached-template re-parenting (usage on tool span is the fingerprint) """ by_id = {s.span_id: s for s in spans} seen_tool_ids: dict[tuple[str, str], str] = {} for span in by_id.values(): # (1) usage attributes must never ride on a tool span. if span.is_tool_span and ( span.usage_input_tokens is not None or span.usage_output_tokens is not None ): raise LineageDetachmentError( f"tool span {span.span_id} carries gen_ai.usage.* attributes; " f"this is the fingerprint of a cached span template re-parented " f"into a new invocation (op={span.operation_name})" ) # (2) tool_call_id must be unique per parent, not per trace. if span.is_tool_span and span.tool_call_id is not None: key = (span.trace_id, span.parent_span_id or "") prior = seen_tool_ids.get(key) if prior is not None and prior != span.span_id: raise LineageDetachmentError( f"tool_call_id {span.tool_call_id!r} collides across spans " f"{prior} and {span.span_id} under parent " f"{span.parent_span_id}; lineage cannot be resolved" ) seen_tool_ids[key] = span.span_id # (3) temporal containment. if span.parent_span_id is None: continue parent = by_id.get(span.parent_span_id) if parent is None: continue if span.start_time_ns < parent.start_time_ns: raise LineageDetachmentError( f"span {span.span_id} starts ({span.start_time_ns}) before " f"parent {parent.span_id} ({parent.start_time_ns}); " f"cached-template timestamp copy suspected" ) if span.end_time_ns > parent.end_time_ns: raise LineageDetachmentError( f"span {span.span_id} ends ({span.end_time_ns}) after " f"parent {parent.span_id} ({parent.end_time_ns}); " f"tool execution escaped its invocation window" ) ```