# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-is-valid-but-whose-attestation-epoch-predates-the-delegating-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-is-valid-but-whose-attestation-epoch-predates-the-delegating-a.warrant.json
# Markdown SHA-256:   a83e188bbac881ea2a5eb9dccec097fc4ae889ff06b28fedcc55fc288a371a11
# Code AST SHA-256:   e18d840f4baa528e810e28359eb8d1376b97cd02588cd2c3bcbf52396a31bd95
# Verified Classes:   StaleLineageError, Edge, KeyState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleLineageError(RuntimeError):
    """Raised when a delegated credential's attestation epoch predates the
    delegating agent's active key epoch, or when an edge's delegator key id
    does not match the verifier's resolved active key."""


@dataclass
class Edge:
    delegator_subject: str
    delegator_key_id: str
    child_attestation_epoch: int
    child_attestation_subject: str


@dataclass
class KeyState:
    active_key_id: str
    key_epoch: int
    rotation_logged: bool  # True if a rotation event explains a mismatch


def verify_lineage(
    chain: list[Edge],
    key_resolver,
    max_renegotiations: int = 1,
) -> None:
    """
    Enforce the lineage-epoch binding invariant across a delegation chain.
    Raises StaleLineageError on the first edge that violates it.
    """
    renegotiations = 0
    for edge in chain:
        state: Optional[KeyState] = key_resolver(edge.delegator_subject)
        if state is None:
            raise StaleLineageError(
                f"cannot resolve active key for {edge.delegator_subject}"
            )

        # Rule 3: hard reject on unexplained key-id mismatch.
        if edge.delegator_key_id != state.active_key_id:
            if not state.rotation_logged:
                raise StaleLineageError(
                    f"edge delegator_key_id={edge.delegator_key_id} does not "
                    f"match active key={state.active_key_id} for "
                    f"{edge.delegator_subject} and no rotation is logged; "
                    f"treating as substitution"
                )

        # Rule 2: stale-epoch rejection with bounded renegotiation.
        if edge.child_attestation_epoch < state.key_epoch:
            if renegotiations >= max_renegotiations:
                raise StaleLineageError(
                    f"child attestation epoch={edge.child_attestation_epoch} "
                    f"predates active key epoch={state.key_epoch} for "
                    f"{edge.delegator_subject} after {renegotiations} "
                    f"renegotiation(s); refusing to loop"
                )
            renegotiations += 1
            raise StaleLineageError(
                f"STALE_LINEAGE: re-attestation required for "
                f"{edge.child_attestation_subject} under epoch "
                f"{state.key_epoch}"
            )
