# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-credential-chain-has-gone-stale-mid-execution-rather-than-being-legitimately-revoked.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-credential-chain-has-gone-stale-mid-execution-rather-than-being-legitimately-revoked.warrant.json
# Markdown SHA-256:   fcc0800a319b762ad41c979b9e807c003671c3ea2ed8f658aa3c212427dd1341
# Code AST SHA-256:   5ae3c3d53417bae02485b9176061c7dc68348becb3791dc98620c0201854ea3c
# Verified Classes:   ChainStateError, ChainVerdict, Warrant, ProbeResult, IssuerProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class ChainStateError(RuntimeError):
    """Raised when a delegated credential chain cannot be classified as
    STALE, REVOKED, or STALE_NARROWED with the available evidence."""
    pass


class ChainVerdict(Enum):
    CURRENT = "current"
    STALE = "stale"
    STALE_NARROWED = "stale_narrowed"
    REVOKED = "revoked"


@dataclass
class Warrant:
    issuer: str
    subject: str
    issuance_seq: int
    not_after: float
    scope: frozenset


@dataclass
class ProbeResult:
    current_seq: int
    current_scope: frozenset


class IssuerProbe:
    """Cheap, unauthenticated-read probe of the issuer's current sequence."""

    def __init__(self, table: dict):
        self._table = table  # (issuer, subject) -> ProbeResult

    def current(self, issuer: str, subject: str) -> ProbeResult:
        key = (issuer, subject)
        if key not in self._table:
            raise ChainStateError(
                f"probe has no record for {key}; cannot distinguish "
                f"staleness from revocation"
            )
        return self._table[key]


def classify_chain(
    leaf: Warrant,
    parent: Warrant,
    probe: IssuerProbe,
    now: float,
    skew_tolerance: float = 5.0,
) -> ChainVerdict:
    # Fast path: everything current.
    if now + skew_tolerance < parent.not_after and now + skew_tolerance < leaf.not_after:
        return ChainVerdict.CURRENT

    # Parent appears expired or near-expired. Probe before concluding anything.
    if now + skew_tolerance >= parent.not_after:
        result = probe.current(issuer=parent.issuer, subject=parent.subject)

        if result.current_seq <= parent.issuance_seq:
            # No successor exists: this is a genuine revocation or expiry.
            return ChainVerdict.REVOKED

        # A successor exists. Is our scope still covered by it?
        if not leaf.scope.issubset(result.current_scope):
            return ChainVerdict.STALE_NARROWED

        return ChainVerdict.STALE

    # Leaf itself is the expired element with a valid parent: re-attest.
    return ChainVerdict.STALE


def guarded_tool_call(
    leaf: Warrant,
    parent: Warrant,
    probe: IssuerProbe,
    retry_count: int,
    now: float,
) -> ChainVerdict:
    if retry_count > 1:
        # Retrying without probing is the failure mode this guards against.
        verdict = classify_chain(leaf, parent, probe, now)
        if verdict is ChainVerdict.REVOKED:
            raise ChainStateError(
                "chain revoked after retry; halting to avoid token-budget "
                "exhaustion on a dead chain"
            )
        return verdict

    verdict = classify_chain(leaf, parent, probe, now)
    if verdict is ChainVerdict.STALE_NARROWED:
        raise ChainStateError(
            "successor warrant narrowed scope below active grant; "
            "checkpoint and return partial results, do not continue"
        )
    return verdict
