# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-warrant-that-verifies-cryptographically-but-violates-the-delegator-s-policy-closure-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-warrant-that-verifies-cryptographically-but-violates-the-delegator-s-policy-closure-i.warrant.json
# Markdown SHA-256:   22a5b17476960a307ebf85887f7fc8cd50bd69f78c5799623dd44876ae500fff
# Code AST SHA-256:   f3697411cb9ced838a25e697b598557771757d16f1e257a44c48a184cda31fcf
# Verified Classes:   ClosureViolation, Warrant, ReceiverPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Dict, Set


class ClosureViolation(RuntimeError):
    """Raised when a cryptographically valid warrant does not entail the
    receiver's obligation set. This is a delegation-shape error, not a
    runtime error: it must be surfaced to the delegator, never swallowed."""

    def __init__(self, warrant_id: str, unmet: Set[str]):
        self.warrant_id = warrant_id
        self.unmet = unmet
        super().__init__(
            f"warrant {warrant_id} fails policy closure; unmet obligations: "
            f"{sorted(unmet)}"
        )


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    signature_valid: bool
    caveats: Dict[str, str]          # caveat name -> value, additive only
    capability: str


@dataclass
class ReceiverPolicy:
    org: str
    # obligation name -> predicate over caveat value; must be POSITIVELY discharged
    obligations: Dict[str, Callable[[str], bool]] = field(default_factory=dict)

    def check_closure(self, w: Warrant) -> None:
        # Iterate O_R, NOT C_W. Absence of a caveat is a failure, not a pass.
        unmet: Set[str] = set()
        for name, predicate in self.obligations.items():
            if name not in w.caveats:
                unmet.add(f"{name}:absent")
                continue
            if not predicate(w.caveats[name]):
                unmet.add(f"{name}:unsatisfied")
        if unmet:
            raise ClosureViolation(w.warrant_id, unmet)


def admit(w: Warrant, policy: ReceiverPolicy) -> None:
    if not w.signature_valid:
        raise ClosureViolation(w.warrant_id, {"signature:invalid"})
    policy.check_closure(w)   # gate 2: positive entailment C_W |= O_R


# --- reproduction of the observed failure ---
w2 = Warrant(
    warrant_id="W2",
    issuer="broker@z",
    signature_valid=True,
    caveats={"region": "EU", "purpose": "audit", "max_calls": "50"},
    capability="read:records",
)

y_policy = ReceiverPolicy(
    org="Y",
    obligations={
        "region": lambda v: v == "EU",
        "subprocessor_approved": lambda v: v == "true",
    },
)

try:
    admit(w2, y_policy)           # signature OK; closure fails on subprocessor_approved
except ClosureViolation as e:
    # correct bounded response: reject + escalate to delegator, do NOT execute
    # and do NOT strip the capability and run a narrowed remainder
    escalate_to_delegator(e)
