# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-renegotiate-the-sse-upgrade-when-a-resumable-mcp-stream-crosses-a-session-rebind-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-renegotiate-the-sse-upgrade-when-a-resumable-mcp-stream-crosses-a-session-rebind-boundary.warrant.json
# Markdown SHA-256:   007a2b9898b59c96aa50079c118fd55063e8b313d2d48448cf43ee77b0c6d580
# Code AST SHA-256:   907be064399c4de946a68a5591123c391ec7ff947f42c3fc10b004af4ce20088
# Verified Classes:   UncommittedResumptionError, McpStreamSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UncommittedResumptionError(RuntimeError):
    """Raised when a resumable MCP stream attempts to replay events onto a
    connection that has not committed the SSE upgrade handshake."""
    pass


class McpStreamSession:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.last_event_id = 0
        self.event_log: list[tuple[int, dict]] = []
        # Per-connection upgrade state. Keyed by connection id, NOT session id.
        self.upgraded_connections: set[str] = set()

    def commit_sse_upgrade(self, connection_id: str) -> None:
        """Called only after 200 + text/event-stream headers are flushed."""
        self.upgraded_connections.add(connection_id)

    def resume(self, connection_id: str, last_event_id: int) -> list[dict]:
        if connection_id not in self.upgraded_connections:
            # The boundary: resumption without a committed upgrade on THIS
            # connection is invalid. Do not silently downgrade or replay.
            raise UncommittedResumptionError(
                f"session {self.session_id}: connection {connection_id} "
                f"attempted Last-Event-ID={last_event_id} resumption before "
                f"SSE upgrade was committed; client must renegotiate "
                f"Accept: text/event-stream on this connection"
            )
        if last_event_id < self.last_event_id - len(self.event_log):
            raise UncommittedResumptionError(
                f"session {self.session_id}: Last-Event-ID={last_event_id} "
                f"is below compaction frontier; events permanently lost"
            )
        return [payload for eid, payload in self.event_log if eid > last_event_id]
