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
cache iteration: various fixes- will invalidate exisiting cache (#3480)
Dylan Madisettica092e92a483
diff --git a/marimo/_ast/models.py b/marimo/_ast/models.pyindex 8fd3f22bbe..1795c11531 100644--- a/marimo/_ast/models.py+++ b/marimo/_ast/models.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsfrom dataclasses import dataclassdiff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.pyindex c521635cfb..375453f21d 100644--- a/marimo/_runtime/primitives.py+++ b/marimo/_runtime/primitives.py@@ -79,13 +79,24 @@ def is_data_primitive(value: Any) -> bool:or (hasattr(value.dtype, "hasobject") and value.dtype.hasobject))elif hasattr(value, "dtypes"):- for dtype in value.dtypes:- # Capture pandas cases- if getattr(dtype, "hasobject", None):- return False- # Capture polars cases- if hasattr(dtype, "is_numeric") and not dtype.is_numeric:- return False+ # Bit of discrepancy between objects like polars and pandas, so use+ # narwhals to normalize the dataframe.+ import narwhals as nw++ try:+ return bool(+ nw.narwhalify(+ lambda df: all(+ df[col].dtype.is_numeric() for col in df.columns+ )+ )(value)+ )+ except Exception as err:+ raise err from ValueError(+ "Unexpected datatype, narwhals was unable to normalize "+ "dataframe. Please report this to "+ "github.com/marimo-team/marimo"+ )# Otherwise may be a closely related array objectreturn Truediff --git a/marimo/_save/ast.py b/marimo/_save/ast.pyindex 2a7f954836..344c07fe29 100644--- a/marimo/_save/ast.py+++ b/marimo/_save/ast.py@@ -8,6 +8,8 @@ from typing import Any, Callable, Sequence, castfrom marimo._utils.variables import unmangle_local+ARG_PREFIX: str = "*"+class BlockException(Exception):pass@@ -91,11 +93,22 @@ class ExtractWithBlock(ast.NodeTransformer):assert isinstance(node, list), "Unexpected block structure."for n in node:+ # There's a chance that the block is first evaluated somewhere in a+ # multiline line expression, for instance:+ # 1 >>> with cache as c:+ # 2 >>> a = [+ # 3 >>> f(x) # <<< first frame call is here, and not line 2+ # 4 >>> ]+ # so check that the "target" line is in the interval+ # (i.e. 1 <= 3 <= 4)+ parent = Noneif n.lineno < self.target_line:pre_block.append(n)previous = n- elif n.lineno == self.target_line:+ # the line is contained with this+ elif n.lineno <= self.target_line <= n.end_lineno:on_line.append(n)+ parent = n# The target line can easily be skipped if there are comments or# white space or if the block is contained within another block.else:@@ -106,15 +119,35 @@ class ExtractWithBlock(ast.NodeTransformer):# excluding by omission try, for, classes and functions.if len(on_line) == 0:if isinstance(previous, (ast.With, ast.If)):- try:- # Recursion by referring the the containing block also- # captures the case where the target line number was not- # exactly hit.- return ExtractWithBlock(self.target_line).generic_visit(- previous.body # type: ignore[arg-type]- )- except BlockException:- on_line.append(previous)+ on_line.append(previous)+ # Captures both branches of If, and the With block.+ bodies = (+ [previous.body]+ if isinstance(previous, ast.With)+ else [previous.body, previous.orelse]+ )+ for body in bodies:+ try:+ # Recursion by referring to the containing block also+ # captures the case where the target line number was not+ # exactly hit.+ # for instance:+ # 1 >>> if True: # Captured ast node+ # 2 >>> with fn() as x:+ # 3 >>> with cache as c:+ # 4 >>> a = 1 # <<< frame line+ # will recurse through here thrice to get to the frame+ # line.+ # NB. the "extracted" With block is the one that+ # invoked this call+ return ExtractWithBlock(+ self.target_line+ ).generic_visit(+ body # type: ignore[arg-type]+ )+ except BlockException:+ pass+else:raise BlockException("persistent_cache cannot be invoked within a block "@@ -122,15 +155,44 @@ class ExtractWithBlock(ast.NodeTransformer):)# Intentionally not elif (on_line can be added in previous block)if len(on_line) == 1:- assert isinstance(on_line[0], ast.With), "Unexpected block."+ if parent and not isinstance(on_line[0], ast.With):+ raise BlockException("Detected line is not a With statement.")+ if not isinstance(on_line[0], ast.With):+ raise BlockException(+ "Unconventional formatting may lead to unexpected behavior. "+ "Please format your code, and/or reduce nesting.\n"+ "For instance, the following is not supported:\n"+ ">>>> with cache() as c: a = 1 # all one line"+ )return clean_to_modules(pre_block, on_line[0])# It should be possible to relate the lines with the AST,# but reduce potential bugs by just throwing an error.raise BlockException(- "Saving on a shared line may lead to unexpected behavior."+ "Unable to determine structure your call. Please"+ " report this to github:marimo-team/marimo/issues")+class MangleArguments(ast.NodeTransformer):+ """Mangles arguments names to prevent shadowing issues in analysis."""++ def __init__(+ self,+ args: set[str],+ *arg: Any,+ prefix: str = ARG_PREFIX,+ **kwargs: Any,+ ) -> None:+ super().__init__(*arg, **kwargs)+ self.prefix = prefix+ self.args = args++ def visit_Name(self, node: ast.Name) -> ast.Name:+ if node.id in self.args:+ node.id = f"{self.prefix}{node.id}"+ return node++class DeprivateVisitor(ast.NodeTransformer):"""Removes the mangling of private variables from a module."""@@ -157,6 +219,7 @@ class RemoveReturns(ast.NodeTransformer):def strip_function(fn: Callable[..., Any]) -> ast.Module:code, _ = inspect.getsourcelines(fn)+ args = set(fn.__code__.co_varnames)function_ast = ast.parse(textwrap.dedent("".join(code)))body = function_ast.body.pop()assert isinstance(body, (ast.FunctionDef, ast.AsyncFunctionDef)), (@@ -164,5 +227,6 @@ def strip_function(fn: Callable[..., Any]) -> ast.Module:)extracted = ast.Module(body.body, type_ignores=[])module = RemoveReturns().visit(extracted)+ module = MangleArguments(args).visit(module)assert isinstance(module, ast.Module), "Expected a module"return modulediff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex f7c0fdbfbb..550f666b73 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -8,7 +8,7 @@ import inspectimport structimport sysimport types-from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, Optional+from typing import TYPE_CHECKING, Any, Callable, Iterable, NamedTuple, Optionalfrom marimo._ast.visitor import Name, ScopedVisitorfrom marimo._dependencies.dependencies import DependencyManager@@ -22,7 +22,7 @@ from marimo._runtime.primitives import (is_pure_function,)from marimo._runtime.state import SetFunctor, State-from marimo._save.ast import DeprivateVisitor+from marimo._save.ast import DeprivateVisitor, strip_functionfrom marimo._save.cache import Cache, CacheTypefrom marimo._utils.variables import (get_cell_from_local,@@ -57,10 +57,6 @@ 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:@@ -79,7 +75,9 @@ def hash_module(hash_alg.update(str(const).encode("utf8"))# Concatenate the names and bytecode of the current code object# Will cause invalidation of variable naming at the top level- hash_alg.update(bytes("|".join(code_obj.co_names), "utf8"))++ names = [unmangle_local(name).name for name in code_obj.co_names]+ hash_alg.update(bytes("|".join(names), "utf8"))hash_alg.update(code_obj.co_code)process(code)@@ -92,7 +90,7 @@ def hash_raw_module(# AST has to be compiled to code object prior to process.return hash_module(compile(- module,+ DeprivateVisitor().visit(module),"<hash>",mode="exec",flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,@@ -107,6 +105,38 @@ def hash_cell_impl(cell: CellImpl, hash_type: str = DEFAULT_HASH) -> bytes:)+def hash_function(+ fn: Callable[..., Any], hash_type: str = DEFAULT_HASH+) -> bytes:+ return hash_raw_module(+ DeprivateVisitor().visit(strip_function(fn)), hash_type+ )+++def hash_cell_group(+ cell_ids: set[CellId_t],+ graph: DirectedGraph,+ hash_type: str = DEFAULT_HASH,+) -> bytes:+ hash_alg = hashlib.new(hash_type, usedforsecurity=False)+ hashes = []+ for cell_id in cell_ids:+ cell_impl = graph.cells[cell_id]+ hashes.append(hash_cell_impl(cell_impl, hash_alg.name))++ # Sort results post hash, to ensure deterministic ordering.+ for hashed_cell in sorted(hashes):+ hash_alg.update(hashed_cell)+ return hash_alg.digest()+++def hash_cell_execution(+ cell_id: CellId_t, graph: DirectedGraph, hash_type: str = DEFAULT_HASH+) -> bytes:+ ancestors = graph.ancestors(cell_id)+ return hash_cell_group(ancestors, graph, hash_type)++def standardize_tensor(tensor: Tensor) -> Optional[Tensor]:if (hasattr(tensor, "__array__")@@ -719,22 +749,6 @@ class BlockHasher: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(@@ -776,9 +790,8 @@ class BlockHasher:*[self.graph.definitions.get(ref, set()) for ref in refs])to_hash = ancestors & ref_cells- for ancestor_id in sorted(to_hash):+ for ancestor_id in to_hash:cell_impl = self.graph.cells[ancestor_id]- self.hash_alg.update(hash_cell_impl(cell_impl, self.hash_alg.name))for ref in cell_impl.defs:# Look for both, since mangle reference depends on the context# of the definition.@@ -787,6 +800,9 @@ class BlockHasher:unmangled_ref, _ = unmangle_local(ref)if unmangled_ref in refs:refs.remove(unmangled_ref)+ self.hash_alg.update(+ hash_cell_group(to_hash, self.graph, self.hash_alg.name)+ )return refsdef hash_and_verify_context_refs(diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex e9004a05e0..3159a4ea31 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -21,12 +21,11 @@ from marimo._messaging.tracebacks import write_tracebackfrom marimo._runtime.context import get_contextfrom marimo._runtime.runtime import notebook_dirfrom marimo._runtime.state import State-from marimo._save.ast import ExtractWithBlock, strip_function+from marimo._save.ast import ARG_PREFIX, ExtractWithBlock, strip_functionfrom marimo._save.cache import Cache, CacheExceptionfrom marimo._save.hash import (DEFAULT_HASH,BlockHasher,- ShadowedRef,cache_attempt_from_hash,content_cache_attempt_from_base,)@@ -115,21 +114,13 @@ 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.# For instance, the args of the invoked function are restricted to the# block.cell_id = ctx.cell_id or ctx.execution_context.cell_id or ""- self.scoped_refs = set(self._args)+ self.scoped_refs = set([f"{ARG_PREFIX}{k}" for k in self._args])# # As are the "locals" not in globalsself.scoped_refs |= set(f_locals.keys()) - set(ctx.globals.keys())# Defined in the cell, and currently available in scope@@ -184,8 +175,10 @@ class _cache_base(object):self._set_context(args[0])return self+ # Rewrite scoped args to prevent shadowed variables+ arg_dict = {f"{ARG_PREFIX}{k}": v for (k, v) in zip(self._args, args)}+ kwargs = {f"{ARG_PREFIX}{k}": v for (k, v) in kwargs.items()}# Capture the call case- arg_dict = {k: v for (k, v) in zip(self._args, args)}scope = {**self.scope, **get_context().globals, **arg_dict, **kwargs}assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATEattempt = content_cache_attempt_from_base(@@ -193,7 +186,7 @@ class _cache_base(object):scope,self._loader(),scoped_refs=self.scoped_refs,- required_refs=set(self._args),+ required_refs=set([f"{ARG_PREFIX}{k}" for k in self._args]),as_fn=True,)diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 297d49adc2..7d1d5d9474 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -69,7 +69,10 @@ class TestScriptCache:from tests._save.mocks import MockLoader# fmt: off- with persistent_cache(name="one", _loader=MockLoader(data={"X": 7, "Y": 8})) as cache: # noqa: E501+ with persistent_cache(name="one",+ _loader=MockLoader(+ data={"X": 7, "Y": 8})+ ) as cache: # noqa: E501Y = 9X = 10# fmt: on@@ -81,6 +84,203 @@ class TestScriptCache:app.run()+ @staticmethod+ def test_cache_linebreak() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ # fmt: off+ # issues 3332, 2633+ with persistent_cache("one", _loader=_loader) as cache:+ b = [+ 8+ ]+ # fmt: on+ assert b == [8]+ assert cache._cache.defs == {"b": [8]}++ app.run()++ @staticmethod+ def test_cache_if_block_and_break() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ # fmt: off+ b = [2]+ if True:+ with persistent_cache("if", _loader=_loader):+ b = [+ 7+ ]+ # fmt: on+ assert b == [7]++ app.run()++ @staticmethod+ def test_cache_if_block() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ b = 2+ if True:+ with persistent_cache("if", _loader=_loader):+ b = 8+ assert b == 8++ app.run()++ @staticmethod+ def test_cache_else_block() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ if False:+ b = 2+ else:+ with persistent_cache("else", _loader=_loader):+ b = 8+ assert b == 8++ @staticmethod+ def test_cache_elif_block() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ if False:+ b = 2+ elif True:+ with persistent_cache("else", _loader=_loader):+ b = 8+ assert b == 8++ app.run()++ @staticmethod+ def test_cache_with_block() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from contextlib import contextmanager++ @contextmanager+ def called(v):+ assert v+ yield 1++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ with called(True):+ with persistent_cache("else", _loader=_loader):+ b = 8+ assert b == 8++ app.run()++ @staticmethod+ def test_cache_with_block_inner() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from contextlib import contextmanager++ @contextmanager+ def called(v):+ assert v+ yield 1++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ with persistent_cache("else", _loader=_loader):+ with called(True):+ b = 8+ assert b == 8++ app.run()++ @staticmethod+ def test_cache_same_line_fails() -> None:+ app = App()+ app._anonymous_file = True+ from marimo._save.ast import BlockException++ @app.cell+ def one() -> tuple[int]:+ def call(v):+ assert v++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()+ # fmt: off+ with persistent_cache("else", _loader=_loader): call(False) # noqa: E701+ # fmt: on++ with pytest.raises(BlockException):+ app.run()++ @staticmethod+ def test_cache_in_fn_fails() -> None:+ app = App()+ app._anonymous_file = True+ from marimo._save.ast import BlockException++ @app.cell+ def one() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ _loader = MockLoader()++ def call():+ with persistent_cache("else", _loader=_loader):+ return 1++ call()++ with pytest.raises(BlockException):+ app.run()+class TestAppCache:async def test_cache_miss(self, any_kernel: Kernel) -> None:@@ -996,11 +1196,49 @@ class TestCacheDecorator:app.run()@staticmethod- def test_transitive_shadowed_state_fails() -> None:+ def test_internal_shadowed() -> 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):+ state0, set_state0 = mo.state(1)+ state1, set_state1 = mo.state(1)+ state2, set_state2 = mo.state(10)++ state, set_state = mo.state(100)++ @mo.cache+ def h(state):+ x = state()++ def g():+ global state++ def f(state):+ return x + state()++ return state() + f(state2)++ return g()++ assert h(state0) == 111+ assert h.hits == 0+ assert h(state1) == 111+ assert h.hits == 1++ app.run()++ @staticmethod+ def test_transitive_shadowed_state_passes() -> None:+ app = App()+ app._anonymous_file = True@app.celldef __():@@ -1010,29 +1248,33 @@ class TestCacheDecorator:@app.celldef __(mo):+ state0, set_state0 = mo.state(1)state1, set_state1 = mo.state(1)- state2, set_state2 = mo.state(2)+ state2, set_state2 = mo.state(10)- state, set_state = mo.state(3)+ state, set_state = mo.state(100)# 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():+ # This is solved by rewriting potential name collisions+ def h(state):return state()+ def f():+ return state() + h(state2)+@mo.cachedef g(state):return state() + f()- # Cannot resolved shadowed ref.- with pytest.raises(RuntimeError) as e:- app.run()+ assert g(state0) == 111+ assert g.hits == 0+ assert g(state1) == 111+ assert g.hits == 1- assert "rename the argument" in str(e)+ app.run()@staticmethoddef test_shadowed_state_mismatch() -> None:@@ -1050,6 +1292,7 @@ class TestCacheDecorator:state1, set_state1 = mo.state(1)state2, set_state2 = mo.state(2)+ # Here as a var for shadowingstate, set_state = mo.state(3)@mo.cache@@ -1058,7 +1301,7 @@ class TestCacheDecorator:a = g(state1)b = g(state2)-+ assert g.hits == 0A = g(state1)B = g(state2)assert g.hits == 2diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 4ede3813ae..5de2bc4690 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -142,7 +142,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "V_BAVE7PI97W7iec44GYXD69pebyztj7R3jgGFAnnEM"+ == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -163,7 +163,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "V_BAVE7PI97W7iec44GYXD69pebyztj7R3jgGFAnnEM"+ == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -172,6 +172,64 @@ class TestHash:app.run()+ @staticmethod+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_execution_reproducibility_different_cell_order() -> None:+ app = App()+ app._anonymous_file = True++ # NB. load is last for cell order difference.+ @app.cell+ def one(persistent_cache, MockLoader, shared) -> tuple[int]:+ _a = [1, object()]+ with persistent_cache(+ name="one", _loader=MockLoader(data={"_X": 7})+ ) as _cache:+ _X = 10 + _a[0] - len(shared) # Comment+ assert _X == 7+ # Cannot be reused/ shared, because it will change the hash.+ assert (+ _cache._cache.hash+ == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ ), _cache._cache.hash+ assert _cache._cache.cache_type == "ContextExecutionPath"+ return++ @app.cell+ def two(persistent_cache, MockLoader, shared) -> tuple[int]:+ # The same as cell one, but with this comment+ _a = [+ 1, # Comment+ object(),+ ]+ # Some white space+ with persistent_cache(+ name="one", _loader=MockLoader(data={"_X": 7})+ ) as _cache:+ # More Comments+ _X = 10 + _a[0] - len(shared)+ assert _X == 7+ assert (+ _cache._cache.hash+ == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ ), _cache._cache.hash+ assert _cache._cache.cache_type == "ContextExecutionPath"+ # and a post block difference+ Z = 11+ return (Z,)++ @app.cell+ def load() -> tuple[int]:+ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ shared = [None, object()]+ return persistent_cache, MockLoader, shared++ app.run()+@staticmethoddef test_transitive_content_hash() -> None:app = App()@@ -579,7 +637,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.mocks import MockLoader- expected_hash = "rTAh8yNbBbq9qkF1nGNUw4DXhZSxRqGe4ptbDh2AwBI"+ expected_hash = "iV5v_cNAxBPqe8tNJnI5volNORTH_gyhKuIvHcG_cds"return MockLoader, persistent_cache, expected_hash, torch@app.cell@@ -655,7 +713,7 @@ class TestDataHash:@pytest.mark.skipif("sys.version_info < (3, 12) or sys.version_info >= (3, 13)")- def test_process_dataframe() -> None:+ def test_dataframe() -> None:app = App()app._anonymous_file = True@@ -724,7 +782,7 @@ class TestDataHash:@pytest.mark.skipif("sys.version_info < (3, 12) or sys.version_info >= (3, 13)")- def test_process_dataframe_object() -> None:+ def test_dataframe_object() -> None:app = App()app._anonymous_file = True@@ -736,7 +794,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.mocks import MockLoader- expected_hash = "n4KGJ3wrRHd6pDCyekTWZXShmtT_ZkDY4Wo3C6BXzh4"+ expected_hash = "RbeMLx994_-kB9rF2ebi6mFMbCW_S6-Q41MsrgJgwUA"return MockLoader, persistent_cache, expected_hash, np, pd@app.cell@@ -771,7 +829,7 @@ class TestDataHash:@pytest.mark.skipif("sys.version_info < (3, 12) or sys.version_info >= (3, 13)")- def test_process_polars_dataframe() -> None:+ def test_polars_dataframe() -> None:app = App()app._anonymous_file = True@@ -824,3 +882,46 @@ class TestDataHash:assert one == 14app.run()++ @staticmethod+ @pytest.mark.skipif(+ not DependencyManager.has("polars"),+ reason="optional dependencies not installed",+ )+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_polars_object() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def load() -> tuple[Any]:+ import polars as pl++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ expected_hash = "QzGgcNS-eEP58qkkFphgAOJNKEpoTNcXhJ-L2exXzr4"+ return MockLoader, persistent_cache, expected_hash, pl++ @app.cell+ def two(MockLoader, persistent_cache, expected_hash, pl) -> tuple[int]:+ _a = {+ "A": [2, 8, 18],+ "B": ["a", "a", "a"],+ "C": [14, 16, 18],+ }+ _a = pl.DataFrame(_a)++ with persistent_cache(name="two", _loader=MockLoader()) as _cache:+ _A = _a.select(pl.col("A").sum()).item()++ assert _cache._cache.cache_type == "ContextExecutionPath"+ assert _cache._cache.hash == expected_hash, (+ f"expected_hash != {_cache._cache.hash}"+ )+ assert _A == 28+ return (two,)++ app.run()