# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-stall-on-a-single-mcp-stream-when-http-2-flow-control-windows-and-agent-level-concurrency-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-stall-on-a-single-mcp-stream-when-http-2-flow-control-windows-and-agent-level-concurrency-diverge.warrant.json
# Markdown SHA-256:   0017edf69c87d4492786f18459ab8f2fc98166f80349beb4f35bb8fed7fa14a8
# Code AST SHA-256:   4d197657a0edaa1aaa9d3acc10fadd652e39126becea0cb17fe468234b5d4fac
# Verified Classes:   ConnectionWindowStarvationError, StreamState, ConnectionMonitor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class ConnectionWindowStarvationError(RuntimeError):
    """Raised when a stream is misclassified as failed while the HTTP/2
    connection-level flow-control window is the actual binding constraint."""
    pass


@dataclass
class StreamState:
    stream_id: int
    bytes_received: int = 0
    last_progress_ts: float = 0.0


@dataclass
class ConnectionMonitor:
    initial_connection_window: int
    expected_body_size: int
    streams: Dict[int, StreamState] = field(default_factory=dict)
    connection_bytes_since_check: int = 0

    def max_safe_concurrency(self) -> int:
        # Never open more streams than the connection window can carry at once.
        return max(1, self.initial_connection_window // max(1, self.expected_body_size))

    def record_bytes(self, stream_id: int, n: int) -> None:
        st = self.streams.setdefault(stream_id, StreamState(stream_id))
        st.bytes_received += n
        self.connection_bytes_since_check += n

    def classify_stall(self, stream_id: int, now: float, stream_timeout: float) -> str:
        st = self.streams.setdefault(stream_id, StreamState(stream_id))
        idle = now - st.last_progress_ts
        if idle < stream_timeout:
            return "progressing"
        # Stream has been idle past its timeout. Decide whether the failure
        # is stream-scoped or connection-scoped.
        if self.connection_bytes_since_check == 0:
            # No bytes moved anywhere: connection window is starved.
            # Do NOT retry; do NOT report tool failure. Back off the connection.
            raise ConnectionWindowStarvationError(
                f"stream {stream_id} idle {idle:.2f}s but connection moved 0 bytes; "
                f"connection-window starvation, not tool failure. "
                f"Reduce concurrency to <= {self.max_safe_concurrency()} and drain siblings."
            )
        # Connection is progressing; this stream genuinely stalled.
        return "stream_failed"

    def reset_checkpoint(self) -> None:
        self.connection_bytes_since_check = 0


def handle_stream_timeout(monitor: ConnectionMonitor, stream_id: int, now: float) -> str:
    try:
        verdict = monitor.classify_stall(stream_id, now, stream_timeout=5.0)
    except ConnectionWindowStarvationError:
        # Re-raise after the caller has a chance to shrink its pool; the
        # invariant is that this never reaches the model as a tool error.
        raise
    if verdict == "stream_failed":
        # Only now is a retry legitimate, and only with an idempotency key.
        return f"retry stream {stream_id} with idempotency key"
    return "wait"
