# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-s-egress-allowlist-decision-as-valid-only-for-the-exact-resolved-invocation-tuple-and-reject-reuse.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-s-egress-allowlist-decision-as-valid-only-for-the-exact-resolved-invocation-tuple-and-reject-reuse.warrant.json
# Markdown SHA-256:   ff2e9a0c5fe9a0903974a56a34f65893063bcf3c3eaf692b8496fcd269829870
# Code AST SHA-256:   f3d344245be067e1dd6dd49084f815b9d9fcde6cb1c93a008869e58ceadc71c7
# Verified Classes:   EgressDecisionInvalid, Invocation, Decision, EgressPolicy
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class EgressDecisionInvalid(RuntimeError):
    """Raised when a cached allowlist decision is reused outside its validity tuple."""


@dataclass(frozen=True)
class Invocation:
    agent_instance_id: str
    tool_id: str
    args_digest: str          # hash of canonicalized args; NOT sufficient alone
    resolved_target: str      # address the transport will actually connect to
    resolution_epoch: int     # monotonic counter bumped on every re-resolution
    policy_version: int
    redirect_hops: tuple = field(default_factory=tuple)


@dataclass(frozen=True)
class Decision:
    agent_instance_id: str
    tool_id: str
    resolved_target: str
    resolution_epoch: int
    policy_version: int
    redirects_covered: int
    minted_at: float
    verdict: str              # "ALLOW" | "DENY"


class EgressPolicy:
    def __init__(self, allowlist_cidrs, min_resolver_ttl_s: float):
        self.allowlist = allowlist_cidrs
        self.min_ttl = min_resolver_ttl_s
        self._table: dict[tuple, Decision] = {}
        self._policy_version = 1

    def revoke(self) -> None:
        self._policy_version += 1
        self._table.clear()

    def evaluate(self, inv: Invocation) -> Decision:
        if not self._target_allowed(inv.resolved_target):
            return Decision(
                inv.agent_instance_id, inv.tool_id, inv.resolved_target,
                inv.resolution_epoch, self._policy_version,
                len(inv.redirect_hops), time.monotonic(), "DENY",
            )
        d = Decision(
            inv.agent_instance_id, inv.tool_id, inv.resolved_target,
            inv.resolution_epoch, self._policy_version,
            len(inv.redirect_hops), time.monotonic(), "ALLOW",
        )
        key = (inv.agent_instance_id, inv.tool_id, inv.resolved_target,
               inv.resolution_epoch, self._policy_version)
        self._table[key] = d
        return d

    def _target_allowed(self, target: str) -> bool:
        return any(target.startswith(c) for c in self.allowlist)


def dispatch(policy: EgressPolicy, inv: Invocation) -> Decision:
    """Dispatch-time gate: only a target-bound, epoch-current, policy-current,
    identity-matched, redirect-complete decision may authorize egress."""
    key = (inv.agent_instance_id, inv.tool_id, inv.resolved_target,
           inv.resolution_epoch, policy._policy_version)
    d: Optional[Decision] = policy._table.get(key)

    if d is not None:
        # A hit is valid only if every element of the tuple still matches.
        if d.resolved_target != inv.resolved_target:
            raise EgressDecisionInvalid(
                f"decision target {d.resolved_target!r} != resolved target "
                f"{inv.resolved_target!r} for invocation {inv.tool_id}"
            )
        if d.resolution_epoch != inv.resolution_epoch:
            raise EgressDecisionInvalid(
                f"stale resolution epoch {d.resolution_epoch} != "
                f"{inv.resolution_epoch}; re-resolve invalidated decision"
            )
        if d.policy_version != policy._policy_version:
            raise EgressDecisionInvalid(
                f"decision minted under policy v{d.policy_version}, "
                f"current v{policy._policy_version}; revocation not applied"
            )
        if d.agent_instance_id != inv.agent_instance_id:
            raise EgressDecisionInvalid(
                "decision inherited across instance identity; "
                "checkpoint-restored tables must be discarded, not reused"
            )
        if d.redirects_covered < len(inv.redirect_hops):
            raise EgressDecisionInvalid(
                f"decision covers {d.redirects_covered} hops but invocation "
                f"carries {len(inv.redirect_hops)}; every hop must be evaluated"
            )
        if (time.monotonic() - d.minted_at) > policy.min_ttl:
            raise EgressDecisionInvalid(
                "decision lease expired relative to resolver min TTL"
            )
        if d.verdict != "ALLOW":
            raise EgressDecisionInvalid(f"cached verdict is {d.verdict}")

    return policy.evaluate(inv)


def resume_from_checkpoint(policy: EgressPolicy, serialized_table: dict) -> None:
    """Checkpoint-resume must NOT restore decision tables: they carry stale
    authority minted under a prior resolver state and policy version."""
    if serialized_table:
        raise EgressDecisionInvalid(
            "refusing to restore serialized egress decision table across "
            "process boundary; re-mint decisions under current policy epoch"
        )
    policy._table.clear()
