# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-of-an-ordered-event-log-rather-than-a-reconnection-to-a-li.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-of-an-ordered-event-log-rather-than-a-reconnection-to-a-li.warrant.json
# Markdown SHA-256:   a5b40a4c35698c3cc112b8175d7c3ad0bdff9200190725ed037469a046d52cbc
# Code AST SHA-256:   e17153e8b25dfd425d22d442633d52c8bacd851cebf656c82e764bd0ba6fc640
# Verified Classes:   SessionResumeGapError, SessionState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SessionResumeGapError(RuntimeError):
    """Raised when a resumed MCP session's first event id is not contiguous
    with the client's durably committed checkpoint while a request is in flight."""


@dataclass
class SessionState:
    committed_event_id: int = 0
    in_flight_request_ids: set = field(default_factory=set)
    # Results are only persisted after the terminal event is observed;
    # the cursor advances only after persistence. Order matters.
    persisted_results: dict = field(default_factory=dict)


def resume_session(state: SessionState, first_received_event_id: int) -> None:
    """Validate that a resumed stream is a contiguous replay from our checkpoint.

    Cursor semantics (no in-flight requests) tolerate any starting id.
    Replay semantics (in-flight requests) require exact contiguity.
    """
    if not state.in_flight_request_ids:
        # Cursor semantics: nothing to corrupt, accept any resume point.
        state.committed_event_id = first_received_event_id - 1
        return

    expected = state.committed_event_id + 1
    if first_received_event_id != expected:
        raise SessionResumeGapError(
            f"Resume gap detected: committed_event_id={state.committed_event_id}, "
            f"expected first event id {expected}, received {first_received_event_id}. "
            f"In-flight requests {sorted(state.in_flight_request_ids)} cannot be "
            f"safely reconstructed; aborting rather than synthesizing a result."
        )


def apply_terminal_event(
    state: SessionState, event_id: int, request_id: str, payload: dict
) -> None:
    """Apply a terminal result/error event and advance the commit cursor.

    Persist the result BEFORE advancing committed_event_id. A crash between
    the two must leave the cursor behind the event so replay redelivers it.
    """
    if request_id not in state.in_flight_request_ids:
        raise SessionResumeGapError(
            f"Terminal event {event_id} for unknown request {request_id}; "
            f"session state is inconsistent with the server's event log."
        )

    # Persist first (simulated here as an atomic dict write).
    state.persisted_results[request_id] = payload

    # Only now advance the cursor and clear the in-flight marker.
    state.committed_event_id = event_id
    state.in_flight_request_ids.discard(request_id)
