# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-text-event-stream-reconnect-as-a-new-session-rather-than-a-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-text-event-stream-reconnect-as-a-new-session-rather-than-a-resumption.warrant.json
# Markdown SHA-256:   f1d46b8b639eb6c1f3bfc33441dbf93ce892b2023171595076b59b223867c686
# Code AST SHA-256:   3e6bd3ad97eb2a0c4703c2f747b255afd39051546872da9b2576f0e2b16717bb
# Verified Classes:   ResumptionGapError, StreamResumeGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StreamResumeGuard:
    """Validates that an MCP HTTP SSE reconnect is a true resumption,
    not a silent session re-instantiation."""

    def __init__(self, session_id: str, last_event_id: int):
        self.session_id = session_id
        self.last_event_id = last_event_id
        self.awaiting_first_event = True

    def on_reconnect_response(self, resp_session_id: str, status: int) -> None:
        if status != 200:
            # Server explicitly refused resumption; safe to re-instantiate.
            raise ResumptionGapError(
                f"server refused resume for {self.session_id}: status={status}"
            )
        if resp_session_id != self.session_id:
            # Server minted a new session without being asked.
            raise ResumptionGapError(
                f"session identity changed on resume: "
                f"sent={self.session_id} got={resp_session_id}"
            )

    def on_first_event(self, event_id: int) -> None:
        if not self.awaiting_first_event:
            return
        self.awaiting_first_event = False
        if event_id <= self.last_event_id:
            # Counter reset or replay window lost: this is a new event log,
            # not a continuation. Must re-instantiate and reconcile.
            raise ResumptionGapError(
                f"event id regressed on resume: sent Last-Event-ID="
                f"{self.last_event_id} got first id={event_id}; "
                f"treating as new session and reconciling state"
            )
        if event_id != self.last_event_id + 1:
            # Monotonic but with a gap the client cannot fill.
            raise ResumptionGapError(
                f"unfillable event gap: expected {self.last_event_id + 1}, "
                f"got {event_id}; {event_id - self.last_event_id - 1} events lost"
            )
        # Continuity proven: safe to continue as the same session.
