# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegation-chain-credential-rotation-as-a-transactional-boundary-rather-than-a-stateless-token-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegation-chain-credential-rotation-as-a-transactional-boundary-rather-than-a-stateless-token-swap.warrant.json
# Markdown SHA-256:   4a9fc69a48ae89df2f37b2d04ee5add6ea26846b8a5849e28992f2399fadbd6f
# Code AST SHA-256:   66b523fb95a6cbe8136b1cee072e73172338c6abd28bbcd0be93736142df93a2
# Verified Classes:   RotationChainInvariantError, Warrant, RotationRequest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RotationChainInvariantError(RuntimeError):
    """Raised when a credential rotation would break delegation-chain continuity."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    delegator_key_thumbprint: str
    delegate_key_thumbprint: str
    depth_budget: int
    issued_at: float
    expires_at: float


@dataclass
class RotationRequest:
    instance_id: str
    old_key: str
    new_key: str
    now: float
    live_child_warrants: list[Warrant]
    max_inflight_tool_call_seconds: float
    checkpoint_granularity_seconds: float


def plan_rotation(req: RotationRequest) -> dict:
    """
    Decide whether a stateless swap is safe or a transactional rotation is required.
    Enforces the chain-continuity invariant: no live warrant may be orphaned by
    revoking a key it still embeds, and checkpoint granularity must be finer than
    the shortest unit of work a re-verification can invalidate.
    """
    if not req.live_child_warrants:
        # Leaf or drained: stateless swap is safe.
        return {"mode": "stateless_swap", "revoke_old_immediately": True}

    # Mid-chain delegator with live children: transactional rotation required.
    if req.checkpoint_granularity_seconds > req.max_inflight_tool_call_seconds:
        raise RotationChainInvariantError(
            f"instance {req.instance_id}: checkpoint granularity "
            f"({req.checkpoint_granularity_seconds}s) is coarser than max in-flight "
            f"tool-call duration ({req.max_inflight_tool_call_seconds}s); rotation "
            f"would discard non-replayable work on abort. Tighten checkpoints first."
        )

    orphaned = [
        w for w in req.live_child_warrants
        if w.delegate_key_thumbprint == req.old_key and w.expires_at > req.now
    ]
    if orphaned:
        overlap = max(
            (w.expires_at - req.now for w in orphaned), default=0.0
        ) + req.max_inflight_tool_call_seconds
        return {
            "mode": "transactional_rotation",
            "revoke_old_immediately": False,
            "reissue_warrants": [w.warrant_id for w in orphaned],
            "dual_validity_until": req.now + overlap,
            "deferred_revocation_at": req.now + overlap,
            "atomic_publish_required": True,
        }

    # Live children exist but none embed the old key: safe to revoke now.
    return {"mode": "stateless_swap", "revoke_old_immediately": True}
