# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-verify-a-delegated-authorization-warrant-after-a-policy-bound-capability-exchange-rather-than-trusting-the-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-verify-a-delegated-authorization-warrant-after-a-policy-bound-capability-exchange-rather-than-trusting-the-cache.warrant.json
# Markdown SHA-256:   24ec3e11fc08a3f8073e688f118d14542aff17156a0d8b470103ca9e9afc4cd2
# Code AST SHA-256:   dafdecb3546bf4a0dce18ea3cc67cfbc391c5b62104855b7d9316fff4fcdeaec
# Verified Classes:   StaleWarrantError, WarrantLink, CachedGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a cached post-exchange grant is presented past a boundary
    it cannot soundly cover without re-verifying the live warrant chain."""
    pass


@dataclass
class WarrantLink:
    issuer: str
    subject: str
    constraints: dict
    expires_at: float
    signature: str
    predicate_owner: str  # org that owns the mutable predicate


@dataclass
class CachedGrant:
    capability: str
    chain: list  # list[WarrantLink]
    exchanged_at: float
    max_clock_skew: float = 0.0
    re_delegable: bool = False


def effective_expiry(chain: list) -> float:
    # The most restrictive upstream expiry governs the whole chain.
    return min(link.expires_at for link in chain)


def crosses_unobservable_boundary(grant: CachedGrant, holder_org: str,
                                  op_duration: float, now: float) -> bool:
    if grant.re_delegable:
        return True  # re-delegation always requires fresh attenuation
    for link in grant.chain:
        if link.predicate_owner != holder_org:
            return True  # holder cannot observe that org's policy mutations
    remaining = effective_expiry(grant.chain) - now
    if remaining < grant.max_clock_skew + op_duration:
        return True  # op could complete after upstream lapse
    return False


def reverify_or_refuse(grant: CachedGrant, holder_org: str,
                       op_duration: float, now: Optional[float] = None,
                       live_predicate_check=None) -> None:
    now = time.time() if now is None else now

    # 1. Chain must be self-contained and linkable.
    if not grant.chain:
        raise StaleWarrantError(
            f"grant for {grant.capability!r} carries no warrant chain; "
            "cannot re-derive authority")

    # 2. Hard expiry against the most restrictive upstream link.
    if now >= effective_expiry(grant.chain):
        raise StaleWarrantError(
            f"grant for {grant.capability!r} expired upstream at "
            f"{effective_expiry(grant.chain)}; now={now}")

    # 3. Boundary crossing forces live re-verification.
    if crosses_unobservable_boundary(grant, holder_org, op_duration, now):
        if live_predicate_check is None:
            raise StaleWarrantError(
                f"grant for {grant.capability!r} crosses an unobservable "
                "policy/time boundary but no live predicate check was supplied; "
                "refusing to reuse cached conclusion")
        for link in grant.chain:
            if not live_predicate_check(link):
                raise StaleWarrantError(
                    f"live predicate for {link.predicate_owner} no longer "
                    f"satisfies constraints {link.constraints!r}; "
                    "cached grant is stale")


# Example trigger: B reuses an exchanged sub-grant across a batch while C's
# jurisdiction predicate has tightened, and B has no live check wired in.
if __name__ == "__main__":
    chain = [
        WarrantLink("orgX/billing", "orgY/recon", {"customer_id": "S"},
                    expires_at=time.time() + 3600, signature="sigA",
                    predicate_owner="orgX"),
        WarrantLink("orgZ/policy", "orgY/recon", {"jurisdiction": "EU"},
                    expires_at=time.time() + 3600, signature="sigC",
                    predicate_owner="orgZ"),
    ]
    grant = CachedGrant("convert:currency", chain, exchanged_at=time.time())
    try:
        reverify_or_refuse(grant, holder_org="orgY", op_duration=120.0)
    except StaleWarrantError as e:
        print("REFUSED:", e)
