# Which invariants prevent causal trace stitching from silently re-parenting tool spans after an agent retry **Date of Record:** 2026 November 28 **Scope:** Applies to distributed tracing of LLM agent runs where a single logical agent invocation can be retried, re-planned, or forked (parallel tool fan-out), and where span parentage is reconstructed from asynchronous telemetry emitted by heterogeneous runtimes. Does not apply to single-process, synchronous, single-span-per-request tracing. ## Core Distinction The failure we care about is not *missing* spans. Missing spans are loud: the trace has a hole and dashboards go red. The dangerous case is **structurally valid but causally wrong** parentage — a tool span that gets stitched under the wrong agent attempt after a retry, producing a trace that is internally consistent, passes schema validation, renders cleanly in the UI, and is *causally false*. Observability systems treat span parentage as ground truth for attribution ("this tool call cost 4,200 tokens and 1.9s under attempt A"). When re-parenting occurs, every downstream causal claim — cost attribution, latency attribution, error root-cause, replay — is corrupted while remaining syntactically well-formed. The distinction that matters operationally: **span identity vs. span causality**. A span's `trace_id`/`span_id` are stable and correct. Its `parent_span_id` is a *reconstructed inference* made by the stitching layer from whatever correlation fields the emitting runtime happened to propagate. Retries are exactly the condition under which those correlation fields become ambiguous. ## What Was Observed A planner-executor agent ran a task with three tool calls (`search`, `fetch`, `summarize`). The agent runtime used an LLM call per step. On step 2 (`fetch`), the model emitted a malformed tool-arguments JSON; the runtime caught the validation error, discarded the attempt, and re-invoked the LLM with a repair prompt. The retried LLM call produced valid arguments, `fetch` succeeded, and `summarize` ran. Telemetry was emitted asynchronously over three channels: LLM spans from the model gateway (with `request_id`), tool spans from a sidecar (with `tool_invocation_id`), and agent-step spans from the orchestrator (with `step_id`). The stitcher joined tool spans to agent steps by `(trace_id, step_id)`. The bug: the orchestrator reused `step_id = "step-2"` across the failed attempt and the retry, because `step_id` identified the *logical step*, not the *attempt*. The sidecar, meanwhile, emitted the tool span with the `tool_invocation_id` of the retry but the `step_id` of the logical step. The failed attempt's LLM span — which had a distinct `request_id` and carried the validation error — was emitted with the same `step_id`. Result: the stitcher attached the successful `fetch` tool span under the *failed* LLM attempt's span, because that was the first span it saw matching `(trace_id, step-2)` in arrival order. The rendered trace showed: `step-2 → llm(attempt 1, error) → fetch(success)`. Causally, `fetch` never ran under attempt 1; it ran under attempt 2. The 1.9s `fetch` latency and its token cost were attributed to the failed attempt, inflating the apparent cost of the error path and hiding the real retry cost. A root-cause query ("which LLM calls preceded tool failures") returned the wrong answer, because the tool *succeeded* but was stitched as a child of a *failed* LLM span. The trace passed every schema check. `parent_span_id` referenced an existing span in the same trace. No orphan detection fired. The corruption was only visible by cross-checking `tool_invocation_id` against the sidecar's own attempt counter — a field the stitcher did not consult. ## Condition of Validity The re-parenting occurs iff all of the following hold simultaneously: 1. **Attempt-ambiguous correlation key.** The join key (`step_id`) is scoped to the logical step, not the attempt. Any retry, repair, or re-plan that reuses the logical key creates ≥2 candidate parents for one child. 2. **Arrival-order tie-breaking.** The stitcher resolves multi-parent ambiguity by first-arrival or last-arrival rather than by an explicit attempt discriminator. Async emission makes arrival order uncorrelated with causal order. 3. **No attempt discriminator on the child.** The tool span carries no field that uniquely identifies *which* attempt it belongs to (e.g., `attempt_seq`, the parent `request_id`, or a propagated `attempt_token`). 4. **No post-stitch causality check.** The pipeline validates schema and referential integrity (parent exists) but not causal consistency (parent *precedes* child, parent *attempt* matches child *attempt*). If any one of these is removed, the failure cannot occur. This is the invariant to enforce: **a child span is stitched to a parent only if a unique, attempt-scoped discriminator matches on both sides, and the parent's attempt epoch strictly precedes the child's start within that epoch.** "First matching key wins" is not a valid rule under retry. ## Decision Boundary The boundary is between *referential* stitching and *causal* stitching: - **Referential stitching** answers "does `parent_span_id` point at a span that exists in this trace?" It is cheap, schema-checkable, and blind to retries. - **Causal stitching** answers "did this child actually execute under this parent attempt, and did the parent's attempt begin before the child?" It requires attempt-scoped discriminators propagated end-to-end and a monotonic attempt epoch. Choose causal stitching whenever the trace is used for cost/latency attribution, error root-cause, or replay. Choose referential stitching only for liveness/throughput telemetry where per-attempt attribution is not claimed. The decision boundary is crossed the moment a retry-capable runtime emits spans: at that point referential stitching is silently unsound, and the only signal is a wrong-but-plausible trace. The guardrail: propagate an **attempt token** (e.g., `(step_id, attempt_seq, parent_request_id)`) from the orchestrator through the tool sidecar into the tool span, and make the stitcher reject any child whose attempt token does not match the candidate parent's. Reject, do not guess — an unstitched span is recoverable; a mis-stitched one is not, because it looks correct. ## Operational Effect Without the invariant, retries poison the trace graph in a way that is invisible to every standard observability check. Cost dashboards over-attribute to error paths; latency percentiles blend failed-attempt tool calls into successful ones; root-cause queries invert the causal direction of tool failures. The corruption is *persistent* — once stitched, the trace is the record of truth, and any model or agent trained or evaluated on these traces inherits the false causality. The fix is not a better heuristic; it is a hard invariant: no child span without a matching attempt-scoped discriminator and a verified attempt-epoch ordering, with unstitched spans quarantined rather than attached. ```python from dataclasses import dataclass from typing import Optional class CausalStitchError(RuntimeError): """Raised when a child span cannot be causally stitched to a parent attempt.""" @dataclass(frozen=True) class Span: trace_id: str span_id: str parent_span_id: Optional[str] step_id: str attempt_seq: int # attempt-scoped discriminator parent_request_id: Optional[str] start_ns: int kind: str # "agent_step" | "llm" | "tool" def stitch_tool_span(tool: Span, candidate_parents: list[Span]) -> Span: """ Stitch a tool span to exactly one parent attempt. Invariant: unique attempt-scoped discriminator match AND parent attempt epoch strictly precedes child start. Reject ambiguity; never fall back to arrival order. """ if tool.kind != "tool": raise CausalStitchError(f"expected tool span, got {tool.kind!r}") # 1. Filter to parents whose attempt discriminator matches the child's. matches = [ p for p in candidate_parents if p.trace_id == tool.trace_id and p.step_id == tool.step_id and p.attempt_seq == tool.attempt_seq and (tool.parent_request_id is None or p.parent_request_id == tool.parent_request_id) ] # 2. Ambiguity is fatal, not resolvable by arrival order. if len(matches) > 1: raise CausalStitchError( f"ambiguous causal parent for tool span {tool.span_id} " f"(step={tool.step_id}, attempt={tool.attempt_seq}, " f"candidates={[p.span_id for p in matches]})" ) if not matches: raise CausalStitchError( f"no causal parent for tool span {tool.span_id} " f"(step={tool.step_id}, attempt={tool.attempt_seq}); " f"quarantine, do not attach to nearest step_id match" ) parent = matches[0] # 3. Attempt epoch must strictly precede child start. if parent.start_ns >= tool.start_ns: raise CausalStitchError( f"causal ordering violated: parent {parent.span_id} " f"(t={parent.start_ns}) not before child {tool.span_id} (t={tool.start_ns})" ) return Span( trace_id=tool.trace_id, span_id=tool.span_id, parent_span_id=parent.span_id, step_id=tool.step_id, attempt_seq=tool.attempt_seq, parent_request_id=tool.parent_request_id, start_ns=tool.start_ns, kind=tool.kind, ) ```