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: stub and restore cache meta values (#5996)

Dylan Madisetti0aa4712e31d8
diff --git a/marimo/_save/__init__.py b/marimo/_save/__init__.py
index 5955b964a9..1369e9eed5 100644
--- a/marimo/_save/__init__.py
+++ b/marimo/_save/__init__.py
@@ -1,5 +1,12 @@
# Copyright 2024 Marimo. All rights reserved.
+import marimo._save.cache as _cache_module # prevent variable shadowing
from marimo._save.cache import MARIMO_CACHE_VERSION
from marimo._save.save import cache, lru_cache, persistent_cache
-__all__ = ["cache", "lru_cache", "persistent_cache", "MARIMO_CACHE_VERSION"]
+__all__ = [
+ "cache",
+ "lru_cache",
+ "persistent_cache",
+ "MARIMO_CACHE_VERSION",
+ "_cache_module",
+]
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 88bf706a81..bc1d3fac84 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -102,19 +102,17 @@ class Cache:
def restore(self, scope: dict[str, Any]) -> None:
"""Restores values from cache, into scope."""
+ memo: dict[int, Any] = {} # Track processed objects to handle cycles
for var, lookup in self.contextual_defs():
value = self.defs.get(var, None)
- # If it's a module we must replace with a stub.
- if isinstance(value, ModuleStub):
- scope[lookup] = value.load()
- elif isinstance(value, FunctionStub):
- scope[lookup] = value.load(scope)
- elif isinstance(value, UIElementStub):
- # UIElementStub is a placeholder for UIElement, which cannot be
- # restored directly.
- scope[lookup] = value.load()
- else:
- scope[lookup] = self.defs[var]
+ scope[lookup] = self._restore_from_stub_if_needed(
+ value, scope, memo
+ )
+
+ for key, value in self.meta.items():
+ self.meta[key] = self._restore_from_stub_if_needed(
+ value, scope, memo
+ )
defs = {**globals(), **scope}
for ref in self.stateful_refs:
@@ -136,6 +134,66 @@ class Cache:
f"({type(ref)}:{ref})."
)
+ def _restore_from_stub_if_needed(
+ self,
+ value: Any,
+ scope: dict[str, Any],
+ memo: dict[int, Any] | None = None,
+ ) -> Any:
+ """Restore objects from stubs if needed, recursively handling collections."""
+ if memo is None:
+ memo = {}
+
+ # Check for cycles
+ obj_id = id(value)
+ if obj_id in memo:
+ return memo[obj_id]
+
+ if isinstance(value, ModuleStub):
+ result = value.load()
+ elif isinstance(value, FunctionStub):
+ result = value.load(scope)
+ elif isinstance(value, UIElementStub):
+ result = value.load()
+ elif isinstance(value, tuple):
+ result = tuple(
+ self._restore_from_stub_if_needed(item, scope, memo)
+ for item in value
+ )
+ elif isinstance(value, set):
+ # Sets cannot be recursive (require hashable items), but keep the
+ # reference.
+ result = set(
+ self._restore_from_stub_if_needed(item, scope, memo)
+ for item in value
+ )
+ value.clear()
+ value.update(result)
+ result = value
+ elif isinstance(value, list):
+ memo[obj_id] = value
+ result = [
+ self._restore_from_stub_if_needed(item, scope, memo)
+ for item in value
+ ]
+ # Keep the original list reference
+ value.clear()
+ value.extend(result)
+ result = value
+ elif isinstance(value, dict):
+ memo[obj_id] = value
+ result = {}
+ for k, v in value.items():
+ result[k] = self._restore_from_stub_if_needed(v, scope, memo)
+ value.clear()
+ value.update(result)
+ result = value
+ else:
+ result = value
+
+ memo[obj_id] = result
+ return result
+
def update(
self,
scope: dict[str, Any],
@@ -179,15 +237,73 @@ class Cache:
f"({type(value)}:{ref})."
)
+ # Convert objects to stubs in both defs and meta
+ memo: dict[int, Any] = {} # Track processed objects to handle cycles
for key, value in self.defs.items():
- # If it's a module we must replace with a stub.
- if inspect.ismodule(value):
- self.defs[key] = ModuleStub(value)
- elif inspect.isfunction(value):
- self.defs[key] = FunctionStub(value)
- elif isinstance(value, UIElement):
- # UIElement cannot be restored directly, so we store a stub.
- self.defs[key] = UIElementStub(value)
+ self.defs[key] = self._convert_to_stub_if_needed(value, memo)
+
+ for key, value in self.meta.items():
+ self.meta[key] = self._convert_to_stub_if_needed(value, memo)
+
+ def _convert_to_stub_if_needed(
+ self, value: Any, memo: dict[int, Any] | None = None
+ ) -> Any:
+ """Convert objects to stubs if needed, recursively handling collections."""
+ if memo is None:
+ memo = {}
+
+ # Check for cycles
+ obj_id = id(value)
+ if obj_id in memo:
+ return memo[obj_id]
+
+ result: Any = None
+
+ if inspect.ismodule(value):
+ result = ModuleStub(value)
+ elif inspect.isfunction(value):
+ result = FunctionStub(value)
+ elif isinstance(value, UIElement):
+ result = UIElementStub(value)
+ elif isinstance(value, tuple):
+ # tuples are immutable and cannot be recursive, but we still want to
+ # iteratively convert the internal items.
+ result = tuple(
+ self._convert_to_stub_if_needed(item, memo) for item in value
+ )
+ elif isinstance(value, set):
+ # sets cannot be recursive (require hasable items), but we still
+ # maintain the original set reference.
+ result = set(
+ self._convert_to_stub_if_needed(item, memo) for item in value
+ )
+ value.clear()
+ value.update(result)
+ result = value
+ elif isinstance(value, list):
+ # Store placeholder to handle cycles
+ memo[obj_id] = value
+ result = [
+ self._convert_to_stub_if_needed(item, memo) for item in value
+ ]
+ value.clear()
+ value.extend(result)
+ result = value
+ elif isinstance(value, dict):
+ # Recursively convert dictionary values
+ memo[obj_id] = value
+ result = {
+ k: self._convert_to_stub_if_needed(v, memo)
+ for k, v in value.items()
+ }
+ value.clear()
+ value.update(result)
+ result = value
+ else:
+ result = value
+ memo[obj_id] = result
+
+ return result
def contextual_defs(self) -> dict[tuple[Name, Name], Any]:
"""Uses context to resolve private variable names."""
@@ -196,7 +312,7 @@ class Cache:
assert context is not None, "Context could not be resolved"
private_prefix = f"_cell_{context.cell_id}_"
except (ContextNotInitializedError, AssertionError):
- private_prefix = r"^_cell_\w+_"
+ private_prefix = r"_"
return {
(var, re.sub(r"^_", private_prefix, var)): value
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 09cd88fdf4..542691a093 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -5,14 +5,262 @@ from __future__ import annotations
import sys
import textwrap
import warnings
+from unittest.mock import patch
import pytest
import marimo
from marimo._ast.app import App
+from marimo._plugins.ui._impl.input import dropdown
from marimo._runtime.requests import ExecutionRequest
from marimo._runtime.runtime import Kernel
-from tests.conftest import ExecReqProvider
+from marimo._save.cache import Cache, ModuleStub, UIElementStub
+from tests.conftest import ExecReqProvider, TestableModuleStub
+
+
+class TestCache:
+ @staticmethod
+ def test_cache_basic_update() -> None:
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+ scope = {}
+ ret = 1
+ cache.update(scope, {"return": ret})
+ assert cache.meta["return"] == ret
+
+ @staticmethod
+ def test_cache_recursive_update() -> None:
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+ scope = {}
+ ret = []
+ ret.append(ret)
+ cache.update(scope, {"return": ret})
+
+ stored = cache.meta["return"]
+ assert isinstance(stored, list)
+ assert len(stored) == 1
+ assert stored[0] is stored # Self-reference maintained
+
+ @staticmethod
+ def test_cache_scope_recursive() -> None:
+ _list = []
+ _list.append(_list)
+ d = {}
+ d["self"] = d
+ scope = {
+ "_list": _list,
+ "_dict": d,
+ }
+ cache = Cache(
+ defs=scope,
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+
+ # Force update to trigger stubbing.
+ cache.update(scope, {"return": None})
+ assert "_list" in cache.defs
+ assert "_dict" in cache.defs
+
+ @staticmethod
+ @patch("marimo._save._cache_module.ModuleStub", TestableModuleStub)
+ def test_cache_iterable() -> None:
+ scope = {
+ "_tuple": (1, 2, 3, marimo),
+ "_set": {1, 2, 3, marimo},
+ }
+ cache = Cache(
+ defs=scope,
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+
+ # Force update to trigger stubbing.
+ cache.update(scope, {"return": None})
+ assert "_tuple" in cache.defs
+ assert "_set" in cache.defs
+ assert isinstance(cache.defs["_tuple"][-1], ModuleStub)
+ assert TestableModuleStub(marimo) in cache.defs["_set"]
+
+ cache.restore(scope)
+ assert marimo == cache.defs["_tuple"][-1]
+ assert marimo in cache.defs["_set"]
+
+ @staticmethod
+ def test_cache_preserves_ref() -> None:
+ _set = {1, 2, 3, marimo}
+ _list = [1, 2, 3, _set]
+ _dict = {"_set": _set, "_list": _list}
+ scope = {
+ "_list": _list,
+ "_set": _set,
+ "_dict": _dict,
+ }
+ cache = Cache(
+ defs=scope,
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+
+ cache.update(scope, {"return": None})
+ assert "_list" in cache.defs
+ assert "_dict" in cache.defs
+ assert "_set" in cache.defs
+ assert id(cache.defs["_set"]) == id(_set)
+ assert id(cache.defs["_list"]) == id(_list)
+ assert id(cache.defs["_dict"]) == id(_dict)
+
+ @staticmethod
+ def test_cache_ui_element_update() -> None:
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={},
+ )
+ scope = {}
+ ret = dropdown(options=[1, 2, 3])
+ cache.update(scope, {"return": ret})
+
+ stub = cache.meta["return"]
+
+ assert isinstance(stub, UIElementStub)
+
+ assert stub.load().options == ret.options
+ assert stub.load().value == ret.value
+
+ @staticmethod
+ def test_cache_basic_restore() -> None:
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={"return": 42},
+ )
+ scope = {}
+ cache.restore(scope)
+ assert cache.meta["return"] == 42
+
+ @staticmethod
+ def test_cache_recursive_restore() -> None:
+ # Create a self-referential list
+ ret = []
+ ret.append(ret)
+
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={"return": ret},
+ )
+ scope = {}
+ cache.restore(scope)
+
+ # After restoration, should maintain the self-reference
+ restored = cache.meta["return"]
+ assert isinstance(restored, list)
+ assert len(restored) == 1
+ assert restored[0] is restored # Self-reference maintained
+
+ @staticmethod
+ def test_cache_ui_element_restore() -> None:
+ # Create a UIElement and convert it to a stub
+ original_dropdown = dropdown(options=[1, 2, 3])
+ stub = UIElementStub(original_dropdown)
+
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={"return": stub},
+ )
+ scope = {}
+ cache.restore(scope)
+
+ # After restoration, should have a new UIElement instance with same properties
+ restored = cache.meta["return"]
+ assert isinstance(restored, type(original_dropdown))
+ assert restored is not original_dropdown # Different instance
+ assert restored.options == original_dropdown.options
+ assert restored.value == original_dropdown.value
+
+ @staticmethod
+ def test_cache_nested_ui_element_restore() -> None:
+ # Create nested structure with UIElements
+ slider = dropdown(options=["a", "b", "c"])
+ button = dropdown(options=[1, 2, 3])
+ nested = {
+ "controls": [slider, button],
+ "primary": slider,
+ "secondary": button,
+ }
+
+ # Convert to stubs
+ slider_stub = UIElementStub(slider)
+ button_stub = UIElementStub(button)
+ nested_with_stubs = {
+ "controls": [slider_stub, button_stub],
+ "primary": slider_stub,
+ "secondary": button_stub,
+ }
+
+ cache = Cache(
+ defs={},
+ hash="123",
+ cache_type="Pure",
+ stateful_refs=set(),
+ hit=True,
+ meta={"return": nested_with_stubs},
+ )
+ scope = {}
+ cache.restore(scope)
+
+ # After restoration, should have new UIElement instances but preserve structure
+ restored = cache.meta["return"]
+ assert isinstance(restored, dict)
+ assert len(restored["controls"]) == 2
+
+ # Should be same instances within the structure (shared references preserved)
+ assert restored["primary"] is restored["controls"][0]
+ assert restored["secondary"] is restored["controls"][1]
+
+ # But different from originals
+ assert restored["primary"] is not slider
+ assert restored["secondary"] is not button
+
+ # Properties should match
+ assert restored["primary"].options == slider.options
+ assert restored["secondary"].options == button.options
class TestScriptCache:
diff --git a/tests/conftest.py b/tests/conftest.py
index a8256c1f99..4b0f0eb738 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -33,6 +33,7 @@ from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import AppMetadata, ExecutionRequest
from marimo._runtime.runtime import Kernel
+from marimo._save.cache import ModuleStub
from marimo._server.model import SessionMode
from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
@@ -633,6 +634,17 @@ def app() -> Generator[App, None, None]:
app.run()
+class TestableModuleStub(ModuleStub):
+ def __eq__(self, other: Any) -> bool:
+ # Used for testing, equality otherwise not useful.
+ if not isinstance(other, ModuleStub):
+ return False
+ return self.name == other.name
+
+ def __hash__(self) -> int:
+ return hash(self.name) + hash("module")
+
+
# A pytest hook to fail when raw marimo cells are not collected.
# Meta testing gets a little messy, and may leave you a little testy. This is
# increasingly coupled with the following specific tests that test testing: