# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-gaps-before-honoring-an-mcp-session-resumption-token.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-gaps-before-honoring-an-mcp-session-resumption-token.warrant.json
# Markdown SHA-256:   d0dd7becfcfed58d923c9da894ed0a40479f947d5dce1cf2a24f5a8fffbfbc09
# Code AST SHA-256:   410c598f55af3d5d407114764412e8c7655968ec36414a5f36397de42324de7e
# Verified Classes:   SSEStreamDiscontinuity, StreamCursor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SSEStreamDiscontinuity(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven continuous
    with the client's last acknowledged event under the session's
    (epoch, event_id) total order."""


@dataclass(frozen=True)
class StreamCursor:
    epoch: str          # changes on emitter/session restart
    event_id: int       # monotonic within epoch


def reconcile_resumption(
    last_acked: StreamCursor,
    first_received: StreamCursor,
    *,
    gap_tolerable: bool,
) -> Optional[str]:
    """Validate the first event of a resumed MCP SSE stream.

    Returns None on clean continuation, or a resync reason string when a
    within-epoch gap is tolerated by the caller's notification policy.
    Raises SSEStreamDiscontinuity when continuity cannot be proven.
    """
    if first_received.epoch != last_acked.epoch:
        raise SSEStreamDiscontinuity(
            f"epoch changed on resumption: {last_acked.epoch!r} -> "
            f"{first_received.epoch!r}; server ID space was recycled, "
            f"local derived state is unprovable"
        )

    if first_received.event_id <= last_acked.event_id:
        raise SSEStreamDiscontinuity(
            f"non-monotonic resumption: last_acked={last_acked.event_id} "
            f"first_received={first_received.event_id}; server likely "
            f"replayed from head instead of honoring Last-Event-ID"
        )

    if first_received.event_id == last_acked.event_id + 1:
        return None

    missing = first_received.event_id - last_acked.event_id - 1
    if not gap_tolerable:
        raise SSEStreamDiscontinuity(
            f"unrecoverable gap of {missing} event(s) between "
            f"{last_acked.event_id} and {first_received.event_id}; "
            f"notification type requires exact delivery"
        )
    return f"gap:{missing}"


def handle_resumed_stream(
    last_acked: StreamCursor,
    first_received: StreamCursor,
    notification_type: str,
) -> None:
    # progress deltas and cancellations are not gap-safe
    gap_safe_types = {"state_snapshot"}
    try:
        resync_reason = reconcile_resumption(
            last_acked,
            first_received,
            gap_tolerable=notification_type in gap_safe_types,
        )
    except SSEStreamDiscontinuity:
        # escalate: drop session token, re-run initialize, resubscribe fresh
        raise
    if resync_reason is not None:
        # tolerated gap: force full state re-sync before applying deltas
        request_full_state_resync(resync_reason)


def request_full_state_resync(reason: str) -> None:
    raise SSEStreamDiscontinuity(
        f"gap-tolerated resync required before applying deltas: {reason}"
    )
