# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-equivocation-window-before-committing-a-plan-under-byzantine-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-equivocation-window-before-committing-a-plan-under-byzantine-peers.warrant.json
# Markdown SHA-256:   1ff2be10588e87acc8c729f5889af87bb7337f0f0926cef3503fabe2426a9c04
# Code AST SHA-256:   80af6f362ab570aa07fa21339ffce716ee7595049acdfdf953d1380c64a6b71c
# Verified Classes:   EquivocationWindowError, Certificate, Agent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class EquivocationWindowError(RuntimeError):
    """Raised when an agent attempts to dispatch an irreversible plan
    before its commit certificate is provably disjoint from any
    conflicting certificate within the T_cert gossip horizon."""
    pass

@dataclass
class Certificate:
    plan_id: str
    prepare_set: Set[str]           # signed voter IDs
    timestamp: float

@dataclass
class Agent:
    node_id: str
    f: int
    n: int
    t_cert: float = 1.5
    seen_certs: Dict[str, Certificate] = field(default_factory=dict)

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

    def _overlaps_conflict(self, cert: Certificate) -> bool:
        for other in self.seen_certs.values():
            if other.plan_id != cert.plan_id and (other.prepare_set & cert.prepare_set):
                return True
        return False

    def dispatch_irreversible(self, cert: Certificate, tool_call) -> None:
        if len(cert.prepare_set) < self.quorum():
            raise EquivocationWindowError(
                f"insufficient quorum: {len(cert.prepare_set)} < {self.quorum()}"
            )
        self.seen_certs[cert.plan_id] = cert

        # Enforce the equivocation window: wait T_cert for competing certs.
        deadline = time.monotonic() + self.t_cert
        while time.monotonic() < deadline:
            if self._overlaps_conflict(cert):
                raise EquivocationWindowError(
                    f"overlapping prepare-set detected for plan {cert.plan_id}; "
                    f"equivocators present, aborting dispatch"
                )
            time.sleep(0.05)

        # Post-horizon re-check: a conflicting cert may have arrived late.
        if self._overlaps_conflict(cert):
            raise EquivocationWindowError(
                f"late conflicting certificate surfaced after T_cert for {cert.plan_id}"
            )

        tool_call()
