# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-scope-has-silently-widened-across-a-re-issuance-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-scope-has-silently-widened-across-a-re-issuance-hop.warrant.json
# Markdown SHA-256:   a82f8b28826705d166e01c46e10d364d70e699df0cdad1cc8f420e45ac775381
# Code AST SHA-256:   d18ae76c518ae14155254ef20277b045083038c1903c624429d6730b1539a33c
# Verified Classes:   ScopeMonotonicityViolation, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeMonotonicityViolation(RuntimeError):
    """Raised when a delegated warrant's scope is not a subset of its parent's."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    grantor: str
    resources: FrozenSet[str]
    verbs: FrozenSet[str]
    expires: float
    parent_ref: str | None


def verify_chain(leaf: Warrant, ancestors: dict[str, Warrant],
                 verifier_matcher) -> None:
    """Reconstruct the delegation chain and assert non-increasing authority.

    `verifier_matcher` maps a resource pattern to its concrete covered set;
    it MUST be the same matcher the leaf uses at call time, never the
    re-issuer's serializer.
    """
    current = leaf
    while current.parent_ref is not None:
        parent = ancestors.get(current.parent_ref)
        if parent is None:
            raise ScopeMonotonicityViolation(
                f"dangling parent_ref {current.parent_ref!r} for issuer "
                f"{current.issuer!r}; cannot prove monotonicity"
            )
        child_set = verifier_matcher(current.resources)
        parent_set = verifier_matcher(parent.resources)
        if not child_set <= parent_set:
            widened = child_set - parent_set
            raise ScopeMonotonicityViolation(
                f"issuer {current.issuer!r} widened scope over grantor "
                f"{current.grantor!r}: uncovered resources {sorted(widened)}"
            )
        if not current.verbs <= parent.verbs:
            raise ScopeMonotonicityViolation(
                f"issuer {current.issuer!r} widened verbs: "
                f"{sorted(current.verbs - parent.verbs)}"
            )
        if current.expires > parent.expires:
            raise ScopeMonotonicityViolation(
                f"issuer {current.issuer!r} extended expiry beyond parent"
            )
        current = parent
