# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-against-a-re-established-sse-session-id-that-the-server-has-already-garbage-collected.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-against-a-re-established-sse-session-id-that-the-server-has-already-garbage-collected.warrant.json
# Markdown SHA-256:   f6d9fd1c4d24ed6305ac7dac803efd5f527f888c6eeb3816d89e36848767680a
# Code AST SHA-256:   77b63039d627fe3fc71a5b25617d5b21e2601e106fd617ea774b1655bb7debb1
# Verified Classes:   StreamResumptionError, ResumeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StreamResumptionError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven continuous
    with the stream the client last observed."""


@dataclass
class ResumeState:
    session_id: str
    last_event_id: int
    incarnation: str | None


def verify_resumption(state: ResumeState, response_incarnation: str | None,
                      first_event_id: int | None) -> None:
    """Validate that a 200-OK reconnect actually continues the prior stream.

    Must be called before any event from the new stream is consumed or
    deduplicated. Raises if continuity cannot be established.
    """
    if first_event_id is None:
        # Stream opened but delivered nothing; cannot confirm continuity.
        raise StreamResumptionError(
            f"session {state.session_id}: stream opened with no events; "
            f"cannot confirm resumption past Last-Event-ID={state.last_event_id}"
        )

    if response_incarnation is not None and state.incarnation is not None:
        if response_incarnation != state.incarnation:
            raise StreamResumptionError(
                f"session {state.session_id}: stream incarnation rotated "
                f"({state.incarnation} -> {response_incarnation}); "
                f"event IDs are not comparable, full re-initialize required"
            )

    if first_event_id <= state.last_event_id:
        raise StreamResumptionError(
            f"session {state.session_id}: non-monotonic event ID on resume "
            f"(first_new={first_event_id} <= last_seen={state.last_event_id}); "
            f"server likely minted a fresh stream under a stale session — "
            f"refusing to apply dedup filter over a gap"
        )
