# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-task-commitment-has-crossed-from-byzantine-fault-tolerant-agreement-into-quorum-liveness-collapse-in-multi-agent-at.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-task-commitment-has-crossed-from-byzantine-fault-tolerant-agreement-into-quorum-liveness-collapse-in-multi-agent-at.warrant.json
# Markdown SHA-256:   6db992f61222414d906e4962e717ccfb79a367e9ab66a2f6471fe698b9e44414
# Code AST SHA-256:   1458cc970a7d141640473051297cf5e589320198e7a542dc6960c8b37a45ce15
# Verified Classes:   QuorumLivenessCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class QuorumLivenessCollapseError(RuntimeError):
    """Raised when BFT safety holds but effective quorum is unreachable."""
    pass


def check_commit_viability(
    n: int,
    quorum_threshold: int,
    reachable_attesters: int,
    conflicting_attestations: int,
    consecutive_stalled_rounds: int,
    rotation_period_rounds: int = 3,
) -> str:
    # Safety must be intact for this diagnosis to apply.
    if conflicting_attestations > 0:
        # A real Byzantine safety event; different runbook entirely.
        return "SAFETY_VIOLATION"

    deficit = quorum_threshold - reachable_attesters

    if deficit <= 0:
        return "HEALTHY"

    if deficit == 1 and consecutive_stalled_rounds > 2 * rotation_period_rounds:
        raise QuorumLivenessCollapseError(
            f"Liveness collapse: quorum={quorum_threshold} but only "
            f"{reachable_attesters}/{n} attesters reachable; "
            f"{consecutive_stalled_rounds} stalled rounds with zero "
            f"conflicting attestations. Safety-green, liveness-red. "
            f"Re-weight quorum to reachable set; do not extend deadline."
        )

    if deficit >= 2:
        raise QuorumLivenessCollapseError(
            f"Availability incident: deficit={deficit}, cohort cannot "
            f"finalize under any leader."
        )

    return "TRANSIENT_STALL"
