# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-the-transport-layer-has-silently-re-bound-the-session-to-a-new-event-id-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-the-transport-layer-has-silently-re-bound-the-session-to-a-new-event-id-epoch.warrant.json
# Markdown SHA-256:   f96c836d535f4bc86930d99a9ab4621ab3c4faac32602db996c4740eb88eb00d
# Code AST SHA-256:   ce7ac968db78b2ecda698e41d2031e8dab11356c36d970d8eaddb36944b6c612
# Verified Classes:   EpochResetError, SseEvent, StreamCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

last_seen = 57
for event in stream:
    if event.id <= last_seen:
        continue          # dedupe
    last_seen = event.id
    dispatch(event)

from __future__ import annotations

from dataclasses import dataclass


class EpochResetError(RuntimeError):
    """Raised when a resumed stream's first event ID does not advance past the cursor.

    Indicates the server silently re-bound the session to a new event-ID epoch
    (replica change, GC, permissive session creation). The cursor is stale and
    must not be used for dedupe; the in-flight request must be reconciled.
    """


@dataclass
class SseEvent:
    id: int | None
    event: str
    data: str


@dataclass
class StreamCursor:
    last_event_id: int | None
    epoch: str | None


def resume_stream(
    cursor: StreamCursor,
    events: list[SseEvent],
    server_epoch: str | None,
) -> list[SseEvent]:
    """Filter a reopened SSE stream against a prior cursor.

    Returns the events that are genuinely new for this epoch. Raises
    EpochResetError if the stream belongs to a different epoch than the cursor.
    """
    if not events:
        return []

    if server_epoch is not None and cursor.epoch is not None:
        if server_epoch != cursor.epoch:
            raise EpochResetError(
                f"epoch mismatch: cursor epoch={cursor.epoch!r} "
                f"server epoch={server_epoch!r}; session re-attached, "
                f"cursor is stale"
            )

    first_id = events[0].id
    if first_id is None:
        # Server is not emitting IDs; resumption is impossible. Treat as new epoch.
        raise EpochResetError(
            "stream opened without event IDs; cannot honor Last-Event-ID"
        )

    if cursor.last_event_id is not None and first_id <= cursor.last_event_id:
        raise EpochResetError(
            f"first event id {first_id} does not advance past cursor "
            f"{cursor.last_event_id}; server reset the event namespace. "
            f"Reconcile in-flight request before continuing."
        )

    out: list[SseEvent] = []
    for ev in events:
        if ev.id is None:
            continue
        if cursor.last_event_id is not None and ev.id <= cursor.last_event_id:
            continue
        out.append(ev)
    return out
