# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-multi-agent-decision-quorums-before-the-quorum-threshold-is-crossed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-multi-agent-decision-quorums-before-the-quorum-threshold-is-crossed.warrant.json
# Markdown SHA-256:   198ecb7bb5379ee155c775e2abd4438aec4cdb8cf0809b85ca282f5adf927178
# Code AST SHA-256:   9a5d01d15b379fccc5a0b6137a22a68ed06084fc2f182bd1d3eae7c99cb94b91
# Verified Classes:   Vote, EquivocationWitnessError, FallbackQuorumError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

@dataclass(frozen=True)
class Vote:
    agent_id: str
    proposal: str
    round_nonce: int
    value: str  # "approve" | "reject"
    signature: str

class EquivocationWitnessError(RuntimeError):
    """Raised when a received-vote log contains a functional inconsistency."""
    pass

class FallbackQuorumError(RuntimeError):
    """Raised when a coordinator attempts to escalate to a fallback that includes a witnessed equivocator."""
    pass

def detect_equivocation(
    received_logs: Dict[str, List[Vote]]
) -> List[Tuple[str, str, int]]:
    """
    received_logs: agent_id -> list of Votes that agent received this round.
    Returns list of (equivocator_id, proposal, round_nonce) witnesses.
    A witness exists iff some agent_id maps to >1 distinct value for the same (proposal, round_nonce).
    """
    seen: Dict[Tuple[str, str, int], str] = {}
    witnesses: List[Tuple[str, str, int]] = []
    for _reporter, votes in received_logs.items():
        for v in votes:
            key = (v.agent_id, v.proposal, v.round_nonce)
            if key in seen and seen[key] != v.value:
                witnesses.append(key)
            else:
                seen[key] = v.value
    return witnesses

def escalate_to_fallback(
    received_logs: Dict[str, List[Vote]],
    fallback_members: List[str],
    timeout_count: int,
) -> List[str]:
    """
    Decide whether escalation is permitted and return the validated fallback set.
    Raises EquivocationWitnessError if witnesses exist but are not excluded.
    Raises FallbackQuorumError if timeout_count < 2 (insufficient evidence of stall).
    """
    if timeout_count < 2:
        raise FallbackQuorumError(
            f"Escalation refused: timeout_count={timeout_count} < 2; "
            "a single timeout is indistinguishable from latency."
        )

    witnesses = detect_equivocation(received_logs)
    if not witnesses:
        return fallback_members  # no equivocation; fallback as proposed

    equivocators = {w[0] for w in witnesses}
    contaminated = equivocators.intersection(fallback_members)
    if contaminated:
        raise EquivocationWitnessError(
            f"Fallback quorum includes witnessed equivocator(s): {sorted(contaminated)}. "
            f"Witnesses: {witnesses}. Exclude and re-derive threshold."
        )
    return fallback_members
