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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Merge main into fix/stale-inflight-model-load
Lincoln Stein7e6d17a81660
diff --cc invokeai/app/api/routers/model_manager.pyindex dc3238a3ca,39a26bd25b..c64f4ffc20--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@@ -28,8 -29,12 +29,13 @@@ from invokeai.app.services.model_imagesModelImageFileDeleteException,ModelImageFileNotFoundException,)- from invokeai.app.services.model_install.model_install_common import ModelInstallJob+ from invokeai.app.services.model_install.model_install_common import (+ InstallCancellationConflictError,+ InstallDownloadConflictError,+ InstallRecoveryRequiredError,+ ModelInstallJob,+ )+from invokeai.app.services.model_load.model_load_common import load_settings_changedfrom invokeai.app.services.model_records import (InvalidModelException,ModelRecordChanges,@@@ -502,9 -510,9 +511,11 @@@ def _reidentify_model(key: str) -> AnyMresult.config.source = config.sourceresult.config.source_type = config.source_type- # The probe resets load-affecting settings (cpu_only, default_settings), so in-flight loads must re-check.- updated = ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)- _invalidate_model_load_caches(config.key, config, updated)++ # The probe can reset load-affecting settings (cpu_only, default_settings), so in-flight loads must re-check.+ with ApiDependencies.invoker.services.model_manager.load.record_edit(config.key):- return ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)++ updated = ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)++ _invalidate_model_load_caches(config.key, config, updated)+ return updatedclass FoundModel(BaseModel):@@@ -701,6 -695,65 +698,20 @@@ async def update_model_recordreturn await asyncio.to_thread(_update_model_record, key, changes)-_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")-_MODEL_METADATA_FIELDS: tuple[str, ...] = (- "name",- "description",- "cover_image",- "source",- "source_type",- "source_api_response",- "source_url",- "trigger_phrases",-)---def _model_load_fingerprint(config: AnyModelConfig) -> dict[str, Any]:- """Return record values whose change can make a cached model instance stale."""- if model_dump := getattr(config, "model_dump", None):- fingerprint = model_dump(mode="python")- else:- fingerprint = vars(config).copy()- for field in _MODEL_METADATA_FIELDS:- fingerprint.pop(field, None)-- # Keep hash and file_size: re-identification recomputes them from disk, and a changed value can mean- # the bytes at an unchanged path no longer match the loaded module.-- default_settings = fingerprint.pop("default_settings", None)- fingerprint["default_settings"] = {- field: default_settings.get(field)- if isinstance(default_settings, dict)- else getattr(default_settings, field, None)- for field in _LOAD_AFFECTING_SETTINGS- }- return fingerprint---def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:- """Return True if any setting that influences how the model is loaded changed.-- Such settings are read by the loader during `_load_model` and baked into the resulting- nn.Module, so a cached entry built under the old value must be evicted for the change- to take effect.- """- return _model_load_fingerprint(previous) != _model_load_fingerprint(updated)--+ def _invalidate_model_load_caches(key: str, previous: AnyModelConfig, updated: AnyModelConfig) -> None:+ """Drop cached instances when a record change affects how the model is loaded."""- if not _load_settings_changed(previous, updated):++ if not load_settings_changed(previous, updated):+ return+ services = ApiDependencies.invoker.services+ # Prevent a concurrent load from re-registering state built from the previous model identity.+ with MODEL_LOAD_LOCK.write_lock():+ dropped = sum(cache.drop_model(key) for cache in services.model_manager.load.ram_caches.values())+ if dropped:+ services.logger.info(+ f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."+ )++@model_manager_router.get("/i/{key}/image",operation_id="get_model_image",diff --cc invokeai/app/services/model_load/model_load_common.pyindex cca3c2ecc2,0000000000..7b2e250c4fmode 100644,000000..100644--- a/invokeai/app/services/model_load/model_load_common.py+++ b/invokeai/app/services/model_load/model_load_common.py@@@ -1,23 -1,0 +1,58 @@@+"""Shared rules for when a model record change invalidates loaded instances of that model."""+++from pathlib import Path++from typing import Any, Optional+++from invokeai.backend.model_manager.configs.factory import AnyModelConfig++_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")++_MODEL_METADATA_FIELDS: tuple[str, ...] = (++ "name",++ "description",++ "cover_image",++ "source",++ "source_type",++ "source_api_response",++ "source_url",++ "trigger_phrases",++)++++++def _model_load_fingerprint(config: AnyModelConfig, models_path: Optional[Path]) -> dict[str, Any]:++ """Return record values whose change can make a cached model instance stale."""++ if model_dump := getattr(config, "model_dump", None):++ fingerprint = model_dump(mode="python")++ else:++ fingerprint = vars(config).copy()++ for field in _MODEL_METADATA_FIELDS:++ fingerprint.pop(field, None)++++ # Keep hash and file_size: re-identification recomputes them from disk, and a changed value can mean++ # the bytes at an unchanged path no longer match the loaded module.++++ if models_path is not None and fingerprint.get("path") is not None:++ # The loader rewrites `config.path` to an absolute path in place; a config object it has already++ # loaded from must still match its stored, models-relative record.++ fingerprint["path"] = (models_path / fingerprint["path"]).resolve()++++ default_settings = fingerprint.pop("default_settings", None)++ fingerprint["default_settings"] = {++ field: default_settings.get(field)++ if isinstance(default_settings, dict)++ else getattr(default_settings, field, None)++ for field in _LOAD_AFFECTING_SETTINGS++ }++ return fingerprint++- def load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:- """Return True if any setting that influences how the model is loaded changed.++def load_settings_changed(++ previous: AnyModelConfig, updated: AnyModelConfig, models_path: Optional[Path] = None++) -> bool:++ """Return True if anything that influences how the model is loaded changed.+- Such settings are read by the loader during `_load_model` and baked into the resulting- nn.Module, so a cached entry built under the old value must be evicted for the change- to take effect, and a load that started from the old value must not be admitted after- that eviction.++ Such values are read by the loader during `_load_model` and baked into the resulting nn.Module, so a++ cached entry built under the old value must be evicted for the change to take effect, and a load that++ started from the old value must not be admitted after that eviction. Pass `models_path` to compare++ paths after resolving them against it.+ """- if getattr(previous, "cpu_only", None) != getattr(updated, "cpu_only", None):- return True- previous_settings = getattr(previous, "default_settings", None)- updated_settings = getattr(updated, "default_settings", None)- for field in _LOAD_AFFECTING_SETTINGS:- if getattr(previous_settings, field, None) != getattr(updated_settings, field, None):- return True- return False++ return _model_load_fingerprint(previous, models_path) != _model_load_fingerprint(updated, models_path)diff --cc invokeai/app/services/model_load/model_load_default.pyindex 87aa0a3e92,4d519e381d..a451fac69f--- a/invokeai/app/services/model_load/model_load_default.py+++ b/invokeai/app/services/model_load/model_load_default.py@@@ -147,43 -96,12 +147,43 @@@ class ModelLoadService(ModelLoadServiceapp_config=self._app_config,logger=self._logger,ram_cache=self.ram_cache,- ).load_model(model_config, submodel_type)+ )+ if hasattr(self, "_invoker") and isinstance(loader, ModelLoader):+ loader.config_check = self._check_config+ return loader.load_model(model_config, submodel_type)++ def record_edit(self, key: str) -> ContextManager[None]:+ return self._record_edits.edit(key)++ def _check_config(self, config: AnyModelConfig) -> Callable[[], bool]:+ """Check `config` against its record; the returned callable completes the check under MODEL_LOAD_LOCK.++ The record is read here, before the lock, so a long DB transaction (e.g. VACUUM) stalls only this+ load and not every MODEL_LOAD_LOCK user. An edit brackets its commit and its cache invalidation+ with `record_edit()`, so an edit that commits after this read was either in progress when the+ snapshot below was taken or bumped the generation since; only then is the record read again,+ under the lock, as the invalidation that follows the commit also takes that lock.+ """+ generation, edit_in_progress = self._record_edits.snapshot(config.key)+ current = self._config_is_current(config)- if hasattr(self, "_invoker"):- self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")+ def still_current() -> bool:+ if not current:+ return False+ if edit_in_progress or self._record_edits.snapshot(config.key)[0] != generation:+ return self._config_is_current(config)+ return True- return loaded_model+ return still_current++ def _config_is_current(self, config: AnyModelConfig) -> bool:+ """Whether `config` still loads the same model as the stored record for its key."""+ try:+ current = self._invoker.services.model_manager.store.get_model(config.key)+ except UnknownModelException:+ # Nothing newer to load instead, and the key can no longer be requested.+ return True- return not load_settings_changed(config, current)++ return not load_settings_changed(config, current, models_path=self._app_config.models_path)def load_model_from_path(self, model_path: Path, loader: Optional[Callable[[Path], AnyModel]] = Nonediff --cc tests/app/routers/test_update_model_record_cache_invalidation.pyindex 0000000000,928308c3da..f0cedc6189mode 000000,100644..100644--- a/tests/app/routers/test_update_model_record_cache_invalidation.py+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py@@@ -1,0 -1,362 +1,298 @@@-"""Tests for `_load_settings_changed` — the predicate that decides whether to evict cached-model entries after an `update_model_record` call. Settings like `fp8_storage` and `cpu_only`-are baked into the loaded nn.Module at load time, so toggling them silently has no effect-until the cached entry is evicted. The predicate must catch changes to those settings while-ignoring changes that don't affect how the model loads (e.g. name, description).-"""++"""Model record edits and re-identification evict cached instances of the model exactly when the change++affects how it loads (see `test_model_load_common.py` for the predicate itself)."""+++import contextlib+ from pathlib import Path+ 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 _no_record_edit(_key: str) -> contextlib.AbstractContextManager[None]:++ return contextlib.nullcontext()+++++ 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,+ )++-def test_no_change_returns_false():- assert _load_settings_changed(_config(fp8=True), _config(fp8=True)) is False- assert _load_settings_changed(_config(fp8=None), _config(fp8=None)) is False---def test_fp8_storage_toggle_returns_true():- """The primary motivating case: a user toggling FP8 storage in the Model Manager must- drop the cached entry, otherwise inference keeps using the old (non-FP8) module."""- assert _load_settings_changed(_config(fp8=False), _config(fp8=True)) is True- assert _load_settings_changed(_config(fp8=True), _config(fp8=False)) is True- assert _load_settings_changed(_config(fp8=None), _config(fp8=True)) is True- assert _load_settings_changed(_config(fp8=True), _config(fp8=None)) is True---def test_cpu_only_toggle_returns_true():- """`cpu_only` is also read by the loader (in `_get_execution_device`) and baked into the- cache entry's execution device — toggling it after load is a silent no-op without eviction."""- assert _load_settings_changed(_config(cpu_only=False), _config(cpu_only=True)) is True- assert _load_settings_changed(_config(cpu_only=True), _config(cpu_only=None)) is True---def test_missing_default_settings_is_handled():- """default_settings can legitimately be None (e.g. a freshly identified config)."""- no_settings = SimpleNamespace(cpu_only=None, default_settings=None)- assert _load_settings_changed(no_settings, no_settings) is False- assert _load_settings_changed(no_settings, _config(fp8=True)) is True---def test_default_generation_steps_change_does_not_invalidate_model_cache():- """Generation defaults are read per invocation, not baked into the loaded model module."""- previous = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=20))- updated = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=40))-- assert _load_settings_changed(previous, updated) is False--[email protected]("field", ["fp8_storage", "cpu_only"])-def test_pydantic_nested_load_setting_changes_trigger_invalidation(field: str) -> None:- from pydantic import BaseModel-- from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings-- class PydanticConfig(BaseModel):- default_settings: MainModelDefaultSettings | None = None-- previous = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: False}))- updated = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: True}))-- assert _load_settings_changed(previous, updated) is True---def test_unrelated_field_does_not_trigger_invalidation():- """A config missing the fp8/cpu_only attributes entirely (e.g. a model type with no such- fields) must not falsely report a change."""- bare_a = SimpleNamespace()- bare_b = SimpleNamespace()- assert _load_settings_changed(bare_a, bare_b) is False--[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant", "hash", "file_size"])-def test_model_identity_changes_trigger_invalidation(field: str):- """Loader identity or changed on-disk content must evict a module loaded from the previous record."""- previous = _config(**{field: "old"})- updated = _config(**{field: "new"})- assert _load_settings_changed(previous, updated) is True--+ @pytest.mark.parametrize(+ "field",+ [+ "path",+ "base",+ "type",+ "format",+ "variant",+ "repo_variant",+ "name",+ "description",+ "cover_image",+ "source",+ "source_type",+ "source_api_response",+ "source_url",+ "trigger_phrases",+ ],+ )+ 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}),++ load=SimpleNamespace(record_edit=_no_record_edit, 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",+ "cover_image",+ "source",+ "source_type",+ "source_api_response",+ "source_url",+ "trigger_phrases",+ }:+ cache.drop_model.assert_not_called()+ else:+ cache.drop_model.assert_called_once_with("model-key")+++ def test_cache_invalidation_holds_model_load_write_lock(monkeypatch: pytest.MonkeyPatch) -> None:+ from contextlib import contextmanager++ previous = _config(path="old")+ updated = _config(path="new")+ inside_write_lock = False+ observed_drop_under_lock: list[bool] = []++ class TrackingModelLoadLock:+ @contextmanager+ def write_lock(self):+ nonlocal inside_write_lock+ inside_write_lock = True+ try:+ yield+ finally:+ inside_write_lock = False++ def drop_model(_key: str) -> int:+ observed_drop_under_lock.append(inside_write_lock)+ return 1++ cache = SimpleNamespace(drop_model=drop_model)+ services = SimpleNamespace(+ logger=MagicMock(),- model_manager=SimpleNamespace(load=SimpleNamespace(ram_caches={"cpu": cache})),++ model_manager=SimpleNamespace(load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={"cpu": cache})),+ )+ monkeypatch.setattr(model_manager_router, "MODEL_LOAD_LOCK", TrackingModelLoadLock())+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )++ model_manager_router._invalidate_model_load_caches("model-key", previous, updated)++ assert observed_drop_under_lock == [True]+++ @pytest.mark.parametrize(("field", "expected_eviction"), [("path", True), ("name", False), ("description", False)])+ def test_record_update_handles_real_cpu_cache_entries(+ field: str, expected_eviction: bool, monkeypatch: pytest.MonkeyPatch+ ):+ """Load-affecting edits drop all model entries; metadata edits retain cached entries."""+ import logging++ import torch++ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache++ previous = _config(**{field: "old"})+ updated = _config(**{field: "new"})+ record_store = SimpleNamespace(+ get_model=MagicMock(return_value=previous),+ update_model=MagicMock(return_value=updated),+ )+ caches = [+ ModelCache(+ execution_device_working_mem_gb=1,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=logging.getLogger("test.model_manager_cache_invalidation"),+ )+ for _ in range(2)+ ]+ try:+ for cache in caches:+ cache.put("model-key", torch.ones(2))+ cache.put("model-key:unet", torch.ones(2))+ cache.put("other-model", torch.ones(2))++ services = SimpleNamespace(+ logger=MagicMock(),+ model_manager=SimpleNamespace(+ store=record_store,- load=SimpleNamespace(ram_caches={"cpu": caches[0], "cpu:1": caches[1]}),++ load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={"cpu": caches[0], "cpu:1": caches[1]}),+ ),+ )+ 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)++ assert model_manager_router._update_model_record(key="model-key", changes=ModelRecordChanges()) is updated++ for cache in caches:+ assert ("model-key" not in cache._cached_models) is expected_eviction+ assert ("model-key:unet" not in cache._cached_models) is expected_eviction+ assert "other-model" in cache._cached_models+ finally:+ for cache in caches:+ cache.shutdown()+++ def test_reidentify_invalidates_caches_when_identification_changes_model_class(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ):+ """Re-probing can change loader identity just like an explicit model-record edit."""+ from types import SimpleNamespace++ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelSourceType, ModelType++ previous = SimpleNamespace(+ key="model-key",+ path="model.safetensors",+ name="Model",+ description="",+ cover_image=None,+ source="local-source",+ source_type=ModelSourceType.Path,+ image_encoder_model_id="custom/image-encoder",+ base=BaseModelType.StableDiffusion1,+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+ variant="old",+ cpu_only=False,+ default_settings=None,+ )+ identified = SimpleNamespace(+ key="model-key",+ path="model.safetensors",+ name="identified name",+ description="identified description",+ cover_image=None,+ source="new-source",+ source_type=ModelSourceType.Path,+ base=BaseModelType.StableDiffusionXL,+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+ variant="new",+ cpu_only=False,+ default_settings=None,+ )+ stored = SimpleNamespace(+ replace_model=MagicMock(return_value=identified), get_model=MagicMock(return_value=previous)+ )+ caches = [SimpleNamespace(drop_model=MagicMock(return_value=1)) for _ in range(2)]+ services = SimpleNamespace(+ model_manager=SimpleNamespace(- store=stored, load=SimpleNamespace(ram_caches={str(i): cache for i, cache in enumerate(caches)})++ store=stored,++ load=SimpleNamespace(++ record_edit=_no_record_edit, ram_caches={str(i): cache for i, cache in enumerate(caches)}++ ),+ ),+ configuration=SimpleNamespace(models_path=tmp_path / "models"),+ logger=MagicMock(),+ )+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )+ monkeypatch.setattr(model_manager_router, "ModelOnDisk", lambda _path: object())+ factory_overrides: dict[str, object] = {}++ def identify(_model_on_disk: object, override_fields: dict[str, object]) -> object:+ factory_overrides.update(override_fields)+ return SimpleNamespace(config=identified)++ monkeypatch.setattr(model_manager_router.ModelConfigFactory, "from_model_on_disk", identify)++ assert model_manager_router._reidentify_model("model-key") is identified+ assert factory_overrides["image_encoder_model_id"] == "custom/image-encoder"++ for cache in caches:+ cache.drop_model.assert_called_once_with("model-key")+++ def test_reidentify_preserves_ip_adapter_encoder_override_with_blank_metadata(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ import torch++ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+ from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI_SD1_Config+ from invokeai.backend.model_manager.taxonomy import ModelSourceType++ models_path = tmp_path / "models"+ model_path = models_path / "ip-adapter"+ model_path.mkdir(parents=True)+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, model_path / "ip_adapter.bin")+ (model_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")+ result = ModelConfigFactory.from_model_on_disk(+ model_path, override_fields={"image_encoder_model_id": "custom/image-encoder"}, allow_unknown=False+ )+ assert isinstance(result.config, IPAdapter_InvokeAI_SD1_Config)+ previous = result.config+ previous.key = "ip-adapter-key"+ previous.path = "ip-adapter"+ previous.name = "IP-Adapter"+ previous.source = "local-source"+ previous.source_type = ModelSourceType.Path++ store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)+ services = SimpleNamespace(- model_manager=SimpleNamespace(store=store, load=SimpleNamespace(ram_caches={})),++ model_manager=SimpleNamespace(store=store, load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={})),+ configuration=SimpleNamespace(models_path=models_path),+ logger=MagicMock(),+ )+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )++ updated = model_manager_router._reidentify_model("ip-adapter-key")++ assert isinstance(updated, IPAdapter_InvokeAI_SD1_Config)+ assert updated.image_encoder_model_id == "custom/image-encoder"diff --cc tests/app/services/model_load/test_model_load_common.pyindex b1133fdfe7,0000000000..4884b76277mode 100644,000000..100644--- a/tests/app/services/model_load/test_model_load_common.py+++ b/tests/app/services/model_load/test_model_load_common.py@@@ -1,54 -1,0 +1,98 @@@- """Tests for `load_settings_changed` — the predicate that decides both whether an `update_model_record`- call evicts cached model entries and whether a load that read the record before that edit may still be- admitted to the cache. Settings like `fp8_storage` and `cpu_only` are baked into the loaded nn.Module at- load time, so toggling them silently has no effect until the cached entry is evicted. The predicate must- catch changes to those settings while ignoring changes that don't affect how the model loads (e.g. name,++"""Tests for `load_settings_changed` — the predicate that decides both whether a model record change evicts++cached model entries and whether a load that read the record before that change may still be admitted to the++cache. Load-affecting values (e.g. `fp8_storage`, `cpu_only`, loader identity) are baked into the loaded++nn.Module at load time, so changing them silently has no effect until the cached entry is evicted. The++predicate must catch those changes while ignoring ones that don't affect how the model loads (e.g. name,+description).+"""+++from pathlib import Path+from types import SimpleNamespace+++import pytest+++from invokeai.app.services.model_load.model_load_common import load_settings_changed++- 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,+ )+++def test_no_change_returns_false():+ assert load_settings_changed(_config(fp8=True), _config(fp8=True)) is False+ assert load_settings_changed(_config(fp8=None), _config(fp8=None)) is False+++def test_fp8_storage_toggle_returns_true():+ """The primary motivating case: a user toggling FP8 storage in the Model Manager must+ drop the cached entry, otherwise inference keeps using the old (non-FP8) module."""+ assert load_settings_changed(_config(fp8=False), _config(fp8=True)) is True+ assert load_settings_changed(_config(fp8=True), _config(fp8=False)) is True+ assert load_settings_changed(_config(fp8=None), _config(fp8=True)) is True+ assert load_settings_changed(_config(fp8=True), _config(fp8=None)) is True+++def test_cpu_only_toggle_returns_true():+ """`cpu_only` is also read by the loader (in `_get_execution_device`) and baked into the+ cache entry's execution device — toggling it after load is a silent no-op without eviction."""+ assert load_settings_changed(_config(cpu_only=False), _config(cpu_only=True)) is True+ assert load_settings_changed(_config(cpu_only=True), _config(cpu_only=None)) is True+++def test_missing_default_settings_is_handled():+ """default_settings can legitimately be None (e.g. a freshly identified config)."""+ no_settings = SimpleNamespace(cpu_only=None, default_settings=None)+ assert load_settings_changed(no_settings, no_settings) is False+ assert load_settings_changed(no_settings, _config(fp8=True)) is True++++def test_default_generation_steps_change_does_not_invalidate_model_cache():++ """Generation defaults are read per invocation, not baked into the loaded model module."""++ previous = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=20))++ updated = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=40))++++ assert load_settings_changed(previous, updated) is False++++[email protected]("field", ["fp8_storage", "cpu_only"])++def test_pydantic_nested_load_setting_changes_trigger_invalidation(field: str) -> None:++ from pydantic import BaseModel++++ from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings++++ class PydanticConfig(BaseModel):++ default_settings: MainModelDefaultSettings | None = None++++ previous = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: False}))++ updated = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: True}))++++ assert load_settings_changed(previous, updated) is True+++++def test_unrelated_field_does_not_trigger_invalidation():+ """A config missing the fp8/cpu_only attributes entirely (e.g. a model type with no such+ fields) must not falsely report a change."""+ bare_a = SimpleNamespace()+ bare_b = SimpleNamespace()+ assert load_settings_changed(bare_a, bare_b) is False++++[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant", "hash", "file_size"])++def test_model_identity_changes_trigger_invalidation(field: str):++ """Loader identity or changed on-disk content must evict a module loaded from the previous record."""++ previous = _config(**{field: "old"})++ updated = _config(**{field: "new"})++ assert load_settings_changed(previous, updated) is True++++++def test_path_made_absolute_by_the_loader_matches_its_stored_record(tmp_path: Path):++ """The loader rewrites `config.path` in place; that must not read as a change against the record."""++ stored = _config(path="sd-1/main/model.safetensors")++ loaded_from = _config(path=str(tmp_path / "sd-1/main/model.safetensors"))++++ assert load_settings_changed(loaded_from, stored, models_path=tmp_path) is False++ assert load_settings_changed(loaded_from, _config(path="sd-1/main/other.safetensors"), models_path=tmp_path)diff --cc tests/app/services/model_load/test_stale_model_load_fence.pyindex 2d68afd01d,0000000000..3e70e575d1mode 100644,000000..100644--- a/tests/app/services/model_load/test_stale_model_load_fence.py+++ b/tests/app/services/model_load/test_stale_model_load_fence.py@@@ -1,276 -1,0 +1,278 @@@+"""A load that read a model record before a load-affecting edit must not repopulate the cache after+that edit's invalidation; later loads must build from the updated record."""++import threading+import time+from pathlib import Path+from types import SimpleNamespace+from typing import Callable, Optional++import pytest+import torch++from invokeai.app.services.config import InvokeAIAppConfig+from invokeai.app.services.model_load.model_load_default import ModelLoadService+from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL+from invokeai.backend.model_manager.configs.factory import AnyModelConfig+from invokeai.backend.model_manager.configs.siglip import SigLIP_Diffusers_Config+from invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader, StaleModelConfigError+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK+from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType+from invokeai.backend.util.logging import InvokeAILogger+from tests.fixtures.sqlite_database import create_mock_sqlite_database++KEY = "siglip-key"+++class _RecordingLoader(ModelLoader):+ """Builds a tiny module and records the `cpu_only` value each construction was built from."""++ built_from: list[Optional[bool]] = []++ def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:+ self.built_from.append(getattr(config, "cpu_only", None))+ return torch.nn.Linear(2, 2)+++class _Registry:+ @classmethod+ def get_implementation(cls, config: AnyModelConfig, submodel_type: Optional[SubModelType]):+ return _RecordingLoader, config, submodel_type+++class _LoadEvents:+ """Records the model load events in order, as (event, model name)."""++ def __init__(self) -> None:+ self.log: list[tuple[str, str]] = []++ def emit_model_load_started(self, config: AnyModelConfig, submodel_type, user_id: str) -> None:+ self.log.append(("started", config.name))++ def emit_model_load_complete(self, config: AnyModelConfig, submodel_type, user_id: str) -> None:+ self.log.append(("complete", config.name))+++def harness(tmp_path: Path):+ _RecordingLoader.built_from = []- app_config = InvokeAIAppConfig(use_memory_db=True)++ app_config = InvokeAIAppConfig(use_memory_db=True, models_dir=tmp_path)+ logger = InvokeAILogger.get_logger()+ store = ModelRecordServiceSQL(create_mock_sqlite_database(app_config, logger), logger)+ model_dir = tmp_path / "siglip"+ model_dir.mkdir()+ store.add_model(+ SigLIP_Diffusers_Config(- key=KEY, path=str(model_dir), name="siglip", hash="abc", file_size=1, source="test", source_type="path"++ key=KEY, path="siglip", name="siglip", hash="abc", file_size=1, source="test", source_type="path"+ )+ )+ cache = ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=True,+ max_ram_cache_size_gb=1.0,+ max_vram_cache_size_gb=0.0,+ execution_device="cpu",+ logger=logger,+ # Keep the process-global weight store out of it, so no other test's model can be adopted.+ shared_cpu_weights=None,+ )+ service = ModelLoadService(app_config=app_config, ram_cache=cache, registry=_Registry) # type: ignore[arg-type]+ events = _LoadEvents()+ service.start(SimpleNamespace(services=SimpleNamespace(events=events, model_manager=SimpleNamespace(store=store)))) # type: ignore[arg-type]+ return service, store, cache, events+++def _edit_and_invalidate(+ service: ModelLoadService, store: ModelRecordServiceSQL, cache: ModelCache, changes: ModelRecordChanges+) -> None:+ """The record edit followed by the cache drop, as `update_model_record` performs them."""+ with service.record_edit(KEY):+ store.update_model(KEY, changes=changes, allow_class_change=True)+ with MODEL_LOAD_LOCK.write_lock():+ cache.drop_model(KEY)+++def _is_cached(cache: ModelCache) -> bool:+ try:+ cache.get(KEY)+ except IndexError:+ return False+ return True+++def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record(harness):+ service, store, cache, events = harness+ stale = store.get_model(KEY)++ _edit_and_invalidate(service, store, cache, ModelRecordChanges(cpu_only=True))++ loaded = service.load_model(stale)+ assert loaded.config.cpu_only is True+ assert _RecordingLoader.built_from == [True]+ assert _is_cached(cache)+ # One load as far as the UI can tell: a retry that re-announced itself would leave a load showing.+ assert events.log == [("started", "siglip"), ("complete", "siglip")]+++def test_load_from_record_read_before_metadata_only_edit_still_loads(harness):+ service, store, cache, _ = harness+ previous = store.get_model(KEY)++ # A rename does not invalidate the cache, so nothing fences a load that read the old name.+ store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))++ service.load_model(previous)+ assert _RecordingLoader.built_from == [None]+ assert _is_cached(cache)+++def _run_with_edit_while_queued_on_construction_lock(+ service: ModelLoadService, store: ModelRecordServiceSQL, cache: ModelCache, load: Callable[[], object]+) -> object:+ """The #9674 ordering: `load` reads a current record, then waits for the construction lock while+ a `cpu_only` edit commits and invalidates under it. Returns what `load` returned or raised."""+ outcome: list[object] = []++ def run() -> None:+ try:+ outcome.append(load())+ except BaseException as e:+ outcome.append(e)++ loader = threading.Thread(target=run)+ with MODEL_LOAD_LOCK.write_lock():+ loader.start()+ deadline = time.monotonic() + 10+ while MODEL_LOAD_LOCK._writers_waiting == 0:+ assert time.monotonic() < deadline, "loader never queued for the construction lock"+ time.sleep(0.001)+ with service.record_edit(KEY):+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))+ cache.drop_model(KEY)+ loader.join(timeout=10)+ assert len(outcome) == 1+ return outcome[0]+++def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_updated_record(harness):+ service, store, cache, events = harness++ outcome = _run_with_edit_while_queued_on_construction_lock(+ service, store, cache, lambda: service.load_model(store.get_model(KEY))+ )++ assert isinstance(outcome, LoadedModel)+ assert outcome.config.cpu_only is True+ # Built once, from the updated record: the stale construction never ran.+ assert _RecordingLoader.built_from == [True]+ # One load as far as the UI can tell: a retry that re-announced itself would leave a load showing.+ assert events.log == [("started", "siglip"), ("complete", "siglip")]+++def test_edit_committed_while_load_waits_but_invalidating_after_it_is_not_built_from_the_old_record(harness):+ """The load reads a current record and queues behind an unrelated construction; the edit commits+ meanwhile but reaches its invalidation only after the load holds the construction lock."""+ service, store, cache, _ = harness+ outcome: list[LoadedModel] = []+ loader = threading.Thread(target=lambda: outcome.append(service.load_model(store.get_model(KEY))))++ with service.record_edit(KEY):+ with MODEL_LOAD_LOCK.write_lock(): # an unrelated construction in progress+ loader.start()+ deadline = time.monotonic() + 10+ while MODEL_LOAD_LOCK._writers_waiting == 0:+ assert time.monotonic() < deadline, "loader never queued for the construction lock"+ time.sleep(0.001)+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))+ loader.join(timeout=10)+ with MODEL_LOAD_LOCK.write_lock():+ cache.drop_model(KEY)++ assert len(outcome) == 1+ assert outcome[0].config.cpu_only is True+ assert _RecordingLoader.built_from == [True]+++def test_config_object_reused_after_eviction_still_loads(harness):+ """The loader rewrites `config.path` to an absolute path in place; a service that keeps its config+ object across loads must not see that as a load-affecting edit."""+ service, store, cache, _ = harness+ config = store.get_model(KEY)+ # Use it once so its first-use hold is released and the drop below evicts it outright.+ with service.load_model(config):+ pass+ with MODEL_LOAD_LOCK.write_lock():+ cache.drop_model(KEY)+++ # Checked directly: a spurious rejection would otherwise be hidden by the retry.++ assert service._config_is_current(config)+ service.load_model(config)+ assert _RecordingLoader.built_from == [None, None]+++def test_record_superseded_again_during_retry_raises(harness, monkeypatch):+ service, store, _, _ = harness+ fence_checks: list[str] = []++ def never_current(config: AnyModelConfig) -> bool:+ fence_checks.append(config.key)+ return False++ monkeypatch.setattr(service, "_config_is_current", never_current)++ with pytest.raises(StaleModelConfigError):+ service.load_model(store.get_model(KEY))+ assert fence_checks == [KEY, KEY]+ assert _RecordingLoader.built_from == []+++def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold_the_model_load_lock(+ harness, monkeypatch+):+ """A long DB transaction (e.g. VACUUM) that starts after a cold load read its record, while that load+ waits for the construction lock, must not leave the load holding MODEL_LOAD_LOCK while it waits on the+ database: unrelated MODEL_LOAD_LOCK users, such as other devices' VRAM moves, would stall with it."""+ service, store, cache, _ = harness+ config = store.get_model(KEY)+ record_reads = threading.Semaphore(0)+ store_get_model = store.get_model++ def get_model(key: str) -> AnyModelConfig:+ record_reads.release()+ return store_get_model(key)++ monkeypatch.setattr(store, "get_model", get_model)+ loads: list[LoadedModel] = []+ acquired = threading.Event()++ def take_model_load_lock() -> None:+ with MODEL_LOAD_LOCK.write_lock():+ acquired.set()++ loader = threading.Thread(target=lambda: loads.append(service.load_model(config)))+ other = threading.Thread(target=take_model_load_lock)+ with MODEL_LOAD_LOCK.write_lock(): # an unrelated construction in progress+ loader.start()+ assert record_reads.acquire(timeout=10)+ deadline = time.monotonic() + 10+ while MODEL_LOAD_LOCK._writers_waiting == 0:+ assert time.monotonic() < deadline, "loader never queued for the construction lock"+ time.sleep(0.001)+ store._db._lock.acquire() # the transaction starts; VACUUM holds this for its whole run+ try:+ # The loader now holds the construction lock: it either finishes without the database, or reads+ # its record again under the lock and blocks there.+ deadline = time.monotonic() + 10+ while loader.is_alive() and not record_reads.acquire(timeout=0.01):+ assert time.monotonic() < deadline, "loader neither finished nor read its record again"+ other.start()+ lock_was_free = acquired.wait(timeout=5)+ finally:+ store._db._lock.release()+ loader.join(timeout=10)+ other.join(timeout=10)++ assert lock_was_free+ assert len(loads) == 1+ assert _is_cached(cache)