# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-scopes-from-silently-widening-across-aaif-credential-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-scopes-from-silently-widening-across-aaif-credential-chains.warrant.json
# Markdown SHA-256:   d030b69244368749212b2a8634adc25a360757c99e33dd5eb865c636672f32c8
# Code AST SHA-256:   7f040370e146814eab6b77a7b01c4081eedb822f0617f8aceda40dc1e9b4c142
# Verified Classes:   ScopeWideningError, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated credential's resolved capability set is not a
    subset of its parent's resolved capability set under the same epoch."""


@dataclass(frozen=True)
class Credential:
    scope_expr: str
    resolution_epoch: int
    delegation_depth: int
    max_depth: int


def resolve(scope_expr: str, epoch: int) -> FrozenSet[str]:
    # Registry lookup; open qualifiers may gain members across epochs.
    registry = {
        (41, "invoice:read:region=eu"): frozenset({"read:eu", "read:us", "read:apac"}),
        (40, "invoice:read:region=eu"): frozenset({"read:eu"}),
        (41, "invoice:read:*"): frozenset({"read:eu", "read:us", "read:apac", "read:latam"}),
        (40, "invoice:read:*"): frozenset({"read:eu", "read:us", "read:apac"}),
    }
    if (epoch, scope_expr) not in registry:
        raise ScopeWideningError(f"unresolvable scope {scope_expr!r} at epoch {epoch}")
    return registry[(epoch, scope_expr)]


def verify_attenuation(parent: Credential, child: Credential, pdp_epoch: int) -> None:
    if child.delegation_depth > child.max_depth:
        raise ScopeWideningError(
            f"delegation depth {child.delegation_depth} exceeds max {child.max_depth}"
        )
    # Invariant: child must be proven against the same epoch the PDP now uses,
    # and that epoch must match the parent's pinned epoch.
    if child.resolution_epoch != pdp_epoch:
        raise ScopeWideningError(
            f"epoch skew: credential pinned at {child.resolution_epoch}, "
            f"PDP resolving at {pdp_epoch}"
        )
    if parent.resolution_epoch != child.resolution_epoch:
        raise ScopeWideningError(
            f"parent/child epoch mismatch: {parent.resolution_epoch} vs "
            f"{child.resolution_epoch}"
        )
    parent_caps = resolve(parent.scope_expr, parent.resolution_epoch)
    child_caps = resolve(child.scope_expr, child.resolution_epoch)
    if not child_caps.issubset(parent_caps):
        raise ScopeWideningError(
            f"scope widening: child {sorted(child_caps)} not subset of "
            f"parent {sorted(parent_caps)} at epoch {pdp_epoch}"
        )


# Demonstrate the failure the syntactic check missed:
parent = Credential("invoice:read:*", resolution_epoch=40, delegation_depth=1, max_depth=2)
child = Credential("invoice:read:region=eu", resolution_epoch=40, delegation_depth=2, max_depth=2)

# Syntactic subset holds at epoch 40, but PDP now runs at epoch 41.
try:
    verify_attenuation(parent, child, pdp_epoch=41)
except ScopeWideningError as e:
    print(f"blocked: {e}")

# Re-pinning child to the PDP epoch exposes the actual widening.
child_v41 = Credential("invoice:read:region=eu", resolution_epoch=41, delegation_depth=2, max_depth=2)
parent_v41 = Credential("invoice:read:*", resolution_epoch=41, delegation_depth=1, max_depth=2)
try:
    verify_attenuation(parent_v41, child_v41, pdp_epoch=41)
except ScopeWideningError as e:
    raise ScopeWideningError(f"semantic widening detected: {e}") from e
