# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-replayed-sse-event-from-a-fresh-one-when-resuming-an-mcp-stream-after-a-session-scoped-capability-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-replayed-sse-event-from-a-fresh-one-when-resuming-an-mcp-stream-after-a-session-scoped-capability-downgrade.warrant.json
# Markdown SHA-256:   81cb8e9ae80185c9b8c491909edb2e28d18f062ef84b20ff1e033288b08cf13c
# Code AST SHA-256:   800c918aa0cd51d0bf7cd2bbf3d2968050e899cfd0716d84296c17f9a2236f57
# Verified Classes:   StaleEpochReplayError, CapabilitySnapshot, SSEEvent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable, Optional

class StaleEpochReplayError(RuntimeError):
    """Raised when a replayed SSE event belongs to a capability epoch
    older than the client's current session snapshot, or when the
    session is no longer valid at replay time."""
    pass

@dataclass
class CapabilitySnapshot:
    epoch: int
    tools: bool = True
    resources: bool = True
    sampling: bool = False

@dataclass
class SSEEvent:
    event_id: int
    kind: str          # e.g. "sampling/createMessage", "capabilities/changed", "notification"
    epoch: Optional[int]  # None if server does not stamp epochs
    payload: dict = field(default_factory=dict)

def probe_session_valid(session_id: str, ping) -> bool:
    """Cheap liveness check before committing to replay side effects."""
    try:
        return ping(session_id) == 200
    except Exception:
        return False

def resume_stream(
    session_id: str,
    last_event_id: int,
    current: CapabilitySnapshot,
    replay: Iterable[SSEEvent],
    ping,
) -> CapabilitySnapshot:
    # Guard 1: session must still exist before we replay anything.
    if not probe_session_valid(session_id, ping):
        raise StaleEpochReplayError(
            f"session {session_id} reclaimed before replay at cursor {last_event_id}"
        )

    events = sorted(replay, key=lambda e: e.event_id)

    # Guard 2: two-pass replay. First pass applies only capability barriers
    # so that the snapshot is correct before any dependent event is applied.
    snapshot = CapabilitySnapshot(**vars(current))
    for ev in events:
        if ev.kind == "capabilities/changed":
            new_epoch = ev.payload.get("epoch", snapshot.epoch + 1)
            if new_epoch <= snapshot.epoch:
                continue
            snapshot = CapabilitySnapshot(
                epoch=new_epoch,
                tools=ev.payload.get("tools", snapshot.tools),
                resources=ev.payload.get("resources", snapshot.resources),
                sampling=ev.payload.get("sampling", snapshot.sampling),
            )

    # Guard 3: second pass applies non-barrier events, discarding any whose
    # emission epoch predates the post-barrier snapshot.
    for ev in events:
        if ev.kind == "capabilities/changed":
            continue
        if ev.epoch is not None and ev.epoch < snapshot.epoch:
            # Event was emitted under a superseded capability set; drop it
            # and advance the cursor rather than applying it.
            continue
        if ev.kind == "sampling/createMessage" and not snapshot.sampling:
            raise StaleEpochReplayError(
                f"event {ev.event_id} requests sampling but current epoch "
                f"{snapshot.epoch} has sampling disabled"
            )
        # ... dispatch ev under snapshot ...
    return snapshot
