# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-sse-resumption-gap-when-an-mcp-streamable-http-session-is-handed-off-mid-keepalive.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-sse-resumption-gap-when-an-mcp-streamable-http-session-is-handed-off-mid-keepalive.warrant.json
# Markdown SHA-256:   5e30cb4e1acd2e88de6ecce00cfa30f20f85e3bb6c46d478b7f04e33877a27d5
# Code AST SHA-256:   6a2cc8df98ce50e6ab4985eec589b09a701c9dad5a4c20e9becfd256bf299196
# Verified Classes:   ResumptionGapError, SseEvent, ResumptionValidator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionGapError(RuntimeError):
    """Raised when an SSE resumption cannot be proven contiguous."""
    pass


@dataclass
class SseEvent:
    id: int
    is_keepalive: bool = False


class ResumptionValidator:
    """Client-side guard against silent SSE-resumption gaps during MCP handoff."""

    def __init__(self, last_event_id: int, keepalive_interval_s: float):
        self.last_event_id = last_event_id
        self.keepalive_interval_s = keepalive_interval_s
        self.seconds_since_semantic = 0.0
        self.pending_tool_call: Optional[str] = None

    def on_event(self, ev: SseEvent) -> None:
        if ev.is_keepalive:
            self.seconds_since_semantic += self.keepalive_interval_s
            if (self.pending_tool_call is not None
                    and self.seconds_since_semantic >= 2 * self.keepalive_interval_s):
                # Keepalives healthy but no semantic event for an outstanding call:
                # completion notification may be in a silent gap. Do not trust it.
                raise ResumptionGapError(
                    f"keepalive-only window exceeds bound while "
                    f"{self.pending_tool_call!r} outstanding; completion may be lost"
                )
            return

        if ev.id <= self.last_event_id:
            raise ResumptionGapError(
                f"non-monotonic event id {ev.id} <= cursor {self.last_event_id}"
            )
        if ev.id > self.last_event_id + 1:
            raise ResumptionGapError(
                f"gap detected: cursor {self.last_event_id}, next event {ev.id}; "
                f"events in ({self.last_event_id}, {ev.id}) were never delivered"
            )
        self.last_event_id = ev.id
        self.seconds_since_semantic = 0.0
        self.pending_tool_call = None


def establish_stream(cursor: int, server_max_contiguous: Optional[int]) -> int:
    """Server-side warrant: replay-or-refuse, never accept-and-continue."""
    if server_max_contiguous is None:
        raise ResumptionGapError(
            f"server cannot serve Last-Event-ID={cursor}: no durable event log"
        )
    if server_max_contiguous < cursor:
        raise ResumptionGapError(
            f"server max contiguous {server_max_contiguous} < requested cursor {cursor}"
        )
    return cursor
