# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-org-settlement-quorum-as-unattainable-rather-than-slow-the-quorum-floor-ambiguity-in-partial-sync.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-org-settlement-quorum-as-unattainable-rather-than-slow-the-quorum-floor-ambiguity-in-partial-sync.warrant.json
# Markdown SHA-256:   090aca08384f91d6f38af5fd55964218097e6ff56a6834236d311548fffd79c8
# Code AST SHA-256:   1e56108a906c5897107874302013607ba6da09f80663edf438595c8f225926f4
# Verified Classes:   QuorumUnattainable, SettlementRound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import FrozenSet


class QuorumUnattainable(RuntimeError):
    """Raised when the responsive signer set has rotated below the quorum
    floor, meaning no amount of waiting will assemble a stable quorum."""


@dataclass
class SettlementRound:
    epoch: int
    quorum_floor: int
    responsive: FrozenSet[str]
    deadline_s: float
    opened_at: float = field(default_factory=time.monotonic)


def evaluate_round(
    previous: SettlementRound | None,
    current: SettlementRound,
) -> str:
    """Decide commit / retry / abort for a cross-org settlement round.

    Returns 'commit', 'retry', or raises QuorumUnattainable.
    The decisive check is set rotation, NOT elapsed time.
    """
    n = len(current.responsive)
    if n >= current.quorum_floor:
        return "commit"

    # Below floor. Retry is sound only if the responsive set is stable/growing
    # relative to the prior round within the same membership epoch.
    if previous is not None and previous.epoch == current.epoch:
        rotated_out = previous.responsive - current.responsive
        if rotated_out:
            raise QuorumUnattainable(
                f"epoch {current.epoch}: responsive set lost {sorted(rotated_out)} "
                f"while below floor ({n}/{current.quorum_floor}); "
                f"quorum is unattainable, not slow — abort retries, "
                f"reconfigure membership or fork settlement."
            )

    if time.monotonic() - current.opened_at > current.deadline_s:
        # Timeout alone is NOT proof of unattainability; it only bounds waiting.
        return "retry"  # caller must still re-check rotation next round

    return "retry"


def settle(rounds: list[SettlementRound]) -> str:
    prev: SettlementRound | None = None
    for r in rounds:
        try:
            decision = evaluate_round(prev, r)
        except QuorumUnattainable:
            raise
        if decision == "commit":
            return f"committed at epoch {r.epoch}"
        prev = r
    raise QuorumUnattainable("round budget exhausted without stable quorum")
