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.

Additional tests for content hashing in tables (pandas, polars) (#2562)

Dylan Madisetti374e303f59bc
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
index 08d402aa5e..fafee7de8b 100644
--- a/marimo/_runtime/primitives.py
+++ b/marimo/_runtime/primitives.py
@@ -65,19 +65,27 @@ def is_data_primitive(value: Any) -> bool:
):
return False
+ # 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"
+
# 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 (
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.
+ 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
+ # Otherwise may be a closely related array object
return True
diff --git a/pyproject.toml b/pyproject.toml
index 90237f1085..af66723517 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -195,7 +195,7 @@ extra-dependencies = [
"pillow~=10.4.0",
"anywidget~=0.9.13",
"ipython~=8.12.3",
- # testing gen ai
+ # testing gen ai
"openai~=1.41.1",
"anthropic==0.34.1",
"google-generativeai==0.8.2",
@@ -365,6 +365,9 @@ asyncio_mode = "auto"
[tool.coverage.run]
omit = ["marimo/_tutorials/*"]
+[tool.typos.default]
+extend-ignore-re = ["[0-9a-zA-Z]{43}"]
+
[tool.typos.default.extend-words]
wheres = "wheres"
Ue = "Ue" # Used in one of the cell IDs
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index 6ea9ff5c3f..2e35bcd8e5 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -644,3 +644,183 @@ class TestDataHash:
return (one,)
app.run()
+
+ @staticmethod
+ @pytest.mark.skipif(
+ not DependencyManager.has("pandas"),
+ 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_process_dataframe() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import numpy as np
+ import pandas as pd
+
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ expected_hash = "wtrS6NoH2AOH3DnWm7wooK4Bgw8TmMotgMbiY0bu5as"
+ return MockLoader, persistent_cache, expected_hash, np, pd
+
+ @app.cell
+ def one(
+ MockLoader, persistent_cache, expected_hash, np, pd
+ ) -> tuple[int]:
+ _a = {
+ "A": [1, 2, 3],
+ "column names don't contribute to hash": [4, 5, 6],
+ "the dict order does though": [7, 8, 9],
+ }
+ _a = pd.DataFrame(_a) ** 2
+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:
+ _A = np.sum(_a["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, pd
+ ) -> tuple[int]:
+ _a = {"A": [1, 4, 9], "B": [16, 25, 36], "C": [49, 64, 81]}
+ _a = pd.DataFrame(_a)
+
+ with persistent_cache(name="two", _loader=MockLoader()) as _cache:
+ _A = np.sum(_a["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 == 14
+
+ app.run()
+
+ @staticmethod
+ @pytest.mark.skipif(
+ not DependencyManager.has("pandas"),
+ 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_process_dataframe_object() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import numpy as np
+ import pandas as pd
+
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ expected_hash = "n4KGJ3wrRHd6pDCyekTWZXShmtT_ZkDY4Wo3C6BXzh4"
+ return MockLoader, persistent_cache, expected_hash, np, pd
+
+ @app.cell
+ def one(
+ MockLoader, persistent_cache, expected_hash, np, pd
+ ) -> tuple[int]:
+ _a = {
+ "A": [2, 8, 18],
+ "B": ["a", "a", "a"],
+ "C": [14, 16, 18],
+ }
+ _a = pd.DataFrame(_a)
+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:
+ _A = np.sum(_a["A"])
+ one = _A
+
+ assert _cache._cache.cache_type == "ContextExecutionPath"
+ assert (
+ _cache._cache.hash == expected_hash
+ ), f"expected_hash != {_cache._cache.hash}"
+ return (one,)
+
+ app.run()
+
+ @staticmethod
+ @pytest.mark.skipif(
+ not DependencyManager.has("polars"),
+ 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_process_polars_dataframe() -> 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 = "rC6YiNsuaZKQ1JqMgSRa0iyEDwi7ZTl6InABjuM0RDY"
+ return MockLoader, persistent_cache, expected_hash, pl
+
+ @app.cell
+ def one(MockLoader, persistent_cache, expected_hash, pl) -> tuple[int]:
+ _a = {
+ "A": [1, 2, 3],
+ "column names don't contribute to hash": [4, 5, 6],
+ "the dict order does though": [7, 8, 9],
+ }
+ _a = pl.DataFrame(_a).select(pl.all() ** 2)
+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:
+ _A = _a.select(pl.col("A").sum()).item()
+ 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, pl) -> tuple[int]:
+ _a = {"A": [1, 4, 9], "B": [16, 25, 36], "C": [49, 64, 81]}
+ _a = pl.DataFrame(_a)
+
+ with persistent_cache(name="two", _loader=MockLoader()) as _cache:
+ _A = _a.select(pl.col("A").sum()).item()
+ 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 == 14
+
+ app.run()