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.

test(architectures): registry mechanics, completeness gate and layering policy

Alexander Eichhorn5e7856590718
diff --git a/tests/backend/architectures/test_layering.py b/tests/backend/architectures/test_layering.py
new file mode 100644
index 0000000000..41fd2debe5
--- /dev/null
+++ b/tests/backend/architectures/test_layering.py
@@ -0,0 +1,183 @@
+"""The architecture package has an internal direction of dependency; this pins it.
+
+ facet.py <- registry.py <- facets/* <- defs/* <- __init__.py <- the rest of the codebase
+
+Two of these edges are load-bearing rather than tidy. `defs/*` must import `architectures.registry`
+directly and never the `architectures` package, because it is that package's own import that brings
+the defs modules into being — reaching back for an attribute would find a half-initialized module.
+And everything outside must go through the facade, so that importing the registry always means the
+registry has been filled.
+
+Modelled on invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts: named rules, a single
+assertion listing every violation at once, and self-tests proving the checker actually catches
+things. The self-tests are the important half — an AST walker with a bug reports no violations and
+stays green forever, which is indistinguishable from a codebase that obeys the rules.
+"""
+
+import ast
+from collections.abc import Iterable
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).parents[3]
+ARCH = "invokeai.backend.architectures"
+ARCH_DIR = "invokeai/backend/architectures"
+TAXONOMY = "invokeai.backend.model_manager.taxonomy"
+DISCOVERY = "invokeai.backend.util.module_discovery"
+
+# Vendored third-party trees, mirroring [tool.ruff] exclude, plus the frontend.
+EXCLUDED = (
+ "invokeai/backend/image_util/mediapipe_face",
+ "invokeai/backend/image_util/mlsd",
+ "invokeai/backend/image_util/normal_bae",
+ "invokeai/backend/image_util/pidi",
+ "invokeai/backend/image_util/imwatermark",
+ "invokeai/frontend",
+)
+
+
+def _allowed_for(path: str) -> tuple[str, frozenset[str], tuple[str, ...]] | None:
+ """The rule governing `path`: its name, the exact imports it may make, and allowed prefixes.
+
+ Returns None for a file no rule covers, which is most of the repository — those are only
+ subject to `aggregate-only` below.
+ """
+ if path == f"{ARCH_DIR}/facet.py":
+ return "facet-is-a-leaf", frozenset(), ()
+ if path == f"{ARCH_DIR}/registry.py":
+ return "registry-is-a-leaf", frozenset({f"{ARCH}.facet", TAXONOMY}), ()
+ if path == f"{ARCH_DIR}/__init__.py":
+ return "aggregate-is-a-facade", frozenset({ARCH}), (f"{ARCH}.",)
+ if path.startswith(f"{ARCH_DIR}/facets/"):
+ return "facets-allowlist", frozenset({f"{ARCH}.facet", f"{ARCH}.registry", TAXONOMY, DISCOVERY}), ()
+ if path.startswith(f"{ARCH_DIR}/defs/"):
+ return (
+ "defs-allowlist",
+ frozenset({f"{ARCH}.facet", f"{ARCH}.facets", f"{ARCH}.registry", TAXONOMY, DISCOVERY}),
+ (f"{ARCH}.facets.",),
+ )
+ return None
+
+
+def _imported_modules(tree: ast.AST) -> set[str]:
+ """Every `invokeai.*` module the file depends on, plus a marker for any relative import.
+
+ `from a.b import c` yields `a.b`, and also `a.b.c` when that is a module on disk — otherwise
+ `from ...defs import wan` would be invisible while `import ...defs.wan` was not. The on-disk
+ check is what keeps `from ...registry import require` from being read as a module import.
+
+ Imports guarded by `if TYPE_CHECKING:` count. A type-only edge is still an architecture edge:
+ it is the reason a module cannot later be moved or split.
+ """
+ modules: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ modules.update(alias.name for alias in node.names if alias.name.startswith("invokeai."))
+ elif isinstance(node, ast.ImportFrom):
+ if node.level > 0:
+ modules.add("<relative>")
+ continue
+ if not node.module or not node.module.startswith("invokeai."):
+ continue
+ modules.add(node.module)
+ for alias in node.names:
+ candidate = f"{node.module}.{alias.name}"
+ relative = candidate.replace(".", "/")
+ if (REPO_ROOT / f"{relative}.py").exists() or (REPO_ROOT / relative / "__init__.py").exists():
+ modules.add(candidate)
+ return modules
+
+
+def _violations(path: str, source: str) -> list[str]:
+ """Rule violations in one file, as `rule-name: importer -> imported` strings."""
+ dotted = path.removesuffix(".py").replace("/", ".").removesuffix(".__init__")
+ rule = _allowed_for(path)
+ found: list[str] = []
+
+ for imported in sorted(_imported_modules(ast.parse(source))):
+ if rule is None:
+ # No rule covers this file, so it is outside the package: the facade or nothing. The
+ # relative-import ban is deliberately not applied here — ruff's TID252 owns the rest of
+ # the repository, and duplicating it would make this test fail on pre-existing debt that
+ # has nothing to do with the architecture package.
+ if imported.startswith(f"{ARCH}."):
+ found.append(f"aggregate-only: {dotted} -> {imported}")
+ elif imported == "<relative>":
+ found.append(f"no-relative-imports: {dotted}")
+ else:
+ name, exact, prefixes = rule
+ if imported not in exact and not imported.startswith(prefixes):
+ found.append(f"{name}: {dotted} -> {imported}")
+ return found
+
+
+def _production_files() -> Iterable[tuple[str, str]]:
+ for p in sorted((REPO_ROOT / "invokeai").rglob("*.py")):
+ path = p.relative_to(REPO_ROOT).as_posix()
+ if path.startswith(EXCLUDED):
+ continue
+ yield path, p.read_text(encoding="utf-8")
+
+
+def test_no_layering_violations() -> None:
+ violations = sorted(v for path, source in _production_files() for v in _violations(path, source))
+ assert violations == []
+
+
+# --- self-tests: does the checker actually catch anything? ----------------------------------------
+
+
+def test_catches_defs_reaching_into_core() -> None:
+ v = _violations(f"{ARCH_DIR}/defs/wan.py", "from invokeai.app.util.step_callback import calc_percentage\n")
+ assert v == [f"defs-allowlist: {ARCH}.defs.wan -> invokeai.app.util.step_callback"]
+
+
+def test_catches_defs_importing_the_aggregate() -> None:
+ """The circular-import trap: `defs` is imported *by* the package it would be reaching into."""
+ v = _violations(f"{ARCH_DIR}/defs/wan.py", "from invokeai.backend.architectures import register\n")
+ assert v == [f"defs-allowlist: {ARCH}.defs.wan -> {ARCH}"]
+
+
+def test_catches_core_bypassing_the_facade() -> None:
+ v = _violations("invokeai/app/util/step_callback.py", f"from {ARCH}.registry import require\n")
+ assert v == [f"aggregate-only: invokeai.app.util.step_callback -> {ARCH}.registry"]
+
+
+def test_catches_a_type_checking_only_edge() -> None:
+ source = "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from invokeai.app.invocations import model\n"
+ assert _violations(f"{ARCH_DIR}/registry.py", source) == [
+ f"registry-is-a-leaf: {ARCH}.registry -> invokeai.app.invocations",
+ f"registry-is-a-leaf: {ARCH}.registry -> invokeai.app.invocations.model",
+ ]
+
+
+def test_catches_a_relative_import() -> None:
+ assert _violations(f"{ARCH_DIR}/defs/wan.py", "from ..registry import register\n") == [
+ f"no-relative-imports: {ARCH}.defs.wan"
+ ]
+
+
+def test_catches_registry_importing_a_facet() -> None:
+ """`facet.py` is a separate module precisely so this edge cannot exist.
+
+ Note the reported module is `...facets.latent_space`, not `...facets`: `from a.b.c import X`
+ depends on `a.b.c`. The one-character difference between `facet` (allowed) and `facets`
+ (forbidden) is the whole point of the rule, so the assertion spells the name out in full.
+ """
+ v = _violations(f"{ARCH_DIR}/registry.py", f"from {ARCH}.facets.latent_space import LatentSpaceFacet\n")
+ assert v == [f"registry-is-a-leaf: {ARCH}.registry -> {ARCH}.facets.latent_space"]
+
+
+def test_registry_may_import_facet_but_not_facets() -> None:
+ """Pins the one-character distinction from both sides."""
+ assert _violations(f"{ARCH_DIR}/registry.py", f"from {ARCH}.facet import Facet\n") == []
+ assert _violations(f"{ARCH_DIR}/registry.py", f"from {ARCH}.facets import something\n") == [
+ f"registry-is-a-leaf: {ARCH}.registry -> {ARCH}.facets"
+ ]
+
+
+def test_allows_the_legitimate_cases() -> None:
+ """A checker that flagged everything would also pass every test above."""
+ assert _violations(f"{ARCH_DIR}/defs/wan.py", f"from {ARCH}.registry import register\n") == []
+ assert _violations(f"{ARCH_DIR}/registry.py", f"from {TAXONOMY} import BaseModelType\n") == []
+ assert _violations("invokeai/app/util/step_callback.py", f"from {ARCH} import require\n") == []
+ assert _violations("invokeai/app/util/step_callback.py", "import torch\nfrom PIL import Image\n") == []
diff --git a/tests/backend/architectures/test_registry.py b/tests/backend/architectures/test_registry.py
new file mode 100644
index 0000000000..0a7b9151e7
--- /dev/null
+++ b/tests/backend/architectures/test_registry.py
@@ -0,0 +1,136 @@
+"""Registry mechanics, exercised against throwaway facets rather than the real ones.
+
+Using dummy facets keeps these tests from restating what production declares — otherwise they would
+fail on every legitimate change to an architecture, and pass for the wrong reason when a facet is
+quietly dropped.
+"""
+
+from collections.abc import Iterator
+from dataclasses import dataclass
+
+import pytest
+
+from invokeai.backend.architectures import registry
+from invokeai.backend.architectures.facet import Facet
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+
+
+@dataclass(frozen=True)
+class _Colour(Facet):
+ name: str
+
+
+@dataclass(frozen=True)
+class _Size(Facet):
+ value: int
+
+
+@dataclass(frozen=True)
+class _Mandatory(Facet):
+ REQUIRED = True
+
+
+# `Facet.__init_subclass__` put the three above into the real `Facet.FACET_TYPES` the moment this
+# module was imported, and `validate()` reads that collection to decide what every architecture must
+# declare — so leaving `_Mandatory` in it would make the real registry fail validation for the rest
+# of the session. Undone here rather than in a fixture: the damage is done at import time, which is
+# before any fixture runs.
+for _test_double in (_Colour, _Size, _Mandatory):
+ Facet.FACET_TYPES.pop(_test_double, None)
+
+
+def isolated_registry(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ """An empty registry, and an empty facet-type collection.
+
+ Both have to be reset. `Facet.FACET_TYPES` is class state filled at import time by every facet
+ in the codebase, so leaving it alone would let a real `REQUIRED` facet leak into `validate()`
+ here and fail against architectures this test never registered.
+ """
+ monkeypatch.setattr(registry, "_ARCHITECTURES", {})
+ monkeypatch.setattr(Facet, "FACET_TYPES", {})
+ yield
+
+
+def test_register_then_get_round_trips(isolated_registry: None) -> None:
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
+ assert registry.get(BaseModelType.Flux, _Colour) == _Colour("blue")
+ assert registry.get(BaseModelType.Flux, _Size) == _Size(3)
+
+
+def test_get_returns_none_for_an_undeclared_facet(isolated_registry: None) -> None:
+ registry.register(BaseModelType.Flux, _Colour("blue"))
+ assert registry.get(BaseModelType.Flux, _Size) is None
+
+
+def test_get_returns_none_for_an_unregistered_base(isolated_registry: None) -> None:
+ assert registry.get(BaseModelType.Wan, _Colour) is None
+
+
+def test_facets_of_returns_everything_declared(isolated_registry: None) -> None:
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
+ assert set(registry.facets_of(BaseModelType.Flux)) == {_Colour("blue"), _Size(3)}
+
+
+def test_registering_twice_raises(isolated_registry: None) -> None:
+ registry.register(BaseModelType.Flux, _Colour("blue"))
+ with pytest.raises(registry.ArchitectureError, match="already registered"):
+ registry.register(BaseModelType.Flux, _Colour("red"))
+
+
+def test_the_same_facet_type_twice_in_one_call_raises(isolated_registry: None) -> None:
+ with pytest.raises(registry.ArchitectureError, match="more than once"):
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Colour("red"))
+
+
[email protected]("base", [BaseModelType.Any, BaseModelType.External, BaseModelType.Unknown])
+def test_a_sentinel_cannot_be_registered(isolated_registry: None, base: BaseModelType) -> None:
+ with pytest.raises(registry.ArchitectureError, match="not a model architecture"):
+ registry.register(base, _Colour("blue"))
+
+
+def test_require_names_the_file_to_edit_when_the_facet_is_missing(isolated_registry: None) -> None:
+ registry.register(BaseModelType.ZImage, _Colour("blue"))
+ with pytest.raises(registry.ArchitectureError) as exc:
+ registry.require(BaseModelType.ZImage, _Size)
+ assert "invokeai/backend/architectures/defs/z_image.py" in str(exc.value)
+ assert "_Size" in str(exc.value)
+
+
+def test_require_says_how_to_create_a_missing_architecture(isolated_registry: None) -> None:
+ """The other half of the message: there is no file yet, so say what to put in it."""
+ with pytest.raises(registry.ArchitectureError) as exc:
+ registry.require(BaseModelType.ZImage, _Size)
+ message = str(exc.value)
+ assert "invokeai/backend/architectures/defs/z_image.py" in message
+ assert "register(BaseModelType.ZImage, _Size(...))" in message
+ assert "no import list to edit" in message
+
+
+def test_architecture_error_is_a_value_error() -> None:
+ """It replaces `raise ValueError("Unsupported base model: ...")`, so handlers must still catch."""
+ assert issubclass(registry.ArchitectureError, ValueError)
+
+
+def test_validate_reports_an_undeclared_required_facet(isolated_registry: None) -> None:
+ """The negative probe for the boot gate. Without this, `validate()` could be a no-op forever."""
+ for base in BaseModelType:
+ if base not in registry._NOT_ARCHITECTURES:
+ registry.register(base)
+ Facet.FACET_TYPES[_Mandatory] = None
+
+ with pytest.raises(registry.ArchitectureError) as exc:
+ registry.validate()
+ assert "_Mandatory" in str(exc.value)
+ assert "invokeai/backend/architectures/defs/flux.py" in str(exc.value)
+
+
+def test_validate_reports_an_unregistered_architecture(isolated_registry: None) -> None:
+ """Discovery is automatic, so the way to fail is a new enum member with no module under defs/."""
+ for base in BaseModelType:
+ if base not in registry._NOT_ARCHITECTURES and base is not BaseModelType.Wan:
+ registry.register(base)
+
+ with pytest.raises(registry.ArchitectureError) as exc:
+ registry.validate()
+ assert "'wan'" in str(exc.value)
diff --git a/tests/backend/architectures/test_registry_completeness.py b/tests/backend/architectures/test_registry_completeness.py
new file mode 100644
index 0000000000..df4620bc48
--- /dev/null
+++ b/tests/backend/architectures/test_registry_completeness.py
@@ -0,0 +1,59 @@
+"""The registry covers every architecture, and the files on disk agree with it.
+
+These run against the *real* registry, unlike test_registry.py. They are what makes the boot check
+meaningful before any facet is required: with no required facets, `validate()` still has to catch a
+`BaseModelType` member that nobody declared.
+"""
+
+from pathlib import Path
+
+from invokeai.backend.architectures import facets, generative_bases, validate
+from invokeai.backend.architectures.registry import _NOT_ARCHITECTURES, defs_module_path
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+
+REPO_ROOT = Path(__file__).parents[3]
+DEFS_DIR = REPO_ROOT / "invokeai" / "backend" / "architectures" / "defs"
+
+
+def test_every_architecture_is_registered() -> None:
+ """The one place the sentinel subtraction is written down.
+
+ Production code never computes `set(BaseModelType) - sentinels` to decide what is generative —
+ being registered is what makes an architecture generative. This asserts the two agree, which is
+ what catches a new enum member whose `defs/` module was never written.
+ """
+ assert generative_bases() == set(BaseModelType) - _NOT_ARCHITECTURES
+
+
+def test_each_registered_architecture_has_the_file_its_errors_name() -> None:
+ """`defs_module_path` is quoted in every error message; a wrong path is worse than no path."""
+ missing = [
+ defs_module_path(base) for base in generative_bases() if not (REPO_ROOT / defs_module_path(base)).exists()
+ ]
+ assert missing == []
+
+
+def test_no_defs_module_is_left_over() -> None:
+ """The other direction: a file for a base that no longer exists would never be noticed.
+
+ Discovery imports whatever is in the directory, and a stale module's `register()` call would
+ either raise on an unknown enum member or, worse, keep registering a base that was renamed.
+ """
+ on_disk = {p.stem for p in DEFS_DIR.glob("*.py") if not p.stem.startswith("_")}
+ derived = {base.value.replace("-", "_") for base in BaseModelType if base not in _NOT_ARCHITECTURES}
+ assert on_disk == derived
+
+
+def test_every_facet_module_was_imported() -> None:
+ """`validate()` only checks requirements it knows about, and it learns them at import time."""
+ facets_dir = REPO_ROOT / "invokeai" / "backend" / "architectures" / "facets"
+ on_disk = {
+ f"invokeai.backend.architectures.facets.{p.stem}"
+ for p in facets_dir.rglob("*.py")
+ if not any(part.startswith("_") for part in p.relative_to(facets_dir).parts)
+ }
+ assert on_disk == set(facets._MODULES)
+
+
+def test_validate_passes() -> None:
+ validate()