# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-across-mcp-http-native-transport-session-resumption-under-sse-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-across-mcp-http-native-transport-session-resumption-under-sse-backpressure.warrant.json
# Markdown SHA-256:   32864465c93a9131361bbd20fca4b7fb50de41c5bfbd23b6aa43468c01fa1d19
# Code AST SHA-256:   1aac951be51e3d79439dafb97084c8fac5b7bc4a4aef3b9ddc7c1270c4c5baf6
# Verified Classes:   ResumptionGapError, ReplayBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when a resume request cannot be honored contiguously.

    This is a hard failure by design: silently resuming from the oldest
    retained event converts a detectable loss into an undetectable one.
    """
    pass


class ReplayBuffer:
    def __init__(self, max_events: int):
        self.max_events = max_events
        self._events: list[tuple[int, dict]] = []  # (event_id, payload), ordered
        self._committed_cursor = 0  # highest durably-stored event id

    def commit(self, payload: dict) -> int:
        # ID is assigned at commit time, never at enqueue time.
        self._committed_cursor += 1
        self._events.append((self._committed_cursor, payload))
        if len(self._events) > self.max_events:
            self._events.pop(0)
        return self._committed_cursor

    def oldest_retained(self) -> int:
        return self._events[0][0] if self._events else self._committed_cursor + 1

    def replay_after(self, last_event_id: int) -> list[tuple[int, dict]]:
        if last_event_id > self._committed_cursor:
            # Client claims to have processed an event we never committed.
            raise ResumptionGapError(
                f"client Last-Event-ID {last_event_id} exceeds committed cursor "
                f"{self._committed_cursor}; client state is ahead of durable truth"
            )
        if last_event_id < self.oldest_retained() - 1:
            # The requested resume point has been evicted from the window.
            raise ResumptionGapError(
                f"Last-Event-ID {last_event_id} older than retained window "
                f"(oldest retained {self.oldest_retained()}); cannot guarantee "
                f"contiguous delivery"
            )
        return [(eid, p) for eid, p in self._events if eid > last_event_id]


def handle_resume(buffer: ReplayBuffer, last_event_id_header: str | None) -> list[tuple[int, dict]]:
    if last_event_id_header is None:
        return []
    try:
        last_event_id = int(last_event_id_header)
    except ValueError:
        raise ResumptionGapError(f"malformed Last-Event-ID: {last_event_id_header!r}")
    return buffer.replay_after(last_event_id)
