# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-http-native-transport-stream-the-last-event-id-session-lifetime-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-http-native-transport-stream-the-last-event-id-session-lifetime-invariant.warrant.json
# Markdown SHA-256:   bc37bdaf9872d5088db90a967805ba10c890156123d86f433357decc40fa48b3
# Code AST SHA-256:   e95f41a9d48141562b353d3db50297bc0d1c335bc7b914dce628e369e3fac314
# Verified Classes:   StreamResumeError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StreamResumeError(RuntimeError):
    """Raised when an MCP HTTP-native stream resume request cannot be honored
    without risking silent event loss. Callers must not open a stream."""


def resume_stream(session, last_event_id):
    """Decide whether an SSE resume request may proceed.

    Returns the list of buffered events to replay (possibly empty if the gap is
    provably empty and the stream is still live). Raises StreamResumeError with
    an HTTP status hint otherwise.
    """
    if session is None or session.state in ("expired", "terminated"):
        # Unknown or dead session: client must re-initialize.
        raise StreamResumeError(
            "unknown or expired Mcp-Session-Id; re-initialize session",
            status=404,
        )

    if last_event_id is None:
        # Fresh subscribe at current head. Always valid.
        return []

    if not session.owns_event_id(last_event_id):
        # ID is not part of this session's sequence. Never alias across sessions.
        raise StreamResumeError(
            f"Last-Event-ID {last_event_id!r} not in session event sequence",
            status=400,
        )

    retained = session.retained_events_after(last_event_id)
    highest = session.highest_emitted_event_id()

    if highest is None or last_event_id == highest:
        # No events emitted after the resume point: gap is provably empty.
        return []

    if retained is None:
        # Buffer evicted; server cannot prove the gap is empty.
        raise StreamResumeError(
            "event buffer evicted for resume point; gap cannot be guaranteed",
            status=400,
        )

    if not retained:
        # Events exist after last_event_id but none are retained: gap lost.
        raise StreamResumeError(
            "events exist after Last-Event-ID but were not retained",
            status=400,
        )

    # Verify contiguity: retained must begin at the first event after last_event_id.
    if retained[0].id != session.next_id_after(last_event_id):
        raise StreamResumeError(
            "retained events do not start at the requested resume point",
            status=400,
        )

    return retained
