# When must an instance refuse to emit a GenAI span: attribute cardinality collapse at the `gen_ai.input.messages` / `gen_ai.output.messages` boundary **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime instrumenting LLM calls and tool invocations with OpenTelemetry GenAI semantic conventions (v1.29+), specifically the point at which `gen_ai.input.messages` and `gen_ai.output.messages` are serialized onto a span. Does not apply to plain request/response HTTP spans or to metrics-only instrumentation. ## Core Distinction The GenAI semantic conventions draw a distinction that is easy to miss: **span attributes are metadata about an operation; message content is the operation's payload.** `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, and `gen_ai.response.finish_reasons` are low-cardinality, bounded-shape attributes. `gen_ai.input.messages` and `gen_ai.output.messages` are, by contrast, *unbounded, high-cardinality, schema-drifting JSON blobs* — arrays of role/content parts that can each contain arbitrary tool-call arguments, base64 image parts, and full retrieved-context dumps. The convention permits emitting these payload attributes, but it does not bound them. The boundary condition is this: **an instance must refuse to emit a GenAI span whose message-payload attributes exceed the exporter's per-span attribute budget, because a truncated or partially-serialized message array is not a smaller truth — it is a silently corrupted record that downstream evaluation, replay, and distillation pipelines will treat as complete.** The invariant is *payload atomicity*: either the full message array is present and parseable, or the span is emitted without payload attributes and flagged as such. ## What Was Observed A tool-using agent (ReAct-style loop, ~9 turns) was instrumented so that each LLM call produced a span with `gen_ai.input.messages` set to the full conversation array and `gen_ai.output.messages` set to the model's reply, including `tool_calls` parts. The span was created with `start_as_current_span` and attributes were set *incrementally*: role and content were added per-message inside the loop, then the span ended. Failure trace, observed on a long-context turn: 1. The agent's context had grown to ~140 messages, several containing 4–8 KB tool results (file reads, search dumps). 2. The OTel SDK's default `SpanLimits` bounded attribute *count* (128) and attribute *value length* (default 1024 bytes for string values in older SDKs, configurable via `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`). 3. The instrumentation set `gen_ai.input.messages` as a single JSON string. The SDK silently truncated the value at the length limit. The span exported with a JSON string ending mid-token: `...{"role":"tool","content":"{\"path\":\"/src/ma`. 4. No error was raised. `span.set_attribute` returned normally. The span status was `UNSET`. 5. Downstream, the eval pipeline's JSON parser caught the truncation and *dropped the whole span's payload*, but the trace-level aggregator counted the span as a successful LLM call with `gen_ai.usage.input_tokens` intact. Token accounting and payload accounting diverged by an order of magnitude. 6. A replay harness that reconstructs conversations from spans produced a conversation with a tool result whose content was the string `{"path":"/src/ma` — and the model, when replayed, hallucinated a plausible file body to complete it. The replay "passed" because no assertion checked content integrity. The non-obvious part: the truncation is *not* a per-attribute failure the SDK reports. The SDK enforces limits by truncating string values, and the truncation is invisible to the caller. The instrumentation code believed it had recorded the full conversation. ## Condition of Validity The invariant holds — payload attributes are safe to emit — only when all of the following are true: - **Size is measured before emission, not after.** The instrumentation serializes the message array to a string and checks `len(serialized.encode("utf-8"))` against the effective limit *before* calling `set_attribute`. The effective limit is `min(OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, exporter_max_attribute_value_length, backend_ingest_limit)` — the minimum across the whole pipeline, not the SDK default. - **The serialization is canonical and re-parseable.** The same serializer produces the value and the validation parse; a value that fails to round-trip is not emitted. - **The span carries an explicit completeness marker.** A boolean attribute (e.g., `gen_ai.messages.complete`) distinguishes "payload present and whole" from "payload omitted by policy." Without it, absence is ambiguous between "not instrumented" and "dropped for size." - **Truncation is never silent.** If a payload exceeds budget, the instrumentation must *omit the payload attribute entirely* and set the completeness marker false, rather than emitting a truncated string. A truncated message array is worse than no message array because it is indistinguishable from a complete one at parse time. When any of these is false, the span is not a valid record and must not be emitted as if it were. ## Decision Boundary The decision at each span close is a three-way branch, not a two-way one: - **Emit full payload:** serialized size ≤ effective limit *and* round-trip parse succeeds. Set `gen_ai.messages.complete = true`. - **Emit metadata-only span:** serialized size > effective limit, or serialization raises. Omit `gen_ai.input.messages` / `gen_ai.output.messages`, set `gen_ai.messages.complete = false`, and set an attribute recording the *actual* byte size and the limit that was exceeded. This preserves the token/usage/timing record without corrupting it. - **Refuse the span:** the serializer itself is non-deterministic or the message array contains a part type the schema version does not define (e.g., a provider-specific content part the convention has not mapped). In this case the span must not be emitted with payload attributes at all, because there is no valid serialization to validate against. Emitting a best-effort serialization here produces a record whose schema drifts per provider — the exact failure the conventions exist to prevent. The boundary is *not* "size > limit → truncate." It is "size > limit → degrade to metadata-only, and mark the degradation." The refusal case is reserved for schema-invalid payloads, where degradation is not possible because the payload cannot be faithfully represented. ## Operational Effect With the invariant enforced, three properties hold that did not hold before: 1. **Token accounting and payload accounting stay coupled.** A span with `gen_ai.messages.complete = false` is a known-partial record; the eval pipeline can exclude it from content-based metrics while still counting its usage tokens. The divergence observed above (span counted, payload dropped silently) becomes a first-class, queryable state. 2. **Replay harnesses can gate on completeness.** A replay that reconstructs conversations filters on `gen_ai.messages.complete = true`; a replay that needs the full context for a subset of turns fetches the payload from the agent's own checkpoint store using the span's trace/span ID as the key, rather than trusting the span to carry it. The span becomes an *index* into durable state, not a substitute for it. 3. **Cardinality is bounded at the exporter.** Because oversized payloads never reach the exporter as truncated strings, backend attribute-cardinality explosions from near-identical-but-truncated message blobs stop; the metadata-only spans are low-cardinality by construction. The cost is that some spans no longer carry their payload. That is the correct trade: a trace with a marked hole is auditable; a trace with an unmarked truncation is a liability that surfaces as a hallucination during replay, far from the instrumentation that caused it. ```python import json from typing import Any class PayloadAtomicityError(RuntimeError): """Raised when a GenAI message payload cannot be emitted atomically.""" pass def serialize_messages(messages: list[dict[str, Any]], *, schema_version: str, max_bytes: int) -> tuple[str | None, bool]: """ Returns (serialized_payload_or_None, complete_flag). Raises PayloadAtomicityError if the payload is schema-invalid and therefore cannot be faithfully represented even as a degraded record. """ allowed_part_types = {"text", "tool_call", "tool_result", "image"} for msg in messages: for part in msg.get("parts", []): if part.get("type") not in allowed_part_types: raise PayloadAtomicityError( f"unmapped content part type {part.get('type')!r} " f"under schema {schema_version}; refusing span" ) try: serialized = json.dumps(messages, separators=(",", ":"), sort_keys=True) except (TypeError, ValueError) as exc: raise PayloadAtomicityError(f"non-serializable message array: {exc}") from exc if len(serialized.encode("utf-8")) > max_bytes: # Degrade to metadata-only; never emit a truncated payload. return None, False # Round-trip validation: a value that cannot be re-parsed is not emitted. try: json.loads(serialized) except json.JSONDecodeError as exc: raise PayloadAtomicityError(f"round-trip parse failed: {exc}") from exc return serialized, True def emit_genai_span(span, messages: list[dict[str, Any]], *, schema_version: str, max_bytes: int) -> None: payload, complete = serialize_messages( messages, schema_version=schema_version, max_bytes=max_bytes ) span.set_attribute("gen_ai.messages.complete", complete) if payload is not None: span.set_attribute("gen_ai.input.messages", payload) else: span.set_attribute( "gen_ai.messages.omitted_bytes", len(json.dumps(messages, separators=(",", ":")).encode("utf-8")), ) span.set_attribute("gen_ai.messages.limit_bytes", max_bytes) ```