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: GitHub copilot resiliency with LSP proxy retry (#6131)
Myles Scolnick5122f5d07016
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex d1ab5f50e2..722f6b16df 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -263,6 +263,9 @@ class SetUserConfigRequest:# MarimoConfig TypedDictconfig: MarimoConfig+ def __repr__(self) -> str:+ return "SetUserConfigRequest(config=...)"+@dataclassclass CreationRequest:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 6d0db2e0e9..9b5be03596 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport asyncioimport jsonimport sys-from enum import IntEnumfrom typing import TYPE_CHECKING, Any, Callable, Optionalfrom starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState@@ -30,6 +29,7 @@ from marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._plugins.core.web_component import JSONTypefrom marimo._runtime.params import QueryParamsfrom marimo._server.api.deps import AppState+from marimo._server.codes import WebSocketCodesfrom marimo._server.file_router import MarimoFileKeyfrom marimo._server.model import (ConnectionState,@@ -57,12 +57,6 @@ FILE_QUERY_PARAM_KEY = "file"KIOSK_QUERY_PARAM_KEY = "kiosk"-class WebSocketCodes(IntEnum):- ALREADY_CONNECTED = 1003- NORMAL_CLOSE = 1000- FORBIDDEN = 1008--DOC_MANAGER = LoroDocManager()diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex 9e194c1e9f..c3bce83846 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -31,13 +31,14 @@ from starlette.middleware.base import (from starlette.requests import Requestfrom starlette.responses import JSONResponse, Response, StreamingResponsefrom starlette.websockets import WebSocket, WebSocketState-from websockets import ConnectionClosed, connect+from websockets import ClientConnection, ConnectionClosed, connectfrom marimo import _loggersfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._server.api.auth import validate_authfrom marimo._server.api.deps import AppState, AppStateBase+from marimo._server.codes import WebSocketCodesfrom marimo._server.model import SessionModefrom marimo._tracer import server_tracer@@ -422,7 +423,45 @@ class ProxyMiddleware:ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k, v in original_params.items())}"await websocket.accept()- async with connect(ws_url) as ws_client:+ # Try to connect to the upstream WebSocket with retries+ max_retries = 3+ exponential_backoff = 1.5++ async def get_client() -> ClientConnection:+ retry_delay = 0.5 # seconds++ for attempt in range(max_retries):+ try:+ ws_client = await connect(ws_url)+ LOGGER.debug(f"Successfully connected to {ws_url}")+ return ws_client+ except Exception as e:+ LOGGER.info(+ f"WebSocket connection attempt {attempt + 1}/{max_retries} failed for {ws_url}: {e}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(retry_delay)+ retry_delay *= exponential_backoff+ else:+ LOGGER.error(+ f"Failed to connect to {ws_url} after {max_retries} attempts. Final error: {e}"+ )+ # Close the client WebSocket with a meaningful error+ if (+ websocket.client_state+ != WebSocketState.DISCONNECTED+ ):+ await websocket.close(+ code=WebSocketCodes.UNEXPECTED_ERROR,+ reason="Failed to connect to LSP server",+ )+ raise e++ raise ValueError("Failed to connect to LSP server")++ ws_client = await get_client()++ async with ws_client:async def client_to_upstream() -> None:try:@@ -483,7 +522,14 @@ class ProxyMiddleware:await websocket.close()await ws_client.close()except Exception as e:- LOGGER.error(f"WebSocket proxy error: {e}")+ LOGGER.error(f"WebSocket proxy error for {ws_url}: {e}")+ # Check if this is a connection error suggesting the LSP server isn't running+ if "Connection refused" in str(e) or "Connect call failed" in str(+ e+ ):+ LOGGER.error(+ f"LSP server appears to be down at {ws_url}. Check if the LSP server started successfully."+ )if websocket.client_state != WebSocketState.DISCONNECTED:- await websocket.close(code=1011) # Internal error+ await websocket.close(code=WebSocketCodes.UNEXPECTED_ERROR)raisediff --git a/marimo/_server/codes.py b/marimo/_server/codes.pynew file mode 100644index 0000000000..c08af177bd--- /dev/null+++ b/marimo/_server/codes.py@@ -0,0 +1,8 @@+from enum import IntEnum+++class WebSocketCodes(IntEnum):+ ALREADY_CONNECTED = 1003+ NORMAL_CLOSE = 1000+ FORBIDDEN = 1008+ UNEXPECTED_ERROR = 1011diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 5239bc896f..55133791cf 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -1096,12 +1096,18 @@ class SessionManager:LOGGER.warning("Cannot start LSP server in run mode")return+ LOGGER.debug("Starting LSP server...")alert = self.lsp_server.start()if alert is not None:+ LOGGER.warning(+ f"LSP server startup failed: {alert.title} - {alert.description}"+ )for session in self.sessions.values():session.write_operation(alert, from_consumer_id=None)return+ else:+ LOGGER.debug("LSP server started successfully")def close_session(self, session_id: SessionId) -> bool:"""Close a session and remove its file watcher if it has one."""diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 8d52794105..d3cb6a6f71 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -12,9 +12,7 @@ from starlette.websockets import WebSocketDisconnectfrom marimo._config.config import ExperimentalConfigfrom marimo._config.manager import UserConfigManagerfrom marimo._messaging.ops import KernelCapabilities, KernelReady-from marimo._server.api.endpoints.ws import (- WebSocketCodes,-)+from marimo._server.codes import WebSocketCodesfrom marimo._server.model import SessionModefrom marimo._server.sessions import SessionManagerfrom marimo._utils.parse_dataclass import parse_raw