# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-result-it-did-not-compute-equivocation-tolerant-commitment-under-partial-byzantine-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-result-it-did-not-compute-equivocation-tolerant-commitment-under-partial-byzantine-quorum.warrant.json
# Markdown SHA-256:   2ec419e4bc1bd3ae6959053e302bc47b27fb16e58ae38ac6b08d3404e89eb064
# Code AST SHA-256:   2b079d8aeffd5f565cc8e79d1f72baceba7f521d86b9058218bc9028bd39fe07
# Verified Classes:   QuorumIntersectionViolation, ThresholdMisconfiguration, Certificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Set


class QuorumIntersectionViolation(RuntimeError):
    """Raised when two certificates on the same task certify divergent results."""
    pass


class ThresholdMisconfiguration(RuntimeError):
    """Raised when the attestation threshold cannot guarantee quorum intersection."""
    pass


@dataclass
class Certificate:
    task_id: str
    result_hash: str
    attestors: Set[str]
    broadcast_dedup: bool


def required_threshold(n: int, f: int) -> int:
    if n < 3 * f + 1:
        raise ThresholdMisconfiguration(
            f"N={n} cannot tolerate f={f}; need N >= 3f+1 = {3*f+1}"
        )
    return (n + f + 1 + 1) // 2  # ceil((N+f+1)/2)


def validate_certificate(cert: Certificate, n: int, f: int) -> None:
    q = required_threshold(n, f)
    if len(cert.attestors) < q:
        raise ThresholdMisconfiguration(
            f"cert for {cert.task_id} has {len(cert.attestors)} attestors, need {q}"
        )
    if not cert.broadcast_dedup:
        raise ThresholdMisconfiguration(
            f"cert for {cert.task_id} assembled from routed channels; "
            f"requires {f+1} independent replay confirmations"
        )


def detect_conflict(certs: List[Certificate], n: int, f: int) -> None:
    by_task: Dict[str, List[Certificate]] = {}
    for c in certs:
        validate_certificate(c, n, f)
        by_task.setdefault(c.task_id, []).append(c)
    for task_id, group in by_task.items():
        hashes = {c.result_hash for c in group}
        if len(hashes) > 1:
            # Under correct q, any two quorums share >= f+1 honest members,
            # so divergent certificates are structurally impossible.
            raise QuorumIntersectionViolation(
                f"task {task_id} has {len(hashes)} divergent certified results: "
                f"{sorted(hashes)}; memory integrity compromised, quarantine episode"
            )


# Reproduction of the observed failure: N=7, f=2, q configured as simple majority (4).
n, f = 7, 2
c1 = Certificate("T-4421", hashlib.sha256(b"R1").hexdigest(),
                 {"A1", "A2", "A3", "A6"}, broadcast_dedup=True)
c2 = Certificate("T-4421", hashlib.sha256(b"R2").hexdigest(),
                 {"A4", "A5", "A6", "A7"}, broadcast_dedup=True)

try:
    detect_conflict([c1, c2], n, f)
except QuorumIntersectionViolation as e:
    print(f"HALT: {e}")
    # Correct q for N=7, f=2 is 5; at q=5 these 4-member certs would be rejected
    # before conflict detection even runs.
