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: robust websocket disconnect, nonblocking usage stats (#1655)
Akshay Agrawala25c26b65734
diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxindex fa529ef56f..8571ccb9c8 100644--- a/frontend/src/core/websocket/useWebSocket.tsx+++ b/frontend/src/core/websocket/useWebSocket.tsx@@ -35,6 +35,9 @@ export function useWebSocket(options: UseWebSocketOptions) {maxRetries: 10,debug: false,startClosed: true,+ // long timeout -- the server can become slow when many notebooks+ // are open.+ connectionTimeout: 60_000,});onOpen && socket.addEventListener("open", onOpen);diff --git a/marimo/_server/api/auth.py b/marimo/_server/api/auth.pyindex da701fecc6..085d31ffcc 100644--- a/marimo/_server/api/auth.py+++ b/marimo/_server/api/auth.py@@ -34,6 +34,7 @@ TOKEN_QUERY_PARAM = "access_token"def validate_auth(conn: HTTPConnection, form_dict: Optional[dict[str, str]] = None) -> bool:+ LOGGER.debug("Validating auth")state = AppState.from_app(conn.app)auth_token = str(state.session_manager.auth_token)diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.pyindex cd4821bdc8..d6c959b0c6 100644--- a/marimo/_server/api/endpoints/health.py+++ b/marimo/_server/api/endpoints/health.py@@ -156,7 +156,9 @@ async def usage(request: Request) -> JSONResponse:import psutilmemory = psutil.virtual_memory()- cpu = psutil.cpu_percent(interval=1)+ # interval=None is nonblocking; first value is meaningless but after+ # that it's useful.+ cpu = psutil.cpu_percent(interval=None)# Server memory (and children)main_process = psutil.Process()diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 89712eb2eb..323ba8935b 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport asyncioimport jsonfrom enum import IntEnum-from typing import Callable, Optional+from typing import Any, Callable, Optionalfrom starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState@@ -290,6 +290,49 @@ class WebsocketHandler(SessionConsumer):LOGGER.debug("Replaying operation %s", serialize(op))self.write_operation(op)+ def _on_disconnect(+ self,+ e: Exception,+ cleanup_fn: Callable[[], Any],+ ) -> None:+ LOGGER.debug(+ "Websocket disconnected for session %s with exception %s, type %s",+ self.session_id,+ str(e),+ type(e),+ )++ # Change the status+ self.status = ConnectionState.CLOSED+ # Disconnect the consumer+ session = self.manager.get_session(self.session_id)+ if session:+ session.disconnect_consumer(self)++ if self.manager.mode == SessionMode.RUN:+ # When the websocket is closed, we wait TTL_SECONDS before+ # closing the session. This is to prevent the session from+ # being closed if the during an intermittent network issue.+ def _close() -> None:+ if self.status != ConnectionState.OPEN:+ LOGGER.debug(+ "Closing session %s (TTL EXPIRED)",+ self.session_id,+ )+ # wait until TTL is expired before calling the cleanup+ # function+ cleanup_fn()+ self.manager.close_session(self.session_id)++ session = self.manager.get_session(self.session_id)+ cancellation_handle = asyncio.get_event_loop().call_later(+ Session.TTL_SECONDS, _close+ )+ if session is not None:+ self.cancel_close_handle = cancellation_handle+ else:+ cleanup_fn()+async def start(self) -> None:# Accept the websocket connectionawait self.websocket.accept()@@ -413,27 +456,27 @@ class WebsocketHandler(SessionConsumer):async def listen_for_messages() -> None:while True:(op, data) = await self.message_queue.get()++ if op in KIOSK_ONLY_OPERATIONS and not self.kiosk:+ LOGGER.debug(+ "Ignoring operation %s, not in kiosk mode",+ op,+ )+ continue+ if op in KIOSK_EXCLUDED_OPERATIONS and self.kiosk:+ LOGGER.debug(+ "Ignoring operation %s, in kiosk mode",+ op,+ )+ continue+try:- if op in KIOSK_ONLY_OPERATIONS and not self.kiosk:- LOGGER.debug(- "Ignoring operation %s, not in kiosk mode",- op,- )- continue- if op in KIOSK_EXCLUDED_OPERATIONS and self.kiosk:- LOGGER.debug(- "Ignoring operation %s, in kiosk mode",- op,- )- continue- await self.websocket.send_text(- json.dumps(- {- "op": op,- "data": data,- },- cls=WebComponentEncoder,- )+ text = json.dumps(+ {+ "op": op,+ "data": data,+ },+ cls=WebComponentEncoder,)except TypeError as e:# This is a deserialization error@@ -441,49 +484,37 @@ class WebsocketHandler(SessionConsumer):"Failed to send message to frontend: %s", str(e))LOGGER.error("Message: %s", data)+ continue++ try:+ await self.websocket.send_text(text)+ except WebSocketDisconnect as e:+ self._on_disconnect(+ e,+ cleanup_fn=lambda: listen_for_disconnect_task.cancel(),+ )+ except RuntimeError as e:+ # Starlette can raise a runtime error if a message is sent+ # when the socket is closed. In case the disconnection+ # error hasn't made its way to listen_for_disconnect, do+ # the cleanup here.+ if (+ self.websocket.application_state+ == WebSocketState.DISCONNECTED+ ):+ self._on_disconnect(+ e,+ cleanup_fn=lambda: listen_for_disconnect_task.cancel(), # noqa: E501+ )async def listen_for_disconnect() -> None:try:await self.websocket.receive_text()except WebSocketDisconnect as e:- LOGGER.debug(- "Websocket disconnected for session %s with exception %s",- self.session_id,- str(e),+ self._on_disconnect(+ e, cleanup_fn=lambda: listen_for_messages_task.cancel())- # Change the status- self.status = ConnectionState.CLOSED- # Disconnect the consumer- session = self.manager.get_session(self.session_id)- if session:- session.disconnect_consumer(self)-- if self.manager.mode == SessionMode.RUN:- # When the websocket is closed, we wait TTL_SECONDS before- # closing the session. This is to prevent the session from- # being closed if the during an intermittent network issue.- def _close() -> None:- if self.status != ConnectionState.OPEN:- LOGGER.debug(- "Closing session %s (TTL EXPIRED)",- self.session_id,- )- # wait until TTL is expired before canceling the- # listener task- listen_for_messages_task.cancel()- self.manager.close_session(self.session_id)-- session = self.manager.get_session(self.session_id)- cancellation_handle = asyncio.get_event_loop().call_later(- Session.TTL_SECONDS, _close- )- if session is not None:- self.cancel_close_handle = cancellation_handle- else:- # Stop listening for messages -- kernel will be torn down- listen_for_messages_task.cancel()-listen_for_messages_task = asyncio.create_task(listen_for_messages())listen_for_disconnect_task = asyncio.create_task(listen_for_disconnect()diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex ff4b40be08..04f46fc119 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -302,14 +302,20 @@ class Room:self.main_consumer = consumerdef remove_consumer(self, consumer: SessionConsumer) -> None:- assert consumer in self.consumers, "Consumer not in room"+ if consumer not in self.consumers:+ LOGGER.debug(+ "Attempted to remove a consumer that was not in room."+ )+ returnif consumer == self.main_consumer:self.main_consumer = Noneself.consumers.pop(consumer)disposable = self.disposables.pop(consumer)- consumer.on_stop()- disposable.dispose()+ try:+ consumer.on_stop()+ finally:+ disposable.dispose()def broadcast(self, operation: MessageOperation) -> None:for consumer in self.consumers: