# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-rollback-divergence-when-speculative-branches-share-a-mutable-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-rollback-divergence-when-speculative-branches-share-a-mutable-tool-sandbox.warrant.json
# Markdown SHA-256:   43a6c374e411c994ce89a7ab839ca18038714e0ea169a38dabd35aa97172b5cb
# Code AST SHA-256:   5b716fcd231a7c461d8aba833c676d6623c166bc6e66488ea4e0b545444efd1b
# Verified Classes:   RollbackDivergenceError, BranchResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class RollbackDivergenceError(RuntimeError):
    """Raised when a selected branch's verdict no longer reproduces after sibling rollback."""
    pass


@dataclass
class BranchResult:
    branch_id: str
    verdict: str                      # "PASS" / "FAIL"
    read_provenance: str              # content hash of state observed at verification time
    writes: list = field(default_factory=list)


def state_identity(probe: Callable[[], bytes]) -> str:
    return hashlib.sha256(probe()).hexdigest()


def commit_with_divergence_gate(
    winner: BranchResult,
    losers: list,
    rollback: Callable[[BranchResult], None],
    probe: Callable[[], bytes],
    replay_verify: Callable[[], str],
) -> str:
    # 1. Quiesce + roll back every losing branch.
    for b in losers:
        rollback(b)

    # 2. Post-rollback state identity must equal what the winner read.
    post_rollback_id = state_identity(probe)
    if post_rollback_id != winner.read_provenance:
        raise RollbackDivergenceError(
            f"branch {winner.branch_id} verified against {winner.read_provenance[:12]}, "
            f"but post-rollback world is {post_rollback_id[:12]}; "
            f"winner's verdict was computed against state erased by sibling rollback"
        )

    # 3. Replay the winner's verification against the settled world.
    replayed = replay_verify()
    if replayed != winner.verdict:
        raise RollbackDivergenceError(
            f"branch {winner.branch_id} recorded verdict {winner.verdict!r} "
            f"but replay against settled world yields {replayed!r}"
        )

    return winner.verdict
