# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-credential-scope-as-a-narrowing-lattice-rather-than-a-snapshot-and-why-revocation-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-credential-scope-as-a-narrowing-lattice-rather-than-a-snapshot-and-why-revocation-propagation.warrant.json
# Markdown SHA-256:   066781f6a63bb2ea18749fbb8d185c61243b51ec847c500ad651ce95d4e62a71
# Code AST SHA-256:   87e36f59bcee5cbe534c7b8f476f598d834da954c6b7d014e9b6ecc80bf95a2d
# Verified Classes:   DelegationChainError, Credential, AAIFRegistry
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class DelegationChainError(RuntimeError):
    """Raised when a delegated credential's effective authority cannot be soundly derived."""
    pass


@dataclass
class Credential:
    cred_id: str
    parent_id: Optional[str]
    scopes: frozenset
    expires_at: float
    revoked: bool = False


@dataclass
class AAIFRegistry:
    _creds: dict = field(default_factory=dict)

    def register(self, c: Credential) -> None:
        self._creds[c.cred_id] = c

    def get(self, cred_id: str) -> Credential:
        if cred_id not in self._creds:
            # Unknown ancestor == untrusted; never default to valid.
            raise DelegationChainError(f"ancestor {cred_id} not found in registry")
        return self._creds[cred_id]


def effective_scope(registry: AAIFRegistry, leaf_id: str, now: float) -> frozenset:
    """
    Recompute the meet (intersection) of scopes across the entire delegation chain.
    Fails closed on: missing ancestor, revoked ancestor, expired ancestor,
    or a chain-walk that cannot complete. This must be called at every
    admission / checkpoint boundary, never cached across authority changes.
    """
    effective = None
    cursor = registry.get(leaf_id)
    seen = set()
    while cursor is not None:
        if cursor.cred_id in seen:
            raise DelegationChainError(f"cycle detected at {cursor.cred_id}")
        seen.add(cursor.cred_id)

        if cursor.revoked:
            raise DelegationChainError(
                f"ancestor {cursor.cred_id} revoked; leaf {leaf_id} is semantically orphaned"
            )
        if cursor.expires_at <= now:
            raise DelegationChainError(
                f"ancestor {cursor.cred_id} expired; leaf {leaf_id} authority lapsed"
            )

        effective = cursor.scopes if effective is None else (effective & cursor.scopes)
        if not effective:
            raise DelegationChainError(
                f"empty effective scope at {cursor.cred_id}; delegation meet collapsed"
            )
        cursor = registry.get(cursor.parent_id) if cursor.parent_id else None

    return effective


def admit(registry: AAIFRegistry, leaf_id: str, required: frozenset, now: float) -> None:
    """
    Admission gate. Raises if the requested operation is not covered by the
    live lattice meet. Never trusts the leaf's embedded scope string alone.
    """
    try:
        live = effective_scope(registry, leaf_id, now)
    except DelegationChainError:
        # Fail closed: inability to verify == denial.
        raise
    if not required.issubset(live):
        missing = required - live
        raise DelegationChainError(
            f"operation requires {sorted(missing)} not granted by live chain of {leaf_id}"
        )


# --- Reproduce the T+8min revocation trace ---
reg = AAIFRegistry()
reg.register(Credential("O", None, frozenset({"read:db", "write:db", "write:cache"}), now=time.time() + 3600))
reg.register(Credential("P", "O", frozenset({"read:db", "write:cache"}), now=time.time() + 1800))
reg.register(Credential("E", "P", frozenset({"write:cache"}), now=time.time() + 1800))

t0 = time.time()
admit(reg, "E", frozenset({"write:cache"}), t0)  # passes: chain intact

reg.get("O").revoked = True  # operator revokes at T+8min; only O is flagged

try:
    admit(reg, "E", frozenset({"write:cache"}), t0 + 9 * 60)
except DelegationChainError as e:
    # Correct behavior: leaf E is denied because its ancestor O was revoked,
    # even though E's own token is unrevoked and unexpired.
    print(f"denied as expected: {e}")
else:
    raise DelegationChainError("snapshot bug: revoked ancestor did not gate leaf admission")
