# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-sse-fallback-negotiation-when-an-mcp-streamable-http-transport-silently-degrades-to-a-half-open-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-sse-fallback-negotiation-when-an-mcp-streamable-http-transport-silently-degrades-to-a-half-open-event-stream.warrant.json
# Markdown SHA-256:   f58528eeafb17bfd7870674300394ce2a725912b72e8b267ec1b3a70d456c2b6
# Code AST SHA-256:   bb9e73de452552bfd44cd97e367860556cd5f592fec848c175f564da03392942
# Verified Classes:   HalfOpenStreamError, RequestScopedSSEReader
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import http.client
from typing import Optional


class HalfOpenStreamError(RuntimeError):
    """Raised when an SSE reader is reused or read after terminal EOF."""
    pass


class RequestScopedSSEReader:
    """Reader bound to exactly one HTTP response. EOF is terminal."""

    def __init__(self, response: http.client.HTTPResponse, request_id: str):
        self._response = response
        self._request_id = request_id
        self._eof_seen = False
        self._terminal_dispatched = False

    def read_event(self) -> Optional[bytes]:
        if self._eof_seen:
            # Reuse after EOF is the half-open bug: refuse instead of
            # silently returning b"" and letting the caller misattribute
            # the next request's frames to this one.
            raise HalfOpenStreamError(
                f"reader for request {self._request_id} already reached EOF; "
                f"allocate a new reader per POST"
            )
        chunk = self._response.read(1)
        if chunk == b"":
            self._eof_seen = True
            if not self._terminal_dispatched:
                raise HalfOpenStreamError(
                    f"request {self._request_id} stream closed before terminal "
                    f"`message` event; cannot mark complete"
                )
            return None
        return chunk

    def mark_terminal(self) -> None:
        self._terminal_dispatched = True


def dispatch_tool_result(
    reader: RequestScopedSSEReader, expected_request_id: str
) -> dict:
    if reader._request_id != expected_request_id:
        raise HalfOpenStreamError(
            f"reader bound to {reader._request_id} cannot serve "
            f"{expected_request_id}; transport worker was reused across requests"
        )
    # ... parse frames until `event: message`, then call reader.mark_terminal()
    # and rely on EOF as the completion signal for request-scoped streams.
    return {}
