# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-sse-stream-against-a-server-that-has-already-garbage-collected-the-session-silent-event-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-sse-stream-against-a-server-that-has-already-garbage-collected-the-session-silent-event-r.warrant.json
# Markdown SHA-256:   a127f6ade8f0c5ca09ad5b17304b35c0675bf24f5e256e991f98a185f34fb9dc
# Code AST SHA-256:   6e699206dbf5bd847890354e453325728effac078c7dca7f86924a9a4dc97d1a
# Verified Classes:   SessionContinuityError, SSEEvent, ResumableStreamClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class SessionContinuityError(RuntimeError):
    """Raised when an MCP Streamable HTTP SSE resumption violates the
    Last-Event-ID monotonicity invariant, indicating the server has
    silently restarted or evicted the session's event log."""


@dataclass
class SSEEvent:
    id: int
    event: str
    data: str


@dataclass
class ResumableStreamClient:
    session_id: str
    last_event_id: int = 0
    log: list[SSEEvent] = field(default_factory=list)

    def resume(self, events: Iterable[SSEEvent]) -> None:
        """Consume a reconnected SSE stream, enforcing continuity.

        The invariant: the first event after reconnect MUST have
        id > last_event_id. Any regression means the server is serving a
        different logical stream under a colliding ID namespace, and the
        session must be treated as lost -- not deduped.
        """
        first = True
        for ev in events:
            if first:
                first = False
                if ev.id <= self.last_event_id:
                    raise SessionContinuityError(
                        f"session {self.session_id!r} resumed with event id "
                        f"{ev.id} <= Last-Event-ID {self.last_event_id}; "
                        f"server event log was evicted or restarted. "
                        f"Refusing to append; re-initialize from checkpoint."
                    )
            if ev.id <= self.last_event_id:
                # Mid-stream regression is equally fatal.
                raise SessionContinuityError(
                    f"non-monotonic event id {ev.id} after "
                    f"{self.last_event_id} on session {self.session_id!r}"
                )
            self.log.append(ev)
            self.last_event_id = ev.id


def handle_reconnect(
    client: ResumableStreamClient, reconnected_events: Iterable[SSEEvent]
) -> None:
    try:
        client.resume(reconnected_events)
    except SessionContinuityError:
        # Surface to the agent's control loop: do NOT silently continue.
        # Discard the stream and re-initialize the session from a checkpoint.
        raise SessionContinuityError(
            f"aborting resumption for session {client.session_id!r}; "
            f"agent must re-derive state from last known-good checkpoint"
        )
