Skip to content

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.

refactor(util): extract the package walker used to fill registries

Alexander Eichhorn80085e77165a
diff --git a/invokeai/app/invocations/__init__.py b/invokeai/app/invocations/__init__.py
index 86d9e7960a..d71ed35319 100644
--- a/invokeai/app/invocations/__init__.py
+++ b/invokeai/app/invocations/__init__.py
@@ -10,45 +10,15 @@ are grouped into per-architecture subpackages (`flux/`, `wan/`, ...) and cross-c
not surface at boot but later, as an "unknown node type" when a user opens a workflow that uses one.
"""
-import pkgutil
from importlib import import_module
from pathlib import Path
from types import ModuleType
-_PACKAGE_ROOT = Path(__file__).parent
+from invokeai.backend.util.module_discovery import discover_modules
-
-def _on_discovery_error(name: str) -> None:
- """Re-raise whatever broke while walking the tree.
-
- `pkgutil.walk_packages` swallows errors raised while importing a *subpackage* by default, which
- would turn "this architecture's `__init__.py` is broken" into "these nodes quietly do not exist".
- That is the exact failure mode this module exists to prevent, so refuse to continue.
- """
- raise ImportError(f"Failed to walk invocation package {name!r} while discovering nodes.")
-
-
-def discover_node_modules(root: Path = _PACKAGE_ROOT, prefix: str = f"{__name__}.") -> list[str]:
- """Fully-qualified names of every non-private module in the package tree rooted at `root`.
-
- A path component starting with `_` excludes the module: that covers `__pycache__` and marks a
- module as internal. Subpackages themselves are skipped — importing them is a side effect of the
- walk, and their `__init__.py` files hold no nodes.
-
- Parameterized on `root`/`prefix` so the walk can be exercised against a synthetic tree. A walker
- with a bug here finds nothing and stays green forever, so it needs a test that does not depend
- on the layout of this package.
- """
- names: list[str] = []
- for info in pkgutil.walk_packages([str(root)], prefix=prefix, onerror=_on_discovery_error):
- relative = info.name.removeprefix(prefix)
- if info.ispkg or any(part.startswith("_") for part in relative.split(".")):
- continue
- names.append(info.name)
- return names
-
-
-_MODULES: dict[str, ModuleType] = {name: import_module(name) for name in discover_node_modules()}
+_MODULES: dict[str, ModuleType] = {
+ name: import_module(name) for name in discover_modules(Path(__file__).parent, f"{__name__}.")
+}
# `import *` binds names, and a dotted name is not one. Only the top component of each module path
# is an attribute of this package, so a node in a subpackage contributes that subpackage's name.
diff --git a/invokeai/backend/util/module_discovery.py b/invokeai/backend/util/module_discovery.py
new file mode 100644
index 0000000000..375abe414e
--- /dev/null
+++ b/invokeai/backend/util/module_discovery.py
@@ -0,0 +1,45 @@
+"""Import-for-side-effect discovery of the modules in a package tree.
+
+Two registries in this codebase are filled by importing modules rather than from a hand-maintained
+list: node invocations (`invokeai.app.invocations`) and model architectures
+(`invokeai.backend.architectures.defs`). Both fail the same way when discovery is subtly wrong —
+they find nothing, register nothing, and stay green — so both go through this one function, and its
+pitfalls are handled and tested in one place.
+"""
+
+import pkgutil
+from 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.
+ """
+ raise ImportError(f"Failed to walk package {name!r} while discovering modules.")
+
+
+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.
+
+ 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.
+
+ 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: 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(".")):
+ continue
+ names.append(info.name)
+ return names
diff --git a/tests/app/invocations/test_node_discovery.py b/tests/app/invocations/test_node_discovery.py
index 1c0e1189bc..a19d8e9f50 100644
--- a/tests/app/invocations/test_node_discovery.py
+++ b/tests/app/invocations/test_node_discovery.py
@@ -1,56 +1,19 @@
-"""The invocation walker must find nodes in subpackages, not just in the top directory.
+"""Every node module on disk must actually have been imported.
-A walker that silently finds nothing is green forever, so the self-tests below run it against a
-synthetic tree whose expected result is written out by hand — independent of how
-`invokeai/app/invocations/` happens to be laid out today.
+The walker itself is exercised against a synthetic tree in
+`tests/backend/util/test_module_discovery.py`. What is left to check here is that this package's
+real layout agrees with it — the realistic mistake being a new architecture folder that never got an
+`__init__.py`, which is not a package and therefore contributes no nodes at all.
"""
-import sys
-from collections.abc import Iterator
from pathlib import Path
-import pytest
-
-from invokeai.app.invocations import _MODULES, discover_node_modules
+from invokeai.app.invocations import _MODULES
PACKAGE = "invokeai.app.invocations"
-def synthetic_tree(tmp_path: Path) -> Iterator[Path]:
- """A miniature invocations package: one flat module, one in a subpackage, plus things to skip."""
- root = tmp_path / "synthetic_nodes"
- (root / "arch").mkdir(parents=True)
- (root / "__pycache__").mkdir()
- (root / "__init__.py").write_text("", encoding="utf-8")
- (root / "flat_node.py").write_text("", encoding="utf-8")
- (root / "_private.py").write_text("", encoding="utf-8")
- (root / "arch" / "__init__.py").write_text("", encoding="utf-8")
- (root / "arch" / "nested_node.py").write_text("", encoding="utf-8")
- (root / "__pycache__" / "stale.py").write_text("", encoding="utf-8")
-
- sys.path.insert(0, str(tmp_path))
- try:
- yield root
- finally:
- sys.path.remove(str(tmp_path))
- for name in [m for m in sys.modules if m.startswith("synthetic_nodes")]:
- del sys.modules[name]
-
-
-def test_walker_descends_into_subpackages(synthetic_tree: Path) -> None:
- found = discover_node_modules(synthetic_tree, prefix="synthetic_nodes.")
- assert sorted(found) == ["synthetic_nodes.arch.nested_node", "synthetic_nodes.flat_node"]
-
-
-def test_walker_reports_a_broken_subpackage(synthetic_tree: Path) -> None:
- (synthetic_tree / "arch" / "__init__.py").write_text("raise RuntimeError('boom')", encoding="utf-8")
- with pytest.raises(ImportError, match="synthetic_nodes.arch"):
- discover_node_modules(synthetic_tree, prefix="synthetic_nodes.")
-
-
def test_every_node_module_on_disk_was_imported() -> None:
- """Filesystem and registry agree. Catches a subpackage that never got an `__init__.py`."""
root = Path(__file__).parents[3] / "invokeai" / "app" / "invocations"
on_disk = {
f"{PACKAGE}." + p.relative_to(root).with_suffix("").as_posix().replace("/", ".")
diff --git a/tests/backend/util/test_module_discovery.py b/tests/backend/util/test_module_discovery.py
new file mode 100644
index 0000000000..f7f0d560c4
--- /dev/null
+++ b/tests/backend/util/test_module_discovery.py
@@ -0,0 +1,54 @@
+"""The package walker must descend into subpackages, and must not hide a broken one.
+
+A walker that silently finds nothing is green forever, so these run it against a synthetic tree
+whose expected result is written out by hand — independent of any real package's layout.
+"""
+
+import sys
+from collections.abc import Iterator
+from pathlib import Path
+
+import pytest
+
+from invokeai.backend.util.module_discovery import discover_modules
+
+
+def tree(tmp_path: Path) -> Iterator[Path]:
+ """A miniature package: one flat module, one in a subpackage, plus things that must be skipped."""
+ root = tmp_path / "synthetic_pkg"
+ (root / "sub").mkdir(parents=True)
+ (root / "__pycache__").mkdir()
+ (root / "__init__.py").write_text("", encoding="utf-8")
+ (root / "flat.py").write_text("", encoding="utf-8")
+ (root / "_private.py").write_text("", encoding="utf-8")
+ (root / "sub" / "__init__.py").write_text("", encoding="utf-8")
+ (root / "sub" / "nested.py").write_text("", encoding="utf-8")
+ (root / "__pycache__" / "stale.py").write_text("", encoding="utf-8")
+
+ sys.path.insert(0, str(tmp_path))
+ try:
+ yield root
+ finally:
+ sys.path.remove(str(tmp_path))
+ for name in [m for m in sys.modules if m.startswith("synthetic_pkg")]:
+ del sys.modules[name]
+
+
+def test_descends_into_subpackages(tree: Path) -> None:
+ assert sorted(discover_modules(tree, "synthetic_pkg.")) == [
+ "synthetic_pkg.flat",
+ "synthetic_pkg.sub.nested",
+ ]
+
+
+def test_skips_private_modules_and_pycache(tree: Path) -> None:
+ found = discover_modules(tree, "synthetic_pkg.")
+ 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."""
+ (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.")