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: enable cache at top level (#5678)
Dylan Madisetti7e923c75b14f
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 02f875a99d..645e401c52 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -298,13 +298,13 @@ def get_source_position(# Fallback won't capture embedded scriptsif inspect.isclass(f):is_script = f.__module__ == "__main__"- # Larger catch all than if inspect.isfunction(f):- elif hasattr(f, "__globals__"):- is_script = f.__globals__["__name__"] == "__main__" # type: ignore# Could be something wrapped in a decorator, like# functools._lru_cache_wrapper.elif hasattr(f, "__wrapped__"):return get_source_position(f.__wrapped__, lineno, col_offset)+ # Larger catch all than if inspect.isfunction(f):+ elif hasattr(f, "__globals__") and hasattr(f, "__name__"):+ is_script = f.__globals__["__name__"] == "__main__" # type: ignoreelse:return None# TODO: spec is None for markdown notebooks, which is fine for nowdiff --git a/marimo/_runtime/context/__init__.py b/marimo/_runtime/context/__init__.pyindex 9f66370677..ffbda592dc 100644--- a/marimo/_runtime/context/__init__.py+++ b/marimo/_runtime/context/__init__.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.__all__ = ["get_context",+ "safe_get_context","get_global_context","ContextNotInitializedError","ExecutionContext",@@ -15,5 +16,6 @@ from marimo._runtime.context.types import (get_context,get_global_context,runtime_context_installed,+ safe_get_context,teardown_context,)diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex 90296001e5..967c35fdfa 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -234,6 +234,11 @@ def get_context() -> RuntimeContext:return _THREAD_LOCAL_CONTEXT.runtime_context+def safe_get_context() -> Optional[RuntimeContext]:+ """Return the runtime context if it exists, otherwise None."""+ return _THREAD_LOCAL_CONTEXT.runtime_context++def runtime_context_installed() -> bool:try:get_context()diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 0102e71f97..67b1a8135a 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -667,7 +667,7 @@ class BlockHasher:# State relevant to the context, should be dependent on it's value-# not the object.- value: Optional[State[Any]]+ value: Optional[State[Any]] = None# Prefer actual object over reference.# Skip if the reference has already been subbed in, or if it is# a shadowed reference.@@ -692,6 +692,7 @@ class BlockHasher:scope[state_name] = scope[ref]# Likewise, UI objects should be dependent on their value.+ ui: Optional[UIElement[Any, Any]] = Noneif ref in scope and isinstance(scope[ref], UIElement):ui = scope[ref]elif ctx:diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 19d152f82a..6dfdd88c5a 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -29,7 +29,8 @@ from marimo._ast.transformers import ()from marimo._ast.variables import is_mangled_local, unmangle_localfrom marimo._messaging.tracebacks import write_traceback-from marimo._runtime.context import get_context+from marimo._runtime.context import get_context, safe_get_context+from marimo._runtime.dataflow import DirectedGraphfrom marimo._runtime.side_effect import SideEffectfrom marimo._runtime.state import Statefrom marimo._save.cache import Cache, CacheException@@ -135,12 +136,17 @@ class _cache_call:def _set_context(self, fn: Callable[..., Any]) -> None:assert callable(fn), "the provided function must be callable"- ctx = get_context()- assert ctx.execution_context is not None, (- "Could not resolve context for cache. "- "Either @cache is not called from a top level cell or "- f"{UNEXPECTED_FAILURE_BOILERPLATE}"- )+ ctx = safe_get_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+ else:+ cell_id = CellId_t("")+ graph = None+ glbls = {}self.__wrapped__ = fnsig = inspect.signature(fn)@@ -180,34 +186,30 @@ class _cache_call:# Note, that deeply nested frames may cause issues, however# checking a single frame- should be good enough.f_locals = inspect.stack()[2 + self._frame_offset][0].f_locals- self.scope = {**ctx.globals, **f_locals}+ self.scope = {**glbls, **f_locals}# Scoped refs are references particular to this block, that may not be# defined out of the context of the block, or the cell.# For instance, the args of the invoked function are restricted to the# block.- cell_id = ctx.cell_id or ctx.execution_context.cell_id or CellId_t("")self.scoped_refs = set([f"{ARG_PREFIX}{k}" for k in self._args])# As are the "locals" not in globals- self.scoped_refs |= set(f_locals.keys()) - set(ctx.globals.keys())+ self.scoped_refs |= set(f_locals.keys()) - set(glbls.keys())# Defined in the cell, and currently available in scope- self.scoped_refs |= ctx.graph.cells[cell_id].defs & set(- ctx.globals.keys()- )+ if graph is not None:+ self.scoped_refs |= graph.cells[cell_id].defs & set(glbls.keys())# The defined private variables of this cell, normalizedself.scoped_refs |= set(unmangle_local(x).name- for x in ctx.globals.keys()+ for x in glbls.keys()if is_mangled_local(x, cell_id))- graph = ctx.graph- cell_id = ctx.cell_id or ctx.execution_context.cell_idmodule = strip_function(self.__wrapped__)self.base_block = BlockHasher(module=module,- graph=graph,+ graph=graph or DirectedGraph(),cell_id=cell_id,scope=self.scope,pin_modules=self.pin_modules,@@ -217,11 +219,11 @@ class _cache_call:)# Load global cache from state- name = self.__wrapped__.__name__+ name = self.__name__# Note, that if the function name shadows a global variable, the# lifetime of the cache will be tied to the global variable.# We can invalidate that by making an invalid namespace.- if ctx.globals != f_locals:+ if glbls != f_locals:name = f"{name}*"self._loader = self._loader_partial.create_or_reconfigure(name)@@ -231,6 +233,14 @@ class _cache_call:assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATEreturn self._loader()+ @property+ def __name__(self) -> str:+ """Return the name of the wrapped function."""+ # NB. __name__ is expected on introspection in compiler.+ if self.__wrapped__ is None:+ return "<cache>"+ return self.__wrapped__.__name__+def __get__(self, instance: Any, _owner: Optional[type] = None) -> _cache_call:@@ -297,10 +307,13 @@ class _cache_call:arg_dict[f"{ARG_PREFIX}{self._var_kwarg}"] = kwargs.copy()# Capture the call case- ctx = get_context()+ ctx = safe_get_context()+ glbls: dict[str, Any] = {}+ if ctx is not None:+ glbls = ctx.globalsscope = {**self.scope,- **ctx.globals,+ **glbls,**arg_dict,**kwargs_copy,**(self._bound or {}),@@ -333,7 +346,7 @@ class _cache_call:raise efinally:# NB. Exceptions raise their own side effects.- if not failed:+ if ctx and not failed:ctx.cell_lifecycle_registry.add(SideEffect(attempt.hash))return responsediff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.pyindex e1a7639b63..1ab7b113e6 100644--- a/tests/_ast/test_cell.py+++ b/tests/_ast/test_cell.py@@ -397,6 +397,66 @@ class TestDecoratedCells:"add"}+ @staticmethod+ def test_cache_wrapped(app) -> None:+ with app.setup:+ from marimo import cache++ @app.function+ @cache+ def add(a: int, b: int) -> int:+ return a + b++ @app.cell+ def _() -> None:+ # Calling with the same app yields the same runner+ assert add(1, 2) == 3+ assert add.hits == 0++ # Calling with the same app yields the same runner+ assert add(1, 2) == 3+ assert add.hits == 0+ assert add(1, 2) == 3+ assert add.hits == 1+ assert app._cell_manager.get_cell_data_by_name("add").cell.defs == {+ "add"+ }++ @staticmethod+ def test_persistent_cache_wrapped(app) -> None:+ with app.setup:+ import shutil++ # Create a temporary cache directory+ import tempfile++ from marimo import persistent_cache as cache++ cache_dir = tempfile.mkdtemp()++ @app.function+ @cache(save_path=cache_dir)+ def add(a: int, b: int) -> int:+ return a + b++ @app.cell+ def _() -> None:+ # Calling with the same app yields the same runner+ assert add(1, 2) == 3+ # Because the cache is persistent+ assert add.hits == 1+ # Clean up the cache directory after the test+ shutil.rmtree(cache_dir)++ # Calling with the same app yields the same runner+ assert add(1, 2) == 3+ assert add.hits == 0+ assert add(1, 2) == 3+ assert add.hits == 1+ assert app._cell_manager.get_cell_data_by_name("add").cell.defs == {+ "add"+ }+def help_smoke() -> None:app = App()