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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: memory leak in ASGI session cleanup (#8495)
Myles Scolnick80da4617a80f
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 5d44340930..9d1dbd030d 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -330,9 +330,14 @@ class WebSocketHandler(SessionConsumer):# When the websocket is closed, we wait session.ttl_seconds before# closing the session. This prevents the session from being closed# during intermittent network issues.- # In RUN mode, this always applies.+ # In RUN mode, this always applies (sessions always have a default+ # TTL even if the manager's ttl_seconds is None).# In EDIT mode, this only applies when --session-ttl is explicitly set.- if self.manager.ttl_seconds is not None:+ should_ttl_close = (+ self.manager.ttl_seconds is not None+ or self.mode == SessionMode.RUN+ )+ if should_ttl_close:def _close() -> None:if self.status != ConnectionState.OPEN:@@ -357,7 +362,6 @@ class WebSocketHandler(SessionConsumer):cleanup_fn()self.manager.close_session(self.params.session_id)- session = self.manager.get_session(self.params.session_id)if session is not None:cancellation_handle = asyncio.get_event_loop().call_later(session.ttl_seconds, _closediff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 017befd37a..1369493fd7 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -337,7 +337,7 @@ def create_asgi_app(include_code: bool = False,token: Optional[str] = None,skew_protection: bool = False,- session_ttl: Optional[int] = None,+ session_ttl: int = 120,asset_url: Optional[str] = None,redirect_console_to_browser: bool = False,html_head: Optional[str] = None,@@ -352,7 +352,7 @@ def create_asgi_app(If not provided, an empty token is used.skew_protection (bool, optional): Enable skew protection middleware to prevent version mismatch issues.e.g. if the server is updated, the client will be prompted to reload.- session_ttl (int, optional): Time-to-live in seconds for sessions. If not provided, uses default TTL (2 minutes).+ session_ttl (int): Time-to-live in seconds for sessions. Defaults to 120 (2 minutes).asset_url (str, optional): Custom asset URL for loading static resources. Can include {version} placeholder.e.g. https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{version}/distredirect_console_to_browser (bool, optional): Whether to redirect console output (stdout/stderr) to the browser.diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 33ebdb81ba..b771befc48 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -629,6 +629,10 @@ def test_ttl_close_skips_when_session_has_active_consumer() -> None:120,), # RUN mode always uses TTL which has to be integer: default 120.(SessionMode.EDIT, 120), # EDIT mode with --session-ttl+ (+ SessionMode.RUN,+ None,+ ), # RUN mode with manager TTL=None (create_asgi_app default)],)async def test_session_ttl_expiration(@@ -663,6 +667,67 @@ async def test_session_ttl_expiration(task.join()+def test_run_mode_ttl_close_with_manager_ttl_none() -> None:+ """Unit test: RUN mode must schedule TTL cleanup even when+ manager.ttl_seconds is None (the default for create_asgi_app).++ This was a regression from #7863 where the condition only checked+ manager.ttl_seconds, causing ASGI sessions to never be cleaned up.+ """+ from marimo._server.api.endpoints.ws_endpoint import WebSocketHandler++ captured_callback: list[tuple[float, Callable[[], None]]] = []++ def capture_call_later(+ delay: float, callback: Callable[[], None]+ ) -> MagicMock:+ captured_callback.append((delay, callback))+ return MagicMock()++ # Session exists but no active consumer (disconnected)+ session = MagicMock()+ session.connection_state.return_value = ConnectionState.ORPHANED+ session.ttl_seconds = 120++ manager = MagicMock(spec=SessionManager)+ manager.ttl_seconds = None # ASGI default+ manager.get_session.return_value = session++ params = ConnectionParams(+ session_id="123",+ file_key="test.py",+ kiosk=False,+ auto_instantiate=False,+ rtc_enabled=False,+ )++ handler = WebSocketHandler(+ websocket=MagicMock(),+ manager=manager,+ params=params,+ mode=SessionMode.RUN,+ )+ handler.status = ConnectionState.CLOSED++ cleanup_fn = MagicMock()++ with patch(+ "marimo._server.api.endpoints.ws_endpoint.asyncio.get_event_loop"+ ) as mock_loop:+ mock_loop.return_value.call_later = capture_call_later+ handler._on_disconnect(Exception("disconnect"), cleanup_fn)++ # Must schedule TTL cleanup even though manager.ttl_seconds is None+ assert len(captured_callback) == 1+ delay, ttl_callback = captured_callback[0]+ assert delay == 120 # session.ttl_seconds++ # Fire the callback — session has no active consumer, so it should close+ ttl_callback()+ manager.close_session.assert_called_once_with("123")+ cleanup_fn.assert_called_once()++async def test_edit_mode_without_session_ttl_no_delayed_cleanup(client: TestClient,) -> None: