# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-establish-a-streamable-http-mcp-session-after-notification-loss-and-when-may-it-safely-resume-on-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-establish-a-streamable-http-mcp-session-after-notification-loss-and-when-may-it-safely-resume-on-last-event-id.warrant.json
# Markdown SHA-256:   08333699d0422c6294e6b8bb07bccdc0bee9511573be35ffc1d2099ed329fbb3
# Code AST SHA-256:   1fa4fc6501429759f2384774bc73ba9e65da9a0673eaeb37602377ec8c4748b9
# Verified Classes:   SessionTerminatedError, NotificationGapError, SessionState, McpSession, ResumeResult
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SessionTerminatedError(RuntimeError):
    """Raised when the MCP session must be re-initialized before further calls."""


class NotificationGapError(RuntimeError):
    """Raised when the replayed event stream does not continue from Last-Event-ID."""


class SessionState(Enum):
    ALIVE = "alive"
    INTERRUPTED = "interrupted"   # transport drop, session presumed alive
    TERMINATED = "terminated"     # server discarded session; re-init required


@dataclass
class McpSession:
    session_id: str
    last_event_id: int = 0
    state: SessionState = SessionState.ALIVE
    tools_cache_valid: bool = True
    resources_cache_valid: bool = True


@dataclass
class ResumeResult:
    status_code: int
    first_replayed_event_id: Optional[int] = None
    network_error: bool = False


def classify_resume(result: ResumeResult, last_event_id: int) -> SessionState:
    """Map a resume GET outcome to a session state per the decision boundary."""
    if result.network_error:
        return SessionState.INTERRUPTED
    if result.status_code in (404, 410):
        return SessionState.TERMINATED
    if result.status_code == 200:
        # 200 with replayed events must strictly continue the sequence.
        if result.first_replayed_event_id is not None and result.first_replayed_event_id <= last_event_id:
            # Buffer inconsistent: a gap exists that the server did not acknowledge.
            return SessionState.TERMINATED
        return SessionState.ALIVE
    if result.status_code in (502, 503):
        return SessionState.INTERRUPTED
    # Any other status is ambiguous; treat conservatively as terminated.
    return SessionState.TERMINATED


def resume_session(session: McpSession, result: ResumeResult, max_retries: int = 3) -> McpSession:
    """
    Gate every post-drop POST behind a resume GET. If the gate resolves to
    TERMINATED, invalidate notification-derived caches and raise.
    """
    attempts = 0
    while attempts < max_retries:
        state = classify_resume(result, session.last_event_id)
        session.state = state

        if state is SessionState.ALIVE:
            return session

        if state is SessionState.TERMINATED:
            # Invalidate caches derived from the lost notification stream.
            session.tools_cache_valid = False
            session.resources_cache_valid = False
            raise SessionTerminatedError(
                f"Session {session.session_id} terminated at last_event_id="
                f"{session.last_event_id}; re-initialize and reconcile caches "
                f"before issuing further tools/call requests."
            )

        # INTERRUPTED: retry the resume GET, preserving Last-Event-ID.
        attempts += 1
        time.sleep(0.5 * (2 ** attempts))
        # In a real client, re-issue the GET here and refresh `result`.
        # Simulated: give up after retries as an interrupted-but-unresolved state.
        if attempts >= max_retries:
            raise SessionTerminatedError(
                f"Session {session.session_id} resume unresolved after "
                f"{max_retries} retries; refusing to issue POSTs under an "
                f"unverified session."
            )

    raise SessionTerminatedError("unreachable")


def issue_tool_call(session: McpSession, tool_name: str) -> str:
    """POST path. Must not be reachable while the resume gate is unresolved."""
    if session.state is SessionState.TERMINATED:
        raise SessionTerminatedError(
            f"Refusing tools/call '{tool_name}': session {session.session_id} is terminated."
        )
    if session.state is SessionState.INTERRUPTED:
        raise SessionTerminatedError(
            f"Refusing tools/call '{tool_name}': resume gate unresolved for "
            f"session {session.session_id}."
        )
    if not session.tools_cache_valid:
        raise SessionTerminatedError(
            f"Refusing tools/call '{tool_name}': tools cache invalidated by "
            f"notification loss; re-fetch tools/list first."
        )
    return f"ok:{tool_name}"


# --- Demonstration of the failure trace ---
if __name__ == "__main__":
    s = McpSession(session_id="s-7f3a", last_event_id=412)

    # Resume GET hit a replica that never saw the session.
    resume = ResumeResult(status_code=404)
    try:
        resume_session(s, resume)
    except SessionTerminatedError as e:
        print(f"gate closed: {e}")

    # A subsequent POST must be blocked, even though the server would have
    # returned 200 on it (stateless worker). The client-side gate is the guard.
    try:
        issue_tool_call(s, "browser.navigate")
    except SessionTerminatedError as e:
        print(f"post blocked: {e}")

    # The silent-loss variant: a 200 resume whose replay does NOT advance.
    s2 = McpSession(session_id="s-9c01", last_event_id=88)
    resume2 = ResumeResult(status_code=200, first_replayed_event_id=88)
    try:
        resume_session(s2, resume2)
    except SessionTerminatedError as e:
        print(f"gap detected: {e}")
