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: Don't Delete Cached Virtual Files (#320)

Akshay Agrawalf553450192f8
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index e56c67110b..1184173d13 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Literal, final
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
+from marimo._output.utils import flatten_string
if TYPE_CHECKING:
from marimo._plugins.core.web_component import JSONType
@@ -51,7 +52,57 @@ class Html(MIME):
_text: str
def __init__(self, text: str) -> None:
+ """Initialize the HTML element.
+
+ Subclasses of HTML MUST call this method.
+ """
self._text = text
+ # A list of the virtual file names referenced by this HTML element.
+ self._virtual_filenames: list[str] = []
+
+ from marimo._runtime.context import (
+ ContextNotInitializedError,
+ get_context,
+ )
+
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ return
+
+ # Virtual File Refcounting
+ #
+ # HTML elements are responsible for maintaining the reference counts
+ # of virtual files: virtual files cannot be disposed when HTML elements
+ # reference them. For example, a user might cache HTML referencing a
+ # virtual file if they create it using functools.cache.
+ #
+ # flatten the text to make sure searching isn't broken by newlines
+ flat_text = flatten_string(self._text)
+ for virtual_filename in ctx.virtual_file_registry.filenames():
+ if virtual_filename in flat_text:
+ ctx.virtual_file_registry.reference(virtual_filename)
+ self._virtual_filenames.append(virtual_filename)
+
+ def __del__(self) -> None:
+ """Cleanup side-effects related to initialization.
+
+ Subclasses MUST implement a __del__ method that ends by calling
+ this method.
+ """
+
+ from marimo._runtime.context import (
+ ContextNotInitializedError,
+ get_context,
+ )
+
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ return
+
+ for f in self._virtual_filenames:
+ ctx.virtual_file_registry.dereference(f)
@property
def text(self) -> str:
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 88a43d1966..c7ec285fb0 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -197,10 +197,16 @@ class CleanupHandle(CellLifecycleItem):
del context
pass
- def dispose(self, context: RuntimeContext) -> None:
+ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:
del context
+ del deletion
if self.shutdown_event is not None:
self.shutdown_event.set()
+ # TODO: if Html containing server is cached, disposal still trashes
+ # it, which is a bug ... fix this. Use `deletion` flag to make
+ # sure shutdown happens on cell deletion, otherwise need to
+ # find a way to keep server alive if its Html is cached.
+ return True
@mddoc
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index a6db497da3..6b884316c6 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -191,12 +191,13 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
args,
slotted_html,
)
- self._text = (
+ text = (
f"<marimo-ui-element object-id='{self._id}' "
+ f"random-id='{self._random_id}'>"
+ self._inner_text
+ "</marimo-ui-element>"
)
+ super().__init__(text=text)
def _dispose(self) -> None:
"""Handle used by the registry to clean-up this element on removal."""
@@ -213,6 +214,8 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
except ContextNotInitializedError:
pass
+ super().__del__()
+
@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/cell_lifecycle_item.py b/marimo/_runtime/cell_lifecycle_item.py
index a8edb31712..8ef099edbc 100644
--- a/marimo/_runtime/cell_lifecycle_item.py
+++ b/marimo/_runtime/cell_lifecycle_item.py
@@ -11,8 +11,27 @@ if TYPE_CHECKING:
class CellLifecycleItem(abc.ABC):
@abc.abstractmethod
def create(self, context: "RuntimeContext") -> None:
+ """Create this item
+
+ This method is executed at the beginning of a cell's lifecycle.
+ Use it to run side-effects or create state.
+ """
...
@abc.abstractmethod
- def dispose(self, context: "RuntimeContext") -> None:
+ def dispose(self, context: "RuntimeContext", deletion: bool) -> bool:
+ """Dispose this item
+
+ This method is executed at the end of a cell's lifecycle. Use
+ it to clean-up side-effects or state associated with the lifecycle
+ item.
+
+ The `deletion` flag indicates whether the cell is being removed
+ from the graph, which may influence disposal strategy.
+
+ Return True if the disposal is successful and the lifecycle item
+ should be removed from the registry. Return False if the disposal
+ needs to be retried in the next cell lifecycle (note that `create`
+ will not be re-run, only `dispose`).
+ """
...
diff --git a/marimo/_runtime/cell_lifecycle_registry.py b/marimo/_runtime/cell_lifecycle_registry.py
index 34bd69b7d0..1195506c04 100644
--- a/marimo/_runtime/cell_lifecycle_registry.py
+++ b/marimo/_runtime/cell_lifecycle_registry.py
@@ -31,15 +31,25 @@ class CellLifecycleRegistry:
item.create(ctx)
self.registry[cell_id].add(item)
- def dispose(self, cell_id: CellId_t) -> None:
+ def dispose(self, cell_id: CellId_t, deletion: bool) -> None:
"""Dispose lifecycle items associated with `cell_id`
Calls `dispose` hooks and clears items from the registry.
+
+ If `deletion` is `True`, the cell is being removed from the graph.
"""
from marimo._runtime.context import get_context
ctx = get_context()
+ # LifecycleItems can request that their `dispose` method is retried in
+ # the next cell lifecycle; these items are persisted.
+ persisted_lifecycle_items = set()
if cell_id in self.registry:
for lifecycle_item in self.registry[cell_id]:
- lifecycle_item.dispose(context=ctx)
- del self.registry[cell_id]
+ if not lifecycle_item.dispose(context=ctx, deletion=deletion):
+ persisted_lifecycle_items.add(lifecycle_item)
+
+ if persisted_lifecycle_items:
+ self.registry[cell_id] = persisted_lifecycle_items
+ else:
+ del self.registry[cell_id]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index dd7f243194..60193a8fd7 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -291,7 +291,10 @@ class Kernel:
del self.globals["__annotations__"][name]
def _invalidate_cell_state(
- self, cell_id: CellId_t, exclude_defs: Optional[set[str]] = None
+ self,
+ cell_id: CellId_t,
+ exclude_defs: Optional[set[str]] = None,
+ deletion: bool = False,
) -> None:
"""Cleanup state associated with this cell.
@@ -303,7 +306,9 @@ class Kernel:
self._delete_names(
defs_to_delete, exclude_defs if exclude_defs is not None else set()
)
- get_context().cell_lifecycle_registry.dispose(cell_id)
+ get_context().cell_lifecycle_registry.dispose(
+ cell_id, deletion=deletion
+ )
RemoveUIElements(cell_id=cell_id).broadcast()
def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:
@@ -315,7 +320,7 @@ class Kernel:
from the kernel and graph.
"""
if cell_id not in self.errors:
- self._invalidate_cell_state(cell_id)
+ self._invalidate_cell_state(cell_id, deletion=True)
return self.graph.delete_cell(cell_id)
else:
# An errored cell can be thought of as a cell that's in the graph
diff --git a/marimo/_runtime/test_virtual_file.py b/marimo/_runtime/test_virtual_file.py
index 3b592c19cd..3d992fdaba 100644
--- a/marimo/_runtime/test_virtual_file.py
+++ b/marimo/_runtime/test_virtual_file.py
@@ -44,3 +44,195 @@ def test_virtual_file_deletion(k: Kernel, exec_req: ExecReqProvider) -> None:
k.delete(DeleteRequest(er.cell_id))
assert not get_context().virtual_file_registry.registry
+
+
+def test_cached_virtual_file_not_deleted(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import functools
+ """
+ ),
+ vfile_cache := exec_req.get(
+ """
+ @functools.lru_cache()
+ def create_vfile(arg):
+ del arg
+ bytestream = io.BytesIO(b"hello world")
+ return mo.pdf(bytestream)
+ """
+ ),
+ create_vfile_1 := exec_req.get("create_vfile(1)"),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+
+ # Rerun the cell that created the vfile: make sure that the vfile
+ # still exists
+ k.run([create_vfile_1])
+ assert len(get_context().virtual_file_registry.registry) == 1
+
+ # Create a new vfile, make sure we have two now
+ k.run([create_vfile_2 := exec_req.get("create_vfile(2)")])
+ assert len(get_context().virtual_file_registry.registry) == 2
+
+ # Remove the cells that create the vfiles
+ k.delete(DeleteRequest(create_vfile_1.cell_id))
+ k.delete(DeleteRequest(create_vfile_2.cell_id))
+
+ # Reset the vfile cache
+ k.run([vfile_cache])
+
+
+def test_cell_deletion_clears_vfiles(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import functools
+ """
+ ),
+ vfile_cache := exec_req.get(
+ """
+ @functools.lru_cache()
+ def create_vfile(arg):
+ del arg
+ bytestream = io.BytesIO(b"hello world")
+ return mo.pdf(bytestream)
+ """
+ ),
+ exec_req.get("create_vfile(1)"),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+
+ # Delete the vfile cache: virtual file registry should be empty
+ k.delete(DeleteRequest(vfile_cache.cell_id))
+ assert len(get_context().virtual_file_registry.registry) == 0
+
+
+def test_vfile_refcount_incremented(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import functools
+ """
+ ),
+ exec_req.get(
+ """
+ @functools.lru_cache()
+ def create_vfile(arg):
+ del arg
+ bytestream = io.BytesIO(b"hello world")
+ return mo.pdf(bytestream)
+ """
+ ),
+ exec_req.get("md = mo.md(f'{create_vfile(1)}')"),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ vfile = list(get_context().virtual_file_registry.filenames())[0]
+
+ # 1 reference for the cached `mo.pdf`
+ # + 1 reference for the markdown
+ # ---
+ # 2 references
+ assert get_context().virtual_file_registry.refcount(vfile) == 2
+
+
+def test_vfile_refcount_decremented(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import gc
+ """
+ ),
+ # no caching in this test
+ exec_req.get(
+ """
+ def create_vfile(arg):
+ del arg
+ bytestream = io.BytesIO(b"hello world")
+ return mo.pdf(bytestream)
+ """
+ ),
+ make_vfile := exec_req.get("mo.md(f'{create_vfile(1)}')"),
+ ]
+ )
+ ctx = get_context()
+ assert len(ctx.virtual_file_registry.registry) == 1
+ vfile = list(ctx.virtual_file_registry.filenames())[0]
+
+ # 0 references because HTML not bound to a variable
+ # NB: this test may be flaky! refcount decremented when `__del__` is called
+ # but we can't rely on when it will be called.
+ k.run([exec_req.get("gc.collect()")])
+ assert ctx.virtual_file_registry.refcount(vfile) == 0
+
+ # this should dispose the old vfile (because its refcount is 0) and create
+ # a new one
+ k.run([make_vfile])
+ # the previous vfile should not be in the registry
+ assert vfile not in ctx.virtual_file_registry.registry
+ assert len(ctx.virtual_file_registry.registry) == 1
+
+
+def test_cached_vfile_disposal(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import functools
+ """
+ ),
+ exec_req.get(
+ """
+ vfiles = []
+ def create_vfile(arg):
+ del arg
+ bytestream = io.BytesIO(b"hello world")
+ return mo.pdf(bytestream)
+ """
+ ),
+ append_vfile := exec_req.get("vfiles.append(create_vfile(1))"),
+ ]
+ )
+ ctx = get_context()
+ assert len(ctx.virtual_file_registry.registry) == 1
+ vfile = list(ctx.virtual_file_registry.filenames())[0]
+
+ # 1 reference, in the list
+ assert ctx.virtual_file_registry.refcount(vfile) == 1
+
+ # clear the list, refcount should be decremented
+ k.run([exec_req.get("vfiles[:] = []")])
+ # NB: this test may be flaky! refcount decremented when `__del__` is called
+ # but we can't rely on when it will be called.
+ k.run([exec_req.get("gc.collect()")])
+ assert ctx.virtual_file_registry.refcount(vfile) == 0
+
+ # create another vfile. the old one should be deleted
+ k.run([append_vfile])
+ assert len(ctx.virtual_file_registry.registry) == 1
+ assert vfile not in ctx.virtual_file_registry.filenames()
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index d02ecd994b..b22dfb1aa3 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -6,6 +6,7 @@ import random
import string
import sys
import threading
+from collections.abc import Iterable
from multiprocessing import shared_memory
from typing import TYPE_CHECKING, Optional
@@ -74,6 +75,11 @@ class VirtualFileLifecycleItem(CellLifecycleItem):
return self._virtual_file
def create(self, context: "RuntimeContext") -> None:
+ """Create the virtual file
+
+ Every virtual file gets a unique random name. Uniqueness is
+ required for reference counting.
+ """
filename = random_filename(self.ext)
registry = context.virtual_file_registry
# create a unique filename for the virtual file
@@ -90,13 +96,41 @@ class VirtualFileLifecycleItem(CellLifecycleItem):
self._virtual_file = VirtualFile(filename, self.buffer)
context.virtual_file_registry.add(self._virtual_file)
- def dispose(self, context: "RuntimeContext") -> None:
- context.virtual_file_registry.remove(self.virtual_file)
+ def dispose(self, context: "RuntimeContext", deletion: bool) -> bool:
+ # Remove the file if the refcount is 0, or if the cell is being
+ # deleted. (We can't rely on when the refcount will be decremented, so
+ # we need to check for deletion explictly to prevent leaks.)
+ if deletion or (
+ context.virtual_file_registry.refcount(self.virtual_file.filename)
+ <= 0
+ ):
+ context.virtual_file_registry.remove(self.virtual_file)
+ return True
+ # refcount > 0, so need to keep this disposal hook around
+ return False
+
+
+class VirtualFileRegistryItem:
+ # contents of the file
+ shm: shared_memory.SharedMemory
+ # number of HTML objects that are referencing this virtual file
+ refcount: int
@dataclasses.dataclass
class VirtualFileRegistry:
- registry: dict[str, shared_memory.SharedMemory] = dataclasses.field(
+ """Registry of virtual files
+
+ The registry maps virtual file filenames to their contents. Each
+ registry item is reference counted: refcount > 0 means that an object
+ exists somewhere that uses the virtual file.
+
+ The registry itself doesn't maintain the reference counts, it only
+ exposes methods for incrementing, decrementing, and getting the counts.
+ """
+
+ registry: dict[str, VirtualFileRegistryItem] = dataclasses.field(
default_factory=dict
)
shutting_down = False
@@ -107,6 +141,25 @@ class VirtualFileRegistry:
def has(self, filename: str) -> bool:
return filename in self.registry
+ def filenames(self) -> Iterable[str]:
+ return self.registry.keys()
+
+ def reference(self, filename: str) -> None:
+ """Increment the reference count"""
+ if filename in self.registry:
+ self.registry[filename].refcount += 1
+
+ def dereference(self, filename: str) -> None:
+ """Decrement the reference count"""
+ if filename in self.registry:
+ self.registry[filename].refcount -= 1
+
+ def refcount(self, filename: str) -> int:
+ """Get the reference count"""
+ if filename in self.registry:
+ return self.registry[filename].refcount
+ return 0
+
def add(self, virtual_file: VirtualFile) -> None:
key = virtual_file.filename
if key in self.registry:
@@ -144,15 +197,15 @@ class VirtualFileRegistry:
shm.close()
# We hav to keep a reference to the shared memory to prevent it from
# being destroyed on Windows
- self.registry[key] = shm
+ self.registry[key] = VirtualFileRegistryItem(shm=shm, refcount=0)
def remove(self, virtual_file: VirtualFile) -> None:
key = virtual_file.filename
if key in self.registry:
if sys.platform == "win32":
- self.registry[key].close()
+ self.registry[key].shm.close()
# destroy the shared memory
- self.registry[key].unlink()
+ self.registry[key].shm.unlink()
del self.registry[key]
def shutdown(self) -> None:
@@ -164,10 +217,10 @@ class VirtualFileRegistry:
return
try:
self.shutting_down = True
- for _, shm in self.registry.items():
+ for _, item in self.registry.items():
if sys.platform == "win32":
- shm.close()
- shm.unlink()
+ item.shm.close()
+ item.shm.unlink()
self.registry.clear()
finally:
self.shutting_down = False