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: Expand and test hashing data "arrays" (#2547)
Dylan Madisettidc7f6ba55e0d
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.pyindex 6653cb1853..3bf8a80f95 100644--- a/marimo/_runtime/executor.py+++ b/marimo/_runtime/executor.py@@ -17,6 +17,8 @@ from marimo._runtime.copy import (from marimo._runtime.primitives import (CLONE_PRIMITIVES,build_ref_predicate_for_primitives,+ from_unclonable_module,+ is_unclonable_type,)from marimo._utils.variables import is_mangled_local, unmangle_local@@ -24,21 +26,6 @@ if TYPE_CHECKING:from marimo._runtime.dataflow import DirectedGraph-UNCLONABLE_TYPES = [- "marimo._runtime.state.State",- "marimo._runtime.state.SetFunctor",-]--UNCLONABLE_MODULES = set(- [- "_asyncio",- "_io",- "marimo._ast",- "marimo._plugins.ui",- "numpy.lib.npyio",- ]-)-EXECUTION_TYPES: dict[str, Type[Executor]] = {}@@ -313,21 +300,3 @@ class StrictExecutor(Executor):for df in lcls:if is_mangled_local(df, cell.cell_id):glbls[df] = lcls[df]---def is_instance_by_name(obj: object, name: str) -> bool:- if not (hasattr(obj, "__module__") and hasattr(obj, "__class__")):- return False- obj_name = f"{obj.__module__}.{obj.__class__.__name__}"- return obj_name == name---def is_unclonable_type(obj: object) -> bool:- return any([is_instance_by_name(obj, name) for name in UNCLONABLE_TYPES])---def from_unclonable_module(obj: object) -> bool:- obj = obj if hasattr(obj, "__module__") else obj.__class__- return hasattr(obj, "__module__") and any(- [obj.__module__.startswith(name) for name in UNCLONABLE_MODULES]- )diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.pyindex cc5acee99a..08d402aa5e 100644--- a/marimo/_runtime/primitives.py+++ b/marimo/_runtime/primitives.py@@ -19,6 +19,21 @@ CLONE_PRIMITIVES = (weakref.ref,) + PRIMITIVESFN_CACHE_TYPE = Optional[dict[Union[Callable[..., Any], type], bool]]+UNCLONABLE_TYPES = [+ "marimo._runtime.state.State",+ "marimo._runtime.state.SetFunctor",+]++UNCLONABLE_MODULES = set(+ [+ "_asyncio",+ "_io",+ "marimo._ast",+ "marimo._plugins.ui",+ "numpy.lib.npyio",+ ]+)+def is_external(value: Any) -> bool:return "_marimo__cell_" not in inspect.getfile(value)@@ -43,17 +58,27 @@ def is_data_primitive(value: Any) -> bool:if is_primitive(value):return True- # If a numpy array, ensure that it's not an object array.- if hasattr(value, "__array_interface__"):- dtype = getattr(value, "dtype", None)+ if not (+ hasattr(value, "__array__")+ or hasattr(value, "toarray")+ or hasattr(value, "__array_interface__")+ ):+ return False++ # If a numpy like array, ensure that it's not an object array.+ if hasattr(value, "dtype"):+ # Handle cross device tensors particular to torch+ # Transfer may be expensive, so non-cpu tensors are considered+ # unhashable.+ if is_instance_by_name(value, "torch.Tensor"):+ return str(value.device) == "cpu"+return not (- dtype is not None- and hasattr(dtype, "hasobject")- and dtype.hasobject+ value.dtype is None+ or (hasattr(value.dtype, "hasobject") and value.dtype.hasobject))-# Otherwise may be a closely related array object like a pandas DataFrame.- return hasattr(value, "__array__") or hasattr(value, "toarray")+ return Truedef _is_primitive_container(@@ -89,6 +114,24 @@ def is_primitive_container(value: Any) -> bool:return _is_primitive_container(value, is_primitive)+def is_instance_by_name(obj: object, name: str) -> bool:+ if not (hasattr(obj, "__module__") and hasattr(obj, "__class__")):+ return False+ obj_name = f"{obj.__module__}.{obj.__class__.__name__}"+ return obj_name == name+++def is_unclonable_type(obj: object) -> bool:+ return any([is_instance_by_name(obj, name) for name in UNCLONABLE_TYPES])+++def from_unclonable_module(obj: object) -> bool:+ obj = obj if hasattr(obj, "__module__") else obj.__class__+ return hasattr(obj, "__module__") and any(+ [obj.__module__.startswith(name) for name in UNCLONABLE_MODULES]+ )++def is_pure_scope(ref: Name,defs: dict[str, Any],diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 8356ae8272..d25350442b 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport astimport base64import hashlib+import inspectimport structimport sysimport types@@ -107,21 +108,24 @@ def hash_cell_impl(cell: CellImpl, hash_type: str = DEFAULT_HASH) -> bytes:def standardize_tensor(tensor: Tensor) -> Optional[Tensor]:- # TODO: Consider moving to a more general utility module.- if hasattr(tensor, "__array__") or hasattr(tensor, "toarray"):- if not hasattr(tensor, "__array_interface__"):- DependencyManager.numpy.require(- "to access data buffer for hashing."- )- import numpy+ if (+ hasattr(tensor, "__array__")+ or hasattr(tensor, "toarray")+ or hasattr(tensor, "__array_interface__")+ ):+ DependencyManager.numpy.require("to access data buffer for hashing.")+ import numpy+ if not hasattr(tensor, "__array_interface__"):# Capture those sparse casesif hasattr(tensor, "toarray"):tensor = tensor.toarray()- tensor = numpy.array(tensor)- return tensor+ # As array should not perform copy+ return numpy.asarray(tensor)raise ValueError(- f"Expected an image object, but got {type(tensor)} instead."+ f"Expected a data primitive object, but got {type(tensor)} instead."+ "This maybe is an internal marimo issue. Please report to "+ "https://github.com/marimo-team/marimo/issues.")@@ -680,6 +684,14 @@ class BlockHasher:# pinning being the mechanism for invalidation.elif getattr(value, "__module__", "__main__") == "__main__":continue+ # External module that is not a class or function, may be some+ # container we don't know how to hash.+ # Note, function cases care caught by is_pure_function+ # And we assume all marimo cases are caught+ elif not inspect.isclass(+ value+ ) and not value.__module__.startswith("marimo"):+ continueif serial_value is not None:content_serialization[ref] = serial_valuediff --git a/pyproject.toml b/pyproject.tomlindex 037b3b1f0d..90237f1085 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -189,17 +189,23 @@ extra-dependencies = ["polars~=1.9.0","pandas>=1.5.3","geopandas~=0.14.4; python_version > '3.9'",+ # FOr testing sql+ "ibis-framework[duckdb]~=9.5.0; python_version > '3.9'",# For testing mo.image"pillow~=10.4.0","anywidget~=0.9.13","ipython~=8.12.3",+ # testing gen ai"openai~=1.41.1",- "ibis-framework[duckdb]~=9.5.0; python_version > '3.9'","anthropic==0.34.1","google-generativeai==0.8.2",# exporting as ipynb"nbformat >=5.10.4","sympy>=1.13.2",+ # For standard scientific computing/ ML+ "jax>=0.4.0; python_version == '3.12'",+ "torch>=2.4.0; python_version == '3.12'",+ "scikit-bio>=0.6.0; python_version == '3.12'",][[tool.hatch.envs.test-optional.matrix]]diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 7e0fa44cf7..6ea9ff5c3f 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -50,7 +50,7 @@ class TestHash:# Note: Hash may change based on byte code, so pin to particular version@staticmethod@pytest.mark.skipif(- "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)")def test_content_reproducibility() -> None:app = App()@@ -61,7 +61,7 @@ class TestHash:from marimo._save.save import persistent_cachefrom tests._save.mocks import MockLoader- expected_hash = "rzWe8aalExwCRLmrdG0NkCp0QbSupaZdiimloFs9SKw"+ expected_hash = "haIqC9yzlTaNo-ClmY11Kvtiv08oQPz3-SlnOLfhJYM"return expected_hash, persistent_cache, MockLoader@@ -117,7 +117,7 @@ class TestHash:@staticmethod@pytest.mark.skipif(- "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)")def test_execution_reproducibility() -> None:app = App()@@ -142,7 +142,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "ZOoW-62h9ubJQ92u9h1UWydCsuwtXafS2tmDUcH8dLc"+ == "V_BAVE7PI97W7iec44GYXD69pebyztj7R3jgGFAnnEM"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -163,7 +163,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "ZOoW-62h9ubJQ92u9h1UWydCsuwtXafS2tmDUcH8dLc"+ == "V_BAVE7PI97W7iec44GYXD69pebyztj7R3jgGFAnnEM"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -386,7 +386,7 @@ class TestDataHash:# Pin to a particular python version for differences in underlying library# implementations / memory layout.@pytest.mark.skipif(- "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)")def test_numpy_hash() -> None:app = App()@@ -399,7 +399,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.mocks import MockLoader- expected_hash = "aInOwuFXPXqX3XHlU4KGi3w7rzr30OwBIPYTUBrpSKM"+ expected_hash = "w_Bjhpz2xMVQC6Y61GgqB8O80u_UyoJ-1xQmJU3j0Gg"return MockLoader, persistent_cache, expected_hash, np@app.cell@@ -435,3 +435,212 @@ class TestDataHash:assert one == 512app.run()++ @staticmethod+ @pytest.mark.skipif(+ not DependencyManager.has("jax"),+ reason="optional dependencies not installed",+ )+ # Pin to a particular python version for differences in underlying library+ # implementations / memory layout.+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_jax_hash() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def load() -> tuple[Any]:+ from jax import numpy as np++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ expected_hash = "aAL9QNoQIQ1zOJgm_xDbHG63Bc4Atnpn58pGW9x9A_A"+ return MockLoader, persistent_cache, expected_hash, np++ @app.cell+ def one(MockLoader, persistent_cache, expected_hash, np) -> tuple[int]:+ _a = np.ones((16, 16)) * 2+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:+ _A = np.sum(_a)+ one = _A++ assert _cache._cache.cache_type == "ContentAddressed"+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (one,)++ @app.cell+ def two(MockLoader, persistent_cache, expected_hash, np) -> tuple[int]:+ _a = np.ones((16, 16)) + np.ones((16, 16))++ with persistent_cache(name="two", _loader=MockLoader()) as _cache:+ _A = np.sum(_a)+ two = _A++ assert _cache._cache.cache_type == "ContentAddressed"+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (two,)++ @app.cell+ def three(one, two) -> None:+ assert one == two+ assert one == 512++ app.run()++ @staticmethod+ @pytest.mark.skipif(+ not DependencyManager.has("torch"),+ reason="optional dependencies not installed",+ )+ # Pin to a particular python version for differences in underlying library+ # implementations / memory layout.+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_torch_hash() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def load() -> tuple[Any]:+ import torch++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ expected_hash = "stIOtiKIn4yscvKd-uK6mbmZpWzzfGm8Ccz7mvnRrnI"+ return MockLoader, persistent_cache, expected_hash, torch++ @app.cell+ def one(+ MockLoader, persistent_cache, expected_hash, torch+ ) -> tuple[int]:+ _a = torch.ones((16, 16)) * 2+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:+ _A = torch.sum(_a)+ one = _A++ assert _cache._cache.cache_type == "ContentAddressed"+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (one,)++ @app.cell+ def two(+ MockLoader, persistent_cache, expected_hash, torch+ ) -> tuple[int]:+ _a = torch.ones((16, 16)) + torch.ones((16, 16))++ with persistent_cache(name="two", _loader=MockLoader()) as _cache:+ _A = torch.sum(_a)+ two = _A++ assert _cache._cache.cache_type == "ContentAddressed"+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (two,)++ @app.cell+ def three(one, two) -> None:+ assert one == two+ assert one == 512++ app.run()++ @staticmethod+ @pytest.mark.skipif(+ not DependencyManager.has("torch"),+ reason="optional dependencies not installed",+ )+ # Pin to a particular python version for differences in underlying library+ # implementations / memory layout.+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_torch_device_hash() -> None:+ # Utilizing the "meta" device should give similar cross device behavior+ # as gpu.+ app = App()+ app._anonymous_file = True++ @app.cell+ def load() -> tuple[Any]:+ import torch++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ expected_hash = "rTAh8yNbBbq9qkF1nGNUw4DXhZSxRqGe4ptbDh2AwBI"+ return MockLoader, persistent_cache, expected_hash, torch++ @app.cell+ def one(+ MockLoader, persistent_cache, expected_hash, torch+ ) -> tuple[int]:+ _a = torch.ones((16, 16), device="meta") * 2+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:+ _A = torch.sum(_a)+ one = _A++ assert (+ _cache._cache.cache_type == "ContextExecutionPath"+ ), _cache._cache.cache_type+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (one,)++ app.run()++ @staticmethod+ @pytest.mark.skipif(+ not DependencyManager.has("skbio"),+ reason="optional dependencies not installed",+ )+ # Pin to a particular python version for differences in underlying library+ # implementations / memory layout.+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_skibio_hash() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def load() -> tuple[Any]:+ from copy import copy++ from skbio import DNA++ from marimo._save.save import persistent_cache+ from tests._save.mocks import MockLoader++ expected_hash = "ggxwHLzWcyDQltN_Zq0_zYVP_w86a9AAQLQwleAMuH8"+ return MockLoader, persistent_cache, expected_hash, DNA, copy++ @app.cell+ def one(+ MockLoader, persistent_cache, expected_hash, copy, DNA+ ) -> tuple[int]:+ strand = DNA("GATTACA")+ # Siblings not bound to be in-valid+ sibling = copy(strand)+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:+ assert strand == sibling++ assert _cache._cache.cache_type == "ContentAddressed"+ assert (+ _cache._cache.hash == expected_hash+ ), f"expected_hash != {_cache._cache.hash}"+ return (one,)++ app.run()