# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-byzantine-fault-tolerant-attestation-quorum-when-equivocation-is-detected-below-the-f-1-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-byzantine-fault-tolerant-attestation-quorum-when-equivocation-is-detected-below-the-f-1-threshold.warrant.json
# Markdown SHA-256:   44a9fec65aa5abe8ece8b5322291ac39bef725d7d2c83e69de220136614c2cbd
# Code AST SHA-256:   f213d7a12761fde1151543752f87d3e7bd7300ad28f28c2411268d3659979a03
# Verified Classes:   SubThresholdEquivocationError, AttestationRound
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SubThresholdEquivocationError(RuntimeError):
    """Raised when equivocation is detected below the f+1 escalation threshold
    while the equivocator's signature is still in the candidate quorum set."""
    pass


class AttestationRound:
    def __init__(self, task_id: str, round_no: int, n: int):
        self.task_id = task_id
        self.round_no = round_no
        self.f = (n - 1) // 3
        self.quorum = 2 * self.f + 1
        self.seen: dict[tuple, str] = {}
        self.equivocation_keys: set[tuple] = set()
        self.quarantined = False

    def receive(self, agent_id: str, verdict: str) -> str:
        key = (self.task_id, self.round_no, agent_id)
        if key in self.seen and self.seen[key] != verdict:
            self.equivocation_keys.add(key)
            observers = len({k[2] for k in self.equivocation_keys})
            if observers < self.f + 1 and agent_id in self._candidate_agents():
                self.quarantined = True
                raise SubThresholdEquivocationError(
                    f"agent {agent_id} equivocated on {key} with only "
                    f"{observers} observer(s) < f+1={self.f + 1}; "
                    f"round {self.round_no} quarantined"
                )
        self.seen[key] = verdict
        return self._maybe_finalize()

    def _candidate_agents(self) -> set[str]:
        return {k[2] for k in self.seen}

    def _maybe_finalize(self) -> str:
        if self.quarantined:
            return "QUARANTINED"
        distinct = {k[2] for k in self.seen}
        if len(distinct) >= self.quorum:
            return "FINALIZED"
        return "PENDING"
