# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-session-resumption-failure-in-mcp-http-native-streaming-under-sse-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-session-resumption-failure-in-mcp-http-native-streaming-under-sse-backpressure.warrant.json
# Markdown SHA-256:   c7d3f69b804212258bac39e42f8fe1c385885a08d1d9bcea9937d928689b7cd8
# Code AST SHA-256:   511dfb8b1ae74dd15e7fcb790bbf69acae5cbe4dd98373bae35be8a8c4fd9bbe
# Verified Classes:   ResumptionDivergenceError, ResumableSSEConsumer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResumptionDivergenceError(RuntimeError):
    """Raised when SSE replay is not contiguous with the handler-acknowledged cursor."""
    pass


class ResumableSSEConsumer:
    def __init__(self, retention_window: int, buffer_depth: int):
        self.acked_id: int = 0          # advanced only after handler returns
        self.enqueued_ids: set[int] = set()
        self.retention_window = retention_window
        self.buffer_depth = buffer_depth

    def on_reconnect(self, last_event_id_header: int, first_replayed_id: int) -> None:
        # The client MUST send acked_id, not the read-loop position.
        if last_event_id_header != self.acked_id:
            raise ResumptionDivergenceError(
                f"client sent Last-Event-ID={last_event_id_header} but acked_id={self.acked_id}; "
                "cursor was derived from transport receipt, not handler completion"
            )
        if first_replayed_id != self.acked_id + 1:
            raise ResumptionDivergenceError(
                f"replay starts at {first_replayed_id}, expected {self.acked_id + 1}; "
                "gap or overlap in server event log"
            )
        if self.retention_window > self.buffer_depth:
            raise ResumptionDivergenceError(
                f"retention_window={self.retention_window} exceeds buffer_depth={self.buffer_depth}; "
                "a stall longer than the buffer will silently diverge on resume"
            )

    def enqueue(self, event_id: int) -> None:
        if event_id <= self.acked_id:
            # Deduplicate at the read loop; never dispatch an already-acked event.
            return
        if event_id in self.enqueued_ids:
            raise ResumptionDivergenceError(
                f"event {event_id} enqueued twice; server replay overlapped live stream"
            )
        self.enqueued_ids.add(event_id)

    def ack(self, event_id: int) -> None:
        if event_id != self.acked_id + 1:
            raise ResumptionDivergenceError(
                f"non-monotonic ack: got {event_id}, expected {self.acked_id + 1}"
            )
        self.acked_id = event_id
        self.enqueued_ids.discard(event_id)
