# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-capability-as-still-warranted-during-federated-registry-convergence-and-how-does-the-warrant-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-capability-as-still-warranted-during-federated-registry-convergence-and-how-does-the-warrant-epoch.warrant.json
# Markdown SHA-256:   29edc2fe333fc46f3dd5b6dab476924a79d9cede5662f7744a8c4af588860950
# Code AST SHA-256:   352262c7a11a2620dc7d69f7d581f158c9642e0b9b1cbdc6a901d96851f3c307
# Verified Classes:   WarrantEpochInversion, RevocationFloorViolation, Warrant, Revocation, WarrantCache
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class WarrantEpochInversion(RuntimeError):
    """Origin's warrant epoch is behind a grant the instance already holds.

    Grant and revocation paths are not co-serialized; no execution is safe
    until they reconcile.
    """


class RevocationFloorViolation(RuntimeError):
    """Cached warrant epoch is at or below the observed global revocation floor.

    The instance must re-validate against origin before executing.
    """


@dataclass
class Warrant:
    capability: str
    epoch: int


@dataclass
class Revocation:
    capability: str
    revokes_epoch: int
    revocation_epoch: int


@dataclass
class WarrantCache:
    warrants: dict[str, Warrant] = field(default_factory=dict)
    # Global monotonic floor: advanced by EVERY revocation observed,
    # regardless of which capability it names.
    revocation_floor: int = 0

    def observe_revocation(self, rev: Revocation) -> None:
        # Advance the global floor; do NOT compare against per-key epoch.
        if rev.revocation_epoch > self.revocation_floor:
            self.revocation_floor = rev.revocation_epoch
        # Drop any warrant the revocation names, if still present.
        cached = self.warrants.get(rev.capability)
        if cached is not None and cached.epoch <= rev.revokes_epoch:
            del self.warrants[rev.capability]

    def execute(self, capability: str, origin_warrant: Warrant | None) -> str:
        cached = self.warrants.get(capability)

        # Boundary 1: no cached warrant, or cached epoch at/below floor.
        if cached is None or cached.epoch <= self.revocation_floor:
            if origin_warrant is None:
                raise RevocationFloorViolation(
                    f"capability {capability!r} at/below revocation floor "
                    f"{self.revocation_floor} and origin did not confirm"
                )
            if origin_warrant.epoch <= self.revocation_floor:
                raise RevocationFloorViolation(
                    f"origin warrant epoch {origin_warrant.epoch} still at/below "
                    f"floor {self.revocation_floor}"
                )
            # Origin confirmed above floor; install and proceed.
            self.warrants[capability] = origin_warrant
            return f"executed {capability} (origin-validated @ {origin_warrant.epoch})"

        # Boundary 2: origin reports an epoch behind our cached grant.
        if origin_warrant is not None and origin_warrant.epoch < cached.epoch:
            raise WarrantEpochInversion(
                f"origin epoch {origin_warrant.epoch} < cached epoch {cached.epoch} "
                f"for {capability!r}; grant/revocation paths unsynchronized"
            )

        return f"executed {capability} (cached @ {cached.epoch}, floor {self.revocation_floor})"


if __name__ == "__main__":
    cache = WarrantCache()
    cache.warrants["write:ledger"] = Warrant("write:ledger", 41)

    # New grant arrives first (epoch 45), then the revocation of epoch 41.
    cache.warrants["write:reconcile"] = Warrant("write:reconcile", 45)
    cache.observe_revocation(
        Revocation("write:ledger", revokes_epoch=41, revocation_epoch=44)
    )

    # Without the global floor, this would execute. With it, floor=44 and
    # write:reconcile @ 45 is above floor -> allowed; write:ledger is gone.
    assert cache.revocation_floor == 44
    assert "write:ledger" not in cache.warrants

    # A capability the revocation did NOT name but whose epoch <= floor
    # must be re-validated. Simulate a stale cached warrant at epoch 43.
    cache.warrants["rotate:creds"] = Warrant("rotate:creds", 43)
    try:
        cache.execute("rotate:creds", origin_warrant=None)
        raise AssertionError("expected RevocationFloorViolation")
    except RevocationFloorViolation:
        pass

    # Origin reports epoch behind a cached grant -> inversion.
    try:
        cache.execute("write:reconcile", origin_warrant=Warrant("write:reconcile", 40))
        raise AssertionError("expected WarrantEpochInversion")
    except WarrantEpochInversion:
        pass

    print(cache.execute("write:reconcile", origin_warrant=None))
