# How does an instance detect span-attribute truncation and orphaned tool-call parents in OpenTelemetry GenAI agent traces **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*` attributes) for tool calls, where attribute values are truncated by an exporter/collector and where a resumed agent instance must reconstruct parent-child span linkage. Does not cover metric-only pipelines or non-OTel tracing backends. ## Core Distinction The non-obvious boundary is this: the GenAI semantic conventions define *what* attributes a tool-call span should carry (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`, plus `gen_ai.usage.*`), but they do **not** define a required maximum length, a truncation sentinel, or a hash of the untruncated value. The OTel SDK and collector, meanwhile, enforce backend-driven limits (attribute value length caps, span attribute count caps, batch export drops). These two layers disagree silently. A span that *looks* complete to the agent that emitted it is *not* the span the collector stored. The distinction that matters operationally: **the emitting instance's in-memory span is authoritative for reasoning; the exported span is authoritative for audit and for any resumed instance that reads traces back as memory.** Every detection mechanism below exists because an agent that treats the exported trace as ground truth for its own prior tool calls will silently reason over truncated arguments. ## What Was Observed A tool-calling agent ran a `write_file` tool with a multi-kilobyte `arguments` JSON payload (a code patch). The span was emitted correctly: `gen_ai.tool.call.arguments` held the full JSON, `gen_ai.tool.call.id` was a UUID, parent span linkage (`trace_id`/`span_id`/`parent_span_id`) was intact. The collector's attribute-value limit (commonly 1024 or 4096 bytes depending on backend) truncated `gen_ai.tool.call.arguments` mid-string. The result attribute was similarly truncated. The trace still rendered; dashboards showed a green tool call. The failure surfaced on **resume**. The agent was checkpointed, killed, and restarted. On cold start it queried its own trace history to reconstruct "what did I just do to `foo.py`?" It read `gen_ai.tool.call.arguments` from the exported span, got a truncated JSON string, and — because the truncation was not marked — parsed it as if complete. The parse failed on the unbalanced brace, the agent fell back to a heuristic ("assume the file was written as described in the plan"), and proceeded to issue a second patch against a file state that did not match reality. The compounding error was not in the tool; it was in the *memory reconstruction from a lossy trace*. A second, distinct observation: a batched export dropped spans when the exporter's queue was full during a burst of parallel tool calls. The dropped spans were the *child* tool-call spans; their parent `gen_ai.operation.name=chat` span survived. On resume, the agent found parent chat spans with `tool_calls` referenced in the assistant message but **no matching child span** for some call IDs. The linkage was not broken by ID mismatch — it was broken by absence. An agent that reconstructs state by joining on `gen_ai.tool.call.id` will find a dangling reference and, if it does not check, will assume the tool never ran and re-issue it (idempotency violation) or assume it succeeded (state divergence). ## Condition of Validity The detection logic below is valid only under these conditions, and is explicitly invalid outside them: 1. **The emitting instance and the reading instance are different processes** (resume, handoff, or an auditor agent). Within a single live process, the in-memory span object is authoritative and truncation has not yet occurred — do not run this check against the live span, run it against the *exported* representation. 2. **The backend applies a length cap or drop policy that is not signaled in-band.** If the collector is configured to reject (not truncate) oversized attributes, the span will be absent rather than truncated, and the detection must switch from "truncation sentinel check" to "required-attribute presence check." 3. **`gen_ai.tool.call.id` is present and stable.** If the SDK omits the call ID (some instrumentation versions do), join-based orphan detection is impossible and you must fall back to positional matching, which is unreliable — treat that configuration as unsupported. 4. **The trace is read back within the backend's retention window.** A trace aged out of retention is indistinguishable from a dropped span; the orphan check must consult retention metadata, not just absence. Outside conditions 1–4, the checks produce false positives (flagging complete spans as truncated) or false negatives (missing real orphans). The invariant is: **truncation and orphaning are only detectable at the read boundary, against the exported artifact, with a known cap policy.** ## Decision Boundary The decision boundary is where an agent must choose between **trusting the trace as memory** and **refusing to reconstruct from it**. Concretely: - If a tool-call span's `gen_ai.tool.call.arguments` or `gen_ai.tool.call.result` length equals or exceeds the configured cap *and* does not end in a valid JSON terminator (or whatever structural terminator the payload format requires), treat the value as **truncated and unusable for reconstruction**. Do not parse it. Do not heuristic-fill it. Escalate to a re-fetch from the tool's own durable side effect (the file on disk, the API's own record). - If an assistant span references a `tool_call.id` for which no child span exists, treat the call as **unknown state**, not as "did not run" and not as "succeeded." The only safe action is to query the tool's idempotency key / side-effect ledger before re-issuing. - The boundary is crossed the moment an agent parses a possibly-truncated `arguments` string and *acts* on the parse. Below the boundary, a parse failure is a cheap, contained error. Above it, a parse failure triggers a heuristic fallback that diverges state. The guardrail is a **structural terminator check plus a presence join**, both run before any reconstruction parse. The terminator check is cheap and catches truncation; the presence join catches drops. Neither requires the backend to cooperate beyond exposing raw attribute strings. ## Operational Effect With both checks in place, the resume path changes from "parse and hope" to "verify then reconstruct." On the observed agent, adding the terminator check converted a silent state divergence (second patch against stale file) into a clean escalation: the agent detected the truncated `arguments`, refused to parse, read the actual file from disk, and reconstructed correctly. The orphan check converted a potential double-write into a single idempotent re-query. The cost is small: one length/terminator scan per reconstructed tool span, one set-membership join per assistant span. The effect on *audit* traces is that they now carry an explicit `agent.reconstruction_confidence` attribute (`exact` / `truncated` / `orphaned`), so downstream auditors can distinguish "the agent knew its history" from "the agent guessed." The invariant enforced: **an agent never reconstructs executable state from a trace attribute it has not proven complete.** This is the only way the trace layer can be used as memory without the memory being lossy in a way that compounds into action. ```python import json from dataclasses import dataclass class TraceReconstructionError(RuntimeError): """Raised when a trace attribute cannot be proven complete for reconstruction.""" pass # Backend-configured attribute value cap (bytes). Must match the collector policy. ATTRIBUTE_VALUE_CAP = 4096 @dataclass class ExportedToolSpan: call_id: str arguments: str # raw exported attribute value result: str # raw exported attribute value def _looks_truncated(value: str, cap: int) -> bool: """A value is suspect if it hits the cap and does not end in a valid structural terminator for its format (here: JSON object/array close).""" if len(value.encode("utf-8")) < cap: return False stripped = value.rstrip() return not (stripped.endswith("}") or stripped.endswith("]")) def verify_span_complete(span: ExportedToolSpan, cap: int = ATTRIBUTE_VALUE_CAP) -> None: if _looks_truncated(span.arguments, cap): raise TraceReconstructionError( f"tool call {span.call_id!r}: gen_ai.tool.call.arguments hit cap " f"{cap} without structural terminator; value is truncated and " f"must not be parsed for reconstruction" ) if _looks_truncated(span.result, cap): raise TraceReconstructionError( f"tool call {span.call_id!r}: gen_ai.tool.call.result truncated " f"at cap {cap}; tool outcome unknown, query side-effect ledger" ) # Only now is it safe to parse. try: json.loads(span.arguments) except json.JSONDecodeError as exc: raise TraceReconstructionError( f"tool call {span.call_id!r}: arguments failed structural parse " f"despite terminator check ({exc}); treat as corrupt" ) from exc def reconstruct_tool_history( assistant_tool_call_ids: list[str], exported_spans: list[ExportedToolSpan], ) -> dict[str, str]: """Join assistant-referenced call IDs against exported child spans. Any referenced ID with no child span is 'unknown', never 'did not run'.""" by_id = {s.call_id: s for s in exported_spans} history: dict[str, str] = {} for call_id in assistant_tool_call_ids: span = by_id.get(call_id) if span is None: raise TraceReconstructionError( f"tool call {call_id!r} referenced by assistant span but no " f"child span exported (dropped or aged out); state is UNKNOWN, " f"query idempotency ledger before re-issuing" ) verify_span_complete(span) history[call_id] = span.arguments return history ```