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: recursive cell hashing (#5056)
Dylan Madisetti4ebabb69fc7f
diff --git a/marimo/_runtime/cell_lifecycle_registry.py b/marimo/_runtime/cell_lifecycle_registry.pyindex 5086fe84ee..5593a05f56 100644--- a/marimo/_runtime/cell_lifecycle_registry.py+++ b/marimo/_runtime/cell_lifecycle_registry.py@@ -13,6 +13,15 @@ class CellLifecycleRegistry:default_factory=dict)+ def inject(self, cell_id: CellId_t, item: CellLifecycleItem) -> None:+ """Add a provisioned lifecycle item for a specific cell.++ Prefer using `add` to add lifecycle items.+ """+ if cell_id not in self.registry:+ self.registry[cell_id] = set()+ self.registry[cell_id].add(item)+def add(self, item: CellLifecycleItem) -> None:"""Add a lifecycle item for the currently running cell.@@ -27,10 +36,8 @@ class CellLifecycleRegistry:if cell_id is None:return- if cell_id not in self.registry:- self.registry[cell_id] = set()item.create(ctx)- self.registry[cell_id].add(item)+ return self.inject(cell_id, item)def dispose(self, cell_id: CellId_t, deletion: bool) -> None:"""Dispose lifecycle items associated with `cell_id`diff --git a/marimo/_runtime/side_effect.py b/marimo/_runtime/side_effect.pyindex f5f32d398f..94d36a6f8b 100644--- a/marimo/_runtime/side_effect.py+++ b/marimo/_runtime/side_effect.py@@ -37,3 +37,36 @@ class SideEffect(CellLifecycleItem):# Side effects can always be disposed since they are just a cell level# marker that some event has occurred.return True+++class CellHash(CellLifecycleItem):+ """Execution as a side effect to prevent the recomputation of a cell for+ recursive or repeated calls.+ """++ def __init__(self, key: str | bytes) -> None:+ self._key = key++ @property+ def key(self) -> bytes:+ assert self._key is not None+ if isinstance(self._key, bytes):+ return self._key+ return self._key.encode("utf-8")++ @property+ def hash(self) -> bytes:+ """Hash the lookup to a consistent size."""+ return hashlib.sha256(self.key).digest()++ def create(self, context: RuntimeContext | None) -> None:+ """NoOp for side effect.+ Typically hook to expose the object to the context, but the existence of+ the object is enough for side effect tracking.+ """++ def dispose(self, context: RuntimeContext, deletion: bool) -> bool: # noqa: ARG002+ """Clean up and mark the object for deletion"""+ # Side effects can always be disposed since they are just a cell level+ # marker that some event has occurred.+ return Truediff --git a/marimo/_save/cache.py b/marimo/_save/cache.pyindex f7219adcb0..72755f5904 100644--- a/marimo/_save/cache.py+++ b/marimo/_save/cache.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import importlib+import inspectimport refrom collections import namedtuplefrom dataclasses import dataclass@@ -15,7 +17,7 @@ if TYPE_CHECKING:from marimo._save.hash import HashKey# NB. Increment on cache breaking changes.-MARIMO_CACHE_VERSION: int = 2+MARIMO_CACHE_VERSION: int = 3CacheType = Literal["ContextExecutionPath",@@ -39,6 +41,22 @@ ValidCacheSha = namedtuple("ValidCacheSha", ("sha", "cache_type"))MetaKey = Literal["return", "version"]+class ModuleStub:+ def __init__(self, module: Any) -> None:+ self.name = module.__name__++ def load(self) -> Any:+ return importlib.import_module(self.name)+++class FunctionStub:+ def __init__(self, function: Any) -> None:+ self.code = function.__code__++ def load(self, glbls: dict[str, Any]) -> Any:+ return eval(self.code, glbls)++# BaseException because "raise _ as e" is utilized.class CacheException(BaseException):pass@@ -83,6 +101,13 @@ 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],@@ -90,14 +115,20 @@ class Cache:) -> None:"""Loads values from scope, updating the cache."""for var, lookup in self.contextual_defs():+ if lookup not in scope:+ raise CacheException(+ "Failure while saving cached values. "+ "Cache expected a reference to a "+ f"variable that is not present ({lookup})."+ )self.defs[var] = scope[lookup]self.meta = {}if meta is not None:- for key, value in meta.items():- if key not in get_args(MetaKey):- raise CacheException(f"Unexpected meta key: {key}")- self.meta[key] = value+ for metakey, metavalue in meta.items():+ if metakey not in get_args(MetaKey):+ raise CacheException(f"Unexpected meta key: {metakey}")+ self.meta[metakey] = metavalueself.meta["version"] = MARIMO_CACHE_VERSIONdefs = {**globals(), **scope}@@ -120,6 +151,13 @@ class Cache:f"({type(value)}:{ref}).")+ for key, value in self.defs.items():+ # If it's a module we must replace with a stub.+ if inspect.ismodule(value):+ self.defs[key] = ModuleStub(value)+ elif inspect.isfunction(value):+ self.defs[key] = FunctionStub(value)+def contextual_defs(self) -> dict[tuple[Name, Name], Any]:"""Uses context to resolve private variable names."""try:diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex e38dbc3f34..0102e71f97 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -21,6 +21,7 @@ from marimo._ast.visitor import Name, ScopedVisitorfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import ContextNotInitializedError, get_context+from marimo._runtime.dataflow import induced_subgraphfrom marimo._runtime.primitives import (FN_CACHE_TYPE,is_data_primitive,@@ -28,7 +29,7 @@ from marimo._runtime.primitives import (is_primitive,is_pure_function,)-from marimo._runtime.side_effect import SideEffect+from marimo._runtime.side_effect import CellHash, SideEffectfrom marimo._runtime.state import SetFunctor, Statefrom marimo._runtime.watch._path import PathStatefrom marimo._save.cache import Cache, CacheType@@ -427,11 +428,20 @@ class BlockHasher:# execution hashing.if refs:cache_type = "ExecutionPath"+ to_hash = self.cells_from_refs(refs)if ctx:- self.collect_and_hash_side_effects(- self.cells_from_refs(refs), ctx- )- refs = self.hash_and_dequeue_execution_refs(refs)+ self.collect_and_hash_side_effects(to_hash, ctx)+ subgraph, children = induced_subgraph(+ graph, to_hash | {self.cell_id}+ )+ assert not children.get(self.cell_id, None), (+ "No children expected, please report this issue. "+ "You may have a cycle which marimo should have previously "+ "detected."+ )+ refs = self.hash_and_dequeue_execution_refs(+ refs, subgraph[self.cell_id], scope, ctx+ )self.execution_refs -= refs | self.content_refs# Remove values that should be provided by external scope.@@ -488,12 +498,17 @@ class BlockHasher:block.context_refs = set(parent.context_refs)return block+ @property+ def raw_hash(self) -> bytes:+ assert self.hash_alg is not None, "Hash algorithm not initialized."+ return self.hash_alg.digest()+@propertydef hash(self) -> str:if self._hash is None:assert self.hash_alg is not None, "Hash algorithm not initialized."self._hash = (- base64.urlsafe_b64encode(self.hash_alg.digest())+ base64.urlsafe_b64encode(self.raw_hash).decode("utf-8").strip("="))@@ -824,18 +839,12 @@ class BlockHasher:)return SerialRefs(refs, content_serialization, stateful_refs)- def hash_and_dequeue_execution_refs(self, refs: set[Name]) -> set[Name]:- """Determines and uses the hash of refs' cells to update the hash.-- Args:- refs: List of references to account for in cell lookup.-- Returns a list of references that were not utilized in updating the- hash. This should only be possible in the case where a cell context is- provided, as those references should be accounted for in that context.- """+ def hash_and_dequeue_execution_refs_fallback(+ self, refs: set[Name], to_hash: set[CellId_t]+ ) -> set[Name]:+ """Fallback for execution refs, when the context is not available."""self._hash = None- to_hash = self.cells_from_refs(refs)+ refs = set(refs)for ancestor_id in to_hash:cell_impl = self.graph.cells[ancestor_id]for ref in cell_impl.defs:@@ -851,6 +860,70 @@ class BlockHasher:)return refs+ def hash_and_dequeue_execution_refs(+ self,+ refs: set[Name],+ parents: set[CellId_t],+ scope: dict[str, Any],+ ctx: Optional[RuntimeContext] = None,+ ) -> set[Name]:+ """Determines and uses the hash of refs' cells to update the hash.++ Args:+ refs: List of references to account for in cell lookup.+ parents: A set of parent cell ids to hash.+ scope: The definitions of (globals) available in execution context.+ ctx: The runtime context to use for stateful lookups.++ Returns a list of references that were not utilized in updating the+ hash. This should only be possible in the case where a cell context is+ provided, as those references should be accounted for in that context.+ """+ if ctx is None:+ return self.hash_and_dequeue_execution_refs_fallback(refs, parents)++ self._hash = None+ # We want to do a DFS graph traversal, pruning when we either get to a+ # content, or pure hashed cell. For each cell, we either use the known+ # hash, present in CellLifeCycle OR we compute and register it.+ hashes = []+ # Recursive, but in a very round about way.+ # As such, only utilize the top layer.+ for cell_id in parents:+ cell = self.graph.cells[cell_id]++ if cell_id in ctx.cell_lifecycle_registry.registry:+ registry = ctx.cell_lifecycle_registry.registry[cell_id]+ cell_hash = [+ obj.key for obj in registry if isinstance(obj, CellHash)+ ]+ if cell_hash:+ assert len(cell_hash) == 1, (+ "Cell Hash registered multiple times, this is unexpected. "+ "Please report this issue to marimo-team/marimo"+ )+ hashes.append(cell_hash[0])+ refs -= cell.defs+ continue++ attempt = BlockHasher(+ cell.mod,+ self.graph,+ cell.cell_id,+ scope=scope,+ pin_modules=self.pin_modules,+ hash_type=self.hash_alg.name,+ )+ # Register the hash in the lifecycle registry+ ctx.cell_lifecycle_registry.inject(+ cell_id, CellHash(attempt.raw_hash)+ )+ refs -= cell.defs+ hashes.append(attempt.raw_hash)++ self.hash_alg.update(b"".join(sorted(hashes)))+ return refs+def hash_and_verify_context_refs(self, refs: set[Name], context: Optional[ast.Module]) -> None:@@ -896,7 +969,7 @@ class BlockHasher:)assert ref_cells == {self.cell_id}, ("Unexpected execution cell residual "- f"{ref_cells.pop()} expected {self.cell_id}."+ f"{ref_cells.pop()} expected {self.cell_id}. ""This is unexpected, please report this issue to ""https://github.com/marimo-team/marimo/issues")diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex bb87c9cdb2..f17dd48899 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -273,8 +273,7 @@ class _cache_context(SkipContext):# Note the behavior does subtly change in 3.14, but will still be# captured by this check.if self._cache and self._cache.hit:- if with_frame.f_lineno >= self._body_start:- self.skip()+ self.skip()stack = traceback.extract_stack()diff --git a/tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.json b/tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.jsonnew file mode 100644index 0000000000..370284eb6d--- /dev/null+++ b/tests/_save/cache-dumps/json-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.json@@ -0,0 +1,12 @@+{+ "defs": {+ "value": 3+ },+ "hash": "dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE",+ "cache_type": "ExecutionPath",+ "stateful_refs": [],+ "hit": false,+ "meta": {+ "version": 3+ }+}diff --git a/tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.pickle b/tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.picklenew file mode 100644index 0000000000..85d2a42e5eBinary files /dev/null and b/tests/_save/cache-dumps/pickle-dump-v3/E_dLRjBdrj3Fn4Wz71wf1yoNN6kueLAGMX7AOshi6-HDE.pickle differdiff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 8d7ea77feb..7ce8c78002 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -8,6 +8,7 @@ import warningsimport pytest+import marimofrom marimo._ast.app import Appfrom marimo._runtime.requests import ExecutionRequestfrom marimo._runtime.runtime import Kernel@@ -321,6 +322,113 @@ class TestAppCache:assert k.globals["Y"] == 8assert k.globals["Z"] == 3+ async def test_cache_module_hit(self, any_kernel: Kernel) -> None:+ k = any_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ import marimo as mod+ from marimo._save.save import persistent_cache+ from tests._save.loaders.mocks import MockLoader++ def my_func_2():+ return 2++ with persistent_cache(+ name="one", _loader=MockLoader(data={"mo": mod})+ ) as cache:+ import numpy as mo+ """+ ),+ ),+ ]+ )+ assert not k.stderr.messages, k.stderr+ assert not k.stdout.messages, k.stdout+ assert k.globals["mo"].__version__ == marimo.__version__++ async def test_cache_module_miss(self, any_kernel: Kernel) -> None:+ k = any_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ from marimo._save.save import persistent_cache+ from tests._save.loaders.mocks import MockLoader++ with persistent_cache(+ name="one", _loader=MockLoader()+ ) as cache:+ import marimo as mo+ """+ ),+ ),+ ]+ )+ # No warning messages.+ assert k.errors == {}+ assert not k.stderr.messages, k.stderr+ assert not k.stdout.messages, k.stdout+ assert k.globals["mo"].__version__ == marimo.__version__++ async def test_cache_function_hit(self, any_kernel: Kernel) -> None:+ k = any_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ from marimo._save.save import persistent_cache+ from tests._save.loaders.mocks import MockLoader++ def my_func_2():+ return 2++ with persistent_cache(name="one", _loader=MockLoader(data={"my_func": my_func_2})) as cache:+ print("Runs, miss")+ def my_func():+ return 1+ """+ ),+ ),+ ]+ )+ assert not k.stderr.messages, k.stderr+ assert not k.stdout.messages, k.stdout+ assert k.globals["my_func"]() == 2++ async def test_cache_function_miss(self, any_kernel: Kernel) -> None:+ k = any_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ from marimo._save.save import persistent_cache+ from tests._save.loaders.mocks import MockLoader++ with persistent_cache(+ name="one", _loader=MockLoader()+ ) as cache:+ def my_func():+ return 1+ """+ ),+ ),+ ]+ )+ # No warning messages.+ assert not k.stderr.messages, k.stderr+ assert not k.stdout.messages, k.stdout+ assert k.globals["my_func"]() == 1+async def test_cache_one_line(self, any_kernel: Kernel) -> None:k = any_kernelawait k.run(@@ -341,7 +449,6 @@ class TestAppCache:])assert k.errors == {}- assert k.errors == {}assert k.globals["X"] == 1assert k.globals["Y"] == 2diff --git a/tests/_save/test_cache_versions.py b/tests/_save/test_cache_versions.pyindex 55862ba37a..bbd110737f 100644--- a/tests/_save/test_cache_versions.py+++ b/tests/_save/test_cache_versions.py@@ -9,7 +9,7 @@ class TestVersionCache:@pytest.mark.skipif("sys.version_info < (3, 12) or sys.version_info >= (3, 13)")- def test_load_v1_pickle(app) -> None:+ def test_load_v3_pickle(app) -> None:@app.celldef _():unhashable = [object()]@@ -21,7 +21,7 @@ class TestVersionCache:ref = 1with persistent_cache(- name="pickle-dump-v1", save_path="tests/_save/cache-dumps"+ name="pickle-dump-v3", save_path="tests/_save/cache-dumps") as cache:value = 1 + len(unhashable) + refassert cache.hit@@ -31,7 +31,7 @@ class TestVersionCache:@pytest.mark.skipif("sys.version_info < (3, 12) or sys.version_info >= (3, 13)")- def test_load_v1_json(app) -> None:+ def test_load_v3_json(app) -> None:@app.celldef _():unhashable = [object()]@@ -43,7 +43,7 @@ class TestVersionCache:ref = 1with persistent_cache(- name="json-dump-v1",+ name="json-dump-v3",save_path="tests/_save/cache-dumps",method="json",) as cache:diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex da1c9e7acd..272ac3df1e 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -129,7 +129,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"+ == "r2_DqjuluzDmVs1wo1HZCNWz9wApoSSJlnXeYihOaNI"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -150,7 +150,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"+ == "r2_DqjuluzDmVs1wo1HZCNWz9wApoSSJlnXeYihOaNI"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -177,7 +177,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"+ == "r2_DqjuluzDmVs1wo1HZCNWz9wApoSSJlnXeYihOaNI"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -198,7 +198,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"+ == "r2_DqjuluzDmVs1wo1HZCNWz9wApoSSJlnXeYihOaNI"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -238,6 +238,10 @@ class TestHash:with mo.persistent_cache("cache_bug") as cache:output = args.valueassert cache.cache_type == "ExecutionPath"+ from marimo._runtime.context.types import get_context++ ctx = get_context()+ return ctx, output@app1.celldef _(value):@@ -270,6 +274,10 @@ class TestHash:with mo.persistent_cache("cache_bug") as cache:output = args.valueassert cache.cache_type == "ExecutionPath"+ from marimo._runtime.context.types import get_context++ ctx = get_context()+ return ctx, output@app2.celldef _(value):@@ -286,6 +294,8 @@ class TestHash:_, defs1 = app1.run()_, defs2 = app2.run()+ assert len(defs1["ctx"].cell_lifecycle_registry.registry) == 2+ assert len(defs2["ctx"].cell_lifecycle_registry.registry) == 2assert defs1["cache"]._cache.hash != defs2["cache"]._cache.hashassert defs1["output"] != defs2["output"]@@ -378,7 +388,7 @@ class TestHash:@staticmethoddef test_transitive_execution_path_when_state_dependent(app) -> None:@app.cell- def load() -> tuple[Any]:+ def load() -> tuple[Any, ...]:import marimo as mofrom marimo._save.save import persistent_cachefrom tests._save.loaders.mocks import MockLoader@@ -631,7 +641,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.loaders.mocks import MockLoader- expected_hash = "iV5v_cNAxBPqe8tNJnI5volNORTH_gyhKuIvHcG_cds"+ expected_hash = "rTAh8yNbBbq9qkF1nGNUw4DXhZSxRqGe4ptbDh2AwBI"return MockLoader, persistent_cache, expected_hash, torch@app.cell@@ -773,7 +783,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.loaders.mocks import MockLoader- expected_hash = "RbeMLx994_-kB9rF2ebi6mFMbCW_S6-Q41MsrgJgwUA"+ expected_hash = "n4KGJ3wrRHd6pDCyekTWZXShmtT_ZkDY4Wo3C6BXzh4"return MockLoader, persistent_cache, expected_hash, np, pd@app.cell@@ -871,7 +881,7 @@ class TestDataHash:from marimo._save.save import persistent_cachefrom tests._save.loaders.mocks import MockLoader- expected_hash = "QzGgcNS-eEP58qkkFphgAOJNKEpoTNcXhJ-L2exXzr4"+ expected_hash = "jMEurCFLl9VI2sSaQOdCShS1MnudIRZNu84578qM3Jc"return MockLoader, persistent_cache, expected_hash, pl@app.cell@@ -895,7 +905,6 @@ class TestDataHash:# Skip for now, as the local branch is cache busting[email protected](True, reason="Cache busting")class TestDynamicHash:@staticmethodasync def test_transitive_state_hash(@@ -927,7 +936,7 @@ class TestDynamicHash:assert not k.globals["cache"]._cache.hithash_1 = k.globals["cache"]._cache.hash- output_1 = k.globals["output"]+ output_1 = k.globals["output"]._valueawait k.run([exec_req.get("set_value(True)")])assert not k.errors@@ -936,7 +945,7 @@ class TestDynamicHash:assert not k.globals["cache"]._cache.hithash_2 = k.globals["cache"]._cache.hash- output_2 = k.globals["output"]+ output_2 = k.globals["output"]._valueassert hash_1 != hash_2assert output_1 != output_2