# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-sse-resumption-gaps-in-mcp-streamable-http-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-sse-resumption-gaps-in-mcp-streamable-http-transport.warrant.json
# Markdown SHA-256:   23606957c49445ca4e064b50dd9b9f3efdbcd141ca90a66b157bbbf478183ac0
# Code AST SHA-256:   69c9f5a1410fbd851bc8307e0af4f1f9e38988135fa71ef2b1cb9d1fd9c0d8c3
# Verified Classes:   ResumptionGap, ReconnectResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ResumptionGap(RuntimeError):
    """Raised when an SSE reconnect does not resume at last_seen_id + 1."""

    def __init__(self, last_seen_id: int, first_replayed_id: int, session_id: str):
        self.last_seen_id = last_seen_id
        self.first_replayed_id = first_replayed_id
        self.session_id = session_id
        self.gap_size = first_replayed_id - last_seen_id - 1
        super().__init__(
            f"SSE resumption gap on session {session_id}: "
            f"expected id {last_seen_id + 1}, got {first_replayed_id} "
            f"({self.gap_size} events dropped)"
        )


@dataclass
class ReconnectResult:
    session_id: str
    http_status: int
    first_event_id: int | None
    is_stateless_server: bool


def verify_resumption(
    last_seen_id: int,
    result: ReconnectResult,
    *,
    allow_advisory_only: bool = False,
    dropped_events_are_advisory: bool = False,
) -> None:
    """Validate that a streamable-HTTP SSE reconnect is contiguous.

    Raises ResumptionGap if the first replayed event does not continue
    the ID space at last_seen_id + 1, unless the caller has independently
    established that every dropped event was a non-state-mutating advisory
    AND has opted into tolerating that specific case.
    """
    if result.http_status != 200:
        # 404 on session is the *good* failure: explicit and recoverable.
        raise ResumptionGap(last_seen_id, -1, result.session_id)

    if result.first_event_id is None:
        # Empty stream on reconnect: no evidence of contiguity.
        raise ResumptionGap(last_seen_id, last_seen_id, result.session_id)

    if result.is_stateless_server and result.first_event_id <= last_seen_id:
        # Stateless restart: ID space reset. Never trust the cursor.
        raise ResumptionGap(last_seen_id, result.first_event_id, result.session_id)

    if result.first_event_id == last_seen_id + 1:
        return  # contiguous; safe to continue

    if (
        allow_advisory_only
        and dropped_events_are_advisory
        and result.first_event_id > last_seen_id + 1
    ):
        return  # tolerated gap, caller has vouched for advisory-only

    raise ResumptionGap(last_seen_id, result.first_event_id, result.session_id)
