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: improved robustness of cache wrapper in module contexts (#5873)
Dylan Madisetti15e2ea9aa146
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.pyindex 8b100ca692..4dea703f31 100644--- a/marimo/_ast/toplevel.py+++ b/marimo/_ast/toplevel.py@@ -17,7 +17,7 @@ from marimo._ast.names import ()from marimo._ast.variables import BUILTINSfrom marimo._ast.visitor import Name, VariableData-from marimo._runtime.dataflow import DirectedGraph+from marimo._runtime.dataflow import DirectedGraph, topological_sortfrom marimo._types.ids import CellId_tif TYPE_CHECKING:@@ -361,7 +361,11 @@ class TopLevelExtraction:for status in self.collection:if status._cell:+ # init_variable_data is a collected on the visitor level+ # if a var is first defined with a type like:+ # x: int = 1variables.update(status._cell.init_variable_data)+ # Top level defs can also be "variables" since exposed.for var, status in self.toplevel.items():if status._cell:toplevel_variable = status._cell.toplevel_variable@@ -373,19 +377,22 @@ class TopLevelExtraction:@classmethoddef from_graph(cls,- cell: CellImpl,graph: DirectedGraph,+ cell: CellImpl | None = None,) -> TopLevelExtraction:- ancestors = graph.ancestors(cell.cell_id)- deps = {cid: graph.cells[cid] for cid in ancestors}+ if cell:+ ancestors = graph.ancestors(cell.cell_id)+ deps = {cid: graph.cells[cid] for cid in ancestors}+ else:+ deps = {**graph.cells}setup_id = CellId_t(SETUP_CELL_NAME)setup = graph.cells.get(setup_id)- setup = graph.cells.get(setup_id)deps.pop(setup_id, None)- # TODO: Technically, order does matter incase there is a type definition- # or decorator.- path = list(deps.values()) + [cell]+ cell_order = topological_sort(graph, deps.keys())+ path = [deps[cid] for cid in cell_order if deps[cid]]+ if cell:+ path += [cell]return cls.from_cells(path, setup=setup)@classmethoddiff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.pyindex 78c50191ec..606d727407 100644--- a/marimo/_runtime/primitives.py+++ b/marimo/_runtime/primitives.py@@ -208,8 +208,19 @@ def is_pure_function(# 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.- # TODO: Investigate embedded notebook values.- if getattr(value, "__module__", None) != "__main__":+ module = getattr(value, "__module__", None)+ is_lib = module != "__main__"+ # If the function exists on the graph as a top level function, it was+ # defined in the current notebook context. If is_lib is false, then it's a+ # marimo notebook as an external module, and we should still check for+ # 'purity'.+ is_marimo_lib = False+ if graph is not None:+ from marimo._ast.toplevel import TopLevelExtraction++ extraction = TopLevelExtraction.from_graph(graph)+ is_marimo_lib = ref in extraction.variables+ if is_lib and not is_marimo_lib:return Truecache[value] = True # Prevent recursiondiff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex 67c1beeee0..e2a440c958 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -367,7 +367,7 @@ def render_toplevel_defs(del run_resultvariable = cell.toplevel_variableif variable is not None:- extractor = TopLevelExtraction.from_graph(cell, runner.graph)+ extractor = TopLevelExtraction.from_graph(runner.graph, cell=cell)serialization = list(iter(extractor))[-1]CellOp.broadcast_serialization(serialization=serialization,diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex dab588243b..9dc09475ad 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -333,6 +333,7 @@ class BlockHasher:hash_type: str = DEFAULT_HASH,apply_content_hash: bool = True,scoped_refs: Optional[set[Name]] = None,+ external: bool = False,) -> None:"""Hash the context of the module, and return a cache object.@@ -378,6 +379,8 @@ class BlockHasher:execution path hash.scoped_refs: A set of references that cannot be traced via execution path, and must beaccounted for via content hashing.+ external: If True, then the object was imported as a module. As such, the context should+ not be respected, and ignored."""# Hash should not be pinned to cell id@@ -411,7 +414,9 @@ class BlockHasher:if not apply_content_hash:refs, self.missing = self.extract_missing_ref(refs, scope)- ctx = get_and_update_context_from_scope(scope)+ ctx = None+ if not external:+ ctx = get_and_update_context_from_scope(scope)refs, _, stateful_refs = self.extract_ref_state_and_normalize_scope(refs, scope, ctx)@@ -587,8 +592,6 @@ class BlockHasher:## 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(diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 4e03934eaf..c845b887a5 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -30,7 +30,6 @@ from marimo._ast.transformers import (from marimo._ast.variables import is_mangled_local, unmangle_localfrom marimo._messaging.tracebacks import write_tracebackfrom 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@@ -49,6 +48,7 @@ from marimo._save.loaders import (MemoryLoader,)from marimo._save.stores.file import FileStore+from marimo._save.toplevel import get_cell_id_from_scope, graph_from_scopefrom marimo._types.ids import CellId_tfrom marimo._utils.with_skip import SkipContext@@ -64,6 +64,7 @@ UNEXPECTED_FAILURE_BOILERPLATE = (if TYPE_CHECKING:from types import FrameType, TracebackType+ from marimo._runtime.dataflow import DirectedGraphfrom marimo._save.stores import Store@@ -88,7 +89,7 @@ class _cache_call:"__wrapped__",)- base_block: BlockHasher+ base_block: Optional[BlockHasher]scope: dict[str, Any]scoped_refs: set[str]pin_modules: bool@@ -116,6 +117,7 @@ class _cache_call:# with respect to definition of _fnframe_offset: int = 0,) -> None:+ self.base_block = Noneself.pin_modules = pin_modulesself.hash_type = hash_typeself._frame_offset = frame_offset@@ -138,7 +140,6 @@ class _cache_call:return self.loader.hitsdef _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:@@ -149,6 +150,7 @@ class _cache_call:glbls = ctx.globalsself._external = Falseelse:+ # We are in a loaded context.cell_id = CellId_t("")graph = Noneglbls = {}@@ -192,7 +194,12 @@ 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 = {**glbls, **f_locals}+ if glbls:+ self.scope = {**glbls, **f_locals}+ else:+ # Direct assignment, because we need the reference for later+ # lookups.+ self.scope = 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.@@ -204,25 +211,12 @@ class _cache_call:# Defined in the cell, and currently available in scopeif graph is not None:self.scoped_refs |= graph.cells[cell_id].defs & set(glbls.keys())- # The defined private variables of this cell, normalized- self.scoped_refs |= set(- unmangle_local(x).name- for x in glbls.keys()- if is_mangled_local(x, cell_id)- )-- module = strip_function(self.__wrapped__)-- self.base_block = BlockHasher(- module=module,- graph=graph or DirectedGraph(),- cell_id=cell_id,- scope=self.scope,- pin_modules=self.pin_modules,- hash_type=self.hash_type,- scoped_refs=self.scoped_refs,- apply_content_hash=False,- )+ # The defined private variables of this cell, normalized+ self.scoped_refs |= set(+ unmangle_local(x).name+ for x in glbls.keys()+ if is_mangled_local(x, cell_id)+ )# Load global cache from statename = self.__name__@@ -234,6 +228,28 @@ class _cache_call:self._loader = self._loader_partial.create_or_reconfigure(name)+ if graph is not None:+ self.base_block = self._build_base_block(+ self.__wrapped__, graph, cell_id+ )++ def _build_base_block(+ self, fn: Callable[..., Any], graph: DirectedGraph, cell_id: CellId_t+ ) -> BlockHasher:+ module = strip_function(fn)++ return BlockHasher(+ module=module,+ graph=graph,+ cell_id=cell_id,+ scope=self.scope,+ pin_modules=self.pin_modules,+ hash_type=self.hash_type,+ scoped_refs=self.scoped_refs,+ apply_content_hash=False,+ external=self._external,+ )+@propertydef loader(self) -> Loader:assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATE@@ -304,6 +320,16 @@ class _cache_call:self._set_context(args[0])return self+ if self.base_block is None:+ assert self._external, UNEXPECTED_FAILURE_BOILERPLATE+ # We only build the graph on invocation because toplevel functions+ # can be defined out of order.+ graph = graph_from_scope(self.scope)+ cell_id = get_cell_id_from_scope(self.__wrapped__, self.scope)+ self.base_block = self._build_base_block(+ self.__wrapped__, graph, cell_id+ )+# Rewrite scoped args to prevent shadowed variablesarg_dict = {f"{ARG_PREFIX}{k}": v for (k, v) in zip(self._args, args)}kwargs_copy = {f"{ARG_PREFIX}{k}": v for (k, v) in kwargs.items()}diff --git a/marimo/_save/toplevel.py b/marimo/_save/toplevel.pynew file mode 100644index 0000000000..10fe2e3c1b--- /dev/null+++ b/marimo/_save/toplevel.py@@ -0,0 +1,58 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, Callable++from marimo import _loggers+from marimo._ast.app import App, InternalApp+from marimo._ast.names import (+ SETUP_CELL_NAME,+ TOPLEVEL_CELL_PREFIX,+)+from marimo._ast.toplevel import TopLevelExtraction+from marimo._runtime.dataflow import DirectedGraph+from marimo._types.ids import CellId_t++LOGGER = _loggers.marimo_logger()+++def get_app_from_scope(scope: dict[str, Any]) -> App | None:+ app = scope.get("app", None)+ if not isinstance(app, App):+ LOGGER.warning(+ "The scope does not contain a valid 'app' instance. "+ "marimo behavior may be undefined."+ )+ return None++ return app+++def graph_from_app(app: App) -> DirectedGraph:+ cell_manager = app._cell_manager+ extraction = TopLevelExtraction.from_app(InternalApp(app))+ graph = DirectedGraph()+ for cell_id, cell in cell_manager.valid_cells():+ name = cell.name.strip(TOPLEVEL_CELL_PREFIX)+ if name in extraction.toplevel or name == SETUP_CELL_NAME:+ graph.register_cell(cell_id, cell._cell)+ return graph+++def graph_from_scope(scope: dict[str, Any]) -> DirectedGraph:+ app = get_app_from_scope(scope)+ if app is None:+ return DirectedGraph()+ return graph_from_app(app)+++def get_cell_id_from_scope(+ fn: Callable[..., Any], scope: dict[str, Any]+) -> CellId_t:+ app = get_app_from_scope(scope)+ if app is None:+ return CellId_t("")+ maybe_cell = app._cell_manager.get_cell_data_by_name(fn.__name__)+ if maybe_cell is None:+ return CellId_t("")+ return maybe_cell.cell_iddiff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.pyindex 59caee1585..67100e0938 100644--- a/tests/_ast/test_toplevel.py+++ b/tests/_ast/test_toplevel.py@@ -584,8 +584,8 @@ class TestTopLevelHook:return Example()extraction = TopLevelExtraction.from_graph(- f._cell,InternalApp(app).graph,+ cell=f._cell,)assert [TopLevelType.TOPLEVEL,diff --git a/tests/_save/decorator_imports/module_0/__init__.py b/tests/_save/external_decorators/module_0/__init__.pysimilarity index 100%rename from tests/_save/decorator_imports/module_0/__init__.pyrename to tests/_save/external_decorators/module_0/__init__.pydiff --git a/tests/_save/decorator_imports/module_1/__init__.py b/tests/_save/external_decorators/module_1/__init__.pysimilarity index 100%rename from tests/_save/decorator_imports/module_1/__init__.pyrename to tests/_save/external_decorators/module_1/__init__.pydiff --git a/tests/_save/decorator_imports/transitive_imports.py b/tests/_save/external_decorators/transitive_imports.pysimilarity index 89%rename from tests/_save/decorator_imports/transitive_imports.pyrename to tests/_save/external_decorators/transitive_imports.pyindex 5edfdbc3f5..399f5bd429 100644--- a/tests/_save/decorator_imports/transitive_imports.py+++ b/tests/_save/external_decorators/transitive_imports.py@@ -7,7 +7,7 @@ with app.setup:import mathimport marimo as mo- import tests._save.decorator_imports.module_1 as my_module+ import tests._save.external_decorators.module_1 as my_module@app.functiondiff --git a/tests/_save/external_decorators/transitive_wrappers_1.py b/tests/_save/external_decorators/transitive_wrappers_1.pynew file mode 100644index 0000000000..8cd7d6435b--- /dev/null+++ b/tests/_save/external_decorators/transitive_wrappers_1.py@@ -0,0 +1,67 @@+import marimo++__generated_with = "0.14.12"+app = marimo.App()++with app.setup:+ import functools+ from typing import Any++ import marimo as mo++ # This will be an impure decorator (contains non-primitive objects)+ impure_state = [object()]+++def my_impure_decorator(func):+ """An impure decorator that depends on impure_state"""++ @functools.wraps(func)+ def wrapper(*args: Any, **kwargs: Any):+ # Decorator depends on impure_state+ wrapper._call_count = len(impure_state)+ return func(*args, **kwargs)++ return wrapper+++def my_pure_decorator(func):+ """Same pure decorator"""++ @functools.wraps(func)+ def wrapper(*args: Any, **kwargs: Any):+ return func(*args, **kwargs)++ return wrapper+++@my_impure_decorator+def pure_function():+ # This function itself is pure (no external dependencies)+ return 42+++@my_pure_decorator+def impure_function():+ # Same function, but now depends on different impure_dependency+ return len(impure_state)+++def impure_wrapped_pure():+ return pure_function()+++def pure_wrapped_impure():+ return impure_function()+++if __name__ == "__main__":+ app.run()diff --git a/tests/_save/external_decorators/transitive_wrappers_2.py b/tests/_save/external_decorators/transitive_wrappers_2.pynew file mode 100644index 0000000000..b4a7fda121--- /dev/null+++ b/tests/_save/external_decorators/transitive_wrappers_2.py@@ -0,0 +1,70 @@+# NB! The only difference between this file and transitive_wrappers_1.py is that+# impure_state is tweaked.+import marimo++__generated_with = "0.14.12"+app = marimo.App()++with app.setup:+ import functools+ from typing import Any++ import marimo as mo++ # This will be an impure decorator (contains non-primitive objects)+ # impure_state = [object()] in transitive_wrappers_1.py+ impure_state = [object(), object()]+++def my_impure_decorator(func):+ """An impure decorator that depends on impure_state"""++ @functools.wraps(func)+ def wrapper(*args: Any, **kwargs: Any):+ # Decorator depends on impure_state+ wrapper._call_count = len(impure_state)+ return func(*args, **kwargs)++ return wrapper+++def my_pure_decorator(func):+ """Same pure decorator"""++ @functools.wraps(func)+ def wrapper(*args: Any, **kwargs: Any):+ return func(*args, **kwargs)++ return wrapper+++@my_impure_decorator+def pure_function():+ # This function itself is pure (no external dependencies)+ return 42+++@my_pure_decorator+def impure_function():+ # Same function, but now depends on different impure_dependency+ return len(impure_state)+++def impure_wrapped_pure():+ return pure_function()+++def pure_wrapped_impure():+ return impure_function()+++if __name__ == "__main__":+ app.run()diff --git a/tests/_save/test_decorator_imports.py b/tests/_save/test_decorator_imports.pydeleted file mode 100644index 5cf6135d1a..0000000000--- a/tests/_save/test_decorator_imports.py+++ /dev/null@@ -1,132 +0,0 @@-# 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.stderrdiff --git a/tests/_save/test_external_decorators.py b/tests/_save/test_external_decorators.pynew file mode 100644index 0000000000..07a1f979f3--- /dev/null+++ b/tests/_save/test_external_decorators.py@@ -0,0 +1,230 @@+# 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+++class TestDecoratorImports:+ @staticmethod+ def test_has_shared_import(app) -> None:+ with app.setup:+ import marimo as mo+ from tests._save.external_decorators.transitive_imports import (+ has_import,+ )++ @app.cell+ def has_dep_works() -> tuple[int]:+ # matches test + use mo for lint+ assert has_import() == len([mo])++ @staticmethod+ def test_doesnt_have_shared_import(app) -> None:+ with app.setup:+ from tests._save.external_decorators.transitive_imports import (+ doesnt_have_import,+ )++ @app.cell+ def doesnt_have_dep_works() -> tuple[int]:+ # Counts modules on call.+ assert doesnt_have_import() == 2++ @staticmethod+ def test_has_dep_with_differing_name_works(app) -> None:+ for module in list(sys.modules.keys()):+ if module.startswith("tests._save.external_decorators"):+ del sys.modules[module]++ with app.setup:+ import marimo as mo+ import tests._save.external_decorators.module_0 as my_module+ from tests._save.external_decorators.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++ @staticmethod+ 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.external_decorators.module_0 as my_module+ from tests._save.external_decorators.transitive_imports import (+ doesnt_have_namespace as other,+ doesnt_have_namespace_pinned as other_pinned,+ )+ from tests._save.external_decorators.transitive_imports import (+ doesnt_have_import,+ )+ from tests._save.external_decorators.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+++class TestDecoratorTransitiveFns:+ @staticmethod+ async def test_impure_decorator_with_pure_dependencies(app) -> None:+ with app.setup:+ from tests._save.external_decorators.transitive_wrappers_1 import (+ pure_wrapped_impure,+ )+ from tests._save.external_decorators.transitive_wrappers_2 import (+ pure_wrapped_impure as pure_wrapped_impure_2,+ )++ @app.cell+ def _():+ result1 = pure_wrapped_impure()+ hash1 = pure_wrapped_impure._last_hash+ cache_type1 = pure_wrapped_impure.base_block.cache_type+ return result1, hash1, cache_type1++ @app.cell+ def _():+ result2 = pure_wrapped_impure_2()+ hash2 = pure_wrapped_impure_2._last_hash+ cache_type2 = pure_wrapped_impure_2.base_block.cache_type+ return result2, hash2, cache_type2++ @app.cell+ def check_results(+ result1, result2, hash1, hash2, cache_type1, cache_type2+ ):+ assert result1 == 1+ assert result2 == 2++ # The decorator itself is pure, but the function has impure dependencies+ # This should use ExecutionPath hashing, not ContentAddressed+ assert cache_type1 == "ExecutionPath", (+ f"Expected ExecutionPath, got {cache_type1}"+ )+ assert cache_type2 == "ExecutionPath", (+ f"Expected ExecutionPath, got {cache_type2}"+ )++ # Hashes should be different because the execution path changed+ # (due to different impure_dependency)+ assert hash1 != hash2, (+ f"Expected different hashes for different impure dependencies, "+ f"got {hash1} == {hash2}"+ )++ @staticmethod+ async def test_pure_decorator_with_impure_dependencies(app) -> None:+ with app.setup:+ from tests._save.external_decorators.transitive_wrappers_1 import (+ impure_wrapped_pure,+ )+ from tests._save.external_decorators.transitive_wrappers_2 import (+ impure_wrapped_pure as impure_wrapped_pure_2,+ )++ @app.cell+ def _():+ result1 = impure_wrapped_pure()+ hash1 = impure_wrapped_pure._last_hash+ cache_type1 = impure_wrapped_pure.base_block.cache_type++ @app.cell+ def _():+ result2 = impure_wrapped_pure_2()+ hash2 = impure_wrapped_pure_2._last_hash+ cache_type2 = impure_wrapped_pure_2.base_block.cache_type++ @app.cell+ def check_results(+ result1, result2, hash1, hash2, cache_type1, cache_type2+ ) -> None:+ assert result1 == 42+ assert result2 == 42++ # The decorator itself is pure, but the function has impure dependencies+ # This should use ExecutionPath hashing, not ContentAddressed+ assert cache_type1 == "ExecutionPath", (+ f"Expected ExecutionPath, got {cache_type1}"+ )+ assert cache_type2 == "ExecutionPath", (+ f"Expected ExecutionPath, got {cache_type2}"+ )++ # Hashes should be different because the execution path changed+ # (due to different impure_dependency)+ assert hash1 != hash2, (+ f"Expected different hashes for different impure dependencies, "+ f"got {hash1} == {hash2}"+ )diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 305df2ad10..721bbe93de 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -1693,7 +1693,7 @@ class TestWrappedFunctionCache: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+ # ContextExecutionPath, but since decorated ExecutionPathassert first_cache_type == "ExecutionPath", (f"Expected ExecutionPath, got {first_cache_type}")@@ -1709,7 +1709,7 @@ class TestWrappedFunctionCache:)@staticmethod- async def test_decorator_pure_with_impure_dependencies_different_cells(+ async def test_pure_decorator_with_impure_dependencies_different_cells(k: Kernel, exec_req: ExecReqProvider) -> None:"""Test impure dependencies in different cells (should be execution refs)."""@@ -1832,7 +1832,7 @@ class TestWrappedFunctionCache:)@staticmethod- async def test_decorator_pure_with_impure_dependencies(+ async def test_pure_decorator_with_impure_dependencies(k: Kernel, exec_req: ExecReqProvider) -> None:"""Test the impure edge case: decorator is pure but dependent functions are not."""