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: hold references to asyncio tasks (#9261)
Akshay Agrawalf6f5753dd689
diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.pyindex c5a3ebe30c..c2b049f449 100644--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport sys-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom marimo import _loggersfrom marimo._ast.cell import CellConfig@@ -27,6 +27,9 @@ LOGGER = _loggers.marimo_logger()LORO_ALLOWED = sys.version_info >= (3, 11)+# Strong refs so fire-and-forget tasks aren't GC'd mid-flight.+_background_tasks: set[asyncio.Task[Any]] = set()+def build_kernel_ready(session: Session,@@ -184,4 +187,8 @@ def _try_init_rtc_doc("RTC: Loro is not installed, disabling real-time collaboration")else:- asyncio.create_task(doc_manager.create_doc(file_key, cell_ids, codes))+ task = asyncio.create_task(+ doc_manager.create_doc(file_key, cell_ids, codes)+ )+ _background_tasks.add(task)+ task.add_done_callback(_background_tasks.discard)diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 06aaa34cfd..6dd05d90f1 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -66,6 +66,9 @@ router = APIRouter()DOC_MANAGER = LoroDocManager()+# Strong refs so fire-and-forget tasks aren't GC'd mid-flight.+_background_tasks: set[asyncio.Task[None]] = set()+@router.websocket("/ws")async def websocket_endpoint(@@ -500,11 +503,13 @@ class WebSocketHandler(SessionConsumer):or self.status == ConnectionState.CONNECTING) and self.websocket.application_state is WebSocketState.CONNECTEDif is_connected:- asyncio.create_task(+ task = asyncio.create_task(self._safe_close(WebSocketCodes.NORMAL_CLOSE, "MARIMO_SHUTDOWN"))+ _background_tasks.add(task)+ task.add_done_callback(_background_tasks.discard)if self.ws_future:self.ws_future.cancel()diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex 6bcbaaa26f..6880c3d0b1 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -695,7 +695,8 @@ class TimeoutMiddleware(BaseHTTPMiddleware):self.app_state.timeout_tracker = time.time()self.timeout_duration_minutes = timeout_duration_minutes- asyncio.create_task(self.monitor())+ # Hold a strong reference so the monitor task isn't GC'd.+ self._monitor_task = asyncio.create_task(self.monitor())async def __call__(self, scope: Scope, receive: Receive, send: Senddiff --git a/marimo/_utils/file_watcher.py b/marimo/_utils/file_watcher.pyindex 54b6b0a9b7..b8655a5ac3 100644--- a/marimo/_utils/file_watcher.py+++ b/marimo/_utils/file_watcher.py@@ -68,10 +68,12 @@ class PollingFileWatcher(FileWatcher):self.loop = loopself.last_modified: float | None = self._get_modified()self._missing_count = 0+ self._task: asyncio.Task[None] | None = Nonedef start(self) -> None:self._running = True- self.loop.create_task(self._poll())+ # Hold a strong reference so the task isn't GC'd mid-poll.+ self._task = self.loop.create_task(self._poll())def stop(self) -> None:self._running = Falsediff --git a/pyproject.toml b/pyproject.tomlindex 539fe3aa11..176cf47a2b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -417,6 +417,7 @@ extend-select = ["D419","PGH004", # Use specific rule codes when using noqa"PGH005", # Invalid unittest.mock.Mock methods/attributes/properties+ "RUF006", # Store a reference to the return value of asyncio.create_task# "S101", # Checks use `assert` outside the test cases, test cases should be added into the exclusions"B004", # Checks for use of hasattr(x, "__call__") and replaces it with callable(x)"B006", # Checks for uses of mutable objects as function argument defaults.