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(invocations): replace star import with explicit module loading to prevent import cycles

Alexander Eichhornc1a507e608f4
diff --git a/invokeai/app/invocations/__init__.py b/invokeai/app/invocations/__init__.py
index d71ed35319..0b813fd7b0 100644
--- a/invokeai/app/invocations/__init__.py
+++ b/invokeai/app/invocations/__init__.py
@@ -1,12 +1,19 @@
-"""Core invocation modules, imported for their side effects.
+"""Core invocation modules.
-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`.
+Every module in this package registers its `@invocation`-decorated classes with
+`InvocationRegistry` as it is imported, so the app is only correct once *all* of them have been
+imported. `load_all_modules()` does that, and `invokeai.app.services.shared.graph` calls it.
+
+Importing them here, in the package body, would be the obvious shortcut and is wrong: it makes
+`import invokeai.app.invocations.anything` -- including the `baseinvocation` import that
+`invokeai.invocation_api` starts with -- pull in the whole tree. A node module that imports
+`invocation_api` back (`composition-nodes.py` does) then closes a cycle, and
+`import invokeai.invocation_api` fails outright with a partially initialized module. That is the
+first import in the documented node-pack guide, so it has to stay cheap.
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
+`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.
"""
@@ -16,11 +23,11 @@ from types import ModuleType
from invokeai.backend.util.module_discovery import discover_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.
-# 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})
+def load_all_modules() -> dict[str, ModuleType]:
+ """Import every node module in this package, registering the invocations it declares.
+
+ Idempotent: `import_module` returns the cached module on later calls, so callers do not have to
+ coordinate who invokes it first.
+ """
+ return {name: import_module(name) for name in discover_modules(Path(__file__).parent, f"{__name__}.")}
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 1d233e028a..c267f82fbf 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -36,8 +36,7 @@ from pydantic.fields import Field
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
-# Importing * is bad karma but needed here for node detection
-from invokeai.app.invocations import * # noqa: F401 F403
+from invokeai.app.invocations import load_all_modules
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
@@ -54,6 +53,11 @@ from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.misc import uuid_string
+# Node detection: every core invocation must be registered before the unions below are built from
+# `InvocationRegistry`. This is a call rather than a star-import so that importing a single node
+# module -- or `invokeai.invocation_api`, which imports one -- does not drag in the whole tree.
+load_all_modules()
+
if TYPE_CHECKING:
import networkx as nx
else:
diff --git a/tests/app/invocations/test_invocation_api_imports_alone.py b/tests/app/invocations/test_invocation_api_imports_alone.py
new file mode 100644
index 0000000000..7aca72c1bd
--- /dev/null
+++ b/tests/app/invocations/test_invocation_api_imports_alone.py
@@ -0,0 +1,49 @@
+"""`import invokeai.invocation_api` must work as the first invokeai import in a process.
+
+It is the first import in the node-pack guide, so every custom node pack starts here. It broke once:
+the node modules were imported in `invokeai/app/invocations/__init__.py`, which made touching *any*
+submodule -- including the `baseinvocation` import that `invocation_api` itself begins with -- pull
+in the whole tree. `composition-nodes.py` imports `invocation_api` back, and the cycle closed:
+`ImportError: cannot import name 'BaseInvocation' from partially initialized module`.
+
+The app never noticed, because by the time it loads custom nodes everything is already imported.
+Only a fresh process starting at `invocation_api` sees it, which is why this runs in a subprocess.
+"""
+
+import subprocess
+import sys
+
+PROGRAM = """
+import sys
+
+import invokeai.invocation_api as api
+
+assert "BaseInvocation" in api.__all__, "invocation_api did not export its own surface"
+assert api.BaseInvocation is not None
+
+# The point of the split: importing the public surface must not drag in every node module. If this
+# ever has to change, the cycle above is what will break.
+loaded = [m for m in sys.modules if m.startswith("invokeai.app.invocations.") and "flux" in m]
+assert not loaded, f"invocation_api pulled in node modules: {sorted(loaded)[:5]}"
+
+print("OK")
+"""
+
+
+def test_invocation_api_is_importable_on_its_own() -> None:
+ result = subprocess.run([sys.executable, "-c", PROGRAM], capture_output=True, text=True, timeout=300)
+ assert result.returncode == 0, f"stdout:\n{result.stdout}\nstderr:\n{result.stderr[-3000:]}"
+ assert "OK" in result.stdout
+
+
+def test_the_documented_node_pack_imports_work_on_their_own() -> None:
+ """What `docs/development/Guides/creating-node-pack.mdx` tells authors to write, verbatim."""
+ program = (
+ "from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation\n"
+ "from invokeai.app.invocations.fields import InputField, OutputField\n"
+ "from invokeai.invocation_api import BaseInvocationOutput, invocation_output\n"
+ "print('OK')\n"
+ )
+ result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, timeout=300)
+ assert result.returncode == 0, f"stderr:\n{result.stderr[-3000:]}"
+ assert "OK" in result.stdout
diff --git a/tests/app/invocations/test_node_discovery.py b/tests/app/invocations/test_node_discovery.py
index a19d8e9f50..69b6f8267b 100644
--- a/tests/app/invocations/test_node_discovery.py
+++ b/tests/app/invocations/test_node_discovery.py
@@ -4,11 +4,15 @@ 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.
+
+Calling `load_all_modules()` here rather than reading a module-level dict is the point of the
+split: the package body must stay cheap so that `import invokeai.invocation_api` -- the first
+import in the node-pack guide -- does not pull in this tree and close an import cycle.
"""
from pathlib import Path
-from invokeai.app.invocations import _MODULES
+from invokeai.app.invocations import load_all_modules
PACKAGE = "invokeai.app.invocations"
@@ -20,4 +24,4 @@ def test_every_node_module_on_disk_was_imported() -> None:
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"
+ assert on_disk == set(load_all_modules()), "walker and filesystem disagree"