# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-resumption-cursor-when-the-mcp-server-upgrades-an-http-native-session-to-sse-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-resumption-cursor-when-the-mcp-server-upgrades-an-http-native-session-to-sse-mid-stream.warrant.json
# Markdown SHA-256:   b86d930822bea011aa5dac798df03a3cb675a0ddb4e63f06554fac726b52144d
# Code AST SHA-256:   5b45c7776cc48bd35d98b91ba87b8adbfdbf2afe241da6c0538664537187d3fc
# Verified Classes:   ResumptionCursorInvalid, StreamCursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ResumptionCursorInvalid(RuntimeError):
    """Raised when a resumption cursor cannot be trusted across an SSE upgrade."""
    pass


@dataclass
class StreamCursor:
    session_id: str
    epoch: int
    last_event_id: int | None = None
    seen_ids: set[int] = field(default_factory=set)


def consume_event(cursor: StreamCursor, event_id: int, transport: str) -> StreamCursor:
    """Consume one event, enforcing monotonic continuity across upgrades."""
    if cursor.last_event_id is not None and event_id <= cursor.last_event_id:
        # Content-type transitioned and the server's counter reset or forked.
        # We cannot represent two sequences in one scalar; refuse to resume.
        raise ResumptionCursorInvalid(
            f"event id {event_id} <= last {cursor.last_event_id} on session "
            f"{cursor.session_id} (epoch {cursor.epoch}, transport {transport}); "
            f"server likely reset its event counter on SSE upgrade — "
            f"re-anchor required, do not echo stale Last-Event-ID"
        )
    cursor.last_event_id = event_id
    cursor.seen_ids.add(event_id)
    return cursor


def verify_complete(cursor: StreamCursor, first_id: int, last_id: int) -> None:
    """Server-side terminal digest check: every ID in range must be present."""
    expected = set(range(first_id, last_id + 1))
    missing = expected - cursor.seen_ids
    if missing:
        raise ResumptionCursorInvalid(
            f"session {cursor.session_id} epoch {cursor.epoch} missing events "
            f"{sorted(missing)} in range [{first_id},{last_id}] — "
            f"partial result must not be accepted"
        )
