# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-authority-has-been-silently-attenuated-by-a-downstream-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-authority-has-been-silently-attenuated-by-a-downstream-re-delegation.warrant.json
# Markdown SHA-256:   6fd782182040c51959c41f05181d05266116a15ca921d16893ec7a6b690a5c63
# Code AST SHA-256:   85f497a3e427f4f2879f7d69bac130369ab6699e23c52e3f5010aaf31788be36
# Verified Classes:   AuthorityAttenuated, StaleRevocationView, Warrant, RevocationView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class AuthorityAttenuated(RuntimeError):
    """Raised when an agent's effective scope cannot be proven to cover a pending action."""
    pass


class StaleRevocationView(RuntimeError):
    """Raised when the revocation list is older than the allowed staleness bound."""
    pass


@dataclass
class Warrant:
    jti: str
    parent_jti: Optional[str]
    scope: frozenset            # e.g. frozenset({"tenant/eu/finance"})
    expiry: float
    revoked: bool = False


@dataclass
class RevocationView:
    last_poll: float
    revoked_jtis: frozenset = field(default_factory=frozenset)

    def staleness(self, now: float) -> float:
        return now - self.last_poll


def effective_scope(warrant: Warrant, chain: dict[str, Warrant]) -> frozenset:
    """Intersect this warrant's scope with every live ancestor's scope."""
    scope = set(warrant.scope)
    cur = warrant
    while cur.parent_jti is not None:
        parent = chain.get(cur.parent_jti)
        if parent is None:
            # Broken chain: cannot prove ancestry -> empty authority.
            return frozenset()
        if parent.revoked:
            return frozenset()
        scope &= parent.scope
        cur = parent
    return frozenset(scope)


def assert_action_permitted(
    my_warrant: Warrant,
    target_scope: frozenset,
    chain: dict[str, Warrant],
    view: RevocationView,
    max_staleness: float,
    idempotent: bool,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    if my_warrant.revoked or my_warrant.jti in view.revoked_jtis:
        raise AuthorityAttenuated(
            f"warrant {my_warrant.jti} is revoked; refusing action on {target_scope}"
        )

    if my_warrant.expiry <= now:
        raise AuthorityAttenuated(
            f"warrant {my_warrant.jti} expired at {my_warrant.expiry}"
        )

    # Staleness gate: beyond bound, treat scope as unknown for non-idempotent work.
    if view.staleness(now) > max_staleness:
        if not idempotent:
            raise StaleRevocationView(
                f"revocation view stale by {view.staleness(now):.2f}s "
                f"(bound {max_staleness}s); cannot prove scope for non-idempotent action"
            )
        return  # idempotent: proceed, re-derive before next non-idempotent action

    eff = effective_scope(my_warrant, chain)
    if not target_scope.issubset(eff):
        raise AuthorityAttenuated(
            f"target scope {set(target_scope)} not within effective scope {set(eff)} "
            f"for warrant {my_warrant.jti}; ancestor attenuation detected"
        )


def execute_non_idempotent_write(
    my_warrant: Warrant,
    target_scope: frozenset,
    chain: dict[str, Warrant],
    view: RevocationView,
    max_staleness: float,
) -> None:
    assert_action_permitted(
        my_warrant=my_warrant,
        target_scope=target_scope,
        chain=chain,
        view=view,
        max_staleness=max_staleness,
        idempotent=False,
    )
    # ... perform the write only after the assertion above passes ...
