# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-federation-egress-policy-at-tool-call-time-and-why-cached-residency-verdicts-silently-expire.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-federation-egress-policy-at-tool-call-time-and-why-cached-residency-verdicts-silently-expire.warrant.json
# Markdown SHA-256:   eed70e45eb025d4f9e029153deac0b5e6ae936040c6a9761731828047d619652
# Code AST SHA-256:   88add1687ef8e4ce723477e5583fd3b07f46f66df26688c2cb0afdc9f4a02e72
# Verified Classes:   StaleEgressVerdict, EgressVerdict
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEgressVerdict(RuntimeError):
    """Raised when a cached federation egress verdict no longer describes
    the state vector it was minted against."""
    pass


@dataclass(frozen=True)
class EgressVerdict:
    tenant: str
    tool: str
    treaty_version: int
    tool_epoch: int
    residency: str
    payload_class: str
    ttl_remaining_s: int


def pre_egress_barrier(
    verdict: EgressVerdict,
    *,
    current_treaty_version: int,
    current_tool_epoch: int,
    current_residency: str,
    payload_class_now: str,
    payload_transformed_since_mint: bool,
) -> None:
    # TTL and signature are necessary but NOT sufficient.
    if verdict.ttl_remaining_s <= 0:
        raise StaleEgressVerdict(
            f"verdict for {verdict.tool} expired (ttl={verdict.ttl_remaining_s})"
        )

    # Clause 1: treaty renegotiation invalidates the lease.
    if current_treaty_version != verdict.treaty_version:
        raise StaleEgressVerdict(
            f"treaty drift: verdict={verdict.treaty_version} "
            f"current={current_treaty_version}"
        )

    # Clause 2: tool re-registration (epoch bump) invalidates the lease,
    # even when the new egress class is WIDER than the old one.
    if current_tool_epoch != verdict.tool_epoch:
        raise StaleEgressVerdict(
            f"tool epoch drift for {verdict.tool}: "
            f"verdict={verdict.tool_epoch} current={current_tool_epoch}"
        )

    # Clause 3: tenant re-homing invalidates the lease.
    if current_residency != verdict.residency:
        raise StaleEgressVerdict(
            f"residency drift for {verdict.tenant}: "
            f"verdict={verdict.residency} current={current_residency}"
        )

    # Clause 4: the clause agents most often miss. A transformation since
    # mint can PROMOTE payload classification; the verdict was never
    # evaluated for the promoted class.
    if payload_transformed_since_mint and payload_class_now != verdict.payload_class:
        raise StaleEgressVerdict(
            f"payload class promoted since mint for {verdict.tool}: "
            f"verdict={verdict.payload_class} current={payload_class_now}; "
            f"re-derive verdict before egress"
        )


def guarded_egress(
    verdict: EgressVerdict,
    *,
    current_treaty_version: int,
    current_tool_epoch: int,
    current_residency: str,
    payload_class_now: str,
    payload_transformed_since_mint: bool,
    rederive,
):
    try:
        pre_egress_barrier(
            verdict,
            current_treaty_version=current_treaty_version,
            current_tool_epoch=current_tool_epoch,
            current_residency=current_residency,
            payload_class_now=payload_class_now,
            payload_transformed_since_mint=payload_transformed_since_mint,
        )
    except StaleEgressVerdict:
        # Barrier failed: re-derive against the live state vector, do not
        # fall back to the stale verdict under any circumstance.
        fresh: Optional[EgressVerdict] = rederive(
            verdict.tenant, verdict.tool, payload_class_now
        )
        if fresh is None:
            raise StaleEgressVerdict(
                f"re-derivation refused for {verdict.tool}; egress blocked"
            )
        return fresh
    return verdict
