# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-silently-when-speculative-branch-rollback-restores-state-but-not-the-cost-ledger-s-monotonic-fan-out-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-silently-when-speculative-branch-rollback-restores-state-but-not-the-cost-ledger-s-monotonic-fan-out-watermark.warrant.json
# Markdown SHA-256:   bfadc55ade2de56952fb32ead88f6de6431d8a84ac13cedc2e4c96744ced7e1c
# Code AST SHA-256:   99bc737b40e6d2134c5fd5300e64ad575863233aa1d79674b66f4e276ef6387e
# Verified Classes:   SpeculativeRollbackDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeRollbackDivergence(RuntimeError):
    """Raised when a speculative round's accounting plane disagrees with its
    execution plane after rollback: the verifier's expected quorum no longer
    matches the set of branches actually admitted for the current round."""
    pass


def open_verification_barrier(round_state: dict, ledger: dict) -> int:
    admitted = round_state["admitted_branches"]          # live branches this round
    expected_quorum = round_state["verifier_expected_quorum"]
    watermark = ledger["fanout_watermark"]               # monotonic, NOT rolled back
    live_peak = round_state["live_peak"]

    # Invariant 1: quorum must be bound to the admitted set, not the watermark.
    if expected_quorum != admitted:
        raise SpeculativeRollbackDivergence(
            f"quorum mismatch: verifier expects {expected_quorum} votes but "
            f"only {admitted} branches were admitted this round "
            f"(watermark={watermark}, live_peak={live_peak}); a prior rollback "
            f"inflated the watermark without resetting the verifier's expectation"
        )

    # Invariant 2: watermark must not exceed the live peak of the current round.
    if watermark > live_peak:
        raise SpeculativeRollbackDivergence(
            f"watermark {watermark} exceeds live_peak {live_peak}: monotonic "
            f"counter survived rollback and will under-admit future fan-out"
        )

    return admitted  # barrier may safely open
