# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-mcp-resource-subscription-push-semantics-when-an-agent-s-event-consumer-is-slower-than-the-producer-s-notifications-resou.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-mcp-resource-subscription-push-semantics-when-an-agent-s-event-consumer-is-slower-than-the-producer-s-notifications-resou.warrant.json
# Markdown SHA-256:   2c6d1520e2ed3958f090d18e6edcb82146adc0337f9c7c65d638e81cca90c597
# Code AST SHA-256:   c2a671305dac743875639fe8e31d377ce55aae250865b6340858e1af6937d331
# Verified Classes:   SubscriptionInvariantError, UriStreamState, SubscriptionGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class SubscriptionInvariantError(RuntimeError):
    """Raised when an agent attempts to draw a completeness claim from a
    resource URI whose notification stream was coalesced or starved."""
    pass

@dataclass
class UriStreamState:
    last_notification_ts: float = 0.0
    last_read_version: int = 0
    observed_rate_hz: float = 0.0          # EWMA of notification rate
    expected_updates_in_window: float = 0.0
    received_updates_in_window: int = 0
    resolution: str = "edge"               # "edge" | "snapshot" | "suspect-starved"
    lossy_windows: list = field(default_factory=list)

class SubscriptionGuard:
    def __init__(self, process_latency_s: float, starvation_tolerance: float = 0.5):
        self.process_latency_s = process_latency_s
        self.starvation_tolerance = starvation_tolerance
        self.streams: Dict[str, UriStreamState] = {}

    def on_notification(self, uri: str, now: Optional[float] = None) -> str:
        now = now if now is not None else time.monotonic()
        st = self.streams.setdefault(uri, UriStreamState())
        if st.last_notification_ts:
            dt = now - st.last_notification_ts
            inst_rate = 1.0 / dt if dt > 0 else float("inf")
            st.observed_rate_hz = 0.7 * st.observed_rate_hz + 0.3 * inst_rate
        st.last_notification_ts = now
        st.received_updates_in_window += 1

        # Rate boundary: producer cadence vs consumer latency.
        if st.observed_rate_hz > 0 and (1.0 / st.observed_rate_hz) < self.process_latency_s:
            st.resolution = "snapshot"
        else:
            st.resolution = "edge"

        # Starvation detector: fewer notifications than the rate implies.
        elapsed = now - (st.last_notification_ts - (1.0 / st.observed_rate_hz if st.observed_rate_hz else 0))
        expected = st.observed_rate_hz * max(elapsed, 1e-6)
        if expected > 0 and st.received_updates_in_window < (1 - self.starvation_tolerance) * expected:
            st.resolution = "suspect-starved"
            st.lossy_windows.append((st.last_notification_ts, now))
        return st.resolution

    def assert_claim_valid(self, uri: str, window_start: float, window_end: float) -> None:
        st = self.streams.get(uri)
        if st is None:
            raise SubscriptionInvariantError(
                f"no stream state for {uri}; cannot validate completeness claim")
        if st.resolution != "edge":
            raise SubscriptionInvariantError(
                f"claim over {uri} [{window_start:.3f},{window_end:.3f}] rejected: "
                f"stream resolution={st.resolution!r}; history is not edge-complete")
        for lo, hi in st.lossy_windows:
            if not (window_end < lo or window_start > hi):
                raise SubscriptionInvariantError(
                    f"claim over {uri} overlaps lossy window [{lo:.3f},{hi:.3f}]")

    def reconcile(self, uri: str, read_version: int) -> None:
        st = self.streams.setdefault(uri, UriStreamState())
        if read_version < st.last_read_version:
            raise SubscriptionInvariantError(
                f"read-after-notification monotonicity violated for {uri}: "
                f"version {read_version} < prior {st.last_read_version}")
        st.last_read_version = read_version
        # A successful reconcile read does not clear a starvation tag; only a
        # full quiet window with no expected updates may reset it.
        if st.resolution == "suspect-starved" and st.observed_rate_hz == 0.0:
            st.resolution = "edge"
