# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-revoked-credential-after-a-peer-fails-to-propagate-its-rotation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-revoked-credential-after-a-peer-fails-to-propagate-its-rotation-epoch.warrant.json
# Markdown SHA-256:   b0102c5a4771e8f9fe6a7b182fe662c06fc5da368d768350337931696a59056a
# Code AST SHA-256:   a28f3b63551ec0331c17daaf39ccbdf31341a8f2f33cd8d810f497966482fe68
# Verified Classes:   RevokedWarrantResurrection, ReplicaForkDetected, Warrant, EpochFloor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevokedWarrantResurrection(RuntimeError):
    """Raised when a verifier is asked to accept a warrant epoch below its persisted floor."""
    pass


class ReplicaForkDetected(RuntimeError):
    """Raised when two distinct instances present the same epoch for one agent_id."""
    pass


@dataclass
class Warrant:
    agent_id: str
    instance_id: str
    epoch: int
    scopes: tuple
    signature_valid: bool  # stand-in for real crypto verification


@dataclass
class EpochFloor:
    # Durable, monotonic, keyed on stable agent_id — never on instance_id.
    floor: dict = field(default_factory=dict)          # agent_id -> highest epoch accepted
    bound_instance: dict = field(default_factory=dict)  # agent_id -> instance_id at that epoch

    def verify(self, w: Warrant) -> None:
        if not w.signature_valid:
            raise RevokedWarrantResurrection(
                f"invalid signature for {w.agent_id} epoch {w.epoch}"
            )

        current = self.floor.get(w.agent_id)

        if current is None:
            # First sighting: establish the floor.
            self.floor[w.agent_id] = w.epoch
            self.bound_instance[w.agent_id] = w.instance_id
            return

        if w.epoch < current:
            # Epoch regression: a superseded, possibly revoked warrant re-presented.
            # This is the resurrection. Reject unconditionally; do NOT lower the floor.
            raise RevokedWarrantResurrection(
                f"agent {w.agent_id} presented epoch {w.epoch} "
                f"below floor {current} (instance {w.instance_id}); "
                f"revocation must be enforced at the verifier"
            )

        if w.epoch == current:
            if w.instance_id != self.bound_instance[w.agent_id]:
                # Same epoch, different instance: replica fork, not rotation.
                raise ReplicaForkDetected(
                    f"agent {w.agent_id} epoch {w.epoch} seen on instance "
                    f"{w.instance_id} but floor bound to "
                    f"{self.bound_instance[w.agent_id]}"
                )
            return

        # Strictly newer epoch: advance the floor atomically with authorization.
        self.floor[w.agent_id] = w.epoch
        self.bound_instance[w.agent_id] = w.instance_id


def authorize_action(floor: EpochFloor, w: Warrant, action: str) -> None:
    floor.verify(w)
    if action == "spawn" and "spawn" not in w.scopes:
        raise RevokedWarrantResurrection(
            f"agent {w.agent_id} epoch {w.epoch} lacks scope 'spawn'"
        )


# --- Reproduction of the observed failure ---
floor = EpochFloor()

primary = Warrant("executor", "inst-A", epoch=8, scopes=("read", "write"), signature_valid=True)
authorize_action(floor, primary, "write")  # floor -> 8, bound to inst-A

# Snapshot-restored replica re-presents the pre-rotation warrant.
replica = Warrant("executor", "inst-B", epoch=7, scopes=("read", "write", "spawn"), signature_valid=True)
try:
    authorize_action(floor, replica, "spawn")
except RevokedWarrantResurrection as e:
    print(f"BLOCKED: {e}")
    # Floor remains 8; the resurrection window is closed at first re-presentation.
    assert floor.floor["executor"] == 8
