# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-sse-stream-when-the-server-s-last-event-id-replay-window-has-already-evicted-the-expected-event-and-why.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-sse-stream-when-the-server-s-last-event-id-replay-window-has-already-evicted-the-expected-event-and-why.warrant.json
# Markdown SHA-256:   f18ac0f9f3887d59bf11f77fc11aceb33890eba4b1fd271e9fc6ac94e2a8067c
# Code AST SHA-256:   140862a03a683a701538e04eb74df6fa040505c72e6a254b450454b908a8f6b0
# Verified Classes:   McpResumptionGapError, SseResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class McpResumptionGapError(RuntimeError):
    """Raised when a resumed SSE stream skips events the client has not processed.

    This is not a transport error. The HTTP request succeeded (200). The stream
    is well-formed. The failure is logical: the server's event log no longer
    contains the event the client asked to resume from, and the server did not
    signal the loss explicitly.
    """


@dataclasses.dataclass
class SseResumeState:
    session_id: str
    last_event_id: int          # last FULLY PROCESSED event id
    retention_horizon: int      # server-declared, if known; else -1


def reconcile_resume(
    state: SseResumeState,
    first_replayed_id: Optional[int],
    server_signaled_unrecoverable: bool,
) -> int:
    """Decide whether the resumed stream is a continuation or a gap.

    Returns the new cursor on continuation. Raises McpResumptionGapError
    on any gap, because the client cannot soundly continue with partial state.
    """
    if server_signaled_unrecoverable:
        # Explicit signal: server knows it evicted. Cold-start required.
        raise McpResumptionGapError(
            f"server declared events after {state.last_event_id} unrecoverable "
            f"for session {state.session_id}; cold-start required"
        )

    if first_replayed_id is None:
        # Empty stream. Ambiguous: no events, or all evicted. Do not assume
        # "no events occurred" — that is the silent-gap trap.
        raise McpResumptionGapError(
            f"resume of session {state.session_id} returned empty stream; "
            f"cannot distinguish idle from evicted"
        )

    expected = state.last_event_id + 1
    if first_replayed_id == expected:
        return first_replayed_id  # exact continuation

    if first_replayed_id < expected:
        # Server replayed something we already processed. Harmless duplicate,
        # but cursor must not regress.
        return state.last_event_id

    # first_replayed_id > expected: events [expected .. first_replayed_id-1]
    # were emitted by the server and never delivered to the client.
    gap_size = first_replayed_id - expected
    raise McpResumptionGapError(
        f"session {state.session_id}: resumed at event {first_replayed_id}, "
        f"expected {expected}; {gap_size} event(s) lost "
        f"(control-plane notifications may be among them); "
        f"re-sync or cold-start required"
    )


def resume_or_restart(
    state: SseResumeState,
    first_replayed_id: Optional[int],
    server_signaled_unrecoverable: bool,
    can_resync: bool,
) -> str:
    try:
        cursor = reconcile_resume(state, first_replayed_id, server_signaled_unrecoverable)
        return f"continued at cursor {cursor}"
    except McpResumptionGapError as gap:
        if can_resync:
            return f"degraded: {gap}; triggering full-state resync"
        raise McpResumptionGapError(
            f"{gap}; agent context already consumed pre-gap results and "
            f"cannot re-derive state — aborting session"
        ) from gap
