# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-valid-capability-grant-but-the-egress-policy-is-evaluated-against-stale-tool-descriptor-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-valid-capability-grant-but-the-egress-policy-is-evaluated-against-stale-tool-descriptor-state.warrant.json
# Markdown SHA-256:   6897640b97c94c12e0eaa95b5f0ebb365f3785f1fe3bb3a62cfe8512ceac7e53
# Code AST SHA-256:   df2f2621ced4b7d120ee21945ada3df94fe545345d5bc0f8425e758548a5d7a2
# Verified Classes:   StalePolicyError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StalePolicyError(RuntimeError):
    """Raised when an egress decision would be made against a descriptor that
    is neither fresh (within max_staleness) nor provably a subset of current
    policy. Retrying will not help; the cache must be refreshed or the call
    rejected. Distinct from transient EgressDenied so retry loops back off."""
    pass


def authorize_egress(conn, token, cached, registry_head, now):
    # 1. Consistency witness: token and descriptor were minted together.
    if token.descriptor_hash != cached.hash:
        raise StalePolicyError(
            f"token pins {token.descriptor_hash}, cache holds {cached.hash}"
        )

    # 2. Freshness: is the cache recent enough to speak for current policy?
    fresh = (now - cached.fetched_at) <= cached.max_staleness

    if fresh and registry_head is not None and registry_head.hash == cached.hash:
        # Current and confirmed: decide directly.
        return conn.host in cached.egress_allow

    # 3. Stale path. Registry may or may not be reachable.
    if registry_head is None:
        # Cannot prove subset; refuse to serve egress from an unverified cache.
        raise StalePolicyError(
            f"descriptor age {now - cached.fetched_at}s exceeds "
            f"max_staleness {cached.max_staleness}s and registry unreachable"
        )

    # 4. Directional check: a stale cache is only safe if it is a SUBSET of
    #    current policy. A superset may permit a newly-revoked host.
    if not cached.egress_allow.issubset(registry_head.egress_allow):
        widened = cached.egress_allow - registry_head.egress_allow
        raise StalePolicyError(
            f"stale cache permits hosts current policy forbids: {sorted(widened)}"
        )

    # Conservative stale cache: narrower than or equal to current policy.
    return conn.host in cached.egress_allow
