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 cleanup of UI elements (#313)

Akshay Agrawal12b4f39e9ce8
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 9df5a79fd7..1bedccf38c 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -28,6 +28,11 @@ class UIElementRegistry:
ui_element: UIElement[Any, Any],
) -> None:
kernel = get_context().kernel
+ if object_id in self._objects:
+ # on cell re-run, a UI element may be (re)-registered before
+ # its destructor was called, so manually delete the old element
+ # here
+ self.delete(object_id, id(self._objects[object_id]))
self._objects[object_id] = weakref.ref(ui_element)
assert kernel.execution_context is not None
self._constructing_cells[object_id] = kernel.execution_context.cell_id
@@ -60,15 +65,19 @@ class UIElementRegistry:
if object_id not in self._objects:
return
- registered_python_id = id(self._objects[object_id]())
+ ui_element = self._objects[object_id]()
+ registered_python_id = id(ui_element)
if registered_python_id != python_id:
+ # guards against UIElement's destructor racing against
+ # registration of another element when a cell re-runs
LOGGER.debug(
"Python id mismatch when deleting UI element %s", object_id
)
return
- if self._objects[object_id]:
+ if ui_element is not None:
del self._objects[object_id]
+ ui_element._dispose()
if object_id in self._bindings:
del self._bindings[object_id]
if object_id in self._constructing_cells:
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 8eaf89bd5a..a6db497da3 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -19,10 +19,8 @@ from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType, build_ui_plugin
from marimo._plugins.ui._core import ids
-from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
from marimo._runtime.context import (
ContextNotInitializedError,
- RuntimeContext,
get_context,
)
from marimo._runtime.functions import Function
@@ -47,22 +45,6 @@ class MarimoConvertValueException(Exception):
pass
-class UIElementLifeCycleItem(CellLifecycleItem):
- """Handles to cleanup a UI element."""
-
- def __init__(self, element_id: str, object_id: int) -> None:
- self.element_id = element_id
- self.object_id = object_id
-
- def create(self, context: RuntimeContext) -> None:
- del context
- pass
-
- def dispose(self, context: RuntimeContext) -> None:
- context.function_registry.delete(namespace=self.element_id)
- context.ui_element_registry.delete(self.element_id, self.object_id)
-
-
@mddoc
class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
"""An HTML element with a value
@@ -197,12 +179,6 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
ctx.function_registry.register(
namespace=self._id, function=function
)
-
- # This has to happen in the cell lifecycle, not del, to avoid
- # races; order in which __del__ is called is not guaranteed
- ctx.cell_lifecycle_registry.add(
- UIElementLifeCycleItem(element_id=self._id, object_id=id(self))
- )
self._initial_value_frontend = initial_value
self._value_frontend = initial_value
self._value = self._initial_value = self._convert_value(initial_value)
@@ -222,6 +198,21 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
+ "</marimo-ui-element>"
)
+ def _dispose(self) -> None:
+ """Handle used by the registry to clean-up this element on removal."""
+ try:
+ ctx = get_context()
+ ctx.function_registry.delete(namespace=self._id)
+ except ContextNotInitializedError:
+ pass
+
+ def __del__(self) -> None:
+ try:
+ ctx = get_context()
+ ctx.ui_element_registry.delete(self._id, id(self))
+ except ContextNotInitializedError:
+ pass
+
@abc.abstractmethod
def _convert_value(self, value: S) -> T:
"""Converts a value from the frontend to a value for the `UIElement`
diff --git a/marimo/_runtime/test_ui_element_registration.py b/marimo/_runtime/test_ui_element_registration.py
new file mode 100644
index 0000000000..778c5136e9
--- /dev/null
+++ b/marimo/_runtime/test_ui_element_registration.py
@@ -0,0 +1,35 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._runtime.conftest import ExecReqProvider
+from marimo._runtime.context import get_context
+from marimo._runtime.runtime import Kernel
+
+
+# TODO: colocate test with UIElementRegistry file; requires refactoring
+# pytest's conftests ...
+def test_cached_element_still_registered(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k.run(
+ [
+ exec_req.get("import functools"),
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ """
+ @functools.lru_cache
+ def slider():
+ return mo.ui.slider(1, 10)
+ """
+ ),
+ (construct_slider := exec_req.get("s = slider()")),
+ ]
+ )
+ # Make sure that the slider is registered
+ s = k.globals["s"]
+ assert get_context().ui_element_registry.get_object(s._id) == s
+
+ # Re-run the cell but fetch the same slider, since we're using
+ # functools.cache. Make sure it's still registered!
+ k.run([construct_slider])
+ assert get_context().ui_element_registry.get_object(s._id) == s