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: ignore attribute error during websocket closure in certain edge cases (#9020)
Myles Scolnick771fe429d27f
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 9d1dbd030d..bf7a71b555 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -446,10 +446,29 @@ class WebSocketHandler(SessionConsumer):return Falsereturn True+ async def _safe_close(self, code: int, reason: str) -> None:+ """Close the WebSocket, ignoring errors from uninitialized state.++ uvicorn never calls websockets' ``connection_open()``, so internal+ attributes like ``transfer_data_task`` are missing. Closing a+ websocket in that state raises ``AttributeError``. The connection+ is cleaned up when the handler returns regardless.+ """+ try:+ await self.websocket.close(code, reason)+ except AttributeError as e:+ if "transfer_data_task" not in str(e):+ raise+ LOGGER.debug(+ "Ignoring AttributeError during websocket close: "+ "missing transfer_data_task",+ exc_info=True,+ )+async def _close_already_connected(self) -> None:"""Close the WebSocket with an 'already connected' error."""if self.websocket.application_state is WebSocketState.CONNECTED:- await self.websocket.close(+ await self._safe_close(WebSocketCodes.ALREADY_CONNECTED,"MARIMO_ALREADY_CONNECTED",)@@ -461,7 +480,7 @@ class WebSocketHandler(SessionConsumer):text = serialize_notification_for_websocket(notification)await self.websocket.send_text(text)# Then close with simple reason- await self.websocket.close(+ await self._safe_close(WebSocketCodes.UNEXPECTED_ERROR,"MARIMO_KERNEL_STARTUP_ERROR",)@@ -479,7 +498,7 @@ class WebSocketHandler(SessionConsumer):) and self.websocket.application_state is WebSocketState.CONNECTEDif is_connected:asyncio.create_task(- self.websocket.close(+ self._safe_close(WebSocketCodes.NORMAL_CLOSE, "MARIMO_SHUTDOWN"))