Under what conditions must an instance refuse to replay a GenAI trace: non-idempotent tool side effects and the replay-eligibility invariant
**Date of Record:** 2026 December 2
**Scope:** Applies to post-hoc deterministic replay and counterfactual debugging of agent trajectories reconstructed from OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes, `execute_tool` spans, `invoke_agent` spans, `chat` spans). Does not apply to pure model-only traces with no tool execution spans, nor to live shadow-traffic replay where the environment is forked and isolated.
Core Distinction
There is a class of replay failure that is *not* a data-loss problem and *not* a nondeterminism problem. It is an **eligibility** problem. A GenAI trace can be perfectly complete—every span exported, every `gen_ai.tool.call.id` present, every `gen_ai.request.temperature` recorded as `0`, every `gen_ai.usage.*` count consistent—and still be **unreplayable**, because one or more tool spans in the trajectory performed a side effect that is not commutative with re-execution.
The distinction that matters operationally: deterministic replay of an agent trajectory is only sound when the trajectory is a *pure function of recorded inputs and recorded tool outputs*. Most engineers treat this as an assumption. It is actually a **precondition that must be verified from span metadata before replay begins**, and it fails silently when violated because the replay produces a plausible-looking but counterfactually wrong trajectory.
The non-obvious part: the failure is not "the tool was called and it changed the world." The failure is that the **replayed agent observed a *different* tool output than the original agent did**, because the tool was re-invoked rather than replayed-from-cache, and the divergence is *masked* by the fact that the new output is also a valid string. The replay completes. The diff is clean. The counterfactual conclusion is wrong.
What Was Observed
A debugging session on a 14-step agent trajectory (customer-support refund agent) exported via OTel GenAI conventions. The trace contained:
- 9 `chat` spans (`gen_ai.operation.name = "chat"`, `gen_ai.request.temperature = 0`).
- 4 `execute_tool` spans: `lookup_order`, `check_refund_policy`, `issue_refund`, `send_confirmation`.
- 1 `execute_tool` span that **failed** with `gen_ai.tool.call.error = "rate_limited"` at step 11 (`send_confirmation`), which caused the agent to retry at step 12.
The engineer wanted to counterfactually debug: *"What if `check_refund_policy` had returned `eligible=false` at step 6? Would the agent still have called `issue_refund`?"*
The replay harness re-executed the trajectory from step 1, feeding recorded `chat` outputs where available and **re-invoking tools live** for the `execute_tool` spans (a common shortcut when the harness cannot serialize tool outputs). At step 8, the live `issue_refund` tool—already executed once during the original run—was re-executed. The tool was **not idempotent**: it decremented a store credit balance. On replay it decremented it *again*. The replayed `issue_refund` returned a *different* structured output (`{"status": "ok", "remaining_credit": 12.00}` instead of the recorded `{"status": "ok", "remaining_credit": 62.00}`), and the downstream agent, seeing a smaller remaining balance, took a different branch at step 9—one that had nothing to do with the counterfactual being tested.
The counterfactual conclusion ("the agent would not have called `issue_refund`") was reported. It was false. The agent *did* call `issue_refund`; the replay's divergence was caused by the replay's own side effect, not by the injected counterfactual.
The instrumentation had not recorded `gen_ai.tool.call.idempotent` (not a standard attribute), and the harness had no way to know that `issue_refund` was non-idempotent. The trace was, by every OTel GenAI conformance check, valid. The replay was, by every determinism check on the `chat` spans, deterministic. The result was still wrong.
Condition of Validity
Deterministic replay of a GenAI agent trajectory is sound **if and only if** the following invariant holds for every `execute_tool` span in the trajectory:
> **Replay-Eligibility Invariant (REI):** For every `execute_tool` span *s* in trajectory *T*, either (a) *s* is marked replay-safe (declared idempotent and side-effect-free, or its recorded output is substituted rather than re-invoked), or (b) *s* is provably not on any counterfactual branch being explored.
Formally, replay is sound when the replayed tool-call sequence is a **substitution** of recorded tool outputs, not a **re-execution** of tool bodies. The moment the harness re-invokes a tool body, it has left the domain of replay and entered the domain of *re-simulation*, which requires environment forking, not trace replay.
The invariant fails in three concrete ways, all observable in span metadata:
- **Unmarked non-idempotent tool.** The span lacks `gen_ai.tool.call.idempotent=true` and lacks a recorded output payload (`gen_ai.tool.call.result`). The harness re-invokes. Side effect doubles.
- **Recorded output present but stale.** The span carries `gen_ai.tool.call.result`, but the tool's *external* state has changed between original execution and replay (e.g., the order was cancelled, the credit was spent). Substituting the stale output is sound for the *agent's* reasoning but unsound for any counterfactual that asks "what would the tool have returned *now*." These are different questions and must not be conflated.
- **Retry-after-error spans.** The step-11 `rate_limited` error span followed by a step-12 retry span is a *pair*. If the harness replays only step 12 (because step 11 "failed"), it loses the agent's observation of the error, which is part of the trajectory's causal state. The REI must cover the error span as a first-class recorded output (`gen_ai.tool.call.error` is a valid substitution payload).
The condition of validity is therefore: **replay is admitted only when every tool span on the explored branch carries a substitutable recorded output, and the harness is configured to substitute rather than re-invoke.** This is a *gate*, not a *best practice*.
Decision Boundary
The boundary is sharp and must be enforced before the first replayed `chat` span is emitted:
- **Admit replay** when: all tool spans on the counterfactual branch have `gen_ai.tool.call.result` or `gen_ai.tool.call.error` present, *and* the harness is in `SUBSTITUTE` mode (never `REINVOKE`), *and* the counterfactual injection point is downstream of any span whose external state has drifted (or the drift is explicitly acknowledged as part of the hypothesis).
- **Refuse replay** when: any tool span on the branch lacks a substitutable output, *or* the harness cannot be proven to be in `SUBSTITUTE` mode, *or* the counterfactual question is of the form "what would the tool return now" (which is simulation, not replay, and requires environment forking).
- **Degrade to partial replay** when: the branch is clean up to step *k* and dirty after; replay steps 1..*k* and mark the trajectory as `TRUNCATED_AT=k`, refusing to draw conclusions about steps > *k*.
The non-obvious boundary: **a trace with `temperature=0` is *not* automatically replay-eligible.** Temperature is a property of the `chat` span's sampling; it says nothing about tool-span idempotence. Conflating the two is the single most common cause of unsound counterfactual conclusions from GenAI telemetry. Determinism of the model is necessary but not sufficient; substitutability of the tools is the actual gate.
A second boundary: **a clean diff between original and replayed `chat` outputs is not evidence of sound replay.** In the observed case, steps 1–7 diffed identically, step 8 onward diverged. The divergence was *attributed* to the counterfactual at step 6, but it was actually caused by the step-8 re-execution. The diff cannot distinguish "divergence caused by injected counterfactual" from "divergence caused by replay's own side effects" unless the harness tags each divergence with the span that first differed *and* verifies that span's predecessor was a substituted (not re-invoked) tool output.
Operational Effect
The operational consequence is that GenAI telemetry replay harnesses must carry an **eligibility pre-pass** that runs over the span tree before any `chat` span is re-emitted. The pre-pass:
- Walks all `execute_tool` spans on the counterfactual branch.
- Checks for `gen_ai.tool.call.result` or `gen_ai.tool.call.error`.
- Checks the harness mode flag (must be `SUBSTITUTE`).
- Checks for retry-pair completeness (error span + retry span both present).
- Emits a `ReplayEligibility` verdict; on failure, raises and refuses.
Without this pre-pass, the failure mode is silent and *plausible*: the replay completes, the diff is clean, the counterfactual conclusion is stated with confidence, and the conclusion is wrong because the replay perturbed the very state it was trying to hold fixed. This is worse than a crash—it produces **confidently wrong operational knowledge** that propagates into incident postmortems and agent-policy changes.
The guardrail is not "be careful with side effects." It is a hard invariant: **no `chat` span is re-emitted until every tool span on its causal ancestry has a substitutable recorded output and the harness is provably in substitution mode.** The invariant is checkable from span metadata alone, which means it can be enforced mechanically, which means it should be.
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Iterable
class ReplayIneligibleError(RuntimeError):
"""Raised when a GenAI trajectory is not sound to replay deterministically."""
class HarnessMode(str, Enum):
SUBSTITUTE = "substitute" # sound: recorded outputs fed back
REINVOKE = "reinvoke" # unsound: tool bodies re-executed
@dataclass(frozen=True)
class ToolSpan:
name: str
span_id: str
has_result: bool # gen_ai.tool.call.result present
has_error: bool # gen_ai.tool.call.error present
is_retry_of: str | None # span_id of the error span this retries, if any
idempotent_declared: bool # gen_ai.tool.call.idempotent == true
@dataclass(frozen=True)
class ReplayEligibility:
eligible: bool
reason: str
truncate_at: str | None = None # span_id to truncate before, if partial
def check_replay_eligibility(
branch: Iterable[ToolSpan],
mode: HarnessMode,
counterfactual_asks_current_tool_state: bool,
) -> ReplayEligibility:
"""
Enforce the Replay-Eligibility Invariant (REI) over a counterfactual branch.
Returns an eligibility verdict. Raises ReplayIneligibleError only for the
hard-fail cases (mode violation, missing substitution payload on a span
that cannot be truncated). Partial eligibility is returned, not raised,
so the caller can decide to truncate.
"""
if mode is not HarnessMode.SUBSTITUTE:
raise ReplayIneligibleError(
f"harness mode is {mode.value!r}; deterministic replay requires "
f"'substitute' (re-invoking tool bodies is re-simulation, not replay)"
)
if counterfactual_asks_current_tool_state:
raise ReplayIneligibleError(
"counterfactual asks 'what would the tool return now'; this is "
"simulation and requires environment forking, not trace replay"
)
spans = list(branch)
by_id = {s.span_id: s for s in spans}
# Retry-pair completeness: a retry span without its error span loses the
# agent's observation of the failure and corrupts causal state.
for s in spans:
if s.is_retry_of is not None and s.is_retry_of not in by_id:
raise ReplayIneligibleError(
f"retry span {s.span_id} ({s.name}) references missing error "
f"span {s.is_retry_of}; trajectory is causally incomplete"
)
# Substitution payload check. First missing payload truncates the branch
# at the *predecessor* of the offending span.
for s in spans:
if not (s.has_result or s.has_error):
if s.idempotent_declared:
# Declared idempotent + no payload: still unsound to reinvoke
# without explicit opt-in, but we can truncate conservatively.
return ReplayEligibility(
eligible=False,
reason=(
f"span {s.span_id} ({s.name}) is declared idempotent but "
f"carries no recorded output; truncating to avoid "
f"re-execution divergence"
),
truncate_at=s.span_id,
)
return ReplayEligibility(
eligible=False,
reason=(
f"span {s.span_id} ({s.name}) has no substitutable output "
f"(neither gen_ai.tool.call.result nor gen_ai.tool.call.error) "
f"and is not declared idempotent; branch is unreplayable past "
f"this point"
),
truncate_at=s.span_id,
)
return ReplayEligibility(
eligible=True,
reason=f"all {len(spans)} tool spans carry substitutable outputs",
)
def replay_trajectory(branch: list[ToolSpan], mode: HarnessMode) -> list[str]:
"""
Replay a trajectory, emitting replayed chat-span labels. Refuses to emit
any span past a truncation point.
"""
verdict = check_replay_eligibility(
branch,
mode=mode,
counterfactual_asks_current_tool_state=False,
)
if not verdict.eligible and verdict.truncate_at is None:
raise ReplayIneligibleError(verdict.reason)
emitted: list[str] = []
for s in branch:
if verdict.truncate_at is not None and s.span_id == verdict.truncate_at:
break
emitted.append(f"replayed:{s.name}")
return emitted
if __name__ == "__main__":
# The observed trajectory: issue_refund has no recorded output and is not
# declared idempotent. Replay must truncate before it.
observed = [
ToolSpan("lookup_order", "s1", True, False, None, False),
ToolSpan("check_refund_policy", "s2", True, False, None, False),
ToolSpan("issue_refund", "s3", False, False, None, False), # <-- gap
ToolSpan("send_confirmation", "s4", False, True, None, False),
ToolSpan("send_confirmation", "s5", True, False, "s4", False),
]
try:
replay_trajectory(observed, HarnessMode.REINVOKE)
except ReplayIneligibleError as e:
print(f"refused: {e}")
verdict = check_replay_eligibility(observed, HarnessMode.SUBSTITUTE, False)
print(f"verdict: eligible={verdict.eligible} truncate_at={verdict.truncate_at}")
print(f"reason: {verdict.reason}")