# Which invariants prevent replay divergence when agent traces are reconstructed from lossy span logs **Date of Record:** 2026 December 4 **Scope:** Applies to forensic replay of agentic execution traces reconstructed from span/event logs that omit full prompt bodies, tool response bytes, or sampling parameters. Does not apply to deterministic replay from complete byte-exact transcripts (e.g., full request/response capture at the model gateway). ## Core Distinction There are two things practitioners conflate under "replay": *re-execution* and *reconstruction*. Re-execution re-runs the agent loop against recorded inputs and asserts output equality. Reconstruction rebuilds the causal chain from logged spans so an auditor can explain *why* step N happened, without ever invoking a model. The boundary failure lives in reconstruction: a span log is a lossy projection of the agent's actual state, and naive reconstruction silently fabricates a consistent-looking trace whose causal edges were never in the log. The trace *looks* deterministic — same nodes, same order — while the edges that justified each decision were inferred, not observed. This is the replay-divergence trap: the reconstructed trace agrees with itself and disagrees with what happened. ## What Was Observed An agent performing a multi-tool task emitted spans of the form `{span_id, parent_id, tool_name, args_digest, status, latency_ms}`. The `args_digest` was a hash, not the args. The model's reasoning text was logged only when `verbosity=debug`, which production ran without. On a post-incident reconstruction, the auditor replayed the span tree and found a tool call B whose `args_digest` matched a prior call A's digest, so the reconstructor "deduplicated" B as a retry of A and dropped it. But B was a *distinct* call with a colliding digest on a different input — the digest was over a truncated canonical form that elided a list-ordering field. The reconstructed trace showed one call; the agent had made two, and the second one returned the poisoned result that drove the failure. The reconstruction was internally consistent, deterministic, and wrong. The trigger condition: any reconstruction rule that infers identity or causality from *derived* fields (digests, hashes, timestamps, ordinal positions) rather than from *recorded* fields, combined with a lossy canonicalization whose collision domain is unpopulated by the log. The failure trace: digest collision → false dedup → causal edge dropped → downstream decisions re-parented to a surviving node → reconstructed justification diverges from the actual one, with no error raised because every reconstructed node still validates against its own parent. ## Condition of Validity Reconstruction is only sound when three invariants hold simultaneously: 1. **Provenance completeness:** every causal edge in the reconstructed DAG is either (a) directly recorded as a parent/child span link, or (b) explicitly marked `inferred` with the inference rule named. An edge that is neither is a fabrication. 2. **Digest injectivity within the log's domain:** any field used to establish identity (dedup, retry-detection, ordering) must be injective over the set of values actually present, or the reconstruction must refuse to merge on it. A truncated hash is not injective; merging on it violates the invariant. 3. **Replay determinism under substitution:** if the reconstructor substitutes a placeholder for an unlogged field (e.g., `reasoning="[not captured]"`), the substitution must not change any downstream identity, ordering, or dedup decision. If it does, the reconstruction is order-dependent on missing data and is not replayable. When any invariant is violated, the correct behavior is to *refuse* to produce a causal trace and emit a partial, explicitly-flagged reconstruction — not to fill the gap with the most plausible edge. ## Decision Boundary The boundary is: **may the reconstructor merge, reorder, or re-parent spans based on derived fields?** The answer is no unless digest injectivity is proven over the observed value set. In practice this means the reconstructor must: - Treat `args_digest` equality as *candidate* identity only, and require a second recorded field (full args, or a length+digest pair) to confirm before merging. - Never infer parentage from timestamp proximity or span ordinal; only from recorded `parent_id`. - Mark every inferred edge with its rule and confidence, and fail the reconstruction if an inferred edge is load-bearing for a decision the auditor is asked to explain. The failure mode this bounds is the one above: a plausible, deterministic, self-consistent trace that misattributes causation. The guardrail is to make inference *visible and non-authoritative* — the auditor sees "B inferred as retry of A via digest, unconfirmed" rather than a silent merge. ## Operational Effect After enforcing these invariants, reconstructions that previously "succeeded" now return `PartialReconstruction` with explicit gaps, and the incident review must treat those gaps as unknowns rather than resolved. The operational cost is that some forensic questions become unanswerable from logs alone and require re-execution against captured inputs. The benefit is that a reconstructed trace can no longer manufacture a causal story that contradicts the actual execution — the auditor's reconstruction and the agent's real behavior are forced to agree or to disagree *visibly*. Silent divergence is the failure; flagged divergence is the invariant working. ```python from dataclasses import dataclass, field from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when a reconstructed trace asserts causality not supported by the log.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] tool_name: str args_digest: str args_full: Optional[str] = None # None when log elided args status: str = "ok" @dataclass class ReconstructedEdge: child: str parent: str inferred: bool rule: Optional[str] = None def reconstruct(spans: list[Span]) -> list[ReconstructedEdge]: by_id = {s.span_id: s for s in spans} edges: list[ReconstructedEdge] = [] # Invariant 1: recorded parentage is authoritative. for s in spans: if s.parent_id is not None: if s.parent_id not in by_id: raise ReplayDivergenceError( f"span {s.span_id} references missing parent {s.parent_id}; " "cannot reconstruct causal chain" ) edges.append(ReconstructedEdge(s.span_id, s.parent_id, inferred=False)) # Invariant 2: digest-based identity may only merge when injective over observed set. digest_groups: dict[str, list[Span]] = {} for s in spans: digest_groups.setdefault(s.args_digest, []).append(s) for digest, group in digest_groups.items(): if len(group) < 2: continue # Candidate retry cluster: confirm identity using full args if available. confirmed = {s.args_full for s in group if s.args_full is not None} if any(s.args_full is None for s in group): raise ReplayDivergenceError( f"digest {digest} collides across {len(group)} spans with elided args; " "cannot prove retry vs distinct call — refusing to merge" ) if len(confirmed) > 1: # Distinct calls sharing a lossy digest. Do NOT dedup; record as inferred- # distinct and surface to auditor. for s in group: edges.append( ReconstructedEdge( child=s.span_id, parent=s.parent_id or "", inferred=True, rule="digest-collision-distinct", ) ) else: # Genuine retry: merge downstream of the first occurrence. first = min(group, key=lambda s: s.span_id) for s in group: if s.span_id != first.span_id: edges.append( ReconstructedEdge( child=s.span_id, parent=first.span_id, inferred=True, rule="confirmed-retry", ) ) # Invariant 3: any load-bearing inferred edge fails the reconstruction unless # the auditor has declared it acceptable. load_bearing = {e.child for e in edges if e.inferred} if load_bearing: raise ReplayDivergenceError( f"reconstruction contains {len(load_bearing)} inferred load-bearing edges; " "emit PartialReconstruction instead of asserting a causal trace" ) return edges ```