# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-silent-event-loss-when-an-mcp-streamable-http-session-resumes-across-a-rebalanced-stream-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-silent-event-loss-when-an-mcp-streamable-http-session-resumes-across-a-rebalanced-stream-boundary.warrant.json
# Markdown SHA-256:   f20af359f87e226f74a2ae46fc62c582060535051e6d4f87d552140faac8530f
# Code AST SHA-256:   6e6a3cf78ea3078ba5f774adbdcbf52623cf7722c5fad071f67b897a40f8e558
# Verified Classes:   SilentEventLossError, ResumeAttempt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class SilentEventLossError(RuntimeError):
    """Raised when a resumed MCP stream skips events between the sent
    Last-Event-ID and the first event actually received."""
    pass


@dataclass
class ResumeAttempt:
    sent_cursor: int
    first_received: int


def verify_resume_continuity(attempt: ResumeAttempt, *, id_is_monotonic: bool) -> None:
    """
    Enforce the client-side invariant: a resumption whose first received
    event is not the immediate successor of the sent cursor has lost events.
    Fails closed. Never returns a "best effort" continuation.
    """
    if not id_is_monotonic:
        # Server uses opaque, non-ordered IDs: gap detection is impossible.
        # We cannot certify continuity, so we must not pretend to.
        raise SilentEventLossError(
            "cannot certify stream continuity: event IDs are non-monotonic; "
            "re-execute the in-flight request instead of trusting the resume"
        )

    expected = attempt.sent_cursor + 1
    if attempt.first_received != expected:
        gap = attempt.first_received - expected
        raise SilentEventLossError(
            f"event loss on resume: sent Last-Event-ID={attempt.sent_cursor}, "
            f"expected first id={expected}, got {attempt.first_received} "
            f"({gap} event(s) silently dropped); discard partial state and "
            f"re-issue the in-flight tools/call with an idempotency key"
        )
    # Continuity certified; the caller may safely continue the stream.
