# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-survive-credential-rotation-when-its-own-revocation-is-in-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-survive-credential-rotation-when-its-own-revocation-is-in-flight.warrant.json
# Markdown SHA-256:   77939b479949a41a03cb1e71f65665f86c41cf4d531f43ec273f6c3ed9ac4fef
# Code AST SHA-256:   e7f3850a18ba2c513674f7f7ed1de915c5bc6278f3ffa96e16e6d26c95edf8b0
# Verified Classes:   RotationCommitError, InFlightOp, RotationState, RotationController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class RotationCommitError(RuntimeError):
    """Raised when a credential rotation cannot be committed safely."""
    pass


@dataclass
class InFlightOp:
    op_id: str
    warrant_id: str
    dispatched_at: float
    deadline: float


@dataclass
class RotationState:
    current_warrant: str
    new_warrant: Optional[str] = None
    phase: str = "STEADY"  # STEADY | DRAINING | ROTATED | RESUMED
    inflight: Dict[str, InFlightOp] = field(default_factory=dict)


class RotationController:
    def __init__(self, verifier_poll_interval: float, clock_skew_margin: float):
        self.poll = verifier_poll_interval
        self.skew = clock_skew_margin

    def max_inflight_latency(self, state: RotationState, now: float) -> float:
        if not state.inflight:
            return 0.0
        return max(op.deadline - now for op in state.inflight.values())

    def begin_rotation(self, state: RotationState, new_warrant: str,
                       t_rev: float, now: float) -> str:
        """Decide drain vs hand-forward. Returns the chosen phase."""
        state.new_warrant = new_warrant
        horizon = self.max_inflight_latency(state, now)
        safe_hand_forward = (now + horizon) < (t_rev - self.poll - self.skew)
        if safe_hand_forward:
            state.current_warrant = new_warrant
            state.phase = "ROTATED"
            return "hand_forward"
        state.phase = "DRAINING"
        return "drain"

    def dispatch(self, state: RotationState, op_id: str, now: float,
                 latency_bound: float) -> None:
        """Any dispatch during ROTATED with unresolved DRAINING ops is illegal."""
        if state.phase == "ROTATED" and state.inflight:
            unresolved = list(state.inflight.keys())
            raise RotationCommitError(
                f"dispatch of {op_id} under {state.current_warrant} while "
                f"DRAINING ops unresolved: {unresolved}; rotation is not "
                f"committed and retries will duplicate side effects"
            )
        state.inflight[op_id] = InFlightOp(
            op_id=op_id,
            warrant_id=state.current_warrant,
            dispatched_at=now,
            deadline=now + latency_bound,
        )

    def on_audit_rejection(self, state: RotationState, op_id: str,
                           rejected_warrant: str) -> str:
        """Audit-time rejection of an applied effect must never be retried."""
        op = state.inflight.get(op_id)
        if op is None:
            raise RotationCommitError(
                f"audit rejection for unknown op {op_id}; cannot attribute "
                f"to a warrant, refusing to retry"
            )
        if rejected_warrant != state.current_warrant and op.warrant_id == rejected_warrant:
            # The effect was applied under a now-revoked warrant.
            state.phase = "ROTATION_UNSAFE"
            return "escalate_reconciliation"
        raise RotationCommitError(
            f"unexpected rejection ordering for {op_id}: rejected={rejected_warrant} "
            f"current={state.current_warrant}"
        )

    def complete(self, state: RotationState, op_id: str) -> None:
        state.inflight.pop(op_id, None)
        if state.phase == "DRAINING" and not state.inflight:
            state.current_warrant = state.new_warrant
            state.phase = "RESUMED"
