# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-mcp-http-native-transport-streaming-session-resumption-fail-silently-when-sse-multiplexing-reuses-an-event-id-namespace-across.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-mcp-http-native-transport-streaming-session-resumption-fail-silently-when-sse-multiplexing-reuses-an-event-id-namespace-across.warrant.json
# Markdown SHA-256:   593eabf0ae6b2199853e979cc6432a71acc77febb20eb53c51a010fa81225cd0
# Code AST SHA-256:   649601785f3d30e9a0b1a537069a05d139f4654b33ea368bf1f5ff7c01d0dc54
# Verified Classes:   MCPEventScopeError, SessionEventAllocator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class MCPEventScopeError(RuntimeError):
    """Raised when event-ID allocation would make resumption over-broad."""
    pass


class SessionEventAllocator:
    """
    Enforces the invariant: replay_scope(Last-Event-ID) subset-of stream_scope.
    Event IDs are namespaced per stream; a session-wide counter is rejected
    once more than one stream exists and resumption is enabled.
    """

    def __init__(self, session_id: str, resumption_enabled: bool):
        self.session_id = session_id
        self.resumption_enabled = resumption_enabled
        self._streams: dict[str, int] = {}  # stream_id -> next seq
        self._replay: dict[str, dict[int, object]] = {}  # stream_id -> seq -> event

    def open_stream(self, stream_id: str) -> None:
        if stream_id in self._streams:
            raise MCPEventScopeError(
                f"stream {stream_id!r} already open in session {self.session_id!r}"
            )
        if self.resumption_enabled and len(self._streams) >= 1:
            # Multiplexed + resumable: a session-wide counter would leak across
            # streams on replay. Require per-stream namespacing (which this
            # allocator provides) and forbid any shared-counter fallback.
            pass  # namespacing below is the only legal path
        self._streams[stream_id] = 0
        self._replay[stream_id] = {}

    def allocate(self, stream_id: str, event: object) -> str:
        if stream_id not in self._streams:
            raise MCPEventScopeError(
                f"allocate on unopened stream {stream_id!r} in session {self.session_id!r}"
            )
        seq = self._streams[stream_id]
        self._streams[stream_id] = seq + 1
        self._replay[stream_id][seq] = event
        # Namespaced ID: stream identity is intrinsic to the ID, so a replay
        # lookup can never cross streams even without the reconnect URL.
        return f"{stream_id}:{seq}"

    def replay_for(self, stream_id: str, last_event_id: str) -> list[object]:
        try:
            id_stream, id_seq_s = last_event_id.split(":", 1)
            id_seq = int(id_seq_s)
        except (ValueError, AttributeError):
            raise MCPEventScopeError(
                f"malformed Last-Event-ID {last_event_id!r}; expected '<stream>:<seq>'"
            )
        if id_stream != stream_id:
            # The client resumed stream X but presented an ID minted on stream Y.
            # Replaying here would be the over-broad-lookup bug in disguise.
            raise MCPEventScopeError(
                f"Last-Event-ID {last_event_id!r} belongs to stream {id_stream!r}, "
                f"but reconnect targeted stream {stream_id!r}"
            )
        buf = self._replay.get(stream_id, {})
        return [buf[s] for s in sorted(buf) if s > id_seq]
