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: potential rtc deadlock (#4908)
Myles Scolnicke8febb519b93
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 0ade6c0351..4b768f46fe 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -722,11 +722,11 @@ class WebsocketHandler(SessionConsumer):# so we can just store this in memory.# We still want to check for updates (which are debounced 24 hours)# but don't keep toasting.- global HAS_TOASTED- if HAS_TOASTED:+ global has_toasted+ if has_toasted:return- HAS_TOASTED = True+ has_toasted = Truetitle = f"Update available {current_version} → {latest_version}"release_url = "https://github.com/marimo-team/marimo/releases"@@ -755,4 +755,4 @@ class WebsocketHandler(SessionConsumer):self._replay_previous_session(session)-HAS_TOASTED = False+has_toasted = Falsediff --git a/marimo/_server/rtc/doc.py b/marimo/_server/rtc/doc.pyindex 4e5b08bdc0..8dc3726c74 100644--- a/marimo/_server/rtc/doc.py+++ b/marimo/_server/rtc/doc.py@@ -40,7 +40,7 @@ class LoroDocManager:f"RTC: Removing loro doc for file {file_key} as it has no clients")# Clean up the document- await self.remove_doc(file_key)+ await self._do_remove_doc(file_key)except asyncio.CancelledError:# Task was cancelled due to client reconnectionLOGGER.debug(@@ -130,6 +130,8 @@ class LoroDocManager:update_queue: asyncio.Queue[bytes],) -> None:"""Clean up a loro client and potentially the doc if no clients remain."""+ should_create_cleaner = False+async with self.loro_docs_lock:if file_key not in self.loro_docs_clients:return@@ -141,25 +143,25 @@ class LoroDocManager:cleaner = self.loro_docs_cleaners.get(file_key, None)if cleaner is not None:cleaner.cancel()- self.loro_docs_cleaners[file_key] = None- # Create a new cleaner with timeout of 60 secondsself.loro_docs_cleaners[file_key] = None+ should_create_cleaner = True- # Create the cleaner task outside the lock- if (- file_key in self.loro_docs_clients- and len(self.loro_docs_clients[file_key]) == 0- ):+ # Create the cleaner task outside the lock to avoid deadlocks+ if should_create_cleaner:self.loro_docs_cleaners[file_key] = asyncio.create_task(self._clean_loro_doc(file_key, 60.0))+ async def _do_remove_doc(self, file_key: MarimoFileKey) -> None:+ """Actual implementation of removing a doc, separate from remove_doc to avoid deadlocks."""+ if file_key in self.loro_docs:+ del self.loro_docs[file_key]+ if file_key in self.loro_docs_clients:+ del self.loro_docs_clients[file_key]+ if file_key in self.loro_docs_cleaners:+ del self.loro_docs_cleaners[file_key]+async def remove_doc(self, file_key: MarimoFileKey) -> None:- """Remove a loro doc and all associated clients, without waiting."""+ """Remove a loro doc and all associated clients"""async with self.loro_docs_lock:- if file_key in self.loro_docs:- del self.loro_docs[file_key]- if file_key in self.loro_docs_clients:- del self.loro_docs_clients[file_key]- if file_key in self.loro_docs_cleaners:- del self.loro_docs_cleaners[file_key]+ await self._do_remove_doc(file_key)diff --git a/pyproject.toml b/pyproject.tomlindex 65890db5f7..a5fe6e5882 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -222,7 +222,7 @@ extra-dependencies = ["pytest~=8.3.4","pytest-timeout~=2.3.1","pytest-codecov~=0.6.1",- "pytest-asyncio~=0.25.2",+ "pytest-asyncio~=0.26.0",][[tool.hatch.envs.test.matrix]]@@ -250,7 +250,7 @@ extra-dependencies = ["pytest~=8.3.4","pytest-timeout~=2.3.1","pytest-codecov~=0.6.1",- "pytest-asyncio~=0.25.2",+ "pytest-asyncio~=0.26.0","python-lsp-server>=1.10.0",# For testing mo.ui.chart, table, ..."vl-convert-python",diff --git a/tests/_server/rtc/test_rtc_doc.py b/tests/_server/rtc/test_rtc_doc.pyindex c5136430f6..4e848abd85 100644--- a/tests/_server/rtc/test_rtc_doc.py+++ b/tests/_server/rtc/test_rtc_doc.py@@ -1,4 +1,5 @@import asyncio+import sysfrom collections.abc import AsyncGeneratorfrom typing import cast@@ -240,3 +241,84 @@ async def test_concurrent_doc_removal(setup_doc_manager: None) -> None:assert file_key not in doc_manager.loro_docsassert file_key not in doc_manager.loro_docs_clientsassert file_key not in doc_manager.loro_docs_cleaners+++ sys.version_info < (3, 11), reason="Python 3.10+ required for Barrier"+)+async def test_prevent_lock_deadlock(setup_doc_manager: None) -> None:+ """Test that our deadlock prevention measures work correctly.++ This test simulates the scenario that could cause a deadlock:+ 1. A client disconnects, starting the cleanup process+ 2. Another operation acquires the lock before cleanup timer finishes+ 3. Cleanup timer expires and tries to acquire the lock++ The fixed implementation should handle this without deadlocking.+ """+ del setup_doc_manager+ file_key = MarimoFileKey("test_file")++ # Create a doc and add a client+ doc = LoroDoc()+ doc_manager.loro_docs[file_key] = doc+ queue = asyncio.Queue[bytes]()+ doc_manager.add_client_to_doc(file_key, queue)++ # Set a very short cleanup timeout for testing+ original_timeout = 60.0+ cleanup_timeout = 0.1 # 100ms++ # Create a barrier to coordinate tasks+ barrier = asyncio.Barrier(2)+ long_operation_done = asyncio.Event()++ # Task 1: Remove client, which will schedule cleanup with short timeout+ async def remove_client_task() -> None:+ await doc_manager.remove_client(file_key, queue)+ # Wait at barrier to synchronize with the long operation+ await barrier.wait()+ # Wait for long operation to complete+ await long_operation_done.wait()++ # Task 2: Simulate a long operation that holds the lock+ async def long_lock_operation() -> None:+ # Wait for remove_client to schedule the cleanup+ await barrier.wait()++ # Acquire the lock and hold it for longer than the cleanup timeout+ async with doc_manager.loro_docs_lock:+ # Sleep while holding the lock (longer than cleanup timeout)+ await asyncio.sleep(cleanup_timeout * 2)++ # Signal that we're done holding the lock+ long_operation_done.set()++ # Modified test version of _clean_loro_doc with shorter timeout+ original_clean_loro_doc = doc_manager._clean_loro_doc++ async def test_clean_loro_doc(+ file_key: MarimoFileKey, timeout: float = original_timeout+ ) -> None:+ del timeout+ # Override timeout with our test value+ await original_clean_loro_doc(file_key, cleanup_timeout)++ # Override the method for this test+ doc_manager._clean_loro_doc = test_clean_loro_doc++ try:+ # Run both tasks simultaneously+ task1 = asyncio.create_task(remove_client_task())+ task2 = asyncio.create_task(long_lock_operation())++ # This should complete without deadlocking+ await asyncio.gather(task1, task2)++ # Verify the doc was properly cleaned up+ assert file_key not in doc_manager.loro_docs+ assert file_key not in doc_manager.loro_docs_clients+ assert file_key not in doc_manager.loro_docs_cleaners+ finally:+ # Restore the original method+ doc_manager._clean_loro_doc = original_clean_loro_doc