# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-http-native-transport-stream-is-resumable-versus-silently-orphaned-after-a-session-drop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-http-native-transport-stream-is-resumable-versus-silently-orphaned-after-a-session-drop.warrant.json
# Markdown SHA-256:   63e00739c4becb95a28acb929724903b244e05db990dc053fcf86bfa7128c604
# Code AST SHA-256:   214a1b124d2897d3eb95a291beb6953a1d99d770dd97d20ab8ad9ddea399bc93
# Verified Classes:   StreamResumptionError, ReconnectObservation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StreamResumptionError(RuntimeError):
    """Raised when an MCP HTTP-native stream reconnect is not a true resumption."""


@dataclass
class ReconnectObservation:
    sent_session_id: str
    sent_last_event_id: Optional[int]
    recv_session_id: str
    first_replayed_event_id: Optional[int]
    server_signaled_eviction: bool


def assert_resumption_is_contiguous(obs: ReconnectObservation) -> None:
    # C1: watermark must have been persisted and sent.
    if obs.sent_last_event_id is None:
        raise StreamResumptionError(
            "reconnect omitted Last-Event-ID; server will stream from head, "
            "silently dropping events after the disconnect point"
        )

    # C3: session identity must be stable across the reconnect.
    if obs.recv_session_id != obs.sent_session_id:
        raise StreamResumptionError(
            f"session migrated on reconnect: sent {obs.sent_session_id!r}, "
            f"received {obs.recv_session_id!r}; prior event buffer is gone, "
            "treat all events after watermark as unknown and re-issue the request"
        )

    # C2: server must not have evicted the buffer we depend on.
    if obs.server_signaled_eviction:
        raise StreamResumptionError(
            "server rejected Last-Event-ID (buffer evicted or session expired); "
            "session is dead, abort and re-initialize"
        )

    # C4: replay must be contiguous with the watermark.
    if obs.first_replayed_event_id is None:
        raise StreamResumptionError(
            "reconnect produced no replayed event; cannot prove continuity"
        )
    expected = obs.sent_last_event_id + 1
    if obs.first_replayed_event_id != expected:
        raise StreamResumptionError(
            f"replay gap: expected first event {expected}, "
            f"got {obs.first_replayed_event_id}; "
            f"{obs.first_replayed_event_id - expected} events lost — "
            "reconcile by re-issuing the originating request, do not assume completion"
        )


def resume_stream(obs: ReconnectObservation) -> str:
    assert_resumption_is_contiguous(obs)
    return "resumed"
