# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-mcp-tool-call-state-when-a-resumable-sse-stream-is-upgraded-to-websocket-mid-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-mcp-tool-call-state-when-a-resumable-sse-stream-is-upgraded-to-websocket-mid-negotiation.warrant.json
# Markdown SHA-256:   50170e61ba62941ac8bb12bc21beba8dec94e716b48c3b6087c6dfda503cddd9
# Code AST SHA-256:   9bb4718a1e162408fb89ba4fe2ace5beedb8630c189f6ec2a670096e2ec8b14a
# Verified Classes:   TransportEpochDesyncError, SessionLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TransportEpochDesyncError(RuntimeError):
    """Raised when a client's Last-Event-ID cannot be placed in the server's
    current session log — typically because an SSE->WebSocket upgrade
    renumbered the event stream and the client's cursor is from the prior epoch."""


@dataclass
class SessionLog:
    session_id: str
    head: int = 0          # session-scoped monotonic counter, survives epochs
    epoch: str = "sse"     # current transport epoch label

    def next_id(self) -> int:
        self.head += 1
        return self.head


def resume_stream(log: SessionLog, last_event_id: int | None) -> int:
    """Return the id from which to replay. Must NOT replay from head on a
    desynced cursor — that silently duplicates in-flight tools/call frames."""
    if last_event_id is None:
        return log.head  # fresh client, no replay

    if last_event_id > log.head:
        # Cursor is ahead of the session log. In a monotonic session-scoped
        # counter this is impossible; it means the client is from a different
        # epoch (e.g. a WebSocket-phase id presented after an SSE re-establish)
        # or a stale session. Refuse rather than guess.
        raise TransportEpochDesyncError(
            f"session={log.session_id} epoch={log.epoch} "
            f"last_event_id={last_event_id} head={log.head}: "
            f"cursor outside contiguous log; refusing head-replay"
        )

    if last_event_id < log.head - 1_000:
        # Cursor is far behind; replay window exceeded. Explicit failure is
        # safer than a partial replay that may drop a pending tools/call.
        raise TransportEpochDesyncError(
            f"session={log.session_id} last_event_id={last_event_id} "
            f"head={log.head}: replay window exceeded"
        )

    return last_event_id


def upgrade_transport(log: SessionLog, to_epoch: str) -> dict:
    """Upgrade SSE->WS while preserving the session-scoped id counter."""
    if to_epoch == log.epoch:
        raise TransportEpochDesyncError(
            f"session={log.session_id}: upgrade to identical epoch {to_epoch!r}"
        )
    prior = log.epoch
    cursor = log.head
    log.epoch = to_epoch
    return {"from": prior, "to": to_epoch, "cursor": cursor}
