# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-sse-resumption-from-silently-replaying-a-divergent-event-prefix-when-the-reconnect-token-outlives-the-server-s-per-sessio.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-sse-resumption-from-silently-replaying-a-divergent-event-prefix-when-the-reconnect-token-outlives-the-server-s-per-sessio.warrant.json
# Markdown SHA-256:   4169a2f27346a12aa1e09eea8c8e43dd041d3f87bbd4f570127358422d394c47
# Code AST SHA-256:   e24d5849fa49f1518fb51f619d7dc72ab7eb020ec4d69d08d5ef87b329ea90e8
# Verified Classes:   ResumeContiguityViolation, SessionEventLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ResumeContiguityViolation(RuntimeError):
    """Raised when a session resume would emit a non-contiguous event prefix."""


@dataclass
class SessionEventLog:
    capacity: int
    _events: dict = field(default_factory=dict)   # id -> payload
    _head: int = 0                                # highest emitted id
    _evicted_through: int = 0                     # watermark: ids <= this are gone

    def emit(self, payload: str) -> int:
        self._head += 1
        self._events[self._head] = payload
        if len(self._events) > self.capacity:
            oldest = min(self._events)
            del self._events[oldest]
            self._evicted_through = max(self._evicted_through, oldest)
        return self._head

    def resume_after(self, last_event_id: int) -> list:
        # The invariant: contiguity, not mere presence.
        if last_event_id <= self._evicted_through:
            raise ResumeContiguityViolation(
                f"Last-Event-ID {last_event_id} <= evicted_through "
                f"{self._evicted_through}; prefix lost, snapshot required"
            )
        first = last_event_id + 1
        if first not in self._events and first <= self._head:
            raise ResumeContiguityViolation(
                f"gap: expected first event {first}, buffer starts at "
                f"{min(self._events)}"
            )
        return [self._events[i] for i in range(first, self._head + 1)
                if i in self._events]


def handle_reconnect(log: SessionEventLog, last_event_id: int) -> list:
    try:
        return log.resume_after(last_event_id)
    except ResumeContiguityViolation:
        # Force full snapshot; never stitch a divergent prefix.
        raise


# Reproduction of the observed failure:
log = SessionEventLog(capacity=200)
for _ in range(520):
    log.emit("progress")
# Client last saw e140; buffer now evicted through e320.
handle_reconnect(log, 140)  # raises ResumeContiguityViolation
