# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-its-delegated-scope-rather-than-trust-the-cached-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-its-delegated-scope-rather-than-trust-the-cached-warrant-chain.warrant.json
# Markdown SHA-256:   675b5828548504b2c52a6d68629cae6991cc4f25e6186f8f70c5ac5e295c7b09
# Code AST SHA-256:   9b3d2969d17902b2fa4e3a945b2424230322f22c9bfdaccd207943bc26ad3e45
# Verified Classes:   EpochSkewViolation, CachedDerivation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class EpochSkewViolation(RuntimeError):
    """Raised when a cached effective scope is being trusted across a policy epoch boundary."""
    pass


@dataclass(frozen=True)
class CachedDerivation:
    sig_chain: str
    epoch: int
    effective_scope: frozenset  # set of capability selectors
    literal_scope: frozenset     # most restrictive literal reading of raw chain claims
    derived_at: float


def cache_key(sig_chain: str, epoch: int) -> str:
    return hashlib.sha256(f"{sig_chain}:{epoch}".encode()).hexdigest()


def authorize(
    cached: CachedDerivation,
    requested: str,
    root_current_epoch: int | None,
    epoch_ttl: float,
    irreversible: bool,
    now: float | None = None,
) -> bool:
    now = now if now is not None else time.time()

    # Partition from epoch service: cannot confirm currency -> fall back to literal bounds.
    if root_current_epoch is None:
        if irreversible:
            raise EpochSkewViolation(
                f"irreversible action {requested!r} requested while partitioned from epoch service"
            )
        return requested in cached.literal_scope

    # Epoch advanced since derivation: cache is stale regardless of signature identity.
    if root_current_epoch != cached.epoch:
        raise EpochSkewViolation(
            f"cached epoch {cached.epoch} != root epoch {root_current_epoch} "
            f"for {requested!r}; re-derive required"
        )

    # Widening edge: requested capability is in effective but not literal scope.
    # The broadening came from an epoch interpretation; must re-derive.
    if requested in cached.effective_scope and requested not in cached.literal_scope:
        raise EpochSkewViolation(
            f"{requested!r} permitted only via epoch-dependent widening; re-derive required"
        )

    # Stale beyond TTL.
    if now - cached.derived_at > epoch_ttl:
        raise EpochSkewViolation(
            f"derivation age {now - cached.derived_at:.1f}s exceeds ttl {epoch_ttl}s"
        )

    # Irreversible actions always re-derive even on a fresh, epoch-current cache.
    if irreversible:
        raise EpochSkewViolation(
            f"irreversible action {requested!r} requires fresh derivation"
        )

    return requested in cached.effective_scope
