# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-tolerant-quorum-loss-in-multi-agent-auditor-swarms-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-tolerant-quorum-loss-in-multi-agent-auditor-swarms-under-partial-synchrony.warrant.json
# Markdown SHA-256:   8c1a424b740482dcee1a51399fb1ed9990de5239b910f767cb25e1dafa29f49c
# Code AST SHA-256:   a9e2b910172e0aa65a70820e8396668c534bcc093539d39ffe716940bd4f1c22
# Verified Classes:   ForkedIdentityError, QuorumBudgetExhausted, VoteRecord, CollectorLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class ForkedIdentityError(RuntimeError):
    """Raised when a vote record's epoch counter regresses, indicating a forked instance."""
    pass

class QuorumBudgetExhausted(RuntimeError):
    """Raised when eviction of a forked identity would push the swarm below 2f+1."""
    pass

@dataclass
class VoteRecord:
    agent_id: str
    epoch: int
    payload: str
    signature: str

@dataclass
class CollectorLedger:
    high_water: dict = field(default_factory=dict)   # agent_id -> max epoch observed
    evicted: set = field(default_factory=set)
    n: int = 5
    f: int = 1

    def _sig(self, rec: VoteRecord) -> str:
        return hashlib.sha256(f"{rec.agent_id}:{rec.epoch}:{rec.payload}".encode()).hexdigest()

    def admit(self, rec: VoteRecord) -> str:
        if rec.agent_id in self.evicted:
            raise ForkedIdentityError(f"agent {rec.agent_id} already evicted")
        if self._sig(rec) != rec.signature:
            raise ForkedIdentityError(f"bad signature for {rec.agent_id}@{rec.epoch}")

        prior = self.high_water.get(rec.agent_id)
        if prior is not None and rec.epoch <= prior:
            # Epoch regression => forked honest instance, NOT byzantine equivocation.
            # Quarantine + re-vote; do NOT evict (eviction would spend fault budget).
            raise ForkedIdentityError(
                f"epoch regression for {rec.agent_id}: got {rec.epoch}, high-water {prior}"
            )

        self.high_water[rec.agent_id] = rec.epoch
        return "accepted"

    def evict_on_genuine_equivocation(self, agent_id: str) -> None:
        # Only call when two records share (agent_id, epoch) with DIFFERENT signatures
        # (true byzantine equivocation), never on epoch regression.
        remaining = self.n - len(self.evicted) - 1
        if remaining < 2 * self.f + 1:
            raise QuorumBudgetExhausted(
                f"evicting {agent_id} leaves {remaining} voters, below 2f+1={2*self.f+1}"
            )
        self.evicted.add(agent_id)
