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(model-manager): cover failure recovery and validation boundaries

JPPhoto137f412376a0
diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.py
index ba4961f094..374d9cb5c0 100644
--- a/tests/app/routers/test_update_model_record_cache_invalidation.py
+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py
@@ -6,14 +6,20 @@ ignoring changes that don't affect how the model loads (e.g. name, description).
"""
from types import SimpleNamespace
+from unittest.mock import MagicMock
+import pytest
+
+from invokeai.app.api.routers import model_manager as model_manager_router
from invokeai.app.api.routers.model_manager import _load_settings_changed
+from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
-def _config(*, fp8: bool | None = None, cpu_only: bool | None = None):
+def _config(*, fp8: bool | None = None, cpu_only: bool | None = None, **fields):
return SimpleNamespace(
cpu_only=cpu_only,
default_settings=SimpleNamespace(fp8_storage=fp8),
+ **fields,
)
@@ -51,3 +57,46 @@ def test_unrelated_field_does_not_trigger_invalidation():
bare_a = SimpleNamespace()
bare_b = SimpleNamespace()
assert _load_settings_changed(bare_a, bare_b) is False
+
+
[email protected]("field", ["path", "base", "type", "format", "variant"])
+def test_model_identity_changes_trigger_invalidation(field: str):
+ """Fields exposed by ModelRecordChanges can change the module selected or its source path."""
+ previous = _config(**{field: "old"})
+ updated = _config(**{field: "new"})
+ assert _load_settings_changed(previous, updated) is True
+
+
[email protected]("field", ["path", "base", "type", "format", "variant", "name", "description"])
+def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkeypatch: pytest.MonkeyPatch):
+ previous = _config(**{field: "old"})
+ updated = _config(**{field: "new"})
+ record_store = SimpleNamespace(
+ get_model=MagicMock(return_value=previous),
+ update_model=MagicMock(return_value=updated),
+ )
+ cache_a = SimpleNamespace(drop_model=MagicMock(return_value=1))
+ cache_b = SimpleNamespace(drop_model=MagicMock(return_value=1))
+ services = SimpleNamespace(
+ logger=MagicMock(),
+ model_manager=SimpleNamespace(
+ store=record_store,
+ load=SimpleNamespace(ram_caches={"cuda:0": cache_a, "cuda:1": cache_b}),
+ ),
+ )
+ monkeypatch.setattr(
+ model_manager_router.ApiDependencies,
+ "invoker",
+ SimpleNamespace(services=services),
+ raising=False,
+ )
+ monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _deps: config)
+
+ result = model_manager_router._update_model_record(key="model-key", changes=ModelRecordChanges())
+ assert result is updated
+
+ for cache in (cache_a, cache_b):
+ if field in {"name", "description"}:
+ cache.drop_model.assert_not_called()
+ else:
+ cache.drop_model.assert_called_once_with("model-key")
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 180cb5690f..ba0d5f802e 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -6,6 +6,7 @@ import gc
import json
import platform
import shutil
+import sqlite3
import threading
import time
import uuid
@@ -32,6 +33,7 @@ from invokeai.app.services.model_install import (
HFModelSource,
ModelInstallService,
ModelInstallServiceBase,
+ model_install_default,
)
from invokeai.app.services.model_install.model_install_common import (
InstallStatus,
@@ -45,7 +47,7 @@ from invokeai.app.services.model_install.model_install_default import (
INSTALL_MARKER_VERSION,
TMPDIR_PREFIX,
)
-from invokeai.app.services.model_records import ModelRecordChanges, UnknownModelException
+from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL, UnknownModelException
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
from invokeai.backend.model_manager.metadata import RemoteModelFile
from invokeai.backend.model_manager.taxonomy import (
@@ -132,6 +134,135 @@ def test_install(
assert model_record.source == embedding_file.as_posix()
+def test_directory_install_retries_windows_move_failures(
+ mm2_installer: ModelInstallServiceBase,
+ diffusers_dir: Path,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A transient handle failure must not strand a partially moved directory install."""
+ expected_files = {
+ path.relative_to(diffusers_dir): path.read_bytes() for path in diffusers_dir.rglob("*") if path.is_file()
+ }
+ real_move = shutil.move
+ calls = 0
+
+ def flaky_move(src: Path, dst: Path):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise PermissionError("simulated Windows file-handle race")
+ return real_move(src, dst)
+
+ monkeypatch.setattr(model_install_default, "move", flaky_move)
+
+ key = mm2_installer.install_path(diffusers_dir)
+
+ model_record = mm2_installer.record_store.get_model(key)
+ installed_path = mm2_app_config.models_path / model_record.path
+ installed_files = {
+ path.relative_to(installed_path): path.read_bytes() for path in installed_path.rglob("*") if path.is_file()
+ }
+ assert installed_files == expected_files
+ assert calls >= 3
+
+
+def test_directory_install_failure_does_not_leave_partial_destination(
+ mm2_installer: ModelInstallServiceBase,
+ diffusers_dir: Path,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ existing_paths = set(mm2_app_config.models_path.iterdir())
+
+ def fail_first_move(_src: Path, _dst: Path):
+ raise PermissionError("simulated Windows file-handle race")
+
+ monkeypatch.setattr(model_install_default, "move", fail_first_move)
+
+ with pytest.raises(PermissionError, match="simulated Windows file-handle race"):
+ mm2_installer.install_path(diffusers_dir)
+
+ assert set(mm2_app_config.models_path.iterdir()) == existing_paths
+ assert list(diffusers_dir.iterdir())
+ assert mm2_installer.record_store.all_models() == []
+
+
+def test_directory_install_late_move_failure_restores_source_files(
+ mm2_installer: ModelInstallServiceBase,
+ diffusers_dir: Path,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A locked later file must not strand files already removed from a user's import folder."""
+ expected_files = {
+ path.relative_to(diffusers_dir): path.read_bytes() for path in diffusers_dir.rglob("*") if path.is_file()
+ }
+ existing_paths = set(mm2_app_config.models_path.iterdir())
+ first_item, locked_item, *_ = list(diffusers_dir.iterdir())
+ real_move = shutil.move
+ moved_first_item = False
+
+ def move_with_locked_source(src: Path, dst: Path):
+ nonlocal moved_first_item
+ if src == locked_item:
+ assert moved_first_item
+ raise PermissionError("source file remains locked")
+ result = real_move(src, dst)
+ if src == first_item:
+ moved_first_item = True
+ return result
+
+ monkeypatch.setattr(model_install_default, "move", move_with_locked_source)
+
+ with pytest.raises(PermissionError, match="source file remains locked"):
+ mm2_installer.install_path(diffusers_dir)
+
+ assert moved_first_item
+ assert {
+ path.relative_to(diffusers_dir): path.read_bytes() for path in diffusers_dir.rglob("*") if path.is_file()
+ } == expected_files
+ assert set(mm2_app_config.models_path.iterdir()) == existing_paths
+ assert mm2_installer.record_store.all_models() == []
+
+
+def test_install_registration_failure_preserves_complete_recoverable_files(
+ mm2_installer: ModelInstallServiceBase,
+ diffusers_dir: Path,
+ mm2_app_config: InvokeAIAppConfig,
+) -> None:
+ """A database made read-only after startup can reject registration after file moves succeed."""
+ expected_files = {
+ path.relative_to(diffusers_dir): path.read_bytes() for path in diffusers_dir.rglob("*") if path.is_file()
+ }
+ existing_paths = set(mm2_app_config.models_path.iterdir())
+
+ store = mm2_installer.record_store
+ assert isinstance(store, ModelRecordServiceSQL)
+ # Exercise a genuine SQLite write rejection without changing permissions on any real user database.
+ with store._db.transaction() as cursor:
+ cursor.execute("PRAGMA query_only = ON")
+ try:
+ with pytest.raises(sqlite3.OperationalError, match="readonly database"):
+ mm2_installer.install_path(diffusers_dir)
+ finally:
+ with store._db.transaction() as cursor:
+ cursor.execute("PRAGMA query_only = OFF")
+
+ assert mm2_installer.record_store.all_models() == []
+ new_paths = set(mm2_app_config.models_path.iterdir()) - existing_paths
+ # A rollback to the source or a complete unregistered managed folder both preserve recovery.
+ recoverable_roots = [diffusers_dir, *new_paths]
+ complete_copies = [
+ root
+ for root in recoverable_roots
+ if {path.relative_to(root): path.read_bytes() for path in root.rglob("*") if path.is_file()} == expected_files
+ ]
+ assert len(complete_copies) == 1
+ recovered_key = mm2_installer.register_path(complete_copies[0])
+ assert mm2_installer.record_store.get_model(recovered_key).key == recovered_key
+
+
def test_rename(
mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig
) -> None:
diff --git a/tests/app/services/model_records/test_model_records_sql.py b/tests/app/services/model_records/test_model_records_sql.py
index 9307e35e0c..68e28a3017 100644
--- a/tests/app/services/model_records/test_model_records_sql.py
+++ b/tests/app/services/model_records/test_model_records_sql.py
@@ -139,24 +139,37 @@ def test_update_changing_type_drops_stale_format_and_variant(store: ModelRecordS
assert isinstance(new_config, TextLLM_Diffusers_Config)
-def test_model_records_rejects_invalid_attr_changes(store: ModelRecordServiceBase):
- config = example_ti_config("key1")
- store.add_model(config)
- config = store.get_model("key1")
- # upcast_attention is an invalid field for TIs
- changes = ModelRecordChanges(upcast_attention=True)
[email protected]("allow_class_change", [False, True])
+def test_rejected_update_preserves_the_complete_stored_record(
+ store: ModelRecordServiceBase, allow_class_change: bool
+) -> None:
+ original = example_ti_config("key1")
+ store.add_model(original)
+ before = store.get_model(original.key)
+ # A classification edit may combine valid metadata changes with an incompatible model format.
+ changes = ModelRecordChanges(name="edited name", path="/tmp/edited.bin", format=ModelFormat.Diffusers)
+
with pytest.raises(ValidationError):
- store.update_model(config.key, changes)
+ store.update_model(original.key, changes, allow_class_change=allow_class_change)
+ after = store.get_model(original.key)
+ assert type(after) is type(before)
+ assert after.model_dump() == before.model_dump()
+
+
+def test_rejected_class_change_preserves_the_original_record(store: ModelRecordServiceBase) -> None:
+ original = example_ti_config("key1")
+ store.add_model(original)
+ before = store.get_model(original.key)
+ # Correcting a model's classification can leave an explicitly incompatible format in the submitted edit.
+ changes = ModelRecordChanges(type=ModelType.LoRA, format=ModelFormat.EmbeddingFile, name="edited name")
-def test_model_records_rejects_invalid_attr_changes_that_change_class(store: ModelRecordServiceBase):
- config = example_ti_config("key1")
- store.add_model(config)
- config = store.get_model("key1")
- # upcast_attention is an invalid field for TIs
- changes = ModelRecordChanges(upcast_attention=True)
with pytest.raises(ValidationError):
- store.update_model(config.key, changes)
+ store.update_model(original.key, changes, allow_class_change=True)
+
+ after = store.get_model(original.key)
+ assert isinstance(after, TI_File_SD1_Config)
+ assert after.model_dump() == before.model_dump()
def test_unknown_key(store: ModelRecordServiceBase):
diff --git a/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py b/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py
new file mode 100644
index 0000000000..15a566347e
--- /dev/null
+++ b/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py
@@ -0,0 +1,64 @@
+"""Tests for SQLite model relationship storage contracts."""
+
+import logging
+import sqlite3
+
+import pytest
+
+from invokeai.app.services.model_relationship_records.model_relationship_records_sqlite import (
+ SqliteModelRelationshipRecordStorage,
+)
+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
+
+
+def storage() -> SqliteModelRelationshipRecordStorage:
+ db = SqliteDatabase(db_path=None, logger=logging.getLogger(__name__))
+ with db.transaction() as cursor:
+ cursor.execute("CREATE TABLE models (id TEXT PRIMARY KEY NOT NULL)")
+ cursor.execute(
+ """
+ CREATE TABLE model_relationships (
+ model_key_1 TEXT NOT NULL,
+ model_key_2 TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
+ PRIMARY KEY (model_key_1, model_key_2),
+ FOREIGN KEY (model_key_1) REFERENCES models(id) ON DELETE CASCADE,
+ FOREIGN KEY (model_key_2) REFERENCES models(id) ON DELETE CASCADE
+ )
+ """
+ )
+ cursor.executemany("INSERT INTO models (id) VALUES (?)", [("model-a",), ("model-b",)])
+ return SqliteModelRelationshipRecordStorage(db)
+
+
+def test_add_relationship_is_bidirectional_and_duplicate_is_idempotent(
+ storage: SqliteModelRelationshipRecordStorage,
+) -> None:
+ storage.add_model_relationship("model-b", "model-a")
+
+ assert storage.get_related_model_keys("model-a") == ["model-b"]
+ assert storage.get_related_model_keys("model-b") == ["model-a"]
+
+ storage.add_model_relationship("model-a", "model-b")
+ assert storage.get_related_model_keys("model-a") == ["model-b"]
+ assert storage.get_related_model_keys("model-b") == ["model-a"]
+
+
+def test_add_relationship_rejects_missing_model_key(storage: SqliteModelRelationshipRecordStorage) -> None:
+ with pytest.raises(sqlite3.IntegrityError, match="FOREIGN KEY"):
+ storage.add_model_relationship("model-a", "missing-model")
+
+
+def test_remove_missing_relationship_is_idempotent(storage: SqliteModelRelationshipRecordStorage) -> None:
+ storage.remove_model_relationship("model-a", "model-b")
+ assert storage.get_related_model_keys("model-a") == []
+
+
+def test_delete_model_cascades_relationship(storage: SqliteModelRelationshipRecordStorage) -> None:
+ storage.add_model_relationship("model-a", "model-b")
+ db = storage._db
+ with db.transaction() as cursor:
+ cursor.execute("DELETE FROM models WHERE id = ?", ("model-a",))
+
+ assert storage.get_related_model_keys("model-b") == []
diff --git a/tests/backend/model_manager/configs/test_flux_variant_detection.py b/tests/backend/model_manager/configs/test_flux_variant_detection.py
new file mode 100644
index 0000000000..5537e84696
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_flux_variant_detection.py
@@ -0,0 +1,36 @@
+"""Tests for FLUX variant detection boundaries."""
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.configs.main import _get_flux_variant
+from invokeai.backend.model_manager.taxonomy import FluxVariantType
+
+
+ ("input_key", "channels", "guidance", "expected"),
+ [
+ ("img_in.weight", 64, False, FluxVariantType.Schnell),
+ ("img_in.weight", 64, True, FluxVariantType.Dev),
+ ("model.diffusion_model.img_in.weight", 64, True, FluxVariantType.Dev),
+ ("img_in.weight", 384, True, FluxVariantType.DevFill),
+ ("model.diffusion_model.img_in.weight", 384, True, FluxVariantType.DevFill),
+ ],
+)
+def test_flux_variant_detection_supports_known_key_layouts(
+ input_key: str, channels: int, guidance: bool, expected: FluxVariantType
+) -> None:
+ state_dict = {input_key: torch.empty(1, channels)}
+ if guidance:
+ guidance_key = (
+ "model.diffusion_model.guidance_in.out_layer.weight"
+ if input_key.startswith("model.")
+ else "guidance_in.out_layer.weight"
+ )
+ state_dict[guidance_key] = torch.empty(1)
+
+ assert _get_flux_variant(state_dict) is expected
+
+
+def test_flux_variant_detection_reports_missing_input_channels() -> None:
+ assert _get_flux_variant({"double_blocks.0.img_attn.norm.key_norm.scale": torch.empty(1)}) is None
diff --git a/tests/backend/model_manager/configs/test_ip_adapter_config.py b/tests/backend/model_manager/configs/test_ip_adapter_config.py
new file mode 100644
index 0000000000..5c5989b1df
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_ip_adapter_config.py
@@ -0,0 +1,23 @@
+"""Tests for InvokeAI-format IP-Adapter probing."""
+
+from pathlib import Path
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
+from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI_SD1_Config
+
+
+ "metadata",
+ ["InvokeAI/ip_adapter_sd_image_encoder\n", " InvokeAI/ip_adapter_sd_image_encoder \r\n"],
+)
+def test_invokeai_ip_adapter_probe_normalizes_image_encoder_metadata(tmp_path: Path, metadata: str) -> None:
+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")
+ (tmp_path / "image_encoder.txt").write_text(metadata, encoding="utf-8")
+
+ result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)
+
+ assert isinstance(result.config, IPAdapter_InvokeAI_SD1_Config)
+ assert result.config.image_encoder_model_id == "InvokeAI/ip_adapter_sd_image_encoder"
diff --git a/tests/backend/model_manager/configs/test_vae_config.py b/tests/backend/model_manager/configs/test_vae_config.py
new file mode 100644
index 0000000000..16deb1f367
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_vae_config.py
@@ -0,0 +1,43 @@
+"""Tests for four-channel Diffusers VAE identification heuristics."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+
+
+ ("config", "name", "expected_base"),
+ [
+ (
+ {"_class_name": "AutoencoderKL", "scaling_factor": 0.18215, "sample_size": 512},
+ "vae",
+ BaseModelType.StableDiffusion1,
+ ),
+ (
+ {"_class_name": "AutoencoderKL", "scaling_factor": 0.13025, "sample_size": 1024},
+ "vae",
+ BaseModelType.StableDiffusionXL,
+ ),
+ (
+ {"_class_name": "AutoencoderKL", "scaling_factor": 0.5, "sample_size": 768},
+ "my-xl-vae",
+ BaseModelType.StableDiffusionXL,
+ ),
+ ],
+)
+def test_diffusers_vae_known_base_detection(
+ tmp_path: Path, config: dict, name: str, expected_base: BaseModelType
+) -> None:
+ model_path = tmp_path / name
+ model_path.mkdir()
+ (model_path / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ (model_path / "diffusion_pytorch_model.safetensors").touch()
+
+ result = ModelConfigFactory.from_model_on_disk(model_path, allow_unknown=False)
+
+ assert result.config is not None
+ assert result.config.base is expected_base
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
index cedc9f6b95..81309713ca 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
@@ -505,3 +505,62 @@ def test_cached_model_partial_load_chunked_matches_uncapped_budget(
# Still partially loaded, so autocasting remains enabled after settling too.
assert model.linear1.is_device_autocasting_enabled()
assert model.linear2.is_device_autocasting_enabled()
+
+
[email protected]("operation", ["load", "unload"])
+def test_partial_transfer_failure_invalidates_vram_accounting(operation: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A failed transfer must not leave a stale cached VRAM byte count."""
+ if operation == "load":
+ model = torch.nn.Linear(4, 4)
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ transfer = cached_model.partial_load_to_vram
+ else:
+ model = torch.nn.Linear(4, 4, device="meta")
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ transfer = cached_model.partial_unload_from_vram
+
+ cached_model.cur_vram_bytes()
+
+ def fail_transfer(*args, **kwargs):
+ raise RuntimeError("simulated transfer failure")
+
+ monkeypatch.setattr(cached_model, "_load_state_dict_with_device_conversion", fail_transfer)
+
+ with pytest.raises(RuntimeError, match="simulated transfer failure"):
+ transfer(cached_model.total_bytes())
+
+ assert cached_model._cur_vram_bytes is None
+
+
[email protected]("operation", ["load", "unload"])
+def test_transfer_failure_after_one_module_recounts_actual_residency(operation: str, monkeypatch: pytest.MonkeyPatch):
+ """OOM/device errors can interrupt the module-by-module transfer after earlier modules changed devices."""
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 2))
+ first_bytes = sum(param.numel() * param.element_size() for param in model[0].parameters())
+ second_bytes = sum(param.numel() * param.element_size() for param in model[1].parameters())
+ cached_model = CachedModelWithPartialLoad(
+ model=model, compute_device=torch.device("meta"), keep_ram_copy=operation == "unload"
+ )
+ if operation == "unload":
+ # Retain genuine CPU weights before simulating initial accelerator residency.
+ model.to("meta")
+ transfer = cached_model.partial_unload_from_vram
+ assert cached_model.cur_vram_bytes() == first_bytes + second_bytes
+ expected_devices = ("cpu", "meta")
+ expected_bytes = second_bytes
+ else:
+ transfer = cached_model.partial_load_to_vram
+ assert cached_model.cur_vram_bytes() == 0
+ expected_devices = ("meta", "cpu")
+ expected_bytes = first_bytes
+
+ def fail_second_module(*args, **kwargs):
+ raise RuntimeError("second module transfer failed")
+
+ monkeypatch.setattr(model[1], "_load_from_state_dict", fail_second_module)
+
+ with pytest.raises(RuntimeError, match="second module transfer failed"):
+ transfer(first_bytes + second_bytes)
+
+ assert tuple(module.weight.device.type for module in model) == expected_devices
+ assert cached_model.cur_vram_bytes() == expected_bytes
diff --git a/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py b/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py
new file mode 100644
index 0000000000..7c632d8f69
--- /dev/null
+++ b/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py
@@ -0,0 +1,56 @@
+"""Tests for malformed dynamic Diffusers loader configuration."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
+
+
+ "config",
+ [
+ {},
+ {"_class_name": "NotARealDiffusersClass"},
+ {"architectures": ["NotARealTransformersClass"]},
+ {"_class_name": 123},
+ {"architectures": []},
+ {"architectures": "AutoModel"},
+ {"architectures": [123]},
+ {"architectures": {}},
+ {"_class_name": "ConfigMixin"},
+ ],
+)
+def test_generic_diffusers_loader_rejects_invalid_class_metadata(tmp_path: Path, config: dict) -> None:
+ (tmp_path / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ loader = object.__new__(GenericDiffusersLoader)
+
+ with pytest.raises(ValueError, match="class|config|model"):
+ loader.get_hf_load_class(tmp_path)
+
+
+def test_generic_diffusers_loader_rejects_invalid_json(tmp_path: Path) -> None:
+ """An interrupted write or a manually edited config must fail before model loading."""
+ (tmp_path / "config.json").write_text('{"_class_name":', encoding="utf-8")
+ loader = object.__new__(GenericDiffusersLoader)
+
+ with pytest.raises(OSError, match="config|JSON|json"):
+ loader.get_hf_load_class(tmp_path)
+
+
+def test_generic_diffusers_loader_accepts_a_real_loadable_class(tmp_path: Path) -> None:
+ from diffusers import AutoencoderKL
+
+ (tmp_path / "config.json").write_text(json.dumps({"_class_name": "AutoencoderKL"}), encoding="utf-8")
+ loader = object.__new__(GenericDiffusersLoader)
+
+ assert loader.get_hf_load_class(tmp_path) is AutoencoderKL
+
+
+def test_generic_diffusers_loader_rejects_non_object_config(tmp_path: Path) -> None:
+ (tmp_path / "config.json").write_text('["AutoencoderKL"]', encoding="utf-8")
+ loader = object.__new__(GenericDiffusersLoader)
+
+ with pytest.raises(ValueError, match="config|object"):
+ loader.get_hf_load_class(tmp_path)