Under what conditions must an instance treat a trace-correlation join as invalid when a memory mutation is committed inside a retried tool span

**Date of Record:** 2026 December 2 **Scope:** Applies to observability pipelines that reconstruct end-to-end causality across LLM generation spans, tool-call spans, and memory-store mutation events by joining on a propagated trace/span identity. Does not apply to single-shot, stateless inference calls with no memory writes, nor to pipelines that record mutations as first-class events with their own monotonic sequence numbers independent of span identity.

Core Distinction

The distinction that matters is between **span identity** and **effect identity**. A span ID identifies an *attempt* at doing something; a memory mutation identifies an *effect* that either committed or did not. Observability pipelines routinely conflate the two because in the happy path one attempt produces exactly one effect, so `span_id → mutation` looks like a valid functional dependency. It is not. When a tool call is retried — by the agent's own retry loop, by a transport-level reconnect, or by an orchestrator replaying a failed step — the same logical operation is attempted N times under N distinct span IDs, but the memory backend may have committed the mutation on attempt 1, attempt 2, or on several attempts before a dedup guard kicked in. A trace join that keys mutations on the *terminal* span ID (the one that returned success) will silently attribute a mutation to the wrong attempt, and a join that keys on *all* span IDs in the retry group will double-count. Neither is a correlation; both are fabrication.

The non-obvious part: the corruption is invisible in aggregate metrics. Span counts, latency histograms, and error rates all stay internally consistent. Only the *causal edge* between a generation step and the memory state it produced is wrong — which is precisely the edge that downstream replay, audit, and "why did the agent know X at step K" queries depend on.

What Was Observed

A three-stage agent (plan → retrieve-and-write → summarize) ran under an orchestrator that retried any tool span returning a transient transport error. The memory tool performed a read-modify-write against an episodic store: it fetched the current episode list, appended a new entry derived from the LLM's output, and wrote back under an optimistic concurrency token.

The failure trace:

  1. Attempt 1 of span `S_a1`: read episode list at version `v7`, LLM-derived entry computed, write submitted. The write **committed** at the store (`v7 → v8`) but the response was lost to a socket timeout. The tool surfaced a transient error.
  2. Orchestrator retried under a new span `S_a2`, carrying the same propagated `trace_id` but a fresh `span_id`.
  3. Attempt 2: read at `v8`, recomputed the entry (the LLM re-ran, producing a *semantically similar but not byte-identical* entry — different phrasing, same fact), write committed at `v8 → v9`.
  4. Attempt 2 returned success. The pipeline recorded `S_a2` as the successful span and joined the mutation event to it.

Two mutations committed. The trace recorded one. The pipeline's join logic, keyed on "successful span → mutation," attributed the `v8 → v9` write to `S_a2` and dropped the `v7 → v8` write entirely — it had no span to attach to, because `S_a1` was marked failed and the pipeline's rule was "failed spans produce no effects." The store now held a duplicate episodic entry, and the trace claimed the agent's memory contained one. A later replay from the trace reconstructed a memory state that never existed: single-entry where the store held two.

The second-order damage: a downstream "memory drift" detector compared the replayed state to the live store, found a discrepancy, and flagged the *memory backend* as divergent. The actual fault was in the observability join. The detector spent two days chasing a store bug that was a trace bug.

Condition of Validity

The invariant a pipeline must enforce is:

> A mutation event may be joined to a span only if the mutation carries an idempotency key that is a function of the *logical operation*, not the attempt, and the pipeline has observed the terminal disposition (committed / aborted / unknown) of every attempt in the retry group before emitting the causal edge.

Three conditions must all hold for a `span → mutation` edge to be admissible:

The condition fails silently when the store is idempotent (deduped writes hide the double-attempt) but the *payloads* differed — the pipeline sees one mutation, one success span, and concludes a clean single write, while the LLM actually generated two different facts and only one survived dedup. That is a reasoning divergence laundered into a clean-looking trace.

Decision Boundary

The boundary is drawn at the point where the pipeline must choose between **attributing** a mutation and **quarantining** it. The rule:

The trap is treating quarantine as a failure of the pipeline and retrying the join. Quarantine is the correct terminal state; a retried join against a store that has since accepted more writes will "succeed" by matching a *later* mutation to an *earlier* span — a fabricated edge that is worse than a missing one.

Operational Effect

With the boundary enforced, the pipeline's output changes character: traces now carry explicit `indeterminate` memory states at retry boundaries instead of a clean but false linear history. Replay from such a trace must branch — it cannot reconstruct a single memory state, because the true state depends on which attempts committed, and that fact was lost at the transport layer. The honest artifact is a *set* of possible states with the mutation keys that would distinguish them, not a single reconstructed snapshot.

The cost is that "replay the trace and diff against live memory" stops being a valid drift detector at exactly the steps where drift is most likely — retried writes. The drift detector must be re-scoped to compare only over edges with `correlation_confidence: high`, and must treat quarantined steps as *expected* divergence rather than anomalies. Teams that skip this re-scoping see the detector fire on every retry-heavy workload and eventually mute it, which is the real failure: the guardrail exists, is correct, and is disabled because the pipeline fed it fabricated certainty.

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Disposition(Enum):
    COMMITTED = "committed"
    ABORTED = "aborted"
    UNKNOWN = "unknown"


@dataclass
class Attempt:
    span_id: str
    disposition: Disposition
    payload_hash: str


@dataclass
class Mutation:
    logical_op_key: str
    payload_hash: str
    committed: bool


class CorrelationInvariantError(RuntimeError):
    """Raised when a span->mutation edge would be emitted without satisfying
    attempt-completeness, effect-idempotency, and payload-stability."""


@dataclass
class RetryGroup:
    logical_op_key: str
    attempts: list[Attempt] = field(default_factory=list)
    mutations: list[Mutation] = field(default_factory=list)

    def correlation_confidence(self) -> str:
        if any(a.disposition is Disposition.UNKNOWN for a in self.attempts):
            return "quarantined"
        payloads = {a.payload_hash for a in self.attempts}
        if len(payloads) > 1:
            return "split"
        if not all(m.logical_op_key == self.logical_op_key for m in self.mutations):
            return "degraded"
        return "high"


def emit_causal_edge(group: RetryGroup) -> Optional[str]:
    """Return the span_id a mutation may be soundly attributed to, or None
    after raising/annotating per the decision boundary."""
    confidence = group.correlation_confidence()

    if confidence == "quarantined":
        # Cannot attribute: some attempt outcome is unknown. Do not guess.
        raise CorrelationInvariantError(
            f"logical_op={group.logical_op_key} has unknown-disposition attempt; "
            f"mutation ownership indeterminate, must quarantine not attribute"
        )

    if confidence == "split":
        # Attempts produced divergent payloads: two distinct logical operations.
        raise CorrelationInvariantError(
            f"logical_op={group.logical_op_key} payload divergence across attempts; "
            f"retry group must be split, not collapsed into one edge"
        )

    if confidence == "degraded":
        # Store supplied no logical key; span-local attribution only.
        return None

    successful = [a for a in group.attempts if a.disposition is Disposition.COMMITTED]
    if len(successful) != 1:
        raise CorrelationInvariantError(
            f"logical_op={group.logical_op_key} expected exactly one committed attempt, "
            f"got {len(successful)}; edge would double-count"
        )
    return successful[0].span_id