# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-quorum-certificate-timeout-as-equivocation-evidence-in-latency-tuned-federated-byzantine-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-quorum-certificate-timeout-as-equivocation-evidence-in-latency-tuned-federated-byzantine-agent-swarms.warrant.json
# Markdown SHA-256:   41f4e22e7456eba7f88b3ecd211ddcfc3a1c523b5967be04ed50078d36b2c867
# Code AST SHA-256:   9f32a18e532abe77fc070b03331bac5393cc59bb41c6f041f3a17cb2c824b00b
# Verified Classes:   EquivocationBoundaryError, SignedDigest, QcObservation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EquivocationBoundaryError(RuntimeError):
    """Raised when a QC timeout is misclassified relative to the overlap-before-accusation invariant."""


@dataclass(frozen=True)
class SignedDigest:
    round: int
    view: int
    digest: str
    signer_slice: frozenset[str]


@dataclass(frozen=True)
class QcObservation:
    round: int
    view: int
    digest: str
    qc_received: bool
    elapsed_ms: int
    round_timer_ms: int


def classify_leader_event(
    obs: QcObservation,
    witnessed: list[SignedDigest],
    slice_intersection_known: bool,
) -> str:
    """
    Returns one of: 'commit', 'rotate', 'halt_and_prove', 'widen_witness'.

    Invariant: a timeout escalates to equivocation evidence ONLY when two
    distinct signed digests for the same (round, view) are witnessed with
    slice overlap. Timeout alone is liveness-only.
    """
    if not slice_intersection_known:
        # Permissionless / disjoint slices: no local witness can prove overlap.
        raise EquivocationBoundaryError(
            "cannot classify equivocation without known slice intersection; "
            "fall back to gossip-based proof"
        )

    relevant = [w for w in witnessed if w.round == obs.round and w.view == obs.view]
    distinct_digests = {w.digest for w in relevant}

    if len(distinct_digests) >= 2:
        # Safety signal: two signed digests, same (round, view).
        # Verify at least one overlapping slice member attests each side.
        signers = [w.signer_slice for w in relevant]
        if not any(a & b for i, a in enumerate(signers) for b in signers[i + 1:]):
            return "widen_witness"
        return "halt_and_prove"

    if obs.qc_received and obs.elapsed_ms <= obs.round_timer_ms:
        return "commit"

    if obs.elapsed_ms > obs.round_timer_ms and len(distinct_digests) <= 1:
        # Timeout with no overlap witness: liveness only.
        return "rotate"

    return "widen_witness"


def guarded_commit(obs: QcObservation, witnessed: list[SignedDigest], slice_intersection_known: bool) -> str:
    decision = classify_leader_event(obs, witnessed, slice_intersection_known)
    if decision == "halt_and_prove":
        raise EquivocationBoundaryError(
            f"equivocation at round={obs.round} view={obs.view}: "
            f"distinct digests witnessed with slice overlap; commits halted on both branches"
        )
    if decision == "commit" and not slice_intersection_known:
        raise EquivocationBoundaryError(
            "refusing commit: QC present but slice intersection unknown, "
            "cannot rule out masked equivocation"
        )
    return decision
