# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-replay-window-across-a-session-resume-without-a-replayed-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-replay-window-across-a-session-resume-without-a-replayed-event-id.warrant.json
# Markdown SHA-256:   54ba1d650d030c13761335acb334b4db00aed2c4081fc3fe19ab4cebeca31faf
# Code AST SHA-256:   66cb79a8e15797a6afa42732c28453dfb0320276162cb97496e1f2c5eb018c1f
# Verified Classes:   StreamResumeGapError, SessionEventBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StreamResumeGapError(RuntimeError):
    """Raised when a resume would silently skip evicted events in an MCP session."""
    pass


@dataclass
class SessionEventBuffer:
    session_id: str
    min_retained_event_id: int
    head_event_id: int
    buffer: dict  # event_id -> payload


def handle_resume(
    buf: SessionEventBuffer,
    requested_last_event_id: Optional[int],
) -> list:
    """
    Returns the list of events to replay on a resume.
    Raises StreamResumeGapError if the requested ID predates the retained window,
    which MUST be surfaced to the client as 410 Gone, never silently satisfied.
    """
    if requested_last_event_id is None:
        # Fresh subscription, no continuity claim; start at head.
        return []

    if requested_last_event_id > buf.head_event_id:
        raise StreamResumeGapError(
            f"session {buf.session_id}: client Last-Event-ID "
            f"{requested_last_event_id} is ahead of server head "
            f"{buf.head_event_id}; protocol desync, reject with 400"
        )

    if requested_last_event_id < buf.min_retained_event_id:
        # The continuity hole. Do NOT replay from min_retained; reject.
        raise StreamResumeGapError(
            f"session {buf.session_id}: Last-Event-ID "
            f"{requested_last_event_id} evicted; retained window starts at "
            f"{buf.min_retained_event_id}. Reject with 410 Gone carrying "
            f"min_retained_event_id={buf.min_retained_event_id}; client must "
            f"reconcile in-flight calls before retrying."
        )

    # Normal path: replay everything strictly after the requested ID.
    return [
        buf.buffer[eid]
        for eid in sorted(buf.buffer)
        if eid > requested_last_event_id
    ]
