# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-sse-stream-after-the-server-has-already-reaped-the-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-sse-stream-after-the-server-has-already-reaped-the-session.warrant.json
# Markdown SHA-256:   0fc6b58d0bf3cbab56410d1e18bb6e7a53fc8b81fabc606886b21e3831cfdb46
# Code AST SHA-256:   037e654d38f36c2f13a51a362118ca43237016a255a8031d763adcc480ac0305
# Verified Classes:   SessionResumptionError, ReconnectContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class SessionResumptionError(RuntimeError):
    """Raised when a resumption attempt cannot be proven gap-free."""
    pass


@dataclass
class ReconnectContext:
    session_id: Optional[str]
    last_event_id: int
    reconnect_attempt: int
    max_reconnect_horizon_s: float
    session_ttl_s: float


def validate_resumption(
    ctx: ReconnectContext,
    new_session_id: Optional[str],
    first_event_id: int,
) -> str:
    """
    Decide how to treat the first event after a reconnect.

    Returns one of: "resumed", "gap", "reset".
    Raises SessionResumptionError when the case is ambiguous or unsafe.
    """
    # Guard 1: TTL vs reconnect horizon. If the client's backoff can exceed
    # the server's session TTL, resumption is unsound by construction.
    if ctx.max_reconnect_horizon_s >= ctx.session_ttl_s:
        raise SessionResumptionError(
            f"reconnect horizon {ctx.max_reconnect_horizon_s}s >= "
            f"session TTL {ctx.session_ttl_s}s; resumption cannot be guaranteed"
        )

    # Guard 2: explicit session identity change => hard reset.
    if new_session_id is not None and new_session_id != ctx.session_id:
        return "reset"

    # Guard 3: ID regression => counter restart (reset) or duplicate replay.
    # Without a session token we cannot distinguish; treat as reset and force re-sync.
    if first_event_id <= ctx.last_event_id:
        if new_session_id is None:
            raise SessionResumptionError(
                f"event ID regression {first_event_id} <= {ctx.last_event_id} "
                "with no session token; cannot distinguish reset from replay"
            )
        return "reset"

    # Guard 4: gap detection.
    if first_event_id > ctx.last_event_id + 1:
        return "gap"

    return "resumed"


def resume_stream(
    ctx: ReconnectContext,
    new_session_id: Optional[str],
    first_event_id: int,
    status_query,
) -> dict:
    verdict = validate_resumption(ctx, new_session_id, first_event_id)

    if verdict == "resumed":
        return {"action": "continue", "from_event_id": ctx.last_event_id}

    if verdict == "gap":
        # Events were skipped; the stream is not a complete source of truth.
        raise SessionResumptionError(
            f"gap detected: expected {ctx.last_event_id + 1}, got {first_event_id}; "
            "event stream cannot be trusted, re-sync required"
        )

    # verdict == "reset": abandon event stream, re-derive from authoritative status.
    authoritative = status_query()
    if authoritative is None:
        raise SessionResumptionError(
            "session reset with no authoritative status available; "
            "cannot safely resume"
        )
    return {"action": "resync", "state": authoritative}
