# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-attestation-boundary-when-a-byzantine-peer-can-forge-liveness-proofs-to-stall-a-bft-agent-council.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-attestation-boundary-when-a-byzantine-peer-can-forge-liveness-proofs-to-stall-a-bft-agent-council.warrant.json
# Markdown SHA-256:   bfd09d2655f112b60083e04b4d2b26c9bd4c9ac00196202fc40c815809959c47
# Code AST SHA-256:   e7f34a96206aac0c966c76ea7a57e7e5b999491c1f9b8ce124463106fe1890b7
# Verified Classes:   QuorumStallError, CouncilView
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class QuorumStallError(RuntimeError):
    """Raised when a view cannot reach commit quorum within T_commit despite heartbeats."""
    pass


@dataclass
class CouncilView:
    n_peers: int
    f_byzantine: int
    t_commit_seconds: float = 2.0
    prepares: dict = field(default_factory=dict)   # peer_id -> bool
    commits: dict = field(default_factory=dict)    # peer_id -> bool
    first_quorum_prepare_at: float | None = None
    strikes: dict = field(default_factory=dict)    # peer_id -> int

    @property
    def quorum(self) -> int:
        return 2 * self.f_byzantine + 1

    def record_prepare(self, peer_id: str, now: float) -> None:
        self.prepares[peer_id] = True
        if self.first_quorum_prepare_at is None and len(self.prepares) >= self.n_peers - self.f_byzantine:
            self.first_quorum_prepare_at = now

    def record_commit(self, peer_id: str) -> None:
        self.commits[peer_id] = True

    def check_commit_progress(self, now: float, heartbeats_seen: bool) -> bool:
        """Returns True if committed. Raises QuorumStallError if stalled past T_commit.

        Critically: heartbeats_seen is IGNORED for the stall decision. A peer that
        heartbeats but withholds its commit must not suppress the view change.
        """
        if len(self.commits) >= self.quorum:
            return True

        if self.first_quorum_prepare_at is None:
            return False  # not yet at prepare quorum; normal

        stalled_for = now - self.first_quorum_prepare_at
        if stalled_for > self.t_commit_seconds:
            # Attribute the missing commit to peers that prepared but did not commit.
            missing = [p for p in self.prepares if p not in self.commits]
            for peer in missing:
                self.strikes[peer] = self.strikes.get(peer, 0) + 1
            raise QuorumStallError(
                f"commit quorum {self.quorum} unreachable after {stalled_for:.2f}s; "
                f"missing commits from {missing}; heartbeats_seen={heartbeats_seen} "
                f"(heartbeats do not count as progress)"
            )
        return False


def run_consensus_round(view: CouncilView, clock=time.monotonic) -> bool:
    """Drive one view to commit or raise QuorumStallError to force a view change."""
    now = clock()
    # simulate: all peers prepared, but one withholds commit while heartbeating
    for peer in [f"A{i}" for i in range(view.n_peers)]:
        view.record_prepare(peer, now)
    for peer in [f"A{i}" for i in range(view.n_peers - 1)]:
        view.record_commit(peer)

    # heartbeats arrive from all peers including the withholder
    heartbeats_seen = True
    # advance clock past T_commit
    now = now + view.t_commit_seconds + 0.5

    if not view.check_commit_progress(now, heartbeats_seen):
        raise QuorumStallError("consensus did not commit and did not stall-detect — invariant broken")
    return True


if __name__ == "__main__":
    v = CouncilView(n_peers=7, f_byzantine=2, t_commit_seconds=2.0)
    try:
        run_consensus_round(v)
    except QuorumStallError as e:
        print(f"view change forced: {e}")
        print(f"strikes: {v.strikes}")
