# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-after-a-server-initiated-sse-drop-without-replaying-the-missed-event-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-after-a-server-initiated-sse-drop-without-replaying-the-missed-event-window.warrant.json
# Markdown SHA-256:   f6b6dc7202d18b65e7ba8a5e864d6ab78311828277f0052178e1dc55be17132d
# Code AST SHA-256:   9596c871cca58d8f5fe0c4ae9748d6d72ff9db4225a405d682bbfd1091744302
# Verified Classes:   ResumptionGapError, ReconnectObservation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ResumptionGapError(RuntimeError):
    """Raised when an SSE reconnect cannot prove event-window continuity.

    Signals that the client must re-establish the MCP session rather than
    resume, because events between Last-Event-ID and the first event on the
    reconnected stream are unaccounted for.
    """


@dataclass(frozen=True)
class ReconnectObservation:
    last_event_id: int            # last event the client fully parsed AND durably applied
    first_event_id_on_reconnect: Optional[int]  # None if stream opened but emitted nothing yet
    disconnect_duration_s: Optional[float]      # None if clock unreliable
    advertised_retention_ttl_s: Optional[float] # None if server advertised no retention metadata


def classify_reconnect(obs: ReconnectObservation) -> str:
    """Return 'resume' or 'reestablish'. 'unknown' MUST collapse to 'reestablish'."""
    # Retention TTL bound: if we were disconnected longer than the server retains, gap is certain.
    if obs.advertised_retention_ttl_s is None or obs.disconnect_duration_s is None:
        return "reestablish"
    if obs.disconnect_duration_s > obs.advertised_retention_ttl_s:
        return "reestablish"

    # Monotonic dense-ID continuity check.
    if obs.first_event_id_on_reconnect is None:
        # Stream opened, no events yet. Cannot prove continuity. Do not resume.
        return "reestablish"
    if obs.first_event_id_on_reconnect != obs.last_event_id + 1:
        # Either a gap (missed events) or a duplicate (replay of already-applied event).
        return "reestablish"

    return "resume"


def apply_reconnect(obs: ReconnectObservation) -> str:
    decision = classify_reconnect(obs)
    if decision == "reestablish":
        # Only raise when a gap is *provable*; unknown collapses silently to reestablish
        # by the caller, but we surface the provable-gap case loudly for observability.
        if (
            obs.first_event_id_on_reconnect is not None
            and obs.first_event_id_on_reconnect > obs.last_event_id + 1
        ):
            missed = obs.first_event_id_on_reconnect - obs.last_event_id - 1
            raise ResumptionGapError(
                f"SSE resumption gap: {missed} event(s) in "
                f"({obs.last_event_id}, {obs.first_event_id_on_reconnect}) "
                f"were not replayed; server retention TTL="
                f"{obs.advertised_retention_ttl_s}s, disconnect="
                f"{obs.disconnect_duration_s}s. Re-establish session; invalidate "
                f"tool/resource schema caches; re-issue in-flight requests."
            )
    return decision


# Example trace: the observed failure.
try:
    apply_reconnect(
        ReconnectObservation(
            last_event_id=4471,
            first_event_id_on_reconnect=4489,   # server aged out 4472..4488
            disconnect_duration_s=61.0,
            advertised_retention_ttl_s=30.0,
        )
    )
except ResumptionGapError as e:
    # Correct response: DELETE session, initialize, re-fetch tools/list & resources/list.
    print(f"RE-ESTABLISH: {e}")
