Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Give sessions a stable internal ID (#10906)

Trevor Manz874279711cdc
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index deb45f6a29..391668fa8b 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import asyncio
import contextlib
+import secrets
from typing import TYPE_CHECKING
from uuid import uuid4
@@ -62,7 +63,7 @@ from marimo._session.types import (
QueueManager,
Session,
)
-from marimo._types.ids import ConsumerId
+from marimo._types.ids import ConsumerId, StableSessionId
from marimo._utils.repr import format_repr
if TYPE_CHECKING:
@@ -76,10 +77,17 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
_DEFAULT_TTL_SECONDS = 120
+_SESSION_ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"
__all__ = ["Session", "SessionImpl"]
+def _new_stable_session_id() -> StableSessionId:
+ """Match Hub's session IDs: sess- plus 80 random bits in Crockford Base32."""
+ body = "".join(secrets.choice(_SESSION_ID_ALPHABET) for _ in range(16))
+ return StableSessionId(f"sess-{body}")
+
+
class SessionImpl(Session):
"""A client session.
@@ -239,10 +247,9 @@ class SessionImpl(Session):
extensions: list[SessionExtension],
) -> None:
"""Initialize kernel and client connection to it."""
- # This is some unique ID that we can use to identify the session
- # in edit mode. We don't use the session_id because this can change if
- # the session is resumed
+ # The notebook's creation key is used to find resumable sessions.
self.initialization_id = initialization_id
+ self._stable_id = _new_stable_session_id()
self.app_file_manager = app_file_manager
self.room = Room()
self._kernel_manager = kernel_manager
@@ -267,6 +274,11 @@ class SessionImpl(Session):
# to avoid calling on_attach on the main consumer twice.
self.connect_consumer(session_consumer, main=True)
+ @property
+ def stable_id(self) -> StableSessionId:
+ """Internal identity that survives reconnects and notebook renames."""
+ return self._stable_id
+
@property
def document(self) -> NotebookDocument:
"""The notebook document this session reflects.
diff --git a/marimo/_session/types.py b/marimo/_session/types.py
index 8edc134282..c7d14995d9 100644
--- a/marimo/_session/types.py
+++ b/marimo/_session/types.py
@@ -34,7 +34,7 @@ if TYPE_CHECKING:
from marimo._session.queue import ProcessLike, QueueType
from marimo._session.room import Room
from marimo._session.state.session_view import SessionView
- from marimo._types.ids import ConsumerId
+ from marimo._types.ids import ConsumerId, StableSessionId
from marimo._utils.typed_connection import TypedConnection
@@ -142,6 +142,20 @@ class Session(Protocol):
scratchpad_lock: asyncio.Lock
room: Room
+ @property
+ def stable_id(self) -> StableSessionId:
+ """Opaque, server-generated identity for this session instance.
+
+ Remains unchanged across consumer disconnects, browser resumes, and
+ notebook renames. Each new session gets a fresh ID, even for the same
+ notebook; IDs are not persisted across server restarts.
+
+ This is separate from the browser-supplied `SessionId`, which can
+ change on resume, and `initialization_id`, the notebook's creation
+ key. Internal only: not used for routing or exposed to clients.
+ """
+ ...
+
@property
def notebook_sandbox(self) -> NotebookSandbox | None:
"""The retained sandbox binding used by this session, if any."""
diff --git a/marimo/_types/ids.py b/marimo/_types/ids.py
index ca44783552..bdb1d674d3 100644
--- a/marimo/_types/ids.py
+++ b/marimo/_types/ids.py
@@ -7,8 +7,14 @@ CellId_t = NewType("CellId_t", str)
UIElementId = NewType("UIElementId", str)
+# Session routing key, which may change when a browser resumes.
SessionId = NewType("SessionId", str)
+# Internal identity for one session lifetime, preserved across reconnects and
+# notebook renames. A replacement session gets a fresh ID even for the same
+# notebook. Separate from SessionId and the creation key (initialization_id).
+StableSessionId = NewType("StableSessionId", str)
+
ConsumerId = NewType("ConsumerId", str)
VariableName = NewType("VariableName", str)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 1cecb2aa4b..2d255ab0f9 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -135,9 +135,11 @@ def test_disconnect_and_reconnect(client: TestClient) -> None:
def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
+ manager = get_session_manager(client)
with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
+ stable_id = manager.sessions[SessionId("123")].stable_id
websocket.close()
# Connect by the same session id
with client.websocket_connect(WS_URL) as websocket:
@@ -145,12 +147,14 @@ def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
data = websocket.receive_json()
assert data["op"] == "alert"
- # New session with new ID (simulates refresh)
+ assert manager.sessions[SessionId("123")].stable_id == stable_id
+ # New connection with a new browser ID (simulates refresh)
with client.websocket_connect(OTHER_WS_URL) as websocket:
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({"resumed": True}))
+ assert manager.sessions[SessionId("456")].stable_id == stable_id
def test_allows_multiple_connections_with_other_sessions(
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 9e0bed695d..5c62763968 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -387,6 +387,26 @@ async def test_session() -> None:
assert session.connection_state() == ConnectionState.CLOSED
+def test_sessions_for_same_file_have_distinct_stable_ids() -> None:
+ sessions = [
+ SessionImpl(
+ initialization_id="notebook.py",
+ session_consumer=MagicMock(),
+ kernel_manager=MagicMock(spec=KernelManagerImpl),
+ app_file_manager=AppFileManager.from_app(InternalApp(App())),
+ config_manager=get_default_config_manager(current_path=None),
+ ttl_seconds=None,
+ extensions=[],
+ )
+ for _ in range(2)
+ ]
+ try:
+ assert sessions[0].stable_id != sessions[1].stable_id
+ finally:
+ for session in sessions:
+ session.close()
+
+
async def test_session_disconnect_reconnect() -> None:
session_consumer: Any = MagicMock()
session_consumer.connection_state.return_value = ConnectionState.OPEN
@@ -1002,6 +1022,7 @@ def __():
# Rename to the second file
session = session_manager.get_session(session_id)
assert session is not None
+ stable_id = session.stable_id
success, error = await session_manager.rename_session(
session_id, str(new_path)
)
@@ -1011,6 +1032,7 @@ def __():
assert (
session_manager.get_session_by_file_key(str(new_path)) is session
)
+ assert session.stable_id == stable_id
# Modify the new file
operations.clear()