# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-sse-reattachment-after-a-resumable-mcp-stream-s-last-event-id-diverges-from-the-server-s-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-sse-reattachment-after-a-resumable-mcp-stream-s-last-event-id-diverges-from-the-server-s-replay-window.warrant.json
# Markdown SHA-256:   beaea695c694979da7f90561c86f2281a722bd3df4b8f6bee40353525773b4c4
# Code AST SHA-256:   fc9f468ab63c9a694d39dd92f249379c2be66823e10575d55f8ba7a062548be2
# Verified Classes:   ReplayWindowDivergence, McpStreamSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ReplayWindowDivergence(RuntimeError):
    """Raised when an SSE reattach cannot be proven contiguous with the client's last acked event."""
    pass


class McpStreamSession:
    def __init__(self, session_id: str, buffer_capacity: int):
        self.session_id = session_id
        self.buffer_capacity = buffer_capacity
        self._retained_min: int = 0
        self._max_emitted: int = -1

    def emit(self, event_id: int) -> None:
        if event_id != self._max_emitted + 1:
            raise ReplayWindowDivergence(
                f"non-monotonic emit: got {event_id}, expected {self._max_emitted + 1}"
            )
        self._max_emitted = event_id
        # Evict oldest when over capacity.
        if self._max_emitted - self._retained_min + 1 > self.buffer_capacity:
            self._retained_min = self._max_emitted - self.buffer_capacity + 1

    def reattach(self, last_event_id: int, presented_session_id: str) -> int:
        """Return the first event id the client will receive, or raise if unsafe."""
        if presented_session_id != self.session_id:
            raise ReplayWindowDivergence(
                f"session re-minted: client has {presented_session_id!r}, "
                f"server has {self.session_id!r}; treat as new session, not resumption"
            )
        next_id = last_event_id + 1
        if next_id < self._retained_min:
            raise ReplayWindowDivergence(
                f"Last-Event-ID {last_event_id} is outside retained window "
                f"[{self._retained_min}, {self._max_emitted}]; "
                f"events {next_id}..{self._retained_min - 1} are lost and cannot be replayed"
            )
        if next_id > self._max_emitted + 1:
            raise ReplayWindowDivergence(
                f"Last-Event-ID {last_event_id} is ahead of server head "
                f"{self._max_emitted}; client state is from a different stream"
            )
        return next_id


def safe_reattach(session: McpStreamSession, last_event_id: int, session_id: str) -> int:
    try:
        return session.reattach(last_event_id, session_id)
    except ReplayWindowDivergence:
        # Do not retry the reattach. Abandon the session and reconcile
        # the tool call's actual outcome via a fresh request.
        raise
