# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-silence-as-a-vote-and-when-must-it-treat-silence-as-an-abstention-that-shrinks-the-qu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-silence-as-a-vote-and-when-must-it-treat-silence-as-an-abstention-that-shrinks-the-qu.warrant.json
# Markdown SHA-256:   56ade3c9716b0bff85f32677eac0d104571f5f319782a937cdd3eba42408d3f7
# Code AST SHA-256:   319e3565f7e8a069d244e18725cc7a1f2dd3c16c77644f23cd0132210140b4bd
# Verified Classes:   QuorumAbstentionViolation, QuorumTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class QuorumAbstentionViolation(RuntimeError):
    """Raised when an instance reinterprets agent silence as abstention
    without satisfying the liveness-attestation conditions S1-S3, or when
    it shrinks the quorum denominator below the safety floor N - f."""
    pass


class QuorumTracker:
    def __init__(self, n_agents: int, f_byzantine: int):
        self.n = n_agents
        self.f = f_byzantine
        self.safety_floor = n_agents - f_byzantine
        self.epoch = 0
        # epoch -> set of agent ids that have attested to a suspect's liveness
        self.attestations: dict[int, dict[str, set[str]]] = {}

    def record_attestation(self, epoch: int, suspect: str, attester: str) -> None:
        if epoch < self.epoch:
            # Stale attestation from a superseded epoch: discard (Condition S2).
            return
        self.attestations.setdefault(epoch, {}).setdefault(suspect, set()).add(attester)

    def resolve_silence(
        self,
        epoch: int,
        suspect: str,
        responding_agents: set[str],
        pending_votes: dict[str, str],
    ) -> tuple[int, int]:
        """Return (effective_denominator, threshold) for the current epoch.

        Raises QuorumAbstentionViolation if the instance attempts to shrink
        the denominator without meeting Conditions S1-S3, or below the floor.
        """
        if epoch != self.epoch:
            raise QuorumAbstentionViolation(
                f"epoch mismatch: resolving epoch {epoch} while current is {self.epoch}"
            )

        attested = self.attestations.get(epoch, {}).get(suspect, set())

        # Condition S1 + S3: at least f + 1 distinct same-epoch attestations.
        if len(attested) < self.f + 1:
            # Silence must remain PENDING; the decision blocks. Do not shrink.
            return self.n, (2 * self.n) // 3 + 1

        # Condition S2: attestations must be from the current epoch (already
        # enforced by the key lookup above, but assert for clarity).
        if not attested.issubset(responding_agents | {suspect}):
            raise QuorumAbstentionViolation(
                f"attestations for {suspect} include non-participating agents"
            )

        effective_n = self.n - 1
        if effective_n < self.safety_floor:
            raise QuorumAbstentionViolation(
                f"denominator {effective_n} below safety floor {self.safety_floor}; "
                f"epoch must abort and re-elect, not commit"
            )

        # Threshold MUST be recomputed from the shrunk denominator.
        threshold = (2 * effective_n) // 3 + 1
        return effective_n, threshold


def commit_decision(
    tracker: QuorumTracker,
    epoch: int,
    suspect: str,
    responding_agents: set[str],
    votes: dict[str, str],
) -> str:
    effective_n, threshold = tracker.resolve_silence(
        epoch=epoch,
        suspect=suspect,
        responding_agents=responding_agents,
        pending_votes=votes,
    )
    accepts = sum(1 for v in votes.values() if v == "accept")
    if accepts >= threshold:
        return "COMMITTED"
    rejects = sum(1 for v in votes.values() if v == "reject")
    if rejects >= threshold:
        return "ABORTED"
    # Neither side reaches the recomputed threshold: block, do not shrink further.
    if effective_n <= tracker.safety_floor:
        raise QuorumAbstentionViolation(
            f"deadlock at safety floor {tracker.safety_floor}; "
            f"epoch {epoch} must abort and re-elect"
        )
    return "PENDING"
