# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-sse-replay-and-websocket-resumption-when-an-mcp-session-upgrades-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-sse-replay-and-websocket-resumption-when-an-mcp-session-upgrades-mid-stream.warrant.json
# Markdown SHA-256:   4b139de4b02378e7998b2f61ee27197613b696ccd96410cd434080a02887c5bf
# Code AST SHA-256:   b239f2706e3ec3c3927820c12db36dcbc127a716faa9c981a8750f0323edff44
# Verified Classes:   CursorHandoffError, SessionEvent, SessionCursor
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class CursorHandoffError(RuntimeError):
    """Raised when an SSE->WebSocket upgrade breaks the session event-cursor invariant."""
    pass


@dataclass
class SessionEvent:
    session_id: str
    event_id: int
    epoch: str  # transport epoch: "sse" or "ws:<conn_id>"


@dataclass
class SessionCursor:
    session_id: str
    last_event_id: int = 0
    epoch: str = "sse"
    gap_buffer: list = field(default_factory=list)


def negotiate_upgrade(cursor: SessionCursor, ws_epoch: str,
                      gap_events: list, ws_first_event_id: int) -> SessionCursor:
    """
    Enforce the cursor-handoff contract at the server boundary.

    Invariants:
      - ws_first_event_id MUST equal cursor.last_event_id + 1 (no reset, no gap).
      - Every gap event MUST be buffered and drained in order.
      - The new epoch MUST be recorded so the client can distinguish replays.
    """
    expected_first = cursor.last_event_id + 1

    if ws_first_event_id != expected_first:
        raise CursorHandoffError(
            f"WS cursor reset on session {cursor.session_id}: "
            f"expected first event_id={expected_first}, got {ws_first_event_id}. "
            f"Upgrade is a state transfer, not a new session."
        )

    # Gap window must be accounted for: events emitted between SSE freeze and 101.
    for gap_ev in gap_events:
        if gap_ev.session_id != cursor.session_id:
            raise CursorHandoffError(
                f"Gap event belongs to foreign session {gap_ev.session_id}"
            )
        if gap_ev.event_id != cursor.last_event_id + 1:
            raise CursorHandoffError(
                f"Gap window out of order: expected {cursor.last_event_id + 1}, "
                f"got {gap_ev.event_id}"
            )
        cursor.gap_buffer.append(gap_ev)
        cursor.last_event_id = gap_ev.event_id

    if cursor.last_event_id + 1 != ws_first_event_id:
        raise CursorHandoffError(
            f"Gap buffer did not close the window: last_event_id="
            f"{cursor.last_event_id}, ws_first={ws_first_event_id}"
        )

    cursor.epoch = ws_epoch
    return cursor


def client_accept(client_cursor: SessionCursor, incoming: SessionEvent) -> bool:
    """
    Client-side dedup: monotonic within inherited epoch, reject stale replays.
    """
    if incoming.session_id != client_cursor.session_id:
        raise CursorHandoffError(
            f"Event for foreign session {incoming.session_id}"
        )
    if incoming.event_id <= client_cursor.last_event_id:
        # Replay of an already-delivered event: drop, do not re-execute.
        return False
    if incoming.event_id != client_cursor.last_event_id + 1:
        raise CursorHandoffError(
            f"Client cursor gap: expected {client_cursor.last_event_id + 1}, "
            f"got {incoming.event_id}. Transport lost events; do not re-issue tool."
        )
    client_cursor.last_event_id = incoming.event_id
    client_cursor.epoch = incoming.epoch
    return True


# --- Demonstration of the failure trace ---
if __name__ == "__main__":
    cur = SessionCursor(session_id="s-1", last_event_id=47, epoch="sse")
    gap = [SessionEvent("s-1", 48, "sse"), SessionEvent("s-1", 49, "sse")]

    # Correct upgrade: inherits cursor, drains gap, starts at 50.
    negotiate_upgrade(cur, "ws:conn-a", gap, ws_first_event_id=50)
    assert cur.last_event_id == 49 and cur.epoch == "ws:conn-a"

    # Buggy upgrade: WS handler reset its counter to 1.
    try:
        bad = SessionCursor(session_id="s-2", last_event_id=47, epoch="sse")
        negotiate_upgrade(bad, "ws:conn-b", gap_events=[], ws_first_event_id=1)
    except CursorHandoffError as e:
        print(f"[BLOCKED] {e}")
