# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-whose-policy-predicate-was-satisfied-by-a-peer-s-stale-attestation-rather-than-by-live-state.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-whose-policy-predicate-was-satisfied-by-a-peer-s-stale-attestation-rather-than-by-live-state.warrant.json
# Markdown SHA-256:   80a19b15cfe3917fab045ba1a94ae90404e65b3ea80315df6b541322bfcd28e0
# Code AST SHA-256:   b30d4bbc949edf03d011dd26c8b6bcfcdedf225d408ac8083d20fc74857bc2e5
# Verified Classes:   StaleAttestationGrantError, PredicateAtom, Attestation, Capability
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleAttestationGrantError(RuntimeError):
    """Raised when a capability would be granted on a predicate whose
    volatile facts are not freshness-contained by the attestation."""
    pass


@dataclass(frozen=True)
class PredicateAtom:
    name: str
    volatile: bool          # True = can change autonomously between attestations
    freshness_s: int        # max age at which this fact is still trustworthy


@dataclass
class Attestation:
    issuer: str
    epoch: str              # pinned identity of this snapshot
    issued_at: float
    facts: Dict[str, object]
    ttl_s: int

    def remaining_ttl(self, now: float) -> float:
        return max(0.0, (self.issued_at + self.ttl_s) - now)


@dataclass
class Capability:
    subject: str
    predicate: list          # list[PredicateAtom]
    not_before: float
    expires: float
    pinned_epoch: str


def evaluate_predicate(att: Attestation, atoms: list) -> bool:
    # Pure function of the pinned snapshot — no live reads, no clock.
    for a in atoms:
        if a.name not in att.facts:
            return False
        # Simplified comparison; real impl compiles per-atom semantics.
        if not att.facts[a.name]:
            return False
    return True


def negotiate_grant(
    att: Attestation,
    atoms: list,
    subject: str,
    now: Optional[float] = None,
    invalidation_channel_live: bool = False,
) -> Capability:
    now = time.time() if now is None else now

    if not evaluate_predicate(att, atoms):
        # Content failure: ordinary denial, no re-attestation challenge.
        raise StaleAttestationGrantError(
            f"DENIED_PREDICATE_FALSE for {subject}: predicate not satisfied "
            f"by attestation epoch {att.epoch}"
        )

    # Predicate is satisfied. Now enforce freshness containment.
    volatile = [a for a in atoms if a.volatile]
    remaining = att.remaining_ttl(now)

    for a in volatile:
        if a.freshness_s > remaining:
            # Satisfied-but-stale: the fact can change faster than the
            # attestation refreshes. Refuse and demand re-attestation.
            raise StaleAttestationGrantError(
                f"DENIED_STALE_ATTESTATION for {subject}: volatile fact "
                f"'{a.name}' has freshness {a.freshness_s}s but attestation "
                f"epoch {att.epoch} has only {remaining:.0f}s remaining; "
                f"demand re-attestation with TTL <= {a.freshness_s}s"
            )
        if not invalidation_channel_live:
            raise StaleAttestationGrantError(
                f"DENIED_NO_INVALIDATION_CHANNEL for {subject}: fact "
                f"'{a.name}' is volatile and no revocation path exists; "
                f"cannot bound temporal over-scope"
            )

    # Clamp capability lifetime to the minimum freshness of volatile atoms.
    min_freshness = min((a.freshness_s for a in volatile), default=remaining)
    expires = min(now + min_freshness, att.issued_at + att.ttl_s)

    return Capability(
        subject=subject,
        predicate=atoms,
        not_before=now,
        expires=expires,
        pinned_epoch=att.epoch,
    )


def replay_decision(att_at_epoch: Attestation, atoms: list, cap: Capability) -> bool:
    # Replay MUST use the pinned epoch, never a live or later attestation.
    if att_at_epoch.epoch != cap.pinned_epoch:
        raise StaleAttestationGrantError(
            f"episode mismatch: replay attestation {att_at_epoch.epoch} != "
            f"pinned epoch {cap.pinned_epoch}; decision is not reproducible"
        )
    return evaluate_predicate(att_at_epoch, atoms)
