Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(architectures): discover modules without importing excluded packages
Alexander Eichhorn3e7992e08d89
diff --git a/invokeai/backend/util/module_discovery.py b/invokeai/backend/util/module_discovery.pyindex 07ea0a6e6f..8f2a7b8dd3 100644--- a/invokeai/backend/util/module_discovery.py+++ b/invokeai/backend/util/module_discovery.py@@ -12,19 +12,6 @@ from collections.abc import Iteratorfrom pathlib import Path-def _reraise(name: str) -> None:- """Refuse to continue past a subpackage that would not import.-- `pkgutil.walk_packages` swallows such errors by default, which turns "this package's- `__init__.py` is broken" into "the things it holds quietly do not exist" — the exact failure- mode a registry filled by import is meant to avoid.- """- # `walk_packages` calls this from inside its own `except ImportError`, so the original failure- # is chained implicitly and the traceback shows the offending file and line above this message.- # An explicit `raise ... from` would need `sys.exc_info()` and would only change the wording.- raise ImportError(f"Failed to walk package {name!r} while discovering modules.")--def _holds_modules(directory: Path) -> bool:"""Whether `directory` contains any module that discovery would be expected to reach.@@ -40,7 +27,7 @@ def _holds_modules(directory: Path) -> bool:def _orphan_directories(package_dir: Path) -> Iterator[Path]:"""Directories under `package_dir` that hold modules but have no `__init__.py`.- `pkgutil.walk_packages` does not descend into such a directory, and says nothing about it: every+ The walk does not descend into such a directory, and says nothing about it: everymodule below it is simply absent from the result, which is indistinguishable from there beingnothing to find. That is the discovery mistake that actually happens — one `__init__.py`forgotten in a new subdirectory — so it is looked for rather than waited for.@@ -58,19 +45,21 @@ def discover_modules(root: Path, prefix: str) -> list[str]:"""Fully-qualified names of every non-private module in the package tree rooted at `root`.`prefix` is the dotted path of the package that lives at `root`, trailing dot included; it is- what the returned names are prefixed with, and what `walk_packages` uses to import subpackages- so it can descend into them.+ what the returned names are prefixed with.- A path component starting with `_` excludes the module: that covers `__pycache__` and marks a- module as internal. Packages themselves are skipped — importing them is a side effect of the- walk, and it is their contents that carry the registrations.+ A path component starting with `_` excludes the module and everything below it: that covers+ `__pycache__` and marks a module or package as internal. Packages themselves are not returned --+ importing a module imports its packages, and it is their contents that carry the registrations.- A directory holding modules but no `__init__.py` raises: `walk_packages` would skip it in- silence, which is the one discovery failure that produces no symptom at all.+ A directory holding modules but no `__init__.py` raises: the walk would skip it in silence,+ which is the one discovery failure that produces no symptom at all.- Names only; importing them is the caller's job. Keeping the two apart is what lets the walk be- tested against a synthetic tree, which matters because a walker with a bug returns an empty list- and no test that merely asserts "some modules were found" would notice.+ Names only, and nothing is imported to find them: `pkgutil.walk_packages` imports every package+ to descend into it, which runs an excluded package's `__init__.py` before any filter can see its+ name. Importing is the caller's job, so a broken package fails there, with its own traceback.+ Keeping the two apart is also what lets the walk be tested against a synthetic tree, which+ matters because a walker with a bug returns an empty list and no test that merely asserts "some+ modules were found" would notice."""orphans = [d.relative_to(root).as_posix() for d in _orphan_directories(root)]if orphans:@@ -80,10 +69,14 @@ def discover_modules(root: Path, prefix: str) -> list[str]:f"rename it with a leading underscore if it is not meant to be imported.")- names: list[str] = []- for info in pkgutil.walk_packages([str(root)], prefix=prefix, onerror=_reraise):- relative = info.name.removeprefix(prefix)- if info.ispkg or any(part.startswith("_") for part in relative.split(".")):+ return list(_walk(root, prefix))+++def _walk(directory: Path, prefix: str) -> Iterator[str]:+ for info in pkgutil.iter_modules([str(directory)]):+ if info.name.startswith("_"):continue- names.append(info.name)- return names+ if info.ispkg:+ yield from _walk(directory / info.name, f"{prefix}{info.name}.")+ else:+ yield f"{prefix}{info.name}"diff --git a/tests/backend/util/test_module_discovery.py b/tests/backend/util/test_module_discovery.pyindex 70079f6cb6..ecf92afc9c 100644--- a/tests/backend/util/test_module_discovery.py+++ b/tests/backend/util/test_module_discovery.py@@ -4,6 +4,7 @@ A walker that silently finds nothing is green forever, so these run it against awhose expected result is written out by hand — independent of any real package's layout."""+import importlibimport sysfrom collections.abc import Iteratorfrom pathlib import Path@@ -53,15 +54,29 @@ def test_skips_private_modules_and_pycache(tree: Path) -> None:assert not [n for n in found if "_private" in n or "__pycache__" in n or "stale" in n]-def test_reports_a_broken_subpackage(tree: Path) -> None:- """The default `walk_packages` behaviour is to swallow this, leaving the caller none the wiser."""+def test_an_excluded_package_is_neither_imported_nor_descended_into(tree: Path) -> None:+ """`walk_packages` imports a package to descend into it, so a `_disabled` package's initializer+ ran -- and could register nodes or abort startup -- before its name was ever filtered."""+ (tree / "_disabled").mkdir()+ (tree / "_disabled" / "__init__.py").write_text("raise RuntimeError('imported')", encoding="utf-8")+ (tree / "_disabled" / "node.py").write_text("", encoding="utf-8")++ assert sorted(discover_modules(tree, "synthetic_pkg.")) == ["synthetic_pkg.flat", "synthetic_pkg.sub.nested"]+ assert "synthetic_pkg._disabled" not in sys.modules+++def test_a_broken_subpackage_fails_when_its_modules_are_imported(tree: Path) -> None:+ """Discovery imports nothing, so a broken initializer surfaces at the caller's import, with its+ own error, rather than as a module that quietly does not exist."""(tree / "sub" / "__init__.py").write_text("raise RuntimeError('boom')", encoding="utf-8")- with pytest.raises(ImportError, match="synthetic_pkg.sub"):- discover_modules(tree, "synthetic_pkg.")++ with pytest.raises(RuntimeError, match="boom"):+ for name in discover_modules(tree, "synthetic_pkg."):+ importlib.import_module(name)def test_reports_a_directory_with_no_init(tree: Path) -> None:- """`walk_packages` does not descend into one, and does not complain either.+ """The walk does not descend into one, and does not complain either.The result is a module that is simply never imported and a registration that silently neverhappens — the failure this whole module exists to make impossible.