# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-stable-multi-agent-negotiation-as-a-livelock-rather-than-a-resolved-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-stable-multi-agent-negotiation-as-a-livelock-rather-than-a-resolved-consensus.warrant.json
# Markdown SHA-256:   90482903d869b149fbddc4e6f9ed2fa1313ab275fcd04d49a34ac505152cca19
# Code AST SHA-256:   61fc1c37f4181ea5d963f3c611932f6dc935478b2fba31e91748a96e5be1a63f
# Verified Classes:   NegotiationLivelockError, Pathology, CycleObservation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Sequence


class NegotiationLivelockError(RuntimeError):
    """Raised when a negotiation is provably cycling rather than converging."""


class Pathology(Enum):
    LIVELOCK = "livelock"
    DEADLOCK = "deadlock"
    PARTITION = "partition"
    STORM = "storm"
    BYZANTINE = "byzantine"


@dataclass(frozen=True)
class CycleObservation:
    candidate_ids: frozenset[str]
    vote_counts: dict[str, int]
    message_rate: float
    max_message_rate: float
    local_rationality_holds: bool


def classify(obs: CycleObservation, quorum: int) -> Pathology | None:
    if not obs.local_rationality_holds:
        return Pathology.BYZANTINE
    if len(obs.candidate_ids) > 2:
        return Pathology.STORM
    if any(c >= quorum for c in obs.vote_counts.values()):
        return None  # absorbing state reached; not a pathology
    if len(obs.vote_counts) == 1 and next(iter(obs.vote_counts.values())) >= 1:
        # one candidate holds all votes but below quorum -> partition
        return Pathology.PARTITION
    if obs.message_rate < 0.5 * obs.max_message_rate:
        return Pathology.DEADLOCK
    # stable small candidate set, non-degenerate votes, high activity, rational
    return Pathology.LIVELOCK


def enforce_convergence(
    history: Sequence[CycleObservation],
    quorum: int,
    k_cycles: int = 3,
    max_break_attempts: int = 2,
) -> None:
    if len(history) < k_cycles:
        return
    window = history[-k_cycles:]
    verdicts = [classify(o, quorum) for o in window]
    if all(v is Pathology.LIVELOCK for v in verdicts):
        # symmetry-break: content-addressed tie-break + causal freshness
        # (implemented by the caller); if already attempted M times, escalate
        attempts = sum(1 for o in window if o.message_rate >= o.max_message_rate)
        if attempts >= max_break_attempts * k_cycles:
            raise NegotiationLivelockError(
                f"negotiation livelocked across {k_cycles} cycles with stable "
                f"candidate set {window[-1].candidate_ids!r}; symmetry-break "
                f"exhausted, escalate to VRF-elected resolver for this epoch"
            )
