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.

fix: External decorators in the case of wrapped functions now work #5873 (#5876)

Dylan Madisetti4aa335408c9c
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
index a35de1a5f5..78c50191ec 100644
--- a/marimo/_runtime/primitives.py
+++ b/marimo/_runtime/primitives.py
@@ -197,6 +197,14 @@ def is_pure_function(
if not inspect.isfunction(value):
return False
+ # If this object wraps another, call the check on the wrapped object.
+ if hasattr(value, "__wrapped__"):
+ wrapped = getattr(value, "__wrapped__", None)
+ if wrapped is not None:
+ # This still catches impure decorated functions since the impure
+ # reference will be captured by required refs.
+ return is_pure_function(ref, wrapped, defs, cache, graph)
+
# We assume all external module function references to be pure. Cache can
# still be be invalidated by pin_modules attribute. Note this also captures
# cases like functors from an external module.
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index b18ad3778e..dab588243b 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -23,7 +23,9 @@ from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.dataflow import induced_subgraph
from marimo._runtime.primitives import (
+ CLONE_PRIMITIVES,
FN_CACHE_TYPE,
+ build_ref_predicate_for_primitives,
is_data_primitive,
is_data_primitive_container,
is_primitive,
@@ -90,6 +92,24 @@ def hash_module(
return hash_alg.digest()
+def hash_wrapped_functions(
+ wrapped: Callable[..., Any], hash_type: str = DEFAULT_HASH
+) -> bytes:
+ seen = set()
+
+ # there is a chance for a circular reference
+ # likely manually created, but easy to guard against.
+ def process_function(fn: Callable[..., Any]) -> bytes:
+ fn_hash = hash_module(fn.__code__, hash_type)
+ if fn_hash not in seen and hasattr(fn, "__wrapped__"):
+ child_hash = hash_wrapped_functions(fn.__wrapped__, hash_type)
+ return child_hash + fn_hash
+ seen.add(fn_hash)
+ return fn_hash
+
+ return process_function(wrapped)
+
+
def hash_raw_module(
module: ast.Module, hash_type: str = DEFAULT_HASH
) -> bytes:
@@ -564,6 +584,27 @@ class BlockHasher:
exceptions = []
# By rights, could just fail here - but this final attempt should
# provide better user experience.
+ #
+ # Get a transitive closure over the object, and attempt to pickle
+ # each dependent object.
+ #
+ # TODO: Maybe just try dill?
+ closure = self.graph.get_transitive_references(
+ unhashable,
+ predicate=build_ref_predicate_for_primitives(
+ scope, CLONE_PRIMITIVES
+ ),
+ )
+ closure -= set(content_serialization.keys()) | self.execution_refs
+ unhashable_closure, relevant_serialization, _ = (
+ self.serialize_and_dequeue_content_refs(
+ closure - unhashable, scope
+ )
+ )
+ unhashable |= unhashable_closure
+ content_serialization.update(relevant_serialization)
+ refs |= unhashable_closure
+
for ref in unhashable:
try:
_hashed = pickle.dumps(scope[ref])
@@ -778,7 +819,9 @@ class BlockHasher:
elif is_pure_function(
local_ref, value, scope, self.fn_cache, self.graph
):
- serial_value = hash_module(value.__code__, self.hash_alg.name)
+ serial_value = hash_wrapped_functions(
+ value, self.hash_alg.name
+ )
# An external module variable is assumed to be pure, with module
# pinning being the mechanism for invalidation.
elif getattr(value, "__module__", "__main__") == "__main__":
diff --git a/tests/_runtime/test_primitives.py b/tests/_runtime/test_primitives.py
new file mode 100644
index 0000000000..272387e38f
--- /dev/null
+++ b/tests/_runtime/test_primitives.py
@@ -0,0 +1,132 @@
+"""Tests for marimo._runtime.primitives module."""
+
+import functools
+from typing import Any
+
+from marimo._runtime.primitives import is_pure_function
+
+
+class TestWrappedFunctionHandling:
+ """Test handling of wrapped functions (decorators) in is_pure_function."""
+
+ def test_wrapped_function_follows_wrapped_object(self):
+ """Test that is_pure_function follows __wrapped__ attribute to check the underlying function."""
+
+ def external_function():
+ """A function from external module."""
+ return 42
+
+ external_function.__module__ = "external_module"
+
+ # Create a decorator that wraps the function
+ def decorator(func):
+ @functools.wraps(func)
+ def wrapper():
+ return func()
+
+ return wrapper
+
+ decorated_function = decorator(external_function)
+
+ # Mock globals dict
+ defs = {"decorated_function": decorated_function}
+ cache = {}
+
+ # Should follow the wrapped function and determine purity based on that
+ result = is_pure_function(
+ "decorated_function", decorated_function, defs, cache
+ )
+
+ # Should be True since the wrapped function is external
+ assert result is True
+
+ def test_nested_wrapped_functions(self):
+ """Test handling of functions with multiple layers of wrapping."""
+
+ def original_function():
+ return "original"
+
+ original_function.__module__ = "external_module"
+
+ def decorator1(func: Any) -> Any:
+ @functools.wraps(func)
+ def wrapper1(*args: Any, **kwargs: Any):
+ return func(*args, **kwargs)
+
+ return wrapper1
+
+ def decorator2(func: Any) -> Any:
+ @functools.wraps(func)
+ def wrapper2(*args: Any, **kwargs: Any):
+ return func(*args, **kwargs)
+
+ return wrapper2
+
+ # Apply multiple decorators
+ @decorator2
+ @decorator1
+ def nested_decorated():
+ return original_function()
+
+ defs = {"nested_decorated": nested_decorated}
+ cache = {}
+
+ # Should handle nested wrapping correctly
+ result = is_pure_function(
+ "nested_decorated", nested_decorated, defs, cache
+ )
+ assert isinstance(result, bool)
+
+ def test_wrapped_attribute_is_none(self):
+ """Test handling when __wrapped__ exists but is None."""
+
+ def function_with_none_wrapped():
+ return 42
+
+ function_with_none_wrapped.__module__ = "external_module"
+
+ # Set __wrapped__ to None
+ function_with_none_wrapped.__wrapped__ = None
+
+ defs = {"function_with_none_wrapped": function_with_none_wrapped}
+ cache = {}
+
+ # Should handle None __wrapped__ gracefully
+ result = is_pure_function(
+ "function_with_none_wrapped",
+ function_with_none_wrapped,
+ defs,
+ cache,
+ )
+ assert result is True # External function should be pure
+
+ def test_main_module_wrapped_function(self):
+ """Test wrapped function from __main__ module."""
+
+ def internal_function():
+ return 42
+
+ internal_function.__module__ = "__main__"
+
+ def decorator(func):
+ @functools.wraps(func)
+ def wrapper():
+ return func()
+
+ return wrapper
+
+ decorated_function = decorator(internal_function)
+
+ defs = {
+ "decorated_function": decorated_function,
+ "internal_function": internal_function,
+ }
+ cache = {}
+
+ # Should follow wrapped function and check if it's pure
+ result = is_pure_function(
+ "decorated_function", decorated_function, defs, cache
+ )
+
+ # Should be True since the wrapped function is also pure (no external refs)
+ assert result is True
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index d47b0da5ec..305df2ad10 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -1478,3 +1478,466 @@ class TestSideEffects:
assert hashes[1] != hashes[3]
assert hashes[0] != hashes[2]
assert non_primitive[1] == 2 == v
+
+
+class TestWrappedFunctionCache:
+ """Test cache behavior with wrapped functions (decorators) across kernel calls."""
+
+ @staticmethod
+ async def test_decorator_hash_same_name_different_kernels(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test that decorators with same function names in different kernel calls have different hashes."""
+
+ # First kernel execution
+ cell_id = "test_cell"
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ def my_decorator(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ wrapper._call_count = getattr(wrapper, '_call_count', 0) + 1
+ return func(*args, **kwargs)
+ wrapper._kernel_version = 1
+ return wrapper
+
+ @my_decorator
+ def my_function():
+ return "kernel_1"
+
+ @mo.cache
+ def cached_decorated_function():
+ return my_function()
+
+ result1 = cached_decorated_function()
+ hash1 = cached_decorated_function._last_hash
+ cache_type1 = cached_decorated_function.base_block.cache_type
+ """,
+ )
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["result1"] == "kernel_1"
+ first_hash = k.globals["hash1"]
+ first_function = k.globals["my_function"]
+ first_cache_type = k.globals["cache_type1"]
+
+ # Second kernel execution - update the same cell with different definitions
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ def my_decorator(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ wrapper._call_count = getattr(wrapper, '_call_count', 0) + 1
+ return func(*args, **kwargs)
+ wrapper._kernel_version = 2 # Different version
+ return wrapper
+
+ @my_decorator
+ def my_function():
+ return "kernel_2" # Different return value
+
+ @mo.cache
+ def cached_decorated_function():
+ return my_function()
+
+ result2 = cached_decorated_function()
+ hash2 = cached_decorated_function._last_hash
+ cache_type2 = cached_decorated_function.base_block.cache_type
+ """,
+ )
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["result2"] == "kernel_2"
+ second_hash = k.globals["hash2"]
+ second_function = k.globals["my_function"]
+ second_cache_type = k.globals["cache_type2"]
+
+ # Functions should be different objects despite same name
+ assert first_function is not second_function
+ assert (
+ first_function._kernel_version != second_function._kernel_version
+ )
+
+ # Should use ContentAddressed cache type since decorator is pure
+ assert first_cache_type == "ContentAddressed", (
+ f"Expected ContentAddressed, got {first_cache_type}"
+ )
+ assert second_cache_type == "ContentAddressed", (
+ f"Expected ContentAddressed, got {second_cache_type}"
+ )
+
+ # Cache hashes should be different
+ assert first_hash != second_hash, (
+ f"Expected different hashes, got {first_hash} == {second_hash}"
+ )
+
+ @staticmethod
+ async def test_impure_decorator_with_pure_function(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test impure decorator applied to pure function - decorator should dominate purity."""
+
+ # First execution with impure decorator
+ cell_id = "test_cell"
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ # This will be an impure decorator (contains non-primitive objects)
+ impure_state = [object()] # Non-primitive, makes decorator impure
+
+ def my_impure_decorator(func):
+ '''An impure decorator that depends on impure_state'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ # Decorator depends on impure_state
+ wrapper._call_count = len(impure_state)
+ return func(*args, **kwargs)
+ return wrapper
+
+ @my_impure_decorator
+ def pure_function():
+ # This function itself is pure (no external dependencies)
+ return 42
+
+ @mo.cache
+ def cached_function():
+ return pure_function()
+ """,
+ ),
+ exec_req.get_with_id(
+ "call_cell",
+ """
+
+ result1 = cached_function()
+ hash1 = cached_function._last_hash
+ cache_type1 = cached_function.base_block.cache_type
+ """,
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["result1"] == 42
+ first_hash = k.globals["hash1"]
+ first_cache_type = k.globals["cache_type1"]
+
+ # Second execution - change the impure decorator state
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ # Different impure state (different length)
+ impure_state = [object(), object()] # Different length affects decorator
+
+ def my_impure_decorator(func):
+ '''Same impure decorator with different state'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ # Decorator depends on impure_state (now different)
+ wrapper._call_count = len(impure_state)
+ return func(*args, **kwargs)
+ return wrapper
+
+ @my_impure_decorator
+ def pure_function():
+ # Same pure function
+ return 42
+
+ @mo.cache
+ def cached_function():
+ return pure_function()
+ """,
+ ),
+ exec_req.get_with_id(
+ "call_cell",
+ """
+
+ result2 = cached_function()
+ hash2 = cached_function._last_hash
+ cache_type2 = cached_function.base_block.cache_type
+ """,
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert (
+ k.globals["result2"] == 42
+ ) # Same result since pure_function unchanged
+ second_hash = k.globals["hash2"]
+ second_cache_type = k.globals["cache_type2"]
+
+ # The decorated function should be treated as impure due to impure decorator
+ # This should use ContentAddressed hashing but with different hashes due to closure analysis
+ assert first_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {first_cache_type}"
+ )
+ assert second_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {second_cache_type}"
+ )
+
+ # Hashes should be different because the decorator's dependencies changed
+ # (even though the underlying pure function is the same)
+ assert first_hash != second_hash, (
+ f"Expected different hashes for different decorator dependencies, "
+ f"got {first_hash} == {second_hash}"
+ )
+
+ @staticmethod
+ async def test_decorator_pure_with_impure_dependencies_different_cells(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test impure dependencies in different cells (should be execution refs)."""
+
+ # First execution - setup dependencies in separate cells
+ await k.run(
+ [
+ exec_req.get_with_id(
+ "dep_cell",
+ """
+ import functools
+
+ # This will be an impure dependency (contains non-primitive objects)
+ impure_dependency = [object()] # Non-primitive, makes it impure
+
+ def my_pure_decorator(func):
+ '''A pure decorator from external module perspective'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+ """,
+ ),
+ exec_req.get_with_id(
+ "func_cell",
+ """
+ @my_pure_decorator
+ def decorated_function():
+ # This function depends on impure_dependency from another cell
+ return len(impure_dependency)
+ """,
+ ),
+ exec_req.get_with_id(
+ "cache_cell",
+ """
+ import marimo as mo
+
+ @mo.cache
+ def cached_function():
+ return decorated_function()
+
+ result1 = cached_function()
+ hash1 = cached_function._last_hash
+ cache_type1 = cached_function.base_block.cache_type
+ """,
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert k.globals["result1"] == 1
+ first_hash = k.globals["hash1"]
+ first_cache_type = k.globals["cache_type1"]
+
+ # Second execution - change the impure dependency in separate cell
+ await k.run(
+ [
+ exec_req.get_with_id(
+ "dep_cell",
+ """
+ import functools
+
+ # Different impure dependency (different object, different length)
+ impure_dependency = [object(), object()] # Different length
+
+ def my_pure_decorator(func):
+ '''Same pure decorator'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+ """,
+ ),
+ exec_req.get_with_id(
+ "func_cell",
+ """
+ @my_pure_decorator
+ def decorated_function():
+ # Same function, but now depends on different impure_dependency
+ return len(impure_dependency)
+ """,
+ ),
+ exec_req.get_with_id(
+ "cache_cell",
+ """
+ import marimo as mo
+
+ @mo.cache
+ def cached_function():
+ return decorated_function()
+
+ result2 = cached_function()
+ hash2 = cached_function._last_hash
+ cache_type2 = cached_function.base_block.cache_type
+ """,
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert (
+ k.globals["result2"] == 2
+ ) # Different result due to different dependency
+ second_hash = k.globals["hash2"]
+ second_cache_type = k.globals["cache_type2"]
+
+ # Should use ExecutionPath hashing since dependencies are in different cells
+ assert first_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {first_cache_type}"
+ )
+ assert second_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {second_cache_type}"
+ )
+
+ # Hashes should be different because the execution path changed
+ # (due to different cells being hashed)
+ assert first_hash != second_hash, (
+ f"Expected different hashes for different cell dependencies, "
+ f"got {first_hash} == {second_hash}"
+ )
+
+ @staticmethod
+ async def test_decorator_pure_with_impure_dependencies(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test the impure edge case: decorator is pure but dependent functions are not."""
+
+ # First execution with impure dependency
+ cell_id = "test_cell"
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ # This will be an impure dependency (contains non-primitive objects)
+ impure_dependency = [object()] # Non-primitive, makes it impure
+
+ def my_pure_decorator(func):
+ '''A pure decorator from external module perspective'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+
+ @my_pure_decorator
+ def decorated_function():
+ # This function depends on impure_dependency
+ return len(impure_dependency)
+
+ @mo.cache
+ def cached_function():
+ return decorated_function()
+
+ result1 = cached_function()
+ hash1 = cached_function._last_hash
+ cache_type1 = cached_function.base_block.cache_type
+ """,
+ )
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert not k.stdout.messages, k.stdout
+
+ assert k.globals["result1"] == 1
+ first_hash = k.globals["hash1"]
+ first_cache_type = k.globals["cache_type1"]
+
+ # Second execution - change the impure dependency
+ await k.run(
+ [
+ exec_req.get_with_id(
+ cell_id,
+ """
+ import functools
+ import marimo as mo
+
+ # Different impure dependency (different object, different length)
+ impure_dependency = [object(), object()] # Different length
+
+ def my_pure_decorator(func):
+ '''Same pure decorator'''
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+
+ @my_pure_decorator
+ def decorated_function():
+ # Same function, but now depends on different impure_dependency
+ return len(impure_dependency)
+
+ @mo.cache
+ def cached_function():
+ return decorated_function()
+
+ result2 = cached_function()
+ hash2 = cached_function._last_hash
+ cache_type2 = cached_function.base_block.cache_type
+ """,
+ )
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert not k.stdout.messages, k.stdout
+
+ assert (
+ k.globals["result2"] == 2
+ ) # Different result due to different dependency
+ second_hash = k.globals["hash2"]
+ second_cache_type = k.globals["cache_type2"]
+
+ # The decorator itself is pure, but the function has impure dependencies
+ # This should use ExecutionPath hashing, not ContentAddressed
+ assert first_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {first_cache_type}"
+ )
+ assert second_cache_type == "ExecutionPath", (
+ f"Expected ExecutionPath, got {second_cache_type}"
+ )
+
+ # Hashes should be different because the execution path changed
+ # (due to different impure_dependency)
+ assert first_hash != second_hash, (
+ f"Expected different hashes for different impure dependencies, "
+ f"got {first_hash} == {second_hash}"
+ )