# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-across-a-load-balancer-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-across-a-load-balancer-boundary.warrant.json
# Markdown SHA-256:   60af9f64d257394a535877616cc781d04f284111c4a844e1cd55ef3a3817dd26
# Code AST SHA-256:   1351e90776d8dc9881163306c68485466dac0d029a4d6b33910c800ca4776bc1
# Verified Classes:   SessionResumeGapError, McpSessionClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SessionResumeGapError(RuntimeError):
    """Raised when an SSE resume succeeds at the transport layer but the
    event cursor cannot be proven contiguous, leaving server->client
    requests orphaned. Fail-closed: the caller must re-initialize."""
    pass


class McpSessionClient:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.last_event_id: int | None = None
        # Server->client requests we have emitted to the loop and not yet seen answered.
        self.outstanding: set[str] = set()

    def on_server_request(self, request_id: str) -> None:
        self.outstanding.add(request_id)

    def on_server_response(self, request_id: str) -> None:
        self.outstanding.discard(request_id)

    def resume_stream(self, reconnect_fn, observed_events: list[dict]) -> None:
        """Reconnect the SSE stream and verify cursor contiguity.

        `reconnect_fn(last_event_id)` returns (status_code, events, new_cursor).
        A 200 with a cursor that does not strictly advance past our prior
        cursor is a silent gap: the server restarted its buffer.
        """
        prior = self.last_event_id
        status, events, new_cursor = reconnect_fn(prior)

        if status != 200:
            # Honest failure: caller re-initializes. Safe.
            raise SessionResumeGapError(
                f"resume rejected status={status} session={self.session_id}"
            )

        # Contiguity check: a valid resume replays events strictly after `prior`
        # and lands on a cursor > prior. A fresh buffer lands at cursor 0 or None.
        if prior is not None:
            if new_cursor is None or new_cursor <= prior:
                raise SessionResumeGapError(
                    f"cursor did not advance: prior={prior} new={new_cursor} "
                    f"session={self.session_id} — server restarted event buffer; "
                    f"outstanding server->client requests orphaned: {self.outstanding}"
                )
            replayed = {e.get("id") for e in events}
            expected = set(range(prior + 1, new_cursor + 1))
            missing = expected - replayed
            if missing:
                raise SessionResumeGapError(
                    f"non-contiguous replay, missing event ids {sorted(missing)} "
                    f"session={self.session_id}"
                )

        self.last_event_id = new_cursor
        for e in events:
            if e.get("type") == "response":
                self.on_server_response(e["request_id"])

        # After a clean resume, no outstanding request may predate the cursor.
        if self.outstanding and prior is not None and new_cursor <= prior:
            raise SessionResumeGapError(
                f"orphaned requests after resume: {self.outstanding}"
            )
