# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quorum-certification-drift-when-irreversible-tool-actions-are-authorized-across-a-consensus-epoch-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quorum-certification-drift-when-irreversible-tool-actions-are-authorized-across-a-consensus-epoch-boundary.warrant.json
# Markdown SHA-256:   eb71af4711ffe4a1907f767f3d133b37154a2a5d56d0f4d9e2dc2bc9b20800b0
# Code AST SHA-256:   fe0fcca3426b7b0e67d681e7e58c6b010a96e547521c3e1d84474a869f1a8126
# Verified Classes:   QuorumCertificationError, Warrant, EpochState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class QuorumCertificationError(RuntimeError):
    """Raised when a warrant cannot certify a quorum under the executing epoch."""
    pass


@dataclass(frozen=True)
class Warrant:
    proposal_hash: str
    epoch: int
    policy_hash: str
    votes: Set[str]          # voter ids that returned approve
    declared_threshold: int  # threshold as computed at mint time


@dataclass
class EpochState:
    epoch: int
    policy_hash: str
    seated: Dict[str, int]   # voter id -> weight
    threshold: int


def validate_irreversible_warrant(w: Warrant, current: EpochState) -> None:
    # Condition 2: policy identity. A changed policy voids the arithmetic.
    if w.policy_hash != current.policy_hash:
        raise QuorumCertificationError(
            f"policy drift: warrant minted under {w.policy_hash}, "
            f"executing under {current.policy_hash}; warrant void"
        )

    # Condition 1 + 3: seated-intersection quorum under the EXECUTING epoch.
    # Votes from de-seated voters do not count, even if the raw count passes.
    seated_votes = {v for v in w.votes if v in current.seated}
    seated_weight = sum(current.seated[v] for v in seated_votes)

    if seated_weight < current.threshold:
        raise QuorumCertificationError(
            f"quorum invalid at execution: warrant epoch {w.epoch} "
            f"(declared threshold {w.declared_threshold}, raw votes {len(w.votes)}) "
            f"but seated-intersection weight {seated_weight} < "
            f"executing threshold {current.threshold} at epoch {current.epoch}; "
            f"de-seated voters {sorted(w.votes - seated_votes)} dropped"
        )

    # Fast path only when the warrant was minted under the executing epoch.
    if w.epoch == current.epoch and w.declared_threshold != current.threshold:
        raise QuorumCertificationError(
            f"threshold mismatch at same epoch {current.epoch}: "
            f"warrant says {w.declared_threshold}, epoch says {current.threshold}"
        )


# --- reproduction of the observed failure ---
warrant = Warrant(
    proposal_hash="p",
    epoch=7,
    policy_hash="H7",
    votes={"A", "C"},
    declared_threshold=2,
)

epoch8 = EpochState(
    epoch=8,
    policy_hash="H8",
    seated={"A": 1, "B": 1, "D": 1},
    threshold=2,
)

try:
    validate_irreversible_warrant(warrant, epoch8)
except QuorumCertificationError as e:
    print(f"BLOCKED irreversible action: {e}")
