# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-after-the-sse-event-id-has-been-reaped-but-the-session-token-remains-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-after-the-sse-event-id-has-been-reaped-but-the-session-token-remains-valid.warrant.json
# Markdown SHA-256:   9c7e6f85c4e4c510ce45addcb19355d85b29d7b5944921ce27b44d63af9b33ed
# Code AST SHA-256:   31032a6aa229f1d77e39f7388cc6fe3173aa8ad3efc7eb48004116110cf5f628
# Verified Classes:   StreamResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot prove event contiguity."""
    pass


def validate_resume(
    last_event_id: int,
    oldest_retained_id: int,
    first_delivered_id: int,
    session_ttl_seconds: int,
    event_retention_seconds: int,
) -> None:
    # Invariant: event retention must cover session retention, or resume must be refused.
    if event_retention_seconds < session_ttl_seconds:
        if last_event_id < oldest_retained_id:
            raise StreamResumeGapError(
                f"Last-Event-ID {last_event_id} precedes oldest retained "
                f"{oldest_retained_id}; session still valid but replay impossible. "
                f"event_retention={event_retention_seconds}s < "
                f"session_ttl={session_ttl_seconds}s. Refusing silent resume."
            )
    # Even when retention is sufficient, the delivered stream must be contiguous.
    expected = last_event_id + 1
    if first_delivered_id != expected:
        raise StreamResumeGapError(
            f"Resume delivered id {first_delivered_id}, expected {expected}; "
            f"gap of {first_delivered_id - expected} events. "
            f"Client must re-initialize rather than apply stale state."
        )
