# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-split-brain-identity-during-federated-agent-key-rotation-under-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-split-brain-identity-during-federated-agent-key-rotation-under-aaif.warrant.json
# Markdown SHA-256:   e0758149b13ae5582a32a44e8ff92d99fe71c1ced44d23d32cb31802da77c984
# Code AST SHA-256:   6c0eefe890c3af4acbf26bae6198779f9d75d87fa549a9bcb7790699a5648d16
# Verified Classes:   EpochFenceTimeout, MonotonicityViolation, FenceState, EpochFenceVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class EpochFenceTimeout(RuntimeError):
    """Raised when a verifier cannot confirm the superseded epoch's revocation
    within the rotation quarantine TTL, and therefore must fail closed rather
    than accept the higher epoch on faith."""


class MonotonicityViolation(RuntimeError):
    """Raised when a warrant's epoch is lower than the highest epoch already
    acknowledged for the same agent_id in this verifier's table."""


@dataclass
class FenceState:
    agent_id: str
    highest_epoch: int
    pending_epoch: int | None = None
    pending_since: float | None = None
    superseded_confirmed: bool = False


class EpochFenceVerifier:
    def __init__(self, quarantine_ttl_s: float = 6.0):
        self.ttl = quarantine_ttl_s
        self._table: dict[str, FenceState] = {}
        self._revoked: dict[str, set[int]] = {}

    def note_revocation(self, agent_id: str, epoch: int) -> None:
        self._revoked.setdefault(agent_id, set()).add(epoch)
        st = self._table.get(agent_id)
        if st and st.pending_epoch is not None and epoch == st.pending_epoch - 1:
            st.superseded_confirmed = True

    def verify(self, agent_id: str, epoch: int, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now
        st = self._table.get(agent_id)
        if st is None:
            self._table[agent_id] = FenceState(agent_id, epoch)
            return

        if epoch < st.highest_epoch:
            raise MonotonicityViolation(
                f"{agent_id}: warrant epoch {epoch} < acknowledged {st.highest_epoch}"
            )

        if epoch == st.highest_epoch:
            return

        # Higher epoch observed: open a pending fence, do not accept yet.
        if st.pending_epoch != epoch:
            st.pending_epoch = epoch
            st.pending_since = now
            st.superseded_confirmed = (st.highest_epoch in self._revoked.get(agent_id, set()))

        if not st.superseded_confirmed:
            if now - st.pending_since > self.ttl:
                raise EpochFenceTimeout(
                    f"{agent_id}: epoch {epoch} fence unconfirmed for "
                    f"{now - st.pending_since:.2f}s > ttl {self.ttl}s; "
                    f"superseded epoch {st.highest_epoch} revocation not observed"
                )
            # Quarantine: caller must retry, not accept.
            raise EpochFenceTimeout(
                f"{agent_id}: epoch {epoch} quarantined pending confirmation of "
                f"epoch {st.highest_epoch} revocation"
            )

        st.highest_epoch = epoch
        st.pending_epoch = None
        st.pending_since = None
        st.superseded_confirmed = False
