# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-session-resumption-across-an-sse-to-websocket-upgrade-as-a-state-transfer-hazard-rather-than-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-session-resumption-across-an-sse-to-websocket-upgrade-as-a-state-transfer-hazard-rather-than-a.warrant.json
# Markdown SHA-256:   d2b69d91c18e2ed143b9b5923835cd622afe5b3b7f2857139dcbb30fc2d385dd
# Code AST SHA-256:   71f4178d23885ffec234f08ccc8a9454268101b57e7db07d0a859e4465f7aa45
# Verified Classes:   CursorDivergenceError, SessionResumeGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CursorDivergenceError(RuntimeError):
    """Raised when a transport re-binding delivers an event whose id is not
    contiguous with the last applied id, indicating duplicate replay or a gap."""
    pass


class SessionResumeGuard:
    def __init__(self, session_id: str, idempotent: bool):
        self.session_id = session_id
        self.idempotent = idempotent
        self.last_applied_id = -1
        self.reconciled = False

    def bind_transport(self, transport: str, carried_cursor):
        # Upgrade handshakes commonly omit Last-Event-ID; require it explicitly.
        if transport == "websocket" and carried_cursor is None:
            if not self.idempotent:
                raise CursorDivergenceError(
                    f"WebSocket upgrade for session {self.session_id} carries no "
                    f"cursor; refusing to apply non-idempotent events until reconciled"
                )
        self.reconciled = self.idempotent

    def apply_event(self, event_id: int, effect):
        if event_id <= self.last_applied_id:
            if self.idempotent:
                return  # duplicate replay is a no-op
            raise CursorDivergenceError(
                f"Duplicate event {event_id} after last applied {self.last_applied_id} "
                f"in session {self.session_id}; possible double-application of effect"
            )
        if event_id > self.last_applied_id + 1 and not self.reconciled:
            raise CursorDivergenceError(
                f"Gap: event {event_id} follows {self.last_applied_id} in session "
                f"{self.session_id}; events may have been lost during upgrade"
            )
        effect()
        self.last_applied_id = event_id
