# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-revoke-a-taint-propagating-capability-token-mid-plan-the-stale-warrant-join-failure-in-least-privilege-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-revoke-a-taint-propagating-capability-token-mid-plan-the-stale-warrant-join-failure-in-least-privilege-tool-invocation.warrant.json
# Markdown SHA-256:   3f40ab59ddf981403fbbc67b48216e611b8fdc6c0a8ad91774bb60490d81ba12
# Code AST SHA-256:   7b7f15e7501b3e2e3679ac6e6b0bc7c06cace2d0492025702f3ac18b9d5d3afa
# Verified Classes:   StaleWarrantError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class StaleWarrantError(RuntimeError):
    """Raised when a capability token is redeemed against a payload whose
    taint exceeds the token's minted taint, with no sanctioned downgrade."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    scope: str
    taint: FrozenSet[str]
    payload_hash: str
    signature: str


def redeem(
    token: CapabilityToken,
    scope: str,
    payload: bytes,
    payload_taint: FrozenSet[str],
    payload_hash: str,
    downgradable: FrozenSet[str] = frozenset(),
) -> None:
    # Identity and scope are the cheap checks; they are necessary, not sufficient.
    if token.scope != scope:
        raise StaleWarrantError(
            f"scope mismatch: token={token.scope!r} call={scope!r}"
        )
    if token.payload_hash != payload_hash:
        # Token was bound to a different payload than the one being written.
        raise StaleWarrantError(
            f"payload hash mismatch for token {token.token_id}"
        )

    excess = payload_taint - token.taint
    if not excess:
        return  # warrant is fresh; execute

    # Excess labels exist. Only a runtime-sanctioned downgrade may proceed,
    # and only by re-minting, never by widening the existing token in place.
    if excess <= downgradable:
        raise StaleWarrantError(
            f"token {token.token_id} requires re-mint for downgradable "
            f"labels {sorted(excess)}; in-place widening is forbidden"
        )

    # Non-downgradable taint: the warrant is stale. Revoke, do not execute.
    raise StaleWarrantError(
        f"revoking token {token.token_id}: payload carries non-downgradable "
        f"taint {sorted(excess)} beyond minted taint {sorted(token.taint)}"
    )
