# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-its-own-rotated-credential-mid-session-under-aaif-continuous-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-its-own-rotated-credential-mid-session-under-aaif-continuous-authorization.warrant.json
# Markdown SHA-256:   ae75ee4c7f7a80b8dd35fa5bbec6f3c52e15e496100a43aa71764ae6a129847e
# Code AST SHA-256:   c765df88b33359283fe10a5e3e8f69096f55588207b724f68d6678d703620ef8
# Verified Classes:   StaleCredentialEpochError, Credential, Decision, SessionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleCredentialEpochError(RuntimeError):
    """Raised when a privileged action is attempted with an authorization
    decision derived from a superseded credential epoch."""


@dataclass
class Credential:
    token: str
    epoch: int
    scopes: frozenset
    expires_at: float


@dataclass
class Decision:
    work_order_id: str
    epoch: int
    scopes: frozenset
    expires_at: float


@dataclass
class SessionState:
    current: Credential
    decisions: dict = field(default_factory=dict)  # key: work_order_id -> Decision

    def rotate(self, new_cred: Credential) -> None:
        # Epoch must strictly increase; rotation is revoke-then-issue.
        if new_cred.epoch <= self.current.epoch:
            raise StaleCredentialEpochError(
                f"rotation epoch {new_cred.epoch} not greater than "
                f"current {self.current.epoch}"
            )
        superseded = self.current.epoch
        self.current = new_cred
        # Atomic-with-swap invalidation: drop every decision from the old epoch.
        for wo_id in list(self.decisions):
            if self.decisions[wo_id].epoch <= superseded:
                del self.decisions[wo_id]

    def authorize(self, work_order_id: str, required_scope: str, now: float) -> Decision:
        decision = self.decisions.get(work_order_id)
        if decision is not None and decision.epoch != self.current.epoch:
            # Fail closed: never serve a decision from a superseded epoch.
            raise StaleCredentialEpochError(
                f"decision for {work_order_id} derived under epoch "
                f"{decision.epoch}, current epoch is {self.current.epoch}"
            )
        if decision is None or decision.expires_at <= now:
            # Re-derive scope from the LIVE credential, not a work-order manifest.
            decision = Decision(
                work_order_id=work_order_id,
                epoch=self.current.epoch,
                scopes=self.current.scopes,
                expires_at=self.current.expires_at,
            )
            self.decisions[work_order_id] = decision
        if required_scope not in decision.scopes:
            raise StaleCredentialEpochError(
                f"scope {required_scope!r} absent from current epoch "
                f"{self.current.epoch}; decision may be stale"
            )
        return decision


def perform_privileged_action(state: SessionState, work_order_id: str,
                              scope: str, now: float) -> str:
    try:
        state.authorize(work_order_id, scope, now)
    except StaleCredentialEpochError:
        # Do not retry against a policy decision; surface for re-derivation.
        raise
    return f"executed {scope} under epoch {state.current.epoch}"
