# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-task-and-invalidates-its-own-delegated-authorization-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-task-and-invalidates-its-own-delegated-authorization-chain.warrant.json
# Markdown SHA-256:   89e695e276d87d294c3fc22b5b3649b3345e5badde7193f032dfc62f2b7c05f9
# Code AST SHA-256:   ab9a318ec7b3e6e046a23d20c0d109600d1814a68afe6979035919364896af84
# Verified Classes:   DelegationBindingError, AttestationState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationBindingError(RuntimeError):
    """Raised when an instance's current attestation digest no longer matches
    the binding claim embedded in an outstanding delegated authorization token.
    This is a TERMINAL authority event, never a transient auth failure."""
    pass


class AttestationState:
    def __init__(self, digest: str):
        self.digest = digest
        self.reattesting = False


def present_token_for_call(token: dict, state: AttestationState) -> None:
    bound = token.get("sub_attestation_digest")
    if state.reattesting:
        # Barrier active: refuse to spend authority we know is being rotated.
        raise DelegationBindingError(
            f"call blocked: instance in REATTESTING state, token bound to {bound}"
        )
    if bound != state.digest:
        # Valid signature, stale binding — must escalate, must not retry.
        raise DelegationBindingError(
            f"binding_mismatch: token bound to {bound}, "
            f"current attestation {state.digest}; escalate to delegator for re-issuance"
        )


def reattest(state: AttestationState, new_digest: str, live_outbound_tokens: list[dict]) -> None:
    if live_outbound_tokens:
        # Enter the barrier instead of silently rotating under live authority.
        state.reattesting = True
        stale = {t["sub_attestation_digest"] for t in live_outbound_tokens}
        raise DelegationBindingError(
            f"re-attestation blocked: {len(live_outbound_tokens)} live DATs "
            f"bound to digests {stale}; drain, checkpoint, and escalate before rotating"
        )
    state.digest = new_digest
    state.reattesting = False
