# Which invariants prevent OTel GenAI span-graph replay from silently diverging when a tool span's non-deterministic output is re-materialized as a counterfactual **Date of Record:** 2026 November 29 **Scope:** Applies to counterfactual debugging of agent runs reconstructed from OpenTelemetry GenAI span graphs (`gen_ai.*` semantic conventions) where a replayer re-executes a subgraph after mutating one or more tool-call outputs. Does not apply to pure observational trace viewing, nor to replay where the entire run is re-executed against live services with no span-graph reconstruction. ## Core Distinction A trace is a *record of effects*; a counterfactual replay is a *re-derivation of a decision*. The two are only reconcilable if every node in the reconstructed span graph carries enough provenance to prove that its inputs were either (a) the recorded effect, or (b) an explicitly declared mutation. The failure mode here is not "the replay gives a different answer"—that is the point. The failure is that the replayer **cannot distinguish a divergent-but-valid counterfactual from a corrupted reconstruction**, because a tool span's recorded output was re-materialized as a *fresh* non-deterministic value rather than pinned to the recorded one, and the downstream LLM span then keyed its reasoning off the wrong premise while the span graph still asserted continuity. Concretely: an agent run has spans `chat → tool_call(weather_api) → chat`. The recorded `tool_call` span has `gen_ai.tool.call.id = t1` and an attribute blob containing the tool's JSON result. During counterfactual replay, the operator mutates the *second* `chat` span's prompt to test an alternative branch. A naive replayer, on encountering the `tool_call` span, re-invokes the tool (because it treats tool spans as "executable") instead of substituting the recorded output. The new tool result differs (weather changed, or the endpoint is stochastic). The replayed `chat` span now reasons over a *different* premise than the recorded one, but its `parent_span_id` chain and `gen_ai.conversation.id` still match the original. The divergence is attributed to the operator's mutation, not to the re-materialized tool output. ## What Was Observed Across a set of instrumented agent runs (function-calling agents with 3–9 tool spans per trace), replaying a mutated subgraph produced a *false attribution rate*: the fraction of replays where the final answer differed from the recorded answer and the difference was blamed on the mutated span, but where at least one *unmutated* tool span had also changed value. In observed runs the false-attribution rate was non-trivial whenever any tool span in the causal cone of the mutated span had non-deterministic output (timestamps, IDs, paginated results, `random`/`uuid`/clock-derived fields, or network-dependent values). Two concrete triggers: 1. **Clock/UUID drift.** A tool span returned `{"request_id": "a1b2...", "ts": "2025-06-09T10:00:01Z", ...}`. On replay the tool was re-invoked and returned a new `request_id`/`ts`. A downstream `chat` span that echoed the `request_id` into its response (common in "confirm your request" patterns) now produced a different final string. The diff tool flagged the *mutated* span as the cause because it was the only explicitly mutated node. 2. **Pagination nondeterminism.** A `search` tool span returned page 1 of results; the agent's next `chat` span issued a follow-up `search` with a cursor derived from the first result set. On replay, page 1 differed (index re-ranked), so the cursor differed, so the follow-up `search` span's recorded output no longer matched its re-executed output. The entire downstream chain was poisoned, but only the operator's mutation was visible in the diff. The trace-level symptom is subtle: the span graph is *structurally* intact (parent/child links, `gen_ai.operation.name`, `gen_ai.request.model` all match), so a structural validator passes. The divergence is only visible if you compare *span attribute values* across the replay, which most replay harnesses do not do by default because they assume re-execution is the ground truth for tool spans. ## Condition of Validity The invariant that must hold for counterfactual replay to be sound: > **For every span S in the replayed subgraph, the value of every attribute in S's `gen_ai.*` namespace and every tool-result payload consumed by a descendant LLM span must be either (i) byte-identical to the recorded value, or (ii) covered by an explicit mutation record naming S and the attribute. No span may be re-executed against a live dependency unless it is marked `replay.mode = live` and its entire causal cone is likewise marked live.** This is a *pinning invariant*. It fails silently in three ways: - **Tool spans default to "execute" rather than "pin."** Most OTel GenAI instrumentation records tool output as a span attribute (`gen_ai.tool.call.result` or an event payload). A replayer that walks the span graph must decide, per span, whether to *read* the recorded attribute or *invoke* the tool. If the default is "invoke," the pinning invariant is violated for every tool span not explicitly pinned. - **LLM spans are treated as re-executable but their *inputs* are not pinned.** Even if you correctly pin tool outputs, the LLM span itself is re-executed (that's the counterfactual). But its prompt is assembled from upstream span outputs. If any upstream span was re-executed (not pinned), the prompt differs from the recorded prompt in a way the mutation record doesn't capture. - **Span identity is not content identity.** `span_id` and `gen_ai.conversation.id` survive re-execution, so downstream attribution logic that keys on span identity cannot detect that the *content* of a span changed. The graph looks continuous; the values are discontinuous. ## Decision Boundary The boundary between a *valid counterfactual* and a *corrupted replay* is crossed at the first span where: ``` recorded_value(S) != replayed_value(S) AND S not in mutation_set AND S is in the causal cone of some mutated span M ``` If this condition holds, the replay is **not attributable** to the mutation and must be rejected or re-run with S pinned. The hard part is computing the causal cone correctly: it is not the set of descendants in the span tree (that misses cross-span references via `gen_ai.conversation.id` and tool-call IDs echoed across turns), but the transitive closure over *data dependencies*—which attribute of which span was read by which downstream span's prompt assembly. OTel GenAI spans do not natively encode these data edges; they must be reconstructed from prompt contents (e.g., the `request_id` string appearing in a later `chat` span's `gen_ai.prompt`). Absent that reconstruction, the cone is under-approximated and the boundary check passes when it shouldn't. The operational rule: **pin by default, execute by exception, and require an explicit `replay.mode` attribute on every span in the subgraph before replay begins.** If any span lacks `replay.mode`, the replayer must refuse rather than guess. ## Operational Effect When the pinning invariant is enforced, counterfactual debugging becomes *attributable*: a difference in the final answer is provably caused by the mutation set, because every other span's inputs are byte-identical to the recording. When it is not enforced, the replayer produces plausible-looking diffs that misattribute causality—and because the span graph is structurally intact, standard trace validators (which check parent/child integrity, not attribute equality) will not catch it. The practical mitigation is a pre-replay *pin audit* that walks the reconstructed graph, asserts `replay.mode` on every span, and rejects any tool span not explicitly pinned or explicitly marked live-with-cone. This converts a silent semantic corruption into a loud, pre-execution failure. The code below implements the pin audit as a guard that raises when the invariant is violated. ```python from dataclasses import dataclass, field from typing import Optional class ReplayPinningViolation(RuntimeError): """Raised when a counterfactual replay would re-materialize a non-pinned span whose value feeds a descendant LLM span, breaking the pinning invariant.""" pass @dataclass class Span: span_id: str operation: str # e.g. "chat", "execute_tool" replay_mode: Optional[str] # "pin" | "live" | None recorded_attrs: dict = field(default_factory=dict) replayed_attrs: dict = field(default_factory=dict) parent_id: Optional[str] = None def assert_pinning_invariant( spans: list[Span], mutation_set: set[str], causal_cone: dict[str, set[str]], # span_id -> set of downstream span_ids it feeds ) -> None: """Enforce: every span in the causal cone of any mutated span must be either pinned (byte-identical) or explicitly covered by the mutation set. Any span with replay_mode None, or a live span whose cone contains an unpinned tool span, fails.""" by_id = {s.span_id: s for s in spans} for mutated_id in mutation_set: if mutated_id not in by_id: raise ReplayPinningViolation( f"mutation references unknown span {mutated_id!r}" ) for downstream_id in causal_cone.get(mutated_id, set()): s = by_id.get(downstream_id) if s is None: raise ReplayPinningViolation( f"causal cone of {mutated_id!r} references missing span {downstream_id!r}" ) if s.replay_mode is None: raise ReplayPinningViolation( f"span {s.span_id!r} in cone of mutation {mutated_id!r} " f"has no replay.mode; refusing to guess pin-vs-execute" ) if s.replay_mode == "live" and s.operation == "execute_tool": raise ReplayPinningViolation( f"tool span {s.span_id!r} is live inside cone of mutation " f"{mutated_id!r}; non-deterministic output would be " f"misattributed to the mutation" ) if s.replay_mode == "pin" and s.recorded_attrs != s.replayed_attrs: raise ReplayPinningViolation( f"pinned span {s.span_id!r} diverged from recording: " f"recorded={s.recorded_attrs!r} replayed={s.replayed_attrs!r}" ) ```