# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-a-capability-warrant-after-cross-org-policy-renegotiation-and-why-the-first-use-cache-is-the-failure-point.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-a-capability-warrant-after-cross-org-policy-renegotiation-and-why-the-first-use-cache-is-the-failure-point.warrant.json
# Markdown SHA-256:   c38859a02038b086fa28f5309e514e4707ddeb09a5c792ec871b7adc79a602d7
# Code AST SHA-256:   3580a1b0fb226d9bbbb04e2612d2ef573f1793371c188dd6b476ab79ebf1a710
# Verified Classes:   StaleWarrantError, WarrantCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleWarrantError(RuntimeError):
    """Raised when a cached capability warrant references an issuer policy
    epoch that has advanced since the warrant was issued."""
    pass


class WarrantCache:
    def __init__(self, issuer_epoch_probe):
        # cache key: (capability, issuer_policy_epoch) -> warrant
        self._cache = {}
        # tracks the epoch each cached warrant was issued under
        self._warrant_epoch = {}
        self._probe_epoch = issuer_epoch_probe  # callable(issuer) -> epoch token

    def consume(self, issuer, capability, invoke):
        warrant = self._cache.get((issuer, capability))
        if warrant is None:
            warrant = self._negotiate(issuer, capability)
            epoch = self._probe_epoch(issuer)
            self._cache[(issuer, capability)] = warrant
            self._warrant_epoch[(issuer, capability)] = epoch
            return invoke(warrant)

        issued_epoch = self._warrant_epoch[(issuer, capability)]
        current_epoch = self._probe_epoch(issuer)

        # Invariant: a warrant is a lease on a policy epoch, not a capability.
        if current_epoch != issued_epoch:
            del self._cache[(issuer, capability)]
            del self._warrant_epoch[(issuer, capability)]
            raise StaleWarrantError(
                f"warrant for {capability!r} from {issuer!r} issued under "
                f"epoch {issued_epoch!r} but issuer is now at {current_epoch!r}; "
                f"renegotiation required before reuse"
            )

        # Even at matching epoch, a burst of granular denials is a warrant-health
        # signal, not independent object errors.
        result = invoke(warrant)
        if result.denial_rate(window=20) > 0.15:
            del self._cache[(issuer, capability)]
            del self._warrant_epoch[(issuer, capability)]
            raise StaleWarrantError(
                f"granular denial rate {result.denial_rate(window=20):.2f} under "
                f"warrant for {capability!r} suggests epoch-advance masking; "
                f"forcing revalidation"
            )
        return result

    def _negotiate(self, issuer, capability):
        raise NotImplementedError
