# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-streamable-http-resumption-has-silently-forked-the-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-streamable-http-resumption-has-silently-forked-the-event-stream.warrant.json
# Markdown SHA-256:   1c640f593157e43ce4339482e9b5bb647ba30d4bac12e4c83d9ef613bc805adb
# Code AST SHA-256:   f89c4aac892ac72c23451ae61af11802271aa5d181e3f696de600eaa935c4424
# Verified Classes:   StreamForkedError, UnrecoverableCursorError, SessionStream
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StreamForkedError(RuntimeError):
    """Raised when a resumed MCP event stream does not continue from the acknowledged cursor."""


class UnrecoverableCursorError(RuntimeError):
    """Raised server-side when Last-Event-ID precedes the session's retention watermark."""


@dataclass
class SessionStream:
    session_id: str
    last_applied_event_id: int = 0
    retention_watermark: int = 0          # oldest event still replayable
    pending_calls: dict[str, str] = field(default_factory=dict)  # request_id -> "pending"|"done"


def resume_server_side(sess: SessionStream, requested_last_event_id: int) -> int:
    """Return the first event id to emit on resume, or fail closed."""
    if requested_last_event_id + 1 < sess.retention_watermark:
        # Cursor is in the evicted hole. Do NOT fall through to "start at head".
        raise UnrecoverableCursorError(
            f"session {sess.session_id}: Last-Event-ID {requested_last_event_id} "
            f"precedes retention watermark {sess.retention_watermark}; replay impossible"
        )
    return requested_last_event_id + 1


def resume_client_side(
    sess: SessionStream,
    first_replayed_id: Optional[int],
    gap_marker_present: bool,
) -> None:
    """Validate that the resumed stream is gapless before accepting it."""
    if first_replayed_id is None:
        raise StreamForkedError(
            f"session {sess.session_id}: resumed stream delivered no events; cannot verify continuity"
        )
    expected = sess.last_applied_event_id + 1
    if first_replayed_id != expected and not gap_marker_present:
        # The server silently forked the stream. Any pending call whose result
        # lived in the hole is now unrecoverable and must not be inferred.
        for req_id in list(sess.pending_calls):
            if sess.pending_calls[req_id] == "pending":
                sess.pending_calls[req_id] = "UNRECOVERABLE"
        raise StreamForkedError(
            f"session {sess.session_id}: expected event {expected}, "
            f"received {first_replayed_id}; stream forked, pending calls marked unrecoverable"
        )
