# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-last-event-id-has-been-garbage-collected-the-resumption-silence-gap-and-the-replay-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-last-event-id-has-been-garbage-collected-the-resumption-silence-gap-and-the-replay-identity.warrant.json
# Markdown SHA-256:   5d74ba093a5bd9dccb63b380950ae6c34d0782e2fa2b4448b89b5928aa6afe18
# Code AST SHA-256:   d51e2644e3abac9bf2c2c55c292fb681be2607eaaaf53aae20ff1901ceaccc99
# Verified Classes:   StreamContinuityError, StreamEvent, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import dataclasses
from typing import Iterable, Optional


class StreamContinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot prove continuity with the
    consumer's persisted Last-Event-ID cursor. This is a hard session-invalidating
    condition: the consumer must NOT advance its cursor or trust the stream."""


@dataclasses.dataclass(frozen=True)
class StreamEvent:
    event_id: int          # monotonically increasing per session
    kind: str              # "notification" | "result" | "gap-notice" | ...
    payload: dict


@dataclasses.dataclass
class ResumeState:
    last_event_id: Optional[int] = None   # persisted cursor; None = fresh session
    pending_requests: set[str] = dataclasses.field(default_factory=set)


def resume_stream(
    server_events: Iterable[StreamEvent],
    state: ResumeState,
    *,
    gap_notice_kinds: frozenset[str] = frozenset({"gap-notice", "resync-required"}),
) -> Iterable[StreamEvent]:
    """
    Consume a resumed server event stream, enforcing the continuity invariant:

        A resumed stream is trusted iff its first event is either
          (a) the immediate successor of state.last_event_id, or
          (b) preceded by an explicit gap-notice declaring the lost range.

    On violation, raise StreamContinuityError WITHOUT mutating state.last_event_id,
    so the caller can force a full resync rather than silently reasoning over a gap.
    """
    events = iter(server_events)

    try:
        first = next(events)
    except StopIteration:
        # A resumed stream that immediately closes is suspicious but not proof of a gap;
        # treat as an empty no-op only if we had no pending work.
        if state.pending_requests:
            raise StreamContinuityError(
                f"resumed stream closed immediately with {len(state.pending_requests)} "
                f"pending request(s); continuity unverifiable"
            )
        return

    if state.last_event_id is None:
        # Fresh session: accept whatever head the server offers.
        yield first
        yield from events
        return

    expected_successor = state.last_event_id + 1

    if first.kind in gap_notice_kinds:
        # Explicit gap declaration: server told us what we lost. Accept, but
        # force the caller to reconcile (it sees the gap-notice payload).
        yield first
        for ev in events:
            yield ev
        return

    if first.event_id != expected_successor:
        # Silent truncation: the server fell back to live streaming past an
        # evicted window. This is the failure this guard exists to catch.
        raise StreamContinuityError(
            "resumed stream is not contiguous with persisted cursor: "
            f"last_event_id={state.last_event_id}, expected first id="
            f"{expected_successor}, got {first.event_id} "
            f"(kind={first.kind!r}). Server likely evicted the retained buffer "
            "and fell back to live-only streaming without a gap notice. "
            "Cursor NOT advanced; full resync required."
        )

    # Contiguous: safe to advance.
    yield first
    state.last_event_id = first.event_id
    for ev in events:
        if ev.event_id != state.last_event_id + 1 and ev.kind not in gap_notice_kinds:
            raise StreamContinuityError(
                f"mid-stream discontinuity: expected id={state.last_event_id + 1}, "
                f"got {ev.event_id} (kind={ev.kind!r})"
            )
        yield ev
        state.last_event_id = ev.event_id


def handle_resume(server_events: Iterable[StreamEvent], state: ResumeState) -> None:
    """Adapter entry point: on continuity failure, invalidate the session and
    force a full resync instead of trusting the (possibly gapped) stream."""
    try:
        for ev in resume_stream(server_events, state):
            if ev.kind == "result":
                state.pending_requests.discard(ev.payload.get("request_id", ""))
    except StreamContinuityError:
        # Do NOT retry the same resume with the same cursor: that destroys evidence.
        # Invalidate, re-fetch capability manifests, and re-issue outstanding calls.
        state.pending_requests.clear()
        raise
