# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-when-the-server-initiated-sse-stream-reconnects-after-a-mid-stream-last-event-id-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-when-the-server-initiated-sse-stream-reconnects-after-a-mid-stream-last-event-id-gap.warrant.json
# Markdown SHA-256:   27ca40c1963925a76bf4f35b22f08df7e55bf3499e3400af53ad79278be646c3
# Code AST SHA-256:   e633f9092ecafbcba280239003020684fa1c1a8632959b5e7df244bab7ab532c
# Verified Classes:   StreamResumeGapError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when a server-initiated SSE replay skips event ids, indicating
    the server buffer evicted messages the client never received. The session
    cannot be resumed; state must be re-synchronized from the server."""


def resume_stream(session_id: str, last_seen_id: int, replayed_ids: list[int]) -> int:
    """Validate continuity of a resumed server-initiated stream.

    Returns the new last_seen_id on success. Raises StreamResumeGapError if the
    first replayed id is not exactly last_seen_id + 1, meaning one or more
    events were evicted from the server buffer and are unrecoverable.
    """
    if not replayed_ids:
        # Empty replay is legal (server may have nothing buffered); continuity
        # is unprovable but no gap is observed. Caller continues live.
        return last_seen_id

    first = replayed_ids[0]
    expected = last_seen_id + 1

    if first == expected:
        return replayed_ids[-1]

    if first > expected:
        # Gap: ids [expected, first) were never delivered. Silent-loss case.
        raise StreamResumeGapError(
            f"session {session_id}: replay starts at {first} but last seen was "
            f"{last_seen_id}; events [{expected}, {first}) evicted by server "
            f"buffer. Stream not resumable — re-sync state from server."
        )

    # first < expected: server replayed already-consumed events (idempotent
    # replay). Safe to skip to last_seen_id, then continue.
    return last_seen_id
