# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-abort-a-cross-org-speculative-handoff-when-its-consistency-proof-cannot-be-revalidated-against-a-peer-s-post-failure-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-abort-a-cross-org-speculative-handoff-when-its-consistency-proof-cannot-be-revalidated-against-a-peer-s-post-failure-state.warrant.json
# Markdown SHA-256:   e1d5701b14e987adc021c4d28f8a97fd3960f2d622b52d486635e19e61ef1b62
# Code AST SHA-256:   bb409f6b7d3c82cf62b79a26006583bd96061dcfae6429c28cc4923e3b34f56d
# Verified Classes:   HandoffProofError, ProofVerdict, ConsistencyProof, PeerState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class HandoffProofError(RuntimeError):
    """Raised when a speculative handoff cannot be soundly committed."""


class ProofVerdict(Enum):
    VALID = "valid"
    UNRESOLVABLE = "unresolvable"
    FALSIFIED = "falsified"


@dataclass(frozen=True)
class ConsistencyProof:
    slice_digest: str
    transcript_merkle_root: str
    post_state_hash: str
    a_epoch: int
    ttl_epochs: int


@dataclass(frozen=True)
class PeerState:
    transcript_merkle_root: str
    post_state_hash: str
    a_epoch: int
    slice_append_only: bool


def classify(proof: ConsistencyProof, peer: PeerState) -> ProofVerdict:
    if not peer.slice_append_only:
        # No immutability guarantee: any drift is unsound to speculate on.
        return ProofVerdict.FALSIFIED
    if peer.a_epoch < proof.a_epoch:
        return ProofVerdict.FALSIFIED  # epoch regression
    if peer.a_epoch - proof.a_epoch > proof.ttl_epochs:
        return ProofVerdict.FALSIFIED  # witness liveness expired
    if peer.transcript_merkle_root == proof.transcript_merkle_root:
        if peer.post_state_hash != proof.post_state_hash:
            return ProofVerdict.FALSIFIED
        return ProofVerdict.VALID
    # Root drifted with epoch advance: compaction vs fork is decided by
    # whether the attested post-state survived the transition.
    if peer.post_state_hash == proof.post_state_hash:
        return ProofVerdict.UNRESOLVABLE  # benign compaction, retry
    return ProofVerdict.FALSIFIED  # fork: attested state superseded


def commit_speculative_branch(
    proof: ConsistencyProof,
    peer: PeerState,
    retries_used: int,
    max_retries: int,
) -> str:
    verdict = classify(proof, peer)

    if verdict is ProofVerdict.FALSIFIED:
        raise HandoffProofError(
            f"proof falsified at A_epoch={peer.a_epoch} "
            f"(proof epoch={proof.a_epoch}, post_state match="
            f"{peer.post_state_hash == proof.post_state_hash})"
        )

    if verdict is ProofVerdict.UNRESOLVABLE:
        if retries_used >= max_retries:
            # Budget exhaustion is NOT promotion to VALID.
            raise HandoffProofError(
                f"unresolvable proof after {retries_used} retries; "
                f"refusing to commit speculative branch"
            )
        # Caller must re-fetch leaves at peer.a_epoch and re-invoke.
        return "RETRY"

    # VALID: derive the commit token from the attested post-state.
    return hashlib.sha256(
        (proof.post_state_hash + ":" + str(peer.a_epoch)).encode()
    ).hexdigest()
