# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-replay-is-diverging-unrecorded-reads-as-the-hidden-input-channel-in-multi-agent-incident-forensics.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-replay-is-diverging-unrecorded-reads-as-the-hidden-input-channel-in-multi-agent-incident-forensics.warrant.json
# Markdown SHA-256:   b1ea0160e82658803ca1aa91493476ba9970200eb0f4727ad892a048c974c97f
# Code AST SHA-256:   0a3a1ec5801a55720f26cee16401f9995fd5caa1237a5e7a85d12dc0372c0150
# Verified Classes:   ReplayDivergenceError, DecisionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ReplayDivergenceError(RuntimeError):
    """Raised when a causal replay's input tuple diverges from the recorded tuple.

    A divergence here means an unrecorded read (ambient state, harness-side
    retrieval, or cache-served value) resolved differently at replay time than
    at incident time. The replay is invalid at and after this step; any
    counterfactual conclusion drawn downstream of it is unsound.
    """


@dataclass(frozen=True)
class DecisionRecord:
    step: int
    input_tuple: bytes          # fully resolved prompt + served reads + ambient values
    output: bytes


def certify_replay_step(recorded: DecisionRecord, replayed: DecisionRecord) -> None:
    if recorded.step != replayed.step:
        raise ReplayDivergenceError(
            f"step mismatch: recorded {recorded.step}, replayed {replayed.step}"
        )
    if recorded.input_tuple != replayed.input_tuple:
        # Input-divergent: unrecorded read. Do NOT fall through to output comparison.
        raise ReplayDivergenceError(
            f"unrecorded read at step {recorded.step}: input tuples differ "
            f"({len(recorded.input_tuple)}B vs {len(replayed.input_tuple)}B); "
            f"replay is invalid downstream of this step"
        )
    if recorded.output != replayed.output:
        # Input-identical, output-divergent: genuine nondeterminism, not a replay artifact.
        raise ReplayDivergenceError(
            f"nondeterministic completion at step {recorded.step}: inputs identical, "
            f"outputs differ; investigate sampling/model-version drift, not the log"
        )


def find_first_divergence(
    recorded: list[DecisionRecord], replayed: list[DecisionRecord]
) -> int:
    """Walk forward; return the first step whose input tuple differs from the record.

    The reported divergence step from an output-diffing harness is a lower bound.
    The true first divergence is the first step whose *input* differs, which is
    by construction an unrecorded read if the log is read-incomplete.
    """
    for rec, rep in zip(recorded, replayed):
        if rec.input_tuple != rep.input_tuple:
            return rec.step
        certify_replay_step(rec, rep)
    raise ReplayDivergenceError(
        "no input divergence found in recorded window; replay is read-complete "
        "over this window and any output divergence is genuine nondeterminism"
    )
