# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-aaif-warrant-s-attenuation-chain-is-valid-but-its-scope-lattice-is-non-monotonic.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-aaif-warrant-s-attenuation-chain-is-valid-but-its-scope-lattice-is-non-monotonic.warrant.json
# Markdown SHA-256:   f92e5c06b9853aa4a4a011e7d7927a3009259634de681302b56822ef19374a1e
# Code AST SHA-256:   572910d16b2403b99399f41f60b331bf80e91287eb872393c00c8644b2bafba2
# Verified Classes:   DelegationScopeViolation, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationScopeViolation(RuntimeError):
    """Raised when an AAIF attenuation chain verifies but effective scope is not monotonic."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: str | None
    serialized_scope: FrozenSet[str]
    lattice_snapshot: str | None


def effective_scope(warrant: Warrant, lattice: dict[str, FrozenSet[str]], snapshot: str) -> FrozenSet[str]:
    if warrant.lattice_snapshot is not None and warrant.lattice_snapshot != snapshot:
        raise DelegationScopeViolation(
            f"warrant {warrant.warrant_id} pinned to snapshot {warrant.lattice_snapshot}, "
            f"evaluated under {snapshot}"
        )
    scope = set(warrant.serialized_scope)
    for cap in warrant.serialized_scope:
        scope |= lattice.get(cap, frozenset())
    return frozenset(scope)


def authorize_delegated_call(
    child: Warrant,
    parent: Warrant,
    requested: str,
    lattice: dict[str, FrozenSet[str]],
    snapshot: str,
) -> None:
    if child.parent_id != parent.warrant_id:
        raise DelegationScopeViolation(
            f"warrant {child.warrant_id} does not name {parent.warrant_id} as parent"
        )

    parent_eff = effective_scope(parent, lattice, snapshot)
    child_eff = effective_scope(child, lattice, snapshot)

    if requested not in child_eff:
        raise DelegationScopeViolation(
            f"requested capability {requested} not in child effective scope"
        )

    difference = child_eff - parent_eff
    if difference:
        raise DelegationScopeViolation(
            f"non-monotonic delegation under snapshot {snapshot}: "
            f"child {child.warrant_id} effective scope exceeds parent {parent.warrant_id} "
            f"by {sorted(difference)}"
        )
