# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-session-rather-than-a-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-session-rather-than-a-replay.warrant.json
# Markdown SHA-256:   dbb332a8c039246e08005bf8e953f10671a5aad3762e0343d8314eca422a9aa4
# Code AST SHA-256:   46f13ac214bb31150eb9b18a31b4e017679c2035b3e9eab065fad3182ad07539
# Verified Classes:   SessionResumptionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionResumptionError(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be honored and must not
    be silently downgraded to a fresh session."""
    pass


def handle_streamable_http_request(
    session_id: str | None,
    last_event_id: int | None,
    session_store,          # resolves session_id -> Session | None
    event_buffer,           # Session -> contiguous range (lo, hi) or None
    mint_new_session,       # () -> Session
) -> tuple[str, int]:
    """Returns (session_id, http_status). Enforces the resume-vs-fresh boundary."""

    # Fresh client: no session id at all. Last-Event-ID is meaningless here.
    if session_id is None:
        sess = mint_new_session()
        return sess.id, 200

    sess = session_store.get(session_id)

    # Reaped session: positive evidence of a mid-session client.
    # Do NOT mint a new session under this request.
    if sess is None:
        raise SessionResumptionError(
            f"session {session_id} was reaped; client must re-derive state, "
            f"not continue under a new session"
        )

    if last_event_id is None:
        # Session live, no resume requested: continue normally.
        return sess.id, 200

    rng = event_buffer.range_for(sess)

    # Client claims to have seen an event the server never emitted.
    if rng is None or last_event_id > rng.hi:
        raise SessionResumptionError(
            f"Last-Event-ID {last_event_id} exceeds highest emitted {rng.hi if rng else 'none'}"
        )

    # Contiguity check: the buffer must cover (last_event_id, hi] with no gap.
    if not rng.covers_contiguous(last_event_id + 1, rng.hi):
        raise SessionResumptionError(
            f"event buffer gap for session {session_id} in "
            f"({last_event_id}, {rng.hi}]; replay would skip a tool_result"
        )

    # Safe to resume.
    return sess.id, 200
