# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-sign-a-delegated-capability-token-after-an-upstream-warrant-has-been-revoked-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-sign-a-delegated-capability-token-after-an-upstream-warrant-has-been-revoked-mid-chain.warrant.json
# Markdown SHA-256:   cd806a50bf2d978bc7498e3c46dc65e6c140e1da2b3dc8c58e0fb5b3540481ae
# Code AST SHA-256:   a9aada49f47522d362ea9d5be47e092ef6555fd5a3740e5ca18c1bd3b1b0b50e
# Verified Classes:   DelegationAncestryUnverifiable, Warrant, RevocationView
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationAncestryUnverifiable(RuntimeError):
    """Raised when a re-delegator cannot prove its ancestry is live at mint time."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    scope: frozenset
    expires_at: float          # epoch seconds
    revocation_epoch: int      # epoch of the root's revocation feed this was minted against
    parent_id: Optional[str]   # None for root warrants


@dataclass
class RevocationView:
    root_epoch: int            # highest revocation epoch the feed has delivered
    dead: frozenset            # warrant_ids known revoked
    feed_age_seconds: float    # staleness of the feed


FRESHNESS_BOUND_SECONDS = 5.0


def re_sign_downstream(
    own: Warrant,
    parent: Optional[Warrant],
    view: RevocationView,
    requested_scope: frozenset,
    requested_expiry: float,
    now: float,
) -> Warrant:
    # 1. Own warrant must be live in the view.
    if own.warrant_id in view.dead:
        raise DelegationAncestryUnverifiable(
            f"own warrant {own.warrant_id} is revoked; refusing to re-sign"
        )

    # 2. Revocation feed must be fresh enough to trust liveness.
    if view.feed_age_seconds > FRESHNESS_BOUND_SECONDS:
        raise DelegationAncestryUnverifiable(
            f"revocation feed stale ({view.feed_age_seconds:.1f}s > "
            f"{FRESHNESS_BOUND_SECONDS}s); ancestor liveness unknown"
        )

    # 3. Own warrant's minted epoch must match the root's current epoch.
    if own.revocation_epoch < view.root_epoch:
        raise DelegationAncestryUnverifiable(
            f"own warrant minted at epoch {own.revocation_epoch} < root "
            f"epoch {view.root_epoch}; ancestry not proven live"
        )

    # 4. Every ancestor in the proof must be live and epoch-current.
    if parent is not None:
        if parent.warrant_id in view.dead:
            raise DelegationAncestryUnverifiable(
                f"ancestor {parent.warrant_id} revoked; refusing to re-sign"
            )
        if parent.revocation_epoch < view.root_epoch:
            raise DelegationAncestryUnverifiable(
                f"ancestor {parent.warrant_id} epoch {parent.revocation_epoch} "
                f"< root {view.root_epoch}"
            )

    # 5. Scope must attenuate, never widen.
    if not requested_scope.issubset(own.scope):
        raise DelegationAncestryUnverifiable(
            f"requested scope {requested_scope} not subset of {own.scope}"
        )

    # 6. New expiry must not outlive any ancestor (orphan-in-waiting guard).
    ceiling = own.expires_at
    if parent is not None:
        ceiling = min(ceiling, parent.expires_at)
    if requested_expiry > ceiling:
        raise DelegationAncestryUnverifiable(
            f"requested expiry {requested_expiry} exceeds ancestor ceiling {ceiling}"
        )

    return Warrant(
        warrant_id=f"re-mint-{own.warrant_id}-{int(now)}",
        issuer=own.subject,
        subject="downstream",
        scope=requested_scope,
        expires_at=requested_expiry,
        revocation_epoch=view.root_epoch,
        parent_id=own.warrant_id,
    )
