# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-peer-warrant-is-still-cached-valid-in-its-own-trust-store.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-peer-warrant-is-still-cached-valid-in-its-own-trust-store.warrant.json
# Markdown SHA-256:   603006f487114bdf7b30bd8d1eb504122e01452c077685c7ec8a02cd76e8647d
# Code AST SHA-256:   d3f81fc67b23e5654bab0cd20e01c22e16ad726f0fabaced82d1191aa06b6eec
# Verified Classes:   TrustStoreStaleError, WarrantRevokedError, StatusArtifact, Warrant, FederatedTrustStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class TrustStoreStaleError(RuntimeError):
    """Raised when a warrant cannot be proven fresh against the local trust store."""
    pass


class WarrantRevokedError(RuntimeError):
    """Raised when the peer's warrant is revoked under the current issuer epoch."""
    pass


@dataclass(frozen=True)
class StatusArtifact:
    issuer_id: str
    epoch: int
    issued_at: float
    next_update: float
    revoked_warrant_ids: frozenset


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer_id: str
    issuer_epoch: int
    not_before: float
    not_after: float


class FederatedTrustStore:
    def __init__(self, local_max_staleness: float = 600.0):
        # Keyed by issuer_id -> newest artifact seen. Durable; must be checkpointed.
        self._artifacts: dict[str, StatusArtifact] = {}
        self._local_max_staleness = local_max_staleness

    def ingest(self, artifact: StatusArtifact) -> None:
        stored = self._artifacts.get(artifact.issuer_id)
        # Epoch monotonicity: never overwrite a newer epoch with an older one.
        if stored is not None and artifact.epoch <= stored.epoch:
            return
        self._artifacts[artifact.issuer_id] = artifact

    def verify(
        self,
        warrant: Warrant,
        caller_max_staleness: float,
        side_effecting: bool,
        now: Optional[float] = None,
    ) -> None:
        now = time.time() if now is None else now
        stored = self._artifacts.get(warrant.issuer_id)
        if stored is None:
            # Cold-start amnesia: no epoch to compare against. Fail closed.
            raise TrustStoreStaleError(
                f"no stored artifact for issuer {warrant.issuer_id}; cannot prove freshness"
            )

        # Condition 4: warrant must be issued under the current known epoch.
        if warrant.issuer_epoch < stored.epoch:
            raise TrustStoreStaleError(
                f"warrant epoch {warrant.issuer_epoch} < stored epoch {stored.epoch} "
                f"for issuer {warrant.issuer_id}; possible revocation outrun"
            )

        # Condition 2: composite staleness bound.
        artifact_staleness = now - stored.issued_at
        budget = min(
            stored.next_update - stored.issued_at,
            caller_max_staleness,
            self._local_max_staleness,
        )
        if artifact_staleness > budget:
            raise TrustStoreStaleError(
                f"artifact staleness {artifact_staleness:.1f}s exceeds budget {budget:.1f}s"
            )

        # Condition 3: side-effecting ops require synchronous authoritative check.
        if side_effecting:
            # In production this is a network call to the issuer's status endpoint.
            # Here we simulate a synchronous re-fetch that returns the current epoch.
            authoritative = self._fetch_authoritative(warrant.issuer_id)
            if authoritative.epoch > stored.epoch:
                self.ingest(authoritative)
                stored = authoritative

        if warrant.warrant_id in stored.revoked_warrant_ids:
            raise WarrantRevokedError(
                f"warrant {warrant.warrant_id} revoked under epoch {stored.epoch}"
            )

    def _fetch_authoritative(self, issuer_id: str) -> StatusArtifact:
        # Placeholder for the synchronous status endpoint call.
        raise NotImplementedError


def handle_peer_call(store: FederatedTrustStore, warrant: Warrant, action: str) -> None:
    side_effecting = action in {"write", "execute", "egress"}
    try:
        store.verify(
            warrant,
            caller_max_staleness=600.0,
            side_effecting=side_effecting,
        )
    except (TrustStoreStaleError, WarrantRevokedError) as exc:
        # Halt synchronously; do not enqueue and proceed.
        raise TrustStoreStaleError(f"halting peer call: {exc}") from exc
    # ... proceed with the tool call ...
