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(kernel): callback bug fixes in cache clear, dataset connections, and model updates (#9588)
Myles Scolnicka8dd4b6716d1
diff --git a/marimo/_runtime/callbacks/cache.py b/marimo/_runtime/callbacks/cache.pyindex ceefc4149c..e1a6f3aa43 100644--- a/marimo/_runtime/callbacks/cache.py+++ b/marimo/_runtime/callbacks/cache.py@@ -27,14 +27,13 @@ class CacheCallbacks:async def clear_cache(self, request: ClearCacheCommand) -> None:del requestfrom marimo._save.cache import CacheContext- from marimo._save.loaders import BasePersistenceLoaderctx = get_context()saved = 0for obj in ctx.globals.values():if isinstance(obj, CacheContext):- if isinstance(obj.loader, BasePersistenceLoader):- obj.loader.clear()+ # Loader.clear is a no-op by default; safe on any subclass.+ obj.loader.clear()broadcast_notification(CacheClearedNotification(bytes_freed=saved))diff --git a/marimo/_runtime/callbacks/datasets.py b/marimo/_runtime/callbacks/datasets.pyindex 57e7c46a7c..a401fdaab3 100644--- a/marimo/_runtime/callbacks/datasets.py+++ b/marimo/_runtime/callbacks/datasets.py@@ -327,11 +327,11 @@ class DatasetCallbacks:async def preview_datasource_connection(self, request: ListDataSourceConnectionCommand) -> None:- """Broadcasts a datasource connection for a given engine"""+ """Broadcasts a datasource connection for a given engine."""variable_name = cast(VariableName, request.engine)- engine, error = self.get_engine_catalog(variable_name)+ engine, error = self._kernel.get_sql_connection(variable_name)if error is not None or engine is None:- LOGGER.error("Failed to get engine %s", variable_name)+ LOGGER.error("Failed to get engine %s: %s", variable_name, error)returndata_source_connection = engine_to_data_source_connection(diff --git a/tests/_runtime/test_kernel_request_handlers.py b/tests/_runtime/test_kernel_request_handlers.pynew file mode 100644index 0000000000..9dd52da484--- /dev/null+++ b/tests/_runtime/test_kernel_request_handlers.py@@ -0,0 +1,80 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from marimo._runtime.commands import ModelCommand, ModelUpdateMessage+from marimo._runtime.kernel_request_handlers import KernelRequestHandlers+from marimo._types.ids import WidgetModelId++if TYPE_CHECKING:+ from tests.conftest import MockedKernel+++class TestReceiveModelMessage:+ @pytest.fixture+ def model_command(self) -> ModelCommand:+ return ModelCommand(+ model_id=WidgetModelId("comm-id"),+ message=ModelUpdateMessage(state={}, buffer_paths=[]),+ buffers=[],+ )++ async def test_empty_state_skips_ui_dispatch(+ self,+ mocked_kernel: MockedKernel,+ model_command: ModelCommand,+ ) -> None:+ kernel = mocked_kernel.k+ handlers = KernelRequestHandlers(kernel)++ with (+ patch(+ "marimo._runtime.kernel_request_handlers.WIDGET_COMM_MANAGER"+ ) as mock_comm_manager,+ patch.object(+ kernel,+ "set_ui_element_value",+ new=AsyncMock(),+ ) as mock_set_ui,+ ):+ mock_comm_manager.receive_comm_message.return_value = (+ "ui-element-id",+ {},+ )+ kernel.state_updates = MagicMock()+ kernel.state_updates.__bool__ = MagicMock(return_value=False)++ await handlers._handle_receive_model_message(model_command)++ mock_set_ui.assert_not_called()++ async def test_non_empty_state_dispatches(+ self,+ mocked_kernel: MockedKernel,+ model_command: ModelCommand,+ ) -> None:+ kernel = mocked_kernel.k+ handlers = KernelRequestHandlers(kernel)++ with (+ patch(+ "marimo._runtime.kernel_request_handlers.WIDGET_COMM_MANAGER"+ ) as mock_comm_manager,+ patch.object(+ kernel,+ "set_ui_element_value",+ new=AsyncMock(return_value=True),+ ) as mock_set_ui,+ ):+ mock_comm_manager.receive_comm_message.return_value = (+ "ui-element-id",+ {"value": 1},+ )++ await handlers._handle_receive_model_message(model_command)++ mock_set_ui.assert_awaited_once()diff --git a/tests/_runtime/test_runtime_cache.py b/tests/_runtime/test_runtime_cache.pynew file mode 100644index 0000000000..c30d8a9be8--- /dev/null+++ b/tests/_runtime/test_runtime_cache.py@@ -0,0 +1,53 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING++from marimo._messaging.notification import CacheClearedNotification+from marimo._runtime.commands import ClearCacheCommand+from marimo._save.cache import CacheContext+from marimo._save.loaders.memory import MemoryLoader++if TYPE_CHECKING:+ from tests.conftest import MockedKernel+++class _RecordingMemoryLoader(MemoryLoader):+ def __init__(self) -> None:+ super().__init__("test")+ self.cleared = False++ def clear(self) -> None:+ self.cleared = True+ super().clear()+++class _StubCacheContext(CacheContext):+ def __init__(self, loader: MemoryLoader) -> None:+ # CacheContext.loader calls self._loader(); wrap in a zero-arg callable.+ self._loader = lambda: loader # type: ignore[assignment]++ @property+ def last_hash(self) -> str | None:+ return None+++class TestClearCache:+ async def test_clears_memory_loaders(+ self, mocked_kernel: MockedKernel+ ) -> None:+ k = mocked_kernel.k+ stream = mocked_kernel.stream++ memory_loader = _RecordingMemoryLoader()+ k.globals["_cache_a"] = _StubCacheContext(memory_loader)++ await k.handle_message(ClearCacheCommand())++ assert memory_loader.cleared is True+ notifications = [+ op+ for op in stream.operations+ if isinstance(op, CacheClearedNotification)+ ]+ assert len(notifications) == 1diff --git a/tests/_runtime/test_runtime_datasets.py b/tests/_runtime/test_runtime_datasets.pyindex 992ead5caf..6ac83bb37f 100644--- a/tests/_runtime/test_runtime_datasets.py+++ b/tests/_runtime/test_runtime_datasets.py@@ -400,6 +400,38 @@ class TestPreviewDatasourceConnection:]assert preview_datasource_connection_results == []+ @pytest.mark.skipif(not HAS_SQL, reason="SQL deps not available")+ async def test_query_only_engine_is_broadcast(+ self,+ mocked_kernel: MockedKernel,+ connection_requests: list[ExecuteCellCommand],+ ) -> None:+ k = mocked_kernel.k+ stream = mocked_kernel.stream++ await k.run(connection_requests)++ # k.run emits auto-discovery notifications; take a baseline.+ baseline = sum(+ 1+ for op in stream.operations+ if isinstance(op, DataSourceConnectionsNotification)+ )++ await k.handle_message(+ ListDataSourceConnectionCommand(engine=SQLITE_CONN)+ )++ results = [+ op+ for op in stream.operations+ if isinstance(op, DataSourceConnectionsNotification)+ ]+ assert len(results) == baseline + 1+ connection = results[-1].connections[0]+ assert connection.name == SQLITE_CONN+ assert connection.databases == []+@pytest.mark.xfail(reason="Should have only 2 connections (duckdb and sqlite)")