# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-notifications-resources-updated-push-as-authoritative-for-a-long-running-task-and-when-is-it-a-stale-echo.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-notifications-resources-updated-push-as-authoritative-for-a-long-running-task-and-when-is-it-a-stale-echo.warrant.json
# Markdown SHA-256:   30784299f7ceed401dc45959dacc38d2051add035a03f0a50b4d804fe688592e
# Code AST SHA-256:   d25fe1c60763a0cd3a3fb20b77c007763c527514df737c71089c308369bcc0a3
# Verified Classes:   NotificationThrash, StaleEchoSuppressed, ResourceCache, SubscriptionGuard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class NotificationThrash(RuntimeError):
    """Raised when notifications force re-derivation without content change."""


class StaleEchoSuppressed(RuntimeError):
    """Raised (internally) when a notification is causally behind the agent's own read."""


@dataclass
class ResourceCache:
    uri: str
    last_read_hash: str
    last_read_seq: int
    last_read_wall: float
    rederive_count: int = 0
    rederive_window_start: float = field(default_factory=time.monotonic)


class SubscriptionGuard:
    """
    Enforces: notifications schedule reads; reads determine state; state determines plans.
    """

    MAX_REDERIVE_PER_WINDOW = 3
    REDERIVE_WINDOW_S = 120.0
    MAX_STALENESS_S = 90.0

    def __init__(self, read_fn, plan_fn):
        self._read_fn = read_fn          # (uri) -> bytes
        self._plan_fn = plan_fn          # (uri, content) -> plan
        self._cache: dict[str, ResourceCache] = {}
        self._read_seq = 0
        self._pending: dict[str, int] = {}

    def _hash(self, content: bytes) -> str:
        return hashlib.sha256(content).hexdigest()

    def initial_read(self, uri: str):
        content = self._read_fn(uri)
        self._read_seq += 1
        h = self._hash(content)
        self._cache[uri] = ResourceCache(
            uri=uri,
            last_read_hash=h,
            last_read_seq=self._read_seq,
            last_read_wall=time.monotonic(),
        )
        return self._plan_fn(uri, content)

    def on_notification(self, uri: str, current_plan):
        """
        Notification handler. Never mutates the plan directly.
        Returns the plan to use (possibly the same object).
        """
        if uri not in self._cache:
            return self.initial_read(uri)

        entry = self._cache[uri]
        now = time.monotonic()

        # Coalesce: if a read is already in flight for this URI, fold this in.
        self._pending[uri] = self._pending.get(uri, 0) + 1

        # Speculative re-read — cheap relative to re-plan.
        content = self._read_fn(uri)
        self._read_seq += 1
        new_hash = self._hash(content)

        # Stale-echo / identical-rewrite case: no content change.
        if new_hash == entry.last_read_hash:
            self._pending[uri] = 0
            entry.last_read_wall = now
            return current_plan

        # Genuine content change. Rate-limit re-derivation.
        if now - entry.rederive_window_start > self.REDERIVE_WINDOW_S:
            entry.rederive_window_start = now
            entry.rederive_count = 0
        entry.rederive_count += 1
        if entry.rederive_count > self.MAX_REDERIVE_PER_WINDOW:
            raise NotificationThrash(
                f"{uri}: {entry.rederive_count} re-derivations in "
                f"{self.REDERIVE_WINDOW_S}s window; notification stream is "
                f"adversarial or misconfigured. Halting plan mutation."
            )

        entry.last_read_hash = new_hash
        entry.last_read_seq = self._read_seq
        entry.last_read_wall = now
        self._pending[uri] = 0
        return self._plan_fn(uri, content)

    def enforce_staleness_floor(self, uri: str, current_plan):
        """
        Push is not guaranteed delivery. Force a read if too stale.
        """
        entry = self._cache.get(uri)
        if entry is None:
            return self.initial_read(uri)
        if time.monotonic() - entry.last_read_wall < self.MAX_STALENESS_S:
            return current_plan
        return self.on_notification(uri, current_plan)
