# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-half-upgraded-mcp-streamable-http-session-sse-to-post-handshake-divergence-and-the-orphaned-response-stream-invaria.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-half-upgraded-mcp-streamable-http-session-sse-to-post-handshake-divergence-and-the-orphaned-response-stream-invaria.warrant.json
# Markdown SHA-256:   f2ca91f4d9b6b567bb37e8143aa827e80716891666b0ee470615cf03f6ab5473
# Code AST SHA-256:   3256eb42e28b9dd806375a1487d4823231bfb45584e24548a62fad213cd0fa18
# Verified Classes:   HalfUpgradedSessionError, StreamBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class HalfUpgradedSessionError(RuntimeError):
    """Raised when an MCP streamable-HTTP session is bound but the SSE
    stream the client holds is not the response-bearing channel for its
    POSTed request-ids (heartbeats present, zero id-matched messages)."""


@dataclass
class StreamBinding:
    session_id: str
    keepalive_interval_s: float
    opened_at: float = field(default_factory=time.monotonic)
    last_heartbeat: float = 0.0
    matched_ids: set = field(default_factory=set)          # ids answered on THIS stream
    outstanding_ids: set = field(default_factory=set)       # ids POSTed, awaiting result

    def on_heartbeat(self) -> None:
        self.last_heartbeat = time.monotonic()

    def on_message(self, msg_id: int) -> None:
        self.matched_ids.add(msg_id)
        self.outstanding_ids.discard(msg_id)

    def assert_response_bearing(self, now: float | None = None) -> None:
        """Enforce the invariant: a held stream with outstanding requests must
        have answered at least one of them, or be young enough to be legitimately
        pending. Heartbeats alone are NOT evidence of a response-bearing stream."""
        now = now or time.monotonic()
        if not self.outstanding_ids:
            return
        age = now - self.opened_at
        # Grace window: allow one keepalive interval per outstanding request.
        grace = self.keepalive_interval_s * (len(self.outstanding_ids) + 1)
        if age > grace and not self.matched_ids:
            raise HalfUpgradedSessionError(
                f"session {self.session_id!r}: stream open {age:.1f}s, "
                f"{len(self.outstanding_ids)} outstanding id(s) "
                f"{sorted(self.outstanding_ids)}, zero id-matched messages, "
                f"heartbeats={'alive' if self.last_heartbeat else 'none'} — "
                f"stream is orphaned; response channel diverged from held GET."
            )


def post_and_await(binding: StreamBinding, req_id: int, send_post, read_stream) -> dict:
    binding.outstanding_ids.add(req_id)
    send_post(req_id)
    deadline = time.monotonic() + binding.keepalive_interval_s * 30
    while time.monotonic() < deadline:
        event = read_stream(timeout=binding.keepalive_interval_s)
        if event is None:
            binding.on_heartbeat()
            binding.assert_response_bearing()   # may raise HalfUpgradedSessionError
            continue
        if event.get("type") == "heartbeat":
            binding.on_heartbeat()
            binding.assert_response_bearing()
            continue
        if event.get("id") == req_id:
            binding.on_message(req_id)
            return event["result"]
    raise HalfUpgradedSessionError(
        f"session {binding.session_id!r}: request {req_id} timed out with no "
        f"id-matched message; re-initialize session to force a converged path."
    )
