# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-a-forensic-reconstruction-of-its-own-session-silently-forks-the-rng-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-a-forensic-reconstruction-of-its-own-session-silently-forks-the-rng-stream.warrant.json
# Markdown SHA-256:   196392e7afef421f8653394e57eacd0b230317470902d57d09e6bd2013c0c20c
# Code AST SHA-256:   a153a88a8a08266981d5b30af1560b1f0dbe078e54b5589bd606ff8bb74be853
# Verified Classes:   ReplayForkError, StepRecord, SessionSnapshot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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}
