# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-llm-proposed-consensus-fail-only-when-the-proposal-space-is-adversarially-dense.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-llm-proposed-consensus-fail-only-when-the-proposal-space-is-adversarially-dense.warrant.json
# Markdown SHA-256:   fdb5f291526bdc5d1fa6e5c66aad8685979516e5f329c0d8c92ad55805683ed8
# Code AST SHA-256:   128e80307c6540dae0203973de0868b3ac0e0cc357c7ab0183037e5ece7b38ae
# Verified Classes:   ProposalDensitySafetyError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProposalDensitySafetyError(RuntimeError):
    """Raised when proposal-space density has collapsed the BFT safety invariant."""
    pass


CANONICAL_OPERATIONS = frozenset({"restart", "scale", "drain", "rollback"})
FALLBACK_RATE_THRESHOLD = 0.05
MIN_QUORUM_FRACTION = 2 / 3  # 2f+1 over 3f+1


def admit_proposal(proposal: dict) -> str:
    """Return a canonical hash key, or raise if the proposal cannot be canonicalized."""
    op = proposal.get("op")
    target = proposal.get("target")
    if op not in CANONICAL_OPERATIONS:
        raise ProposalDensitySafetyError(
            f"non-canonical operation {op!r}; refusing to admit to consensus round"
        )
    if not isinstance(target, str) or not target.strip():
        raise ProposalDensitySafetyError("missing canonical target")
    return f"{op}:{target.strip().lower()}"


def check_round_safety(round_stats: dict) -> None:
    """Refuse to continue if the fallback path has been entered too often."""
    fallback_rate = round_stats["fallback_rounds"] / max(round_stats["total_rounds"], 1)
    if fallback_rate > FALLBACK_RATE_THRESHOLD:
        raise ProposalDensitySafetyError(
            f"fallback rate {fallback_rate:.2%} exceeds {FALLBACK_RATE_THRESHOLD:.0%}; "
            "effective fault tolerance is zero, halt and canonicalize"
        )
    if round_stats.get("quorum_fraction", 1.0) < MIN_QUORUM_FRACTION:
        raise ProposalDensitySafetyError(
            "commit path used sub-quorum majority; intersection property violated"
        )
