# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-monotonicity-against-mcp-session-resumption-to-avoid-silent-tool-call-replay-loss-under-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-monotonicity-against-mcp-session-resumption-to-avoid-silent-tool-call-replay-loss-under-backpressure.warrant.json
# Markdown SHA-256:   342a0f9bedb242fbbce8106e9531ccbb260fb770fdb48b9e9ed4e265f4ad642e
# Code AST SHA-256:   943940089e8502c9798ed3395a53301fb9a77f2c1fa77d2665dedece3be457a6
# Verified Classes:   McpResumeGapError, ReplayStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class McpResumeGapError(RuntimeError):
    """Raised when a resumable MCP SSE stream cannot honor Last-Event-ID
    without silently dropping essential events."""
    pass


class ReplayStore:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.events: dict[int, dict] = {}
        self.high_water = 0  # last ID ever enqueued
        self.durable_low = 0  # min ID still resumable

    def enqueue(self, payload: dict) -> int:
        self.high_water += 1
        self.events[self.high_water] = payload
        if len(self.events) > self.capacity:
            # Evicting the oldest event while it is still unacked
            # is the exact condition that breaks resumption.
            self.durable_low = min(self.events)  # advance low-water
            del self.events[min(self.events)]
        return self.high_water


def resume_stream(store: ReplayStore, last_event_id: int) -> list[dict]:
    """Return events to replay for a resume request, or raise on gap."""
    if last_event_id > store.high_water:
        raise McpResumeGapError(
            f"client Last-Event-ID {last_event_id} exceeds server "
            f"high-water {store.high_water}; state is inconsistent"
        )
    if last_event_id < store.durable_low - 1:
        # The client is asking for events we already evicted under
        # backpressure. Returning [] here is the silent-loss bug.
        raise McpResumeGapError(
            f"resume gap: Last-Event-ID {last_event_id} below durable "
            f"low-water {store.durable_low}; events "
            f"[{last_event_id + 1}..{store.durable_low - 1}] were evicted "
            f"and cannot be replayed; client must re-subscribe non-resumably"
        )
    return [store.events[i] for i in range(last_event_id + 1, store.high_water + 1)
            if i in store.events]
