# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-stream-resumption-has-silently-lost-message-ordering-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-stream-resumption-has-silently-lost-message-ordering-guarantees.warrant.json
# Markdown SHA-256:   76d08c43f4e3412cb145ac36358bd1f406162b9ca75077ff496daf381a2b661e
# Code AST SHA-256:   51ec404fcb82630a9c5d5e5ab7385a28c821256b7682eaae702229b3cea6a3b8
# Verified Classes:   ResumeContiguityError, ReplayWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumeContiguityError(RuntimeError):
    """Raised when a resumed MCP stream cannot be proven contiguous."""
    pass


@dataclass
class ReplayWindow:
    oldest_id: int
    newest_id: int
    events: dict = field(default_factory=dict)  # id -> payload

    def can_serve(self, cursor: int) -> bool:
        # A cursor is servable only if the *next* event after it is retained.
        # Cursor == newest_id means "nothing new yet", which is servable (empty resume).
        return cursor >= self.oldest_id - 1 and cursor <= self.newest_id


def resume_stream(window: ReplayWindow, last_event_id: int) -> dict:
    """Server-side resume. Rejects evicted cursors instead of silently skipping."""
    if not window.can_serve(last_event_id):
        raise ResumeContiguityError(
            f"cursor_evicted: requested Last-Event-ID={last_event_id} "
            f"but retained range is [{window.oldest_id}, {window.newest_id}]; "
            f"refusing to resume from nearest surviving event"
        )
    resumed_from = last_event_id
    first_new_id = last_event_id + 1
    if first_new_id in window.events:
        # Assert the retained window is actually dense at the seam.
        if first_new_id - 1 != resumed_from:
            raise ResumeContiguityError(
                f"seam_gap: expected first event id {resumed_from + 1}, "
                f"got {first_new_id}"
            )
    return {"resumed_from": resumed_from, "first_new_id": first_new_id}


def verify_resumed_stream(client_last_seen: int, resumed_frame: dict, first_event_id: int) -> None:
    """Client-side check: refuse to deliver a resumed stream that is not contiguous."""
    if resumed_frame.get("resumed_from") != client_last_seen:
        raise ResumeContiguityError(
            f"resume_ack_mismatch: asked {client_last_seen}, "
            f"server resumed from {resumed_frame.get('resumed_from')}"
        )
    if first_event_id != client_last_seen + 1:
        raise ResumeContiguityError(
            f"resume_discontinuity: last_seen={client_last_seen}, "
            f"first_resumed_event={first_event_id}, "
            f"gap={first_event_id - client_last_seen - 1} events lost"
        )
