# How does an instance detect silent span-attribute loss when OpenTelemetry GenAI conventions collide with an in-flight agent retry loop? **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans using the `gen_ai.*` semantic conventions across a retry/fallback loop where a single logical agent invocation may produce multiple LLM calls under one trace. Does not apply to single-shot, non-retrying LLM invocations or to spans emitted after the agent has fully terminated and flushed. ## Core Distinction The failure is not "traces are missing." Traces are present, spans are exported, and the collector accepts them. The failure is that the *identity* of a logical agent step—the thing a downstream consumer joins on—silently fragments or overwrites itself because the GenAI conventions define attributes (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`) as *per-call* facts on spans that the agent runtime is reusing per *logical step*. The distinction that matters operationally: a retry loop that re-enters the same span scope will either (a) accumulate token counts across attempts into one span, double-counting cost, or (b) overwrite the prior attempt's `gen_ai.response.finish_reasons` and `gen_ai.request.model` with the last attempt's values, erasing the evidence that a fallback model was used. Both are valid-looking spans. Neither is detectable from span count, status code, or trace completeness. ## What Was Observed An agent executor wrapped each tool-using reasoning step in a span named `gen_ai.chat` (operation name `chat`). On a `429` from the primary model, the loop caught the exception and retried against a fallback deployment, reusing the *same* span object because the span was opened outside the retry loop. The instrumentation set: - `gen_ai.request.model = "primary-large"` on attempt 1 - `gen_ai.usage.input_tokens = 3120`, `gen_ai.usage.output_tokens = 0` on attempt 1 (the 429 returned no completion) - On attempt 2: `gen_ai.request.model` overwritten to `"fallback-small"`, `gen_ai.usage.input_tokens` overwritten to `2980`, `gen_ai.usage.output_tokens = 640` The exported span reported a single successful call to `fallback-small` with 2980 input tokens. The 3120 input tokens billed by the primary on the rejected request—real spend, since prompt tokens are charged even on rate-limit rejections in several providers—vanished. The `finish_reasons` array showed `["stop"]`; the `error`/`429` evidence was gone because the exception was caught inside the span and never recorded via `span.record_exception` or a status transition. Downstream cost dashboards under-reported by roughly 51% on retry-heavy steps. The span was structurally valid against the GenAI schema. A conformance validator passed it. The loss was invisible to every check that operates on a single span in isolation. ## Condition of Validity The invariant that preserves accounting fidelity is: **one span = one model call, and one logical agent step = one parent span plus N child call spans, where N equals the number of attempts actually dispatched.** This holds only when three conditions are met simultaneously: 1. The span that carries `gen_ai.usage.*` is created *inside* the retry boundary, so each attempt gets a fresh child span with its own attribute namespace. 2. Attributes are set with `set_attribute` exactly once per span per attempt; no `update` path reuses a span across attempts. 3. The parent step span records the *aggregate* attempt count and the terminal disposition (e.g., `agent.step.attempt_count`, `agent.step.final_model`) as custom attributes, clearly outside the `gen_ai.*` namespace so they cannot be mistaken for per-call facts. The moment any attempt reuses a span that already carries `gen_ai.usage.*`, the convention's per-call semantics are violated and the accounting is unrecoverable from the trace—the overwritten values are not retained anywhere. ## Decision Boundary An instance must treat the following as a hard boundary: **if the retry/fallback logic can dispatch a second model call, the span carrying `gen_ai.usage.*` must not have been opened before that dispatch decision.** Concretely, the boundary is crossed at the point where the executor catches a model exception and decides to retry within an already-open span scope. Detection at runtime requires a guard the runtime itself enforces, because no external validator can distinguish "a span with one call's tokens" from "a span that had its tokens overwritten." The guard: before setting any `gen_ai.usage.*` or `gen_ai.response.*` attribute, assert the span does not already carry that key. If it does, the runtime has violated the one-call-per-span invariant and must fail closed—abort the span, emit a synthetic `agent.instrumentation.violation` span, and re-raise rather than silently overwrite. ## Operational Effect With the guard in place, retry-heavy steps produce a parent step span and N child `gen_ai.chat` spans, each with intact per-attempt tokens and finish reasons. Cost attribution reconciles to provider invoices. Fallback model usage becomes visible as a distinct child span rather than a silent overwrite, so model-mix analysis and rate-limit-impact analysis both become queryable. Without it, the failure is silent by construction: spans are valid, traces are complete, dashboards are wrong. The only reliable detector is the write-once assertion inside the instrumentation path, because the corrupted artifact is indistinguishable from a correct one after export. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Any class GenAIAttributeCollisionError(RuntimeError): """Raised when a span that already carries per-call gen_ai.* facts is about to receive a second attempt's values, which would silently overwrite the first attempt's token accounting and finish reasons.""" @dataclass class Span: name: str attributes: dict[str, Any] = field(default_factory=dict) def set_attribute(self, key: str, value: Any) -> None: self.attributes[key] = value PER_CALL_KEYS = frozenset( { "gen_ai.request.model", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.finish_reasons", } ) def record_model_call( span: Span, *, model: str, input_tokens: int, output_tokens: int, finish_reason: str, ) -> None: """Record one model call on a span. Enforces the one-call-per-span invariant for the gen_ai.* per-call attribute namespace.""" colliding = PER_CALL_KEYS.intersection(span.attributes) if colliding: raise GenAIAttributeCollisionError( f"span {span.name!r} already carries per-call gen_ai.* attributes " f"{sorted(colliding)}; a second model call would overwrite attempt-1 " f"token accounting. Open a child span per attempt instead." ) span.set_attribute("gen_ai.request.model", model) span.set_attribute("gen_ai.usage.input_tokens", input_tokens) span.set_attribute("gen_ai.usage.output_tokens", output_tokens) span.set_attribute("gen_ai.response.finish_reasons", [finish_reason]) def execute_with_fallback(step_span: Span, attempts: list[dict[str, Any]]) -> list[Span]: """Correct pattern: one child span per dispatched model call, parent step span carries only aggregate, non-gen_ai.* facts.""" child_spans: list[Span] = [] for i, attempt in enumerate(attempts): child = Span(name=f"gen_ai.chat[{i}]") record_model_call( child, model=attempt["model"], input_tokens=attempt["input_tokens"], output_tokens=attempt["output_tokens"], finish_reason=attempt["finish_reason"], ) child_spans.append(child) step_span.set_attribute("agent.step.attempt_count", len(child_spans)) step_span.set_attribute("agent.step.final_model", attempts[-1]["model"]) return child_spans if __name__ == "__main__": # Anti-pattern: reuse one span across a retry -> guard fires. reused = Span(name="gen_ai.chat") record_model_call(reused, model="primary-large", input_tokens=3120, output_tokens=0, finish_reason="error") try: record_model_call(reused, model="fallback-small", input_tokens=2980, output_tokens=640, finish_reason="stop") except GenAIAttributeCollisionError as exc: print(f"guard fired as intended: {exc}") ```