# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-crosses-a-sovereignty-boundary-mid-tool-call-and-the-federation-router-silently-re-derives-policy-from-a-stale-capabilit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-crosses-a-sovereignty-boundary-mid-tool-call-and-the-federation-router-silently-re-derives-policy-from-a-stale-capabilit.warrant.json
# Markdown SHA-256:   9c958f89bc3167ea6d3a1702cb578081a4f2ff4873bf7b5cde2224e5f42548fe
# Code AST SHA-256:   8b32859b2f586c8e0e6f02ea6770e5e71f8e5f9bb5569546225ae2f6a03ff498
# Verified Classes:   SovereigntyCacheKeyCollapse, Warrant, ToolCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SovereigntyCacheKeyCollapse(RuntimeError):
    """Raised when a routing warrant cache key would conflate a capability
    family with a payload sovereignty class, allowing a read-phase warrant
    to authorize a write-phase message."""
    pass


@dataclass(frozen=True)
class Warrant:
    capability_id: str
    sovereignty_class: str  # e.g. "EU-only", "US-only", "GLOBAL"
    cacheable: bool
    expires_at: float


@dataclass(frozen=True)
class ToolCall:
    sender: str
    recipient: str
    capability_id: str
    payload_sovereignty_class: Optional[str]  # None => unclassified, must fail closed


SOVEREIGNTY_SUBSET = {
    ("EU-only", "EU-only"): True,
    ("EU-only", "GLOBAL"): True,
    ("US-only", "US-only"): True,
    ("US-only", "GLOBAL"): True,
    ("GLOBAL", "GLOBAL"): True,
}


def derive_cache_key(call: ToolCall, capability_family: str) -> tuple:
    """Cache key MUST include the concrete capability_id and the payload
    sovereignty class. Normalizing capability_id to a family is permitted
    only for tool-name matching, never for warrant cache keying."""
    if call.capability_id != capability_family:
        raise SovereigntyCacheKeyCollapse(
            f"capability_id={call.capability_id!r} was normalized to "
            f"family={capability_family!r} for cache keying; this collapses "
            f"distinct sovereignty classes and is unsound."
        )
    if call.payload_sovereignty_class is None:
        # Fail closed: unclassified payloads must not hit the cache.
        return (call.sender, call.recipient, call.capability_id, "__UNCACHED__")
    return (call.sender, call.recipient, call.capability_id, call.payload_sovereignty_class)


def authorize_via_cache(
    call: ToolCall,
    cache: dict,
    now: float,
) -> Warrant:
    if call.payload_sovereignty_class is None:
        raise SovereigntyCacheKeyCollapse(
            "Refusing cache lookup: payload sovereignty class is unclassified. "
            "Router must consult PDP synchronously (fail-closed)."
        )
    key = derive_cache_key(call, capability_family=call.capability_id)
    warrant = cache.get(key)
    if warrant is None:
        raise SovereigntyCacheKeyCollapse(
            f"No warrant cached for {key}; mandatory PDP consultation required."
        )
    if not warrant.cacheable or warrant.expires_at < now:
        raise SovereigntyCacheKeyCollapse(
            f"Warrant {key} is not reusable (cacheable={warrant.cacheable}, "
            f"expired={warrant.expires_at < now})."
        )
    if not SOVEREIGNTY_SUBSET.get((call.payload_sovereignty_class, warrant.sovereignty_class), False):
        raise SovereigntyCacheKeyCollapse(
            f"Payload class {call.payload_sovereignty_class!r} is not a subset of "
            f"warrant class {warrant.sovereignty_class!r}; refusing reuse."
        )
    return warrant
