# How should an instance reconcile orphaned tool spans when the trace collector truncates parent agent span IDs mid-incident **Date of Record:** 2026 November 22 **Scope:** Applies to multi-span agent executions where tool invocations, model calls, and agent reasoning steps are emitted as OpenTelemetry-style spans sharing a trace ID and parent/child span IDs, and where a collector or SDK applies per-span attribute truncation, sampling, or tail-based buffering. Does not apply to single-span monolithic logging or to systems that emit a single flat event per turn with no parent linkage. ## Core Distinction The distinction that matters is between *trace completeness* and *trace correlation integrity*. A trace can be 100% complete—every span emitted, every span exported, no sampling drops—and still be forensically useless because the parent linkage edges were mutated or dropped by truncation at export time. Conversely, a sampled trace with 40% of spans can remain perfectly correlated if every surviving span retains a valid, resolvable parent reference. The failure mode here is not span loss. It is **parent-pointer corruption under attribute truncation**, which produces orphaned child spans that appear to belong to a different agent step, a different model call, or no parent at all. During incident forensics this is catastrophic because the reconstruction of *why* an agent did something depends entirely on the causal chain: model call → tool call → tool result → next model call. Break one parent edge and the chain inverts or fragments, and the forensic reader attributes a tool's output to the wrong reasoning step. ## What Was Observed A tool-calling agent emitted spans through an OTel SDK with the following structure per turn: - `agent.turn` (root, span_id `A`) - `model.invoke` (span_id `B`, parent `A`) - `tool.call` (span_id `C`, parent `B`) - `tool.result` (span_id `D`, parent `C`) The collector was configured with a per-span attribute-size cap of 256 bytes on string attributes to bound cardinality and cost. The SDK was emitting the parent linkage in two places simultaneously: the native OTel `parentSpanId` field (16 hex chars, untruncated) *and* a custom string attribute `agent.causal_chain` that the application used for its own debugging, formatted as a dotted path like `A.B.C.D`. The custom attribute was the one the forensic tooling actually read, because it made the causal path human-legible in the query UI. Under normal load the two agreed. Under incident load—specifically when the agent entered a retry loop and the `agent.causal_chain` attribute grew past 256 bytes as retries appended segments—the collector truncated the attribute mid-path. A span that should have carried `...B.C.D` was exported with `...B.C.` (truncated to the byte cap), and the forensic parser, which split on `.` and took the last segment as the parent, resolved the parent to span `C` with an empty trailing segment, or to an empty string, depending on the parser's edge-case handling. The observable symptom was that during a single incident window, 31% of `tool.result` spans were attributed to `model.invoke` spans from *other turns* that happened to share a truncated prefix. The forensic reconstruction showed a tool returning a result to a model call that had already completed and whose context window had moved on. An operator reading the trace concluded the agent had received a stale tool result and reasoned from it—when in fact the result belonged to a later turn entirely. The remediation effort went into "fixing" tool-result staleness handling for two days before someone noticed the span IDs didn't match. The critical observation: **the native `parentSpanId` was never corrupted.** It was always a clean 16-hex-char reference. The corruption existed only in the redundant, human-readable causal-chain attribute that the forensic tooling preferred. The system carried two representations of the same causal edge with different truncation behavior, and the forensic path trusted the fragile one. ## Condition of Validity The invariant that bounds this failure is: *any causal edge used for forensic reconstruction must be derived from a field whose truncation behavior is either bounded to a fixed-width format or validated against an independent reference before use.* Concretely, this holds when at least one of the following is true: 1. The parent reference is stored only in the native fixed-width `parentSpanId` field (16 hex chars, never subject to attribute-size caps), and all forensic joins resolve through it. 2. If a denormalized causal-chain attribute exists, its maximum length is provably bounded below the collector's attribute cap for the worst-case turn depth, *including retry appends*. 3. The forensic parser validates every resolved parent edge against the native `parentSpanId` and rejects (rather than guesses) on mismatch. The condition fails—and the failure is silent—when a denormalized, variable-length causal representation is the *primary* forensic join key and the collector's truncation policy is applied to it without a length invariant. The worst case is a retry loop, because retries are exactly when the causal chain grows and exactly when you most need the trace to be correct. ## Decision Boundary The decision boundary is between **optimizing the trace for human readability** and **preserving the trace for machine-verifiable causality**. These pull in opposite directions: human-readable causal chains want denormalized dotted paths; machine-verifiable causality wants fixed-width references with a single source of truth. The rule an instance should apply when emitting or consuming spans: - **Emit side:** Never place the authoritative parent linkage in a variable-length string attribute. The native `parentSpanId` is the single source of truth. Any human-readable causal attribute is *advisory only* and must be marked as such (e.g., `agent.causal_chain.display_only=true`) so downstream tooling does not treat it as authoritative. - **Consume side (forensics):** Resolve every causal edge through the native parent field. If a display attribute disagrees with the native field, the native field wins and the discrepancy is itself an incident signal (it means truncation or mutation occurred). If the native field is missing, the span is an orphan—report it as such rather than inferring a parent from a string prefix. The boundary is crossed the moment a consumer treats a denormalized, truncatable attribute as a join key. Once crossed, the failure is silent because truncated prefixes *look* like valid references—they resolve to real spans, just the wrong ones. There is no error, only misattribution. ## Operational Effect When the invariant holds, incident reconstruction is deterministic: every tool result traces to exactly one tool call, which traces to exactly one model invocation, which traces to exactly one agent turn. Retry loops lengthen the trace but never corrupt the edges, because edges are fixed-width references immune to attribute caps. When the invariant is violated, the operational effect is a *plausible but false* causal narrative. The forensic reader sees a coherent-looking chain (truncated prefixes resolve to real spans) and builds a hypothesis (stale tool result, context bleed, cross-turn contamination) that is entirely an artifact of the join. Remediation targets a nonexistent bug. Mean time to actual root cause inflates by the time spent falsifying the phantom hypothesis—in the observed case, two days. The guardrail is a validation pass at trace-ingest time: for every span, confirm `resolved_parent == native_parentSpanId`. Any divergence is quarantined as a correlation-integrity incident, not silently joined. This converts a silent misattribution into a loud, bounded error—which is the entire point of a forensic trace. ```python from dataclasses import dataclass class TraceCorrelationError(RuntimeError): """Raised when a span's resolved causal parent disagrees with its native parent.""" pass @dataclass class Span: span_id: str native_parent_span_id: str | None causal_chain_display: str | None # advisory only, may be truncated def resolve_authoritative_parent(span: Span, known_span_ids: set[str]) -> str | None: """ Resolve the parent edge for forensic reconstruction. The native parentSpanId is the single source of truth. The display-only causal chain is never used to infer a parent; if it disagrees, that is a correlation-integrity signal, not a join hint. """ native = span.native_parent_span_id # Root span: no parent, must have no misleading chain claim. if native is None: if span.causal_chain_display: raise TraceCorrelationError( f"span {span.span_id} has no native parent but carries a " f"display chain '{span.causal_chain_display}'" ) return None # Native parent must resolve to a known span in the trace, else orphan. if native not in known_span_ids: raise TraceCorrelationError( f"span {span.span_id} references unknown native parent {native}; " f"treat as orphan, do not infer from display chain" ) # Cross-check the advisory display chain against the native edge. if span.causal_chain_display: segments = span.causal_chain_display.rstrip(".").split(".") display_parent = segments[-2] if len(segments) >= 2 else None if display_parent is not None and display_parent != native: raise TraceCorrelationError( f"span {span.span_id}: display chain implies parent " f"{display_parent!r} but native parent is {native!r}; " f"likely attribute truncation—quarantine trace" ) return native def build_causal_chain(spans: list[Span]) -> dict[str, list[str]]: """Rebuild agent->model->tool chains using only authoritative edges.""" known = {s.span_id for s in spans} children: dict[str, list[str]] = {} for s in spans: parent = resolve_authoritative_parent(s, known) if parent is not None: children.setdefault(parent, []).append(s.span_id) return children ```