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: clean up finder/module logic for recursion (#6075)

Dylan Madisetti6fc8aa4f057b
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index abaa4a6b53..2329591569 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -84,6 +84,85 @@ NATIVE_FACTORIES: Sequence[FormatterFactory] = [
]
+def patch_finder(
+ finder: Any,
+ third_party_factories: dict[str, FormatterFactory] | None = None,
+ theme: Theme = "light",
+) -> None:
+ """Patch a MetaPathFinder to register formatters for third-parties.
+ Python's import logic has roughly the following logic:
+ 1. search for a module; if found, create a "module spec" that knows
+ how to create and load the module.
+ 2. use the spec's loader to load the module.
+
+ We monkey-patch the first step to check if a searched-for module
+ has a registered formatter. If a registered formatter is found,
+ our patch in turn patches the loader to run the formatter after
+ the module is exec'd.
+
+ Because Python's import system caches modules, our formatters'
+ register methods will be called at most once.
+ """
+ if third_party_factories is None:
+ third_party_factories = THIRD_PARTY_FACTORIES
+ # Note: "Vendored" dependencies may not have a find_spec method.
+ # E.g. `six` bundled with a project.
+ original_find_spec = getattr(finder, "find_spec", None)
+ if original_find_spec is None:
+ return
+
+ # Method stub ignores typing for "self" to allow binding.
+ def find_spec( # type:ignore[no-untyped-def]
+ self,
+ fullname,
+ path=None,
+ target=None,
+ ) -> Any:
+ del self
+ spec = original_find_spec(fullname, path, target)
+ if spec is None:
+ return spec
+
+ if spec.loader is not None and fullname in third_party_factories:
+ # We're now in the process of importing a module with
+ # an associated formatter factory. We'll hook into its
+ # loader to register the formatters.
+ original_exec_module = spec.loader.exec_module
+ factory = third_party_factories[fullname]
+
+ # We use kwargs instead of closing over the variables
+ # `original_exec_module` and `factory` to force binding.
+ def exec_module(
+ module: Any,
+ original_exec_module: Callable[
+ ..., Any
+ ] = original_exec_module,
+ factory: FormatterFactory = factory,
+ ) -> Any:
+ loader_return_value = original_exec_module(module)
+ factory.register()
+ factory.apply_theme_safe(theme)
+ return loader_return_value
+
+ spec.loader.exec_module = exec_module
+
+ return spec
+
+ # Recursive wrap can lead to a stack overflow in long running apps.
+ # `find_spec` is dynamic, so just compare the __module__s
+ module_name = getattr(finder.find_spec, "__module__", None)
+ if hasattr(finder.find_spec, "__func__"):
+ module_name = finder.find_spec.__module__
+
+ # Only patch the finder if the module it was defined in is
+ # different from the current module (`find_spec.__module__`)
+ # i.e., only patch the finder if it isn't already patched
+ if module_name != find_spec.__module__:
+ # Use the __get__ descriptor to bind find_spec to this finder object,
+ # to make sure self/cls gets passed
+ finder.find_spec = find_spec.__get__(finder) # type: ignore[method-assign] # noqa: E501
+
+
def register_formatters(theme: Theme = "light") -> None:
"""Register formatters with marimo.
@@ -123,71 +202,12 @@ def register_formatters(theme: Theme = "light") -> None:
# formatters whenever a supported third-party package is imported (in
# particular, when its module is exec'd). This ensures that formatters are
# loaded at the last possible moment: when its package is imported.
- #
- # Python's import logic has roughly the following logic:
- # 1. search for a module; if found, create a "module spec" that knows
- # how to create and load the module.
- # 2. use the spec's loader to load the module.
- #
- # We monkey-patch the first step to check if a searched-for module
- # has a registered formatter. If a registered formatter is found,
- # our patch in turn patches the loader to run the formatter after
- # the module is exec'd.
- #
- # Because Python's import system caches modules, our formatters'
- # register methods will be called at most once.
for finder in sys.meta_path:
- # Note: "Vendored" dependencies may not have a find_spec method.
- # E.g. `six` bundled with a project.
- original_find_spec = getattr(finder, "find_spec", None)
- if original_find_spec is None:
- continue
-
- # We include `original_find_spec` as a kwarg to force it to be bound
- # to the new `find_spec` method; this is needed because closures are
- # late-binding and we're in a for loop ...
- def find_spec( # type:ignore[no-untyped-def]
- self,
- fullname,
- path=None,
- target=None,
- original_find_spec=original_find_spec,
- ) -> Any:
- del self
-
- spec = original_find_spec(fullname, path, target)
- if spec is None:
- return spec
-
- if spec.loader is not None and fullname in third_party_factories:
- # We're now in the process of importing a module with
- # an associated formatter factory. We'll hook into its
- # loader to register the formatters.
- original_exec_module = spec.loader.exec_module
- factory = THIRD_PARTY_FACTORIES[fullname]
-
- # Once again, we use kwargs instead of closing over the
- # variables `original_exec_module` and `factory` to force
- # binding.
- def exec_module(
- module: Any,
- original_exec_module: Callable[
- ..., Any
- ] = original_exec_module,
- factory: FormatterFactory = factory,
- ) -> Any:
- loader_return_value = original_exec_module(module)
- factory.register()
- factory.apply_theme_safe(theme)
- return loader_return_value
-
- spec.loader.exec_module = exec_module
-
- return spec
-
- # Use the __get__ descriptor to bind find_spec to this finder object,
- # to make sure self/cls gets passed
- finder.find_spec = find_spec.__get__(finder) # type: ignore[method-assign] # noqa: E501
+ patch_finder(
+ finder,
+ third_party_factories=third_party_factories,
+ theme=theme,
+ )
# These factories are for builtins or other things that don't require a
# package import. So we can register them at program start-up.
diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.py
index 21b22359a8..f68b09fb0c 100644
--- a/marimo/_runtime/functions.py
+++ b/marimo/_runtime/functions.py
@@ -40,19 +40,13 @@ class Function(Generic[S, T]):
arg_cls: type[S],
function: Callable[[S], T],
) -> None:
- from marimo._runtime.context import (
- ContextNotInitializedError,
- get_context,
- )
+ from marimo._runtime.context import safe_get_context
self.name = name
self.arg_cls = arg_cls
self.function = function
- try:
- ctx = get_context()
- except ContextNotInitializedError:
- ctx = None
+ ctx = safe_get_context()
if ctx is not None and ctx.execution_context is not None:
self.cell_id = ctx.execution_context.cell_id
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index 5d63adf4b5..31b7023b8e 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -75,6 +75,20 @@ def patch_recursion_limit(limit: int) -> None:
def patch_micropip(glbls: dict[Any, Any]) -> None:
"""Mock micropip with no-ops"""
+ # If micropip is already in sys.meta_path, we don't need to add it
+ # again.
+ had_sys = "sys" in glbls
+ if not had_sys:
+ exec("import sys", glbls)
+
+ if eval(
+ "bool(sys.meta_path and sys.meta_path[-1].__class__.__name__ == '_MicropipFinder')",
+ glbls,
+ ):
+ if not had_sys:
+ del glbls["sys"]
+ return
+
definitions = textwrap.dedent(
"""\
from importlib.abc import Loader, MetaPathFinder
@@ -143,10 +157,17 @@ del Loader; del MetaPathFinder
# append the finder to the end of meta_path, in case the user
# already has a package called micropip
exec(
- "import sys; sys.meta_path.append(_MicropipFinder()); del sys",
+ "sys.meta_path.append(_MicropipFinder());",
glbls,
)
+ from marimo._output.formatters.formatters import patch_finder
+
+ patch_finder(glbls)
+
+ if not had_sys:
+ del glbls["sys"]
+
def create_main_module(
file: str | None,
diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.py
index 119fa1e9e9..1e00a77820 100644
--- a/tests/_output/formatters/test_formatters.py
+++ b/tests/_output/formatters/test_formatters.py
@@ -32,6 +32,32 @@ def test_path_finder_find_spec() -> None:
"test_formatters", [os.path.dirname(__file__)]
)
assert spec is not None
+ assert (
+ importlib.machinery.PathFinder.find_spec.__module__
+ == "marimo._output.formatters.formatters"
+ )
+
+
+def test_path_finder_find_spec_non_recursive() -> None:
+ # exercises a bug surfaced in
+ # https://github.com/marimo-team/marimo/issues/6072
+ register_formatters()
+ spec = importlib.machinery.PathFinder.find_spec(
+ "test_formatters", [os.path.dirname(__file__)]
+ )
+ assert spec is not None
+ assert (
+ importlib.machinery.PathFinder.find_spec.__module__
+ == "marimo._output.formatters.formatters"
+ )
+ original = importlib.machinery.PathFinder.find_spec.__func__
+
+ register_formatters()
+ spec = importlib.machinery.PathFinder.find_spec(
+ "test_formatters", [os.path.dirname(__file__)]
+ )
+ assert spec is not None
+ assert importlib.machinery.PathFinder.find_spec.__func__ == original
HAS_DEPS = DependencyManager.pandas.has() and DependencyManager.polars.has()
diff --git a/tests/_plugins/stateless/test_lazy.py b/tests/_plugins/stateless/test_lazy.py
index 751ab5856b..89cbe27254 100644
--- a/tests/_plugins/stateless/test_lazy.py
+++ b/tests/_plugins/stateless/test_lazy.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import gc
from typing import Any
from marimo._runtime.context import get_context
@@ -12,7 +11,6 @@ from tests.conftest import ExecReqProvider
def get_only_function() -> Function[Any, Any]:
- gc.collect()
context: RuntimeContext = get_context()
assert len(context.function_registry.namespaces.values()) == 1
first_namespace = next(iter(context.function_registry.namespaces.values()))
diff --git a/tests/_plugins/stateless/test_routes.py b/tests/_plugins/stateless/test_routes.py
index 9f0a863838..c21a7ea8d0 100644
--- a/tests/_plugins/stateless/test_routes.py
+++ b/tests/_plugins/stateless/test_routes.py
@@ -1,8 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import gc
-
from marimo._runtime.context import get_context
from marimo._runtime.context.types import RuntimeContext
from marimo._runtime.runtime import Kernel
@@ -28,7 +26,6 @@ async def test_routes_lazy(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
- gc.collect()
context: RuntimeContext = get_context()
# 4 functions, 1 for each route
assert len(context.function_registry.namespaces.values()) == 4
diff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.py
index ff41b4d42b..878d4363bd 100644
--- a/tests/_runtime/test_patches.py
+++ b/tests/_runtime/test_patches.py
@@ -31,6 +31,21 @@ class TestMicropip:
await executing_kernel.run([exec_req.get("import micropip")])
assert "micropip" in executing_kernel.globals
+ @staticmethod
+ async def test_micropip_once(
+ executing_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await executing_kernel.run([exec_req.get("import sys")])
+ assert (
+ executing_kernel.globals["sys"].meta_path[-1].__class__.__name__
+ == "_MicropipFinder"
+ )
+ # Double patched at this point, barring explicit fix.
+ assert (
+ executing_kernel.globals["sys"].meta_path[-2].__class__.__name__
+ != "_MicropipFinder"
+ )
+
@staticmethod
async def test_micropip_install(
executing_kernel: Kernel, exec_req: ExecReqProvider