# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-its-own-warrant-when-a-long-lived-session-outlives-a-credential-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-its-own-warrant-when-a-long-lived-session-outlives-a-credential-rotation.warrant.json
# Markdown SHA-256:   81eed5177f8e095e0f04cf1bb327ce30640859426c75dd4fc550d2cf9e7f57cf
# Code AST SHA-256:   f21bcef5c3dcdeda21774683ff891d43543cfa62220999500470500f2a39821f
# Verified Classes:   WarrantScopeInvalidated, Warrant, PlanStep, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantScopeInvalidated(RuntimeError):
    """Raised when a live plan requires a scope removed by credential rotation.

    This is a terminal condition for the current plan branch, NOT a retryable
    transport fault. Retrying a scope-denied call is a boundary violation.
    """
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    scopes: FrozenSet[str]
    digest: str


@dataclass
class PlanStep:
    name: str
    required_scope: str


@dataclass
class Session:
    in_context_warrant: Warrant
    remaining_plan: list[PlanStep] = field(default_factory=list)


def apply_rotation(session: Session, new_warrant: Warrant) -> None:
    """Re-derive authority from the live warrant at a plan-revision boundary.

    Must be called on every rotation event BEFORE enforcement takes effect.
    Rejects the rotation if any remaining step requires a removed scope.
    """
    old = session.in_context_warrant
    removed = old.scopes - new_warrant.scopes

    if not removed:
        # Contained: rotation widened or neutral. Update belief, continue.
        session.in_context_warrant = new_warrant
        return

    # Constrained vs Invalidated: check every remaining step against removed scopes.
    offending = [
        step for step in session.remaining_plan
        if step.required_scope in removed
    ]
    if offending:
        # Do NOT retry. Halt, checkpoint, request re-plan.
        raise WarrantScopeInvalidated(
            f"rotation {old.warrant_id}->{new_warrant.warrant_id} removed "
            f"{sorted(removed)}; remaining steps "
            f"{[s.name for s in offending]} require removed scope. "
            f"Plan invalidated; checkpoint and re-plan from live warrant."
        )

    # Constrained: remaining plan fits, but removed scopes must stay forbidden
    # so fallbacks cannot re-introduce them via scope-valid payload smuggling.
    session.in_context_warrant = new_warrant
    session.remaining_plan = [
        s for s in session.remaining_plan if s.required_scope in new_warrant.scopes
    ]


def execute_step(session: Session, step: PlanStep) -> str:
    """Execute one step, re-checking scope against the LIVE warrant, not t0 belief."""
    live = session.in_context_warrant
    if step.required_scope not in live.scopes:
        # Terminal for this branch. Never classify as retryable.
        raise WarrantScopeInvalidated(
            f"step {step.name!r} requires {step.required_scope!r} "
            f"not in live warrant {live.warrant_id} ({sorted(live.scopes)}). "
            f"Refusing to retry or route around."
        )
    return f"executed:{step.name}"
