# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-resumption-gap-in-mcp-http-native-transport-when-server-initiated-sse-reconnection-silently-loses-in-flight-events.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-resumption-gap-in-mcp-http-native-transport-when-server-initiated-sse-reconnection-silently-loses-in-flight-events.warrant.json
# Markdown SHA-256:   37a8f689e3527ee2cb00763cf7f75187c249374de917966ec4aecdc26ed5db5d
# Code AST SHA-256:   24a6535ccd980758b576b4d564d92a986e9475be17420fcb6ba9892fcfaeb91a
# Verified Classes:   ResumptionGapError, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ResumptionGapError(RuntimeError):
    """Raised when an SSE resume cannot prove event continuity."""
    pass


@dataclass
class ResumeState:
    last_seen_id: str          # id the client sent as Last-Event-ID
    first_received_id: str     # first id observed after reconnect
    numbering: str = "monotonic_int"  # server's id contract


_INT_RE = re.compile(r"^\d+$")


def detect_resumption_gap(state: ResumeState) -> None:
    """
    Verify that the resume did not silently skip events.

    Raises ResumptionGapError if continuity cannot be proven. A caller that
    catches this MUST enter reconciliation rather than trusting the stream.
    """
    if not state.last_seen_id or not state.first_received_id:
        raise ResumptionGapError(
            f"resume without id evidence: last={state.last_seen_id!r} "
            f"first={state.first_received_id!r}; continuity unprovable"
        )

    if state.numbering == "monotonic_int":
        if not (_INT_RE.match(state.last_seen_id) and _INT_RE.match(state.first_received_id)):
            raise ResumptionGapError(
                f"non-integer ids under monotonic contract: "
                f"{state.last_seen_id!r} -> {state.first_received_id!r}"
            )
        last = int(state.last_seen_id)
        first = int(state.first_received_id)
        if first != last + 1:
            raise ResumptionGapError(
                f"resumption gap: expected id {last + 1}, received {first} "
                f"({first - last - 1} event(s) lost in disconnect window)"
            )
        return

    # opaque ids: continuity cannot be established from the id alone
    raise ResumptionGapError(
        f"opaque id contract {state.numbering!r}: cannot prove {state.last_seen_id!r} "
        f"-> {state.first_received_id!r} is contiguous; reconcile application state"
    )


def on_reconnect(state: ResumeState) -> str:
    try:
        detect_resumption_gap(state)
        return "resumed"
    except ResumptionGapError as exc:
        # Do NOT raise-and-forget: transition to reconciliation.
        return f"reconcile: {exc}"
