# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-resource-subscription-starvation-under-http-2-stream-window-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-resource-subscription-starvation-under-http-2-stream-window-collapse.warrant.json
# Markdown SHA-256:   61f5c05aef0d5584ef390d17b0c49990168a762413abbdc44095b5870530ba00
# Code AST SHA-256:   1e81a8aca4a1d19bac6eb39853b39b3adf908d075249425ba28349dc0ae7f565
# Verified Classes:   SubscriptionStarvationError, BoundedSubscriptionDrain
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import asyncio
from collections import deque

class SubscriptionStarvationError(RuntimeError):
    """Raised when a subscription drain path would block the request path."""
    pass

class BoundedSubscriptionDrain:
    """
    Contract B implementation: notification handler never issues a synchronous
    read. It enqueues URIs; a separate task drains them under its own budget.
    """
    def __init__(self, uri: str, max_queue: int = 256, drain_batch: int = 16):
        self.uri = uri
        self._queue: deque[str] = deque()
        self._max = max_queue
        self._batch = drain_batch
        self.dropped = 0

    def on_updated(self, uri: str) -> None:
        # Called from the MCP notification handler. MUST NOT block on I/O.
        if len(self._queue) >= self._max:
            self.dropped += 1
            return
        self._queue.append(uri)

    async def drain(self, read_fn, on_content) -> None:
        # Separate task; owns its own request budget so a pinned subscription
        # stream cannot starve tools/call or other resources/read.
        while True:
            if not self._queue:
                await asyncio.sleep(0.01)
                continue
            batch = [self._queue.popleft() for _ in range(min(self._batch, len(self._queue)))]
            try:
                for uri in batch:
                    content = await asyncio.wait_for(read_fn(uri), timeout=5.0)
                    await on_content(uri, content)
            except asyncio.TimeoutError as e:
                # Do not retry inline — that re-creates the cyclic dependency.
                raise SubscriptionStarvationError(
                    f"drain of {self.uri} timed out; connection window likely pinned "
                    f"by undrained notifications (dropped={self.dropped})"
                ) from e
