# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-replay-gap-as-unrecoverable-rather-than-resumable.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-replay-gap-as-unrecoverable-rather-than-resumable.warrant.json
# Markdown SHA-256:   b4fbc2bf3a698bcdc72b9ae27065e7555d56d960cebd5053294be80923d129d4
# Code AST SHA-256:   5da7e340294e250f24ada424ea33567e9c9ff79fb96d8447d98875db812794cc
# Verified Classes:   UnrecoverableReplayGap, ReconnectContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class UnrecoverableReplayGap(RuntimeError):
    """Raised when an MCP SSE reconnect cannot be proven to have bridged the gap."""
    pass


@dataclass
class ReconnectContext:
    last_seen_id: int
    first_replayed_id: int
    server_events_emitted: int | None  # from status resource; None if not exposed
    replay_window: int | None          # from initialize/resume capability; None if undeclared


def verify_reconnect(ctx: ReconnectContext) -> None:
    """
    Enforce the contiguity-witness invariant. Raises if the resume is unverifiable
    or if the head has advanced past the replay window during the disconnect.
    """
    # Naive contiguity check alone is insufficient and is the trap.
    looks_contiguous = ctx.first_replayed_id == ctx.last_seen_id + 1

    if ctx.server_events_emitted is None or ctx.replay_window is None:
        # Cannot distinguish "replayed from position" from "restarted at head".
        raise UnrecoverableReplayGap(
            f"reconnect at last_seen={ctx.last_seen_id} has no contiguity witness "
            f"(events_emitted={ctx.server_events_emitted}, "
            f"replay_window={ctx.replay_window}); "
            f"naive_contiguous={looks_contiguous} is not sufficient"
        )

    gap = ctx.server_events_emitted - ctx.last_seen_id
    if gap > ctx.replay_window:
        # Head advanced past retention during the disconnect: the missing events
        # are gone, even though first_replayed_id may equal last_seen_id + 1.
        raise UnrecoverableReplayGap(
            f"replay gap overflow: head={ctx.server_events_emitted}, "
            f"last_seen={ctx.last_seen_id}, gap={gap}, window={ctx.replay_window}; "
            f"must re-invoke tool from checkpoint, not resume"
        )

    if not looks_contiguous:
        raise UnrecoverableReplayGap(
            f"non-contiguous resume: first_replayed={ctx.first_replayed_id}, "
            f"expected={ctx.last_seen_id + 1}"
        )


def resume_stream(ctx: ReconnectContext, max_retries: int = 3) -> None:
    for attempt in range(max_retries):
        try:
            verify_reconnect(ctx)
            return
        except UnrecoverableReplayGap:
            if attempt == max_retries - 1:
                raise
            time.sleep(0.5 * (2 ** attempt))
    raise UnrecoverableReplayGap("exhausted resume attempts")
