# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-warrant-mid-handoff-when-the-revocation-event-never-crosses-the-mesh-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-warrant-mid-handoff-when-the-revocation-event-never-crosses-the-mesh-boundary.warrant.json
# Markdown SHA-256:   c45669802f0d07341f65d3ad9271f031c6e6a42306bbe360813e9dbd9d15cdf1
# Code AST SHA-256:   fa3f9235678fd5fad08ef56af05cc02e3a1b8fb403cec4f5f94fbfb9f7da41d7
# Verified Classes:   StaleWarrantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleWarrantError(RuntimeError):
    """Raised when composed freshness evidence exceeds the verifier's tolerance."""
    pass


def verify_handoff_warrant(
    warrant: dict,
    attestation: dict,
    now: float,
    downstream_tolerance_s: float,
    issuer_query_fn,
) -> dict:
    """
    Verify a warrant arriving via a handoff. Accept only if the composed
    freshness bound (upstream residual staleness + transit time) is within
    the downstream verifier's tolerance. Otherwise force a synchronous
    re-check against the issuer.
    """
    if warrant.get("revoked", False):
        raise StaleWarrantError(
            f"warrant {warrant['id']} already marked revoked at receipt"
        )

    attested_at = attestation["verified_at"]
    residual_bound = attestation["residual_bound_s"]
    composed_age = (now - attested_at) + residual_bound

    if composed_age <= downstream_tolerance_s:
        return {"accepted": True, "path": "attested", "composed_age_s": composed_age}

    # Composed freshness exceeds tolerance: cannot trust upstream evidence.
    live = issuer_query_fn(warrant["id"])
    if not live:
        raise StaleWarrantError(
            f"warrant {warrant['id']} failed synchronous liveness re-check; "
            f"composed_age_s={composed_age:.1f} > tolerance={downstream_tolerance_s}"
        )
    return {"accepted": True, "path": "synchronous", "composed_age_s": 0.0}
