# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-a-tool-call-s-non-determinism-is-quarantined-outside-the-decision-provenance-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-a-tool-call-s-non-determinism-is-quarantined-outside-the-decision-provenance-hash.warrant.json
# Markdown SHA-256:   099c130bee30286b7d9d0a62affa00812b962107fc56bc5716f3b16a38ccad58
# Code AST SHA-256:   a3c45c13c288dd4fdf634147a656941e9d5674035d3fc09dad797befc8a33299
# Verified Classes:   ProvenanceReplayDivergence, PipelineFingerprint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceReplayDivergence(RuntimeError):
    """Raised when a trajectory replay re-derives an observation whose
    processing-pipeline fingerprint differs from the one captured, making
    the decision divergence uninterpretable as counterfactual evidence."""
    pass


@dataclass(frozen=True)
class PipelineFingerprint:
    truncator_version: str
    tokenizer_hash: str
    normalizer_config_hash: str

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.truncator_version.encode())
        h.update(self.tokenizer_hash.encode())
        h.update(self.normalizer_config_hash.encode())
        return h.hexdigest()


def observation_hash(raw_payload: bytes, fp: PipelineFingerprint) -> str:
    # Preimage MUST include the fingerprint, not just the processed bytes.
    h = hashlib.sha256()
    h.update(fp.digest().encode())
    h.update(raw_payload)
    return h.hexdigest()


def replay_step(
    recorded_hash: str,
    recorded_fp: PipelineFingerprint,
    live_fp: PipelineFingerprint,
    live_raw_payload: bytes,
) -> str:
    if recorded_fp.digest() != live_fp.digest():
        # Pipeline drifted between capture and replay: the re-derived
        # observation is a new observation, not a replay. Refuse.
        raise ProvenanceReplayDivergence(
            f"pipeline fingerprint drift: captured={recorded_fp.digest()} "
            f"live={live_fp.digest()}; counterfactual attribution invalid"
        )
    recomputed = observation_hash(live_raw_payload, live_fp)
    if recomputed != recorded_hash:
        raise ProvenanceReplayDivergence(
            f"observation hash mismatch under matching fingerprint: "
            f"recorded={recorded_hash} recomputed={recomputed}"
        )
    return recomputed
