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.

Close anywidget comms on cell re-execution and deletion (#8159)

Trevor Manz04059d660f32
diff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.py
index 80121c0a45..2e3d6d44d4 100644
--- a/marimo/_plugins/ui/_impl/anywidget/init.py
+++ b/marimo/_plugins/ui/_impl/anywidget/init.py
@@ -7,12 +7,29 @@ from uuid import uuid4
if TYPE_CHECKING:
import ipywidgets # type: ignore
+ from marimo._runtime.context.types import RuntimeContext
+
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.comm import ( # pyright: ignore[reportMissingTypeStubs]
BufferType,
MarimoComm,
MarimoCommManager,
)
+from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+from marimo._runtime.context import ContextNotInitializedError, get_context
+
+
+class CommLifecycleItem(CellLifecycleItem):
+ def __init__(self, comm: MarimoComm) -> None:
+ self._comm = comm
+
+ def create(self, context: RuntimeContext) -> None:
+ del context
+
+ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:
+ del context, deletion
+ self._comm.close()
+ return True
# Initialize ipywidgets using a MarimoComm
@@ -44,5 +61,13 @@ def init_marimo_widget(w: ipywidgets.Widget) -> None:
# with proper buffer handling via _put_buffers and serializer support
w.comm.on_msg(w._handle_msg)
+ # Register lifecycle item so the comm is closed when the cell is
+ # re-executed or deleted (sends ModelClose to the frontend).
+ try:
+ ctx = get_context()
+ ctx.cell_lifecycle_registry.add(CommLifecycleItem(w.comm))
+ except ContextNotInitializedError:
+ pass
+
WIDGET_COMM_MANAGER = MarimoCommManager()
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 003e05be46..2fe9832175 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import dataclass, field
from typing import Any, Callable, Optional
from marimo._loggers import marimo_logger
@@ -22,8 +23,9 @@ from marimo._types.ids import WidgetModelId
LOGGER = marimo_logger()
+@dataclass
class MarimoCommManager:
- comms: dict[WidgetModelId, MarimoComm] = {}
+ comms: dict[WidgetModelId, MarimoComm] = field(default_factory=dict)
def register_comm(self, comm: MarimoComm) -> str:
comm_id = comm.comm_id
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
index e3a6a9fb5d..de35dee1d4 100644
--- a/tests/_plugins/ui/_impl/test_comm.py
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch
import pytest
+from marimo._plugins.ui._impl.anywidget.init import CommLifecycleItem
from marimo._plugins.ui._impl.comm import (
MarimoComm,
MarimoCommManager,
@@ -25,11 +26,16 @@ def comm_manager():
def comm(comm_manager: MarimoCommManager) -> MarimoComm:
comm_id = WidgetModelId("test-comm")
with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):
- return MarimoComm(
+ c = MarimoComm(
comm_id=comm_id,
comm_manager=comm_manager,
target_name="test_target",
)
+ yield c # type: ignore[misc]
+ # Ensure the comm is closed so __del__ doesn't fire broadcast_notification
+ # during garbage collection in a later test's patch scope.
+ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):
+ c._closed = True
def test_comm_manager_register_unregister(
@@ -190,3 +196,35 @@ def test_comm_manager_receive_custom_message(
result = comm_manager.receive_comm_message(command)
assert result == (None, None)
callback.assert_called_once()
+
+
+def test_comm_lifecycle_item_dispose_closes_comm(
+ comm_manager: MarimoCommManager, comm: MarimoComm
+):
+ """CommLifecycleItem.dispose() should close the comm."""
+ item = CommLifecycleItem(comm)
+ assert not comm._closed
+ assert comm.comm_id in comm_manager.comms
+
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ result = item.dispose(context=MagicMock(), deletion=False)
+
+ assert result is True
+ assert comm._closed
+ assert comm.comm_id not in comm_manager.comms
+ mock_broadcast.assert_called_once()
+
+
+def test_comm_lifecycle_item_dispose_idempotent(comm: MarimoComm):
+ """Calling dispose twice should not error (comm.close is idempotent)."""
+ item = CommLifecycleItem(comm)
+
+ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):
+ item.dispose(context=MagicMock(), deletion=False)
+ # Second dispose — comm is already closed, should be a no-op
+ result = item.dispose(context=MagicMock(), deletion=True)
+
+ assert result is True
+ assert comm._closed