# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-inherit-a-delegated-scope-after-the-parent-s-consent-attestation-is-invalidated-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-inherit-a-delegated-scope-after-the-parent-s-consent-attestation-is-invalidated-mid-run.warrant.json
# Markdown SHA-256:   200af7a0f6f877e5943efcdc24bfe23cc5f8c274fd2d1b09b05d53a1dcf63173
# Code AST SHA-256:   bf64d39cbb3592fe87b2d4a6c021cb9f1252b022d9e61d6e93c8b6d3aed461c4
# Verified Classes:   StaleDelegationError, Grant, Attestation, AttestationCache
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class StaleDelegationError(RuntimeError):
    """Raised when a cached consent attestation outlives its parent delegation."""
    pass


@dataclass
class Grant:
    grant_id: str
    scopes: frozenset
    epoch: int
    revoked: bool = False


@dataclass
class Attestation:
    scopes: frozenset
    parent_grant_id: str
    parent_epoch: int
    issued_at: float
    ttl: float
    signature: str = ""

    def sign(self, key: str) -> None:
        body = f"{sorted(self.scopes)}|{self.parent_grant_id}|{self.parent_epoch}|{self.issued_at}|{self.ttl}"
        self.signature = hashlib.sha256((key + body).encode()).hexdigest()


REVOCATION_BUDGET_S = 5.0
EPOCH_CACHE_TTL_S = 3.0


class AttestationCache:
    def __init__(self, issuer_key: str):
        self._key = issuer_key
        self._epoch_cache: dict[str, tuple[int, float]] = {}

    def _refresh_epoch(self, grant: Grant) -> int:
        cached = self._epoch_cache.get(grant.grant_id)
        now = time.time()
        if cached is None or now - cached[1] > EPOCH_CACHE_TTL_S:
            self._epoch_cache[grant.grant_id] = (grant.epoch, now)
        return self._epoch_cache[grant.grant_id][0]

    def mint(self, grant: Grant, scopes: frozenset) -> Attestation:
        if not scopes.issubset(grant.scopes):
            raise StaleDelegationError(
                f"requested scopes {scopes} not subset of grant {grant.scopes}"
            )
        att = Attestation(
            scopes=scopes,
            parent_grant_id=grant.grant_id,
            parent_epoch=grant.epoch,
            issued_at=time.time(),
            ttl=min(REVOCATION_BUDGET_S, 30.0),
        )
        att.sign(self._key)
        return att

    def authorize(self, att: Attestation, grant: Grant, scope: str) -> None:
        # 1. scope membership
        if scope not in att.scopes:
            raise StaleDelegationError(f"scope {scope} not in attestation")
        # 2. signature
        expected = hashlib.sha256(
            (
                self._key
                + f"{sorted(att.scopes)}|{att.parent_grant_id}|{att.parent_epoch}|{att.issued_at}|{att.ttl}"
            ).encode()
        ).hexdigest()
        if att.signature != expected:
            raise StaleDelegationError("attestation signature invalid")
        # 3. expiry
        if time.time() > att.issued_at + att.ttl:
            raise StaleDelegationError("attestation expired")
        # 4. liveness: epoch check against cached counter
        live_epoch = self._refresh_epoch(grant)
        if att.parent_epoch != live_epoch:
            raise StaleDelegationError(
                f"attestation epoch {att.parent_epoch} != live epoch {live_epoch}; "
                f"parent delegation revoked or re-scoped"
            )
        # 5. belt-and-suspenders: explicit revocation flag
        if grant.revoked:
            raise StaleDelegationError(
                f"parent grant {grant.grant_id} revoked; attestation is a bearer token"
            )


def run_child_task(cache: AttestationCache, att: Attestation, grant: Grant, calls: list[str]) -> int:
    executed = 0
    for scope in calls:
        try:
            cache.authorize(att, grant, scope)
        except StaleDelegationError as e:
            raise StaleDelegationError(
                f"child halted at call {executed} on scope {scope}: {e}"
            ) from e
        executed += 1
    return executed
