# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-resumability-invariant-in-mcp-streamable-http-transports-the-last-event-id-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-resumability-invariant-in-mcp-streamable-http-transports-the-last-event-id-replay-gap.warrant.json
# Markdown SHA-256:   92f56bcdc4bb80dc1a61283602e330f1c952ac8a5674a9e2645c62d850f44b04
# Code AST SHA-256:   343c5fbca63add265f68cd9564c6df29a93882ffaa16c6e191d5d858b20c0180
# Verified Classes:   ResumptionInvariantError, ReplayWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionInvariantError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven contiguous
    with the client's last acknowledged event, or when replay would
    re-trigger non-idempotent execution side effects."""


@dataclass
class ReplayWindow:
    oldest_retained_id: int
    newest_retained_id: int
    session_pinned_execution: bool


def assert_resumption_safe(
    last_seen_id: int,
    window: ReplayWindow,
    first_replayed_id: Optional[int],
) -> None:
    # 1. Requested position must still be retained; silent head-truncation is fatal.
    if last_seen_id < window.oldest_retained_id - 1:
        raise ResumptionInvariantError(
            f"Last-Event-ID {last_seen_id} evicted from replay buffer "
            f"(oldest retained {window.oldest_retained_id}); server must "
            f"refuse-and-resync, not resume from oldest retained."
        )

    # 2. Execution must be session-pinned/idempotent, else replay doubles side effects.
    if not window.session_pinned_execution:
        raise ResumptionInvariantError(
            "Execution not session-pinned; resuming would re-invoke the tool "
            "and duplicate non-idempotent side effects."
        )

    # 3. Client-side continuity: first replayed frame must be exactly last_seen + 1.
    expected_next = last_seen_id + 1
    if first_replayed_id is not None and first_replayed_id != expected_next:
        raise ResumptionInvariantError(
            f"Gap detected on resume: expected next id {expected_next}, "
            f"received {first_replayed_id}. Discard in-flight task state and "
            f"re-fetch authoritative state before continuing."
        )


def resume_stream(last_seen_id: int, window: ReplayWindow,
                  first_replayed_id: Optional[int]) -> None:
    assert_resumption_safe(last_seen_id, window, first_replayed_id)
    # Safe to continue: replay id > last_seen_id verbatim.
