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: misc cache fixes (#5115)

Dylan Madisetti2117df440b6b
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index bb69c34f22..076939dc82 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import ast
+import copy
import inspect
import io
import linecache
@@ -193,6 +194,7 @@ def compile_cell(
expr: ast.Expression
final_expr = module.body[-1]
+ original_module = copy.deepcopy(module)
# Use final expression if it exists doesn't end in a
# semicolon. Evaluates expression to "None" otherwise.
if isinstance(final_expr, ast.Expr) and not ends_with_semicolon(code):
@@ -272,7 +274,7 @@ def compile_cell(
# keyed by original (user) code, for cache lookups
key=code_key(code),
code=code,
- mod=module,
+ mod=original_module,
defs=nonlocals,
refs=v.refs,
temporaries=temporaries,
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 05aecb3759..7ba54eb971 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -470,9 +470,26 @@ class UIElement(Html, Generic[S, T]):
def __deepcopy__(self, memo: dict[int, Any]) -> UIElement[S, T]:
# Custom deepcopy that excludes elements that can't be deepcopied
cls = self.__class__
+ return cls.from_args(
+ self.__dict__, args=self._args, memo=memo, basis=self
+ )
+
+ @classmethod
+ def from_args(
+ cls,
+ data: dict[str, int],
+ args: InitializationArgs[S, T],
+ memo: dict[int, Any] | None = None,
+ basis: UIElement[S, T] | None = None,
+ ) -> UIElement[S, T]:
result = cls.__new__(cls)
- memo[id(self)] = result
- for k, v in self.__dict__.items():
+ if memo is None:
+ memo = {}
+ if basis is None:
+ basis = result
+
+ memo[id(basis)] = result
+ for k, v in data.items():
if isinstance(v, RuntimeContext):
setattr(result, k, v)
else:
@@ -483,18 +500,17 @@ class UIElement(Html, Generic[S, T]):
# We use the new instance's functions, since they are typically bound
# to the UI element instance. But we only use the new on_change
# if the old one was bound to self.
- args: InitializationArgs[S, T]
if (
- isinstance(self._args.on_change, types.MethodType)
- and self._args.on_change.__self__ is self
+ isinstance(args.on_change, types.MethodType)
+ and args.on_change.__self__ is basis
):
# on_change was bound to self; use the new one.
args = InitializationArgs(
**{
# dataclass asdict does a deepcopy, we want shallow.
**{
- field.name: getattr(self._args, field.name)
- for field in fields(self._args)
+ field.name: getattr(args, field.name)
+ for field in fields(args)
},
"on_change": result._args.on_change,
"functions": result._args.functions,
@@ -506,8 +522,8 @@ class UIElement(Html, Generic[S, T]):
args = InitializationArgs(
**{
**{
- field.name: getattr(self._args, field.name)
- for field in fields(self._args)
+ field.name: getattr(args, field.name)
+ for field in fields(args)
},
"functions": result._args.functions,
}
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
index 8308f9530d..a35de1a5f5 100644
--- a/marimo/_runtime/primitives.py
+++ b/marimo/_runtime/primitives.py
@@ -180,8 +180,12 @@ def is_pure_function(
# (e.g. list)
if getattr(value, "__hash__", None) is None:
return False
- if value in cache:
- return cache[value]
+ try:
+ if value in cache:
+ return cache[value]
+ except TypeError:
+ # If value is not hashable, we assume it's not pure.
+ return False
# Trivial enough not to cache.
if inspect.isclass(value) or not callable(value):
return False
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 72755f5904..88bf706a81 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -4,11 +4,12 @@ from __future__ import annotations
import importlib
import inspect
import re
+import textwrap
from collections import namedtuple
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal, Optional, get_args
-from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._core.ui_element import S, T, UIElement
from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.state import SetFunctor
@@ -51,10 +52,33 @@ class ModuleStub:
class FunctionStub:
def __init__(self, function: Any) -> None:
- self.code = function.__code__
+ self.code = textwrap.dedent(inspect.getsource(function))
def load(self, glbls: dict[str, Any]) -> Any:
- return eval(self.code, glbls)
+ # TODO: Fix line cache and associate with the correct module.
+ code_obj = compile(self.code, "<string>", "exec")
+ lcls: dict[str, Any] = {}
+ exec(code_obj, glbls, lcls)
+ # Update the global scope with the function.
+ for value in lcls.values():
+ return value
+
+
+class UIElementStub:
+ def __init__(self, element: UIElement[S, T]) -> None:
+ self.args = element._args
+ self.cls = element.__class__
+ # Ideally only hashable attributes are stored on the subclass level.
+ defaults = set(self.cls.__new__(self.cls).__dict__.keys())
+ defaults |= {"_ctx"}
+ self.data = {
+ k: v
+ for k, v in element.__dict__.items()
+ if hasattr(v, "__hash__") and k not in defaults
+ }
+
+ def load(self) -> UIElement[S, T]:
+ return self.cls.from_args(self.data, self.args) # type: ignore
# BaseException because "raise _ as e" is utilized.
@@ -79,7 +103,18 @@ class Cache:
def restore(self, scope: dict[str, Any]) -> None:
"""Restores values from cache, into scope."""
for var, lookup in self.contextual_defs():
- scope[lookup] = self.defs[var]
+ 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]
defs = {**globals(), **scope}
for ref in self.stateful_refs:
@@ -101,13 +136,6 @@ class Cache:
f"({type(ref)}:{ref})."
)
- for key, value in self.defs.items():
- # If it's a module we must replace with a stub.
- if isinstance(value, ModuleStub):
- scope[key] = value.load()
- elif isinstance(value, FunctionStub):
- value.load(scope)
-
def update(
self,
scope: dict[str, Any],
@@ -157,6 +185,9 @@ class Cache:
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)
def contextual_defs(self) -> dict[tuple[Name, Name], Any]:
"""Uses context to resolve private variable names."""
diff --git a/tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.json b/tests/_save/cache-dumps/json-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.json
similarity index 71%
rename from tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.json
rename to tests/_save/cache-dumps/json-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.json
index 370284eb6d..96778e5578 100644
--- a/tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.json
+++ b/tests/_save/cache-dumps/json-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.json
@@ -2,7 +2,7 @@
"defs": {
"value": 3
},
- "hash": "dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE",
+ "hash": "Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I",
"cache_type": "ExecutionPath",
"stateful_refs": [],
"hit": false,
diff --git a/tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.pickle b/tests/_save/cache-dumps/pickle-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.pickle
similarity index 64%
rename from tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.pickle
rename to tests/_save/cache-dumps/pickle-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.pickle
index 85d2a42e5e..0bc552c7b3 100644
Binary files a/tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.pickle and b/tests/_save/cache-dumps/pickle-dump-v3/E_Gl8RU7GyKYjt8iMk0iIjsMAptXH0xoYfTgL2iidYW0I.pickle differ
diff --git a/tests/_save/loaders/mocks.py b/tests/_save/loaders/mocks.py
index 2007919ebd..2ad5f0ff57 100644
--- a/tests/_save/loaders/mocks.py
+++ b/tests/_save/loaders/mocks.py
@@ -14,6 +14,7 @@ class MockLoader(Loader):
data: Optional[dict[str, Any]] = None,
stateful_refs: Optional[set[str]] = None,
config_value: Any = None,
+ strict: bool = False,
) -> None:
self.save_path = save_path
self._data = data or {}
@@ -22,6 +23,9 @@ class MockLoader(Loader):
self._saved = False
self._stateful_refs = stateful_refs or set()
self.config_value = config_value
+ # "Strict" is more than just spoofing the response, but actually going
+ # through the hydration process.
+ self.strict = strict
super().__init__(name)
def cache_hit(self, _) -> bool:
@@ -31,14 +35,20 @@ class MockLoader(Loader):
if not self._cache_hit:
return None
self._loaded = True
- return Cache(
- defs=self._data,
+ data = self._data
+ if self.strict:
+ data = {key: None for key in self._data}
+ cache = Cache(
+ defs=data,
hash=key.hash,
cache_type=key.cache_type,
stateful_refs=self._stateful_refs,
hit=True,
meta={},
)
+ if self.strict:
+ cache.update(self._data)
+ return cache
def save_cache(self, _cache: Cache) -> bool:
self._saved = True
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 7ce8c78002..c9634a932d 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -308,7 +308,8 @@ class TestAppCache:
from tests._save.loaders.mocks import MockLoader
with persistent_cache(
- name="one", _loader=MockLoader(data={"X": 7, "Y": 8})
+ name="one",
+ _loader=MockLoader(data={"X": 7, "Y": 8}, strict=True)
) as cache:
Y = 9
X = 10
@@ -338,7 +339,8 @@ class TestAppCache:
return 2
with persistent_cache(
- name="one", _loader=MockLoader(data={"mo": mod})
+ name="one",
+ _loader=MockLoader(data={"mo": mod}, strict=True),
) as cache:
import numpy as mo
"""
@@ -372,8 +374,8 @@ class TestAppCache:
)
# No warning messages.
assert k.errors == {}
- assert not k.stderr.messages, k.stderr
assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
assert k.globals["mo"].__version__ == marimo.__version__
async def test_cache_function_hit(self, any_kernel: Kernel) -> None:
@@ -390,8 +392,8 @@ class TestAppCache:
def my_func_2():
return 2
- with persistent_cache(name="one", _loader=MockLoader(data={"my_func": my_func_2})) as cache:
- print("Runs, miss")
+ loader = MockLoader(data={"my_func": my_func_2}, strict=True)
+ with persistent_cache(name="one", _loader=loader) as cache:
def my_func():
return 1
"""
@@ -399,8 +401,9 @@ class TestAppCache:
),
]
)
- assert not k.stderr.messages, k.stderr
+ assert "cache" in k.globals
assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, (k.stderr, k.stdout)
assert k.globals["my_func"]() == 2
async def test_cache_function_miss(self, any_kernel: Kernel) -> None:
@@ -415,7 +418,7 @@ class TestAppCache:
from tests._save.loaders.mocks import MockLoader
with persistent_cache(
- name="one", _loader=MockLoader()
+ name="one", _loader=MockLoader(),
) as cache:
def my_func():
return 1
@@ -425,10 +428,64 @@ class TestAppCache:
]
)
# No warning messages.
- assert not k.stderr.messages, k.stderr
assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
assert k.globals["my_func"]() == 1
+ async def test_cache_ui_hit(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent(
+ """
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.loaders.mocks import MockLoader
+ loaded_slider = mo.ui.slider(20, 30)
+
+ with persistent_cache(
+ name="one",
+ _loader=MockLoader(data={"slider": loaded_slider}, strict=True),
+ ) as cache:
+ slider = mo.ui.slider(0, 1)
+ """
+ ),
+ ),
+ ]
+ )
+ # No warning messages.
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["slider"].value == 20
+
+ async def test_cache_ui_miss(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent(
+ """
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.loaders.mocks import MockLoader
+
+ with persistent_cache(
+ name="one", _loader=MockLoader()
+ ) as cache:
+ slider = mo.ui.slider(0, 1)
+ """
+ ),
+ ),
+ ]
+ )
+ # No warning messages.
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["slider"].value == 0
+
async def test_cache_one_line(self, any_kernel: Kernel) -> None:
k = any_kernel
await k.run(
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index 272ac3df1e..d47b0da5ec 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -98,6 +98,54 @@ class TestHash:
assert cache._cache.cache_type == "ContextExecutionPath"
return (Y,)
+ @staticmethod
+ def test_single_expression_execution_hash() -> None:
+ # The final expression is treated a tiny bit differently than marimo,
+ # which has led to bugs.
+ app = App()
+ app._anonymous_file = True
+ app._pytest_rewrite = True
+
+ @app.cell
+ def _():
+ non_primitive = [object()]
+ return non_primitive
+
+ @app.cell
+ def _(non_primitive) -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.loaders.mocks import MockLoader
+
+ with persistent_cache(name="test", _loader=MockLoader()) as cache:
+ Y = 8 + len(non_primitive)
+ assert cache._cache.cache_type == "ExecutionPath"
+ return (Y,)
+
+ _, defs = app.run()
+
+ app2 = App()
+ app2._anonymous_file = True
+ app2._pytest_rewrite = True
+
+ @app2.cell
+ def _():
+ non_primitive = [object(), object()]
+ return non_primitive
+
+ @app2.cell
+ def _(non_primitive) -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.loaders.mocks import MockLoader
+
+ with persistent_cache(name="test", _loader=MockLoader()) as cache:
+ Y = 8 + len(non_primitive)
+ assert cache._cache.cache_type == "ExecutionPath"
+ return (Y,)
+
+ _, defs2 = app2.run()
+
+ assert defs["cache"]._cache.hash != defs2["cache"]._cache.hash
+
@staticmethod
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"