# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-resumable-sse-checkpoint-has-silently-diverged-from-the-server-s-event-log.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-resumable-sse-checkpoint-has-silently-diverged-from-the-server-s-event-log.warrant.json
# Markdown SHA-256:   12865e8170812c99f3cf1e760beabcd8eea6b743b05d050dd1e05baa49e8a9b5
# Code AST SHA-256:   32ad7e0557d765a70e501bafac7366c35014dcdfe92e786ab37624dceaaffe64
# Verified Classes:   ResumeDivergenceError, ResumeCursor, ReconnectFrame
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class ResumeDivergenceError(RuntimeError):
    """Raised when a resumable SSE reconnect cannot be proven contiguous
    with the client's Last-Event-ID cursor."""


@dataclass
class ResumeCursor:
    session_id: str
    last_event_id: int
    pending_calls: dict[str, str] = field(default_factory=dict)


@dataclass
class ReconnectFrame:
    session_id: str
    first_event_id: Optional[int]  # None if stream opened but no event yet
    retention_floor: Optional[int]  # oldest retained id, if server advertises it


def validate_resume(cursor: ResumeCursor, frame: ReconnectFrame) -> None:
    """Enforce the resume invariant before any replayed event is consumed.

    Three checks, each corresponding to an observed silent-divergence mode:
      1. session re-key  -> cursor belongs to a dead total order
      2. cursor aged out -> gap between last_event_id and retention_floor
      3. non-contiguous  -> first replayed id != last_event_id + 1
    """
    if frame.session_id != cursor.session_id:
        raise ResumeDivergenceError(
            f"session re-keyed: cursor session {cursor.session_id!r} "
            f"!= reconnect session {frame.session_id!r}; "
            f"pending calls {list(cursor.pending_calls)} are indeterminate"
        )

    if frame.retention_floor is not None and cursor.last_event_id < frame.retention_floor - 1:
        raise ResumeDivergenceError(
            f"cursor {cursor.last_event_id} aged out of retained log "
            f"(floor {frame.retention_floor}); events "
            f"{cursor.last_event_id + 1}..{frame.retention_floor - 1} are lost"
        )

    if frame.first_event_id is None:
        # Stream opened but server emitted nothing yet. Acceptable only if the
        # server is idle; do NOT advance the cursor.
        return

    expected = cursor.last_event_id + 1
    if frame.first_event_id != expected:
        raise ResumeDivergenceError(
            f"non-contiguous resume: expected first id {expected}, "
            f"got {frame.first_event_id}; refusing to merge replayed events"
        )


def apply_resume(cursor: ResumeCursor, frame: ReconnectFrame) -> ResumeCursor:
    """Validate, then advance. On divergence, quarantine pending calls
    instead of silently continuing."""
    try:
        validate_resume(cursor, frame)
    except ResumeDivergenceError:
        # Do not drop state: mark every pending call as indeterminate so the
        # caller can re-issue idempotently or fail the task at a checkpoint.
        for call_id in cursor.pending_calls:
            cursor.pending_calls[call_id] = "indeterminate"
        raise
    if frame.first_event_id is not None:
        cursor.last_event_id = frame.first_event_id
    return cursor
