# What happens when an instance emits GenAI span attributes that drift from the semantic conventions across a multi-turn agent trace **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) across multi-turn or multi-step traces where a single logical conversation is reconstructed from spans by a downstream observability or eval consumer. Does not apply to single-shot inference calls with no turn-to-turn correlation, nor to traces consumed only by humans reading a waterfall UI. ## Core Distinction The GenAI semantic conventions are a *schema for reconstruction*, not a logging format. The distinction that matters operationally is between **attribute presence** (a span carries `gen_ai.conversation.id`, `gen_ai.usage.input_tokens`, `gen_ai.request.model`) and **attribute coherence** (the set of attributes across all spans of a trace, when replayed in timestamp order, reconstructs one consistent logical conversation). Most agent runtimes get presence right and coherence wrong, because coherence is a *cross-span invariant* that no single span emission site can enforce locally. The specific non-obvious failure: an agent that mutates its own attribute-emission behavior mid-trace — because it changed model, changed tool, retried a turn on a fallback path, or compacted its context — produces a trace where every individual span is schema-valid but the *reconstructed* conversation is internally contradictory. Downstream consumers that aggregate by `gen_ai.conversation.id` silently merge turns that never belonged to the same logical exchange, or drop turns whose `gen_ai.request.model` changed mid-conversation but whose `gen_ai.conversation.id` did not. ## What Was Observed A multi-turn agent (turn budget ~12, tool-calling loop) was instrumented to emit one span per model invocation with `gen_ai.conversation.id` set from a session-scoped UUID, `gen_ai.request.model` from the model actually dispatched, and `gen_ai.usage.input_tokens` from the provider response. On turn 7 the primary model returned a 429 and the runtime's retry policy fell back to a smaller model for that single turn, then resumed the primary on turn 8. The emitted trace was: - Turns 1–6: `gen_ai.request.model = "primary-large"`, `conversation.id = S`, token counts consistent with a growing context. - Turn 7: `gen_ai.request.model = "fallback-small"`, `conversation.id = S`, `input_tokens` **dropped** ~40% versus turn 6 — because the fallback path re-serialized the message list with a tighter truncation policy. - Turn 8: `gen_ai.request.model = "primary-large"`, `conversation.id = S`, `input_tokens` **jumped** back above turn 6's level, because the primary path re-sent the full history. A downstream eval consumer that computed "context growth" as the delta of `gen_ai.usage.input_tokens` across consecutive spans of the same `conversation.id` recorded a −40% context *shrink* at turn 7 and a +90% *expansion* at turn 8. That consumer's anomaly detector fired, the trace was routed to a "context corruption" review queue, and the agent's turn-7 answer — which was correct — was quarantined as suspect. No span was malformed. The reconstruction was. The deeper issue surfaced on replay: because `gen_ai.request.model` is a per-span attribute, a consumer that groups by `(conversation.id, request.model)` to isolate per-model behavior split the trace into two conversation fragments and lost the causal edge from turn 7 to turn 8. The agent's actual behavior — a graceful degradation and recovery — was unrepresentable in the schema as emitted. ## Condition of Validity The invariant that makes a multi-turn trace reconstructable is: > For every trace `T` with a stable `gen_ai.conversation.id = S`, the ordered span sequence `s_1 … s_n` must satisfy: (a) the *logical* context passed to `s_{i+1}` is derivable from the emitted attributes of `s_i` and its ancestors; and (b) any per-span attribute that a consumer may use as a grouping key (`gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.system`) must either be constant across `S` or be accompanied by an explicit transition attribute marking the boundary. Condition (a) fails silently whenever the runtime's *internal* message list and its *emitted* token accounting diverge — which happens on every fallback, truncation, or compaction path. Condition (b) fails whenever a grouping key varies without a transition marker, which happens on every retry-with-fallback, tool-switch, or model-upgrade-mid-session. The convention does not currently require a transition marker, and this is the boundary. The schema is valid; the invariant is unenforced. ## Decision Boundary The runtime must choose, at each emission site, between two mutually exclusive disciplines: 1. **Conversation-stable emission**: `gen_ai.conversation.id` is the only grouping key; all other varying attributes are treated as *observations*, never as grouping keys, and the runtime emits an explicit `gen_ai.agent.turn.transition` event (or a child span) at every point where model, truncation policy, or tool set changes. Consumers are contractually forbidden from grouping by anything but `conversation.id`. 2. **Segment-stable emission**: every change of model or policy starts a *new* `gen_ai.conversation.id` (or a `gen_ai.conversation.parent.id` link), so each segment is internally homogeneous and the transition is a first-class edge. The boundary is crossed the moment the runtime emits a per-span attribute that a consumer *could* group by, without also emitting the edge that explains its variation. The failure is not in the attribute value; it is in the *unmarked variation*. ## Operational Effect Unmarked variation produces three concrete downstream failures: - **False anomaly signals**: token-count deltas across a fallback boundary look like context corruption. Review queues fill with correct traces. - **Silent fragmentation**: grouping by `(conversation.id, request.model)` splits one logical conversation into N fragments, each of which appears to terminate abnormally (no final assistant turn). - **Unreplayable causality**: an eval harness that replays the trace to score the agent cannot reconstruct *why* turn 8 re-expanded context, because the re-expansion is an artifact of the fallback's truncation policy, which is nowhere in the emitted attributes. The guardrail is a pre-emission coherence check: before any span is exported, the runtime asserts that every attribute it is about to emit as a potential grouping key either matches the conversation's established value or is accompanied by a transition marker in the same span. This is a cheap local check that enforces a global invariant. ```python from dataclasses import dataclass, field from typing import Optional # Attributes a downstream consumer may legitimately group by. GROUPING_KEYS = frozenset({ "gen_ai.request.model", "gen_ai.operation.name", "gen_ai.system", }) # Attributes that mark an explicit, explained transition. TRANSITION_MARKERS = frozenset({ "gen_ai.agent.turn.transition", "gen_ai.conversation.parent.id", }) class TraceCoherenceError(RuntimeError): """Raised when a span would break the multi-turn reconstruction invariant.""" @dataclass class ConversationState: conversation_id: str established: dict = field(default_factory=dict) # grouping key -> value def emit_span( state: ConversationState, attributes: dict, *, turn_index: int, ) -> dict: """Validate and stamp a GenAI span before export. Enforces: every grouping key either matches the conversation's established value, or the span carries an explicit transition marker. """ if attributes.get("gen_ai.conversation.id") != state.conversation_id: raise TraceCoherenceError( f"turn {turn_index}: conversation.id mismatch " f"({attributes.get('gen_ai.conversation.id')!r} != " f"{state.conversation_id!r}); refusing cross-conversation merge" ) has_marker = bool(TRANSITION_MARKERS & attributes.keys()) for key in GROUPING_KEYS & attributes.keys(): current = attributes[key] prior: Optional[str] = state.established.get(key) if prior is None: state.established[key] = current continue if current != prior and not has_marker: raise TraceCoherenceError( f"turn {turn_index}: grouping key {key!r} changed " f"{prior!r} -> {current!r} without a transition marker; " f"this trace would fragment or mis-aggregate downstream. " f"Emit one of {sorted(TRANSITION_MARKERS)} on this span, " f"or start a new conversation.id segment." ) if current != prior and has_marker: # Transition is explained; update the established baseline. state.established[key] = current return {"turn": turn_index, **attributes} # --- Failure trace reproduction ------------------------------------------- def replay_fallback_trace() -> None: state = ConversationState(conversation_id="S") turn6 = {"gen_ai.request.model": "primary-large", "gen_ai.usage.input_tokens": 18000} emit_span(state, {"gen_ai.conversation.id": "S", **turn6}, turn_index=6) # Turn 7: fallback model, truncated context, NO transition marker. turn7 = {"gen_ai.request.model": "fallback-small", "gen_ai.usage.input_tokens": 10800} emit_span(state, {"gen_ai.conversation.id": "S", **turn7}, turn_index=7) if __name__ == "__main__": try: replay_fallback_trace() except TraceCoherenceError as e: print(f"BLOCKED before export: {e}") ```