# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-to-websocket-upgrade-as-a-session-resumption-boundary-rather-than-a-transport-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-to-websocket-upgrade-as-a-session-resumption-boundary-rather-than-a-transport-swap.warrant.json
# Markdown SHA-256:   47840047997654bbc8a36b7c574648cf4c95e42d0fcf16771777ab5ddcf0fada
# Code AST SHA-256:   7cc45a8df2498a8eeb4a8a270ccd2027cb0cfc403c402bef866466de8d1fca82
# Verified Classes:   ResumptionBoundaryError, Event, SessionLog, UpgradeResumptionGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ResumptionBoundaryError(RuntimeError):
    """Raised when an SSE->WebSocket upgrade crosses a session-resumption
    boundary without preserving sequence continuity."""


@dataclass
class Event:
    seq: int
    payload: dict


@dataclass
class SessionLog:
    session_id: str
    events: list = field(default_factory=list)

    def append(self, payload: dict) -> Event:
        ev = Event(seq=(self.events[-1].seq + 1) if self.events else 1, payload=payload)
        self.events.append(ev)
        return ev

    def after(self, cursor: int) -> list:
        return [e for e in self.events if e.seq > cursor]


class UpgradeResumptionGuard:
    """Enforces the invariant: no live dispatch on the new leg until
    replay of events after the client's Last-Event-ID is drained and
    the watermark is re-established with a sequenced frame.
    """

    def __init__(self, log: SessionLog, last_event_id: int, drain_timeout_s: float = 0.5):
        self.log = log
        self.cursor = last_event_id
        self.drain_timeout_s = drain_timeout_s
        self._drained = False
        self._deadline = time.monotonic() + drain_timeout_s

    def on_upgrade_accept(self, server_advertised_drain: bool) -> None:
        if not server_advertised_drain:
            # Server sent a bare 101; we cannot trust live frames.
            raise ResumptionBoundaryError(
                f"upgrade for session {self.log.session_id} accepted without replay-drain "
                f"advertisement; treating as boundary and refusing live dispatch"
            )
        pending = self.log.after(self.cursor)
        for ev in pending:
            self._consume_sequenced(ev)
        self._drained = True

    def on_frame(self, frame: dict) -> Optional[dict]:
        seq = frame.get("id")
        if seq is None:
            if not self._drained:
                # Un-sequenced live frame before drain: boundary crossed.
                raise ResumptionBoundaryError(
                    f"un-sequenced frame on session {self.log.session_id} before replay drain; "
                    f"event loss or duplicate-apply risk at cursor {self.cursor}"
                )
            # Post-drain un-sequenced frame: accept but do not advance watermark.
            return frame.get("payload")
        if seq <= self.cursor:
            # Duplicate replay; safe to drop.
            return None
        if seq != self.cursor + 1:
            raise ResumptionBoundaryError(
                f"sequence gap on session {self.log.session_id}: expected {self.cursor + 1}, got {seq}"
            )
        self.cursor = seq
        return frame.get("payload")

    def _consume_sequenced(self, ev: Event) -> None:
        if ev.seq != self.cursor + 1:
            raise ResumptionBoundaryError(
                f"replay gap on session {self.log.session_id}: expected {self.cursor + 1}, got {ev.seq}"
            )
        self.cursor = ev.seq

    def assert_drained(self) -> None:
        if not self._drained and time.monotonic() > self._deadline:
            raise ResumptionBoundaryError(
                f"replay drain timed out for session {self.log.session_id} at cursor {self.cursor}; "
                f"downgrade to SSE resumption required"
            )
