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.

chore(ruff): ensure cleanup after context errors (#10760)

Shahmir Varqhac491a7a135c5
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index 6f3ebd7638..ca79a16c50 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -77,8 +77,10 @@ class ExecutionContext:
) -> Iterator[None]:
old_conn = self.duckdb_connection
self.duckdb_connection = connection
- yield
- self.duckdb_connection = old_conn
+ try:
+ yield
+ finally:
+ self.duckdb_connection = old_conn
@dataclass
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index fc1bb302be..5468a8c83d 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -36,6 +36,8 @@ if TYPE_CHECKING:
from starlette.applications import Starlette
+ from marimo._server.ai.mcp import MCPClient
+
LOGGER = _loggers.marimo_logger()
background_tasks: set[asyncio.Task[Any]] = set()
@@ -65,9 +67,10 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
registry=background_tasks,
)
- yield
-
- await cancel_and_wait(task)
+ try:
+ yield
+ finally:
+ await cancel_and_wait(task)
@contextlib.asynccontextmanager
@@ -82,11 +85,31 @@ async def tool_manager(app: Starlette) -> AsyncIterator[None]:
yield
+async def _cleanup_mcp_task(
+ task: asyncio.Task[MCPClient | None],
+) -> None:
+ try:
+ await cancel_and_wait(task)
+ if task.cancelled():
+ return
+ mcp_client = task.result()
+ except Exception:
+ LOGGER.exception("MCP connection task failed during cleanup")
+ return
+
+ if mcp_client is None:
+ return
+
+ try:
+ LOGGER.info("Disconnecting from all MCP servers")
+ await mcp_client.disconnect_from_all_servers()
+ LOGGER.info("Successfully disconnected from all MCP servers")
+ except Exception:
+ LOGGER.exception("Failed to disconnect from MCP servers")
+
+
@contextlib.asynccontextmanager
async def mcp(app: Starlette) -> AsyncIterator[None]:
- if TYPE_CHECKING:
- from marimo._server.ai.mcp import MCPClient
-
state = AppState.from_app(app)
session_mgr = state.session_manager
user_config = state.config_manager.get_config()
@@ -126,22 +149,10 @@ async def mcp(app: Starlette) -> AsyncIterator[None]:
on_exception=lambda _exc: None,
)
- yield
-
- await cancel_and_wait(task)
- if task.cancelled():
- return
-
- mcp_client = task.result()
- if not mcp_client:
- return
-
try:
- LOGGER.info("Disconnecting from all MCP servers")
- await mcp_client.disconnect_from_all_servers()
- LOGGER.info("Successfully disconnected from all MCP servers")
- except Exception as e:
- LOGGER.error(f"Error during MCP disconnect: {e}")
+ yield
+ finally:
+ await _cleanup_mcp_task(task)
@contextlib.asynccontextmanager
@@ -189,11 +200,12 @@ async def logging(app: Starlette) -> AsyncIterator[None]:
server_token = str(state.session_manager.skew_protection_token)
print_mcp_server(mcp_url, server_token)
- yield
-
- # Shutdown message
- if not quiet:
- print_shutdown()
+ try:
+ yield
+ finally:
+ # Shutdown message
+ if not quiet:
+ print_shutdown()
@contextlib.asynccontextmanager
@@ -252,9 +264,10 @@ async def server_registry(app: Starlette) -> AsyncIterator[None]:
except Exception as e:
LOGGER.warning("Failed to register server: %s", e)
- yield
-
- writer.deregister()
+ try:
+ yield
+ finally:
+ writer.deregister()
@contextlib.asynccontextmanager
@@ -268,8 +281,10 @@ async def etc(app: Starlette) -> AsyncIterator[None]:
@contextlib.asynccontextmanager
async def reap_subprocesses(app: Starlette) -> AsyncIterator[None]:
del app
- yield
- await cancel_pending_reaps()
+ try:
+ yield
+ finally:
+ await cancel_pending_reaps()
def _startup_url(state: AppStateBase) -> str:
diff --git a/pyproject.toml b/pyproject.toml
index 727ce574fc..93548f5c86 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -393,7 +393,6 @@ ignore = [
"FURB110", # Replace ternary with an `or` expression
"RUF036", # `None` is not last in a union
"FURB113", # Repeated `append` calls
- "RUF075", # Fallible context manager
"FURB171", # Single-item membership test
"NPY002", # Legacy NumPy random API
"RUF100", # Unused `noqa` directive
diff --git a/tests/_runtime/test_context.py b/tests/_runtime/test_context.py
index 1ae009f589..dc7b7af720 100644
--- a/tests/_runtime/test_context.py
+++ b/tests/_runtime/test_context.py
@@ -1,7 +1,17 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+import pytest
+
from marimo._runtime import context
+from marimo._runtime.context.types import ExecutionContext
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
+if TYPE_CHECKING:
+ import duckdb
+
async def test_context_installed(
execution_kernel: Kernel, exec_req: ExecReqProvider
@@ -32,6 +42,27 @@ def test_not_running_in_notebook() -> None:
assert not running_in_notebook()
+def test_execution_context_restores_connection_after_error() -> None:
+ execution_context = ExecutionContext(
+ cell_id="cell_id", setting_element_value=False
+ )
+ original_connection = cast("duckdb.DuckDBPyConnection", object())
+ replacement_connection = cast("duckdb.DuckDBPyConnection", object())
+ execution_context.duckdb_connection = original_connection
+
+ def run_failing_cell() -> None:
+ with execution_context.with_connection(replacement_connection):
+ assert (
+ execution_context.duckdb_connection is replacement_connection
+ )
+ raise RuntimeError("cell failed")
+
+ with pytest.raises(RuntimeError, match="cell failed"):
+ run_failing_cell()
+
+ assert execution_context.duckdb_connection is original_connection
+
+
async def test_is_embedded(
execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
diff --git a/tests/_server/api/test_api_lifespans.py b/tests/_server/api/test_api_lifespans.py
new file mode 100644
index 0000000000..e34307a3c1
--- /dev/null
+++ b/tests/_server/api/test_api_lifespans.py
@@ -0,0 +1,85 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from marimo._server.api import lifespans
+from marimo._session.model import SessionMode
+
+
+async def test_cleanup_mcp_task_disconnects_client() -> None:
+ mcp_client = MagicMock()
+ mcp_client.disconnect_from_all_servers = AsyncMock()
+ task = MagicMock()
+ task.cancelled.return_value = False
+ task.result.return_value = mcp_client
+
+ with patch.object(
+ lifespans, "cancel_and_wait", new_callable=AsyncMock
+ ) as cancel_and_wait:
+ await lifespans._cleanup_mcp_task(task)
+
+ cancel_and_wait.assert_awaited_once_with(task)
+ mcp_client.disconnect_from_all_servers.assert_awaited_once_with()
+
+
+async def test_cleanup_mcp_task_logs_task_failure() -> None:
+ task = MagicMock()
+ task.cancelled.return_value = False
+ task.result.side_effect = RuntimeError("connect failed")
+
+ with (
+ patch.object(
+ lifespans, "cancel_and_wait", new_callable=AsyncMock
+ ) as cancel_and_wait,
+ patch.object(lifespans.LOGGER, "exception") as log_exception,
+ ):
+ await lifespans._cleanup_mcp_task(task)
+
+ cancel_and_wait.assert_awaited_once_with(task)
+ log_exception.assert_called_once_with(
+ "MCP connection task failed during cleanup"
+ )
+
+
+async def test_cleanup_mcp_task_logs_disconnect_failure() -> None:
+ mcp_client = MagicMock()
+ mcp_client.disconnect_from_all_servers = AsyncMock(
+ side_effect=RuntimeError("disconnect failed")
+ )
+ task = MagicMock()
+ task.cancelled.return_value = False
+ task.result.return_value = mcp_client
+
+ with (
+ patch.object(lifespans, "cancel_and_wait", new_callable=AsyncMock),
+ patch.object(lifespans.LOGGER, "exception") as log_exception,
+ ):
+ await lifespans._cleanup_mcp_task(task)
+
+ log_exception.assert_called_once_with(
+ "Failed to disconnect from MCP servers"
+ )
+
+
+async def test_lsp_cleanup_after_error() -> None:
+ state = MagicMock()
+ state.config_manager.get_config.return_value = {}
+ state.session_manager.mode = SessionMode.EDIT
+ task = MagicMock()
+
+ with (
+ patch.object(lifespans.AppState, "from_app", return_value=state),
+ patch.object(lifespans, "any_lsp_server_running", return_value=True),
+ patch.object(lifespans, "supervised_task", return_value=task),
+ patch.object(
+ lifespans, "cancel_and_wait", new_callable=AsyncMock
+ ) as cancel_and_wait,
+ ):
+ with pytest.raises(RuntimeError, match="server failed"):
+ async with lifespans.lsp(MagicMock()):
+ raise RuntimeError("server failed")
+
+ cancel_and_wait.assert_awaited_once_with(task)