# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-authorization-mid-task-when-a-delegated-aaif-credential-expires-between-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-authorization-mid-task-when-a-delegated-aaif-credential-expires-between-tool-calls.warrant.json
# Markdown SHA-256:   2ff6d364c1446e8e3b84493ea10f9abc0fc56b61281982501a67792f740b0065
# Code AST SHA-256:   b68676d2fa40bffcd6bbd68166a3292d378bf78b29b11179a9ab953b86c4968a
# Verified Classes:   AAIFProvenanceError, Credential, SideEffect
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AAIFProvenanceError(RuntimeError):
    """Raised when a side effect would be committed under a credential chain
    that cannot be reconstructed at verification time."""


@dataclass(frozen=True)
class Credential:
    nonce: str
    issued_at: float
    ttl: float
    chain_root_hash: str
    scope: frozenset

    def is_live(self, now: float) -> bool:
        return now < self.issued_at + self.ttl


@dataclass(frozen=True)
class SideEffect:
    step: str
    idempotency_key: str
    reversible: bool


def assert_provenance_checkpoint(
    cred: Credential,
    live_chain_hash: str,
    effect: SideEffect,
    now: float,
) -> None:
    """Guard invoked immediately before any irreversible side effect.

    Enforces two invariants:
      1. The credential's chain root must still be recognized by the
         authorization service (no upstream re-signing orphaned it).
      2. The idempotency key must be task-derived, not credential-derived,
         so a retry under a refreshed credential is recognized as the same
         logical action rather than a new one.
    """
    if not cred.is_live(now):
        raise AAIFProvenanceError(
            f"credential {cred.nonce} expired before step {effect.step!r}; "
            "refusing to begin irreversible effect under a dead warrant"
        )
    if cred.chain_root_hash != live_chain_hash:
        raise AAIFProvenanceError(
            f"chain provenance mismatch at step {effect.step!r}: "
            f"credential root {cred.chain_root_hash!r} is not an ancestor of "
            f"live chain {live_chain_hash!r}; a side effect committed now "
            "would be orphaned and uncompensable"
        )
    if effect.idempotency_key.startswith(cred.nonce):
        raise AAIFProvenanceError(
            f"idempotency key for {effect.step!r} is credential-derived; "
            "a retry under a refreshed credential would duplicate the effect"
        )


def execute_irreversible_step(
    cred: Credential,
    live_chain_hash: str,
    effect: SideEffect,
    now: float,
    commit_fn,
) -> None:
    assert_provenance_checkpoint(cred, live_chain_hash, effect, now)
    commit_fn(effect)
