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.

Fix three issues with `mo.mpl.interactive` in `marimo run` mode (#8747): (#8760)

Myles Scolnickfa67e1db00c1
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index fbaaabf7c8..a5376ed1b8 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -8,6 +8,7 @@ Adapted from https://matplotlib.org/stable/gallery/user_interfaces/embedding_web
from __future__ import annotations
import io
+import warnings
from typing import TYPE_CHECKING, Any, Union
from marimo import _loggers
@@ -43,8 +44,19 @@ def new_figure_manager_given_figure(
class FigureCanvasWebAgg(FigureCanvasWebAggCore):
manager_class = FigureManagerWebAgg # type: ignore[assignment]
- canvas = FigureCanvasWebAgg(figure) # type: ignore[no-untyped-call]
- manager = FigureManagerWebAgg(canvas, num) # type: ignore[no-untyped-call]
+ # Suppress the "Starting a Matplotlib GUI outside of the main thread"
+ # warning. WebAgg only renders to an in-memory Agg buffer and
+ # communicates over the network — no actual GUI toolkit is involved,
+ # so the warning is a false positive (especially in marimo-run mode
+ # where the kernel runs on a worker thread).
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message="Starting a Matplotlib GUI outside of the main thread",
+ category=UserWarning,
+ )
+ canvas = FigureCanvasWebAgg(figure) # type: ignore[no-untyped-call]
+ manager = FigureManagerWebAgg(canvas, num) # type: ignore[no-untyped-call]
return manager
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 599d977deb..b42ef76c08 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -47,7 +47,9 @@ class MarimoCommManager:
The caller can use this to trigger a cell re-run.
"""
if command.model_id not in self.comms:
- LOGGER.warning(
+ # Expected race: the frontend may send messages to a comm
+ # that was already closed (cell re-run, server shutdown).
+ LOGGER.debug(
"Received message for unknown comm: %s", command.model_id
)
return (None, None)
diff --git a/marimo/_plugins/ui/_impl/from_mpl_interactive.py b/marimo/_plugins/ui/_impl/from_mpl_interactive.py
index 458e784198..dc6ec287e4 100644
--- a/marimo/_plugins/ui/_impl/from_mpl_interactive.py
+++ b/marimo/_plugins/ui/_impl/from_mpl_interactive.py
@@ -233,7 +233,11 @@ class mpl_interactive(UIElement[ModelIdRef, dict[str, Any]]):
try:
ctx = get_context()
- ctx.cell_lifecycle_registry.add(_MplCleanupHandle(self._comm))
+ ctx.cell_lifecycle_registry.add(
+ _MplCleanupHandle(
+ self._comm, self._figure_manager, self._sync_ws
+ )
+ )
except ContextNotInitializedError:
pass
@@ -295,15 +299,35 @@ class mpl_interactive(UIElement[ModelIdRef, dict[str, Any]]):
class _MplCleanupHandle(CellLifecycleItem):
- """Closes the MarimoComm when the cell is re-run or deleted."""
+ """Cleans up the matplotlib figure manager and MarimoComm on cell re-run or deletion."""
- def __init__(self, comm: MarimoComm) -> None:
+ def __init__(
+ self,
+ comm: MarimoComm,
+ figure_manager: Any = None,
+ sync_ws: Any = None,
+ ) -> None:
self._comm = comm
+ self._figure_manager = figure_manager
+ self._sync_ws = sync_ws
def create(self, context: RuntimeContext) -> None:
del context
def dispose(self, context: RuntimeContext, deletion: bool) -> bool:
del context, deletion
+ # Disconnect the web socket from the figure manager first,
+ # then destroy the canvas to prevent stale timer callbacks
+ # on thread teardown (avoids "QObject::killTimer" errors).
+ if self._figure_manager is not None and self._sync_ws is not None:
+ try:
+ self._figure_manager.remove_web_socket(self._sync_ws)
+ except Exception:
+ pass
+ if self._figure_manager is not None:
+ try:
+ self._figure_manager.canvas.close()
+ except Exception:
+ pass
self._comm.close()
return True
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index f2a71797b4..3440a0cd9a 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -145,3 +145,48 @@ def test_mpl_interactive_fallback_when_virtual_files_not_supported() -> None:
assert result._mime_()[0] == "image/png"
plt.close(fig)
+
+
[email protected]("matplotlib")
+def test_new_figure_manager_suppresses_thread_warning() -> None:
+ """Regression test for https://github.com/marimo-team/marimo/issues/8747.
+
+ new_figure_manager_given_figure should not emit the
+ 'Starting a Matplotlib GUI outside of the main thread' warning
+ because WebAgg only uses software rendering.
+ """
+ import threading
+ import warnings
+
+ import matplotlib.pyplot as plt
+
+ from marimo._plugins.stateless.mpl._mpl import (
+ new_figure_manager_given_figure,
+ )
+
+ fig, ax = plt.subplots()
+ ax.plot([1, 2, 3])
+
+ captured: list[warnings.WarningMessage] = []
+
+ manager = None
+
+ def run_in_thread() -> None:
+ nonlocal manager
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ manager = new_figure_manager_given_figure(id(fig), fig)
+ captured.extend(w)
+
+ t = threading.Thread(target=run_in_thread)
+ t.start()
+ t.join()
+
+ thread_warnings = [
+ w for w in captured if "outside of the main thread" in str(w.message)
+ ]
+ assert thread_warnings == [], (
+ f"Expected no thread warning, got: {thread_warnings}"
+ )
+
+ plt.close(fig)
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
index 46f0b8d014..dd1124a124 100644
--- a/tests/_plugins/ui/_impl/test_comm.py
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -63,7 +63,7 @@ def test_comm_manager_receive_unknown_message(
buffers=[],
)
comm_manager.receive_comm_message(command)
- mock_logger.warning.assert_called_once()
+ mock_logger.debug.assert_called_once()
def test_comm_initialization(comm: MarimoComm):
diff --git a/tests/_plugins/ui/_impl/test_from_mpl_interactive.py b/tests/_plugins/ui/_impl/test_from_mpl_interactive.py
index 37ed0d5510..25ffef718b 100644
--- a/tests/_plugins/ui/_impl/test_from_mpl_interactive.py
+++ b/tests/_plugins/ui/_impl/test_from_mpl_interactive.py
@@ -208,6 +208,39 @@ class TestMplCleanupHandle:
assert result is True
mock_comm.close.assert_called_once()
+ def test_dispose_cleans_up_figure_manager(self) -> None:
+ from marimo._plugins.ui._impl.from_mpl_interactive import (
+ _MplCleanupHandle,
+ )
+
+ mock_comm = MagicMock()
+ mock_manager = MagicMock()
+ mock_ws = MagicMock()
+ handle = _MplCleanupHandle(mock_comm, mock_manager, mock_ws)
+ result = handle.dispose(context=MagicMock(), deletion=False)
+
+ assert result is True
+ mock_manager.remove_web_socket.assert_called_once_with(mock_ws)
+ mock_manager.canvas.close.assert_called_once()
+ mock_comm.close.assert_called_once()
+
+ def test_dispose_tolerates_manager_errors(self) -> None:
+ from marimo._plugins.ui._impl.from_mpl_interactive import (
+ _MplCleanupHandle,
+ )
+
+ mock_comm = MagicMock()
+ mock_manager = MagicMock()
+ mock_manager.remove_web_socket.side_effect = RuntimeError("boom")
+ mock_manager.canvas.close.side_effect = RuntimeError("boom")
+ mock_ws = MagicMock()
+ handle = _MplCleanupHandle(mock_comm, mock_manager, mock_ws)
+ # Should not raise even if manager cleanup fails
+ result = handle.dispose(context=MagicMock(), deletion=False)
+
+ assert result is True
+ mock_comm.close.assert_called_once()
+
@pytest.mark.requires("matplotlib")
class TestMplInteractiveArgs: