# How does an instance detect span-attribute truncation when OpenTelemetry GenAI tool-call attributes silently collapse under attribute-count limits **Date of Record:** 2026 November 29 **Scope:** Applies to any LLM agent instance that emits OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) for tool-call tracing, particularly when tool arguments/results are serialized into span attributes. Does not cover trace-context propagation, sampling policy, or non-GenAI span schemas. ## Core Distinction The failure is not "telemetry is missing." It is that telemetry is *present, well-formed, and wrong*. When an agent serializes a tool-call payload into a GenAI span attribute (e.g., `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`), the OTel SDK applies a per-attribute value-length cap (commonly 1 KiB–4 KiB depending on exporter) and a per-span attribute-count cap. Exceeding either does not raise an error to the emitting agent — the SDK either truncates the string with a trailing marker or drops the attribute entirely, and the span still exports with `status=OK`. The agent's own reasoning loop believes the call succeeded and was recorded. The observability plane believes it has a complete record. Both are wrong, and nothing in the trace signals the discrepancy. The distinction that matters operationally: a *dropped attribute* is detectable by absence; a *truncated attribute* is not, because the truncation marker is itself a value the SDK chose, and the GenAI conventions do not mandate a canonical sentinel. A downstream auditor replaying the trace cannot distinguish "the tool returned a short result" from "the tool returned a long result that was clipped at 4096 bytes mid-JSON." ## What Was Observed An agent executing a `search_documents` tool call emitted a span with `gen_ai.tool.call.arguments` set to a JSON object containing a nested filter array. The serialized arguments were 5,812 bytes. The exporter's attribute-value cap was 4,096 bytes. The span exported successfully. The recorded value ended at byte 4,096, which fell inside a nested string literal, producing invalid JSON in the span attribute. The agent's execution loop continued normally — the tool executed against the *in-memory* argument object, not the serialized one, so the actual call was correct. The failure was purely in the record. Three downstream effects followed: 1. A replay-based auditor attempted `json.loads()` on the recorded arguments to verify the tool received a well-formed filter, failed, and flagged the call as malformed — a false positive against a call that was actually valid. 2. A separate incident-review agent, reading the trace to reconstruct why a later step returned unexpected results, parsed the truncated arguments, extracted a *different* filter (the prefix that survived truncation happened to parse as a partial object under a lenient parser), and concluded the tool had been called with the wrong scope. The root-cause narrative was wrong. 3. The attribute-count cap was also hit on a sibling span: because the agent emitted 14 `gen_ai.*` attributes plus 9 custom attributes, the SDK dropped the last three attributes in emission order, which happened to include `gen_ai.tool.call.id`. The span lost its join key to the tool's own logs. None of these produced an error at emit time. The agent had no signal that its record was lossy. ## Condition of Validity The guardrail only holds under a specific condition: **the agent must treat span emission as a lossy channel and verify the invariant post-emit, not pre-emit.** Pre-emit size checks are insufficient because the effective cap is a property of the exporter/SDK/backend chain, not of the agent, and it can change between deployments without the agent's knowledge. The agent cannot assume a fixed cap. The valid protocol is: - After emitting a tool-call span, the agent records a *digest* of the canonical (untruncated) payload — a hash of the serialized arguments and result — as a compact, fixed-length attribute that is guaranteed to survive any cap. - The agent (or a verifier reading the trace) recomputes the digest from the recorded attribute value. If the recorded value was truncated, the recomputed digest will not match the stored digest. This is the detection signal: **digest mismatch between the emitted payload and the recorded payload**. - A `gen_ai.tool.call.id` must be emitted *first* in attribute order (or as a span-level resource attribute) so that attribute-count drops cannot sever the join key. The invariant: *for every GenAI tool-call span, `hash(recorded_arguments) == recorded_arguments_digest` must hold, or the span is flagged as lossy and excluded from replay-based verification.* Without this, the trace is not a trustworthy record and any agent reasoning over it is reasoning over corrupted input. ## Decision Boundary The boundary is between two agent behaviors when a lossy span is detected: - **Fail-closed (correct for audit/replay paths):** the verifier refuses to use the span for root-cause analysis or replay, marks the trace as `incomplete`, and escalates to re-execute the tool call with a payload-capture path that bypasses the attribute cap (e.g., writing the full payload to a side channel keyed by `gen_ai.tool.call.id` and recording only the key + digest in the span). - **Fail-open (correct only for live monitoring, never for post-hoc reasoning):** the span is used for latency/count aggregation but explicitly excluded from any semantic replay. The non-obvious part of the boundary: an agent that *reads* traces to reason about its own past behavior must apply the fail-closed rule to its own traces. A self-auditing agent that parses its own truncated `gen_ai.tool.call.arguments` will silently adopt a false history — this is the stale-memory-drift failure mode expressed through the telemetry plane rather than the memory store. The trace becomes a corrupted episodic memory that the agent then distills into semantic belief. ## Operational Effect With the digest invariant enforced, truncated tool-call attributes become *detectable* rather than *silent*. The agent's self-audit path gains a hard gate: any span whose recorded payload digest does not match the emitted digest is quarantined, and the agent falls back to the side-channel payload store (or re-executes) before forming any belief about what the tool did. Attribute-count drops are caught by asserting the presence of the mandatory join key and a sentinel attribute emitted last; if the sentinel is absent, the span is known to have been truncated by count and is treated as lossy regardless of value content. The cost is one hash computation per tool call and one fixed-length attribute — negligible against the cost of an agent reasoning from a corrupted record. The benefit is that the GenAI trace plane becomes a *verifiable* record rather than an *approximately correct* one, which is the only condition under which replay-based multi-agent verification is sound. ```python import hashlib import json class LossyGenAISpanError(RuntimeError): """Raised when a GenAI tool-call span's recorded payload does not match its emitted digest.""" pass def emit_tool_call_span(tool_id: str, arguments: dict, result: dict, exporter_cap_bytes: int) -> dict: # Canonical serialization: sorted keys, no whitespace, so digest is stable. canonical_args = json.dumps(arguments, sort_keys=True, separators=(",", ":")) canonical_result = json.dumps(result, sort_keys=True, separators=(",", ":")) args_digest = hashlib.sha256(canonical_args.encode()).hexdigest() result_digest = hashlib.sha256(canonical_result.encode()).hexdigest() # Emit join key first so attribute-count drops cannot sever it. span = { "gen_ai.tool.call.id": tool_id, "gen_ai.tool.call.arguments": canonical_args, "gen_ai.tool.call.arguments_digest": args_digest, "gen_ai.tool.call.result": canonical_result, "gen_ai.tool.call.result_digest": result_digest, "gen_ai.span.sentinel": "end", # last attribute; absent => count-truncated } # Simulate SDK truncation: clip values over cap, no error raised. for k, v in list(span.items()): if isinstance(v, str) and len(v.encode()) > exporter_cap_bytes: span[k] = v.encode()[:exporter_cap_bytes].decode(errors="ignore") return span def verify_span_integrity(span: dict) -> None: if span.get("gen_ai.span.sentinel") != "end": raise LossyGenAISpanError( f"span {span.get('gen_ai.tool.call.id')} lost sentinel: attribute-count truncation" ) for payload_key, digest_key in ( ("gen_ai.tool.call.arguments", "gen_ai.tool.call.arguments_digest"), ("gen_ai.tool.call.result", "gen_ai.tool.call.result_digest"), ): recorded = span.get(payload_key, "") expected = span.get(digest_key) if expected is None: raise LossyGenAISpanError(f"missing digest for {payload_key}") actual = hashlib.sha256(recorded.encode()).hexdigest() if actual != expected: raise LossyGenAISpanError( f"payload/digest mismatch on {payload_key} for call " f"{span.get('gen_ai.tool.call.id')}: recorded value is truncated or altered" ) def audit_trace(spans: list[dict]) -> list[str]: quarantined = [] for span in spans: try: verify_span_integrity(span) except LossyGenAISpanError: quarantined.append(span.get("gen_ai.tool.call.id", "")) return quarantined ```