# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-policy-assertion-as-stale-rather-than-authoritative-during-cross-org-federation-trust-negotia.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-policy-assertion-as-stale-rather-than-authoritative-during-cross-org-federation-trust-negotia.warrant.json
# Markdown SHA-256:   9b25532c0bc7b23629cefcc306faff237d949137fe597336d49d907de8cab63a
# Code AST SHA-256:   7ac25fc0e7140327b04c589eeb65347cabeee30936010cdf8e572b8e37f6cd5e
# Verified Classes:   StalePolicyAssertion, PolicyAssertion, CallIntent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StalePolicyAssertion(RuntimeError):
    """Raised when a cached cross-org policy assertion cannot be trusted
    as authoritative for the pending call because its enforcement epoch
    is unconfirmed or has diverged from the issuer's current epoch."""


@dataclass
class PolicyAssertion:
    policy_id: str
    issued_at: float
    ttl: float
    epoch: str
    tightenable_constraints: frozenset[str]
    fixed_constraints: frozenset[str]


@dataclass
class CallIntent:
    touches_constraints: frozenset[str]


def authorize_call(
    assertion: PolicyAssertion,
    intent: CallIntent,
    now: float,
    last_response_epoch: Optional[str],
    propagation_worst_case: float,
) -> None:
    effective_ttl = assertion.ttl - propagation_worst_case
    if now - assertion.issued_at >= effective_ttl:
        raise StalePolicyAssertion(
            f"policy {assertion.policy_id} past effective ttl "
            f"({effective_ttl}s after propagation lag); renegotiate"
        )

    tightenable_hit = intent.touches_constraints & assertion.tightenable_constraints
    if not tightenable_hit:
        return  # only fixed constraints: cached bundle is safe

    if last_response_epoch is None:
        raise StalePolicyAssertion(
            f"call touches tightenable constraints {sorted(tightenable_hit)} "
            f"but callee epoch is unconfirmed; refuse cached policy"
        )
    if last_response_epoch != assertion.epoch:
        raise StalePolicyAssertion(
            f"epoch mismatch: cached={assertion.epoch} "
            f"callee={last_response_epoch}; discard bundle and re-fetch"
        )
