# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-certify-a-byzantine-quorum-when-adversarial-agents-exploit-equivocation-across-phase-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-certify-a-byzantine-quorum-when-adversarial-agents-exploit-equivocation-across-phase-boundaries.warrant.json
# Markdown SHA-256:   c05f00368dba21703792ea43877968edb16b0bdc5c7ed42f8f9f708462e71340
# Code AST SHA-256:   741d2a92644edabcbae52a2918092933926da92310d94ac317545fb173458259
# Verified Classes:   EquivocationCertificationError, Certificate, QuorumCertifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationCertificationError(RuntimeError):
    """Raised when an agent attempts to certify a decision while holding
    mutually contradictory quorum certificates for the same view."""
    pass


@dataclass(frozen=True)
class Certificate:
    view: int
    phase: str          # "PREPARE" | "COMMIT"
    value: str
    signers: Tuple[str, ...]

    def quorum_size(self) -> int:
        return len(self.signers)


class QuorumCertifier:
    """Local certifier enforcing cross-phase value mutual-exclusion per view."""

    def __init__(self, n: int, f: int):
        if n < 3 * f + 1:
            raise ValueError("n must be >= 3f+1 for BFT quorum")
        self.n = n
        self.f = f
        self.threshold = 2 * f + 1
        # view -> phase -> value -> certificate
        self._certs: Dict[int, Dict[str, Dict[str, Certificate]]] = {}

    def ingest(self, cert: Certificate) -> None:
        if cert.quorum_size() < self.threshold:
            raise EquivocationCertificationError(
                f"certificate for view {cert.view} phase {cert.phase} "
                f"value {cert.value} has only {cert.quorum_size()} signers, "
                f"below threshold {self.threshold}"
            )
        by_phase = self._certs.setdefault(cert.view, {})
        by_value = by_phase.setdefault(cert.phase, {})
        by_value[cert.value] = cert

    def certify(self, view: int, value: str) -> Certificate:
        """Return the certificate authorizing `value` at `view`, or refuse."""
        by_phase = self._certs.get(view, {})
        observed_values = set()
        for phase, by_value in by_phase.items():
            observed_values.update(by_value.keys())

        if not observed_values:
            raise EquivocationCertificationError(
                f"no certificates observed for view {view}"
            )

        if len(observed_values) > 1:
            # Cross-phase equivocation detected: same view, multiple values.
            raise EquivocationCertificationError(
                f"equivocation across phases at view {view}: "
                f"observed values {sorted(observed_values)}; "
                f"refusing to certify {value}"
            )

        (only_value,) = observed_values
        if only_value != value:
            raise EquivocationCertificationError(
                f"requested certify({value}) but only quorum is for {only_value} "
                f"at view {view}"
            )

        # Pick the highest-phase certificate as the authorization.
        phase_order = {"PREPARE": 0, "COMMIT": 1}
        best_phase = max(by_phase.keys(), key=lambda p: phase_order.get(p, -1))
        return by_phase[best_phase][only_value]


def run_trace() -> None:
    cert = QuorumCertifier(n=5, f=1)
    # A2 observes COMMIT(X) from partition 1 and COMMIT(Y) from partition 2.
    cert.ingest(Certificate(view=7, phase="COMMIT", value="X",
                            signers=("A1", "A2", "A3")))
    cert.ingest(Certificate(view=7, phase="COMMIT", value="Y",
                            signers=("A3", "A4", "A5")))
    # Must refuse: two values at same view.
    cert.certify(view=7, value="X")


if __name__ == "__main__":
    run_trace()
