# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-halt-on-a-revoked-aaif-trust-anchor-rather-than-rotate-and-continue.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-halt-on-a-revoked-aaif-trust-anchor-rather-than-rotate-and-continue.warrant.json
# Markdown SHA-256:   c060a437550646f8d20b8523a929dacd082a081cff9fd0afcefba61a01e4686a
# Code AST SHA-256:   f8d057477dc7b4b1499f417b813c42bf9f7ad238f2712a78894d7c74ea2c8d6d
# Verified Classes:   RevokedAnchorRotationError, RCLUnavailableError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RevokedAnchorRotationError(RuntimeError):
    """Raised when a rotation is attempted against an anchor that the
    federation RCL marks as revoked, or when the RCL cannot be consulted.
    This is terminal for the instance's federated identity: the instance
    must halt and escalate, not rotate and resume."""
    pass


class RCLUnavailableError(RevokedAnchorRotationError):
    """The RCL could not be refreshed within the propagation SLA.
    Treated as anchor-untrusted (fail-closed) for rotation purposes."""
    pass


def rotate_credential(anchor_uri: str, instance_id: str, rcl_client, anchor_client) -> str:
    # Step 1: mandatory RCL refresh BEFORE any rotation call.
    try:
        rcl = rcl_client.fetch(anchor_uri, timeout_s=30)
    except TimeoutError as exc:
        # Fail-closed: no RCL means no evidence the anchor is trusted.
        raise RCLUnavailableError(
            f"RCL refresh timed out for anchor {anchor_uri}; refusing to rotate "
            f"instance {instance_id} without current trust status"
        ) from exc

    # Step 2: check anchor trust status.
    if rcl.status_of(anchor_uri) == "revoked":
        raise RevokedAnchorRotationError(
            f"Anchor {anchor_uri} is revoked in RCL version {rcl.version} "
            f"(revoked_at={rcl.revoked_at(anchor_uri)}); instance {instance_id} "
            f"must halt and escalate, not rotate"
        )

    # Step 3: only now is rotation safe.
    return anchor_client.issue_leaf(anchor_uri, instance_id)


def on_warrant_rejection(error_class: str, anchor_uri: str, instance_id: str, rcl_client, anchor_client) -> str:
    if error_class == "WARRANT_LEAF_EXPIRED":
        return rotate_credential(anchor_uri, instance_id, rcl_client, anchor_client)
    if error_class == "WARRANT_ANCHOR_UNTRUSTED":
        # Never recoverable via rotation; halt regardless of RCL state.
        raise RevokedAnchorRotationError(
            f"Peer reported anchor {anchor_uri} untrusted for instance "
            f"{instance_id}; halting federated identity"
        )
    # Transport errors: retry, do not rotate.
    raise RuntimeError(f"transient error {error_class}; retry with backoff")
