# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-the-mcp-http-native-transport-draw-the-boundary-between-streamable-sse-resumability-and-session-resumption-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-the-mcp-http-native-transport-draw-the-boundary-between-streamable-sse-resumability-and-session-resumption-tokens.warrant.json
# Markdown SHA-256:   5945663a963cb72efa82c17ed74896a2edfdc5fa8dcef532c33ab72b4a712326
# Code AST SHA-256:   fa7984976628a3da7b8a2694b213916951ccc37faaa47f94440e84a5446c664e
# Verified Classes:   SessionResumptionError, SessionEventLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionResumptionError(RuntimeError):
    """Raised when a stream resume cannot be safely bound to a session."""
    pass


class SessionEventLog:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self._events: dict[int, dict] = {}

    def append(self, event_id: int, payload: dict) -> None:
        if event_id in self._events:
            raise SessionResumptionError(
                f"event {event_id} already exists in session {self.session_id}"
            )
        self._events[event_id] = payload

    def resume_after(self, last_event_id: int) -> list[dict]:
        if last_event_id not in self._events:
            raise SessionResumptionError(
                f"Last-Event-ID {last_event_id} not in session {self.session_id}; "
                "refusing cross-session replay"
            )
        return [
            self._events[eid]
            for eid in sorted(self._events)
            if eid > last_event_id
        ]


def handle_resume(
    sessions: dict[str, SessionEventLog],
    session_id: str,
    last_event_id: int,
) -> list[dict]:
    log = sessions.get(session_id)
    if log is None:
        raise SessionResumptionError(
            f"session {session_id} expired; client must re-initialize"
        )
    # Event IDs are validated strictly within the presented session's log.
    return log.resume_after(last_event_id)
