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: top-level cache decorator with additional deps (#5862)

Dylan Madisetti557c5c481caa
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 67b1a8135a..b18ad3778e 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -17,7 +17,7 @@ from marimo._ast.variables import (
if_local_then_mangle,
unmangle_local,
)
-from marimo._ast.visitor import Name, ScopedVisitor
+from marimo._ast.visitor import ImportData, Name, ScopedVisitor
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import ContextNotInitializedError, get_context
@@ -739,7 +739,7 @@ class BlockHasher:
refs = set(refs)
# Content addressed hash is valid if every reference is accounted for
# and can be shown to be a primitive value.
- imports = self.graph.get_imports()
+ imports = get_imports(scope)
for local_ref in sorted(refs):
ref = if_local_then_mangle(local_ref, self.cell_id)
if ref in imports:
@@ -747,9 +747,13 @@ class BlockHasher:
# e.g. module watcher could mutate the version number based
# last updated timestamp.
version = ""
+ module = None
if self.pin_modules:
- module = sys.modules[imports[ref].namespace]
+ module = sys.modules[imports[ref].module]
version = getattr(module, "__version__", "")
+ if not version:
+ module = sys.modules[imports[ref].namespace]
+ version = getattr(module, "__version__", "")
content_serialization[ref] = type_sign(
bytes(f"module:{ref}:{version}", "utf-8"), "module"
@@ -1018,6 +1022,28 @@ class BlockHasher:
)
+def get_imports(scope: dict[str, Any]) -> dict[Name, ImportData]:
+ """Get the imports from the scope.
+
+ Args:
+ scope: The scope to get the imports from.
+
+ Returns:
+ A dictionary of imports.
+ """
+ # In cases without context, we must build the imports
+ # implicitly from scope.
+ imports = {
+ name: ImportData(
+ module=obj.__name__,
+ definition=name,
+ )
+ for name, obj in scope.items()
+ if inspect.ismodule(obj)
+ }
+ return imports
+
+
def cache_attempt_from_hash(
module: ast.Module,
graph: DirectedGraph,
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 4660a6ef51..4e03934eaf 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -84,6 +84,7 @@ class _cache_call:
"_bound",
"_last_hash",
"_frame_offset",
+ "_external",
"__wrapped__",
)
@@ -100,6 +101,7 @@ class _cache_call:
_bound: Optional[dict[str, Any]]
_last_hash: Optional[str]
_frame_offset: int
+ _external: bool
# Consistent with functools.cache
__wrapped__: Optional[Callable[..., Any]]
@@ -123,6 +125,7 @@ class _cache_call:
self._var_kwarg = None
self._loader = None
self._bound = {}
+ self._external = False
if _fn is None:
self.__wrapped__ = None
else:
@@ -137,16 +140,19 @@ class _cache_call:
def _set_context(self, fn: Callable[..., Any]) -> None:
assert callable(fn), "the provided function must be callable"
ctx = safe_get_context()
+ # If we are loaded from a module, then we have no context.
if ctx and ctx.execution_context is not None:
cell_id = (
ctx.cell_id or ctx.execution_context.cell_id or CellId_t("")
)
graph = ctx.graph
glbls = ctx.globals
+ self._external = False
else:
cell_id = CellId_t("")
graph = None
glbls = {}
+ self._external = True
self.__wrapped__ = fn
sig = inspect.signature(fn)
@@ -244,7 +250,9 @@ class _cache_call:
def __get__(
self, instance: Any, _owner: Optional[type] = None
) -> _cache_call:
- """__get__ is invoked on instance access;
+ """Enable @cache as a method decorator.
+
+ __get__ is invoked on instance access;
e.g. `obj.fn` (__get__ called on `fn`)
`instance` is the specific object, while owner is `type(instance)`.
@@ -311,9 +319,20 @@ class _cache_call:
glbls: dict[str, Any] = {}
if ctx is not None:
glbls = ctx.globals
+ # Typically, scope is overridden by globals (scope is just a snapshot of
+ # the current frame, which may have changed)- however in an external
+ # context, scope is the only source of glbls (the definition should be
+ # unaware of working memory).
scope = {
**self.scope,
- **glbls,
+ }
+ if not self._external:
+ scope = {
+ **scope,
+ **glbls,
+ }
+ scope = {
+ **scope,
**arg_dict,
**kwargs_copy,
**(self._bound or {}),
diff --git a/tests/_save/decorator_imports/module_0/__init__.py b/tests/_save/decorator_imports/module_0/__init__.py
new file mode 100644
index 0000000000..6c8e6b979c
--- /dev/null
+++ b/tests/_save/decorator_imports/module_0/__init__.py
@@ -0,0 +1 @@
+__version__ = "0.0.0"
diff --git a/tests/_save/decorator_imports/module_1/__init__.py b/tests/_save/decorator_imports/module_1/__init__.py
new file mode 100644
index 0000000000..5becc17c04
--- /dev/null
+++ b/tests/_save/decorator_imports/module_1/__init__.py
@@ -0,0 +1 @@
+__version__ = "1.0.0"
diff --git a/tests/_save/decorator_imports/transitive_imports.py b/tests/_save/decorator_imports/transitive_imports.py
new file mode 100644
index 0000000000..5edfdbc3f5
--- /dev/null
+++ b/tests/_save/decorator_imports/transitive_imports.py
@@ -0,0 +1,38 @@
+import marimo
+
+__generated_with = "0.14.15"
+app = marimo.App(width="medium")
+
+with app.setup:
+ import math
+
+ import marimo as mo
+ import tests._save.decorator_imports.module_1 as my_module
+
+
+def has_import():
+ return len([mo])
+
+
+def doesnt_have_import():
+ return len([mo, math])
+
+
[email protected](pin_modules=True)
+def doesnt_have_namespace_pinned() -> None:
+ return my_module.__version__
+
+
+def doesnt_have_namespace() -> None:
+ return my_module.__version__
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 9c883dea5c..09cd88fdf4 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -1953,19 +1953,19 @@ class TestCacheDecorator:
app._anonymous_file = True
@app.cell
- def __():
+ def _():
import marimo as mo
return (mo,)
@app.cell
- def __():
+ def _():
import weakref
return (weakref,)
@app.cell
- def __(mo, weakref):
+ def _(mo, weakref):
class Namespace: ...
ns = Namespace()
@@ -1982,7 +1982,7 @@ class TestCacheDecorator:
)
@app.cell
- def __(f):
+ def _(f):
f()
return
@@ -2229,6 +2229,29 @@ class TestCacheDecorator:
assert v == 3
return
+ @staticmethod
+ def test_cache_with_mutation_after_def(app) -> None:
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def _(mo):
+ arr = [1, 2, 3]
+
+ @mo.cache
+ def g():
+ return len(arr)
+
+ assert g() == 3
+ arr.append(4) # Mutation after definition
+ assert g() == 4
+ arr = [1, 2] # Mutation after definition
+ assert g() == 2
+ return (g, arr)
+
class TestPersistentCache:
async def test_pickle_context(
diff --git a/tests/_save/test_decorator_imports.py b/tests/_save/test_decorator_imports.py
new file mode 100644
index 0000000000..5cf6135d1a
--- /dev/null
+++ b/tests/_save/test_decorator_imports.py
@@ -0,0 +1,132 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+import textwrap
+
+from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+def test_has_shared_import(app) -> None:
+ with app.setup:
+ import marimo as mo
+ from tests._save.decorator_imports.transitive_imports import has_import
+
+ @app.cell
+ def has_dep_works() -> tuple[int]:
+ # matches test + use mo for lint
+ assert has_import() == len([mo])
+
+
+def test_doesnt_have_shared_import(app) -> None:
+ with app.setup:
+ from tests._save.decorator_imports.transitive_imports import (
+ doesnt_have_import,
+ )
+
+ @app.cell
+ def doesnt_have_dep_works() -> tuple[int]:
+ # Counts modules on call.
+ assert doesnt_have_import() == 2
+
+
+def test_has_dep_with_differing_name_works(app) -> None:
+ for module in list(sys.modules.keys()):
+ if module.startswith("tests._save.decorator_imports"):
+ del sys.modules[module]
+
+ with app.setup:
+ import marimo as mo
+ import tests._save.decorator_imports.module_0 as my_module
+ from tests._save.decorator_imports.transitive_imports import (
+ doesnt_have_namespace as other,
+ doesnt_have_namespace_pinned as other_pinned,
+ )
+
+ @app.function
+ @mo.cache(pin_modules=True)
+ def doesnt_have_namespace_pinned() -> None:
+ return my_module.__version__
+
+ @app.function
+ @mo.cache
+ def doesnt_have_namespace() -> None:
+ return my_module.__version__
+
+ @app.cell
+ def has_dep_with_differing_name_works() -> tuple[int]:
+ assert other() != my_module.__version__
+ other_hash = other._last_hash
+ assert doesnt_have_namespace() == my_module.__version__
+ # By virtue of backwards compatibility, this is true.
+ # TODO: Negate and fix.
+ assert other_hash == doesnt_have_namespace._last_hash
+
+ @app.cell
+ def has_dep_with_differing_name_works_pinned() -> tuple[int]:
+ assert other_pinned() != my_module.__version__
+ other_hash_pinned = other_pinned._last_hash
+ assert doesnt_have_namespace_pinned() == my_module.__version__
+ assert other_hash_pinned != doesnt_have_namespace_pinned._last_hash
+
+
+async def test_decorator_in_kernel(
+ lazy_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = lazy_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="setup",
+ code=textwrap.dedent(
+ """
+ import marimo as mo
+ import tests._save.decorator_imports.module_0 as my_module
+ from tests._save.decorator_imports.transitive_imports import (
+ doesnt_have_namespace as other,
+ doesnt_have_namespace_pinned as other_pinned,
+ )
+ from tests._save.decorator_imports.transitive_imports import (
+ doesnt_have_import,
+ )
+ from tests._save.decorator_imports.transitive_imports import has_import
+ """
+ ),
+ ),
+ exec_req.get(
+ """
+ @mo.cache(pin_modules=True)
+ def doesnt_have_namespace_pinned() -> None:
+ return my_module.__version__
+ """
+ ),
+ exec_req.get(
+ """
+ @mo.cache
+ def doesnt_have_namespace() -> None:
+ return my_module.__version__
+ """
+ ),
+ exec_req.get(
+ """
+ assert has_import() == 1
+ assert doesnt_have_import() == 2
+ assert other() != my_module.__version__
+ other_hash = other._last_hash
+ assert doesnt_have_namespace() == my_module.__version__
+ # By virtue of backwards compatibility, this is true.
+ # TODO: Negate and fix.
+ assert other_hash == doesnt_have_namespace._last_hash
+
+ assert other_pinned() != my_module.__version__
+ other_hash_pinned = other_pinned._last_hash
+ assert doesnt_have_namespace_pinned() == my_module.__version__
+ assert other_hash_pinned != doesnt_have_namespace_pinned._last_hash
+ resolved = True
+ """
+ ),
+ ]
+ )
+ assert k.globals.get("resolved", False), k.stderr