# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocating-commitment-as-a-liveness-hazard-rather-than-a-safety-hazard-in-bft-task.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocating-commitment-as-a-liveness-hazard-rather-than-a-safety-hazard-in-bft-task.warrant.json
# Markdown SHA-256:   bd338259ef13ee95489d8e6596444dc051072d08d2bb43b939c54c8ddf24b523
# Code AST SHA-256:   30ddd74a8e47394add44653416512ae11c4f7ab9b6f643c23831c74346b12a02
# Verified Classes:   EquivocationLivenessHazard, Certificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

SUPERQUORUM = 5  # S > 2f+1 for N=7, f=2; must be > 2f+1 and <= N-f


class EquivocationLivenessHazard(RuntimeError):
    """Raised when a verified certificate conflict plus a stalled epoch advance
    indicates a Byzantine equivocation liveness hazard requiring reconciliation."""


@dataclass(frozen=True)
class Certificate:
    task_id: str
    epoch: int
    payload_hash: str
    signers: frozenset[str]


def detect_equivocation(certs: Iterable[Certificate]) -> list[tuple[str, int]]:
    """Return (task_id, epoch) pairs with >1 distinct payload_hash."""
    seen: dict[tuple[str, int], set[str]] = {}
    for c in certs:
        seen.setdefault((c.task_id, c.epoch), set()).add(c.payload_hash)
    return [k for k, hashes in seen.items() if len(hashes) > 1]


def reconcile(
    certs: list[Certificate],
    advance_proofs: dict[tuple[str, int], frozenset[str]],
) -> Certificate:
    """Deterministically resolve a certificate conflict, or abort.

    Selection rule: among conflicting certs for the same (task_id, epoch),
    pick the one whose payload_hash is lexicographically smallest AND which
    has a valid superquorum advance proof. If none has an advance proof,
    abort the task (raise) rather than resolve.
    """
    conflicts = detect_equivocation(certs)
    if not conflicts:
        return certs[0]

    task_id, epoch = conflicts[0]
    candidates = [c for c in certs if (c.task_id, c.epoch) == (task_id, epoch)]
    proven = [
        c for c in candidates
        if len(advance_proofs.get((task_id, epoch), frozenset())) >= SUPERQUORUM
    ]
    if not proven:
        raise EquivocationLivenessHazard(
            f"Certificate conflict on task={task_id} epoch={epoch} with no "
            f"superquorum advance proof; aborting task rather than resolving. "
            f"Divergent payloads: {sorted({c.payload_hash for c in candidates})}"
        )
    return min(proven, key=lambda c: c.payload_hash)


def commit_or_abort(
    certs: list[Certificate],
    advance_proofs: dict[tuple[str, int], frozenset[str]],
) -> Certificate:
    resolved = reconcile(certs, advance_proofs)
    # Guard: never act on a bare 2f+1 certificate without advance proof.
    if len(advance_proofs.get((resolved.task_id, resolved.epoch), frozenset())) < SUPERQUORUM:
        raise EquivocationLivenessHazard(
            f"Refusing to commit task={resolved.task_id}: certificate lacks "
            f"superquorum advance proof (safety invariant violated)."
        )
    return resolved
