# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-mcp-session-resumption-when-sse-backpressure-drops-the-last-event-id-frame.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-mcp-session-resumption-when-sse-backpressure-drops-the-last-event-id-frame.warrant.json
# Markdown SHA-256:   635873a0c17e67da8df1cbd8458d1560795ca92a7f8744a3829b2066d31d8bdb
# Code AST SHA-256:   3165658e2846da63137bad23bccd524d0e1259e909dd7fed1ffbb92caaf25c24
# Verified Classes:   ResumptionGapError, EventLog, StreamableSession
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import asyncio
from dataclasses import dataclass, field


class ResumptionGapError(RuntimeError):
    """Raised when a client's Last-Event-ID skips past events the server
    never durably committed, producing a silent state gap on resume."""
    pass


@dataclass
class EventLog:
    committed_high_water: int = 0
    superseded: set[int] = field(default_factory=set)

    def commit(self, event_id: int) -> None:
        # Durable commit MUST happen before the frame reaches the socket.
        if event_id != self.committed_high_water + 1:
            raise ResumptionGapError(
                f"non-contiguous commit: got {event_id}, "
                f"expected {self.committed_high_water + 1}"
            )
        self.committed_high_water = event_id


@dataclass
class StreamableSession:
    log: EventLog
    queue_capacity: int = 256

    async def emit(self, event_id: int, frame: bytes, coalescable: bool = False) -> None:
        # Invariant: commit to the log BEFORE handing the frame to the writer.
        # Backpressure blocks the producer; it never drops committed-range frames.
        self.log.commit(event_id)
        await self._write_with_backpressure(frame, coalescable=coalescable)

    async def _write_with_backpressure(self, frame: bytes, coalescable: bool) -> None:
        # A bounded queue that blocks (awaits) rather than evicts.
        # Coalescable frames may be replaced in-place, never dropped from the
        # committed range.
        await asyncio.sleep(0)  # placeholder for real bounded-queue await

    def validate_resume(self, last_event_id: int) -> None:
        # Guardrail: a resume cursor must not skip uncommitted events.
        if last_event_id > self.log.committed_high_water:
            raise ResumptionGapError(
                f"client resumed at {last_event_id} but server only "
                f"committed through {self.log.committed_high_water}; "
                f"gap would silently truncate side-channel state"
            )
        gap = set(range(last_event_id + 1, self.log.committed_high_water + 1))
        lost = gap - self.log.superseded
        if lost:
            # Force a resync instead of a silent replay.
            raise ResumptionGapError(
                f"resume from {last_event_id} skips non-superseded events "
                f"{sorted(lost)[:5]}...; client must re-fetch state snapshot"
            )
