# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-quorum-membership-in-a-byzantine-task-commitment-set-when-its-own-equivocation-history-is-unverifiable.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-quorum-membership-in-a-byzantine-task-commitment-set-when-its-own-equivocation-history-is-unverifiable.warrant.json
# Markdown SHA-256:   171d258b085e905951dde9128a5a59ddc749a4cf8bc337495a7edaac750ddd59
# Code AST SHA-256:   63c0fef71b9fc815394beb990a68abb1bc789198f9e23b851e3c0a4b436093bc
# Verified Classes:   UnverifiableHistoryError, QuorumRefusalError, LogEntry, Agent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class UnverifiableHistoryError(RuntimeError):
    """Raised when an agent cannot prove cross-observed consistency of its own log."""
    pass


class QuorumRefusalError(RuntimeError):
    """Raised when an agent must refuse JOIN_QUORUM due to suspect history."""
    pass


@dataclass
class LogEntry:
    epoch: int
    slot: str
    owner: str
    timestamp: float
    signature: str


@dataclass
class Agent:
    agent_id: str
    log: list = field(default_factory=list)
    f: int = 1
    delta_rejoin: float = 90.0
    attest_timeout: float = 5.0

    def _suspect_entries(self, now: Optional[float] = None) -> list:
        now = now if now is not None else time.time()
        return [e for e in self.log if now - e.timestamp > self.delta_rejoin]

    def _request_cross_witnesses(self, epoch: int) -> list:
        # In production: fan out to peers, collect signed attestations.
        # Here: simulate a peer set that returns fewer than f+1 during partition.
        return []  # no peers reachable -> zero witnesses

    def handle_join_quorum(self, requested_slots: set, now: Optional[float] = None) -> bool:
        suspect = self._suspect_entries(now)
        if not suspect:
            return True  # condition 1 false: log is fresh

        overlapping = [e for e in suspect if e.slot in requested_slots]
        if not overlapping:
            return True  # condition 3 false: no commitment at stake

        # Condition 2: require f+1 cross-witnesses for each overlapping suspect epoch
        for entry in overlapping:
            witnesses = self._request_cross_witnesses(entry.epoch)
            if len(witnesses) < self.f + 1:
                raise UnverifiableHistoryError(
                    f"agent {self.agent_id} cannot prove cross-observed consistency "
                    f"for epoch {entry.epoch} slot {entry.slot}: "
                    f"got {len(witnesses)} witnesses, need {self.f + 1}"
                )

        return True

    def join_or_refuse(self, requested_slots: set, now: Optional[float] = None) -> str:
        try:
            self.handle_join_quorum(requested_slots, now)
            return "JOINED"
        except UnverifiableHistoryError as e:
            # Refusal is the correct protocol action, but the caller must be told
            # explicitly so it can trigger state transfer rather than retry.
            raise QuorumRefusalError(
                f"refusing quorum membership: {e}. "
                f"agent must be re-onboarded via quorum-verified snapshot."
            ) from e


if __name__ == "__main__":
    a3 = Agent(agent_id="A3", f=1, delta_rejoin=90.0)
    now = time.time()
    # Simulate a stale commitment written 120s ago during a partition
    a3.log.append(LogEntry(
        epoch=14, slot="T-14", owner="A3",
        timestamp=now - 120.0,
        signature=hashlib.sha256(b"A3:T-14:14").hexdigest(),
    ))
    try:
        a3.join_or_refuse(requested_slots={"T-14", "T-15"}, now=now)
    except QuorumRefusalError as exc:
        print(f"PROTOCOL ACTION: {exc}")
