# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-equivocation-induced-commit-divergence-in-heterogeneous-llm-byzantine-consensus-over-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-equivocation-induced-commit-divergence-in-heterogeneous-llm-byzantine-consensus-over-shared-state.warrant.json
# Markdown SHA-256:   57c4dc244337e44149a4ef2ebc0b4e5c55a59e3f802f444ed7eed49f9a6dbce3
# Code AST SHA-256:   2c7a1fde1a2904c1ea7f755f1fbb49681040922bf23f9d38c75e2124ae7908ae
# Verified Classes:   EquivocationDetected, Commitment, Vote, QuorumVoteLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a validator's vote diverges across recipients or is non-canonical."""
    pass


@dataclass(frozen=True)
class Commitment:
    ledger_hash: str
    seq: int

    def canonical_hash(self) -> str:
        # Canonical serialization: sorted keys, no whitespace, UTF-8.
        blob = json.dumps(
            {"ledger_hash": self.ledger_hash, "seq": self.seq},
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(blob).hexdigest()


@dataclass(frozen=True)
class Vote:
    validator_id: str
    view: int
    commitment_hash: str
    recipient: str


class QuorumVoteLedger:
    """Tracks votes per (validator, view) and enforces recipient-independence."""

    def __init__(self, f: int):
        self.f = f
        self.threshold = 2 * f + 1
        # (validator_id, view) -> {commitment_hash: set(recipients)}
        self._votes: Dict[Tuple[str, int], Dict[str, set]] = {}

    def record(self, vote: Vote) -> None:
        key = (vote.validator_id, vote.view)
        slot = self._votes.setdefault(key, {})
        slot.setdefault(vote.commitment_hash, set()).add(vote.recipient)

        # Invariant: a validator may vote for exactly one commitment hash per view,
        # regardless of recipient. Any second hash is equivocation.
        if len(slot) > 1:
            raise EquivocationDetected(
                f"validator {vote.validator_id} equivocated in view {vote.view}: "
                f"hashes={sorted(slot)} recipients="
                f"{ {h: sorted(r) for h, r in slot.items()} }"
            )

    def quorum_hash(self, view: int) -> str:
        """Return the single commitment hash with >= 2f+1 distinct validators,
        refusing to commit if any validator equivocated in this view."""
        tally: Dict[str, set] = {}
        for (vid, v), slot in self._votes.items():
            if v != view:
                continue
            if len(slot) > 1:
                raise EquivocationDetected(
                    f"view {view} tainted: validator {vid} has multiple hashes"
                )
            (h,) = slot.keys()
            tally.setdefault(h, set()).add(vid)

        committed = [h for h, vids in tally.items() if len(vids) >= self.threshold]
        if len(committed) != 1:
            raise EquivocationDetected(
                f"view {view} has {len(committed)} quorum-certified commitments "
                f"(expected exactly 1); refusing to commit"
            )
        return committed[0]


def emit_vote(validator_id: str, view: int, commitment: Commitment,
              recipient: str, recipient_conditioned_prompt: bool) -> Vote:
    """Emit a vote. Rejects recipient-conditioned scaffolds outright: they are
    structurally capable of producing divergent commitments per peer."""
    if recipient_conditioned_prompt:
        raise EquivocationDetected(
            f"validator {validator_id} vote path is recipient-conditioned "
            f"(peer={recipient}); quarantining to deterministic relay"
        )
    return Vote(
        validator_id=validator_id,
        view=view,
        commitment_hash=commitment.canonical_hash(),
        recipient=recipient,
    )


def demo_divergence() -> None:
    ledger = QuorumVoteLedger(f=2)
    c = Commitment(ledger_hash="H1", seq=412)
    c_prime = Commitment(ledger_hash="H1_normalized", seq=412)

    # V3 emits C to V5 and C' to V1 — the observed equivocation.
    ledger.record(emit_vote("V3", 7, c, "V5", recipient_conditioned_prompt=False))
    ledger.record(emit_vote("V3", 7, c_prime, "V1", recipient_conditioned_prompt=False))
    # -> raises EquivocationDetected before any quorum can form.
    ledger.quorum_hash(view=7)


if __name__ == "__main__":
    demo_divergence()
