# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-federated-delegation-when-a-residency-bound-sub-agent-inherits-a-broader-policy-scope-than-its-parent-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-federated-delegation-when-a-residency-bound-sub-agent-inherits-a-broader-policy-scope-than-its-parent-warrant.warrant.json
# Markdown SHA-256:   0ed8c111ed1343772ddcc9d027001ad9abacc8642514156e38fdc02aee662e95
# Code AST SHA-256:   ca47a6736c7d0ebabb926e577cf7191bb36c49f4249f6c41351aa7cb2076b20c
# Verified Classes:   ResidencyScopeViolation, UnrepresentableConstraint, Scope, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResidencyScopeViolation(RuntimeError):
    """Raised when a delegated callee's effective scope is not a subset of the
    delegating warrant's scope on a residency or retention pin."""
    pass


class UnrepresentableConstraint(RuntimeError):
    """Raised when the callee's policy schema cannot express an inherited
    constraint field, making intersection undefined. Fail closed."""
    pass


@dataclass(frozen=True)
class Scope:
    data_class: str
    residency: Optional[str]      # None = field absent in schema
    max_retention_h: Optional[int]
    residency_supported: bool = True


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    scope: Scope
    granted_capabilities: frozenset


def intersect(parent: Scope, child_local: Scope) -> Scope:
    # Residency/retention: intersection, never override. Absent field = undefined.
    if not child_local.residency_supported or child_local.residency is None:
        raise UnrepresentableConstraint(
            f"callee schema cannot express residency (parent pin={parent.residency!r}); "
            f"refusing delegation rather than dropping the pin"
        )
    if parent.residency != child_local.residency:
        # Pin mismatch: intersection of distinct residency sets is empty -> violation.
        raise ResidencyScopeViolation(
            f"residency pin mismatch: warrant={parent.residency!r} "
            f"callee_local={child_local.residency!r}"
        )
    retention = min(
        x for x in (parent.max_retention_h, child_local.max_retention_h) if x is not None
    )
    return Scope(
        data_class=parent.data_class,
        residency=parent.residency,
        max_retention_h=retention,
        residency_supported=True,
    )


def route_delegation(warrant: Warrant, callee_local: Scope,
                     chain: list) -> Scope:
    """Compute effective scope over the full warrant chain and enforce subset.
    chain[0] is the original warrant scope; callee_local is the leaf's local scope."""
    effective = callee_local
    for inherited in reversed(chain):
        effective = intersect(inherited, effective)

    # Subset check against the ORIGINAL warrant, not the immediate parent.
    root = warrant.scope
    if effective.residency != root.residency:
        raise ResidencyScopeViolation(
            f"effective residency {effective.residency!r} not subset of "
            f"warrant {root.residency!r} (warrant={warrant.warrant_id})"
        )
    if (effective.max_retention_h or 0) > (root.max_retention_h or 0):
        raise ResidencyScopeViolation(
            f"effective retention {effective.max_retention_h} exceeds "
            f"warrant {root.max_retention_h} (warrant={warrant.warrant_id})"
        )
    return effective
