# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-forking-an-mcp-http-session-across-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-forking-an-mcp-http-session-across-resumption.warrant.json
# Markdown SHA-256:   0faa6b7811c7c044c4dca8f46c4bc51e003f411753ba0ac24a130e71395768d0
# Code AST SHA-256:   b142dba182606f805a60e5d1e98c8ccd17b1a1d5c541ad7ce31306c92cfe587b
# Verified Classes:   SessionResumeInvariantError, SessionStreamState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SessionResumeInvariantError(RuntimeError):
    """Raised when an SSE resume cursor cannot be honored without forking the session."""


@dataclass
class SessionStreamState:
    session_id: str
    next_event_id: int = 1
    min_retained_id: int = 1
    # event_id -> serialized frame, retained backlog
    backlog: dict[int, str] = field(default_factory=dict)
    max_retained: int = 256

    def emit(self, frame: str) -> int:
        eid = self.next_event_id
        self.next_event_id += 1
        self.backlog[eid] = frame
        # trim, but remember the new floor
        while len(self.backlog) > self.max_retained:
            oldest = min(self.backlog)
            del self.backlog[oldest]
            self.min_retained_id = oldest + 1
        return eid

    def resume(self, last_event_id: int) -> list[str]:
        """Return frames strictly after last_event_id, or raise on any gap."""
        max_emitted = self.next_event_id - 1
        if last_event_id > max_emitted:
            # Cursor ahead of anything this session ever emitted: never clamp.
            raise SessionResumeInvariantError(
                f"session={self.session_id} cursor={last_event_id} "
                f"ahead_of_max_emitted={max_emitted}; refusing to reset numbering"
            )
        if last_event_id < self.min_retained_id - 1:
            raise SessionResumeInvariantError(
                f"session={self.session_id} cursor={last_event_id} "
                f"behind_retained_floor={self.min_retained_id - 1}; replay gap, re-issue required"
            )
        return [self.backlog[eid] for eid in sorted(self.backlog) if eid > last_event_id]


def handle_resume(state: SessionStreamState, last_event_id: int) -> list[str]:
    try:
        return state.resume(last_event_id)
    except SessionResumeInvariantError:
        # Surface as an explicit resumption failure; the client must re-establish.
        raise
