# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-resumption-boundary-when-an-mcp-server-migrates-from-sse-to-streamable-http-and-a-client-replays-a-stale-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-resumption-boundary-when-an-mcp-server-migrates-from-sse-to-streamable-http-and-a-client-replays-a-stale-last-event-id.warrant.json
# Markdown SHA-256:   1c22566b9d938fb692c7e7e6d5a22215c830ca5fc985f401e58acb2fbeb31110
# Code AST SHA-256:   9039568e3103ddd4601d33613ce6556dd829d9a7d6b135ce4a40d883bb357091
# Verified Classes:   ResumptionCursorMismatch, StreamableSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResumptionCursorMismatch(RuntimeError):
    """Raised when a Last-Event-ID cannot be resolved within the
    (session_id, stream_id) continuity domain that issued it."""
    pass


class StreamableSession:
    def __init__(self, session_id: str, stream_id: str):
        self.session_id = session_id
        self.stream_id = stream_id
        self.next_event_id = 1          # monotonic within this stream only
        self.replay_buffer: dict[int, dict] = {}

    def emit(self, payload: dict) -> int:
        eid = self.next_event_id
        self.next_event_id += 1
        self.replay_buffer[eid] = payload
        return eid


def resume_stream(
    session: StreamableSession,
    presented_session_id: str,
    presented_stream_id: str,
    last_event_id: int,
) -> list[dict]:
    # Invariant 1: cursor is only valid in the domain that minted it.
    if presented_session_id != session.session_id:
        raise ResumptionCursorMismatch(
            f"session remap: cursor {last_event_id} minted under "
            f"{presented_session_id!r}, presented to {session.session_id!r}"
        )
    if presented_stream_id != session.stream_id:
        raise ResumptionCursorMismatch(
            f"stream rotation: cursor {last_event_id} minted under "
            f"stream {presented_stream_id!r}, presented to {session.stream_id!r}"
        )

    # Invariant 4: a cursor ahead of the current allocator means the ID
    # space was reset (deploy/restart). Never fall through to fresh IDs.
    if last_event_id >= session.next_event_id and last_event_id != 0:
        raise ResumptionCursorMismatch(
            f"cursor {last_event_id} exceeds allocator "
            f"{session.next_event_id} for stream {session.stream_id!r}; "
            f"ID space was reset — client must re-initialize"
        )

    # Cursor within range but evicted from buffer: explicit gap, not silence.
    if last_event_id not in session.replay_buffer and last_event_id != 0:
        oldest = min(session.replay_buffer) if session.replay_buffer else None
        raise ResumptionCursorMismatch(
            f"cursor {last_event_id} evicted; oldest buffered is {oldest}; "
            f"server must surface replay_gap, not stream fresh IDs"
        )

    return [
        session.replay_buffer[eid]
        for eid in sorted(session.replay_buffer)
        if eid > last_event_id
    ]


def handle_reconnect(req: dict, session: StreamableSession) -> list[dict]:
    try:
        return resume_stream(
            session,
            req["Mcp-Session-Id"],
            req.get("X-Stream-Id", session.stream_id),
            int(req["Last-Event-ID"]),
        )
    except ResumptionCursorMismatch as e:
        # Fail closed: force client re-initialize rather than silent divergence.
        raise ResumptionCursorMismatch(
            f"resumption rejected, client must re-initialize: {e}"
        ) from e
