# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-whose-revocation-proof-is-older-than-its-own-lease-and-why-depth-bounded-attenuation-cannot-answe.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-whose-revocation-proof-is-older-than-its-own-lease-and-why-depth-bounded-attenuation-cannot-answe.warrant.json
# Markdown SHA-256:   2d530fe2ac927b941a7e60df5acffc90718ea2c8e0683a30bc26e436cfb89c82
# Code AST SHA-256:   b36528fdc51341f69fbf03cdf027a48389fc758e91b915afd7cc690bf587947c
# Verified Classes:   UnbackedLeaseError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class UnbackedLeaseError(RuntimeError):
    """Raised when a lease would outlive the revocation horizon of its backing warrant."""
    pass


@dataclass
class Warrant:
    issuer: str
    revocation_epoch: float          # logical time up to which issuer confirms no revocation
    propagation_bound: float         # max time for revocation to reach holders
    not_after: float                 # warrant's own expiry

    def horizon(self) -> float:
        # Latest instant a lease may remain valid and still be backed by live knowledge.
        return min(self.revocation_epoch + self.propagation_bound, self.not_after)


def issue_lease(
    chain: list[Warrant],
    requested_not_after: float,
    clock_skew_margin: float,
    now: float,
) -> float:
    """Issue a lease only if it fits inside the weakest warrant's revocation horizon."""
    if not chain:
        raise UnbackedLeaseError("cannot issue lease against empty delegation chain")

    # Weakest link: the earliest horizon across the whole chain.
    weakest = min(w.horizon() for w in chain)
    safe_horizon = weakest - clock_skew_margin

    if requested_not_after > safe_horizon:
        raise UnbackedLeaseError(
            f"lease not_after={requested_not_after:.1f} exceeds backed horizon "
            f"{safe_horizon:.1f} (weakest warrant horizon {weakest:.1f}, "
            f"skew margin {clock_skew_margin:.1f}); refusing unbacked lease"
        )

    # Lease is backed for its entire lifetime.
    return requested_not_after


def cascade_invalidate(inbound_warrant: Warrant, lease_ledger: dict[str, float]) -> list[str]:
    """On warrant invalidation, revoke every lease whose horizon depended on it."""
    revoked = []
    horizon = inbound_warrant.horizon()
    for lease_id, lease_not_after in list(lease_ledger.items()):
        if lease_not_after > horizon:
            del lease_ledger[lease_id]
            revoked.append(lease_id)
    if not revoked:
        # No dangling sub-tree — but assert we actually walked the ledger.
        raise UnbackedLeaseError(
            "invalidation walked ledger but found no dependent leases; "
            "verify lease ledger is not detached from warrant graph"
        )
    return revoked


if __name__ == "__main__":
    now = time.time()
    root = Warrant("orchestrator", revocation_epoch=now, propagation_bound=30.0, not_after=now + 300)
    mid = Warrant("worker", revocation_epoch=now, propagation_bound=30.0, not_after=now + 290)

    # Legal: fits inside horizon.
    issue_lease([root, mid], requested_not_after=now + 20, clock_skew_margin=2.0, now=now)

    # Illegal: outlives the revocation horizon -> must refuse.
    issue_lease([root, mid], requested_not_after=now + 280, clock_skew_margin=2.0, now=now)
