# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-deadlock-when-an-mcp-server-s-sse-backpressure-signal-is-silently-absorbed-by-the-transport-layer-instead-of-propagating-to-the-m.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-deadlock-when-an-mcp-server-s-sse-backpressure-signal-is-silently-absorbed-by-the-transport-layer-instead-of-propagating-to-the-m.warrant.json
# Markdown SHA-256:   2c2ceffed12a2145a742c8dd1156d0f37697fd16d43cd12fac839bb166cc43ec
# Code AST SHA-256:   d4de718cc7654ee33ff6c58a01fd89e3bdd1c32caffd641a0f8b9abff683c0d2
# Verified Classes:   BackpressureBlindSpotError, StreamedMCPResponse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import asyncio
from dataclasses import dataclass, field
from typing import Optional


class BackpressureBlindSpotError(RuntimeError):
    """Raised when a streamed MCP response stalls because the flow-control
    signal is absorbed at the transport layer and never reaches the actor
    that could relieve it (the consumer / model token loop)."""


@dataclass
class StreamedMCPResponse:
    high_water: int = 64
    low_water: int = 16
    pending: int = 0
    consumed: int = 0
    reader_blocked: bool = False
    last_consumed_echo: Optional[int] = None
    progress_heartbeats_since_echo: int = 0

    def on_frame_received(self, is_progress: bool) -> None:
        self.pending += 1
        if is_progress:
            self.progress_heartbeats_since_echo += 1
        if self.pending >= self.high_water:
            # Correct behavior: reader stops pulling from socket, which
            # propagates backpressure to the server's drain().
            self.reader_blocked = True

    def on_consumer_drain(self, n: int) -> None:
        self.consumed += n
        self.pending = max(0, self.pending - n)
        self.last_consumed_echo = self.consumed
        self.progress_heartbeats_since_echo = 0
        if self.pending <= self.low_water:
            self.reader_blocked = False

    def check_liveness_guard(self, wall_clock_deadline_exceeded: bool) -> None:
        # The bug: heartbeats inside a stalled stream reset the deadline.
        # Guard: only a consumer-side echo may reset liveness.
        if wall_clock_deadline_exceeded and self.last_consumed_echo is None:
            raise BackpressureBlindSpotError(
                f"stream stalled with {self.pending} pending events, "
                f"{self.progress_heartbeats_since_echo} progress heartbeats "
                f"masking the stall, and zero consumer echoes — "
                f"transport absorbed backpressure, consumer never learned to drain"
            )


async def consume_with_flow_control(stream: StreamedMCPResponse, batches: int) -> None:
    for i in range(batches):
        # Simulate a follow-up request issued mid-stream on the same connection.
        if i == 3 and stream.reader_blocked:
            # The follow-up shares the connection and cannot be read while
            # the reader is blocked on drain. This is the deadlock trigger.
            stream.check_liveness_guard(wall_clock_deadline_exceeded=True)
        stream.on_frame_received(is_progress=(i % 5 == 0))
        if i % 4 == 0:
            stream.on_consumer_drain(1)
        await asyncio.sleep(0)
    if stream.pending > stream.high_water:
        raise BackpressureBlindSpotError(
            f"queue overflow: {stream.pending} > {stream.high_water} — "
            f"no backpressure echo reached the server"
        )


async def main() -> None:
    stream = StreamedMCPResponse(high_water=8, low_water=2)
    try:
        await consume_with_flow_control(stream, batches=16)
    except BackpressureBlindSpotError as exc:
        print(f"HALT: {exc}")


if __name__ == "__main__":
    asyncio.run(main())
