# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-as-unreachable-rather-than-merely-slow-liveness-attestation-starvation-under-equivocating-auditors.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-as-unreachable-rather-than-merely-slow-liveness-attestation-starvation-under-equivocating-auditors.warrant.json
# Markdown SHA-256:   3a4eab48afd716c38e488f49820f01a5ed3426a0bcc4a953969ff26b654cad67
# Code AST SHA-256:   67b7a38db42e0599d254659d4ec9c858c226b1cd93c5ae5d56b136845ccca32e
# Verified Classes:   QuorumStarvationError, SignedVote, LivenessAttestation, QuorumView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class QuorumStarvationError(RuntimeError):
    """Raised when a quorum extends its deadline on attestations that cannot
    distinguish a slow honest peer from an equivocating Byzantine peer."""
    pass


@dataclass
class SignedVote:
    voter: str
    view: int
    decision: str          # "APPROVE" | "DENY"
    ts: float
    signature: str


@dataclass
class LivenessAttestation:
    peer: str
    ts: float
    signature: str


@dataclass
class QuorumView:
    view: int
    n: int
    f: int
    quorum: int = field(init=False)
    votes: Dict[str, SignedVote] = field(default_factory=dict)
    attestations: Dict[str, LivenessAttestation] = field(default_factory=dict)
    suspect_peers: Set[str] = field(default_factory=set)
    conflicting_votes: Dict[str, Tuple[SignedVote, SignedVote]] = field(default_factory=dict)
    deadline: float = 0.0

    def __post_init__(self):
        self.quorum = 2 * self.f + 1

    def record_vote(self, v: SignedVote) -> None:
        prior = self.votes.get(v.voter)
        if prior is not None and prior.decision != v.decision and prior.view == v.view:
            self.conflicting_votes[v.voter] = (prior, v)
            self.suspect_peers.add(v.voter)
        self.votes[v.voter] = v

    def record_attestation(self, a: LivenessAttestation) -> None:
        self.attestations[a.peer] = a

    def has_quorum_certificate(self, decision: str) -> bool:
        # A certificate requires 2f+1 distinct voters for the SAME decision
        # in the SAME view. A raw count is insufficient under equivocation.
        agreeing = {
            v.voter for v in self.votes.values()
            if v.decision == decision and v.view == self.view
        }
        return len(agreeing) >= self.quorum

    def count_fresh_non_suspect_attestations(self, now: float, grace: float) -> int:
        return sum(
            1 for a in self.attestations.values()
            if a.peer not in self.suspect_peers and (now - a.ts) <= grace
        )

    def decide_at_deadline(
        self,
        now: float,
        grace: float,
        max_view_duration: float,
        view_started: float,
    ) -> str:
        # Self-observed equivocation is authoritative: block extension.
        if self.conflicting_votes:
            return "VIEW_CHANGE"

        # Peer-reported equivocation is advisory: only the reporter is
        # excluded from liveness accounting, handled in the count above.

        fresh = self.count_fresh_non_suspect_attestations(now, grace)
        within_cap = (now - view_started) < max_view_duration

        if fresh >= self.quorum and within_cap:
            return "EXTEND"
        return "VIEW_CHANGE"


def await_quorum_decision(
    view: QuorumView,
    now_fn,
    grace: float = 0.5,
    max_view_duration: float = 5.0,
    view_started: float = 0.0,
) -> str:
    now = now_fn()
    if now < view.deadline:
        raise QuorumStarvationError(
            f"deadline not yet reached for view {view.view}; "
            f"caller must not evaluate early"
        )

    action = view.decide_at_deadline(now, grace, max_view_duration, view_started)

    if action == "EXTEND":
        # Only extend when we have positive evidence of non-suspect liveness
        # AND we have not observed self-authoritative equivocation.
        if view.conflicting_votes:
            # Defensive: decide_at_deadline should have caught this.
            raise QuorumStarvationError(
                f"attempted to extend view {view.view} despite "
                f"self-observed equivocation by {sorted(view.conflicting_votes)}"
            )
        view.deadline = now + grace
        return "EXTEND"

    if action == "VIEW_CHANGE":
        # Escalation is the correct action when attestation-before-progress
        # cannot be satisfied. Surface the evidence, not a bare timeout.
        suspects = sorted(view.suspect_peers)
        if not suspects and (now - view_started) >= max_view_duration:
            # No suspect, but we hit the cap: this is a possible partition.
            # Still escalate, but flag it as a partition-suspected view change.
            return f"VIEW_CHANGE(partition_suspected,view={view.view})"
        return f"VIEW_CHANGE(suspects={suspects},view={view.view})"

    raise QuorumStarvationError(f"unreachable action {action}")
