# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-shared-plan-commitment-from-surviving-equivocating-peers-in-bft-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-shared-plan-commitment-from-surviving-equivocating-peers-in-bft-agent-swarms.warrant.json
# Markdown SHA-256:   4b081eec989c39a9742e1607a306bf1422b280c1f1d11d5bf3faffb7af91bf5f
# Code AST SHA-256:   c82990524e2ff65e1cb66ea2cfa992e783058016baa910593b792a006d42b1b2
# Verified Classes:   EquivocationDetected, Commitment, VoteGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when an honest agent receives two distinct plan commitments
    for the same (sequence, epoch) key. This is the load-bearing guard:
    overwriting instead of raising silently breaks BFT agreement."""
    pass


@dataclass
class Commitment:
    plan_id: str
    signed_by: str
    nonce: str


@dataclass
class VoteGuard:
    # Key is (sequence_number, epoch) -- NOT sequence alone, or legitimate
    # re-proposals after view change will be misread as equivocation.
    committed: Dict[Tuple[int, int], Commitment] = field(default_factory=dict)

    def cast_vote(self, seq: int, epoch: int, plan: Commitment) -> None:
        key = (seq, epoch)
        existing = self.committed.get(key)

        if existing is None:
            self.committed[key] = plan
            return

        if existing.plan_id != plan.plan_id:
            # Two distinct plans for the same (seq, epoch): equivocation.
            # MUST raise. Overwriting here is the safety violation.
            raise EquivocationDetected(
                f"agent {plan.signed_by} equivocated at seq={seq} epoch={epoch}: "
                f"already committed {existing.plan_id!r}, now offered {plan.plan_id!r}"
            )
        # Same plan re-delivered (retry/replay): idempotent, no-op.
        return

    def retry_vote(self, seq: int, epoch: int, plan: Commitment) -> None:
        # Retry path MUST route through cast_vote, never write directly.
        # A direct `self.committed[key] = plan` here is the observed bug.
        self.cast_vote(seq, epoch, plan)


def commit_plan(guard: VoteGuard, seq: int, epoch: int, plan: Commitment) -> str:
    try:
        guard.cast_vote(seq, epoch, plan)
    except EquivocationDetected as e:
        # Broadcast equivocation proof and halt this agent's participation.
        raise EquivocationDetected(f"halting: {e}") from e
    return f"committed {plan.plan_id} at seq={seq} epoch={epoch}"
