# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-on-a-streamable-http-reconnect-when-the-server-replays-an-sse-event-the-client-already-consumed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-on-a-streamable-http-reconnect-when-the-server-replays-an-sse-event-the-client-already-consumed.warrant.json
# Markdown SHA-256:   b48752d425729a16ef16f53d559868a65109655e97129ebd0e71acc58c8de4fb
# Code AST SHA-256:   c2df15c6665e62f1cd0a9b746003779e491b9dee669b8abb8171bd3192fe50ef
# Verified Classes:   SessionResumptionDivergence, CommittedEffect, StreamableHttpSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import threading
from dataclasses import dataclass, field
from typing import Any


class SessionResumptionDivergence(RuntimeError):
    """Raised when a replayed SSE event would double-commit a JSON-RPC effect."""


@dataclass
class CommittedEffect:
    session_id: str
    jsonrpc_id: str
    event_id: int
    result: Any


@dataclass
class StreamableHttpSession:
    session_id: str
    last_committed_event_id: int = 0
    committed: dict[str, CommittedEffect] = field(default_factory=dict)
    _lock: threading.Lock = field(default_factory=threading.Lock)

    def commit_effect(self, jsonrpc_id: str, event_id: int, result: Any) -> None:
        with self._lock:
            if event_id <= self.last_committed_event_id:
                raise SessionResumptionDivergence(
                    f"event {event_id} <= committed watermark "
                    f"{self.last_committed_event_id} for session {self.session_id}"
                )
            if jsonrpc_id in self.committed:
                prior = self.committed[jsonrpc_id]
                raise SessionResumptionDivergence(
                    f"duplicate commit for jsonrpc_id={jsonrpc_id}: "
                    f"prior event {prior.event_id}, new event {event_id}"
                )
            self.committed[jsonrpc_id] = CommittedEffect(
                session_id=self.session_id,
                jsonrpc_id=jsonrpc_id,
                event_id=event_id,
                result=result,
            )
            self.last_committed_event_id = event_id

    def resume_cursor(self) -> str:
        # Exclusive replay semantics: server must deliver strictly after this id.
        return str(self.last_committed_event_id)


def handle_replayed_event(
    session: StreamableHttpSession,
    event_id: int,
    jsonrpc_id: str,
    payload: Any,
) -> None:
    """Called by the SSE reader on every frame, including replayed ones."""
    if event_id <= session.last_committed_event_id:
        # Boundary event replayed by a server using inclusive (>=) semantics.
        # Do not re-dispatch; the effect is already in context.
        if jsonrpc_id in session.committed:
            return
        raise SessionResumptionDivergence(
            f"replayed event {event_id} has no committed effect for "
            f"jsonrpc_id={jsonrpc_id}; session state is inconsistent"
        )
    if jsonrpc_id in session.committed:
        # Same jsonrpc_id under a *new* event id: server re-executed the tool.
        raise SessionResumptionDivergence(
            f"server re-executed jsonrpc_id={jsonrpc_id} as event {event_id}; "
            f"prior commit at event {session.committed[jsonrpc_id].event_id}"
        )
    session.commit_effect(jsonrpc_id, event_id, payload)
