# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federation-trust-tier-downgrade-as-a-capability-revocation-rather-than-a-transient-routing-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federation-trust-tier-downgrade-as-a-capability-revocation-rather-than-a-transient-routing-failure.warrant.json
# Markdown SHA-256:   a4a4bf7648338d42bfbb2ff719c065b577aa4dda78b948f417e39a29224d70de
# Code AST SHA-256:   53006cc4dbab55e9c47f48f6d9bbb58b487da1e8289dfe5382289e95e2ea0109
# Verified Classes:   TrustTierDowngradeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TrustTierDowngradeError(RuntimeError):
    """Raised when a remote PML rejection proves a capability was revoked by tier downgrade."""
    pass


TRANSIENT_RETRYABLE = {"timeout", "unavailable", "overloaded"}


def classify_federation_rejection(rejection: dict, cached_tier: str, capability: str) -> str:
    """
    Returns one of: "revoked", "ambiguous", "provider_inconsistency".
    Raises TrustTierDowngradeError when the rejection is a structured, signed
    tier delta proving the capability is no longer authorized.
    """
    granted = rejection.get("granted")
    required = rejection.get("required")
    signed = rejection.get("pml_signature") is not None

    # Structured, signed tier delta => terminal revocation, not a transport fault.
    if signed and granted is not None and required is not None and granted < required:
        raise TrustTierDowngradeError(
            f"capability {capability!r} revoked: granted={granted} required={required} "
            f"cached_tier={cached_tier}; do not retry, invalidate manifest entry"
        )

    # Unsigned or generic rejection: ambiguous, single re-discovery only.
    if not signed or rejection.get("error") in TRANSIENT_RETRYABLE:
        return "ambiguous"

    # Signed, tier sufficient, yet still failing => provider-side manifest/cache skew.
    if signed and granted is not None and required is not None and granted >= required:
        return "provider_inconsistency"

    return "ambiguous"


def execute_federated_call(call_fn, rejection_parser, cached_tier, capability):
    try:
        return call_fn()
    except Exception as exc:
        rejection = rejection_parser(exc)
        verdict = classify_federation_rejection(rejection, cached_tier, capability)
        if verdict == "ambiguous":
            # exactly one re-discovery, never a blind retry loop
            return call_fn(rediscover=True)
        if verdict == "provider_inconsistency":
            raise TrustTierDowngradeError(
                f"provider skew on {capability!r}: manifest advertises tier but call fails"
            )
        raise
