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
chore(asyncio): migrate remaining background-task sites to asyncio_utils (#9596)
Myles Scolnick13c3f534eccc
diff --git a/marimo/_server/ai/mcp/client.py b/marimo/_server/ai/mcp/client.pyindex 5da01d1e21..d36c39c1d1 100644--- a/marimo/_server/ai/mcp/client.py+++ b/marimo/_server/ai/mcp/client.py@@ -20,6 +20,7 @@ from marimo._server.ai.mcp.transport import (MCPTransportRegistry,)from marimo._server.ai.mcp.types import MCPToolArgs+from marimo._utils.asyncio_utils import cancel_and_wait, supervised_taskif TYPE_CHECKING:from anyio.streams.memory import (@@ -262,8 +263,9 @@ class MCPClient:await self._discover_tools(connection)if server_name not in self.health_check_tasks:- self.health_check_tasks[server_name] = asyncio.create_task(- self._monitor_server_health(server_name)+ self.health_check_tasks[server_name] = supervised_task(+ self._monitor_server_health(server_name),+ name=f"mcp.health.{server_name}",)# Signal that connection is established@@ -331,9 +333,12 @@ class MCPClient:self._update_server_status(server_name, MCPServerStatus.CONNECTING)self._remove_server_tools(server_name)- # Create task to run existing connection logic+ # Create task to run existing connection logic. Not supervised:+ # this task is awaited in disconnect_from_server(), so supervisor+ # logging would duplicate the awaiter's error handling.connection_task = asyncio.create_task(- self._connection_lifecycle(server_name)+ self._connection_lifecycle(server_name),+ name=f"mcp.lifecycle.{server_name}",)connection.connection_task = connection_task@@ -790,12 +795,7 @@ class MCPClient:if server_name is not None:# Cancel single server monitoringif server_name in self.health_check_tasks:- task = self.health_check_tasks[server_name]- task.cancel()- try:- await task- except asyncio.CancelledError:- pass+ await cancel_and_wait(self.health_check_tasks[server_name])del self.health_check_tasks[server_name]LOGGER.debug(f"Cancelled health monitoring for {server_name}")else:diff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.pyindex b0580b3400..91a3722dc3 100644--- a/marimo/_server/api/endpoints/terminal.py+++ b/marimo/_server/api/endpoints/terminal.py@@ -19,6 +19,7 @@ from marimo._server.api.deps import AppStatefrom marimo._server.codes import WebSocketCodesfrom marimo._server.router import APIRouterfrom marimo._session.model import SessionMode+from marimo._utils.asyncio_utils import cancel_and_waitfrom marimo._utils.platform import is_pyodide, is_windowsif TYPE_CHECKING:@@ -331,12 +332,7 @@ async def _write_to_pty(async def _cancel_tasks(tasks: Iterable[asyncio.Task[Any]]) -> None:for task in tasks:- if not task.done():- task.cancel()- try:- await task- except asyncio.CancelledError:- pass+ await cancel_and_wait(task)def supports_terminal() -> bool:diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex bb84e8c12f..bfe3199226 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -41,6 +41,7 @@ from marimo._server.codes import WebSocketCodesfrom marimo._server.uvicorn_utils import close_uvicornfrom marimo._session.model import SessionModefrom marimo._tracer import server_tracer+from marimo._utils.asyncio_utils import supervised_taskfrom marimo._utils.print import print_tabbedif TYPE_CHECKING:@@ -700,8 +701,9 @@ class TimeoutMiddleware(BaseHTTPMiddleware):self.app_state.timeout_tracker = time.time()self.timeout_duration_minutes = timeout_duration_minutes- # Hold a strong reference so the monitor task isn't GC'd.- self._monitor_task = asyncio.create_task(self.monitor())+ self._monitor_task = supervised_task(+ self.monitor(), name="timeout.monitor"+ )async def __call__(self, scope: Scope, receive: Receive, send: Senddiff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.pyindex 7d476a981f..e51d2d4c46 100644--- a/marimo/_server/lsp.py+++ b/marimo/_server/lsp.py@@ -25,6 +25,7 @@ from marimo._server.models.lsp import (LspServerStatus,)from marimo._tracer import server_tracer+from marimo._utils.asyncio_utils import supervised_taskfrom marimo._utils.net import find_free_portfrom marimo._utils.paths import marimo_package_pathfrom marimo._utils.platform import is_windows@@ -178,8 +179,9 @@ class BaseLspServer(LspServer):self._health_check_task is Noneor self._health_check_task.done()):- self._health_check_task = asyncio.create_task(- self._monitor_process_health()+ self._health_check_task = supervised_task(+ self._monitor_process_health(),+ name=f"lsp.health.{self.id}",)except Exception as e:diff --git a/marimo/_server/rtc/doc.py b/marimo/_server/rtc/doc.pyindex b63ed3ca3e..bcd04a212d 100644--- a/marimo/_server/rtc/doc.py+++ b/marimo/_server/rtc/doc.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKINGfrom marimo import _loggersfrom marimo._server.workspace import FileKeyfrom marimo._types.ids import CellId_t+from marimo._utils.asyncio_utils import supervised_taskif TYPE_CHECKING:from loro import LoroDoc@@ -143,8 +144,9 @@ class LoroDocManager:# Create the cleaner task outside the lock to avoid deadlocksif should_create_cleaner:- self.loro_docs_cleaners[file_key] = asyncio.create_task(- self._clean_loro_doc(file_key, 60.0)+ self.loro_docs_cleaners[file_key] = supervised_task(+ self._clean_loro_doc(file_key, 60.0),+ name=f"rtc.cleaner.{file_key}",)async def _do_remove_doc(self, file_key: FileKey) -> None: