# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-skill-warrant-mid-execution-when-the-cached-capability-manifest-disagrees-with-the-revocation-feed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-skill-warrant-mid-execution-when-the-cached-capability-manifest-disagrees-with-the-revocation-feed.warrant.json
# Markdown SHA-256:   d57e43af28d00ed971910aa45de8aa03e75023f03ad28bd34b34819dd4c38479
# Code AST SHA-256:   e7fbb1c01b430ae8e47254d231fbfaf3d0d213832100d1197e8668df2981404c
# Verified Classes:   RevocationInvariantError, RevocationRecord, CapabilityManifest, Warrant, ConsumerInstance
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class RevocationInvariantError(RuntimeError):
    """Raised when a skill invocation cannot be proven authorized under the
    full conjunction: manifest signature, warrant chain, feed freshness, and
    non-revocation. Fail-closed by design."""


@dataclass
class RevocationRecord:
    skill_id: str
    effective_from: float          # epoch seconds; outputs at/after this are tainted
    effective_to: float            # end of tainted window (usually now + grace)
    quarantined_invocation_ids: set = field(default_factory=set)


@dataclass
class CapabilityManifest:
    skill_id: str
    signature_valid: bool
    expiry: float


@dataclass
class Warrant:
    skill_id: str
    delegated_from: str
    expires: float
    ancestor_revoked: bool = False


class ConsumerInstance:
    def __init__(self, max_staleness: float = 60.0):
        self.max_staleness = max_staleness
        self._feed_last_success: Optional[float] = None
        self._revocations: dict[str, RevocationRecord] = {}
        self._derived_state: dict[str, list] = {}   # invocation_id -> outputs

    def note_feed_poll_success(self, t: Optional[float] = None) -> None:
        self._feed_last_success = t if t is not None else time.time()

    def ingest_revocation(self, rec: RevocationRecord) -> None:
        self._revocations[rec.skill_id] = rec
        # Retroactive quarantine: drop derived state produced in the tainted window.
        self._quarantine_derived(rec)

    def _quarantine_derived(self, rec: RevocationRecord) -> None:
        for inv_id in list(rec.quarantined_invocation_ids):
            self._derived_state.pop(inv_id, None)

    def _feed_fresh(self, now: float) -> bool:
        return (
            self._feed_last_success is not None
            and (now - self._feed_last_success) <= self.max_staleness
        )

    def assert_authorized(
        self, manifest: CapabilityManifest, warrant: Warrant, now: Optional[float] = None
    ) -> None:
        now = now if now is not None else time.time()
        if not manifest.signature_valid:
            raise RevocationInvariantError(
                f"manifest for {manifest.skill_id} signature invalid"
            )
        if now >= manifest.expiry:
            raise RevocationInvariantError(
                f"manifest for {manifest.skill_id} expired"
            )
        if warrant.ancestor_revoked:
            raise RevocationInvariantError(
                f"warrant for {manifest.skill_id} has revoked ancestor "
                f"({warrant.delegated_from})"
            )
        if now >= warrant.expires:
            raise RevocationInvariantError(
                f"warrant for {manifest.skill_id} expired"
            )
        if not self._feed_fresh(now):
            raise RevocationInvariantError(
                f"revocation feed stale ({now - (self._feed_last_success or 0):.1f}s "
                f"> {self.max_staleness}s); cannot assert non-revocation for "
                f"{manifest.skill_id}"
            )
        rec = self._revocations.get(manifest.skill_id)
        if rec is not None and rec.effective_from <= now <= rec.effective_to:
            raise RevocationInvariantError(
                f"skill {manifest.skill_id} revoked in window "
                f"[{rec.effective_from}, {rec.effective_to}]"
            )

    def invoke(self, manifest, warrant, invocation_id: str, now=None):
        self.assert_authorized(manifest, warrant, now)
        out = {"skill": manifest.skill_id, "invocation_id": invocation_id}
        self._derived_state[invocation_id] = [out]
        return out
