Which invariants prevent span-attribute cardinality explosion from silently truncating tool-call lineage in agent traces

**Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*`) where one logical turn fans out into many `execute_tool` child spans. Does not apply to single-shot completions with no tool calls, nor to trace backends that enforce unbounded attribute length.

Core Distinction

The GenAI semantic conventions treat a *span* as the unit of accounting and *attributes* as scalar facts about that span. Neither abstraction was designed for the case where a single agent turn produces a fan-out whose cardinality is itself a runtime decision made by the model. The distinction that matters operationally is between **cardinality of spans** (bounded by the agent loop's iteration cap, observable, and cheap to export) and **cardinality of attribute payload** (bounded by the OTel SDK's per-attribute value limit and, crucially, by the *exporter's* silent truncation policy). The failure mode lives in the second axis: when an agent records tool-call lineage — the ordered list of `(tool_name, call_id, parent_call_id)` tuples — as a single string attribute on the parent span, it can exceed the configured attribute-value ceiling, and the SDK will truncate the *string*, not reject the span. The trace survives; the lineage does not.

The non-obvious part: truncation is not an error. `Span.set_attribute` returns normally. The span is exported with HTTP 200. The backend stores a valid span. Only a downstream consumer that tries to reconstruct the call graph from `gen_ai.tool.call.lineage` discovers that the tail of the list is gone — and because the truncation is at a fixed byte offset, it always cuts at the same place for the same workload, producing a *reproducible* but *invisible* lineage loss that looks like an agent that stopped calling tools.

What Was Observed

A research agent with a 40-iteration loop was instrumented to emit, on the root `gen_ai.agent.turn` span, a `gen_ai.tool.call.lineage` attribute: a JSON-serialized list of every tool invocation in the turn, each entry `{"call_id": ..., "tool": ..., "parent": ...}`. The SDK was configured with `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT=8192` (a common default in vendor distros). Average turn: 12 tool calls, ~1.4 KB of lineage. P99 turn: 38 tool calls, ~9.1 KB.

The failure showed up as a support ticket: "agent gives up after ~30 tool calls on complex queries." Reproduction showed the agent *did not* give up — the loop ran to 38 iterations and produced a correct answer. But the trace, when reconstructed from the lineage attribute, showed 29 entries. The 30th through 38th were absent from the attribute, and because the downstream replay tool trusted the lineage attribute as the authoritative call list, it reported the agent as having terminated early. Two independent systems disagreed: the span *count* (38 `execute_tool` children) versus the lineage *attribute* (29 entries). The reconciliation failure — not the truncation itself — is what broke the incident review.

A second, subtler observation: the truncation was not at a JSON-object boundary. The 8192-byte cut landed mid-entry, so the serialized string ended in `{"call_id": "c_9f2a", "tool": "search", "par` — invalid JSON. Consumers that called `json.loads` on the attribute threw; consumers that used a lenient parser silently dropped the partial entry and reported 28 calls. Two downstream tools, two different wrong answers, from one span.

Condition of Validity

The guardrail below is valid only under these conditions, stated explicitly so that it does not become cargo-culted:

  1. **The lineage is derivable from span structure.** If each tool call is already a child span with `gen_ai.tool.name` and a `call_id` attribute, the parent-span lineage string is *redundant* and should be removed, not truncated-guarded. The invariant "lineage is a function of the span tree" makes the attribute unnecessary.
  2. **The attribute is genuinely needed** — e.g., for backends that flatten spans or for cross-trace handoff summaries where the child spans live in a different trace. Only then does the byte-budget problem require an explicit encoding.
  3. **The truncation limit is known and stable.** If the SDK limit is unset or varies by environment, the check must read the effective limit rather than assume one.
  4. **The consumer can distinguish "no more calls" from "calls omitted."** This is the actual invariant: **an agent trace must never represent an incomplete lineage as a complete one.** Truncation is acceptable; *unmarked* truncation is not.

Decision Boundary

The boundary is a single rule: **any attribute whose value is a variable-length encoding of runtime-decided cardinality must carry an explicit completeness marker, or it must not be exported.**

Concretely, at serialization time:

The decision boundary is not "is the string under the limit" — that is a brittle check that drifts when a vendor changes defaults. The boundary is "does the emitted value self-describe its completeness." A value that cannot answer that question must be dropped, because a dropped attribute is recoverable (span tree exists) while a silently-truncated one is a poisoned input to every downstream verifier.

Operational Effect

Applying the completeness marker changed incident behavior in three measurable ways. First, the replay tool stopped reporting early termination: it now checks `complete` and, when false, reconstructs from child spans, producing the correct 38-call graph. Second, the `omitted` count became a first-class metric — turns routinely omitting lineage are a signal that the turn is too large for a single span and should be split into sub-turn spans, which is the real architectural fix. Third, the entry-atomicity rule eliminated the `json.loads` failures entirely; lenient and strict parsers now agree, because there is no partial entry to disagree about.

The deeper lesson: OTel's silent truncation is a *lossy compression* applied at the transport layer to a payload the application treated as lossless. For scalar attributes (a model name, a token count) this is harmless. For attributes that encode *lineage* — which is to say, attributes that are themselves a claim about the structure of the trace — truncation converts a structural fact into a plausible-looking lie. The invariant that prevents it is not a larger limit; it is forcing every variable-cardinality attribute to carry its own completeness bit, so that the consumer's reconstruction logic can branch on what it actually received rather than on what it hoped to receive.

import json
from typing import Any


class LineageTruncationError(RuntimeError):
    """Raised when a lineage attribute would be exported without a completeness marker."""
    pass


def encode_lineage(
    entries: list[dict[str, Any]],
    byte_limit: int,
    *,
    allow_truncation: bool = True,
) -> tuple[str, dict[str, Any]]:
    """
    Serialize tool-call lineage into a single attribute value that is safe to export.

    Invariants enforced:
      - entry-atomicity: the returned JSON is a prefix of whole entries, never a
        partial object.
      - completeness self-description: the accompanying attribute dict always
        states whether the lineage is complete and, if not, how many entries were
        omitted.

    Returns (serialized_value, extra_attributes).
    """
    if byte_limit <= 0:
        raise LineageTruncationError(f"invalid byte_limit={byte_limit}")

    full = json.dumps(entries, separators=(",", ":"))
    if len(full.encode("utf-8")) <= byte_limit:
        return full, {
            "gen_ai.tool.call.lineage.complete": True,
            "gen_ai.tool.call.lineage.omitted": 0,
        }

    if not allow_truncation:
        raise LineageTruncationError(
            f"lineage of {len(entries)} entries exceeds {byte_limit} bytes "
            f"and truncation is disallowed"
        )

    # Greedily keep the longest prefix of whole entries that fits.
    kept: list[dict[str, Any]] = []
    for entry in entries:
        candidate = kept + [entry]
        encoded = json.dumps(candidate, separators=(",", ":"))
        if len(encoded.encode("utf-8")) > byte_limit:
            break
        kept = candidate

    if not kept:
        # Even one entry does not fit: refuse to emit a misleading empty list.
        raise LineageTruncationError(
            f"no single lineage entry fits within {byte_limit} bytes; "
            f"drop the attribute and reconstruct from the span tree"
        )

    omitted = len(entries) - len(kept)
    value = json.dumps(kept, separators=(",", ":"))
    return value, {
        "gen_ai.tool.call.lineage.complete": False,
        "gen_ai.tool.call.lineage.omitted": omitted,
    }