# In what scenarios must an instance treat OpenTelemetry GenAI span attributes as an unreliable correlation key across tool-call boundaries **Date of Record:** 2026 November 24 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) and use span attributes as the join key for reconstructing per-tool-call token/cost attribution. Does not apply to single-shot LLM calls with no tool loop, nor to traces where a single span covers an entire agent turn. ## Core Distinction The GenAI semantic conventions define *what to record*, not *what is unique*. `gen_ai.tool.call.id` is populated from the model's own tool-call identifier, which is a probabilistic artifact: it is regenerated on retry, absent on some providers, and collides across parallel tool calls when the model emits structurally identical calls in one response. Token usage attributes (`gen_ai.usage.*`) are attached to the *LLM span*, not the *tool span*, and are cumulative across all tool calls in a single model response. The distinction that matters operationally: a span attribute is a *descriptive annotation of one emission*, whereas cost attribution requires a *stable identity across emissions*. Conflating the two produces silent double-counting or orphaned cost whenever the agent retries, parallelizes, or resumes a tool loop mid-turn. ## What Was Observed An agent running a three-tool plan (`search`, `fetch`, `summarize`) emitted a parent `invoke_agent` span with child `chat` spans and grandchild `execute_tool` spans. On a transient 429 from the `fetch` backend, the agent's retry wrapper re-issued the tool call. The retry reused the same `gen_ai.tool.call.id` (because the wrapper copied the request object verbatim) but the second `execute_tool` span carried a fresh `trace_id`/`span_id` pair. Downstream, a cost correlator joined `execute_tool` spans to `chat` spans on `gen_ai.tool.call.id`. Result: the two `fetch` spans both matched the single `chat` span that requested `fetch`, and the `chat` span's `gen_ai.usage.output_tokens` (which included the tool-call emission for *both* the initial and the retried call, since the model was re-invoked) was attributed twice. The dashboard showed `fetch` consuming 2× its real token cost and `summarize` consuming zero — because the retry shifted the model's next response to a new `chat` span whose tool-call id was regenerated with a different casing (`call_AbC` vs `call_abc`), breaking the join entirely and orphaning the `summarize` cost. The failure is not the retry. The failure is that the correlator assumed `gen_ai.tool.call.id` is a primary key. It is a *hint* with three independent invalidation modes: (1) regeneration on model re-invocation, (2) case/normalization drift across providers, (3) absence when the provider does not surface tool-call ids at all (some OpenAI-compatible endpoints omit them, leaving the attribute empty on every tool span — and empty string joins to empty string, collapsing all tool calls into one bucket). ## Condition of Validity The invariant that makes `gen_ai.tool.call.id` a valid join key is: **the id must be minted exactly once per logical tool invocation and propagated unchanged through every retry, every parallel branch, and every resume.** This holds only when the agent runtime owns id generation and injects it into the span *before* the tool executes, treating the model's emitted id as a non-authoritative suggestion. It does **not** hold when: - The id is read from the model response and copied to the span (regeneration on retry breaks it). - Parallel tool calls are dispatched from a single model response and the model emits duplicate ids (collision collapses distinct calls). - The agent resumes from a checkpoint and re-emits the span without the original id (resume produces a new id for the same logical call). - The provider omits the id (empty-attribute collapse). Token correlation is valid only under a *second, independent* invariant: `gen_ai.usage.*` on a `chat` span must be attributed to the set of tool calls *whose results were consumed by that same model response*, which requires an explicit parent-child edge (`chat` span → `execute_tool` span via `parent_span_id`), not an attribute join. Attribute joins are always suspect because attributes are flat and unordered; parent edges are structural and ordered. ## Decision Boundary The boundary is: **join on structure, annotate with attributes.** Concretely: - **Use `parent_span_id` / `trace_id` as the correlation key** for cost attribution. The `execute_tool` span's parent is the `chat` span that requested it; that edge is emitted by the runtime, not the model, and survives retries because the retry wrapper re-parents under the same `chat` span (or under a new `chat` span that is itself a child of the same `invoke_agent` span). - **Use `gen_ai.tool.call.id` only as a display annotation**, never as a key. If you must join on it, first normalize (lowercase, strip) and then *validate uniqueness within the parent `chat` span*; if the id is empty or non-unique, fall back to positional index within the `chat` span's child list. - **Treat `gen_ai.usage.*` as turn-scoped, not call-scoped.** A single `chat` span's output tokens cover *all* tool-call emissions in that response. Per-tool cost must be derived by *distributing* the `chat` span's usage across its child `execute_tool` spans (evenly, or by a weight you record explicitly), never by reading a per-tool token attribute — because no such attribute exists in the convention. - **On resume, re-mint the id deterministically** from `(trace_id, logical_call_index)` so a resumed call produces the same id as the original, and emit a `resume=true` span event so the correlator can dedupe. The boundary condition to detect: any `execute_tool` span whose `gen_ai.tool.call.id` is empty, or whose id appears more than once among siblings under the same `chat` span, or whose `parent_span_id` points to a `chat` span that has already been closed by a prior `execute_tool` sibling (indicating a retry re-parented under a stale chat span). Any of these three is a signal that attribute-join cost attribution is unsound for this trace. ## Operational Effect When the invariant is violated, the observable symptoms are: cost dashboards that sum to more than total billed tokens (double-counting on retry), per-tool cost that is zero for tools that ran (orphaned by id regeneration), and — most insidiously — a *stable but wrong* attribution that never triggers an alert because the totals reconcile against the model's own usage report while the per-tool breakdown is silently permuted. The agent's self-reported cost telemetry becomes an unreliable narrator: it will confidently report that `fetch` is the expensive step when the tokens were actually spent on `summarize`. Any downstream optimization loop (tool selection, prompt trimming, budget enforcement) that reads this telemetry will optimize the wrong tool. The guardrail is structural: cost attribution must be computed from span parent edges, with `gen_ai.tool.call.id` demoted to an annotation and validated for uniqueness before use, and any trace failing the three-way check above must be flagged `attribution_unsound` rather than silently aggregated. ```python from dataclasses import dataclass, field from typing import Optional class UnsoundAttributionError(RuntimeError): """Raised when GenAI span attributes cannot be trusted as a cost-correlation key.""" pass @dataclass class ToolSpan: span_id: str parent_span_id: str tool_call_id: Optional[str] tool_name: str is_retry: bool = False @dataclass class ChatSpan: span_id: str input_tokens: int output_tokens: int children: list = field(default_factory=list) def attribute_cost(chat: ChatSpan, tool_spans: list[ToolSpan]) -> dict[str, float]: """ Distribute a chat span's output tokens across its child tool spans. Refuses to use gen_ai.tool.call.id as a join key; uses parent_span_id only. """ children = [t for t in tool_spans if t.parent_span_id == chat.span_id] if not children: return {} # Guard 1: empty tool_call_id means the provider omitted it -> attribute join would collapse. if any(t.tool_call_id in (None, "") for t in children): raise UnsoundAttributionError( f"chat span {chat.span_id}: empty gen_ai.tool.call.id on child tool span; " "attribute join is unsound, refusing to attribute" ) # Guard 2: duplicate ids among siblings -> collision, cannot key on attribute. ids = [t.tool_call_id.lower() for t in children] if len(set(ids)) != len(ids): raise UnsoundAttributionError( f"chat span {chat.span_id}: duplicate gen_ai.tool.call.id among siblings " f"{ids}; attribute join is unsound" ) # Guard 3: retry re-parented under a stale chat span -> double attribution. if any(t.is_retry for t in children): raise UnsoundAttributionError( f"chat span {chat.span_id}: retry child detected; re-parent retries under " "the originating chat span before attributing" ) # Sound path: structural distribution across children, id used only as label. share = chat.output_tokens / len(children) return {t.tool_call_id: share for t in children} ```