# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-quorum-as-byzantine-faulty-rather-than-merely-slow-when-adaptive-speculation-depth-masks-di.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-quorum-as-byzantine-faulty-rather-than-merely-slow-when-adaptive-speculation-depth-masks-di.warrant.json
# Markdown SHA-256:   9480ae9d01069a178415a7ebd83a678e62f16fa5a05cbd97dbfa56b29aa22c55
# Code AST SHA-256:   2703bf24ff30be576c50395441bafb52206892071c492b16c24cbbc2a413c9b1
# Verified Classes:   QuorumEpochViolation, Epoch, StepDispatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class QuorumEpochViolation(RuntimeError):
    """Raised when a quorum tally is evaluated against a configuration
    that differs from the one frozen at dispatch, or when f was inferred
    from observed dissent rather than the epoch's configured fault budget."""


@dataclass(frozen=True)
class Epoch:
    epoch_id: int
    members: FrozenSet[str]
    fault_budget: int  # f, fixed by configuration, never by observed dissent

    def quorum_threshold(self) -> int:
        # BFT: need 2f+1 of a 3f+1 set; here expressed as majority over members
        # with explicit f. Threshold is a property of the epoch, not the tally.
        return 2 * self.fault_budget + 1


@dataclass
class StepDispatch:
    step_id: str
    dispatch_epoch: Epoch
    votes: dict = field(default_factory=dict)  # peer_id -> (epoch_id, result)


def tally_quorum(dispatch: StepDispatch, committed_result) -> bool:
    frozen = dispatch.dispatch_epoch
    valid_votes = {}
    for peer_id, (vote_epoch_id, result) in dispatch.votes.items():
        if vote_epoch_id != frozen.epoch_id:
            # Late vote from an unattested/admittee peer: discard, do not count,
            # and do not let its arrival change the threshold.
            continue
        if peer_id not in frozen.members:
            raise QuorumEpochViolation(
                f"step {dispatch.step_id}: vote from {peer_id} not in frozen "
                f"epoch {frozen.epoch_id} member set {sorted(frozen.members)}"
            )
        valid_votes[peer_id] = result

    # Safety check: f must equal the epoch's configured budget. If a caller
    # mutated f based on how many peers dissented, the bound is invalid.
    if frozen.fault_budget != _configured_f(frozen.epoch_id):
        raise QuorumEpochViolation(
            f"step {dispatch.step_id}: fault budget {frozen.fault_budget} "
            f"diverged from configured f for epoch {frozen.epoch_id}"
        )

    threshold = frozen.quorum_threshold()
    agreeing = sum(1 for r in valid_votes.values() if r == committed_result)
    if agreeing < threshold:
        return False
    # A quorum met only because depth grew mid-flight is void: require that
    # the agreeing set is a subset of the frozen members (it is, by construction)
    # AND that no depth transition occurred for this step.
    if _depth_changed_since(dispatch.step_id, frozen.epoch_id):
        raise QuorumEpochViolation(
            f"step {dispatch.step_id}: depth adapted during dispatch window; "
            f"quorum void, re-dispatch under a single frozen epoch"
        )
    return True


def _configured_f(epoch_id: int) -> int:
    return CONFIG_EPOCHS[epoch_id].fault_budget


def _depth_changed_since(step_id: str, epoch_id: int) -> bool:
    return DEPTH_TRANSITIONS.get(step_id, epoch_id) != epoch_id


CONFIG_EPOCHS: dict = {}
DEPTH_TRANSITIONS: dict = {}
