# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-across-an-sse-to-websocket-upgrade-and-replays-a-stale-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-across-an-sse-to-websocket-upgrade-and-replays-a-stale-last-event-id.warrant.json
# Markdown SHA-256:   ffff8ff438cba4a555aa7e586e3a656cdac104136fb79c73f84c34b74fa07dd1
# Code AST SHA-256:   9d270561408dc89fb731692b173f89142e575a531b19da637edfbda079e96e3e
# Verified Classes:   TransportEpochMismatch, EventLog, MCPSession
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class TransportEpochMismatch(RuntimeError):
    """Raised when a resumption token's transport epoch does not match the
    current transport epoch and the server cannot safely replay the gap."""
    pass


@dataclass
class EventLog:
    """Session-scoped event log. Survives transport re-binding. This is the
    source of truth; transports are views over it."""
    events: list = field(default_factory=list)  # list of (epoch, seq, payload)
    max_retention: int = 1000

    def append(self, epoch: int, seq: int, payload: dict) -> None:
        self.events.append((epoch, seq, payload))
        if len(self.events) > self.max_retention:
            self.events.pop(0)

    def replay_after(self, epoch: int, seq: int) -> list:
        """Return all events strictly after (epoch, seq) in session order.
        Ordering is by session-scoped seq, not by transport arrival."""
        out = []
        for e_epoch, e_seq, payload in self.events:
            if (e_epoch, e_seq) > (epoch, seq):
                out.append(payload)
        return out


@dataclass
class MCPSession:
    session_id: str
    transport_epoch: int = 0
    session_seq: int = 0
    log: EventLog = field(default_factory=EventLog)

    def bind_transport(self) -> int:
        """Called on every transport re-binding (SSE reconnect, WS upgrade).
        Advances the epoch but NOT the seq counter."""
        self.transport_epoch += 1
        return self.transport_epoch

    def emit(self, payload: dict) -> str:
        self.session_seq += 1
        self.log.append(self.transport_epoch, self.session_seq, payload)
        return f"{self.transport_epoch}:{self.session_seq}"


def resume_stream(session: MCPSession, last_event_id: str) -> list:
    """Resume a stream given a Last-Event-ID of the form '<epoch>:<seq>'.

    The critical guardrail: if the token's epoch is older than the current
    transport epoch, we MUST replay from the session log across the epoch
    boundary. If the log cannot cover the gap, we MUST raise an explicit
    error rather than silently returning nothing (which produces the
    deadlock where the client waits forever for an event it already missed).
    """
    try:
        token_epoch_str, token_seq_str = last_event_id.split(":", 1)
        token_epoch = int(token_epoch_str)
        token_seq = int(token_seq_str)
    except (ValueError, AttributeError) as exc:
        raise TransportEpochMismatch(
            f"malformed Last-Event-ID {last_event_id!r}: expected '<epoch>:<seq>'"
        ) from exc

    if token_epoch > session.transport_epoch:
        raise TransportEpochMismatch(
            f"token epoch {token_epoch} is ahead of current transport epoch "
            f"{session.transport_epoch}; client is from a future transport "
            f"binding and cannot be safely resumed"
        )

    if token_epoch < session.transport_epoch:
        # Transport re-based. The only safe behavior is to replay from the
        # session log across the epoch boundary. Verify the log can cover it.
        oldest = session.log.events[0] if session.log.events else None
        if oldest is None or (oldest[0], oldest[1]) > (token_epoch, token_seq):
            raise TransportEpochMismatch(
                f"transport epoch advanced {token_epoch}->{session.transport_epoch} "
                f"and event log cannot cover the gap from ({token_epoch},{token_seq}); "
                f"oldest retained is {oldest[:2] if oldest else None}. "
                f"Client must re-initialize the session, not resume."
            )
        return session.log.replay_after(token_epoch, token_seq)

    # Same epoch: normal in-transport resumption.
    if token_seq > session.session_seq:
        raise TransportEpochMismatch(
            f"token seq {token_seq} exceeds session head {session.session_seq} "
            f"within epoch {token_epoch}; refusing to treat as caught-up"
        )
    return session.log.replay_after(token_epoch, token_seq)


# --- Reproduction of the observed failure ---
if __name__ == "__main__":
    sess = MCPSession(session_id="s-1")
    sess.bind_transport()  # epoch 1: SSE
    for i in range(47):
        sess.emit({"progress": i})
    # client is at "1:47". SSE drops. Upgrade to WebSocket:
    sess.bind_transport()  # epoch 2: WS, seq counter NOT reset

    # A naive server that reset seq on upgrade would now have head=0 and
    # silently return [] for "1:47". The guarded version replays correctly:
    replayed = resume_stream(sess, "1:47")
    assert replayed == [], "nothing new since 1:47"

    # The pending tool result arrives on the new leg:
    new_id = sess.emit({"tool_result": "ok"})  # -> "2:48"
    replayed = resume_stream(sess, "1:47")
    assert replayed == [{"tool_result": "ok"}], replayed

    # Demonstrate the guardrail firing when the log cannot cover the gap:
    sess.log.events.clear()
    try:
        resume_stream(sess, "1:47")
    except TransportEpochMismatch as exc:
        print(f"guardrail fired: {exc}")
