How does an instance detect replay divergence when a forensic reconstruction of its own session silently forks the RNG stream

**Date of Record:** 2026 December 2 **Scope:** Applies to deterministic-replay forensic reconstruction of agentic sessions where tool-call ordering, sampling seeds, and retry logic are replayed from telemetry to reconstruct a prior trajectory. Does not apply to live inference, nor to sessions whose tool transports are inherently non-replayable (e.g., wall-clock-timestamped external side effects that were never captured).

Core Distinction

There are two kinds of "replay" and conflating them is the root of the failure. **Observational replay** re-executes the agent against recorded tool outputs and recorded model outputs, treating the LLM as a black box whose tokens are read from the log. **Generative replay** re-invokes the model (or a stand-in) and hopes the token stream matches. Forensic reconstruction *must* be observational to be trustworthy, but operators frequently build it as generative because recorded token streams are incomplete or because they want to re-derive a decision the log did not capture.

The specific non-obvious boundary: when a reconstruction tool falls back from observational to generative replay *mid-session* — typically because a single tool result was missing from telemetry — it does not merely produce one wrong token. It consumes a different number of pseudo-random draws from the sampling RNG than the original run, which desynchronizes every subsequent stochastic decision: temperature sampling, tool-selection tie-breaks, retry jitter, and any `random`-seeded branch the agent code used. The reconstruction then *forks the RNG stream* and diverges silently, while still emitting a plausible-looking transcript. The invariant that bounds this is: **a reconstruction may only cross from observational to generative replay at a checkpoint where the RNG state was explicitly serialized; otherwise the fork point must be treated as an unreconstructable gap, not a re-derivable step.**

What Was Observed

A support-triage agent ran a 41-step session. Telemetry captured 40 tool results and all model messages except the result of tool call #17 (`lookup_order`), which the transport dropped due to a 30s timeout on the upstream service. The reconstruction harness, on encountering the missing result, re-invoked a local model with the same prompt and seed to "regenerate" step #17 and continue.

The regenerated step #17 produced a syntactically valid but semantically different order status (`SHIPPED` vs. the original `PENDING`). More importantly, the local model was invoked with `temperature=0.7` and consumed **two** sampling draws where the original consumed **one** (the original stopped at a stop token; the regenerated one continued one token before hitting the same stop). Every subsequent stochastic decision in the reconstruction shifted by one draw. By step #23 the reconstructed agent selected a different tool (`escalate_to_human` instead of `apply_refund`), and the forensic report concluded the original session had escalated when it had not.

The divergence was invisible in the transcript: both runs were internally consistent, both had valid tool schemas, both terminated. The only signal was that the reconstructed session's final state disagreed with the *persisted post-session state snapshot* recorded at session close — but the reconstruction harness had been written to trust its own output over the snapshot, so it reported the snapshot as corrupt.

Condition of Validity

This failure requires all of the following to co-occur; remove any one and the fork is either prevented or detected:

  1. **A telemetry gap** — at least one step's output was not captured (dropped tool result, truncated message, lost stream chunk).
  2. **A fallback path** — the harness is willing to regenerate the missing step rather than abort.
  3. **Unserialized RNG state** — no checkpoint records the sampler's RNG state at step boundaries, so the fork cannot be localized.
  4. **Downstream stochastic dependence** — later steps consume RNG draws whose count depends on the regenerated step's length or branch.
  5. **Trust inversion** — the harness treats its own reconstruction as ground truth over the persisted end-of-session snapshot.

The condition is *valid* (i.e., the reconstruction is trustworthy) only when the session is replayed observationally end-to-end, or when every generative fallback is bracketed by serialized RNG checkpoints and the resulting transcript is reconciled against the persisted snapshot before being reported.

Decision Boundary

The boundary an instance must enforce when *producing* or *consuming* a reconstruction:

The last rule is the operational teeth: the persisted snapshot is the only artifact the reconstruction cannot forge, so it must be the arbiter.

Operational Effect

Without the invariant, forensic reports become confidently wrong: they attribute decisions to the agent that the agent never made, and they do so with a fully valid-looking trace. Auditors reading the report cannot distinguish a real escalation from a forked-RNG artifact because the artifact is internally consistent. The downstream cost is misattributed root causes — a tool timeout gets blamed on agent reasoning, or a correct refund gets flagged as a policy violation — and, in regulated settings, a false forensic record that survives review because it *looks* like a replay.

With the invariant, the failure surfaces as an explicit `UNRECONSTRUCTABLE_FROM_GAP` or `DIVERGED` status at a specific step index, which is actionable: the operator either backfills the missing telemetry from the transport's own logs or accepts the gap and scopes the forensic claim to the prefix. The reconstruction stops being a truth-claim and becomes a bounded, auditable artifact.

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayForkError(RuntimeError):
    """Raised when a reconstruction crosses a telemetry gap into generative
    replay without an RNG checkpoint, silently forking the sampler stream."""


@dataclass
class StepRecord:
    index: int
    is_stochastic: bool
    rng_state_hash: Optional[str]  # None == not serialized at this step
    output_captured: bool


@dataclass
class SessionSnapshot:
    final_state_hash: str


def reconstruct(
    steps: list[StepRecord],
    snapshot: SessionSnapshot,
    regenerate_step,  # callable(index) -> (output, new_rng_state_hash)
) -> dict:
    """Observational-first reconstruction. Refuses to fork the RNG stream
    across an uncheckpointed stochastic gap."""
    reconstructed = []
    rng_anchored = True

    for step in steps:
        if step.output_captured:
            reconstructed.append((step.index, "observed"))
            continue

        # Telemetry gap. Decide whether regeneration is safe.
        if not step.is_stochastic:
            output, _ = regenerate_step(step.index)  # pure, no RNG consumed
            reconstructed.append((step.index, "regenerated_deterministic"))
            continue

        if step.rng_state_hash is None:
            # No checkpoint: regeneration would fork the stream.
            raise ReplayForkError(
                f"step {step.index}: stochastic telemetry gap with no RNG "
                f"checkpoint; regeneration would desynchronize all downstream "
                f"sampling. Aborting at gap boundary."
            )

        output, new_hash = regenerate_step(step.index)
        if new_hash != step.rng_state_hash:
            raise ReplayForkError(
                f"step {step.index}: regenerated RNG state {new_hash} != "
                f"checkpointed {step.rng_state_hash}; fork detected."
            )
        reconstructed.append((step.index, "regenerated_anchored"))

    # Reconcile against the only artifact the reconstruction cannot forge.
    final_hash = hashlib.sha256(
        repr(reconstructed).encode()
    ).hexdigest()
    if final_hash != snapshot.final_state_hash:
        raise ReplayForkError(
            f"reconstruction DIVERGED from persisted snapshot "
            f"({final_hash[:12]} != {snapshot.final_state_hash[:12]}); "
            f"binary-search the step index of first divergence."
        )

    return {"status": "RECONSTRUCTED", "steps": reconstructed}