# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-re-evaluated-authorization-decision-as-invalidating-an-in-flight-a2a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-re-evaluated-authorization-decision-as-invalidating-an-in-flight-a2a-handoff.warrant.json
# Markdown SHA-256:   7a575e1810ccd44744953ac41ef789036841b26dc1c0aab0b435fbc15a90919a
# Code AST SHA-256:   8a973a73a1de5e39088c56da0514fa97176b3595b205e6b89247f909b56d3922
# Verified Classes:   AuthorizationAttribution, BudgetResetLoopError, Warrant, Ledger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict


class AuthorizationAttribution(Enum):
    WARRANT_INVALID = "WARRANT_INVALID"        # revoked / expired / broken chain
    SESSION_OUT_OF_SCOPE = "SESSION_OUT_OF_SCOPE"  # aggregate drift, warrant still valid


class BudgetResetLoopError(RuntimeError):
    """Raised when a re-handshake would reset a warrant-scoped ledger keyed by session epoch."""


@dataclass
class Warrant:
    jti: str
    budget_tokens: int
    revoked: bool = False


@dataclass
class Ledger:
    # Keyed by warrant jti, NOT session epoch. Monotonic. Never reset by reconnect.
    consumed: Dict[str, int] = field(default_factory=dict)

    def remaining(self, jti: str, warrant: Warrant) -> int:
        return warrant.budget_tokens - self.consumed.get(jti, 0)

    def charge(self, jti: str, cost: int) -> None:
        self.consumed[jti] = self.consumed.get(jti, 0) + cost


def admit(ledger: Ledger, warrant: Warrant, requested_cost: int, epoch: int) -> int:
    """Admission gate. Must consult the jti-keyed ledger, never a per-epoch counter."""
    if warrant.revoked:
        raise BudgetResetLoopError(
            f"admission denied: warrant {warrant.jti} revoked; obtain new jti"
        )
    if ledger.remaining(warrant.jti, warrant) < requested_cost:
        # This is the guard that breaks the budget-reset loop.
        raise BudgetResetLoopError(
            f"admission denied: jti {warrant.jti} has "
            f"{ledger.remaining(warrant.jti, warrant)} tokens remaining, "
            f"requested {requested_cost}; re-handshake cannot reset ledger"
        )
    return epoch


def ca_tick(ledger: Ledger, warrant: Warrant, epoch: int) -> AuthorizationAttribution:
    """Continuous authorization. Returns attribution, not a bare boolean."""
    if warrant.revoked:
        return AuthorizationAttribution.WARRANT_INVALID
    if ledger.remaining(warrant.jti, warrant) < 0:
        return AuthorizationAttribution.SESSION_OUT_OF_SCOPE
    return AuthorizationAttribution.SESSION_OUT_OF_SCOPE  # placeholder; caller inspects remaining


def handle_deny(ledger: Ledger, warrant: Warrant, attribution: AuthorizationAttribution,
                next_epoch: int, requested_cost: int) -> int:
    """Remediation must branch on attribution. Re-handshake is legal only for SCOPE denies,
    and only against remaining headroom."""
    if attribution is AuthorizationAttribution.WARRANT_INVALID:
        raise BudgetResetLoopError(
            f"warrant {warrant.jti} invalid; session must terminate and caller must "
            f"request a new jti from the issuer"
        )
    if attribution is AuthorizationAttribution.SESSION_OUT_OF_SCOPE:
        # Legal successor session, but inherits the jti ledger.
        return admit(ledger, warrant, requested_cost, next_epoch)
    raise BudgetResetLoopError(f"unhandled attribution {attribution}")


# --- Reproduce the loop and show the guard breaking it ---
w = Warrant(jti="jti-7f3a", budget_tokens=200_000)
led = Ledger()
led.charge(w.jti, 200_050)  # session epoch=1 exhausted the budget

try:
    # Caller receives SCOPE_EXHAUSTED, retries with same warrant, fresh epoch.
    handle_deny(led, w, AuthorizationAttribution.SESSION_OUT_OF_SCOPE,
                next_epoch=2, requested_cost=500)
except BudgetResetLoopError as e:
    print(f"loop broken: {e}")
