# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-re-derive-delegated-authority-from-a-stale-attestation-root-and-silently-widen-its-own-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-re-derive-delegated-authority-from-a-stale-attestation-root-and-silently-widen-its-own-scope.warrant.json
# Markdown SHA-256:   ef7455f8fee4ed6d60cc898da7c34c86795d04733a53585eaa95f4b39e2da52e
# Code AST SHA-256:   52c795a7938173d21e5d22e1ac808bbbb1dc94b96790805ec3aa78f041f7fdee
# Verified Classes:   StaleAttestationRootError, Root, Warrant, RootRegistry, DelegationEvaluator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationRootError(RuntimeError):
    """Raised when a warrant chain cites a root that is no longer current
    and no supersession proof bridges the cited root to the current root."""


@dataclass(frozen=True)
class Root:
    root_id: str
    scope: frozenset
    not_before: float
    not_after: float
    superseded_by: Optional[str] = None


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    scope: frozenset
    cited_root_id: str
    not_after: float


class RootRegistry:
    """Authoritative, mutable source of the *current* root per issuer."""

    def __init__(self, roots: dict):
        self._roots = roots  # root_id -> Root

    def current_root_for(self, issuer: str) -> Root:
        # In production: query the live registry, not a session cache.
        for r in self._roots.values():
            if r.superseded_by is None and r.root_id.startswith(issuer):
                return r
        raise StaleAttestationRootError(f"no current root for issuer {issuer!r}")

    def get(self, root_id: str) -> Root:
        return self._roots[root_id]

    def supersession_chain(self, from_id: str, to_id: str) -> list:
        """Return the chain of roots from from_id to to_id, or [] if none."""
        chain, cur = [], from_id
        seen = set()
        while cur is not None and cur != to_id:
            if cur in seen:
                return []
            seen.add(cur)
            root = self._roots.get(cur)
            if root is None or root.superseded_by is None:
                return []
            chain.append(root)
            cur = root.superseded_by
        return chain if cur == to_id else []


class DelegationEvaluator:
    def __init__(self, registry: RootRegistry, clock):
        self._registry = registry
        self._clock = clock

    def authorize(self, warrant: Warrant, requested: frozenset) -> bool:
        now = self._clock()
        if not requested <= warrant.scope:
            return False
        if now >= warrant.not_after:
            return False

        current = self._registry.current_root_for(warrant.issuer)

        if warrant.cited_root_id == current.root_id:
            cited = current
        else:
            # Cited root is stale. Only permissible if a supersession chain
            # bridges it to the current root AND every bridge narrows or
            # preserves scope (monotone non-widening), so the cited scope
            # is still a valid upper bound at evaluation time.
            bridge = self._registry.supersession_chain(
                warrant.cited_root_id, current.root_id
            )
            if not bridge:
                raise StaleAttestationRootError(
                    f"warrant {warrant.warrant_id!r} cites root "
                    f"{warrant.cited_root_id!r}, current root is "
                    f"{current.root_id!r}, and no supersession proof exists"
                )
            cited = self._registry.get(warrant.cited_root_id)
            for hop in bridge:
                if not (cited.scope <= hop.scope):
                    # A narrowing occurred between cited and current;
                    # the cached authority is wider than the live one.
                    raise StaleAttestationRootError(
                        f"warrant {warrant.warrant_id!r} cites superseded "
                        f"root {cited.root_id!r} whose scope is not a subset "
                        f"of superseding root {hop.root_id!r}"
                    )
                cited = hop

        if now < cited.not_before or now >= cited.not_after:
            return False
        if not requested <= cited.scope:
            return False
        return True


# --- Trace of the incident above -------------------------------------------

def _clock():
    return 2 * 3600 + 10 * 60  # T+2:10


registry = RootRegistry({
    "O-R1": Root("O-R1", frozenset({"read:repo", "write:staging"}),
                 0, 6 * 3600, superseded_by="O-R2"),
    "O-R2": Root("O-R2", frozenset({"read:repo"}),
                 1.5 * 3600, 6 * 3600, superseded_by=None),
})

warrant = Warrant(
    warrant_id="w_W->A",
    issuer="O",
    subject="A",
    scope=frozenset({"read:repo", "write:staging"}),
    cited_root_id="O-R1",
    not_after=6 * 3600,
)

ev = DelegationEvaluator(registry, _clock)

try:
    ev.authorize(warrant, frozenset({"write:staging"}))
except StaleAttestationRootError as e:
    # Expected: O-R1 was superseded by the narrower O-R2; the cached
    # authority is no longer a subset of the live root. Fail closed.
    print(f"denied: {e}")
