# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-an-mcp-streamable-sse-client-resumes-across-a-rotated-session-token.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-an-mcp-streamable-sse-client-resumes-across-a-rotated-session-token.warrant.json
# Markdown SHA-256:   78764311247e3cb73b376cb5032f03b9000d31c51dda27aaa8a83e57d31d85e2
# Code AST SHA-256:   dd487b04c132329d4252fc08323a1f4ea9e552f0e572c6b189042fa5984f0fd2
# Verified Classes:   ForeignCursorError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ForeignCursorError(RuntimeError):
    """Raised when an event cursor is presented against a session that did not issue it."""
    pass


def resume_stream(session_id: str, last_event_id: str, sessions: dict) -> list:
    """Resolve an MCP streamable-SSE resume request.

    Event IDs are namespaced as '<session>:<seq>'. A cursor is only valid
    against the session encoded in its own prefix.
    """
    if last_event_id is None:
        return []

    if ":" not in last_event_id:
        raise ForeignCursorError(
            f"unbound cursor {last_event_id!r}: no session namespace, cannot validate"
        )

    cursor_session, seq_str = last_event_id.split(":", 1)
    try:
        seq = int(seq_str)
    except ValueError:
        raise ForeignCursorError(f"malformed cursor sequence in {last_event_id!r}")

    if cursor_session != session_id:
        # The core guard: never compare positions across event spaces.
        raise ForeignCursorError(
            f"cursor {last_event_id!r} belongs to session {cursor_session!r}, "
            f"presented against {session_id!r}; client must reset cursor and re-drive request"
        )

    state = sessions.get(session_id)
    if state is None:
        raise ForeignCursorError(
            f"session {session_id!r} unknown/expired; cursor {last_event_id!r} is unverifiable"
        )

    head = state["head"]
    ring = state["ring"]
    if seq > head:
        # Same session but ahead of head: ring wrap. Replay from ring start, flag gap.
        return list(ring)
    return [e for e in ring if e["seq"] > seq]
