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.

feat(invocations): discover node modules recursively

Alexander Eichhorn03b1ef8f75f7
diff --git a/invokeai/app/invocations/__init__.py b/invokeai/app/invocations/__init__.py
index c8d6443752..86d9e7960a 100644
--- a/invokeai/app/invocations/__init__.py
+++ b/invokeai/app/invocations/__init__.py
@@ -1,5 +1,56 @@
+"""Core invocation modules, imported for their side effects.
+
+Every module below registers its `@invocation`-decorated classes with `InvocationRegistry` as it is
+imported, so the app is only correct once *all* of them have been imported. That import is triggered
+by `from invokeai.app.invocations import *` in `invokeai.app.services.shared.graph`.
+
+Discovery walks the whole package tree rather than globbing `*.py` in this directory. Node modules
+are grouped into per-architecture subpackages (`flux/`, `wan/`, ...) and cross-cutting ones (`vae/`,
+`text_encoder/`, `pid/`), and a flat glob would skip every one of them silently — the failure would
+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
+
+
+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()}
-# add core nodes to __all__
-python_files = filter(lambda f: not f.name.startswith("_"), Path(__file__).parent.glob("*.py"))
-__all__ = [f.stem for f in python_files] # type: ignore
+# `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.
+# Binding is incidental here anyway — the registration this module exists for already happened above.
+__all__ = sorted({name.removeprefix(f"{__name__}.").split(".", 1)[0] for name in _MODULES})
diff --git a/tests/app/invocations/test_node_discovery.py b/tests/app/invocations/test_node_discovery.py
new file mode 100644
index 0000000000..1c0e1189bc
--- /dev/null
+++ b/tests/app/invocations/test_node_discovery.py
@@ -0,0 +1,60 @@
+"""The invocation walker must find nodes in subpackages, not just in the top directory.
+
+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.
+"""
+
+import sys
+from collections.abc import Iterator
+from pathlib import Path
+
+import pytest
+
+from invokeai.app.invocations import _MODULES, discover_node_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("/", ".")
+ for p in root.rglob("*.py")
+ if not any(part.startswith("_") for part in p.relative_to(root).parts)
+ }
+ assert on_disk == set(_MODULES), "walker and filesystem disagree"