# Which invariants prevent GenAI span attribute cardinality explosion from silently corrupting agent handoff traces **Date of Record:** 2026 November 22 **Scope:** Applies to agent systems that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) across model invocations, tool calls, and inter-agent handoffs, where span attributes carry per-call payload fragments (prompts, tool args, handoff context). Does not apply to pure metric/log pipelines or to spans emitted only at the root orchestration layer with no per-invocation child spans. ## Core Distinction The GenAI semantic conventions define attributes such as `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.tool.name`, and `gen_ai.agent.id` as *descriptive* metadata. Operators routinely extend these with *content-bearing* attributes — `gen_ai.prompt`, `gen_ai.completion`, tool argument blobs, and handoff payload digests — because the trace is the only place the reasoning chain is observable. The failure boundary is not "attributes get large." It is that **span attribute sets are immutable after `span.end()`, and the OTel SDK's attribute-value truncation and the collector's cardinality limits are applied independently and non-atomically.** A handoff span can therefore record a `gen_ai.agent.id` that survived truncation while the `gen_ai.handoff.context_hash` attribute it was supposed to be paired with was dropped by a limit applied downstream — producing a trace that *looks* complete (valid span, valid agent id, valid parent linkage) but whose content-integrity invariant is silently broken. The distinction that matters: an *absent* span is a detectable gap; a *present-but-inconsistent* span is a poisoned ground truth that downstream replay, audit, and distillation consume as if authoritative. ## What Was Observed A three-agent pipeline (planner → executor → auditor) emitted handoff spans at each `transfer_to_*` boundary. Each handoff span carried: `gen_ai.agent.id` (sender), `gen_ai.agent.handoff.target` (receiver), `gen_ai.handoff.context_hash` (a SHA-256 over the serialized handoff state), and `gen_ai.handoff.context` (the full serialized state, capped at ~8 KB by convention). Under load, the executor's handoff span to the auditor exhibited the following: - The full `gen_ai.handoff.context` attribute exceeded the OTel default attribute-value length limit (the SDK truncates string attribute values at a configured `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`, commonly 4096) and was truncated mid-JSON, yielding an unparseable string. - The collector's `attributes` processor had a `limit` action configured (e.g., `limit: 64` attributes per span) and dropped the *last-declared* attributes once the limit was hit — which, given attribute ordering is not guaranteed stable across SDK versions, was sometimes `gen_ai.handoff.context_hash` and sometimes `gen_ai.usage.output_tokens`. - The auditor agent, on receiving the trace via its trace-context propagation, read `gen_ai.handoff.context_hash` to verify state continuity against its own received state. When the hash attribute was dropped, the auditor's verification step treated "no hash present" as "hash matches" (a permissive default in the verification code), so the continuity check passed vacuously. - Result: the trace showed a clean three-span chain with matching sender/target agent ids and a passing auditor verdict, but the actual handoff state had diverged (the executor had truncated its own context before serialization to fit the 8 KB cap, dropping the final tool-call result that the auditor needed to confirm). The trace was the *evidence of correctness* and the evidence was fabricated by the observability layer, not the agent. The critical observation: the divergence was invisible at every individual layer. The SDK truncated correctly per its config. The collector enforced its limit correctly. The auditor's permissive default was locally reasonable. The failure only exists in the *composition* of these three non-atomic contracts, and it manifests as a span that is structurally valid but semantically false. ## Condition of Validity The invariant that must hold for a handoff span to be trustworthy as continuity evidence is: > For any handoff span `S`, if `S` is emitted with a content-integrity attribute set `C = {context_hash, context_length, context_digest_algo}`, then either *all* of `C` are present and internally consistent with the recorded `gen_ai.handoff.context`, or `S` is marked with an explicit `gen_ai.handoff.integrity = "degraded"` attribute and the auditor MUST treat the handoff as unverified. This condition is valid only when: 1. The SDK attribute-length limit and the collector attribute-count limit are *coordinated* — the emitting agent must know the effective downstream limits before deciding whether to emit content or a digest. 2. Attribute ordering is not relied upon for correctness (i.e., no limit policy that drops "last" attributes can be trusted to preserve a specific attribute). 3. The receiving agent's verification logic uses a *fail-closed* default: absent integrity attributes ⇒ unverified, never ⇒ verified. It is **not** valid when the trace is used only for aggregate metrics (token counts, latency) where per-span content integrity is irrelevant, or when a separate out-of-band channel (e.g., a signed state-transfer message) carries the authoritative handoff payload and the span is purely decorative. ## Decision Boundary The boundary between "trace is evidence" and "trace is telemetry" determines the required guardrail: - **If the trace is the sole record of handoff state** (no out-of-band transfer), then the emitting agent MUST compute the digest *before* serialization, emit `gen_ai.handoff.context_hash` and `gen_ai.handoff.integrity` as *first* attributes (and configure the collector with an explicit `include`/`exclude` allowlist rather than a count-based `limit` drop), and the receiver MUST fail closed on any missing integrity attribute. - **If the trace is decorative** (authoritative state travels out-of-band, e.g., in the A2A message body or an MCP resource), then content attributes should be omitted entirely and only `gen_ai.agent.id`, `gen_ai.agent.handoff.target`, and a `gen_ai.handoff.correlation_id` that joins to the out-of-band record should be emitted. Emitting truncated content in this case is strictly harmful: it creates a second, weaker, and now-ambiguous source of truth. The decision point is per-span, not per-system. A single agent may emit decorative spans for high-volume tool calls and evidentiary spans for handoffs; the invariant applies only to the latter, and the span MUST self-declare which it is via `gen_ai.handoff.integrity ∈ {"verified", "degraded", "decorative"}`. ## Operational Effect When the invariant is enforced: - Truncation becomes *observable*: a degraded handoff span carries `gen_ai.handoff.integrity = "degraded"` and the auditor's continuity check fails closed, surfacing the divergence as a first-class audit event rather than a silent pass. - Replay and distillation pipelines can filter on `integrity = "verified"` before treating a trace as ground truth, preventing the poisoned span from being learned as a correct handoff pattern. - Cardinality limits become a *capacity planning* concern (how many verified handoffs can I retain) rather than a *correctness* concern (did my evidence survive). When the invariant is violated (the observed case): - The trace is a false negative for divergence: the auditor's verdict is "pass" on a handoff that actually lost the final tool-call result. - Downstream episodic-to-semantic distillation ingests the truncated context as a complete example, teaching the distilled policy to elide final tool results at handoff boundaries — a compounding failure that surfaces only after several distillation cycles, far from the original truncation. - The failure is non-reproducible from the trace alone, because the trace is the artifact that was corrupted; root-causing requires the out-of-band logs that the team believed were redundant. The operational rule: **never let the observability layer's limits be the arbiter of agent-state continuity.** Compute integrity digests before any serialization that can truncate, declare integrity status explicitly on the span, and make every consumer of the span fail closed on ambiguity. ```python import hashlib import json from dataclasses import dataclass, field from typing import Optional class HandoffIntegrityError(RuntimeError): """Raised when a handoff span's integrity attributes are inconsistent or missing.""" pass @dataclass class HandoffSpan: agent_id: str target_agent_id: str context: Optional[str] = None context_hash: Optional[str] = None integrity: Optional[str] = None attribute_limit: int = 4096 def emit_handoff_span(agent_id: str, target_agent_id: str, state: dict, attribute_limit: int = 4096) -> HandoffSpan: serialized = json.dumps(state, sort_keys=True) digest = hashlib.sha256(serialized.encode()).hexdigest() # Emit integrity attributes FIRST and independently of the content attribute, # so a count-based collector limit cannot drop them while keeping content. span = HandoffSpan( agent_id=agent_id, target_agent_id=target_agent_id, context_hash=digest, integrity="verified", ) if len(serialized) <= attribute_limit: span.context = serialized else: # Content exceeds the limit: do NOT emit truncated content. # Mark degraded and omit the content attribute entirely. span.context = None span.integrity = "degraded" return span def verify_handoff(span: HandoffSpan, received_state: dict) -> None: # Fail-closed: any missing or ambiguous integrity attribute is an error. if span.integrity not in ("verified", "degraded", "decorative"): raise HandoffIntegrityError( f"handoff span {span.agent_id}->{span.target_agent_id} has " f"unrecognized integrity status {span.integrity!r}" ) if span.integrity == "degraded": raise HandoffIntegrityError( f"handoff span {span.agent_id}->{span.target_agent_id} is degraded; " f"continuity cannot be verified from trace alone" ) if span.integrity == "decorative": # Authoritative state travels out-of-band; trace is not evidence. return if span.context_hash is None: raise HandoffIntegrityError( f"handoff span {span.agent_id}->{span.target_agent_id} missing context_hash " f"despite integrity='verified'" ) actual = hashlib.sha256(json.dumps(received_state, sort_keys=True).encode()).hexdigest() if actual != span.context_hash: raise HandoffIntegrityError( f"handoff state divergence on {span.agent_id}->{span.target_agent_id}: " f"trace_hash={span.context_hash} received_hash={actual}" ) if __name__ == "__main__": big_state = {"tool_results": ["x" * 3000 for _ in range(3)]} span = emit_handoff_span("executor", "auditor", big_state, attribute_limit=4096) try: verify_handoff(span, big_state) except HandoffIntegrityError as e: print(f"caught as designed: {e}") ```