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: Allow lifecycle objects to be managed by mo.Thread (#11358)

Dylan Madisetti13b727484a62
diff --git a/marimo/_plugins/ui/_impl/anywidget/comm_provider.py b/marimo/_plugins/ui/_impl/anywidget/comm_provider.py
index 9d55912857..efb2417f05 100644
--- a/marimo/_plugins/ui/_impl/anywidget/comm_provider.py
+++ b/marimo/_plugins/ui/_impl/anywidget/comm_provider.py
@@ -17,6 +17,7 @@ from marimo._plugins.ui._impl.anywidget.init import (
CommLifecycleItem,
)
from marimo._plugins.ui._impl.comm import MarimoComm
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._types.ids import WidgetModelId
@@ -106,9 +107,14 @@ def install_anywidget_comm_provider() -> None:
# the cell is re-run or deleted.
try:
ctx = get_context()
- ctx.cell_lifecycle_registry.add(CommLifecycleItem(c))
except ContextNotInitializedError:
- pass
+ return c
+ try:
+ ctx.cell_lifecycle_registry.add(CommLifecycleItem(c))
+ except NoOwningCellError:
+ # The comm is already open and nothing else closes it.
+ c.close()
+ raise
return c
_PATCHED_CREATE_COMM = _marimo_create_comm
diff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.py
index 2e3d6d44d4..9b8a80c013 100644
--- a/marimo/_plugins/ui/_impl/anywidget/init.py
+++ b/marimo/_plugins/ui/_impl/anywidget/init.py
@@ -16,6 +16,7 @@ from marimo._plugins.ui._impl.comm import ( # pyright: ignore[reportMissingType
MarimoCommManager,
)
from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.context import ContextNotInitializedError, get_context
@@ -65,9 +66,15 @@ def init_marimo_widget(w: ipywidgets.Widget) -> None:
# re-executed or deleted (sends ModelClose to the frontend).
try:
ctx = get_context()
- ctx.cell_lifecycle_registry.add(CommLifecycleItem(w.comm))
except ContextNotInitializedError:
- pass
+ return
+ try:
+ ctx.cell_lifecycle_registry.add(CommLifecycleItem(w.comm))
+ except NoOwningCellError:
+ # The comm is already open. Closing the whole widget also drops it
+ # from ipywidgets' instance registry.
+ w.close()
+ raise
WIDGET_COMM_MANAGER = MarimoCommManager()
diff --git a/marimo/_plugins/ui/_impl/from_mpl_interactive.py b/marimo/_plugins/ui/_impl/from_mpl_interactive.py
index 744e995923..809a7e6dab 100644
--- a/marimo/_plugins/ui/_impl/from_mpl_interactive.py
+++ b/marimo/_plugins/ui/_impl/from_mpl_interactive.py
@@ -21,6 +21,7 @@ from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
from marimo._plugins.ui._impl.anywidget.init import WIDGET_COMM_MANAGER
from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.context import RuntimeContext
from marimo._runtime.virtual_file.virtual_file import VirtualFile
from marimo._types.ids import WidgetModelId
@@ -363,16 +364,21 @@ class mpl_interactive(UIElement[ModelIdRef, dict[str, Any]]):
try:
ctx = get_context()
- ctx.cell_lifecycle_registry.add(
- _MplCleanupHandle(
- comm=self._comm,
- figure=self._figure,
- figure_manager=self._figure_manager,
- sync_ws=self._sync_ws,
- )
- )
except ContextNotInitializedError:
- pass
+ return
+ cleanup = _MplCleanupHandle(
+ comm=self._comm,
+ figure=self._figure,
+ figure_manager=self._figure_manager,
+ sync_ws=self._sync_ws,
+ )
+ try:
+ ctx.cell_lifecycle_registry.add(cleanup)
+ except NoOwningCellError:
+ # The comm and figure manager already exist and nothing else
+ # tears them down.
+ cleanup.dispose(context=ctx, deletion=True)
+ raise
def _handle_comm_msg(self, msg: dict[str, Any]) -> None:
"""Handle messages from frontend → backend.
diff --git a/marimo/_runtime/cell_lifecycle_registry.py b/marimo/_runtime/cell_lifecycle_registry.py
index feec3f9a53..c061c5d7d1 100644
--- a/marimo/_runtime/cell_lifecycle_registry.py
+++ b/marimo/_runtime/cell_lifecycle_registry.py
@@ -3,10 +3,16 @@ from __future__ import annotations
import dataclasses
+from marimo._messaging.context import EXECUTION_CTX
from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._types.ids import CellId_t
+class NoOwningCellError(RuntimeError):
+ """No cell can own a lifecycle item, so marimo refuses to create it."""
+
+
@dataclasses.dataclass
class CellLifecycleRegistry:
registry: dict[CellId_t, set[CellLifecycleItem]] = dataclasses.field(
@@ -23,18 +29,36 @@ class CellLifecycleRegistry:
self.registry[cell_id].add(item)
def add(self, item: CellLifecycleItem) -> None:
- """Add a lifecycle item for the currently running cell.
+ """Create `item` and register it with the cell that owns it.
- Calls the item's create method upon adding. No-op if no cell
- is running.
+ The owner is the cell whose evaluation created `item`, directly or
+ from a task or thread it spawned, or else the cell running on this
+ context. Raises `NoOwningCellError` when there is neither.
"""
from marimo._runtime.context import get_context
ctx = get_context()
- cell_id = ctx.cell_id
- if cell_id is None:
- return
+ execution = EXECUTION_CTX.get()
+ if execution is None:
+ cell_id = ctx.cell_id
+ if cell_id is None:
+ raise NoOwningCellError(
+ "No cell is running on this thread, so marimo cannot clean "
+ "up. Start background work with mo.Thread within a cell."
+ )
+ else:
+ # The tag is task-local, so it names the spawning cell even when
+ # another cell runs on the shared context, and it outlives the
+ # cell body, so that cell can already be deleted. The scratchpad
+ # cell runs on a graph of its own.
+ cell_id = CellId_t(execution.cell_id)
+ if cell_id not in ctx.graph.cells and cell_id != SCRATCH_CELL_ID:
+ raise NoOwningCellError(
+ "Since the cell that started this background work was deleted, "
+ "marimo cannot provide clean up. Start background work with "
+ "mo.Thread within a cell."
+ )
item.create(ctx)
return self.inject(cell_id, item)
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 43b240f3ca..1e4348502f 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -38,6 +38,7 @@ from marimo._ast.transformers import (
)
from marimo._ast.variables import is_mangled_local, unmangle_local
from marimo._messaging.tracebacks import write_traceback
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.context import get_context, safe_get_context
from marimo._runtime.dataflow import DirectedGraph
from marimo._runtime.scratch import SCRATCH_CELL_ID
@@ -75,6 +76,7 @@ if TYPE_CHECKING:
from typing_extensions import Self
+ from marimo._runtime.context import RuntimeContext
from marimo._save.stores import Store
P = ParamSpec("P")
@@ -83,6 +85,17 @@ Q = ParamSpec("Q")
S = TypeVar("S")
+def _mark_side_effect(ctx: RuntimeContext, key: str) -> None:
+ """Mark the owning cell so cell-level caches see this cache event.
+
+ An off-cell call has no cell to mark and nothing to dispose.
+ """
+ try:
+ ctx.cell_lifecycle_registry.add(SideEffect(key))
+ except NoOwningCellError:
+ pass
+
+
class _cache_call(CacheContext, Generic[P, R]):
"""Like functools.cache but notebook-aware. See `cache` docstring"""
@@ -529,7 +542,7 @@ class _cache_call(CacheContext, Generic[P, R]):
finally:
# NB. Exceptions raise their own side effects.
if ctx and not failed:
- ctx.cell_lifecycle_registry.add(SideEffect(attempt.hash))
+ _mark_side_effect(ctx, attempt.hash)
self._misses += 1
return cast(R, response)
@@ -658,7 +671,7 @@ class _cache_call_async(_cache_call[P, R]):
finally:
# NB. Exceptions raise their own side effects.
if ctx and not failed:
- ctx.cell_lifecycle_registry.add(SideEffect(attempt.hash))
+ _mark_side_effect(ctx, attempt.hash)
self._misses += 1
return response
@@ -887,8 +900,7 @@ class _cache_context(SkipContext, CacheContext):
if not failed:
# Conditional because pendantically, the side effect is on restore /
# save respectively, and exceptions should raise their own.
- ctx = get_context()
- ctx.cell_lifecycle_registry.add(SideEffect(self._cache.hash))
+ _mark_side_effect(get_context(), self._cache.hash)
return False
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index 24ae3edf9c..3f6a1246ba 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -3,11 +3,13 @@ from __future__ import annotations
import gc
import weakref
+from concurrent.futures import ThreadPoolExecutor
import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.anywidget.init import WIDGET_COMM_MANAGER
from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._plugins.ui._impl.from_anywidget import (
WeakCache,
@@ -15,11 +17,13 @@ from marimo._plugins.ui._impl.from_anywidget import (
from_anywidget,
get_anywidget_state,
)
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.commands import (
ModelCommand,
ModelUpdateMessage,
UpdateUIElementCommand,
)
+from marimo._runtime.context import get_context
from marimo._runtime.runtime import Kernel
from marimo._types.ids import WidgetModelId
from marimo._utils.code import hash_code
@@ -425,6 +429,32 @@ x = as_marimo_element.count
assert comm2.esm_spec is not None
assert comm2.esm_spec.hash == hash_code(JSWidget2._esm)
+ @staticmethod
+ def test_widget_constructed_off_cell_raises_and_leaves_no_comm(
+ k: Kernel, # noqa: ARG004
+ ) -> None:
+ # A plain thread that restored the kernel's runtime context while no
+ # cell is running cannot build a widget, because no cell can
+ # close its comm. The error names mo.Thread, and a comm opened before
+ # the check is closed again, so the comm manager is unchanged.
+ ctx = get_context()
+ assert ctx.cell_id is None
+ comms_before = set(WIDGET_COMM_MANAGER.comms)
+
+ def build_off_cell(widget_class: type) -> object:
+ with ctx.install():
+ return widget_class()
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ # Inline ESM: refused before any comm is opened.
+ with pytest.raises(NoOwningCellError, match=r"mo\.Thread"):
+ pool.submit(build_off_cell, CounterWidget).result(timeout=10)
+ # No ESM: the comm opens first and must be closed on refusal.
+ with pytest.raises(NoOwningCellError, match=r"mo\.Thread"):
+ pool.submit(build_off_cell, Widget).result(timeout=10)
+
+ assert set(WIDGET_COMM_MANAGER.comms) == comms_before
+
@staticmethod
def test_state_merging() -> None:
class StateWidget(_anywidget.AnyWidget):
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index b0a9afc380..c33c722e75 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -41,6 +41,7 @@ from marimo._runtime.commands import (
UpdateCellConfigCommand,
UpdateUIElementCommand,
)
+from marimo._runtime.context import get_context
from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.runtime import (
Kernel,
@@ -1725,6 +1726,22 @@ except NameError:
# Does not pollute globals
assert "x" not in k.globals
+ @staticmethod
+ async def test_run_scratch_owns_lifecycle_items(
+ mocked_kernel: MockedKernel,
+ ) -> None:
+ # The scratchpad cell is not in the notebook graph, yet it owns what
+ # it creates.
+ k = mocked_kernel.k
+ await k.run_scratchpad(
+ "from marimo._output.data import data as mo_data\n"
+ 'vfile = mo_data.any_data(b"hello", ext="txt")'
+ )
+ assert not mocked_kernel.stderr.messages, mocked_kernel.stderr
+ ctx = get_context()
+ assert SCRATCH_CELL_ID in ctx.cell_lifecycle_registry.registry
+ assert len(ctx.virtual_file_registry.registry) == 1
+
@staticmethod
async def test_run_scratch_with_other_globals(
mocked_kernel: MockedKernel, exec_req: ExecReqProvider
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
index fd28310bb1..dbca1265d9 100644
--- a/tests/_runtime/test_threads.py
+++ b/tests/_runtime/test_threads.py
@@ -2,10 +2,14 @@ from __future__ import annotations
import asyncio
import time
+from concurrent.futures import ThreadPoolExecutor
from typing import cast
+import pytest
+
from marimo._ast.app import App, InternalApp
from marimo._pyodide.streams import PyodideStream
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.context import get_context
from marimo._runtime.context.script_context import (
@@ -20,6 +24,23 @@ from tests._messaging.mocks import MockStream
from tests.conftest import ExecReqProvider
+def test_thread_constructed_off_cell_raises(
+ k: Kernel, # noqa: ARG001
+) -> None:
+ # A plain thread that restored the kernel's context has no cell that
+ # can tell a mo.Thread to exit, so constructing one there is refused.
+ ctx = get_context()
+ assert ctx.cell_id is None
+
+ def construct_off_cell() -> Thread:
+ with ctx.install():
+ return Thread(target=lambda: None)
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ with pytest.raises(NoOwningCellError, match=r"mo\.Thread"):
+ pool.submit(construct_off_cell).result(timeout=10)
+
+
# Doesn't work with strict kernel ...
async def test_thread_set_global(k: Kernel, exec_req: ExecReqProvider) -> None:
"""Test that a thread starts and runs."""
@@ -93,7 +114,10 @@ def test_thread_copies_pyodide_stream_in_script_context() -> None:
def target() -> None:
observed_contexts.append(cast(ScriptRuntimeContext, get_context()))
- thread = Thread(target=target)
+ # Script cells run under `with_cell_id`, and a mo.Thread needs that
+ # cell as its owner.
+ with ctx.with_cell_id(CellId_t("script-cell")):
+ thread = Thread(target=target)
thread.start()
thread.join(timeout=1)
@@ -377,3 +401,51 @@ async def test_threads_share_output_list_with_parent(
"All threads should share the same output list, "
f"but got ids: {output_ids}"
)
+
+
+async def test_thread_of_deleted_cell_cannot_create_lifecycle_items(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # The spawning cell is deleted while its thread still runs. Nothing can
+ # dispose of what the thread creates afterwards, so the thread gets an
+ # error instead of an item registered under the dead cell.
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import threading
+ import marimo as mo
+ from marimo._output.data import data as mo_data
+ """
+ ),
+ spawn := exec_req.get(
+ """
+ gate = threading.Event()
+ outcome = {}
+
+ def build(gate=gate, outcome=outcome):
+ gate.wait()
+ try:
+ outcome["vfile"] = mo_data.any_data(b"hello", ext="txt")
+ except Exception as e:
+ outcome["error"] = e
+
+ thread = mo.Thread(target=build)
+ thread.start()
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ gate, outcome, thread = (
+ k.globals["gate"],
+ k.globals["outcome"],
+ k.globals["thread"],
+ )
+ await k.delete_cell(DeleteCellCommand(cell_id=spawn.cell_id))
+ gate.set()
+ thread.join(timeout=10)
+
+ assert isinstance(outcome.get("error"), NoOwningCellError), outcome
+ assert spawn.cell_id not in ctx.cell_lifecycle_registry.registry
+ assert not ctx.virtual_file_registry.registry
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index f46a44613a..632b4a02c4 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -2,7 +2,12 @@
from __future__ import annotations
import uuid
+from concurrent.futures import ThreadPoolExecutor
+import pytest
+
+import marimo._output.data.data as mo_data
+from marimo._runtime.cell_lifecycle_registry import NoOwningCellError
from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.context import get_context
from marimo._runtime.runtime import Kernel
@@ -316,6 +321,177 @@ async def test_virtual_file_empty_buffer(
assert len(get_context().virtual_file_registry.registry) == 0
+def test_any_data_with_context_but_no_cell_raises(
+ run_mode_kernel: MockedKernel, # noqa: ARG001
+) -> None:
+ # A runtime context is installed but no cell is running, as on a plain
+ # thread that restored the kernel's context. Nothing can dispose
+ # the file, so marimo refuses to create it rather than leak it.
+ ctx = get_context()
+ assert ctx.cell_id is None
+
+ with pytest.raises(NoOwningCellError, match=r"mo\.Thread"):
+ mo_data.any_data(b"export default {}", ext="js")
+
+ assert not ctx.virtual_file_registry.registry
+ assert not ctx.cell_lifecycle_registry.registry
+
+
+async def test_vfile_from_task_is_owned_by_spawning_cell(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # A cell spawns a task that keeps running after the cell body returns, so
+ # no cell runs when the task creates a file. The cell owns the file and
+ # disposes of it when the cell re-runs.
+ k = execution_kernel
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import asyncio
+ from marimo._output.data import data as mo_data
+ """
+ ),
+ spawn := exec_req.get(
+ """
+ gate = asyncio.Event()
+
+ async def build(gate):
+ await gate.wait()
+ return mo_data.any_data(b"hello world", ext="txt")
+
+ task = asyncio.create_task(build(gate))
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ assert ctx.cell_id is None
+ k.globals["gate"].set()
+ vfile = await k.globals["task"]
+
+ assert vfile.url.startswith("./@file/")
+ assert vfile.filename in ctx.virtual_file_registry.registry
+
+ await k.run([spawn])
+ assert vfile.filename not in ctx.virtual_file_registry.registry
+ k.globals["task"].cancel()
+
+
+async def test_vfile_from_thread_with_copied_context_is_owned_by_spawning_cell(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # A plain thread that restores the kernel context owns nothing
+ # by itself. A cell owns anything the thread creates under a `contextvars`
+ # copy taken in that cell, and deleting the cell disposes it.
+ k = execution_kernel
+ await k.run(
+ [
+ exec_req.get("import contextvars"),
+ spawn := exec_req.get("snapshot = contextvars.copy_context()"),
+ ]
+ )
+ ctx = get_context()
+ snapshot = k.globals["snapshot"]
+
+ def build_off_cell() -> VirtualFile:
+ with ctx.install():
+ return snapshot.run(mo_data.any_data, b"hello world", "txt")
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ vfile = pool.submit(build_off_cell).result(timeout=10)
+
+ assert vfile.url.startswith("./@file/")
+ assert vfile.filename in ctx.virtual_file_registry.registry
+
+ await k.delete_cell(DeleteCellCommand(cell_id=spawn.cell_id))
+ assert vfile.filename not in ctx.virtual_file_registry.registry
+
+
+async def test_vfile_from_task_of_deleted_cell_raises(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # Once the spawning cell is deleted, nothing can dispose the item, so the
+ # task gets an error instead of a file registered under a dead cell.
+ k = execution_kernel
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import asyncio
+ from marimo._output.data import data as mo_data
+ """
+ ),
+ spawn := exec_req.get(
+ """
+ gate = asyncio.Event()
+
+ async def build(gate):
+ await gate.wait()
+ return mo_data.any_data(b"hello world", ext="txt")
+
+ task = asyncio.create_task(build(gate))
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ gate, task = k.globals["gate"], k.globals["task"]
+ await k.delete_cell(DeleteCellCommand(cell_id=spawn.cell_id))
+ gate.set()
+ with pytest.raises(NoOwningCellError, match="deleted"):
+ await task
+
+ assert spawn.cell_id not in ctx.cell_lifecycle_registry.registry
+ assert not ctx.virtual_file_registry.registry
+
+
+async def test_vfile_from_task_resumed_in_another_cell_is_owned_by_spawner(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # The task resumes while another cell runs on the shared context. The
+ # spawning cell still owns the file: re-running the other cell keeps it
+ # and re-running the spawning cell disposes of it. The other cell opens
+ # the gate itself, which strict mode would do on a copy.
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import asyncio
+ from marimo._output.data import data as mo_data
+ """
+ ),
+ spawn := exec_req.get(
+ """
+ gate = asyncio.Event()
+
+ async def build(gate):
+ await gate.wait()
+ return mo_data.any_data(b"hello world", ext="txt")
+
+ task = asyncio.create_task(build(gate))
+ """
+ ),
+ other := exec_req.get(
+ """
+ gate.set()
+ vfile = await task
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ vfile = k.globals["vfile"]
+ assert vfile.filename in ctx.virtual_file_registry.registry
+
+ await k.run([other])
+ assert vfile.filename in ctx.virtual_file_registry.registry
+
+ await k.run([spawn])
+ assert vfile.filename not in ctx.virtual_file_registry.registry
+ k.globals["task"].cancel()
+
+
def test_virtual_file_registry_shared_inmemory_storage(
run_mode_kernel: MockedKernel, # noqa: ARG001
) -> None:
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 3b2f2c80dc..ca254a6021 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -14,7 +14,9 @@ from marimo._ast.app import App
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.input import dropdown
from marimo._runtime.commands import ExecuteCellCommand
+from marimo._runtime.context import get_context
from marimo._runtime.runtime import Kernel
+from marimo._runtime.side_effect import SideEffect
from marimo._save.cache import Cache
from marimo._save.stubs.module_stub import ModuleStub
from marimo._save.stubs.ui_element_stub import UIElementStub
@@ -989,6 +991,37 @@ class TestCacheDecorator:
assert k.globals["a"] == 5
assert k.globals["b"] == 55
+ async def test_call_off_cell_records_no_side_effect(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ # Called after its cell returned, as from a plain thread that restored
+ # the kernel context. No cell runs, so there is no cell to
+ # mark for cache invalidation, and the call still works.
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import cache
+
+ @cache
+ def double(x):
+ return x * 2
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ assert ctx.cell_id is None
+
+ assert k.globals["double"](2) == 4
+ assert k.globals["double"](2) == 4
+ assert k.globals["double"].hits == 1
+ assert not any(
+ isinstance(item, SideEffect)
+ for items in ctx.cell_lifecycle_registry.registry.values()
+ for item in items
+ )
+
async def test_basic_cache(
self, k: Kernel, exec_req: ExecReqProvider
) -> None:
@@ -2952,6 +2985,36 @@ class TestAsyncCacheDecorator:
# Should have cache hits like the sync version
assert k.globals["async_fib"].hits == 9
+ async def test_async_call_off_cell_records_no_side_effect(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ # Awaited after its cell returned, so no cell runs and there is no
+ # cell to mark for cache invalidation. The call still works.
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import cache
+
+ @cache
+ async def double(x):
+ return x * 2
+ """
+ ),
+ ]
+ )
+ ctx = get_context()
+ assert ctx.cell_id is None
+
+ assert await k.globals["double"](2) == 4
+ assert await k.globals["double"](2) == 4
+ assert k.globals["double"].hits == 1
+ assert not any(
+ isinstance(item, SideEffect)
+ for items in ctx.cell_lifecycle_registry.registry.values()
+ for item in items
+ )
+
async def test_async_lru_cache(
self, k: Kernel, exec_req: ExecReqProvider
) -> None: