# Which invariants prevent span-attribute corruption when OpenTelemetry GenAI semantic conventions are emitted mid-loop by an agent that mutates its own tool schema **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.*` semantic conventions, spec version ≥1.27) for tool calls, token accounting, and model attribution while the agent itself can rewrite its own tool manifest, system prompt, or model routing mid-execution. Does not apply to stateless single-turn inference where the span is closed before any tool result returns. ## Core Distinction The failure mode is not "missing spans" or "wrong span names." It is **attribute drift on an already-open span whose semantics were fixed at span start but whose referent changed before span end.** OTel GenAI conventions bind `gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.system`, and the tool identity (`gen_ai.tool.name`, `gen_ai.tool.call.id`) to the moment of span creation. An agent that, between span start and span end, (a) falls back to a different model, (b) renames or re-signs a tool, or (c) re-partitions a completion into a different token count than the one it started reporting, produces a span that is internally consistent as a record but *semantically false as an attribution*. Downstream cost accounting, model-quality regression detection, and tool-execution auditing all silently inherit the lie. The non-obvious part: the corruption is **invisible at the span level**. Each attribute is individually well-formed and within its type. The violation only exists in the *relation between span attributes and the events/child spans emitted inside the same trace*, and only manifests when a consumer joins on `gen_ai.tool.call.id` or `gen_ai.response.model` across the trace. ## What Was Observed A three-step agent loop: `plan → tool_call(search_index) → synthesize`. On step 2, the tool call exceeded a 4s deadline, the runtime retried against a secondary index backend registered under the *same* `gen_ai.tool.name` but a different `gen_ai.tool.description` hash and a different result schema. The retry succeeded at 6.1s. The parent `chat` span had `gen_ai.request.model = "model-a"`, but the runtime's fallback router swapped to `model-b` for the synthesis step *inside the same logical operation* because model-a's context was saturated. Resulting span tree (abridged): ``` chat (span A) gen_ai.request.model=model-a gen_ai.response.model=model-b └ execute_tool (span B) gen_ai.tool.name=search_index gen_ai.tool.call.id=call-7 (retry emitted as event on B, not as child span) └ chat (span C) gen_ai.request.model=model-b ``` Three independent invariant breaks, all individually well-formed: 1. **Model attribution split.** Span A reports `request.model=model-a` and `response.model=model-b`. Per convention this is legal (fallback is expected), but the *token counts* on A (`gen_ai.usage.input_tokens`, `output_tokens`) are summed across both models, so per-model cost attribution is unrecoverable from A alone. 2. **Tool identity aliasing.** Span B's `gen_ai.tool.name` is stable, but the retry event carries a different `gen_ai.tool.description` (and a different response schema). A consumer filtering traces by tool name sees one tool; a consumer filtering by description hash sees two. The `gen_ai.tool.call.id` was reused across the retry, so dedup by call-id undercounts executions. 3. **Token accounting non-additivity.** A's `output_tokens` = model-a tokens + model-b tokens, but `gen_ai.response.model` names only model-b. Any per-model token reconciliation (`sum(output_tokens) group by response.model`) overcounts model-b and drops model-a entirely. The trace passed schema validation. It failed a *reconciliation invariant*: `sum of child usage ≤ parent usage` held, but `sum of per-model usage == parent usage` did not, because the parent had no per-model breakdown. ## Condition of Validity The conventions remain sound only under the following invariant, which the spec states implicitly but does not enforce: > **Attribution closure invariant:** For every span S with `gen_ai.operation.name ∈ {chat, text_completion, execute_tool}`, the tuple `(gen_ai.request.model, gen_ai.response.model, gen_ai.usage.*, gen_ai.tool.name, gen_ai.tool.call.id)` must be constant across the full lifetime of S, OR S must be closed and a new sibling span opened for each change of any tuple member. Corollaries that agents routinely violate: - **C1 (model pinning):** A model fallback mid-span requires closing the current span and opening a new one with the new `request.model`. Reusing one span across a fallback breaks per-model token reconciliation. - **C2 (tool identity immutability):** `gen_ai.tool.call.id` must be unique per *execution attempt*. A retry against a differently-configured backend must mint a new call id and a new `execute_tool` span, even if `gen_ai.tool.name` is unchanged. Reusing the id across a schema change makes the trace unauditable. - **C3 (token additivity):** If a single span reports `output_tokens` that aggregate work from more than one model, the span MUST carry per-model breakdown via child spans or events; otherwise the aggregate is un-attributable and must not be emitted. The invariant is violated specifically when the agent's *runtime router* and its *span emitter* are not co-located — i.e., when the router can mutate model/tool choice between `span.start()` and `span.end()` without the emitter observing the mutation as a discrete event. ## Decision Boundary The agent must decide, at each mutation point (model fallback, tool retry, schema swap), between: - **Boundary A — close-and-reopen:** end the current span, start a sibling with the new attributes, propagate the same `trace_id` and a `parent_span_id` pointing at the enclosing logical operation. Preserves attribution closure at the cost of span cardinality (one logical op → N spans). - **Boundary B — event-annotate:** keep one span, but emit a `gen_ai.model.fallback` or `gen_ai.tool.retry` event carrying the *delta* (from-model, to-model, from-schema-hash, to-schema-hash) and a per-model token breakdown event. Preserves cardinality at the cost of requiring every consumer to read events, not just attributes. Boundary A is mandatory when the mutation changes `response.model` (C1) or the tool response schema (C2). Boundary B is permissible only for mutations that leave `request.model` and tool identity constant — e.g., a retry against the *same* backend config, where the only delta is latency. The decision is *not* free to the agent: it is determined by whether the mutation is **attribution-relevant** (changes the tuple) or **attribution-neutral** (changes only timing/retry count). Agents that treat all retries uniformly — either always close-and-reopen (span explosion, cost blowup) or always annotate (silent attribution loss) — fail one side of the boundary. ## Operational Effect Under the invariant, three downstream systems behave correctly: 1. **Cost reconciliation** (`sum(usage) group by response.model`) becomes exact, because no span aggregates two models. 2. **Tool-execution audit** (`count(distinct gen_ai.tool.call.id) by gen_ai.tool.name`) counts executions, not logical calls, and schema-hash joins on retries are recoverable. 3. **Model-quality regression** detects a fallback as a discrete span transition rather than a blended metric, so a model-a→model-b fallback that degrades quality is visible as a span-level signal, not averaged away. When the invariant is violated, the failure is **silent and additive**: each trace looks fine, but fleet-wide cost dashboards under-report the fallback model's spend, tool-audit counts undercount retries by the retry rate, and quality regressions from fallback are diluted by the fraction of traffic that never fell back. The corruption rate equals the fallback rate, which is exactly the rate at which you most need the data. The guardrail is a **span-emitter/router contract**: the router must publish mutation events to the emitter synchronously (before the mutation takes effect), and the emitter must enforce C1–C3 by closing the span on any attribution-relevant mutation. An agent that routes and emits from the same process without this contract will emit attribution-drifted spans under any load that triggers fallback. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class AttributionClosureViolation(RuntimeError): """Raised when a span's GenAI attribution tuple mutates mid-lifetime.""" pass @dataclass class GenAISpan: span_id: str operation_name: str request_model: str tool_name: Optional[str] = None tool_call_id: Optional[str] = None tool_schema_hash: Optional[str] = None output_tokens: int = 0 closed: bool = False _per_model_tokens: dict = field(default_factory=dict) def _attribution_tuple(self): return ( self.request_model, self.tool_name, self.tool_call_id, self.tool_schema_hash, ) def add_tokens(self, model: str, n: int) -> None: if self.closed: raise AttributionClosureViolation( f"span {self.span_id} closed; cannot add tokens" ) if model != self.request_model: # C1: a token contribution from a different model must not be # folded into a span pinned to request_model. raise AttributionClosureViolation( f"span {self.span_id} pinned to {self.request_model!r} " f"received tokens from {model!r}; close-and-reopen required" ) self.output_tokens += n self._per_model_tokens[model] = self._per_model_tokens.get(model, 0) + n def mutate_tool(self, new_name: str, new_schema: dict) -> None: new_hash = hashlib.sha256( repr(sorted(new_schema.items())).encode() ).hexdigest()[:12] if self.closed: raise AttributionClosureViolation( f"span {self.span_id} closed; cannot mutate tool identity" ) if self.tool_schema_hash is not None and new_hash != self.tool_schema_hash: # C2: schema change under a stable tool name / call id is an # attribution-relevant mutation. Must mint a new call id + span. raise AttributionClosureViolation( f"span {self.span_id} tool {self.tool_name!r} schema changed " f"{self.tool_schema_hash!r} -> {new_hash!r}; " f"retry must mint new gen_ai.tool.call.id and new span" ) self.tool_name = new_name self.tool_schema_hash = new_hash def close(self) -> dict: self.closed = True return { "span_id": self.span_id, "gen_ai.operation.name": self.operation_name, "gen_ai.request.model": self.request_model, "gen_ai.response.model": self.request_model, "gen_ai.usage.output_tokens": self.output_tokens, "gen_ai.tool.name": self.tool_name, "gen_ai.tool.call.id": self.tool_call_id, "_per_model_tokens": dict(self._per_model_tokens), } def reconcile(parent: dict, children: list[dict]) -> None: """Enforce C3: parent token total must equal sum of children, per model.""" child_by_model: dict = {} for c in children: for m, n in c["_per_model_tokens"].items(): child_by_model[m] = child_by_model.get(m, 0) + n parent_by_model = parent["_per_model_tokens"] if child_by_model != parent_by_model: raise AttributionClosureViolation( f"span {parent['span_id']} token attribution non-additive: " f"parent={parent_by_model} children={child_by_model}" ) ```