# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-handshake-as-uncommitted-until-the-counterparty-s-sovereignty-warrant-is-re-verified-again.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-handshake-as-uncommitted-until-the-counterparty-s-sovereignty-warrant-is-re-verified-again.warrant.json
# Markdown SHA-256:   afe83d75ef77b92069ac91c3316b98f3952d6210c534370895b43a1dcdf7ec23
# Code AST SHA-256:   fa17963f63c5d522f8c5b50bc9b1840bd958d17ca8bc28043bc0fa365a681aa6
# Verified Classes:   WarrantDivergence, Policy, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import FrozenSet


class WarrantDivergence(RuntimeError):
    """Raised when a counterparty's sovereignty warrant no longer supports the agreed policy."""
    pass


@dataclass(frozen=True)
class Policy:
    allowed_classes: FrozenSet[str]
    residency: FrozenSet[str]
    retention_hours: int
    agreement_hash: str


@dataclass(frozen=True)
class Warrant:
    current_lattice: FrozenSet[str]
    issued_at: float
    ttl_seconds: float
    bound_to: str  # must equal policy.agreement_hash
    issuer_key_id: str


def validate_transfer(
    policy: Policy,
    warrant: Warrant,
    payload_class: str,
    trusted_issuer_keys: FrozenSet[str],
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if payload_class not in policy.allowed_classes:
        raise WarrantDivergence(
            f"payload class {payload_class!r} not in policy.allowed_classes "
            f"{sorted(policy.allowed_classes)}"
        )

    # The perishable check: warrant must be bound to THIS agreement.
    if warrant.bound_to != policy.agreement_hash:
        raise WarrantDivergence(
            f"warrant bound to {warrant.bound_to!r}, agreement is "
            f"{policy.agreement_hash!r} (stale or replayed warrant)"
        )

    # The perishable check: warrant must be fresh at transfer time.
    if now - warrant.issued_at > warrant.ttl_seconds:
        raise WarrantDivergence(
            f"warrant expired: age {now - warrant.issued_at:.1f}s > "
            f"ttl {warrant.ttl_seconds:.1f}s"
        )

    # The perishable check: policy's declared residency must be a subset of
    # the warrant's CURRENT lattice -- this is the clause that caught the
    # observed incident (policy said EU; warrant lattice had drifted to {EU, US}).
    if not policy.residency.issubset(warrant.current_lattice):
        raise WarrantDivergence(
            f"policy residency {sorted(policy.residency)} not subset of "
            f"warrant lattice {sorted(warrant.current_lattice)}"
        )

    if warrant.issuer_key_id not in trusted_issuer_keys:
        raise WarrantDivergence(
            f"warrant issuer key {warrant.issuer_key_id!r} not in trust root"
        )


def transfer_batch(policy: Policy, warrant: Warrant, payloads: list[dict],
                   trusted_issuer_keys: FrozenSet[str]) -> int:
    """Validate before every batch; fail closed on any divergence."""
    validate_transfer(policy, warrant, "PII-restricted", trusted_issuer_keys)
    # ... actual egress ...
    return len(payloads)
