# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-plan-under-byzantine-quorum-the-equivocation-window-invariant-in-multi-agent-plan-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-plan-under-byzantine-quorum-the-equivocation-window-invariant-in-multi-agent-plan-commitment.warrant.json
# Markdown SHA-256:   6811b3c2a1c559e230bfc72971718cdb08df29a2632fb0f64152c5c3ba2543e5
# Code AST SHA-256:   bd3db18710514ba8f92f2d2fbad3bf35b4c40f73641ef8e051e862ec5f24f5d3
# Verified Classes:   ByzantineCommitViolation, Vote, AgentState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class ByzantineCommitViolation(RuntimeError):
    """Raised when a commit gate would accept a vote not bound to (view, hash, signer)."""
    pass


@dataclass(frozen=True)
class Vote:
    view: int
    plan_hash: str
    signer: str
    kind: str  # "PREPARE-ACK" | "COMMIT"
    sig: str


@dataclass
class AgentState:
    agent_id: str
    f: int
    lock: Tuple[int, str] | None = None  # (view, plan_hash)
    lock_set_at: float = 0.0
    seen_prepares: Dict[Tuple[int, str], Set[str]] = field(default_factory=dict)

    @property
    def quorum(self) -> int:
        return 2 * self.f + 1


def commit_gate(state: AgentState, votes: list[Vote], target_view: int,
                target_hash: str, delta_lock: float) -> bool:
    """
    Returns True iff the agent may finalize (target_view, target_hash).
    Raises ByzantineCommitViolation on structural conflict, not on mere divergence.
    """
    matching: Set[str] = set()
    for v in votes:
        if v.kind != "COMMIT":
            continue
        if v.view != target_view or v.plan_hash != target_hash:
            # A vote for a different (view, hash) is a null vote, never a commit vote.
            continue
        if not v.sig:
            raise ByzantineCommitViolation(
                f"unsigned commit vote from {v.signer} at view {v.view}"
            )
        matching.add(v.signer)

    # Detect equivocation evidence: f+1 prepares for a conflicting hash at >= target_view.
    conflicting = {
        (view, h): signers
        for (view, h), signers in state.seen_prepares.items()
        if view >= target_view and h != target_hash and len(signers) >= state.f + 1
    }
    if conflicting:
        raise ByzantineCommitViolation(
            f"conflicting prepares detected: {list(conflicting)}; must view-change"
        )

    # Lock monotonicity: if locked on a different hash, cannot commit without view-change cert.
    if state.lock is not None and state.lock[1] != target_hash:
        raise ByzantineCommitViolation(
            f"agent {state.agent_id} locked on {state.lock}, refusing commit of "
            f"({target_view}, {target_hash}) without VIEW-CHANGE certificate"
        )

    if len(matching) >= state.quorum:
        return True

    # Liveness boundary: bounded wait, then escalate to view-change — never silent drop.
    if state.lock is not None and (time.monotonic() - state.lock_set_at) > delta_lock:
        raise ByzantineCommitViolation(
            f"commit timeout at view {target_view}; lock held on {state.lock}; "
            f"initiate VIEW-CHANGE rather than dropping lock"
        )
    return False
