# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-event-id-epochs-across-an-mcp-streamable-http-session-resumption-when-the-transport-upgrades-to-websocket-mid-too.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-event-id-epochs-across-an-mcp-streamable-http-session-resumption-when-the-transport-upgrades-to-websocket-mid-too.warrant.json
# Markdown SHA-256:   9bed4822c1618692f2351236addb79d87a0e833b50949c7d32eeb83e3ff74a2e
# Code AST SHA-256:   0f5b732d0a1aafc4e1a939a636a91cebbc1d7fcf635fad716c6c347cbe622a6c
# Verified Classes:   ResumptionEpochViolation, Cursor, EpochAwareResumer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionEpochViolation(RuntimeError):
    """Raised when SSE event-ID continuity cannot be proven across a transport upgrade."""


@dataclass(frozen=True)
class Cursor:
    session_id: str
    epoch: str
    last_event_id: int


class EpochAwareResumer:
    def __init__(self) -> None:
        self._applied: set[tuple[str, str, int]] = set()
        self._cursor: Cursor | None = None

    def apply(self, session_id: str, epoch: str, event_id: int, payload: dict) -> bool:
        key = (session_id, epoch, event_id)
        if key in self._applied:
            return False  # exactly-once: duplicate replay suppressed
        self._applied.add(key)
        self._cursor = Cursor(session_id, epoch, event_id)
        return True

    def on_upgrade(self, server_epoch: str, server_high_water: int,
                   replay_range: tuple[int, int] | None) -> None:
        if self._cursor is None:
            raise ResumptionEpochViolation("cannot upgrade with no applied cursor")
        if self._cursor.last_event_id > server_high_water:
            # Client applied events the server disclaims: split brain, not "ahead".
            raise ResumptionEpochViolation(
                f"cursor inversion: applied {self._cursor.last_event_id} "
                f"> server high-water {server_high_water}"
            )
        if server_epoch != self._cursor.epoch:
            if replay_range is None:
                raise ResumptionEpochViolation(
                    f"epoch {self._cursor.epoch} -> {server_epoch} with no replay window"
                )
            lo, hi = replay_range
            if not (lo <= self._cursor.last_event_id + 1 <= hi + 1):
                raise ResumptionEpochViolation(
                    f"replay window {replay_range} does not cover "
                    f"last_applied+1={self._cursor.last_event_id + 1}"
                )
            # Drain replay, then commit to new epoch explicitly.
            self._cursor = Cursor(self._cursor.session_id, server_epoch,
                                  self._cursor.last_event_id)
