# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-a-streamable-mcp-session-after-a-lost-sse-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-a-streamable-mcp-session-after-a-lost-sse-event-id.warrant.json
# Markdown SHA-256:   193ec277f0911cf006955c2ab7c6cecb13b5c6a56fca5a220264e7452a070fe8
# Code AST SHA-256:   c7651fc96353f34ccba3862ac1878d4d5808cf1b93467f960872a6b3ae111009
# Verified Classes:   ResumptionRefused, GapClass, ResumeVerdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ResumptionRefused(RuntimeError):
    """Raised when a streamable MCP session cannot be safely resumed."""


class GapClass(Enum):
    EMPTY = "empty"            # no events missing; safe to resume
    PROGRESS_ONLY = "progress" # only notifications/progress missing; safe
    SIDE_EFFECTING = "effect"  # tools/call results or control signals missing
    UNKNOWN = "unknown"        # server did not classify; treat as unsafe


@dataclass(frozen=True)
class ResumeVerdict:
    cursor_resolved_exactly: bool
    gap_class: GapClass
    client_watermark: int
    server_replay_watermark: int
    session_shared: bool


def gate_resumption(verdict: ResumeVerdict) -> None:
    """Client-side gate. Must pass before the agent loop consumes any resumed event."""
    if not verdict.cursor_resolved_exactly:
        raise ResumptionRefused(
            f"Last-Event-ID did not resolve exactly; server replay start "
            f"watermark={verdict.server_replay_watermark} exceeds client "
            f"watermark={verdict.client_watermark}. Positional resume would "
            f"silently bridge an unclassified gap."
        )
    if verdict.session_shared:
        raise ResumptionRefused(
            "Mcp-Session-Id is shared with a concurrent writer; event log "
            "interleaves two causal chains and positional resumption cannot "
            "distinguish them. Reconcile session state instead."
        )
    if verdict.gap_class in (GapClass.SIDE_EFFECTING, GapClass.UNKNOWN):
        raise ResumptionRefused(
            f"Gap class={verdict.gap_class.value}; missing events may carry "
            f"committed tool results or control-flow signals. Agent must "
            f"re-query tool state before continuing."
        )
    # EMPTY and PROGRESS_ONLY are safe: resume as a continuation.
