# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-fault-tolerant-quorum-of-agent-commitments-as-invalid-when-the-fault-bound-is-satisfied-but-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-fault-tolerant-quorum-of-agent-commitments-as-invalid-when-the-fault-bound-is-satisfied-but-t.warrant.json
# Markdown SHA-256:   7043655a21c1a97c7b0ceeb4ba9db7237b43ec0096cee20b2a0a7535ace53bdb
# Code AST SHA-256:   b8eb7ec50d6c4671bf04a2798345ce1957c8098113fbaf7860a3e40e8ee489d5
# Verified Classes:   QuorumSafetyViolation, Commitment, QuorumCollector
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class QuorumSafetyViolation(RuntimeError):
    """Raised when a cardinality-valid quorum fails intersection-safety."""


@dataclass(frozen=True)
class Commitment:
    replica_id: str
    epoch_id: str
    manifest_hash: str
    result_digest: str
    nonce: int
    signature: bytes


@dataclass
class QuorumCollector:
    local_epoch_id: str
    local_manifest_hash: str
    fault_bound_f: int
    commitments: list[Commitment] = field(default_factory=list)

    def _manifest_matches(self, c: Commitment) -> bool:
        return c.epoch_id == self.local_epoch_id and c.manifest_hash == self.local_manifest_hash

    def add(self, c: Commitment) -> None:
        if not self._manifest_matches(c):
            # Mixed-universe quorum is the failure we are guarding against.
            raise QuorumSafetyViolation(
                f"commitment from {c.replica_id} references epoch {c.epoch_id}/"
                f"{c.manifest_hash[:8]}, local epoch {self.local_epoch_id}/"
                f"{self.local_manifest_hash[:8]}; abort and restart collection"
            )
        self.commitments.append(c)

    def _equivocators(self, against: Iterable[Commitment]) -> set[str]:
        seen: dict[str, set[int]] = {}
        for c in against:
            seen.setdefault(c.replica_id, set()).add(c.nonce)
        return {rid for rid, nonces in seen.items() if len(nonces) > 1}

    def finalize(self, result_digest: str, threshold: int,
                 concurrent: Iterable[Commitment] = ()) -> str:
        supporting = [c for c in self.commitments if c.result_digest == result_digest]
        if len(supporting) < threshold:
            raise QuorumSafetyViolation(
                f"only {len(supporting)} commitments, need {threshold}"
            )

        equiv = self._equivocators(list(supporting) + list(concurrent))
        if equiv:
            raise QuorumSafetyViolation(
                f"equivocation detected from replicas {sorted(equiv)}; "
                f"cardinality satisfied but vote-uniqueness is not provable"
            )

        # Identity-verified intersection: the intersecting replicas must be
        # provably single-vote. Cardinality alone is never sufficient.
        supporting_ids = {c.replica_id for c in supporting}
        concurrent_ids = {c.replica_id for c in concurrent}
        if concurrent_ids:
            honest_intersection = supporting_ids & concurrent_ids
            if len(honest_intersection) < self.fault_bound_f + 1:
                raise QuorumSafetyViolation(
                    f"intersection {sorted(honest_intersection)} has size "
                    f"{len(honest_intersection)} < f+1={self.fault_bound_f + 1}; "
                    f"two quorums may have finalized conflicting results"
                )

        digest = hashlib.sha256(
            "|".join(sorted(f"{c.replica_id}:{c.nonce}" for c in supporting)).encode()
        ).hexdigest()
        return digest
