# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-i-have-not-heard-dissent-and-consensus-exists-in-a-byzantine-tolerant-plan-commitment-protocol.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-i-have-not-heard-dissent-and-consensus-exists-in-a-byzantine-tolerant-plan-commitment-protocol.warrant.json
# Markdown SHA-256:   e2238d842909f7924bf8581df63743893e57cc779941230534c815c412616042
# Code AST SHA-256:   d26d9cc29590fb06bed926eed31268be30238b6a765358ae51924bfaee8b755c
# Verified Classes:   Prepare, ConsensusViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable
import hashlib

@dataclass(frozen=True)
class Prepare:
    signer: str
    plan_hash: str
    view: int
    seq: int
    signature_valid: bool

class ConsensusViolation(RuntimeError):
    """Raised when an instance attempts to commit without a positive quorum certificate."""
    pass

def certify_commit(
    prepares: Iterable[Prepare],
    f: int,
    current_view: int,
    current_seq: int,
) -> str:
    """
    Deterministic certifier. Returns the plan_hash iff a positive 2f+1 certificate
    exists for the current view/seq. Never consults model judgment or 'absence of dissent'.
    """
    threshold = 2 * f + 1
    # Count DISTINCT valid signers per (plan_hash, view, seq). Dedupe by signer to
    # defeat equivocation inflation and duplicate-message replay.
    signers_by_hash: dict[str, set[str]] = {}
    for p in prepares:
        if not p.signature_valid:
            continue
        if p.view != current_view or p.seq != current_seq:
            continue  # stale-view certificate is not valid here
        signers_by_hash.setdefault(p.plan_hash, set()).add(p.signer)

    certified = [h for h, signers in signers_by_hash.items() if len(signers) >= threshold]

    if len(certified) > 1:
        # Two 2f+1 quorums intersect in >= f+1 honest signers -> provable Byzantine equivocation.
        raise ConsensusViolation(
            f"Two conflicting certificates in view {current_view} seq {current_seq}: "
            f"{certified}. Quorum intersection violated; halt and slash."
        )
    if not certified:
        # This is the boundary: absence of a certificate is NOT permission to commit.
        best = max((len(s) for s in signers_by_hash.values()), default=0)
        raise ConsensusViolation(
            f"No positive certificate: best observed {best}/{threshold} distinct signers "
            f"in view {current_view} seq {current_seq}. Instance may be partitioned or "
            f"context-truncated; must NOT commit on 'no dissent observed'."
        )
    return certified[0]

def commit_plan(plan_hash: str, prepares: Iterable[Prepare], f: int,
                current_view: int, current_seq: int) -> str:
    certified_hash = certify_commit(prepares, f, current_view, current_seq)
    if certified_hash != plan_hash:
        raise ConsensusViolation(
            f"Refusing to commit {plan_hash}: certificate is for {certified_hash}."
        )
    return f"COMMITTED {plan_hash} view={current_view} seq={current_seq}"
