# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-credential-whose-scope-silently-widens-after-a-mid-chain-revocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-credential-whose-scope-silently-widens-after-a-mid-chain-revocation.warrant.json
# Markdown SHA-256:   604f86ad440c8fe7cd4aef7d7dd62e411231b99c41705b212c461c5d4a14d6f3
# Code AST SHA-256:   92b78ee1614a613bb6c495980b1c85d1c9449864f23d89a5267fab2a857aa26b
# Verified Classes:   EpochCoverageError, Credential, Verifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class EpochCoverageError(RuntimeError):
    """Raised when a verifier cannot cover the epoch range of a presented chain."""


@dataclass
class Credential:
    scope: frozenset
    epoch_stamp: int          # attenuer epoch at mint
    parent_scope: frozenset
    chain_stamps: tuple = field(default_factory=tuple)


@dataclass
class Verifier:
    epoch: int
    epoch_log_floor: int      # oldest epoch this verifier can still fetch

    def covers(self, lo: int, hi: int) -> bool:
        return self.epoch_log_floor <= lo and self.epoch >= hi


def verify_and_execute(verifier: Verifier, cred: Credential, tool_call: str,
                       deadline_s: float = 2.0) -> bool:
    stamps = cred.chain_stamps + (cred.epoch_stamp,)
    lo, hi = min(stamps), max(stamps)

    if not verifier.covers(lo, hi):
        # Attempt a bounded synchronous epoch pull; never fall back to
        # leaf-vs-parent subset checking, which is unsound under skew.
        start = time.monotonic()
        while not verifier.covers(lo, hi):
            if time.monotonic() - start > deadline_s:
                raise EpochCoverageError(
                    f"verifier epoch {verifier.epoch} (floor {verifier.epoch_log_floor}) "
                    f"cannot cover chain range [{lo},{hi}] within {deadline_s}s; "
                    f"refusing {tool_call!r} rather than evaluating subset against "
                    f"a stale world"
                )
            time.sleep(0.01)
            verifier.epoch += 1  # simulated epoch ingest

    # Post-pull re-check: a revocation may have landed inside the pulled range.
    if verifier.epoch < hi:
        raise EpochCoverageError(
            f"post-pull epoch {verifier.epoch} < chain max {hi}; concurrent "
            f"revocation suspected, re-mint required"
        )

    if not cred.scope <= cred.parent_scope:
        raise EpochCoverageError(
            f"leaf scope {set(cred.scope)} not subset of claimed parent "
            f"{set(cred.parent_scope)}; structural violation"
        )
    return True
