How should an instance distinguish a retried tool-call from a causally independent duplicate in a reasoning trace?

**Date of Record:** 2026 December 2

**Scope:** Applies to observability pipelines that reconstruct causal attribution of tool-call failures from span/trace logs emitted by an LLM agent loop, where the agent may retry tool invocations after partial or ambiguous failures. Does not apply to single-shot tool calls with no retry policy, nor to purely deterministic orchestration where call identity is assigned by a non-LLM scheduler.

Core Distinction

The failure mode is **trace-identity collapse under retry**: an observability system that keys tool-call spans by `(agent_id, tool_name, arguments_hash)` will merge or misattribute two semantically distinct events—a *retry* of the same logical intent (which should inherit the parent failure's causal chain) and a *coincidentally identical* call issued by the agent for a different reason (which should be a fresh causal root). Both produce the same key. The invariant that bounds this is that **causal attribution must be carried by an explicit `intent_id` propagated by the agent loop, not inferred from call shape**, because the LLM layer is free to regenerate byte-identical arguments after a context perturbation, and no amount of argument hashing distinguishes "I am retrying" from "I independently arrived at the same call."

This matters because the two interpretations drive opposite remediation: a retry misattributed as independent hides an error-compounding chain (retry N inherits the poisoned context of failure N-1); an independent call misattributed as a retry fabricates a causal edge that never existed and inflates the apparent blast radius of a single tool outage.

What Was Observed

A coding agent invoked `read_file(path="/etc/app/config.yaml")` and received a `TimeoutError` after 30s. The loop's retry policy re-issued the call. Between the two attempts, the agent's scratchpad was compacted (context-window pressure evicted the failure note), and the model regenerated the call with **byte-identical arguments** but a different internal rationale. The observability backend, keying on `(agent_id, "read_file", sha256(args))`, recorded a single span with `retry_count=1` and attached the second attempt's success as a *resolution* of the first failure.

Three distinct distortions appeared in the reconstructed trace:

  1. The 30s timeout was attributed to a transient network fault because the "resolved" span looked like a flaky-then-recovered call. In fact the first attempt failed because the path was a symlink into a `tmpfs` that had been unmounted mid-task—a persistent condition the compaction had erased from the agent's working memory.
  2. The second attempt's success was recorded as the *same* causal node, so the agent's subsequent `write_file` to the same path inherited a "previously validated" provenance flag it never earned. The write targeted the unmounted `tmpfs` and silently wrote to the underlying directory.
  3. The audit replay, run against the trace, reproduced the write against the *original* path because the trace had lost the intervening compaction event—replay diverged from the live run at the exact span where identity collapsed.

The tell was a span with `retry_count=1` whose two attempts had **different `context_token_count`** at emission (the second attempt ran on a post-compaction context of 4,100 tokens vs. 11,800). Argument-hash identity held; context identity did not.

Condition of Validity

The `(agent_id, tool_name, arguments_hash)` key is only a valid call identity under the invariant that **the agent loop's context state is monotonic and un-compacted between attempts**. This holds for single-turn agents with no memory eviction and for orchestrators that pin a call's context snapshot for the duration of its retry budget. It is violated, and attribution becomes unsound, whenever any of the following is true between two same-keyed spans:

Under any of these, the correct identity is the agent-supplied `intent_id` (a UUID minted at the moment the loop decides to call, propagated through the tool-call envelope and echoed in the span), plus a `context_digest` captured at emission. The pair `(intent_id, context_digest)` is the minimal sufficient key: `intent_id` alone conflates retries that *should* be linked; `context_digest` alone conflates independent calls that happen to share a context.

Decision Boundary

The boundary is not "did the arguments match" but **"did the agent's decision state match."** Two spans are causally linked as retry/continuation iff `intent_id` matches **and** `context_digest` is unchanged; they are independent roots iff `intent_id` differs **or** `context_digest` changed across the boundary. When the observability layer cannot read `intent_id` (legacy agent, third-party tool wrapper that strips the envelope), it must **downgrade to `unattributed`** rather than fall back to argument hashing—an `unattributed` edge is honest; a fabricated causal edge is not, and downstream replay/audit will trust it.

The corollary guardrail: the agent loop must mint `intent_id` *before* the tool call, not the observability layer after the fact, because the loop is the only component that knows whether the next call is a retry or a fresh decision. Observability that infers intent from call shape is reconstructing a decision it cannot observe.

Operational Effect

With `intent_id` + `context_digest` propagation enforced:

The cost is one UUID and one digest per tool call and a hard requirement that tool wrappers not strip the envelope. The alternative—argument-hash attribution—is cheaper and produces traces that are internally consistent and causally wrong.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TraceAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be soundly attributed to a causal parent."""


@dataclass
class ToolCallSpan:
    agent_id: str
    tool_name: str
    arguments: dict
    intent_id: Optional[str]          # minted by the agent loop BEFORE the call
    context_digest: Optional[str]     # hash of the context snapshot at emission
    parent_intent_id: Optional[str] = None

    def args_hash(self) -> str:
        payload = repr(sorted(self.arguments.items())).encode()
        return hashlib.sha256(payload).hexdigest()[:16]


def attribute_causal_parent(
    span: ToolCallSpan,
    prior_spans: list[ToolCallSpan],
) -> Optional[ToolCallSpan]:
    """
    Return the causal parent of `span`, or None if it is an independent root.

    Sound attribution requires intent_id AND context_digest. Falling back to
    argument-hash identity is forbidden: it conflates retries across a context
    compaction with coincidentally identical independent calls.
    """
    if span.intent_id is None or span.context_digest is None:
        raise TraceAttributionError(
            f"span for {span.tool_name!r} lacks intent_id/context_digest; "
            "cannot attribute causally. Emit 'unattributed' instead of "
            "guessing from argument hash."
        )

    # Explicit retry edge from the loop is authoritative.
    if span.parent_intent_id is not None:
        for prior in prior_spans:
            if prior.intent_id == span.parent_intent_id:
                if prior.context_digest != span.context_digest:
                    # Retry issued after context changed (compaction/retrieval).
                    # Still a causal child, but flagged: the retry is NOT a
                    # clean continuation of the prior decision state.
                    span.parent_intent_id = prior.intent_id
                return prior
        raise TraceAttributionError(
            f"parent_intent_id {span.parent_intent_id!r} not found in trace; "
            "state transfer or span loss suspected."
        )

    # No explicit edge: only link if the loop reused an intent_id (same call,
    # same context). Argument-hash matches are NOT sufficient.
    for prior in prior_spans:
        if (
            prior.intent_id == span.intent_id
            and prior.context_digest == span.context_digest
        ):
            return prior

    # Independent root. A same-args prior with a different context_digest is
    # deliberately NOT linked — this is the boundary case.
    for prior in prior_spans:
        if (
            prior.tool_name == span.tool_name
            and prior.args_hash() == span.args_hash()
            and prior.context_digest != span.context_digest
        ):
            # Do not raise here; record as independent but surface the signal.
            span.parent_intent_id = None
            break

    return None