# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-sse-stream-replay-window-desynchronization-across-a-reconnecting-server-initiated-event-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-sse-stream-replay-window-desynchronization-across-a-reconnecting-server-initiated-event-channel.warrant.json
# Markdown SHA-256:   0bc83bcb64d37fb9dd991aa9878e291a4b27bc5378b87e52516606dc27ac1c44
# Code AST SHA-256:   5ce73ad01b5c8c95a5ddfee8b0ec0b71e72f0f166716657dfb9b0cc340175063
# Verified Classes:   ResumptionDiscontinuityError, StreamCursor, ResumedStream
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionDiscontinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven gap-free and monotonic."""
    pass


@dataclass(frozen=True)
class StreamCursor:
    last_event_id: int
    server_epoch: str
    state_committed: bool  # cursor written atomically with derived state


@dataclass(frozen=True)
class ResumedStream:
    first_event_id: int
    server_epoch: str
    gap_marker_seen: bool


def validate_resumption(cursor: StreamCursor, resumed: ResumedStream) -> None:
    """Gate that must pass before any replayed event is applied to agent state.

    Raises ResumptionDiscontinuityError if the stream must be quarantined and
    the session re-synchronized from an authoritative snapshot instead.
    """
    if not cursor.state_committed:
        raise ResumptionDiscontinuityError(
            f"cursor {cursor.last_event_id} persisted without committed state; "
            "replay would apply events to a state that never saw earlier ones"
        )

    if resumed.server_epoch != cursor.server_epoch:
        raise ResumptionDiscontinuityError(
            f"server epoch changed {cursor.server_epoch!r} -> {resumed.server_epoch!r}; "
            "event-ID space is not shared, replay IDs are not comparable"
        )

    if resumed.first_event_id <= cursor.last_event_id:
        raise ResumptionDiscontinuityError(
            f"monotonicity violation: first replayed id {resumed.first_event_id} "
            f"<= last committed id {cursor.last_event_id}; possible ID-space reset"
        )

    if resumed.gap_marker_seen:
        raise ResumptionDiscontinuityError(
            "server signaled a replay gap (bounded buffer truncation); "
            "events between cursor and first replayed id were dropped"
        )

    # Invariant holds: gap-free, monotonic, same epoch, atomic cursor. Safe to apply.
    return None


def resume_or_resync(cursor: StreamCursor, resumed: ResumedStream) -> str:
    try:
        validate_resumption(cursor, resumed)
        return "apply"
    except ResumptionDiscontinuityError as exc:
        # Do NOT apply. Rebuild state from authoritative reads before consuming push.
        return f"resync: {exc}"
