# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-mcp-server-side-streaming-backpressure-collapse-under-http-2-and-http-3-chunked-tool-result-streaming.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-mcp-server-side-streaming-backpressure-collapse-under-http-2-and-http-3-chunked-tool-result-streaming.warrant.json
# Markdown SHA-256:   6398c37b0c37e42a017a0aa6b212e0725061d6b8e65143fc1826c375d9970ff3
# Code AST SHA-256:   2873a40a903b02268c3d69b7d03d1749c9196a221b825eae640d0a99815ab991
# Verified Classes:   StreamBackpressureCollapse, TransportView
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StreamBackpressureCollapse(RuntimeError):
    """Raised when transport credit is exhausted but the producer keeps writing."""

    def __init__(self, stream_id: int, window: int, buffered: int, turns: int):
        self.stream_id = stream_id
        self.window = window
        self.buffered = buffered
        self.turns = turns
        super().__init__(
            f"stream {stream_id}: remote window={window} buffered={buffered} "
            f"stalled for {turns} event-loop turns without drain"
        )


@dataclass
class TransportView:
    """Adapter over http2 stream.state / quinn send_window / hyper send capacity."""
    stream_id: int
    remote_window: int          # HTTP/2 remoteWindowSize or HTTP/3 MAX_STREAM_DATA credit
    connection_window: int      # HTTP/2 session window or HTTP/3 MAX_DATA credit
    buffered_bytes: int         # writableLength / bufferedAmount
    drained: bool               # did 'drain' / WINDOW_UPDATE fire this turn?


def assert_stream_can_accept(view: TransportView, *, max_stalled_turns: int = 3) -> None:
    """
    Pre-write guard. Call before every chunk write. Raises if the transport has
    no credit and the producer is not honouring the drain signal.
    """
    if view.remote_window > 0 and view.connection_window > 0:
        return
    if view.drained:
        return
    if view.buffered_bytes > 0 and view.remote_window == 0:
        # Credit is zero, buffer is non-empty, and no drain fired: producer is
        # outrunning the consumer and will grow memory without bound.
        raise StreamBackpressureCollapse(
            stream_id=view.stream_id,
            window=view.remote_window,
            buffered=view.buffered_bytes,
            turns=max_stalled_turns,
        )


async def stream_tool_result(stream, chunks, *, high_water: int = 16 * 1024):
    """
    Correct producer: awaits drain before writing when transport credit is gone.
    """
    for chunk in chunks:
        view = TransportView(
            stream_id=stream.id,
            remote_window=stream.state.remote_window_size,
            connection_window=stream.session.state.remote_window_size,
            buffered_bytes=stream.writable_length,
            drained=stream.writable_need_drain is False,
        )
        assert_stream_can_accept(view)
        if stream.writable_need_drain:
            await stream.wait_for_drain()   # yields to reactor; observes RST_STREAM
        stream.write(chunk)
        if stream.writable_length > high_water:
            await stream.wait_for_drain()
