# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-server-side-session-eviction-and-silently-adopts-a-new-session-s-event-ids.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-server-side-session-eviction-and-silently-adopts-a-new-session-s-event-ids.warrant.json
# Markdown SHA-256:   97c250b72d65d76266fdb1bb6f313945b1f7310fc920b31892fa50501cde231e
# Code AST SHA-256:   04ae14b79a0560e427fa5c85caaae35a1026bec0537fcaf3e6957a3baf549403
# Verified Classes:   SessionForkError, SSEResumeGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionForkError(RuntimeError):
    """Raised when a stream event arrives under a different session than the
    cursor was minted under, i.e. a silent resume-vs-fork ambiguity."""
    pass


class SSEResumeGuard:
    def __init__(self, session_id: str, cursor: int):
        self.session_id = session_id
        self.cursor = cursor

    def on_response_headers(self, resp_session_id: str) -> None:
        # Invariant C: adopt session identity on EVERY response, including reconnects.
        if resp_session_id != self.session_id:
            # Fork detected: cursor is meaningless against the new sequence.
            self.session_id = resp_session_id
            self.cursor = -1

    def on_event(self, event_session_id: str, event_id: int) -> bool:
        # Invariant A + B: cursor is only comparable within its minting session.
        if event_session_id != self.session_id:
            raise SessionForkError(
                f"event from session {event_session_id!r} but active session is "
                f"{self.session_id!r}; cursor {self.cursor} is invalid across "
                f"session boundary — re-initialize, do not drop"
            )
        if event_id <= self.cursor:
            # Genuine replay within the same session: safe to drop.
            return False
        self.cursor = event_id
        return True


def handle_reconnect(guard: SSEResumeGuard, resp_headers: dict, first_event: dict) -> bool:
    guard.on_response_headers(resp_headers["Mcp-Session-Id"])
    try:
        return guard.on_event(first_event["session"], int(first_event["id"]))
    except SessionForkError as e:
        # Surface loudly; the caller must re-run initialize and re-issue
        # in-flight requests with fresh IDs (server dedup state is gone).
        raise SessionForkError(
            f"resume aborted, falling back to full re-initialization: {e}"
        ) from e
