# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-silent-sse-resumption-divergence-in-mcp-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-silent-sse-resumption-divergence-in-mcp-http-native-transport.warrant.json
# Markdown SHA-256:   ef8f9aff1ce1bb3c2b888712526927c7bafe559b0ff1b8b19c9a6f95ef0929d0
# Code AST SHA-256:   5cea42c3b384160b380a9eeb456258e95b0e2eea254d9effd62c742258477818
# Verified Classes:   SSEResumptionDivergence, SSECursorGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class SSEResumptionDivergence(RuntimeError):
    """Raised when a resumed SSE stream violates cursor monotonicity.

    A 200 response with a streamable body is NOT proof of continuity.
    The client holds the only trustworthy cursor; the server's first
    emitted id must be strictly greater than the Last-Event-ID we sent.
    """


@dataclass
class SSECursorGuard:
    session_id: str
    sent_last_event_id: int
    received_ids: list = field(default_factory=list)

    def validate_resume_frame(self, raw_event: str) -> None:
        # Parse the first `id:` field of the resumed frame.
        match = re.search(r"^id:\s*(\d+)\s*$", raw_event, re.MULTILINE)
        if match is None:
            # A frame with no id is legal mid-stream but NOT legal as the
            # first frame after a resume with Last-Event-ID set: we cannot
            # prove continuity, so treat it as divergence.
            raise SSEResumptionDivergence(
                f"session {self.session_id}: resumed stream opened with "
                f"id-less frame; cannot confirm cursor > {self.sent_last_event_id}"
            )
        received = int(match.group(1))
        self.received_ids.append(received)

        if received <= self.sent_last_event_id:
            # This is the silent-reset signature: server restarted its
            # counter (e.g. replica migration, buffer eviction) and is
            # emitting from a floor at or below our cursor.
            raise SSEResumptionDivergence(
                f"session {self.session_id}: cursor regression on resume — "
                f"sent Last-Event-ID={self.sent_last_event_id}, "
                f"received id={received}. Server must return 410 Gone, "
                f"not a renumbered stream. Abort session; replay pending "
                f"tools/call set against a fresh Mcp-Session-Id."
            )

        # Monotonicity within the resumed stream.
        if len(self.received_ids) > 1 and received <= self.received_ids[-2]:
            raise SSEResumptionDivergence(
                f"session {self.session_id}: non-monotonic id within resumed "
                f"stream ({self.received_ids[-2]} -> {received})"
            )


def resume_stream(guard: SSECursorGuard, first_frame: str) -> None:
    guard.validate_resume_frame(first_frame)
    # ... proceed with replay of pending tools/call set ...
