# Which invariants prevent OpenTelemetry GenAI span attributes from silently desynchronizing tool-call identity across agent turns **Date of Record:** 2026 November 29 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.agent.turn`, `gen_ai.conversation.id`) where a single logical agent turn fans out into multiple `execute_tool` spans correlated by tool-call ID. Does not apply to single-shot inference spans with no tool dispatch, nor to backend-side trace assembly where spans are already stitched by a deterministic parent. ## Core Distinction The distinction that matters is between **span-level traceability** and **turn-level causal identity**. OTel GenAI conventions give you a rich per-span vocabulary: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`, and so on. What the conventions do *not* enforce is that the `gen_ai.tool.call.id` emitted on an `execute_tool` span is the same identifier the model produced in the assistant message that requested the call, nor that the `gen_ai.agent.turn` counter on child spans matches the turn of the parent `chat` span. Those are *correlation invariants*, not attribute schema. The schema validates; the correlation silently rots. A trace can be 100% schema-conformant and still be causally wrong — every `execute_tool` span present and well-typed, but attributed to the wrong turn, or keyed by a locally-minted UUID that the model never saw. ## What Was Observed A tool-using agent (ReAct loop, 6–11 turns per task) emitted spans through an auto-instrumented SDK. The instrumentation wrapped the tool executor and generated `gen_ai.tool.call.id` from `uuid4()` at execution time — a fresh ID per invocation. The model's actual tool-call ID (returned by the provider API as `tool_call_id`) was recorded only in the assistant message payload, which was *not* captured as a span attribute because it exceeded the SDK's default attribute-size cap and was truncated by the batch span processor. Downstream, a verification agent replayed the trace to audit tool correctness. It matched `execute_tool` spans to assistant tool-call requests by joining on `gen_ai.tool.call.id`. The join returned zero rows — not an error, a clean empty set — because the executor-minted UUIDs never appeared in any assistant message. The auditor then fell back to positional matching (nth tool span ↔ nth tool call in the turn), which is valid *only* when tool calls execute sequentially and none are retried. Under parallel tool dispatch and one network-retry, positional matching shifted by one: the auditor attributed the result of `search_docs(query="refund policy")` to the model's request for `read_file(path="config.yaml")`. The audit passed. The agent had actually done the wrong thing in a way the trace could not show. The second observed failure was turn-counter skew. `gen_ai.agent.turn` was incremented in the orchestrator's loop variable, but child `execute_tool` spans were emitted from a worker thread that captured the loop variable by reference. Under concurrent turns (the orchestrator advanced the turn while a slow tool was still in flight), the tool span reported `turn=7` while its parent `chat` span reported `turn=6`. Token accounting aggregated by turn then double-counted the tool's `gen_ai.usage.input_tokens` into turn 7 and left turn 6 under-counted, which tripped a cost-anomaly alert that fired on the wrong turn and sent on-call to the wrong prompt. ## Condition of Validity The correlation invariant holds only when **all three** of the following are true simultaneously: 1. **ID provenance:** `gen_ai.tool.call.id` on every `execute_tool` span is byte-identical to the `tool_call_id` the model emitted in the requesting assistant message, captured *before* any executor-side transformation, and never regenerated. The executor must accept the ID as an input, not mint one. 2. **Turn binding:** `gen_ai.agent.turn` is captured by value at span creation (immutable snapshot), not read from a mutable loop variable at span-close time. Turn identity must be a property of the span's creation context, not its emission context. 3. **Truncation safety:** any attribute whose absence breaks a join (IDs, turn numbers, `gen_ai.conversation.id`) is exempt from the batch processor's size cap or is hashed deterministically rather than truncated. Truncating a UUID mid-string produces a *collision-prone* key that silently mis-joins. When any one fails, the trace remains schema-valid and the failure is silent: no validator rejects it, no span is dropped, and the only symptom is a downstream join that returns empty or shifted results. ## Decision Boundary The boundary is **whether trace correlation is treated as a schema problem or a causal-identity problem**. If your verification, cost attribution, or replay logic joins spans by any attribute, that attribute is load-bearing and must be governed by an invariant, not by convention defaults. Concretely: - If you only need to *count* tool calls or measure latency, schema conformance suffices; positional or count-based reasoning is adequate and the invariant above is over-engineering. - If you need to *attribute outcomes to specific model requests* (audit, replay, cost-per-turn, failure post-mortem), you are past the boundary and must enforce ID provenance and turn binding as hard invariants — a trace that fails them must be marked `unverifiable`, not silently accepted. The failure mode to design against is the **empty-join-that-looks-like-success**: an auditor that expects N matches, gets 0, and proceeds with a fallback heuristic rather than halting. The guardrail is to make correlation failure *loud* — a join returning fewer matches than expected `execute_tool` spans must raise, not degrade. ## Operational Effect Enforcing the invariant changes three things. First, the tool executor signature gains a mandatory `tool_call_id` parameter sourced from the model message, and the instrumentation refuses to emit an `execute_tool` span without it. Second, turn identity is captured via contextvars at span start, so concurrent turns cannot bleed. Third, the verification agent is rewritten to treat a short join as a hard error. The practical cost is one extra field threaded through the executor and a contextvar; the benefit is that trace-based audit becomes sound rather than plausible. Without it, every cost alert, every replay audit, and every "the agent did X" post-mortem rests on a join that may be silently returning the wrong rows — and the trace, being schema-valid, will never tell you. ```python from __future__ import annotations from dataclasses import dataclass class CorrelationInvariantError(RuntimeError): """Raised when a GenAI span's correlation attributes violate a load-bearing invariant.""" @dataclass(frozen=True) class ToolSpan: tool_call_id: str # gen_ai.tool.call.id agent_turn: int # gen_ai.agent.turn, captured at span start tool_name: str # gen_ai.tool.name @dataclass(frozen=True) class ModelToolRequest: tool_call_id: str # tool_call_id from the assistant message agent_turn: int def emit_execute_tool_span( request: ModelToolRequest, *, executor_minted_id: str | None, span_turn_at_close: int, ) -> ToolSpan: """Emit an execute_tool span, enforcing ID provenance and turn binding. The executor MUST NOT mint its own ID; it must echo the model's tool_call_id. The turn MUST be captured at span start, not read at close. """ if executor_minted_id is not None and executor_minted_id != request.tool_call_id: raise CorrelationInvariantError( f"tool_call_id provenance violated: model emitted {request.tool_call_id!r}, " f"executor minted {executor_minted_id!r}; join will silently fail." ) if span_turn_at_close != request.agent_turn: raise CorrelationInvariantError( f"agent_turn skew: span closed at turn {span_turn_at_close}, " f"request bound to turn {request.agent_turn}; cost attribution will mis-bucket." ) return ToolSpan( tool_call_id=request.tool_call_id, agent_turn=request.agent_turn, tool_name="", # populated by caller ) def verify_trace_correlation( requests: list[ModelToolRequest], spans: list[ToolSpan] ) -> None: """Auditor-side check: a short join is an error, not a fallback trigger.""" span_ids = {s.tool_call_id for s in spans} missing = [r.tool_call_id for r in requests if r.tool_call_id not in span_ids] if missing: raise CorrelationInvariantError( f"trace unverifiable: {len(missing)} tool requests have no matching span " f"(ids={missing[:3]}...); refusing positional fallback." ) for r, s in zip(sorted(requests, key=lambda x: x.tool_call_id), sorted(spans, key=lambda x: x.tool_call_id)): if r.agent_turn != s.agent_turn: raise CorrelationInvariantError( f"turn mismatch on {r.tool_call_id}: request turn {r.agent_turn} " f"vs span turn {s.agent_turn}" ) ```