# What happens when an instance emits GenAI span attributes that violate the OTel semantic conventions' cardinality contract mid-trace **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans per the GenAI semantic conventions (v1.27+) where a single trace spans multiple LLM invocations, tool calls, and sub-agent handoffs. Does not apply to single-shot inference telemetry, nor to legacy non-OTel tracing shims that flatten agent state into flat log lines. ## Core Distinction The GenAI semantic conventions define `gen_ai.*` attributes with an implicit **cardinality contract**: a span represents *one* model invocation or *one* tool execution, and its identifying attributes (`gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.response.finish_reasons`) describe that single unit. The failure mode examined here is not missing attributes or wrong attribute names—those are caught by schema validators. It is **attribute cardinality collapse**: an agent framework that multiplexes several logical model calls into one span (or splits one call across several spans) while still emitting convention-shaped attributes. The trace remains schema-valid. Every span passes the semantic-convention linter. But the attribute values now describe a *set* where the convention's consumers assume a *scalar*. Downstream cost accounting, finish-reason classification, and token-budget enforcement all silently miscompute because they aggregate over attributes that were never designed to be aggregated. The non-obvious part: the OTel collector and backend accept these spans without error. The breakage is invisible at ingestion and only manifests in derived signals—billing dashboards, retry classifiers, and agent-budget governors—hours or days later. ## What Was Observed Consider a planner agent that, to save span overhead, wraps a *retry loop* around a single `gen_ai.chat` span. The inner code calls the model up to N times on rate-limit or validation failure, then returns the final response. The instrumentation emits: - `gen_ai.operation.name = "chat"` - `gen_ai.request.model = "gpt-4o"` (constant across retries) - `gen_ai.usage.input_tokens = ` - `gen_ai.usage.output_tokens = ` - `gen_ai.response.finish_reasons = ["stop"]` — the *final* attempt only - span status `OK` Three concrete distortions follow, each requiring a different consumer to detect: 1. **Token accounting drift.** The convention treats `gen_ai.usage.*` as per-invocation. A cost aggregator that sums usage across spans is now correct in total but wrong per-attempt: it cannot distinguish a single 4,000-token call from four 1,000-token retries. When the retry was caused by a prompt-injection rejection (the model emitted a poisoned tool call, the harness discarded it, retried), the discarded attempt's tokens are attributed to a successful, `OK`-status span. The poisoned attempt vanishes from the audit trail. 2. **Finish-reason laundering.** `gen_ai.response.finish_reasons` is defined to describe *why the emitted response terminated*. By emitting only the final attempt's `["stop"]`, the span erases intermediate `["content_filter"]` or `["length"]` terminations. A downstream safety monitor that greps for `content_filter` in finish reasons sees zero events, even though the retry loop was triggered by exactly that. This is the most dangerous distortion: it is a **negative-evidence fabrication**—the trace actively asserts that no filter fired, when one did. 3. **Operation-name ambiguity under fan-out.** The inverse case: a fan-out agent that issues K parallel model calls and merges them into one span sets `gen_ai.operation.name = "chat"` and a single `gen_ai.response.model`. When the K calls resolve to *different* model versions (A/B routing, or a fallback provider swap mid-fan-out), the span asserts a single `response.model` that no single call actually used. A model-quality regression detector keyed on `gen_ai.response.model` attributes the merged quality signal to the wrong model. The trigger condition in all three cases is identical: **the instrumentation's span boundary does not match the semantic convention's unit-of-attribution boundary**, but the attribute *names* match the convention exactly. The linter cannot see it because the linter checks attribute presence and type, not span-granularity correctness. ## Condition of Validity The cardinality contract holds—and the failure is bounded—only when all of the following are true. Violate any one and the invariant breaks: 1. **One span = one `gen_ai` operation.** If a span emits any `gen_ai.*` attribute, the span must represent exactly one model invocation or tool execution. Retries, fallbacks, and fan-out each require *child spans*, not merged attributes. 2. **`gen_ai.usage.*` is additive only across distinct spans, never within one.** A consumer may sum `usage.input_tokens` across spans in a trace; it may not interpret a single span's usage as a single-call cost. The convention's cost semantics are defined at the span level, and merging calls into one span destroys the per-call decomposition irrecoverably. 3. **`gen_ai.response.finish_reasons` is a complete multiset of terminations for the span's unit.** If a span represents one call, the list has one element. If an implementation merges calls, it *must* emit all finish reasons from all attempts—but since the convention's consumers assume one-call-per-span, the only safe resolution is to not merge. 4. **`gen_ai.response.model` is the model that produced the response, per span.** Under fan-out with heterogeneous routing, this forces per-child spans; there is no valid merged value. 5. **Status reflects the span's own unit.** A span that hides a `content_filter` rejection behind a successful retry is not `OK` in the sense the convention intends—its unit of work included a rejected generation. The `OK` status combined with the final-only finish reason is the specific fabrication. When these hold, downstream aggregation (cost, safety, quality) is sound because the span graph mirrors the actual call graph. When the instrumentation merges calls to reduce span volume, the invariant is violated and every derived signal is contaminated. ## Decision Boundary The operational decision is: **when an agent harness retries, falls back, or fans out, does it emit child spans, or does it collapse into the parent?** The boundary condition is the *first* retry or fan-out. Before it, a single span is correct. At the moment a second model call is issued under the same logical operation, the harness faces a fork: - **Emit a child span per attempt** (`gen_ai.chat` parent with `gen_ai.chat` children, or `gen_ai.chat` with `gen_ai.tool` children for tool retries). Cost, finish-reason, and model attributes stay per-call. Trace volume grows linearly with retries—acceptable, because retries are the signal you most need. - **Collapse into the parent.** Span count stays flat; every attribute becomes a lie of omission. This is the failure path. The decision boundary is sharp because there is no middle ground that preserves the contract. You cannot emit merged usage *and* per-attempt finish reasons on one span and expect consumers to reconcile them—the convention gives no disambiguator. A custom attribute like `gen_ai.retry.count` on a collapsed span does not repair the finish-reason laundering; it merely annotates it. A secondary boundary: **cross-agent handoff spans** (A2A). When agent A delegates to agent B via a tool call, the handoff must be its own span with `gen_ai.operation.name = "execute_tool"` (or the A2A convention's equivalent), and B's subsequent `gen_ai.chat` spans must be *children* of that handoff span, not siblings under A's root. If B's spans are emitted under A's span context without a linking span, the trace graph loses the delegation edge and a "which agent burned the budget" query returns the wrong agent. The invariant: **span parentage must mirror the delegation DAG**; a flattened trace with correct attributes but wrong parentage is still corrupt for any consumer that walks the tree. ## Operational Effect The downstream consequences are graded by how long detection takes: - **Immediate (seconds):** None. The collector accepts the spans. This is why the failure is insidious—the instrumentation "works." - **Hours:** Cost dashboards show per-span costs that don't reconcile with provider invoices, because merged-usage spans inflate individual span costs while the total is coincidentally correct. Finance flags a "variance" that engineers cannot locate, because the total matches. - **Days:** A safety review greps `gen_ai.response.finish_reasons` for `content_filter` and finds zero—concluding the model never triggered the filter. The retry loop that was *caused by* filter hits is invisible. A prompt-injection incident is reconstructed from provider-side logs instead of the agent's own trace, and the two disagree. - **Weeks:** A model-quality regression is attributed to model X because a fan-out span's `gen_ai.response.model` says X, when the actual degraded responses came from fallback model Y inside the same span. The wrong model gets rolled back; the regression persists. The architectural guardrail is a **span-granularity assertion at emission time**, not at ingestion. The instrumentation wrapper must assert that its span represents exactly one `gen_ai` operation before setting any `gen_ai.*` attribute; if a retry or fan-out is detected inside the wrapper, it must either open a child span or refuse to emit. This is enforceable in-process, where the harness knows whether it is on attempt 1 or attempt 3—information the collector never has. The invariant to encode: *a span that sets `gen_ai.usage.input_tokens` must have been constructed by exactly one model client call.* Any wrapper that can call the client more than once must delegate attribute-setting to per-call child spans. The following guard enforces the cardinality contract at the instrumentation boundary, raising before a collapsed span can be emitted: ```python from dataclasses import dataclass, field from typing import Any class GenAISpanCardinalityError(RuntimeError): """Raised when a span would violate the OTel GenAI cardinality contract: one span must represent exactly one model invocation or tool execution, and gen_ai.* attributes must describe that single unit only. """ @dataclass class GenAISpanGuard: operation_name: str model: str _call_count: int = 0 _finish_reasons: list[str] = field(default_factory=list) _input_tokens: int = 0 _output_tokens: int = 0 _response_models: set[str] = field(default_factory=set) def record_call( self, *, response_model: str, finish_reason: str, input_tokens: int, output_tokens: int, ) -> None: self._call_count += 1 self._finish_reasons.append(finish_reason) self._input_tokens += input_tokens self._output_tokens += output_tokens self._response_models.add(response_model) # Contract check: a span may describe exactly one call. if self._call_count > 1: raise GenAISpanCardinalityError( f"Span for operation={self.operation_name!r} model={self.model!r} " f"recorded {self._call_count} model calls. Retries/fallbacks/fan-out " f"must be emitted as child spans, not merged into one span; " f"merged usage={self._input_tokens}in/{self._output_tokens}out " f"and finish_reasons={self._finish_reasons} would launder " f"per-attempt terminations and misattribute cost." ) def assert_single_response_model(self) -> None: if len(self._response_models) > 1: raise GenAISpanCardinalityError( f"Span for operation={self.operation_name!r} observed multiple " f"response models {sorted(self._response_models)}. A single span " f"cannot carry a scalar gen_ai.response.model; split the fan-out " f"into child spans per model." ) def build_attributes(self) -> dict[str, Any]: self.assert_single_response_model() if self._call_count != 1: raise GenAISpanCardinalityError( f"Span for operation={self.operation_name!r} has {self._call_count} " f"calls; refusing to emit gen_ai.* attributes for a span that does " f"not represent exactly one invocation." ) return { "gen_ai.operation.name": self.operation_name, "gen_ai.request.model": self.model, "gen_ai.response.model": next(iter(self._response_models)), "gen_ai.response.finish_reasons": list(self._finish_reasons), "gen_ai.usage.input_tokens": self._input_tokens, "gen_ai.usage.output_tokens": self._output_tokens, } def emit_chat_span(guard: GenAISpanGuard, attempts: list[dict[str, Any]]) -> dict[str, Any]: """Emit attributes for a chat span from a list of raw attempts. The guard forces one-attempt-per-span; callers that pass multiple attempts get a cardinality error and must restructure to child spans. """ for attempt in attempts: guard.record_call( response_model=attempt["response_model"], finish_reason=attempt["finish_reason"], input_tokens=attempt["input_tokens"], output_tokens=attempt["output_tokens"], ) return guard.build_attributes() ```