# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-delegated-credential-after-scope-attenuation-crosses-a-revocation-epoch-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-delegated-credential-after-scope-attenuation-crosses-a-revocation-epoch-boundary.warrant.json
# Markdown SHA-256:   949c9cde235928bfa770f524407e332857779309e442e5b3b90ab1d0d9677d26
# Code AST SHA-256:   616500bfa5b25bd8f2c7d5c9ebfac0e572a6484422dad652f1b2bf7db0edccfb
# Verified Classes:   StaleParentEpochError, Warrant, Registry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class StaleParentEpochError(RuntimeError):
    """Raised when a delegated warrant's parent epoch is behind the live registry epoch."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: str | None
    parent_epoch: int | None
    scope: FrozenSet[str]


@dataclass(frozen=True)
class Registry:
    current_epoch: dict[str, int]              # issuer/parent_id -> live epoch
    revoked_scope: dict[tuple[str, int], FrozenSet[str]]  # (parent_id, epoch) -> withdrawn caps


def verify_delegated(
    child: Warrant,
    parent: Warrant,
    registry: Registry,
) -> FrozenSet[str]:
    """Return the exercisable scope of `child`, or raise if authority continuity is broken.

    Structural subset is checked, then the epoch-continuity gate is applied.
    Exercisable scope is child.scope intersected with the parent's surviving
    authority across every epoch since the child was minted.
    """
    if not child.scope.issubset(parent.scope):
        raise StaleParentEpochError(
            f"scope escalation: {child.scope - parent.scope} not in parent"
        )

    if child.parent_epoch is None:
        raise StaleParentEpochError("child warrant lacks parent_epoch; cannot gate continuity")

    live_epoch = registry.current_epoch.get(child.parent_id or "")
    if live_epoch is None:
        raise StaleParentEpochError(f"unknown parent issuer {child.parent_id!r}")

    if child.parent_epoch == live_epoch:
        return child.scope

    # Parent authority moved after mint: intersect across the epoch delta.
    surviving = set(parent.scope)
    for e in range(child.parent_epoch + 1, live_epoch + 1):
        surviving -= registry.revoked_scope.get((child.parent_id, e), frozenset())

    exercisable = child.scope & surviving
    withdrawn = child.scope - exercisable
    if withdrawn:
        raise StaleParentEpochError(
            f"child {child.warrant_id} inherited {sorted(withdrawn)} "
            f"revoked between parent_epoch={child.parent_epoch} and live={live_epoch}"
        )
    return exercisable
