# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegation-warrant-attenuation-breach-when-a-federated-peer-re-signs-a-capability-grant-under-a-different-policy-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegation-warrant-attenuation-breach-when-a-federated-peer-re-signs-a-capability-grant-under-a-different-policy-epoch.warrant.json
# Markdown SHA-256:   e391c09f24e96c2b94bc28b87caab0f12a797012e1399ebe917c31989d1e064b
# Code AST SHA-256:   636ee50e720a2fa321df0bde1872949bc25f5e3e7410e4241dbafb1a88be3501
# Verified Classes:   AttenuationEpochBreach, EpochLedger, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttenuationEpochBreach(RuntimeError):
    """Raised when a derived warrant's authority root has been revoked or
    superseded in the issuer's epoch ledger, even though the warrant's
    own signature chain remains cryptographically valid."""
    pass


@dataclass
class EpochLedger:
    # org_id -> set of revoked epoch ids, and the current (superseding) epoch
    revoked: dict[str, set[str]] = field(default_factory=dict)
    current: dict[str, str] = field(default_factory=dict)

    def is_authoritative(self, org_id: str, epoch: str) -> bool:
        if epoch in self.revoked.get(org_id, set()):
            return False
        # an epoch older than current is only authoritative if not revoked
        cur = self.current.get(org_id)
        if cur is not None and epoch != cur and epoch in self.revoked.get(org_id, set()):
            return False
        return True


@dataclass
class Warrant:
    warrant_id: str
    issuer_org: str
    signer_org: str
    signer_epoch: str          # epoch under which THIS warrant was signed
    parent_epoch: Optional[str]  # epoch under which the PARENT grant was evaluated
    parent_org: Optional[str]    # org that owns parent_epoch
    scope: str
    ttl_seconds: int
    parent: Optional["Warrant"] = None


def verify_derivation_chain(
    leaf: Warrant,
    ledger: EpochLedger,
    max_skew_seconds: int,
    now_elapsed: int,
) -> None:
    """Walk the attenuation chain and reject if any ancestor's authority
    root is revoked or superseded. Raises AttenuationEpochBreach on the
    first orphaned authority root encountered."""
    node = leaf
    depth = 0
    while node is not None:
        depth += 1
        if depth > 32:
            raise AttenuationEpochBreach(
                f"derivation chain depth {depth} exceeds bound; possible cycle"
            )
        if node.parent_epoch is not None and node.parent_org is not None:
            if not ledger.is_authoritative(node.parent_org, node.parent_epoch):
                raise AttenuationEpochBreach(
                    f"warrant {node.warrant_id}: parent_epoch "
                    f"{node.parent_org}:{node.parent_epoch} is revoked or "
                    f"superseded; signer_epoch {node.signer_org}:"
                    f"{node.signer_epoch} does not restore authority"
                )
            # effective lifetime is bounded by ancestor remaining life
            if node.ttl_seconds > (max_skew_seconds + now_elapsed):
                # signer extended TTL beyond ancestor's authority window
                if node.ttl_seconds > now_elapsed + max_skew_seconds:
                    raise AttenuationEpochBreach(
                        f"warrant {node.warrant_id}: ttl {node.ttl_seconds}s "
                        f"exceeds parent authority window "
                        f"({max_skew_seconds + now_elapsed}s); derived grant "
                        f"would outlive its authority source"
                    )
        node = node.parent


def handle_presentation(
    leaf: Warrant,
    ledger: EpochLedger,
    max_skew_seconds: int,
    now_elapsed: int,
) -> str:
    verify_derivation_chain(leaf, ledger, max_skew_seconds, now_elapsed)
    return f"granted:{leaf.scope}"
