# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-a2a-warrant-whose-revocation-epoch-lags-its-own-the-revocation-propagation-skew-boundary-in-federated-capabil.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-a2a-warrant-whose-revocation-epoch-lags-its-own-the-revocation-propagation-skew-boundary-in-federated-capabil.warrant.json
# Markdown SHA-256:   f930e8492f62c2fac2ee467e58df7c124b111fc803218d0d9f4cbc99b1afdeb3
# Code AST SHA-256:   ab1f0fb3254f6657c0494b3856d3a4f026b7aac5f48f71b4cfc266dd95508d66
# Verified Classes:   StaleRevocationWatermarkError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleRevocationWatermarkError(RuntimeError):
    """Raised when a delegated warrant cannot be proven live against the issuer's current revocation epoch."""
    pass


def authorize_delegated_warrant(
    warrant,
    local_watermark: int,
    publish_delay_bound: int,
    fetch_fresh_watermark,
    revocation_set,
    now: float,
) -> bool:
    """
    Enforce the federation revocation-skew invariant before executing a delegated warrant.
    Returns True only if the warrant is provably live as of a watermark >= mint_epoch + publish_delay_bound.
    """
    if not warrant.verify_signature():
        raise StaleRevocationWatermarkError(f"warrant {warrant.id}: signature invalid")
    if now > warrant.expiry:
        raise StaleRevocationWatermarkError(f"warrant {warrant.id}: expired at {warrant.expiry}")

    required_epoch = warrant.mint_epoch + publish_delay_bound

    if local_watermark < required_epoch:
        # Liveness unknown: local watermark cannot prove the warrant is not revoked.
        fresh = fetch_fresh_watermark(warrant.issuer)
        if fresh is None:
            # Fail-closed: a failed freshness fetch is NOT evidence of liveness.
            raise StaleRevocationWatermarkError(
                f"warrant {warrant.id}: freshness fetch failed; refusing to execute on stale watermark "
                f"(local={local_watermark}, required>={required_epoch})"
            )
        if fresh < required_epoch:
            raise StaleRevocationWatermarkError(
                f"warrant {warrant.id}: issuer watermark still stale after refresh "
                f"(fresh={fresh}, required>={required_epoch})"
            )
        local_watermark = fresh

    if warrant.id in revocation_set(local_watermark):
        raise StaleRevocationWatermarkError(
            f"warrant {warrant.id}: revoked at issuer epoch {local_watermark}"
        )

    # Execution record must capture the liveness triple for post-hoc audit.
    warrant.audit_record = {
        "watermark_used": local_watermark,
        "mint_epoch": warrant.mint_epoch,
        "publish_delay_bound": publish_delay_bound,
        "liveness_proven": local_watermark >= required_epoch,
    }
    return True
