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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: handle shadowed variables in mo.cache, update tutorials (#2480)
Akshay Agrawalc5354cfdaefa
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex c30204af1f..aef7a862aa 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -178,8 +178,11 @@ def _store_state_reference(# Associate state variables with variable namesctx = get_context()ctx.state_registry.register_scope(runner.glbls, defs=cell.defs)+ privates = set().union(+ *[cell.temporaries for cell in ctx.graph.cells.values()]+ )ctx.state_registry.retain_active_states(- set(runner.graph.definitions.keys())+ set(runner.graph.definitions.keys()) | privates)diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.pyindex 22912d56e2..3714620022 100644--- a/marimo/_runtime/state.py+++ b/marimo/_runtime/state.py@@ -51,9 +51,11 @@ class StateRegistry:if id(state) in self._inv_states:ref = next(iter(self._inv_states[id(state)]))# Check for duplicate state ids and clean up accordingly- if id(self._states[ref].ref()) != id(state):+ if ref not in self._states or id(self._states[ref].ref()) != id(+ state+ ):for ref in self._inv_states[id(state)]:- del self._states[ref]+ self._states.pop(ref, None)self._inv_states[id(state)].clear()state_item = StateItem(id(state), weakref.ref(state))self._states[name] = state_itemdiff --git a/marimo/_save/cache.py b/marimo/_save/cache.pyindex ffde3bef79..3f21d4508a 100644--- a/marimo/_save/cache.py+++ b/marimo/_save/cache.py@@ -112,7 +112,7 @@ class Cache:raise CacheException("Failure while saving cached values. ""Unexpected stateful reference type "- f"({type(ref)}:{ref})."+ f"({type(value)}:{ref}).")def contextual_defs(self) -> dict[tuple[Name, Name], Any]:diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 2801c7c12b..8356ae8272 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, Optionalfrom marimo._ast.visitor import Name, ScopedVisitorfrom marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import ContextNotInitializedError, get_contextfrom marimo._runtime.primitives import (FN_CACHE_TYPE,@@ -55,6 +56,10 @@ class SerialRefs(NamedTuple):stateful_refs: set[Name]+class ShadowedRef:+ """Stub for scoped variables that may shadow global references"""++def hash_module(code: Optional[CodeType], hash_type: str = DEFAULT_HASH) -> bytes:@@ -224,8 +229,18 @@ def attempt_signed_bytes(value: bytes, label: str) -> bytes:def get_and_update_context_from_scope(scope: dict[str, Any],+ scope_refs: Optional[set[Name]] = None,) -> Optional[RuntimeContext]:"""Get stateful registers"""++ # Remove non-global references+ ctx_scope = set(scope)+ if scope_refs is None:+ scope_refs = set()+ for ref in scope_refs:+ if ref in ctx_scope:+ ctx_scope.remove(ref)+# This is typically done in post execution hook, but it will not be# called in script mode.# TODO: Strip this out to allow for hash based look up. Name based@@ -551,14 +566,6 @@ class BlockHasher:refs = set(refs)stateful_refs = set()- # State Setters that are not directly consumed, are not needed.- for ref in self.visitor.refs:- # If the setter is consumed, let the hash be tied to the state- # value.- if ref in scope and isinstance(scope[ref], SetFunctor):- stateful_refs.add(ref)- scope[ref] = scope[ref]._state-for ref in set(refs):if ref in scope.get("__builtins__", ()):refs.remove(ref)@@ -570,17 +577,46 @@ class BlockHasher:# State relevant to the context, should be dependent on it's value-# not the object.value: Optional[State[Any]]- if ctx and (value := ctx.state_registry.lookup(ref)):- for state_name in ctx.state_registry.bound_names(value):- scope[state_name] = attempt_signed_bytes(value(), "state")+ # Prefer actual object over reference.+ # Skip if the reference has already been subbed in, or if it is+ # a shadowed reference.+ if ref in scope and isinstance(scope[ref], State):+ value = scope[ref]+ elif ctx:+ value = ctx.state_registry.lookup(ref)++ if value is not None and (+ ref not in scope or isinstance(scope[ref], State)+ ):+ scope[ref] = attempt_signed_bytes(value(), "state")+ if ctx:+ for state_name in ctx.state_registry.bound_names(value):+ scope[state_name] = scope[ref]# Likewise, UI objects should be dependent on their value.- if ctx and (ui := ctx.ui_element_registry.lookup(ref)) is not None:- for ui_name in ctx.ui_element_registry.bound_names(ui._id):- scope[ui_name] = attempt_signed_bytes(ui.value, "ui")- # If the UI is directly consumed, then hold on to the reference- # for proper cache update.+ if ref in scope and isinstance(scope[ref], UIElement):+ ui = scope[ref]+ elif ctx:+ ui = ctx.ui_element_registry.lookup(ref)+ if ui is not None and (+ ref not in scope or isinstance(scope[ref], UIElement)+ ):+ scope[ref] = attempt_signed_bytes(ui.value, "ui")+ if ctx:+ for ui_name in ctx.ui_element_registry.bound_names(ui._id):+ scope[ui_name] = scope[ref]+ # If the UI is directly consumed, then hold on to the+ # reference for proper cache update.+ stateful_refs.add(ref)++ # State Setters that are not directly consumed, are not needed.+ for ref in self.visitor.refs:+ # If the setter is consumed, let the hash be tied to the state+ # value.+ if ref in scope and isinstance(scope[ref], SetFunctor):stateful_refs.add(ref)+ scope[ref] = scope[ref]._state+return SerialRefs(refs, {}, stateful_refs)def serialize_and_dequeue_content_refs(@@ -652,7 +688,10 @@ class BlockHasher:return SerialRefs(refs, content_serialization, set())def serialize_and_dequeue_stateful_content_refs(- self, refs: set[Name], scope: dict[str, Any], ctx: RuntimeContext+ self,+ refs: set[Name],+ scope: dict[str, Any],+ ctx: RuntimeContext,) -> SerialRefs:"""Determines and uses stateful references that impact the code block.@@ -672,6 +711,23 @@ class BlockHasher:transitive_state_refs = self.graph.get_transitive_references(refs, inclusive=False)++ for ref in transitive_state_refs:+ if ref in scope and isinstance(scope[ref], ShadowedRef):+ # TODO(akshayka, dmadisetti): Lift this restriction once+ # function args are rewritten.+ #+ # This makes more sense as a NameError, but the marimo's+ # explainer text for NameError's doesn't make sense in this+ # context. ("Definition expected in ...")+ raise RuntimeError(+ f"The cached function declares an argument '{ref}'"+ "but a captured function or class uses the "+ f"global variable '{ref}'. Please rename "+ "the argument, or restructure the use "+ f"of the global variable."+ )+# Filter for relevant stateful cases.refs |= set(filter(@@ -682,6 +738,7 @@ class BlockHasher:transitive_state_refs,))+# Need to run extract again for the expanded ref set.refs, _, stateful_refs = self.extract_ref_state_and_normalize_scope(refs, scope, ctx@@ -881,7 +938,7 @@ def content_cache_attempt_from_base(refs |= previous_block.context_refshasher = BlockHasher.from_parent(previous_block)- ctx = get_and_update_context_from_scope(scope)+ ctx = get_and_update_context_from_scope(scope, required_refs)refs, _, stateful_refs = hasher.extract_ref_state_and_normalize_scope(refs, scope, ctx)diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex d8c0d719d2..dae394c5af 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -26,6 +26,7 @@ from marimo._save.cache import Cache, CacheExceptionfrom marimo._save.hash import (DEFAULT_HASH,BlockHasher,+ ShadowedRef,cache_attempt_from_hash,content_cache_attempt_from_base,)@@ -114,6 +115,14 @@ class _cache_base(object):# checking a single frame- should be good enough.f_locals = inspect.stack()[2 + self._frame_offset][0].f_localsself.scope = {**ctx.globals, **f_locals}+ # In case scope shadows variables+ #+ # TODO(akshayka, dmadisetti): rewrite function args with an AST pass+ # to make them unique, deterministically based on function body; this+ # will allow for lifting the error when a ShadowedRef is also used+ # as a regular ref.+ for arg in self._args:+ self.scope[arg] = ShadowedRef()# Scoped refs are references particular to this block, that may not be# defined out of the context of the block, or the cell.diff --git a/marimo/_tutorials/dataflow.py b/marimo/_tutorials/dataflow.pyindex 3d7a8f7b78..11ea3d4e47 100644--- a/marimo/_tutorials/dataflow.py+++ b/marimo/_tutorials/dataflow.py@@ -620,18 +620,18 @@ def __():computations (see the next tip)."""),- "Cache intermediate computations with `@functools.cache`": (+ "Cache intermediate computations with `@mo.cache`": ("""- Use Python's builtin `functools` library to cache expensive- intermediate computations. You can do this if you abstract complex- logic into idempotent functions, following earlier tips.+ Use `mo.cache` to cache the return value of expensive functions.+ You can do this if you abstract complex logic into idempotent+ functions, following earlier tips.For example:```python3- import functools+ import marimo as mo- @functools.cache+ @mo.cachedef compute_prediction(problem_parameters):...```@@ -641,6 +641,10 @@ def __():and store them in a cache. The next time it is called with the sameparameters, instead of recomputing the predictions, it will justfetch the previously computed ones from the cache.++ If you are familiar with `functools.cache`, `mo.cache` is+ similar but more robust, with the cache persisting even+ if the cell defining the function is re-run."""),}diff --git a/marimo/_tutorials/markdown.py b/marimo/_tutorials/markdown.pyindex 891beb0b2f..a52849acdd 100644--- a/marimo/_tutorials/markdown.py+++ b/marimo/_tutorials/markdown.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.7.17"+__generated_with = "0.8.22"app = marimo.App()@@ -174,7 +174,7 @@ def __(mo):{leaves}""")- return leaves,+ return (leaves,)@app.cell@@ -230,7 +230,7 @@ def __(missing_numpy_msg, mo, np, numpy_installed):{mo.as_html(make_dataframe())}""")- return make_dataframe,+ return (make_dataframe,)@app.cell(hide_code=True)@@ -279,14 +279,12 @@ def __(matplotlib_installed,missing_matplotlib_msg,missing_numpy_msg,+ mo,np,numpy_installed,plt,):- import functools--- @functools.cache+ @mo.cachedef plotsin(amplitude, period):if not numpy_installed:return missing_numpy_msg@@ -296,7 +294,7 @@ def __(plt.plot(x, amplitude * np.sin(2 * np.pi / period * x))plt.ylim(-2.2, 2.2)return plt.gca()- return functools, plotsin+ return (plotsin,)@app.celldiff --git a/marimo/_tutorials/plots.py b/marimo/_tutorials/plots.pyindex eaee05ac66..aa49c06328 100644--- a/marimo/_tutorials/plots.py+++ b/marimo/_tutorials/plots.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.8.0"+__generated_with = "0.8.22"app = marimo.App()@@ -106,7 +106,7 @@ def __(mo):@app.celldef __(np):x = np.linspace(start=-4, stop=4, num=100, dtype=float)- return x,+ return (x,)@app.cell@@ -140,7 +140,7 @@ def __(plt, x):axis.plot(x, x)axis.plot(x, x**2)axis- return axis,+ return (axis,)@app.cell@@ -173,20 +173,20 @@ def __(mo):{exponent}""")- return exponent,+ return (exponent,)@app.cell-def __(exponent, mo, plt, x):- import functools--- @functools.cache- def _plot(exponent):+def __(mo, plt, x):+ @mo.cache+ def plot_power(exponent):plt.plot(x, x**exponent)return plt.gca()+ return (plot_power,)+def __(exponent, mo, plot_power):_tex = (f"$$f(x) = x^{exponent.value}$$" if exponent.value > 1 else "$$f(x) = x$$")@@ -196,10 +196,10 @@ def __(exponent, mo, plt, x):{_tex}- {mo.as_html(_plot(exponent.value))}+ {mo.as_html(plot_power(exponent.value))}""")- return functools,+ return@app.cell(hide_code=True)@@ -265,7 +265,7 @@ def __():outputs are not shown in the app view."""}- return plt_show_explainer,+ return (plt_show_explainer,)@app.cell@@ -286,7 +286,7 @@ def __():@app.celldef __():import marimo as mo- return mo,+ return (mo,)if __name__ == "__main__":diff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txtindex 6890279f1e..c1e46eedce 100644--- a/tests/_cli/snapshots/dataflow.md.txt+++ b/tests/_cli/snapshots/dataflow.md.txt@@ -426,18 +426,18 @@ tips = {computations (see the next tip)."""),- "Cache intermediate computations with `@functools.cache`": (+ "Cache intermediate computations with `@mo.cache`": ("""- Use Python's builtin `functools` library to cache expensive- intermediate computations. You can do this if you abstract complex- logic into idempotent functions, following earlier tips.+ Use `mo.cache` to cache the return value of expensive functions.+ You can do this if you abstract complex logic into idempotent+ functions, following earlier tips.For example:```python3- import functools+ import marimo as mo- @functools.cache+ @mo.cachedef compute_prediction(problem_parameters):...```@@ -447,6 +447,10 @@ tips = {and store them in a cache. The next time it is called with the sameparameters, instead of recomputing the predictions, it will justfetch the previously computed ones from the cache.++ If you are familiar with `functools.cache`, `mo.cache` is+ similar but more robust, with the cache persisting even+ if the cell defining the function is re-run."""),}diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex e5729693ae..fe90abc9c3 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -934,3 +934,171 @@ class TestCacheDecorator:returnapp.run()++ @staticmethod+ def test_shadowed_state() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def __():+ import marimo as mo++ return (mo,)++ @app.cell+ def __(mo):+ state, set_state = mo.state(None)++ @mo.cache+ def g(state):+ return len(state)++ v = g("123")+ return (g, v)++ @app.cell+ def __(v):+ assert v == 3+ return++ app.run()++ @staticmethod+ def test_shadowed_state_redefined() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def __():+ import marimo as mo++ return (mo,)++ @app.cell+ def __(mo):+ state, set_state = mo.state(None)++ @mo.cache+ def g():+ return len(state)++ state = "123"++ v = g()+ return (g, v)++ @app.cell+ def __(v):+ assert v == 3+ return++ app.run()++ @staticmethod+ def test_transitive_shadowed_state_fails() -> None:+ app = App()+ app._anonymous_file = True++ # Add a unit test to denote a known failure case++ @app.cell+ def __():+ import marimo as mo++ return (mo,)++ @app.cell+ def __(mo):+ state1, set_state1 = mo.state(1)+ state2, set_state2 = mo.state(2)++ state, set_state = mo.state(3)++ # Example of a case where things start to get very tricky. There+ # comes a point where you might also have to capture frame levels+ # as well if you mix scope.+ #+ # This is solved by throwing an exception when state+ # shadowing occurs.+ def f():+ return state()++ @mo.cache+ def g(state):+ return state() + f()++ # Cannot resolved shadowed ref.+ with pytest.raises(RuntimeError) as e:+ app.run()++ assert "rename the argument" in str(e)++ @staticmethod+ def test_shadowed_state_mismatch() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def __():+ import marimo as mo++ return (mo,)++ @app.cell+ def __(mo):+ state1, set_state1 = mo.state(1)+ state2, set_state2 = mo.state(2)++ state, set_state = mo.state(3)++ @mo.cache+ def g(state):+ return state()++ a = g(state1)+ b = g(state2)++ A = g(state1)+ B = g(state2)+ assert g.hits == 2+ return (a, b, A, B)++ @app.cell+ def __(a, b, A, B, state, state1, state2):+ assert state1() != state2()+ assert state1() == a == A+ assert state2() == b == B+ assert state() == 3+ return++ app.run()++ @staticmethod+ def test_shadowed_ui() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def __():+ import marimo as mo++ return (mo,)++ @app.cell+ def __(mo):+ slider = mo.ui.slider(0, 1)++ @mo.cache+ def g(slider):+ return len(slider)++ v = g("123")+ return (g, v, slider)++ @app.cell+ def __(v):+ assert v == 3+ return++ app.run()diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 102ccdae7e..7e0fa44cf7 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -315,17 +315,23 @@ class TestHash:return persistent_cache, MockLoader, shared, state, set_state@app.cell- def one(persistent_cache, MockLoader, shared, set_state) -> tuple[Any]:+ def one(+ persistent_cache, MockLoader, shared, set_state, state+ ) -> tuple[Any]:with persistent_cache(name="one", _loader=MockLoader()) as cache:_Y = len(shared())+ assert _Y == state()set_state(1)assert cache._cache.cache_type == "ExecutionPath"return (cache,)@app.cell- def two(persistent_cache, MockLoader, shared, cache) -> tuple[Any]:+ def two(+ persistent_cache, MockLoader, shared, cache, state+ ) -> tuple[Any]:with persistent_cache(name="two", _loader=MockLoader()) as cache2:_Y = len(shared())+ assert _Y == state()assert cache2._cache.cache_type == "ExecutionPath"assert cache2._cache.hash != cache._cache.hashreturn (cache2,)