# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-resuming-an-mcp-http-native-sse-stream-under-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-resuming-an-mcp-http-native-sse-stream-under-backpressure.warrant.json
# Markdown SHA-256:   1630e018068495161ea60c828a9593b89b5eb773c7bab0dc8f6e2d5d2d32044f
# Code AST SHA-256:   f31b59dfc5b36320a62a83465edfacf4299e1cc97e40be787a5e0bb38830de06
# Verified Classes:   SSEGapError, UncommittedEmitError, SessionEventLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import threading


class SSEGapError(RuntimeError):
    """Raised when a resumed SSE stream skips committed event ids."""


class UncommittedEmitError(RuntimeError):
    """Raised when the transport tries to emit an event not yet in the replay log."""


class SessionEventLog:
    """Single-writer event log enforcing commit-before-emit ordering."""

    def __init__(self, max_inflight_window: int):
        self._lock = threading.Lock()
        self._log: list[tuple[int, dict]] = []        # committed, ordered (id, payload)
        self._next_id = 1001
        self._emitted_high_water = 1000               # max id handed to transport
        self._max_window = max_inflight_window
        self._inflight = 0

    def commit(self, payload: dict) -> int:
        # Append to durable log FIRST; only then expose the id.
        with self._lock:
            eid = self._next_id
            self._log.append((eid, payload))
            self._next_id += 1
            return eid

    def emit(self, eid: int) -> dict:
        # Transport may only emit ids that are already committed.
        with self._lock:
            committed = {e for e, _ in self._log}
            if eid not in committed:
                raise UncommittedEmitError(
                    f"emit id={eid} not committed; commit-before-emit violated"
                )
            if eid > self._emitted_high_water + 1:
                raise UncommittedEmitError(
                    f"emit id={eid} skips committed ids "
                    f"({self._emitted_high_water + 1}..{eid - 1})"
                )
            self._emitted_high_water = max(self._emitted_high_water, eid)
            self._inflight += 1
            if self._inflight > self._max_window:
                raise SSEGapError(
                    f"inflight window {self._inflight} exceeds {self._max_window}; "
                    "replay ring too small — refuse to overwrite unacked entries"
                )
            return dict(self._log[eid - 1001][1])

    def resume_from(self, last_event_id: int) -> list[dict]:
        # Resume point must be a committed id; anything past it is replayed.
        with self._lock:
            committed_ids = {e for e, _ in self._log}
            if last_event_id not in committed_ids and self._log:
                raise SSEGapError(
                    f"Last-Event-ID={last_event_id} is not a committed id; "
                    "client claims to have seen an event the log never persisted"
                )
            return [p for e, p in self._log if e > last_event_id]


def replay_and_verify(log: SessionEventLog, received_ids: list[int]) -> None:
    """Client-side strict continuity check on a resumed stream."""
    for prev, cur in zip(received_ids, received_ids[1:]):
        if cur != prev + 1:
            raise SSEGapError(
                f"resumed stream gap: {prev} -> {cur}; "
                "force full session re-sync instead of trusting resume token"
            )
