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(asyncio): hardening pass — utilities, deprecated API cleanup, lifespan fix (#9552)

Myles Scolnick3d9032af6344
diff --git a/marimo/_server/ai/tools/tool_manager.py b/marimo/_server/ai/tools/tool_manager.py
index 390f9aac30..486120815e 100644
--- a/marimo/_server/ai/tools/tool_manager.py
+++ b/marimo/_server/ai/tools/tool_manager.py
@@ -306,11 +306,7 @@ class ToolManager:
if inspect.iscoroutinefunction(handler):
return await handler(arguments)
- else:
- # Run sync function in thread pool to avoid blocking
- return await asyncio.get_event_loop().run_in_executor(
- None, handler, arguments
- )
+ return await asyncio.to_thread(handler, arguments)
async def _invoke_mcp_tool(
self, tool_name: str, arguments: FunctionArgs
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 1b3f2508ec..742dec5d8e 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
-import contextlib
from typing import TYPE_CHECKING
from uuid import uuid4
@@ -33,6 +32,7 @@ from marimo._server.router import APIRouter
from marimo._server.uvicorn_utils import close_uvicorn
from marimo._server.workspace import MarimoFileKey
from marimo._types.ids import ConsumerId
+from marimo._utils.asyncio_utils import cancel_and_wait
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
@@ -335,9 +335,7 @@ async def execute_code(
yield build_done_event(session, listener)
finally:
- disconnect_task.cancel()
- with contextlib.suppress(asyncio.CancelledError):
- await disconnect_task
+ await cancel_and_wait(disconnect_task)
return StreamingResponse(sse_generator(), media_type="text/event-stream")
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.py
index 6dd05d90f1..d63581e887 100644
--- a/marimo/_server/api/endpoints/ws_endpoint.py
+++ b/marimo/_server/api/endpoints/ws_endpoint.py
@@ -369,7 +369,7 @@ class WebSocketHandler(SessionConsumer):
self.manager.close_session(self.params.session_id)
if session is not None:
- cancellation_handle = asyncio.get_event_loop().call_later(
+ cancellation_handle = asyncio.get_running_loop().call_later(
session.ttl_seconds, _close
)
self.cancel_close_handle = cancellation_handle
diff --git a/marimo/_server/api/interrupt.py b/marimo/_server/api/interrupt.py
index c1cab9ab5b..8fa6503917 100644
--- a/marimo/_server/api/interrupt.py
+++ b/marimo/_server/api/interrupt.py
@@ -21,7 +21,7 @@ class InterruptHandler:
def __init__(self, quiet: bool, shutdown: Callable[[], None]) -> None:
self.quiet = quiet
self.shutdown = shutdown
- self.loop = asyncio.get_event_loop()
+ self.loop = asyncio.get_running_loop()
self.original_handler = signal.getsignal(signal.SIGINT)
self._time_of_last_confirmation: float | None = None
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 10903d0b08..7c9a879969 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -27,6 +27,7 @@ from marimo._server.utils import initialize_mimetypes
from marimo._server.uvicorn_utils import close_uvicorn
from marimo._server.workspace import NEW_FILE
from marimo._session.model import SessionMode
+from marimo._utils.asyncio_utils import cancel_and_wait, supervised_task
from marimo._utils.subprocess import cancel_pending_reaps
if TYPE_CHECKING:
@@ -57,18 +58,15 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
LOGGER.debug("Language Servers are enabled")
# Start LSP server in background to avoid blocking server startup
- task = asyncio.create_task(session_mgr.start_lsp_server())
- background_tasks.add(task) # Keep a reference to prevent GC
- task.add_done_callback(background_tasks.discard) # Clean up when done
+ task = supervised_task(
+ session_mgr.start_lsp_server(),
+ name="lsp.start",
+ registry=background_tasks,
+ )
yield
- # Shutdown
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
+ await cancel_and_wait(task)
@contextlib.asynccontextmanager
@@ -119,24 +117,30 @@ async def mcp(app: Starlette) -> AsyncIterator[None]:
LOGGER.warning(f"Failed to connect MCP servers: {e}")
return None
- task = asyncio.create_task(background_connect_mcp_servers())
- background_tasks.add(task) # Keep a reference to prevent GC
- task.add_done_callback(background_tasks.discard) # Clean up when done
+ # Awaited below — opt out of supervisor logging to avoid duplicate logs.
+ task = supervised_task(
+ background_connect_mcp_servers(),
+ name="mcp.connect",
+ registry=background_tasks,
+ on_exception=lambda _exc: None,
+ )
yield
- # Shutdown
- task.cancel()
+ await cancel_and_wait(task)
+ if task.cancelled():
+ return
+
+ mcp_client = task.result()
+ if not mcp_client:
+ return
+
try:
- mcp_client = await task
- if mcp_client:
- LOGGER.info("Disconnecting from all MCP servers")
- await mcp_client.disconnect_from_all_servers()
- LOGGER.info("Successfully disconnected from all MCP servers")
- except asyncio.CancelledError:
- pass
+ 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 cleanup: {e}")
+ LOGGER.error(f"Error during MCP disconnect: {e}")
@contextlib.asynccontextmanager
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 57c8a8a113..bb84e8c12f 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -343,7 +343,7 @@ class _AsyncHTTPClient:
self, request: _URLRequest, stream: bool = False, max_retries: int = 2
) -> _AsyncHTTPResponse:
del stream
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
body = await self._collect_body(request)
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 8c84cc3ba7..cee285b552 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -746,7 +746,7 @@ class AutoExporter:
filepath = export_dir / download_name
# Run blocking file I/O in thread pool
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
await loop.run_in_executor(
self._executor, self._write_file_sync, filepath, content
)
diff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.py
index 3c115d659d..f65cead6e5 100644
--- a/marimo/_server/session_manager.py
+++ b/marimo/_server/session_manager.py
@@ -8,9 +8,8 @@ file watching, and LSP server management.
from __future__ import annotations
-import asyncio
from pathlib import Path
-from typing import TYPE_CHECKING, TypeVar
+from typing import TYPE_CHECKING
from marimo import _loggers
from marimo._cli.sandbox import SandboxMode
@@ -48,10 +47,11 @@ from marimo._session.session import Session, SessionImpl
from marimo._session.session_repository import SessionRepository
from marimo._session.types import KernelState
from marimo._types.ids import ConsumerId, SessionId
+from marimo._utils.asyncio_utils import fire_and_forget
from marimo._utils.file_watcher import FileWatcherManager
if TYPE_CHECKING:
- from collections.abc import Awaitable, Coroutine, Mapping
+ from collections.abc import Mapping
from marimo._session.notebook import AppFileManager
@@ -241,7 +241,10 @@ class SessionManager:
self._repository.add_sync(session_id, session)
# Emit session created event (triggers file watcher attachment, recents, etc.)
- run_async(self._event_bus.emit_session_created(session))
+ fire_and_forget(
+ self._event_bus.emit_session_created(session),
+ name="session.created",
+ )
return session
@@ -333,10 +336,11 @@ class SessionManager:
if resumed_session:
# Emit resume event (use new_session_id as both old and new since
# the strategy already updated it)
- run_async(
+ fire_and_forget(
self._event_bus.emit_session_resumed(
resumed_session, new_session_id
- )
+ ),
+ name="session.resumed",
)
return resumed_session
@@ -389,7 +393,10 @@ class SessionManager:
if session is None:
return False
- run_async(self._event_bus.emit_session_closed(session))
+ fire_and_forget(
+ self._event_bus.emit_session_closed(session),
+ name="session.closed",
+ )
session.close()
return True
@@ -418,28 +425,3 @@ class SessionManager:
def get_active_connection_count(self) -> int:
"""Get the number of sessions with active connections."""
return len(self._repository.get_active_sessions())
-
-
-T = TypeVar("T")
-
-
-def run_async(coro: Coroutine[None, None, T] | Awaitable[T]) -> T:
- """Run an async coroutine, handling various event loop states.
-
- 1. Event loop is running: create a task
- 2. Event loop exists but not running: run_until_complete
- 3. No event loop: create one with asyncio.run
- """
- try:
- loop = asyncio.get_event_loop()
- if loop.is_running():
- # Create a task and return it (fire and forget)
- # Note: This doesn't wait for completion
- task = asyncio.create_task(coro) # type: ignore
- return task # type: ignore
- else:
- # Run to completion
- return loop.run_until_complete(coro) # type: ignore
- except RuntimeError:
- # No event loop exists, create one
- return asyncio.run(coro) # type: ignore
diff --git a/marimo/_server/utils.py b/marimo/_server/utils.py
index 60821dcbff..a936a2f701 100644
--- a/marimo/_server/utils.py
+++ b/marimo/_server/utils.py
@@ -2,12 +2,20 @@
from __future__ import annotations
import asyncio
-import sys
from typing import TYPE_CHECKING, Any, TypeVar
+from marimo._utils.asyncio_utils import initialize_asyncio
+
if TYPE_CHECKING:
from collections.abc import Coroutine
+__all__ = [
+ "asyncio_run",
+ "initialize_asyncio",
+ "initialize_fd_limit",
+ "initialize_mimetypes",
+]
+
def initialize_mimetypes() -> None:
import mimetypes
@@ -34,16 +42,6 @@ def initialize_mimetypes() -> None:
)
-def initialize_asyncio() -> None:
- """Platform-specific initialization of asyncio.
-
- Sessions use the `add_reader()` API, which is only available in the
- SelectorEventLoop policy; Windows uses the Proactor by default.
- """
- if sys.platform == "win32":
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-
-
def initialize_fd_limit(limit: int) -> None:
"""Raise the limit on open file descriptors.
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index f9194fb073..adc965a906 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -144,11 +144,12 @@ class HeartbeatExtension(SessionExtension):
await _check_alive()
try:
- loop = asyncio.get_event_loop()
- self.heartbeat_task = loop.create_task(_heartbeat())
+ loop = asyncio.get_running_loop()
except RuntimeError:
- # This can happen if there is no event loop running
+ # No loop (tests, scripts) — nothing to schedule against.
self.heartbeat_task = None
+ return
+ self.heartbeat_task = loop.create_task(_heartbeat())
def _stop(self) -> None:
"""Stop the heartbeat monitoring."""
diff --git a/marimo/_utils/asyncio_utils.py b/marimo/_utils/asyncio_utils.py
new file mode 100644
index 0000000000..94297c5973
--- /dev/null
+++ b/marimo/_utils/asyncio_utils.py
@@ -0,0 +1,155 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Small in-tree asyncio helpers.
+
+- ``supervised_task`` / ``fire_and_forget``: create a task that won't be
+ garbage-collected mid-flight and whose non-cancellation exceptions
+ are always logged on completion (intended for fire-and-forget work
+ where the loop's default handler would otherwise swallow them).
+- ``cancel_and_wait``: the ``task.cancel(); await task`` /
+ ``except CancelledError`` dance, in one place.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import sys
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from marimo import _loggers
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Coroutine
+
+LOGGER = _loggers.marimo_logger()
+
+T = TypeVar("T")
+
+# Strong refs for fire_and_forget tasks; the loop only holds weak refs,
+# so without this the task can be GC'd mid-flight.
+_BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
+
+
+def _log_task_exception(task: asyncio.Task[Any]) -> None:
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ LOGGER.error(
+ "Exception in background task %r",
+ task.get_name(),
+ exc_info=exc,
+ )
+
+
+def supervised_task(
+ coro: Coroutine[Any, Any, T],
+ *,
+ name: str,
+ registry: set[asyncio.Task[Any]] | None = None,
+ on_exception: Callable[[BaseException], None] | None = None,
+) -> asyncio.Task[T]:
+ """Schedule ``coro`` with a strong reference and exception logging.
+
+ Intended for fire-and-forget or shutdown-cancelled background tasks.
+ A done-callback logs every non-cancellation exception at error level.
+
+ **Do not use this for tasks you plan to ``await``.** The done-callback
+ logs the exception even if the awaiter also handles it, producing
+ duplicate logs. For awaited tasks, prefer plain ``asyncio.create_task``
+ — or pass ``on_exception=lambda _: None`` to opt out of logging while
+ still benefiting from the strong-ref ``registry`` tracking.
+
+ Args:
+ coro: The coroutine to schedule.
+ name: Task name (shows up in logs and ``asyncio.all_tasks()``).
+ registry: Optional set the task is added to and removed from on
+ completion. Pass one for lifespan-scoped tracking.
+ on_exception: Optional callback that replaces the default error
+ log. Receives the exception; runs for non-cancellation
+ failures only.
+
+ Must be called from within a running event loop.
+ """
+ task = asyncio.create_task(coro, name=name)
+
+ if registry is not None:
+ registry.add(task)
+ task.add_done_callback(registry.discard)
+
+ if on_exception is not None:
+
+ def _handle(t: asyncio.Task[Any]) -> None:
+ if t.cancelled():
+ return
+ exc = t.exception()
+ if exc is not None:
+ try:
+ on_exception(exc)
+ except Exception:
+ LOGGER.exception(
+ "on_exception handler for task %r raised",
+ t.get_name(),
+ )
+
+ task.add_done_callback(_handle)
+ else:
+ task.add_done_callback(_log_task_exception)
+
+ return task
+
+
+def initialize_asyncio() -> None:
+ """Platform-specific initialization of asyncio.
+
+ Sessions use the ``add_reader()`` API, which is only available in
+ the SelectorEventLoop policy; Windows defaults to the Proactor.
+ """
+ if sys.platform == "win32":
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
+
+
+def fire_and_forget(
+ coro: Coroutine[Any, Any, Any], *, name: str
+) -> asyncio.Task[Any] | None:
+ """Schedule ``coro`` on the running loop; caller will not await it.
+
+ Falls back to a synchronous ``asyncio.run`` (returning ``None``) when
+ no loop is running. The platform policy is initialized first so the
+ fallback loop matches the selector-loop policy marimo relies on
+ elsewhere (required on Windows for ``add_reader``).
+ """
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ initialize_asyncio()
+ asyncio.run(coro)
+ return None
+ return supervised_task(coro, name=name, registry=_BACKGROUND_TASKS)
+
+
+async def cancel_and_wait(task: asyncio.Task[Any]) -> None:
+ """Cancel ``task`` and await its completion, suppressing ``CancelledError``.
+
+ If the task is already done, any attached exception is marked
+ retrieved so the loop doesn't log a "Task exception was never
+ retrieved" warning. The exception itself remains queryable via
+ ``task.exception()``. Non-cancellation exceptions raised during
+ cancellation propagate to the caller.
+ """
+ if task.done():
+ if not task.cancelled():
+ # Flag the exception as retrieved to silence the loop warning.
+ task.exception()
+ return
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+
+__all__ = [
+ "cancel_and_wait",
+ "fire_and_forget",
+ "initialize_asyncio",
+ "supervised_task",
+]
diff --git a/marimo/_utils/background_task.py b/marimo/_utils/background_task.py
index 8ee4db498a..4bf0beb619 100644
--- a/marimo/_utils/background_task.py
+++ b/marimo/_utils/background_task.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
+import concurrent.futures
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, final
@@ -96,20 +97,36 @@ class AsyncBackgroundTask(ABC):
"""
Synchronous version of stop that can be called from non-async code.
"""
+ if self.task is None or self.task.done():
+ self.running = False
+ return
+
+ # Reuse the task's loop — a fresh loop via ``asyncio.run`` would
+ # error with "future attached to a different event loop".
+ task_loop = self.task.get_loop()
+
try:
- loop = asyncio.get_event_loop()
- if loop.is_running():
- # Can't run a new event loop while one is running
- # Just set running to false and let the task complete naturally
- self.running = False
- return
- loop.run_until_complete(self.stop(timeout))
+ on_task_thread = asyncio.get_running_loop() is task_loop
except RuntimeError:
- # If there's no event loop, create a new one
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- loop.run_until_complete(self.stop(timeout))
- loop.close()
+ on_task_thread = False
+
+ if on_task_thread:
+ # Blocking here would deadlock our own loop; signal cooperative
+ # shutdown and return.
+ self.running = False
+ return
+
+ if task_loop.is_running():
+ future = asyncio.run_coroutine_threadsafe(
+ self.stop(timeout), task_loop
+ )
+ try:
+ future.result(timeout=timeout)
+ except concurrent.futures.TimeoutError:
+ self.running = False
+ return
+
+ task_loop.run_until_complete(self.stop(timeout))
async def wait_for_startup(self, timeout: float | None = None) -> None:
"""
diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.py
index 127902cb76..5e3557657f 100644
--- a/marimo/_utils/distributor.py
+++ b/marimo/_utils/distributor.py
@@ -59,6 +59,9 @@ class ConnectionDistributor(Distributor[T]):
def __init__(self, input_connection: TypedConnection[T]) -> None:
self.consumers: list[Consumer[T]] = []
self.input_connection = input_connection
+ # Captured on start() so stop() uses the same loop the reader
+ # was registered with — even if another loop is running by then.
+ self._loop: asyncio.AbstractEventLoop | None = None
def add_consumer(self, consumer: Consumer[T]) -> Disposable:
"""Add a consumer to the distributor."""
@@ -91,15 +94,20 @@ class ConnectionDistributor(Distributor[T]):
consumer(response)
def start(self) -> Disposable:
- """Start distributing the response."""
- asyncio.get_event_loop().add_reader(
- self.input_connection.fileno(), self._on_change
- )
+ """Start distributing the response.
+
+ Must be called from a thread that has a running event loop —
+ ``add_reader`` is loop-bound.
+ """
+ self._loop = asyncio.get_running_loop()
+ self._loop.add_reader(self.input_connection.fileno(), self._on_change)
return Disposable(self.stop)
def stop(self) -> None:
"""Stop distributing the response."""
- asyncio.get_event_loop().remove_reader(self.input_connection.fileno())
+ if self._loop is not None:
+ self._loop.remove_reader(self.input_connection.fileno())
+ self._loop = None
if not self.input_connection.closed:
self.input_connection.close()
self.consumers.clear()
diff --git a/marimo/_utils/file_watcher.py b/marimo/_utils/file_watcher.py
index a413a20c94..003e6e59ab 100644
--- a/marimo/_utils/file_watcher.py
+++ b/marimo/_utils/file_watcher.py
@@ -20,14 +20,17 @@ Callback = Callable[[Path], Coroutine[None, None, None]]
class FileWatcher(ABC):
@staticmethod
def create(path: Path, callback: Callback) -> FileWatcher:
+ # Capture the running loop now so background callbacks scheduled
+ # via ``run_coroutine_threadsafe`` target the right loop.
+ loop = asyncio.get_running_loop()
if DependencyManager.watchdog.has():
LOGGER.debug("Using watchdog file watcher")
- return _create_watchdog(path, callback, asyncio.get_event_loop())
+ return _create_watchdog(path, callback, loop)
else:
LOGGER.info(
"watchdog is not installed, using polling file watcher"
)
- return PollingFileWatcher(path, callback, asyncio.get_event_loop())
+ return PollingFileWatcher(path, callback, loop)
def __init__(
self,
diff --git a/marimo/_utils/lifespans.py b/marimo/_utils/lifespans.py
index 4eda151185..956a296a7c 100644
--- a/marimo/_utils/lifespans.py
+++ b/marimo/_utils/lifespans.py
@@ -1,7 +1,6 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import asyncio
import contextlib
from collections.abc import AsyncIterator, Sequence
from contextlib import AbstractAsyncContextManager
@@ -37,15 +36,14 @@ class Lifespans(Generic[T]):
app: T,
lifespans: LifespanList[T],
) -> AsyncIterator[None]:
+ # Don't swallow CancelledError — the ASGI server uses cancellation
+ # to drive graceful shutdown of the lifespan chain.
exit_stack = contextlib.AsyncExitStack()
- try:
- async with exit_stack:
- for lifespan in lifespans:
- LOGGER.debug(f"Setup: {lifespan.__name__}")
- await exit_stack.enter_async_context(lifespan(app))
- yield
- except asyncio.CancelledError:
- pass
+ async with exit_stack:
+ for lifespan in lifespans:
+ LOGGER.debug(f"Setup: {lifespan.__name__}")
+ await exit_stack.enter_async_context(lifespan(app))
+ yield
def __call__(self, app: T) -> AbstractAsyncContextManager[None]:
return self._manager(app, lifespans=self._lifespans)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 245ce376a9..33b7a084e1 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -551,7 +551,7 @@ def test_ttl_close_skips_when_session_has_active_consumer() -> None:
cleanup_fn = MagicMock()
with patch(
- "marimo._server.api.endpoints.ws_endpoint.asyncio.get_event_loop"
+ "marimo._server.api.endpoints.ws_endpoint.asyncio.get_running_loop"
) as mock_loop:
mock_loop.return_value.call_later = capture_call_later
handler._on_disconnect(Exception("disconnect"), cleanup_fn)
@@ -658,7 +658,7 @@ def test_run_mode_ttl_close_with_manager_ttl_none() -> None:
cleanup_fn = MagicMock()
with patch(
- "marimo._server.api.endpoints.ws_endpoint.asyncio.get_event_loop"
+ "marimo._server.api.endpoints.ws_endpoint.asyncio.get_running_loop"
) as mock_loop:
mock_loop.return_value.call_later = capture_call_later
handler._on_disconnect(Exception("disconnect"), cleanup_fn)
diff --git a/tests/_utils/test_asyncio_utils.py b/tests/_utils/test_asyncio_utils.py
new file mode 100644
index 0000000000..77f76a72ed
--- /dev/null
+++ b/tests/_utils/test_asyncio_utils.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from marimo._utils.asyncio_utils import (
+ cancel_and_wait,
+ fire_and_forget,
+ supervised_task,
+)
+
+
+async def test_supervised_task_runs_and_returns_result() -> None:
+ async def work() -> int:
+ await asyncio.sleep(0)
+ return 42
+
+ task = supervised_task(work(), name="work")
+ assert await task == 42
+
+
+async def test_supervised_task_logs_unhandled_exception(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from marimo._utils import asyncio_utils
+
+ seen: list[str] = []
+
+ def fake_error(msg: str, *args: object, **kwargs: object) -> None:
+ del kwargs
+ seen.append(msg % args if args else msg)
+
+ monkeypatch.setattr(asyncio_utils.LOGGER, "error", fake_error)
+
+ async def boom() -> None:
+ raise ValueError("nope")
+
+ task = supervised_task(boom(), name="boom")
+ with pytest.raises(ValueError):
+ await task
+ await asyncio.sleep(0)
+ assert any("boom" in msg for msg in seen)
+
+
+async def test_supervised_task_registry_lifecycle() -> None:
+ registry: set[asyncio.Task[object]] = set()
+
+ async def work() -> None:
+ await asyncio.sleep(0)
+
+ task = supervised_task(work(), name="work", registry=registry)
+ assert task in registry
+ await task
+ await asyncio.sleep(0)
+ assert task not in registry
+
+
+async def test_supervised_task_custom_on_exception() -> None:
+ seen: list[BaseException] = []
+
+ async def boom() -> None:
+ raise RuntimeError("x")
+
+ task = supervised_task(
+ boom(), name="boom", on_exception=lambda e: seen.append(e)
+ )
+ with pytest.raises(RuntimeError):
+ await task
+ await asyncio.sleep(0)
+ assert len(seen) == 1
+ assert isinstance(seen[0], RuntimeError)
+
+
+async def test_fire_and_forget_with_running_loop() -> None:
+ started = asyncio.Event()
+ finished = asyncio.Event()
+
+ async def work() -> None:
+ started.set()
+ await asyncio.sleep(0)
+ finished.set()
+
+ task = fire_and_forget(work(), name="ff")
+ assert task is not None
+ await started.wait()
+ await finished.wait()
+
+
+def test_fire_and_forget_without_running_loop_runs_synchronously() -> None:
+ ran = False
+
+ async def work() -> None:
+ nonlocal ran
+ ran = True
+
+ result = fire_and_forget(work(), name="ff")
+ assert result is None
+ assert ran
+
+
+async def test_cancel_and_wait_swallows_cancelled_error() -> None:
+ async def sleeper() -> None:
+ await asyncio.sleep(10)
+
+ task = asyncio.create_task(sleeper())
+ await asyncio.sleep(0)
+ await cancel_and_wait(task)
+ assert task.cancelled()
+
+
+async def test_cancel_and_wait_preserves_exception_on_done_task() -> None:
+ # If the task already failed before we tried to cancel, the
+ # exception is marked retrieved (no "Task exception was never
+ # retrieved" warning) but stays queryable.
+ async def boom() -> None:
+ raise ValueError("boom")
+
+ task = asyncio.create_task(boom())
+ await asyncio.sleep(0)
+ await cancel_and_wait(task)
+ assert isinstance(task.exception(), ValueError)
+
+
+async def test_cancel_and_wait_done_task_is_noop() -> None:
+ async def fast() -> int:
+ return 1
+
+ task = asyncio.create_task(fast())
+ await task
+ await cancel_and_wait(task)
diff --git a/tests/_utils/test_background_task.py b/tests/_utils/test_background_task.py
index 42aa0dec55..a1f045b0df 100644
--- a/tests/_utils/test_background_task.py
+++ b/tests/_utils/test_background_task.py
@@ -95,3 +95,45 @@ async def test_stop_sync():
assert task.task is not None
await asyncio.sleep(0) # Wait a tick
assert task.task.done(), "Task should be done"
+
+
+def test_stop_sync_from_other_thread_drives_shutdown():
+ """stop_sync called from a non-loop thread should block on the
+ task's own loop and honor the timeout, instead of silently
+ returning without ever stopping the task."""
+ import threading
+
+ bg_task = SimpleTask()
+ loop_ready = threading.Event()
+ loop_done = threading.Event()
+ loop_holder: dict[str, asyncio.AbstractEventLoop] = {}
+
+ def run_loop() -> None:
+ loop = asyncio.new_event_loop()
+ loop_holder["loop"] = loop
+ asyncio.set_event_loop(loop)
+ # ``start()`` calls ``asyncio.create_task`` which requires a
+ # running loop, so schedule it on the loop itself.
+ loop.call_soon(bg_task.start)
+ loop.call_soon(loop_ready.set)
+ try:
+ loop.run_forever()
+ finally:
+ loop.close()
+ loop_done.set()
+
+ thread = threading.Thread(target=run_loop, daemon=True)
+ thread.start()
+ loop_ready.wait(timeout=2.0)
+
+ # From the main thread, stop the task that's running on the
+ # background-thread loop. This exercises the run_coroutine_threadsafe
+ # path; without that, the timeout would be ignored and the task
+ # would still be alive.
+ bg_task.stop_sync(timeout=1.0)
+ assert bg_task.task is not None
+ assert bg_task.task.done()
+
+ # Tear down the background loop.
+ loop_holder["loop"].call_soon_threadsafe(loop_holder["loop"].stop)
+ loop_done.wait(timeout=2.0)
diff --git a/tests/_utils/test_distributor.py b/tests/_utils/test_distributor.py
index 3bf4925350..57a00bb04c 100644
--- a/tests/_utils/test_distributor.py
+++ b/tests/_utils/test_distributor.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import queue
import time
-from typing import Any
from unittest.mock import MagicMock, patch
from marimo._utils.distributor import (
@@ -11,9 +10,9 @@ from marimo._utils.distributor import (
)
-@patch("asyncio.get_event_loop")
-def test_start(mock_get_event_loop: Any) -> None:
- mock_get_event_loop.return_value = MagicMock()
+@patch("asyncio.get_running_loop")
+def test_start(mock_get_running_loop: MagicMock) -> None:
+ mock_get_running_loop.return_value = MagicMock()
mock_connection = MagicMock()
distributor = ConnectionDistributor[str](mock_connection)
diff --git a/tests/_utils/test_lifespans.py b/tests/_utils/test_lifespans.py
index e345a6339c..58f5cb62fa 100644
--- a/tests/_utils/test_lifespans.py
+++ b/tests/_utils/test_lifespans.py
@@ -1,12 +1,18 @@
+from __future__ import annotations
+
import asyncio
-from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
+from typing import TYPE_CHECKING
import pytest
-from marimo._types.lifespan import Lifespan
from marimo._utils.lifespans import Lifespans
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Callable
+
+ from marimo._types.lifespan import Lifespan
+
class MockApp:
def __init__(self) -> None:
@@ -117,10 +123,15 @@ async def test_lifespan_cancellation() -> None:
[mock_lifespan("test1"), mock_lifespan("test2")]
)
- async with lifespans(app):
- assert app.setup_calls == ["test1", "test2"]
- # Simulate cancellation
- raise asyncio.CancelledError()
+ # CancelledError must propagate out of the lifespan chain — the ASGI
+ # server depends on it for graceful shutdown. Teardown still runs
+ # via the inner AsyncExitStack.
+ async def run() -> None:
+ async with lifespans(app):
+ assert app.setup_calls == ["test1", "test2"]
+ raise asyncio.CancelledError()
+
+ with pytest.raises(asyncio.CancelledError):
+ await run()
- # Teardown should still be called even on cancellation
assert app.teardown_calls == ["test2", "test1"]