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(model-manager): apply model record changes in the model manager service (#9941)

Josh Corbett42ec1ade109a
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index e16d973cca..a6140f762a 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -996,7 +996,7 @@ The optional second argument, `subtype` is a `SubModelType` string enum, such as
The optional third argument, `context` can be provided by an invocation to trigger model load event reporting. See below for details.
-If the model has to be built (it is not in the calling device's cache) and its record was edited in a way that changes how it loads (for example its `cpu_only` or `fp8_storage` setting) after the caller read `model_config`, `load_model()` does not cache a model built from the superseded record: it reads the record again and loads that instead. The same applies when the model's files are missing because it was moved and its record updated to the new path. If the record changes again during that retry, it raises `StaleModelConfigError`. Code that writes load-affecting fields of a model record must do so inside `ModelLoadService.record_edit(key)` (see its docstring).
+If the model has to be built (it is not in the calling device's cache) and its record was edited in a way that changes how it loads (for example its `cpu_only` or `fp8_storage` setting) after the caller read `model_config`, `load_model()` does not cache a model built from the superseded record: it reads the record again and loads that instead. The same applies when the model's files are missing because it was moved and its record updated to the new path. If the record changes again during that retry, it raises `StaleModelConfigError`. Code that writes a model record in a way that may change how it loads must do so through `ModelLoadService.apply_record_change(key, write)`: it brackets the write so overlapping loads are re-checked, compares the record before and after the same way the load check does, and when they differ drops the model's entries from each device cache under `MODEL_LOAD_LOCK`. A write that raises an `Exception` may have committed first, so the record as stored is read back and judged the same way before the exception propagates; if it cannot be read back, the change counts as load-affecting. An interrupt such as `KeyboardInterrupt` propagates without the read-back or any drop; loads that overlapped the write are still re-checked. `ModelManagerService.update_model_record()` and `ModelManagerService.reidentify_model()` write records this way.
The returned `LoadedModel` object contains a copy of the configuration record returned by the model record`get_model()` method, as well as the in-memory loaded model:
@@ -1190,6 +1190,14 @@ assert len(configs) > 0
loaded_model = mm.load.load_model(configs[0])
```
+### mm.update_model_record(key, changes) -> AnyModelConfig
+
+Applies a `ModelRecordChanges` to the model's record, allowing its config class to change, and returns the stored result. When the change affects how the model loads (for example its path, format, `cpu_only` or `fp8_storage`), every cached instance of the model is dropped so its next load rebuilds. Raises `UnknownModelException` for an unknown key and `ValueError` for a change the record cannot take. Use this rather than `mm.store.update_model()` for changes that may affect loading.
+
+### mm.reidentify_model(key) -> AnyModelConfig
+
+Identifies the model's files again and replaces its record with the result, keeping the name, description, cover image, trigger phrases, install source and CPU/FP8 preferences. The install source and an IP-Adapter's `image_encoder_model_id` are passed to identification, since the files alone may not name them. Cached instances are dropped as for `update_model_record()`. Raises `UnknownModelException` for an unknown key and `InvalidModelException` when the files are not identified as any model.
+
The model manager also offers a few convenience shortcuts for loading models:
### mm.load_model_by_config(model_config, [submodel], [context]) -> LoadedModel
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index ba86975477..5ec523488a 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -35,7 +35,7 @@ from invokeai.app.services.model_install.model_install_common import (
InstallRecoveryRequiredError,
ModelInstallJob,
)
-from invokeai.app.services.model_load.model_load_common import load_settings_changed
+from invokeai.app.services.model_load.model_load_common import distinct_caches
from invokeai.app.services.model_records import (
InvalidModelException,
ModelRecordChanges,
@@ -48,7 +48,7 @@ from invokeai.app.util.path_safety import is_plain_filename
from invokeai.app.util.suppress_output import SuppressOutput
from invokeai.backend.architectures import ArchitectureCapabilities, architecture_capabilities
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
-from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.configs.main import (
Main_Checkpoint_SD1_Config,
Main_Checkpoint_SD2_Config,
@@ -57,14 +57,12 @@ from invokeai.backend.model_manager.configs.main import (
)
from invokeai.backend.model_manager.load.fp8_capability import Fp8StorageSupport, fp8_storage_support
from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats
-from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetch
from invokeai.backend.model_manager.metadata.metadata_base import (
ModelMetadataWithFiles,
ModelRevisionUnavailableError,
UnknownMetadataException,
)
-from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.search import ModelSearch, ModelSearchCancelled
from invokeai.backend.model_manager.starter_models import (
STARTER_BUNDLES,
@@ -477,61 +475,13 @@ def reidentify_model(
"""Attempt to reidentify a model by re-probing its weights file."""
try:
with _claim_model_key(key):
- return _reidentify_model(key)
+ return ApiDependencies.invoker.services.model_manager.reidentify_model(key)
except UnknownModelException as e:
raise HTTPException(status_code=404, detail=str(e))
except InvalidModelException as e:
raise HTTPException(status_code=400, detail=str(e))
-def _reidentify_model(key: str) -> AnyModelConfig:
- """Re-probe one model and rewrite its record. Callers must hold the key claim."""
- config = ApiDependencies.invoker.services.model_manager.store.get_model(key)
- models_path = ApiDependencies.invoker.services.configuration.models_path
- if pathlib.Path(config.path).is_relative_to(models_path):
- model_path = pathlib.Path(config.path)
- else:
- model_path = models_path / config.path
- mod = ModelOnDisk(model_path)
- # The install source is evidence identification reads: for a model whose weights cannot name its
- # backbone (a 16-channel VAE, a PiD decoder), the HF repo or URL may. A file copied into the models
- # folder has also lost the folder it came from, so without the source a re-probe refiles it under
- # the default.
- override_fields = {"source": config.source, "source_type": config.source_type}
- if encoder_id := getattr(config, "image_encoder_model_id", None):
- override_fields["image_encoder_model_id"] = encoder_id
- result = ModelConfigFactory.from_model_on_disk(mod, override_fields)
- if result.config is None:
- raise InvalidModelException("Unable to identify model format")
-
- # Retain user-editable fields from the original config
- result.config.path = config.path
- result.config.key = config.key
- result.config.name = config.name
- result.config.description = config.description
- result.config.cover_image = config.cover_image
- if hasattr(result.config, "trigger_phrases") and hasattr(config, "trigger_phrases"):
- result.config.trigger_phrases = config.trigger_phrases
- result.config.source = config.source
- result.config.source_type = config.source_type
- if hasattr(config, "cpu_only") and hasattr(result.config, "cpu_only"):
- result.config.cpu_only = config.cpu_only
- previous_settings = getattr(config, "default_settings", None)
- updated_settings = getattr(result.config, "default_settings", None)
- if previous_settings is not None and updated_settings is not None:
- updated_settings = deepcopy(updated_settings)
- result.config.default_settings = updated_settings
- for field in ("cpu_only", "fp8_storage"):
- if hasattr(previous_settings, field) and hasattr(updated_settings, field):
- setattr(updated_settings, field, getattr(previous_settings, field))
-
- # 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) as edit:
- updated = ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)
- edit.load_affecting = _invalidate_model_load_caches(config.key, config, updated)
- return updated
-
-
class FoundModel(BaseModel):
path: str = Field(description="Path to the model")
is_installed: bool = Field(description="Whether or not the model is already installed")
@@ -652,26 +602,19 @@ def get_hugging_face_models(
def _update_model_record(key: str, changes: ModelRecordChanges) -> AnyModelConfig:
- """Update a model record and invalidate any cache affected by the change.
+ """Update a model record under its key claim, and prepare the response.
- Keep the complete claim and synchronous service work in one worker-thread operation. This
- route needs to await cache invalidation, but that must not leave the database read/write and
- response preparation on the event loop before and after that await.
+ The claim, the service's record write and cache invalidation, and the response preparation are synchronous;
+ they run as one worker-thread operation so none of them is left on the event loop.
"""
logger = ApiDependencies.invoker.services.logger
- record_store = ApiDependencies.invoker.services.model_manager.store
# Claimed for the whole update: a conversion running on this key carries a snapshot of the
# record taken before it started and writes it into the replacement, so an edit accepted
# meanwhile would be reported as saved and then silently dropped.
- with _claim_model_key(key), ApiDependencies.invoker.services.model_manager.load.record_edit(key) as edit:
+ with _claim_model_key(key):
try:
- previous_config = record_store.get_model(key)
- config = record_store.update_model(key, changes=changes, allow_class_change=True)
- # Settings that change how the model loads (e.g. fp8_storage, cpu_only) are baked into the cached
- # nn.Module at load time, so toggling them on a cached model is otherwise silently a no-op until
- # the entry is evicted. Drop any unlocked cached entries for this model so the next load rebuilds.
- edit.load_affecting = _invalidate_model_load_caches(key, previous_config, config)
+ config = ApiDependencies.invoker.services.model_manager.update_model_record(key, changes)
config = prepare_model_config_for_response(config, ApiDependencies)
logger.info(f"Updated model: {key}")
except UnknownModelException as e:
@@ -706,27 +649,13 @@ async def update_model_record(
# does post the record back whole, so an unchanged echo is expected and accepted - but a *different* key is
# written into the stored config while the row id keeps the old one, which leaves a record that answers to a
# key nothing can look it up by: `replace_model` (and so reidentify) raises `UnknownModelException` forever
- # after, and the UI caches the model under the new key so every later request for it 404s.
+ # after, and the UI caches the model under the new key so every later request for it 404s. The record store
+ # refuses such a change too; checked here first so it is a 422 before any claim or record lookup can answer.
if "key" in changes.model_fields_set and changes.key != key:
raise HTTPException(status_code=422, detail="A model's key cannot be changed")
return await asyncio.to_thread(_update_model_record, key, changes)
-def _invalidate_model_load_caches(key: str, previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
- """Drop cached instances when a record change affects how the model is loaded; return whether it did."""
- if not load_settings_changed(previous, updated):
- return False
- 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."
- )
- return True
-
-
@model_manager_router.get(
"/i/{key}/image",
operation_id="get_model_image",
@@ -955,7 +884,7 @@ def bulk_reidentify_models(
# carry its own copy of the retain-these-fields logic, which is one edit away from the
# two disagreeing about what a reidentification preserves.
with _claim_model_key(key):
- _reidentify_model(key)
+ ApiDependencies.invoker.services.model_manager.reidentify_model(key)
succeeded.append(key)
logger.info(f"Reidentified model: {key}")
except HTTPException as e:
@@ -1641,12 +1570,7 @@ def get_stats(current_admin: AdminUserOrDefault) -> Optional[CacheStats]:
one cache per generation device; their statistics are aggregated. Will return null if no models
have been loaded."""
stats_list: list[CacheStats] = []
- seen_cache_ids: set[int] = set()
- # ram_caches can map several device keys to the same cache object; count each cache once.
- for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values():
- if id(cache) in seen_cache_ids:
- continue
- seen_cache_ids.add(id(cache))
+ for cache in distinct_caches(ApiDependencies.invoker.services.model_manager.load.ram_caches.values()):
if cache.stats is not None:
stats_list.append(cache.stats)
@@ -1687,14 +1611,7 @@ def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheRespo
ApiDependencies.invoker.services.logger.info("Emptying model cache.")
models_cleared = 0
bytes_freed = 0
- seen_cache_ids: set[int] = set()
- # ram_caches can map several device keys to the same cache object; clearing one twice would
- # report the second (empty) pass and double-count nothing, but the id() guard keeps the totals
- # honest and matches get_stats above.
- for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values():
- if id(cache) in seen_cache_ids:
- continue
- seen_cache_ids.add(id(cache))
+ for cache in distinct_caches(ApiDependencies.invoker.services.model_manager.load.ram_caches.values()):
result = cache.make_room(1000 * 2**30)
models_cleared += result.models_cleared
bytes_freed += result.bytes_freed
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index ea02ca6c71..8b03e94cf6 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -976,20 +976,17 @@ class ImageIndexService(ImageIndexServiceBase):
The shared cache is keyed by model key alone, so an encoder that keeps its key across a
reinstall would be served from the retired weights while its embeddings are stored under
- the replacement's hash, and those survive a restart. The write lock keeps a concurrent
- load from re-registering the old shared CPU weights around the drop. It is taken under
- _activation_lock, so map polls, searches and stop() wait out any model load or VRAM move
- in flight; that cannot deadlock, because the worker and request users have drained and
- nothing takes _activation_lock while holding the load lock.
+ the replacement's hash, and those survive a restart. The drop takes MODEL_LOAD_LOCK's write
+ lock, so a concurrent load cannot re-register the old shared CPU weights around it. It is
+ taken under _activation_lock, so map polls, searches and stop() wait out any model load or
+ VRAM move in flight; that cannot deadlock, because the worker and request users have drained
+ and nothing takes _activation_lock while holding the load lock.
"""
keys = {config.key for config in configs if config is not None}
if not keys:
# Still missing: this runs on every throttled recheck, and must not queue behind a load.
return
- with MODEL_LOAD_LOCK.write_lock():
- for cache in set(invoker.services.model_manager.load.ram_caches.values()):
- for key in keys:
- cache.drop_model(key)
+ invoker.services.model_manager.load.drop_cached_models(keys)
def _reset_model_resources(self) -> None:
"""Retire caches only after the worker and request users have drained.
diff --git a/invokeai/app/services/model_load/model_load_base.py b/invokeai/app/services/model_load/model_load_base.py
index 12c028097e..73b9f86685 100644
--- a/invokeai/app/services/model_load/model_load_base.py
+++ b/invokeai/app/services/model_load/model_load_base.py
@@ -2,9 +2,8 @@
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Callable, ContextManager, Optional
+from typing import Callable, Iterable, Optional
-from invokeai.app.services.model_load.model_load_common import RecordEdit
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load import LoadedModel, LoadedModelWithoutConfig
from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
@@ -31,12 +30,28 @@ class ModelLoadServiceBase(ABC):
"""
@abstractmethod
- def record_edit(self, key: str) -> ContextManager[RecordEdit]:
- """Bracket a write of `key`'s record that may change how it loads, from before it commits until
- after any cache invalidation it performs. Cold loads of `key` wait for open brackets before reading
- the record, and are rejected if a bracket is still open, or a load-affecting one has closed, by the
- time construction is serialized against invalidation. Every writer of load-affecting settings must
- use it, and should clear `load_affecting` on the yielded edit when it changed nothing that loads."""
+ def apply_record_change(self, key: str, write: Callable[[], AnyModelConfig]) -> AnyModelConfig:
+ """Run `write`, which commits a change to `key`'s record and returns the record as stored, and evict
+ what the change made stale; return what `write` returned.
+
+ Every write of a model record that may change how the model loads must go through here. The stored
+ record is read before `write` runs; when the two differ in anything that loads (`load_settings_changed`,
+ paths compared after resolving them against the models directory), every cached entry of the model is
+ dropped from each device cache. Cold loads of `key` that start meanwhile wait for the change to end
+ before reading the record, and a load that read it earlier is rejected, and retried from the stored
+ record, if the change affected loading. If `write` raises an `Exception`, it may have committed first, so the
+ change is judged the same way by the record read back from the store before the exception propagates; if
+ that read fails too, the change counts as load-affecting. An interrupt (a `BaseException` that is not an
+ `Exception`) propagates without the read-back or any drop, but loads that overlapped are still re-checked.
+ The caller must not hold MODEL_LOAD_LOCK."""
+
+ @abstractmethod
+ def drop_cached_models(self, keys: Iterable[str]) -> int:
+ """Drop every cached entry of the models `keys` from each device cache, so their next loads rebuild;
+ return how many entries were dropped at once (in-use entries are marked stale and evicted on release).
+
+ Takes MODEL_LOAD_LOCK's write lock, so no load in construction can re-register state it built from the
+ models' previous records around the drop. The caller must not hold that lock."""
@property
@abstractmethod
diff --git a/invokeai/app/services/model_load/model_load_common.py b/invokeai/app/services/model_load/model_load_common.py
index 58b1203fe6..16377b1b5b 100644
--- a/invokeai/app/services/model_load/model_load_common.py
+++ b/invokeai/app/services/model_load/model_load_common.py
@@ -1,8 +1,8 @@
-"""Shared rules for when a model record change invalidates loaded instances of that model."""
+"""Shared rules for when a model record change invalidates loaded instances of that model, and for visiting the
+per-device caches that hold them."""
-from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Iterable, Optional, TypeVar
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
@@ -59,10 +59,14 @@ def load_settings_changed(
return _model_load_fingerprint(previous, models_path) != _model_load_fingerprint(updated, models_path)
-@dataclass
-class RecordEdit:
- """One bracketed write of a model record (see `ModelLoadServiceBase.record_edit`)."""
+_Cache = TypeVar("_Cache")
- # Whether the write changed how the model loads. A writer that has compared the record before and after
- # clears it; left set, as when the write fails partway, loads that overlapped it are re-checked.
- load_affecting: bool = True
+
+def distinct_caches(caches: Iterable[_Cache]) -> list[_Cache]:
+ """Each cache once, in first-seen order.
+
+ `ModelLoadServiceBase.ram_caches` can map several device keys to one cache (the default cache is filed under its
+ own device key, which another key can also name), so a pass over every cache that counts, clears or drops must
+ visit each once.
+ """
+ return list(dict.fromkeys(caches))
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index 704b4b1d83..5288bc9e3c 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -4,7 +4,7 @@ import threading
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
-from typing import Callable, ContextManager, Iterator, Optional, Type
+from typing import Callable, Iterable, Iterator, Optional, Type
from picklescan.scanner import scan_file_path
from safetensors.torch import load_file as safetensors_load_file
@@ -13,7 +13,7 @@ from torch import load as torch_load
from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_load.model_load_base import ModelLoadServiceBase
-from invokeai.app.services.model_load.model_load_common import RecordEdit, load_settings_changed
+from invokeai.app.services.model_load.model_load_common import distinct_caches, load_settings_changed
from invokeai.app.services.model_records import UnknownModelException
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load import (
@@ -31,6 +31,16 @@ from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
+@dataclass
+class _RecordEdit:
+ """One bracketed write of a model record (see `_RecordEdits.edit`)."""
+
+ # Whether the write changed how the model loads, judged by the record as stored (read back if the write
+ # failed); left set when either record cannot be read or the write is interrupted. While set, overlapping
+ # loads are re-checked.
+ load_affecting: bool = True
+
+
@dataclass
class _KeyEdits:
in_progress: int = 0
@@ -55,8 +65,13 @@ class _RecordEdits:
del self._keys[key]
@contextmanager
- def edit(self, key: str) -> Iterator[RecordEdit]:
- record_edit = RecordEdit()
+ def edit(self, key: str) -> Iterator[_RecordEdit]:
+ """Bracket a write of `key`'s record that may change how it loads, from before it commits until after any
+ cache invalidation it performs. Cold loads of `key` wait for open brackets before reading the record, and
+ are rejected if a bracket is still open, or a load-affecting one has closed, by the time construction is
+ serialized against invalidation. A bracket that changed nothing that loads clears `load_affecting` on the
+ yielded edit. `ModelLoadService.apply_record_change` is the only writer."""
+ record_edit = _RecordEdit()
with self._changed:
self._keys.setdefault(key, _KeyEdits()).in_progress += 1
try:
@@ -200,8 +215,61 @@ class ModelLoadService(ModelLoadServiceBase):
loader.config_check = self._check_config
return loader.load_model(model_config, submodel_type)
- def record_edit(self, key: str) -> ContextManager[RecordEdit]:
- return self._record_edits.edit(key)
+ def apply_record_change(self, key: str, write: Callable[[], AnyModelConfig]) -> AnyModelConfig:
+ # Lock order: the bracket opens before MODEL_LOAD_LOCK is taken and closes after it is released, so a
+ # load rejected under the lock waits for the whole change, its invalidation included.
+ store = self._invoker.services.model_manager.store
+ with self._record_edits.edit(key) as edit:
+ previous = store.get_model(key)
+ try:
+ updated = write()
+ except Exception:
+ # The write may have committed before it failed, so judge it by the record as stored. An
+ # interrupt (KeyboardInterrupt, SystemExit) skips this: dropping waits for MODEL_LOAD_LOCK, which a
+ # construction may hold for a long time. Overlapping loads are still re-checked.
+ try:
+ stored: Optional[AnyModelConfig] = store.get_model(key)
+ except UnknownModelException:
+ # Deleted meanwhile (installs, syncs and prunes delete records outside this bracket): the
+ # cached entries belong to a model that is gone.
+ self._logger.debug(f"Model {key} was deleted during a failed write; dropping its cached entries.")
+ stored = None
+ except Exception:
+ self._logger.warning(
+ f"Could not read back the record of model {key} after a failed write; dropping its cached "
+ "entries.",
+ exc_info=True,
+ )
+ stored = None
+ self._settle_record_change(edit, key, previous, stored)
+ raise
+ self._settle_record_change(edit, key, previous, updated)
+ return updated
+
+ def _settle_record_change(
+ self, edit: _RecordEdit, key: str, previous: AnyModelConfig, stored: Optional[AnyModelConfig]
+ ) -> None:
+ """Record on `edit` whether the change made `key` load differently, and if so drop its cached entries.
+ `stored` is None when the record could not be read back or is gone; the change then counts as
+ load-affecting."""
+ edit.load_affecting = stored is None or self._load_settings_changed(previous, stored)
+ if edit.load_affecting:
+ dropped = self.drop_cached_models([key])
+ if dropped:
+ self._logger.info(
+ f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after "
+ "settings change."
+ )
+
+ def drop_cached_models(self, keys: Iterable[str]) -> int:
+ keys = list(keys)
+ with MODEL_LOAD_LOCK.write_lock():
+ return sum(cache.drop_model(key) for cache in distinct_caches(self._ram_caches.values()) for key in keys)
+
+ def _load_settings_changed(self, previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
+ """The comparison every check of a record against another uses here: edits and the load fence must agree on
+ what loads differently, or a no-op rewrite (a path in another form) would evict and reject loads."""
+ return load_settings_changed(previous, updated, models_path=self._app_config.models_path)
def _current_record(self, key: str) -> AnyModelConfig:
"""The stored record for `key`, read once no edit of it is in progress."""
@@ -216,7 +284,7 @@ class ModelLoadService(ModelLoadServiceBase):
current = self._current_record(config.key)
except UnknownModelException:
return None
- if load_settings_changed(config, current, models_path=self._app_config.models_path):
+ if self._load_settings_changed(config, current):
return current
return None
@@ -226,7 +294,7 @@ class ModelLoadService(ModelLoadServiceBase):
Nothing here touches the database under that lock, so a long DB transaction (e.g. VACUUM) stalls only
this load. The record is read here, once no edit of it is in progress; edits bracket their commit and
- cache invalidation with `record_edit()`. An edit that commits after this read therefore started after
+ cache invalidation with `_RecordEdits.edit()`. An edit that commits after this read therefore started after
the wait, so by the time construction is serialized against invalidation it is either still in
progress or has ended; either way the load is rejected, unless it ended having changed nothing that
loads (e.g. a rename).
@@ -242,7 +310,7 @@ class ModelLoadService(ModelLoadServiceBase):
except UnknownModelException:
# Nothing newer to load instead, and the key can no longer be requested.
return True
- return not load_settings_changed(config, current, models_path=self._app_config.models_path)
+ return not self._load_settings_changed(config, current)
def load_model_from_path(
self, model_path: Path, loader: Optional[Callable[[Path], AnyModel]] = None
diff --git a/invokeai/app/services/model_manager/model_manager_base.py b/invokeai/app/services/model_manager/model_manager_base.py
index 079c4c7b53..1971ee885b 100644
--- a/invokeai/app/services/model_manager/model_manager_base.py
+++ b/invokeai/app/services/model_manager/model_manager_base.py
@@ -9,7 +9,8 @@ from invokeai.app.services.events.events_base import EventServiceBase
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_install.model_install_base import ModelInstallServiceBase
from invokeai.app.services.model_load.model_load_base import ModelLoadServiceBase
-from invokeai.app.services.model_records.model_records_base import ModelRecordServiceBase
+from invokeai.app.services.model_records.model_records_base import ModelRecordChanges, ModelRecordServiceBase
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig
class ModelManagerServiceBase(ABC):
@@ -56,6 +57,23 @@ class ModelManagerServiceBase(ABC):
"""Return the ModelInstallServiceBase used to download and manipulate model files."""
pass
+ @abstractmethod
+ def update_model_record(self, key: str, changes: ModelRecordChanges) -> AnyModelConfig:
+ """Apply `changes` to `key`'s record, which may change its config class, and return the stored result.
+ Cached instances the change made stale are dropped (see `ModelLoadServiceBase.apply_record_change`).
+
+ Raises `UnknownModelException` for an unknown key, and `ValueError` when the changed record is invalid or
+ conflicts with another record."""
+
+ @abstractmethod
+ def reidentify_model(self, key: str) -> AnyModelConfig:
+ """Identify `key`'s files again and replace its record with the result, keeping what the user set: the
+ name, description, cover image, trigger phrases, install source and CPU/FP8 preferences. Cached instances
+ the new record makes stale are dropped (see `ModelLoadServiceBase.apply_record_change`).
+
+ Raises `UnknownModelException` for an unknown key, and `InvalidModelException` when the files are not
+ identified as any model."""
+
@abstractmethod
def start(self, invoker: Invoker) -> None:
pass
diff --git a/invokeai/app/services/model_manager/model_manager_default.py b/invokeai/app/services/model_manager/model_manager_default.py
index 59affc051f..5e20e8e2ff 100644
--- a/invokeai/app/services/model_manager/model_manager_default.py
+++ b/invokeai/app/services/model_manager/model_manager_default.py
@@ -1,5 +1,7 @@
"""Implementation of ModelManagerServiceBase."""
+from copy import deepcopy
+from pathlib import Path
from typing import Optional
import torch
@@ -12,13 +14,20 @@ from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_install.model_install_base import ModelInstallServiceBase
from invokeai.app.services.model_install.model_install_default import ModelInstallService
from invokeai.app.services.model_load.model_load_base import ModelLoadServiceBase
+from invokeai.app.services.model_load.model_load_common import distinct_caches
from invokeai.app.services.model_load.model_load_default import ModelLoadService
from invokeai.app.services.model_manager.model_manager_base import ModelManagerServiceBase
-from invokeai.app.services.model_records.model_records_base import ModelRecordServiceBase
+from invokeai.app.services.model_records.model_records_base import (
+ InvalidModelException,
+ ModelRecordChanges,
+ ModelRecordServiceBase,
+)
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
@@ -55,6 +64,56 @@ class ModelManagerService(ModelManagerServiceBase):
def load(self) -> ModelLoadServiceBase:
return self._load
+ def update_model_record(self, key: str, changes: ModelRecordChanges) -> AnyModelConfig:
+ return self._load.apply_record_change(
+ key, lambda: self._store.update_model(key, changes=changes, allow_class_change=True)
+ )
+
+ def reidentify_model(self, key: str) -> AnyModelConfig:
+ config = self._store.get_model(key)
+ models_path = self._install.app_config.models_path
+ if Path(config.path).is_relative_to(models_path):
+ model_path = Path(config.path)
+ else:
+ model_path = models_path / config.path
+ mod = ModelOnDisk(model_path)
+ # The install source is evidence identification reads: for a model whose weights cannot name its
+ # backbone (a 16-channel VAE, a PiD decoder), the HF repo or URL may. A file copied into the models
+ # folder has also lost the folder it came from, so without the source a re-probe refiles it under
+ # the default.
+ override_fields = {"source": config.source, "source_type": config.source_type}
+ if encoder_id := getattr(config, "image_encoder_model_id", None):
+ override_fields["image_encoder_model_id"] = encoder_id
+ result = ModelConfigFactory.from_model_on_disk(mod, override_fields)
+ if result.config is None:
+ raise InvalidModelException("Unable to identify model format")
+
+ # Retain user-editable fields from the original config
+ identified = result.config
+ identified.path = config.path
+ identified.key = config.key
+ identified.name = config.name
+ identified.description = config.description
+ identified.cover_image = config.cover_image
+ if hasattr(identified, "trigger_phrases") and hasattr(config, "trigger_phrases"):
+ identified.trigger_phrases = config.trigger_phrases
+ identified.source = config.source
+ identified.source_type = config.source_type
+ if hasattr(config, "cpu_only") and hasattr(identified, "cpu_only"):
+ identified.cpu_only = config.cpu_only
+ previous_settings = getattr(config, "default_settings", None)
+ updated_settings = getattr(identified, "default_settings", None)
+ if previous_settings is not None and updated_settings is not None:
+ # The probe may hand back an architecture's shared defaults object; copy it before writing to it.
+ updated_settings = deepcopy(updated_settings)
+ identified.default_settings = updated_settings
+ for field in ("cpu_only", "fp8_storage"):
+ if hasattr(previous_settings, field) and hasattr(updated_settings, field):
+ setattr(updated_settings, field, getattr(previous_settings, field))
+
+ # The probe can change the config class or reset load-affecting settings.
+ return self._load.apply_record_change(config.key, lambda: self._store.replace_model(config.key, identified))
+
def start(self, invoker: Invoker) -> None:
for service in [self._store, self._install, self._load]:
if hasattr(service, "start"):
@@ -63,7 +122,7 @@ class ModelManagerService(ModelManagerServiceBase):
def stop(self, invoker: Invoker) -> None:
# Shutdown every per-device model cache to cancel any pending keep-alive timers.
if hasattr(self._load, "ram_caches"):
- for cache in self._load.ram_caches.values():
+ for cache in distinct_caches(self._load.ram_caches.values()):
cache.shutdown()
for service in [self._store, self._install, self._load]:
@@ -130,14 +189,14 @@ class ModelManagerService(ModelManagerServiceBase):
# leave nothing for the OS, causing swap thrashing. The clamp leaves real headroom; shared-weight
# dedup means the true footprint usually stays well under the cap regardless.
gb = 2**30
- distinct_caches = list(dict.fromkeys(ram_caches.values()))
+ device_caches = distinct_caches(ram_caches.values())
# Cross-device weight adoption (and its per-model meta-shell capture) only pays off with more
# than one device cache; disable the capture cost otherwise.
- shared_store.enable_shell_capture = len(distinct_caches) > 1
+ shared_store.enable_shell_capture = len(device_caches) > 1
if app_config.max_cache_ram_gb is not None:
global_ram_budget_bytes = int(app_config.max_cache_ram_gb * gb)
else:
- summed_cache_bytes = sum(c.local_ram_cache_size_bytes for c in distinct_caches)
+ summed_cache_bytes = sum(c.local_ram_cache_size_bytes for c in device_caches)
system_ram_headroom_bytes = ModelCache.calc_system_ram_headroom_bytes()
global_ram_budget_bytes = min(summed_cache_bytes, system_ram_headroom_bytes)
if global_ram_budget_bytes < summed_cache_bytes:
@@ -146,11 +205,11 @@ class ModelManagerService(ModelManagerServiceBase):
f"headroom (sum of per-device caches was {summed_cache_bytes / gb:.2f} GB)."
)
ram_budget = RamBudget(max_bytes=global_ram_budget_bytes, shared_store=shared_store)
- for cache in distinct_caches:
+ for cache in device_caches:
cache.set_ram_budget(ram_budget)
logger.info(
f"Model cache global RAM budget: {global_ram_budget_bytes / gb:.2f} GB "
- f"across {len(distinct_caches)} device cache(s)."
+ f"across {len(device_caches)} device cache(s)."
)
loader = ModelLoadService(
diff --git a/invokeai/app/services/model_records/model_records_base.py b/invokeai/app/services/model_records/model_records_base.py
index ed454d9fc8..62df48d587 100644
--- a/invokeai/app/services/model_records/model_records_base.py
+++ b/invokeai/app/services/model_records/model_records_base.py
@@ -189,7 +189,8 @@ class ModelRecordServiceBase(ABC):
Update the model, returning the updated version.
:param key: Unique key for the model to be updated.
- :param changes: A set of changes to apply to this model. Changes are validated before being written.
+ :param changes: A set of changes to apply to this model. Changes are validated before being written. A
+ model's key cannot change: `changes.key`, if set, must equal `key`, or ValueError is raised.
:param allow_class_change: If True, allows changes that would change the model config class. For example,
changing a LoRA into a Main model. This does not disable validation, so the changes must still be valid.
"""
diff --git a/invokeai/app/services/model_records/model_records_sql.py b/invokeai/app/services/model_records/model_records_sql.py
index a351399159..5be448684f 100644
--- a/invokeai/app/services/model_records/model_records_sql.py
+++ b/invokeai/app/services/model_records/model_records_sql.py
@@ -127,6 +127,11 @@ class ModelRecordServiceSQL(ModelRecordServiceBase):
raise UnknownModelException("model not found")
def update_model(self, key: str, changes: ModelRecordChanges, allow_class_change: bool = False) -> AnyModelConfig:
+ # Every set field is copied into the stored config, so a different key would be written into the blob while
+ # the row keeps the old one: a record nothing can look up by the key it reports.
+ if "key" in changes.model_fields_set and changes.key != key:
+ raise ValueError("A model's key cannot be changed")
+
def apply(q: Queries) -> str:
# Locked, so that a concurrent update applies its changes to this one's result, not beside it.
stored = q.models.lock(key)
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 45b2b01b3d..eb1f02a7b2 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -1,8 +1,7 @@
-import contextlib
import logging
import os
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any
import pytest
from fastapi.testclient import TestClient
@@ -10,7 +9,6 @@ from PIL import Image
from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api_app import app
-from invokeai.app.services.model_load.model_load_common import RecordEdit
from invokeai.backend.model_manager.configs.external_api import (
ExternalApiModelConfig,
ExternalModelCapabilities,
@@ -352,7 +350,7 @@ def test_get_stats_returns_null_when_no_stats(monkeypatch: Any, client: TestClie
@pytest.mark.anyio
async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch: Any) -> None:
- """The async cache-invalidation path must not strand DB work on the event loop."""
+ """The record write, its cache invalidation and the response preparation must not run on the event loop."""
import threading
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -361,34 +359,21 @@ async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch
event_loop_thread = threading.get_ident()
service_threads: list[int] = []
- previous = SimpleNamespace(
- cpu_only=False,
- default_settings=SimpleNamespace(fp8_storage=False, cpu_only=False),
- )
- updated = SimpleNamespace(
- cpu_only=False,
- default_settings=SimpleNamespace(fp8_storage=False, cpu_only=False),
- )
+ updated = object()
- class Store:
- def get_model(self, key: str) -> Any:
- service_threads.append(threading.get_ident())
- return previous
+ def update_model_record(key: str, changes: Any) -> Any:
+ service_threads.append(threading.get_ident())
+ return updated
- def update_model(self, key: str, changes: Any, allow_class_change: bool) -> Any:
- service_threads.append(threading.get_ident())
- return updated
+ def prepare(config: Any, _deps: Any) -> Any:
+ service_threads.append(threading.get_ident())
+ return config
services = SimpleNamespace(
- logger=MagicMock(),
- model_manager=SimpleNamespace(
- store=Store(),
- load=SimpleNamespace(ram_caches={}, record_edit=lambda key: contextlib.nullcontext(RecordEdit())),
- ),
+ logger=MagicMock(), model_manager=SimpleNamespace(update_model_record=update_model_record)
)
- invoker = DummyInvoker(services)
- monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(invoker))
- monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _: config)
+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
+ monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", prepare)
result = await model_manager_router.update_model_record(
key="model-key",
@@ -397,59 +382,72 @@ async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch
)
assert result is updated
- assert service_threads
+ assert len(service_threads) == 2
assert all(thread_id != event_loop_thread for thread_id in service_threads)
-async def test_update_model_record_brackets_commit_and_cache_drop_as_a_record_edit(monkeypatch: Any) -> None:
- """Loads re-check a record they read while an edit is in progress, so the edit must be announced
- before it commits and stay announced until its cache invalidation is done."""
- from types import SimpleNamespace
- from unittest.mock import MagicMock
-
- import invokeai.app.api.routers.model_manager as model_manager_router
-
- open_edits: list[str] = []
- observed: list[tuple[str, list[str]]] = []
+def model_record_routes(monkeypatch: Any, mm2_model_manager: Any, mm2_app_config: Any) -> Any:
+ """The model record routes over a real model manager; returns that manager."""
+ services = type("Services", (), {})()
+ services.model_manager = mm2_model_manager
+ services.model_images = DummyModelImages()
+ services.configuration = mm2_app_config
+ services.logger = logging.getLogger("test.model_manager_router")
+ invoker = DummyInvoker(services)
+ # The load service reads the record it compares a change against through the invoker.
+ mm2_model_manager.load.start(invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))
+ return mm2_model_manager
- @contextlib.contextmanager
- def record_edit(key: str) -> Iterator[RecordEdit]:
- open_edits.append(key)
- try:
- yield RecordEdit()
- finally:
- open_edits.remove(key)
- def settings(cpu_only: bool) -> Any:
- return SimpleNamespace(cpu_only=cpu_only, default_settings=SimpleNamespace(fp8_storage=False))
+def test_update_model_record_answers_with_the_service_outcome(client: TestClient, model_record_routes: Any) -> None:
+ key = "test_config_1"
- class Store:
- def get_model(self, key: str) -> Any:
- return settings(cpu_only=False)
+ renamed = client.patch(f"/api/v2/models/i/{key}", json={"name": "renamed"})
+ unknown = client.patch("/api/v2/models/i/no-such-model", json={"name": "renamed"})
+ rejected = client.patch(f"/api/v2/models/i/{key}", json={"path": "x" * 800})
- def update_model(self, key: str, changes: Any, allow_class_change: bool) -> Any:
- observed.append(("commit", list(open_edits)))
- return settings(cpu_only=True)
+ assert renamed.status_code == 200
+ assert renamed.json()["name"] == "renamed"
+ assert renamed.json()["cover_image"] == f"https://example.com/models/{key}.png"
+ assert model_record_routes.store.get_model(key).name == "renamed"
+ assert unknown.status_code == 404
+ assert rejected.status_code == 409
+ assert "at most" in rejected.json()["detail"]
- class Cache:
- def drop_model(self, key: str) -> int:
- observed.append(("drop", list(open_edits)))
- return 1
- services = SimpleNamespace(
- logger=MagicMock(),
- model_manager=SimpleNamespace(
- store=Store(), load=SimpleNamespace(ram_caches={"cpu": Cache()}, record_edit=record_edit)
- ),
+def test_reidentify_model_answers_with_the_service_outcome(
+ client: TestClient, model_record_routes: Any, mm2_app_config: Any
+) -> None:
+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
+ from tests.backend.model_manager.load.state_dicts import clip_g_comfy_keys
+ from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors
+
+ # A CLIP-G without the projection SD 3 needs: recognised, and refused as unusable.
+ keys = dict(clip_g_comfy_keys.state_dict_keys)
+ del keys["text_projection.weight"]
+ write_header_only_safetensors(mm2_app_config.models_path / "clip-g.safetensors", keys)
+ model_record_routes.store.add_model(
+ Main_Checkpoint_SD1_Config(
+ key="unusable",
+ path="clip-g.safetensors",
+ name="unusable",
+ hash="hash",
+ file_size=1,
+ source="local-source",
+ source_type=ModelSourceType.Path,
+ prediction_type="epsilon",
+ variant="normal",
+ )
)
- monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
- monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _: config)
- await model_manager_router.update_model_record(key="model-key", changes=MagicMock(), current_admin=MagicMock())
+ unusable = client.post("/api/v2/models/i/unusable/reidentify")
+ unknown = client.post("/api/v2/models/i/no-such-model/reidentify")
- assert observed == [("commit", ["model-key"]), ("drop", ["model-key"])]
- assert open_edits == []
+ assert unusable.status_code == 400
+ assert unknown.status_code == 404
def test_convert_model_rejects_a_second_conversion_while_one_is_running() -> None:
@@ -1067,115 +1065,7 @@ def test_reidentify_is_refused_while_the_same_model_is_being_converted(conversio
reidentify_model(key="busy-key", current_admin=MagicMock())
assert exc_info.value.status_code == 409
- deps.invoker.services.model_manager.store.replace_model.assert_not_called()
-
-
-def test_reidentify_keeps_a_backbone_only_the_install_source_names(
- monkeypatch: Any, mm2_record_store: Any, mm2_app_config: Any
-) -> None:
- """A 16-channel VAE is FLUX.1's or SD3's by its name alone. Copied into the models folder it keeps a
- generic file name in a folder named for its key, and only the Hugging Face source still says SD3."""
- from types import SimpleNamespace
-
- import torch
- from safetensors.torch import save_file
-
- from invokeai.app.api.routers.model_manager import _reidentify_model
- from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
- from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelSourceType
-
- path = mm2_app_config.models_path / "7c1f9d2e" / "diffusion_pytorch_model.safetensors"
- path.parent.mkdir(parents=True)
- save_file(
- {"encoder.conv_in.weight": torch.zeros(8, 3, 3, 3), "decoder.conv_in.weight": torch.zeros(8, 16, 3, 3)}, path
- )
- source = {
- "source": "stabilityai/stable-diffusion-3.5-large::vae/diffusion_pytorch_model.safetensors",
- "source_type": ModelSourceType.HFRepoID,
- }
- installed = ModelConfigFactory.from_model_on_disk(path, source, allow_unknown=False).config
- assert installed is not None and installed.base is BaseModelType.StableDiffusion3
- mm2_record_store.add_model(installed)
-
- # The rewrite can reset load-affecting settings, so it must be announced to in-flight loads.
- open_edits: list[str] = []
- edits_at_replace: list[list[str]] = []
-
- @contextlib.contextmanager
- def record_edit(key: str) -> Iterator[RecordEdit]:
- open_edits.append(key)
- try:
- yield RecordEdit()
- finally:
- open_edits.remove(key)
-
- replace_model = mm2_record_store.replace_model
-
- def replace_model_observed(key: str, config: Any) -> Any:
- edits_at_replace.append(list(open_edits))
- return replace_model(key, config)
-
- monkeypatch.setattr(mm2_record_store, "replace_model", replace_model_observed)
- services = SimpleNamespace(
- model_manager=SimpleNamespace(store=mm2_record_store, load=SimpleNamespace(record_edit=record_edit)),
- configuration=mm2_app_config,
- )
- monkeypatch.setattr(
- "invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(DummyInvoker(services))
- )
-
- assert _reidentify_model(installed.key).base is BaseModelType.StableDiffusion3
- assert edits_at_replace == [[installed.key]]
-
-
-def test_reidentify_records_the_scale_of_an_upscaler_installed_before_it_was_recorded(
- monkeypatch: Any, mm2_record_store: Any, mm2_app_config: Any
-) -> None:
- from types import SimpleNamespace
-
- from invokeai.app.api.routers.model_manager import _reidentify_model
- from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
- from tests.fixtures.spandrel_models import write_compact_upscaler
-
- path = mm2_app_config.models_path / "4x-compact.safetensors"
- write_compact_upscaler(path, 4)
- installed = ModelConfigFactory.from_model_on_disk(path, {}, allow_unknown=False).config
- assert installed is not None
- installed.scale = None
- mm2_record_store.add_model(installed)
- assert mm2_record_store.get_model(installed.key).scale is None
-
- # The recorded scale is part of the record, so the rewrite counts as load-affecting: in-flight loads
- # re-check, and a cached instance built from the scale-less record is dropped.
- edits: list[tuple[str, RecordEdit]] = []
- dropped: list[str] = []
-
- @contextlib.contextmanager
- def record_edit(key: str) -> Iterator[RecordEdit]:
- edit = RecordEdit()
- edits.append((key, edit))
- yield edit
-
- class Cache:
- def drop_model(self, key: str) -> int:
- dropped.append(key)
- return 1
-
- services = SimpleNamespace(
- logger=logging.getLogger(__name__),
- model_manager=SimpleNamespace(
- store=mm2_record_store, load=SimpleNamespace(record_edit=record_edit, ram_caches={"cpu": Cache()})
- ),
- configuration=mm2_app_config,
- )
- monkeypatch.setattr(
- "invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(DummyInvoker(services))
- )
-
- assert _reidentify_model(installed.key).scale == 4
- assert mm2_record_store.get_model(installed.key).scale == 4
- assert [(key, edit.load_affecting) for key, edit in edits] == [(installed.key, True)]
- assert dropped == [installed.key]
+ deps.invoker.services.model_manager.reidentify_model.assert_not_called()
@pytest.mark.anyio
@@ -1201,7 +1091,7 @@ async def test_update_model_record_is_refused_while_the_same_model_is_being_conv
)
assert exc_info.value.status_code == 409
- deps.invoker.services.model_manager.store.update_model.assert_not_called()
+ deps.invoker.services.model_manager.update_model_record.assert_not_called()
def test_model_image_writes_are_refused_while_the_same_model_is_being_converted(conversion_in_flight) -> None:
@@ -1277,20 +1167,19 @@ def test_model_mutations_document_claim_conflicts() -> None:
def test_bulk_reidentify_reports_a_busy_key_instead_of_racing_it(conversion_in_flight) -> None:
- from unittest.mock import MagicMock, patch
+ from unittest.mock import MagicMock
from invokeai.app.api.routers.model_manager import BulkReidentifyModelsRequest, bulk_reidentify_models
- with conversion_in_flight():
- with patch("invokeai.app.api.routers.model_manager._reidentify_model") as reidentify:
- response = bulk_reidentify_models(
- MagicMock(), request=BulkReidentifyModelsRequest(keys=["free-key", "busy-key"])
- )
+ with conversion_in_flight() as deps:
+ response = bulk_reidentify_models(
+ MagicMock(), request=BulkReidentifyModelsRequest(keys=["free-key", "busy-key"])
+ )
assert response.succeeded == ["free-key"]
assert [entry["key"] for entry in response.failed] == ["busy-key"]
assert "already in progress" in response.failed[0]["error"]
- reidentify.assert_called_once_with("free-key")
+ deps.invoker.services.model_manager.reidentify_model.assert_called_once_with("free-key")
@pytest.fixture
@@ -1459,6 +1348,41 @@ async def test_update_model_image_checks_the_record_while_holding_the_claim() ->
deps.invoker.services.model_images.save.assert_called_once()
+async def test_record_writes_run_while_holding_the_claim() -> None:
+ """A conversion of the same key carries a snapshot of the record into its replacement, so an edit or
+ re-identification that ran outside the claim would be reported as saved and then lost."""
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+ from invokeai.app.services.model_records import ModelRecordChanges
+
+ claimed_during_write: list[tuple[str, bool]] = []
+
+ def record(operation: str):
+ def write(key: str, *_args: Any) -> MagicMock:
+ claimed_during_write.append((operation, key in model_manager._CLAIMED_MODEL_KEYS))
+ return MagicMock()
+
+ return write
+
+ with (
+ patch.object(model_manager, "ApiDependencies") as deps,
+ patch.object(model_manager, "prepare_model_config_for_response", lambda config, _deps: config),
+ ):
+ deps.invoker.services.model_manager.update_model_record.side_effect = record("update")
+ deps.invoker.services.model_manager.reidentify_model.side_effect = record("reidentify")
+
+ await model_manager.update_model_record("some-model", ModelRecordChanges(name="renamed"), MagicMock())
+ model_manager.reidentify_model("some-model", MagicMock())
+ model_manager.bulk_reidentify_models(
+ MagicMock(), request=model_manager.BulkReidentifyModelsRequest(keys=["some-model"])
+ )
+
+ assert claimed_during_write == [("update", True), ("reidentify", True), ("reidentify", True)]
+ assert not model_manager._CLAIMED_MODEL_KEYS
+
+
def test_update_model_image_documents_its_404(client: TestClient) -> None:
operation = client.get("/openapi.json").json()["paths"]["/api/v2/models/i/{key}/image"]["patch"]
assert "404" in operation["responses"]
@@ -1518,7 +1442,7 @@ async def test_update_model_record_refuses_to_change_the_key(new_key: str) -> No
)
assert exc_info.value.status_code == 422
- deps.invoker.services.model_manager.store.update_model.assert_not_called()
+ deps.invoker.services.model_manager.update_model_record.assert_not_called()
@pytest.mark.anyio
diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.py
deleted file mode 100644
index f99c69826c..0000000000
--- a/tests/app/routers/test_update_model_record_cache_invalidation.py
+++ /dev/null
@@ -1,491 +0,0 @@
-"""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.services.model_load.model_load_common import RecordEdit
-from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
-
-
-def _no_record_edit(_key: str) -> contextlib.AbstractContextManager[RecordEdit]:
- return contextlib.nullcontext(RecordEdit())
-
-
-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,
- )
-
-
- "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):
- edit = RecordEdit()
- 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(
- record_edit=lambda _key: contextlib.nullcontext(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")
- # Loads that overlapped the edit are re-checked only when it changed how the model loads.
- assert edit.load_affecting is (field in {"path", "base", "type", "format", "variant", "repo_variant"})
-
-
-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(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]
-
-
[email protected](("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(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=True,
- default_settings=SimpleNamespace(fp8_storage=True),
- )
- 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=SimpleNamespace(fp8_storage=False),
- )
- 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(
- 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"
- assert identified.cpu_only is True
- assert identified.default_settings.fp8_storage is True
-
- for cache in caches:
- cache.drop_model.assert_called_once_with("model-key")
-
-
[email protected]("cpu_only", [False, None])
[email protected]("fp8_storage", [False, None])
-def test_reidentify_preserves_explicit_unset_preferences(
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cpu_only: bool | None, fp8_storage: bool | None
-):
- """False and None are user choices too; probe defaults must not replace them."""
- from invokeai.app.api.routers import model_manager as model_manager_router
- from invokeai.backend.model_manager.taxonomy import ModelSourceType
-
- previous = SimpleNamespace(
- key="model-key",
- path="model.safetensors",
- name="Model",
- description="",
- cover_image=None,
- source="local-source",
- source_type=ModelSourceType.Path,
- cpu_only=cpu_only,
- default_settings=SimpleNamespace(fp8_storage=fp8_storage),
- )
- identified = SimpleNamespace(
- key="model-key",
- path="model.safetensors",
- name="identified name",
- description="identified description",
- cover_image=None,
- source="new-source",
- source_type=ModelSourceType.Path,
- cpu_only=not cpu_only if cpu_only is not None else True,
- default_settings=SimpleNamespace(fp8_storage=not fp8_storage if fp8_storage is not None else True),
- )
- store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)
- services = SimpleNamespace(
- model_manager=SimpleNamespace(
- store=store,
- load=SimpleNamespace(record_edit=_no_record_edit, ram_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())
- monkeypatch.setattr(
- model_manager_router.ModelConfigFactory,
- "from_model_on_disk",
- lambda *_args, **_kwargs: SimpleNamespace(config=identified),
- )
-
- updated = model_manager_router._reidentify_model("model-key")
-
- assert updated.cpu_only is cpu_only
- assert updated.default_settings.fp8_storage is fp8_storage
-
-
[email protected]("cpu_only,fp8_storage", [(True, True), (False, False), (None, None)])
-def test_reidentify_preserves_main_model_default_settings(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
- cpu_only: bool | None,
- fp8_storage: bool | None,
-):
- """Main model CPU and FP8 preferences live in the typed default_settings object."""
- from invokeai.app.api.routers import model_manager as model_manager_router
- from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
- from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
- from invokeai.backend.model_manager.taxonomy import ModelSourceType, ModelVariantType, SchedulerPredictionType
-
- def main_config(*, name: str, settings: MainModelDefaultSettings) -> Main_Checkpoint_SD1_Config:
- return Main_Checkpoint_SD1_Config(
- hash=f"hash-{name}",
- path="model.safetensors",
- file_size=1,
- name=name,
- source="local-source",
- source_type=ModelSourceType.Path,
- prediction_type=SchedulerPredictionType.Epsilon,
- variant=ModelVariantType.Normal,
- default_settings=settings,
- )
-
- previous = main_config(
- name="Model",
- settings=MainModelDefaultSettings(cpu_only=cpu_only, fp8_storage=fp8_storage),
- )
- previous.key = "model-key"
- identified = main_config(
- name="Probed model",
- settings=MainModelDefaultSettings(
- cpu_only=not cpu_only if cpu_only is not None else True,
- fp8_storage=not fp8_storage if fp8_storage is not None else True,
- ),
- )
- store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)
- services = SimpleNamespace(
- model_manager=SimpleNamespace(
- store=store,
- load=SimpleNamespace(record_edit=_no_record_edit, ram_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())
- monkeypatch.setattr(
- model_manager_router.ModelConfigFactory,
- "from_model_on_disk",
- lambda *_args, **_kwargs: SimpleNamespace(config=identified),
- )
-
- updated = model_manager_router._reidentify_model("model-key")
-
- assert isinstance(updated, Main_Checkpoint_SD1_Config)
- assert updated.default_settings is not None
- assert updated.default_settings.cpu_only is cpu_only
- assert updated.default_settings.fp8_storage is fp8_storage
-
-
-def test_reidentify_does_not_mutate_shared_architecture_defaults(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-):
- from invokeai.app.api.routers import model_manager as model_manager_router
- from invokeai.backend.architectures.facets.default_settings import DefaultSettingsFacet
- from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
- from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
- from invokeai.backend.model_manager.taxonomy import ModelSourceType, ModelVariantType, SchedulerPredictionType
-
- shared_defaults = MainModelDefaultSettings(cpu_only=None, fp8_storage=True)
- facet = DefaultSettingsFacet(by_variant={None: shared_defaults})
- assert facet.resolve() is shared_defaults
-
- def main_config(*, name: str, settings: MainModelDefaultSettings) -> Main_Checkpoint_SD1_Config:
- return Main_Checkpoint_SD1_Config(
- hash=f"hash-{name}",
- path="model.safetensors",
- file_size=1,
- name=name,
- source="local-source",
- source_type=ModelSourceType.Path,
- prediction_type=SchedulerPredictionType.Epsilon,
- variant=ModelVariantType.Normal,
- default_settings=settings,
- )
-
- previous = main_config(
- name="Model",
- settings=MainModelDefaultSettings(cpu_only=True, fp8_storage=False),
- )
- previous.key = "model-key"
- identified = main_config(name="Probed model", settings=facet.resolve())
- store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)
- services = SimpleNamespace(
- model_manager=SimpleNamespace(
- store=store,
- load=SimpleNamespace(record_edit=_no_record_edit, ram_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())
- monkeypatch.setattr(
- model_manager_router.ModelConfigFactory,
- "from_model_on_disk",
- lambda *_args, **_kwargs: SimpleNamespace(config=identified),
- )
-
- updated = model_manager_router._reidentify_model("model-key")
- later_model_defaults = facet.resolve()
-
- assert updated.default_settings is not shared_defaults
- assert updated.default_settings is not None
- assert updated.default_settings.cpu_only is True
- assert updated.default_settings.fp8_storage is False
- assert later_model_defaults is shared_defaults
- assert later_model_defaults.cpu_only is None
- assert later_model_defaults.fp8_storage is True
-
-
-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.zeros(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(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 --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index 22a0d8b540..44af372234 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -47,8 +47,8 @@ from tests.test_nodes import TestEventService
MODEL_ID = "test-model-hash"
DIM = 8
-# An encoder swap evicts the retired model from every per-device cache; most tests have none.
-_NO_MODEL_CACHES = SimpleNamespace(ram_caches={})
+# An encoder swap evicts the retired model from the model caches; these tests have nothing cached.
+_NO_MODEL_CACHES = SimpleNamespace(drop_cached_models=lambda keys: 0)
def _wait_until(predicate: Callable[[], bool], timeout: float = 10.0) -> None:
@@ -757,12 +757,22 @@ def test_encoder_replacement_waits_for_inflight_embedding_and_discards_retired_b
ImageIndexService, "_resolve_model_config", lambda self, name: installed[0] if installed else None
)
monkeypatch.setattr(ImageIndexService, "_encode_with_model", encode)
+ # Each call's keys: the swap must evict both the retired and the replacement encoder.
+ drops: list[set[str]] = []
+
+ def drop_cached_models(keys) -> int:
+ drops.append(set(keys))
+ return 0
+
+ model_manager = SimpleNamespace(load=SimpleNamespace(drop_cached_models=drop_cached_models))
service = ImageIndexService()
query = None
try:
if background_batch:
_save_image(image_records, "pending.png")
- service.start(_make_invoker(images_service, index_records, image_records=image_records))
+ service.start(
+ _make_invoker(images_service, index_records, image_records=image_records, model_manager=model_manager)
+ )
if not background_batch:
query = threading.Thread(target=lambda: service.embed_image(Image.new("RGB", (16, 16))))
query.start()
@@ -795,6 +805,7 @@ def test_encoder_replacement_waits_for_inflight_embedding_and_discards_retired_b
else:
service.embed_image(Image.new("RGB", (16, 16)))
assert seen_models == [encoder_config, replacement]
+ assert {encoder_config.key, replacement.key} in drops
finally:
release.set()
if query is not None:
diff --git a/tests/app/services/model_load/test_stale_model_load_fence.py b/tests/app/services/model_load/test_stale_model_load_fence.py
index becd772141..694be0da42 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
@@ -2,6 +2,7 @@
that edit's invalidation; later loads must build from the updated record."""
import contextlib
+import gc
import threading
import time
from pathlib import Path
@@ -60,6 +61,15 @@ class _LoadEvents:
self.log.append(("complete", config.name))
[email protected](autouse=True)
+def _collect_only_this_tests_objects():
+ """Every drop runs gc.collect(), and a full collection walks the worker's whole heap. Freezing what existed
+ before the test leaves each collection to the objects the test created."""
+ gc.freeze()
+ yield
+ gc.unfreeze()
+
+
@pytest.fixture
def harness(tmp_path: Path):
_RecordingLoader.built_from = []
@@ -90,14 +100,9 @@ def harness(tmp_path: Path):
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 _apply(service: ModelLoadService, store: ModelRecordServiceSQL, changes: ModelRecordChanges) -> None:
+ """A record edit as `ModelManagerService.update_model_record` applies it."""
+ service.apply_record_change(KEY, lambda: store.update_model(KEY, changes=changes, allow_class_change=True))
def _long_transaction(store: ModelRecordServiceSQL) -> ContextManager[object]:
@@ -148,7 +153,7 @@ def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record
service, store, cache, events = harness
stale = store.get_model(KEY)
- _edit_and_invalidate(service, store, cache, ModelRecordChanges(cpu_only=True))
+ _apply(service, store, ModelRecordChanges(cpu_only=True))
loaded = service.load_model(stale)
assert loaded.config.cpu_only is True
@@ -158,10 +163,17 @@ def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record
assert events.log == [("started", "siglip"), ("complete", "siglip")]
-def test_metadata_only_edit_while_a_load_waits_on_construction_lock_does_not_reject_it(harness, monkeypatch):
- """A rename changes nothing that loads, so a load that read the old name and is queued behind an
- unrelated construction while the rename lands is built as it is, without a retry."""
[email protected]("change", ["rename", "same_path_made_absolute"])
+def test_edit_changing_nothing_that_loads_while_a_load_waits_on_construction_lock_does_not_reject_it(
+ harness, monkeypatch, tmp_path: Path, change: str
+):
+ """A rename changes nothing that loads, and neither does rewriting the path to the absolute form of the same
+ file, so a load that read the old record and is queued behind an unrelated construction while the edit lands
+ is built as it is, without a retry."""
service, store, cache, events = harness
+ changes = (
+ ModelRecordChanges(name="renamed") if change == "rename" else ModelRecordChanges(path=str(tmp_path / "siglip"))
+ )
waits = _waits_for_edits(service, monkeypatch)
outcome: list[LoadedModel] = []
loader = threading.Thread(target=lambda: outcome.append(service.load_model(store.get_model(KEY))))
@@ -172,12 +184,16 @@ def test_metadata_only_edit_while_a_load_waits_on_construction_lock_does_not_rej
while MODEL_LOAD_LOCK._writers_waiting == 0:
assert time.monotonic() < deadline, "loader never queued for the construction lock"
time.sleep(0.001)
- # As `update_model_record` performs a rename: bracketed, and cleared as changing nothing that loads.
- with service.record_edit(KEY) as edit:
- store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))
- edit.load_affecting = False
+ # On its own thread: an edit that wrongly counted as load-affecting would wait here for the construction
+ # lock to drop the model, and must fail the test rather than deadlock it.
+ editor = threading.Thread(target=_apply, args=(service, store, changes))
+ editor.start()
+ editor.join(timeout=10)
+ edit_waited_for_the_lock = editor.is_alive()
+ editor.join(timeout=10)
loader.join(timeout=10)
+ assert not edit_waited_for_the_lock, "the edit dropped the model as if it changed how it loads"
assert len(outcome) == 1
assert _RecordingLoader.built_from == [None]
assert _is_cached(cache)
@@ -185,6 +201,204 @@ def test_metadata_only_edit_while_a_load_waits_on_construction_lock_does_not_rej
assert waits.acquire(timeout=0) and not waits.acquire(timeout=0)
+def _queue_load_behind_a_construction(
+ service: ModelLoadService, config: AnyModelConfig, waits: threading.Semaphore
+) -> tuple[threading.Thread, list[object]]:
+ """Start a load of `config` and return once it has checked the record and queued for the construction lock,
+ which the caller holds. The returned list receives what the load returned or raised."""
+ outcome: list[object] = []
+
+ def run() -> None:
+ try:
+ outcome.append(service.load_model(config))
+ except BaseException as e:
+ outcome.append(e)
+
+ loader = threading.Thread(target=run, daemon=True)
+ 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)
+ # Its wait for edits before reading the record.
+ assert waits.acquire(timeout=10)
+ return loader, outcome
+
+
+def _run_change(change: Callable[[], object]) -> tuple[threading.Thread, list[BaseException]]:
+ """Start `change` on its own thread; a change that waits for a lock the test holds must fail the test, not
+ hang it."""
+ errors: list[BaseException] = []
+
+ def run() -> None:
+ try:
+ change()
+ except BaseException as e:
+ errors.append(e)
+
+ editor = threading.Thread(target=run, daemon=True)
+ editor.start()
+ return editor, errors
+
+
+def test_load_queued_while_a_change_commits_is_rebuilt_from_the_changed_record(harness, monkeypatch):
+ """A load that checked the record and queued for the construction lock before a load-affecting change committed
+ must not cache what it read. The change is announced from before its commit, so the load, checked while the
+ change is still in progress, is rejected and rebuilt from the changed record once the change has ended."""
+ service, store, cache, events = harness
+ waits = _waits_for_edits(service, monkeypatch)
+ committed = threading.Event()
+
+ with MODEL_LOAD_LOCK.write_lock(): # an unrelated construction in progress
+ loader, outcome = _queue_load_behind_a_construction(service, store.get_model(KEY), waits)
+
+ def write() -> AnyModelConfig:
+ updated = store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ committed.set()
+ # Stay inside the change, after its commit, until the load has been checked against it: rejected and
+ # waiting for the change to end, or - were the commit announced too late - admitted and finished.
+ deadline = time.monotonic() + 10
+ while loader.is_alive() and not waits.acquire(timeout=0.01):
+ assert time.monotonic() < deadline, "the load was neither rejected nor finished"
+ return updated
+
+ editor, errors = _run_change(lambda: service.apply_record_change(KEY, write))
+ assert committed.wait(timeout=10)
+ editor.join(timeout=10)
+ loader.join(timeout=10)
+
+ assert not editor.is_alive() and not errors
+ assert not loader.is_alive() and len(outcome) == 1
+ assert isinstance(outcome[0], LoadedModel) and outcome[0].config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]
+ assert _is_cached(cache)
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]
+
+
+def test_load_checked_before_a_change_that_failed_after_committing_is_rebuilt_from_the_stored_record(
+ harness, monkeypatch
+):
+ """A write can fail after its commit. The change may then have changed how the model loads, so a load that
+ checked the record before it and reaches construction only after it ended is rejected and rebuilt from the
+ record as stored, not built from what it read."""
+ service, store, _, _ = harness
+ checked, admit = threading.Event(), threading.Event()
+ config_is_current = service._config_is_current
+
+ def check_then_wait(config: AnyModelConfig) -> bool:
+ current = config_is_current(config)
+ checked.set()
+ assert admit.wait(timeout=10)
+ return current
+
+ monkeypatch.setattr(service, "_config_is_current", check_then_wait)
+ outcome: list[object] = []
+
+ def load() -> None:
+ try:
+ outcome.append(service.load_model(store.get_model(KEY)))
+ except BaseException as e:
+ outcome.append(e)
+
+ loader = threading.Thread(target=load, daemon=True)
+ loader.start()
+ assert checked.wait(timeout=10)
+
+ def write() -> AnyModelConfig:
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ raise RuntimeError("failed after its commit")
+
+ try:
+ with pytest.raises(RuntimeError, match="failed after its commit"):
+ service.apply_record_change(KEY, write)
+ finally:
+ admit.set()
+ loader.join(timeout=10)
+
+ assert not loader.is_alive() and len(outcome) == 1
+ assert isinstance(outcome[0], LoadedModel) and outcome[0].config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]
+
+
+def _warm(service: ModelLoadService, store: ModelRecordServiceSQL) -> None:
+ """Load the model and use it once, so its first-use hold is released and a drop evicts it outright."""
+ with service.load_model(store.get_model(KEY)):
+ pass
+ assert _is_cached(service.ram_cache)
+
+
+def test_a_change_drops_the_model_before_it_ends(harness):
+ """Loads of a model wait for its changes to end, so the cached instance must be gone by then: a load that starts
+ once the change has ended must find nothing to reuse."""
+ service, store, cache, _ = harness
+ _warm(service, store)
+ change_in_progress_at_drop: list[bool] = []
+
+ def observe_drop(**_) -> None:
+ tracked = service._record_edits._keys.get(KEY)
+ change_in_progress_at_drop.append(tracked is not None and tracked.in_progress > 0)
+
+ cache.on_cache_models_cleared(observe_drop)
+
+ _apply(service, store, ModelRecordChanges(cpu_only=True))
+
+ assert change_in_progress_at_drop == [True]
+ assert not _is_cached(cache)
+
+
+def test_change_that_fails_after_committing_a_load_affecting_change_drops_the_cached_model(harness):
+ """A write can commit and then fail; the cached instance, built from the record before it, must not be reused."""
+ service, store, cache, _ = harness
+ _warm(service, store)
+
+ def write() -> AnyModelConfig:
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ raise RuntimeError("failed after its commit")
+
+ with pytest.raises(RuntimeError, match="failed after its commit"):
+ service.apply_record_change(KEY, write)
+
+ assert not _is_cached(cache)
+ assert service.load_model(store.get_model(KEY)).config.cpu_only is True
+ assert _RecordingLoader.built_from == [None, True]
+
+
+def test_change_that_fails_after_committing_only_a_rename_keeps_the_cached_model(harness):
+ """A failed edit whose commit changed nothing that loads must not unload a model that may be in use."""
+ service, store, cache, _ = harness
+ _warm(service, store)
+
+ def write() -> AnyModelConfig:
+ store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))
+ raise ValueError("rejected")
+
+ with pytest.raises(ValueError, match="rejected"):
+ service.apply_record_change(KEY, write)
+
+ assert _is_cached(cache)
+ service.load_model(store.get_model(KEY))
+ assert _RecordingLoader.built_from == [None]
+
+
+def test_change_that_fails_when_the_record_cannot_be_read_back_drops_the_cached_model(harness, monkeypatch):
+ """With the stored record unknown (the database went away mid-write, say), the change may have committed
+ anything, so the cached instance is dropped; the caller still sees the write's own error."""
+ service, store, cache, _ = harness
+ _warm(service, store)
+
+ def unreadable(key: str) -> AnyModelConfig:
+ raise OSError("database unavailable")
+
+ def write() -> AnyModelConfig:
+ monkeypatch.setattr(store, "get_model", unreadable)
+ raise RuntimeError("write failed")
+
+ with pytest.raises(RuntimeError, match="write failed"):
+ service.apply_record_change(KEY, write)
+
+ assert not _is_cached(cache)
+
+
def _run_with_edit_while_queued_on_construction_lock(
service: ModelLoadService, store: ModelRecordServiceSQL, cache: ModelCache, load: Callable[[], object]
) -> object:
@@ -205,7 +419,7 @@ def _run_with_edit_while_queued_on_construction_lock(
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):
+ with service._record_edits.edit(KEY):
store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
cache.drop_model(KEY)
loader.join(timeout=10)
@@ -270,7 +484,7 @@ def test_edit_starting_while_load_waits_but_invalidating_after_it_is_not_built_f
while MODEL_LOAD_LOCK._writers_waiting == 0:
assert time.monotonic() < deadline, "loader never queued for the construction lock"
time.sleep(0.001)
- edit = service.record_edit(KEY)
+ edit = service._record_edits.edit(KEY)
edit.__enter__()
if commit_before_rejection:
store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
@@ -302,7 +516,7 @@ def test_load_overlapping_an_edit_stuck_on_the_database_does_not_hold_the_model_
committing = threading.Event()
def edit() -> None:
- with service.record_edit(KEY):
+ with service._record_edits.edit(KEY):
committing.set()
store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
with MODEL_LOAD_LOCK.write_lock():
@@ -427,7 +641,7 @@ def test_load_from_record_read_before_the_model_was_moved_loads_from_its_new_pat
service, store, cache, events = harness
stale = store.get_model(KEY)
(tmp_path / "siglip").rename(tmp_path / "moved")
- _edit_and_invalidate(service, store, cache, ModelRecordChanges(path="moved"))
+ _apply(service, store, ModelRecordChanges(path="moved"))
loaded = service.load_model(stale)
@@ -450,10 +664,10 @@ def test_edit_tracking_is_retired_once_no_edit_or_load_needs_it(harness):
or a load is between its record read and its check under the construction lock."""
service, store, _, _ = harness
for i in range(100):
- with service.record_edit(f"deleted-{i}"):
+ with service._record_edits.edit(f"deleted-{i}"):
pass
service.load_model(store.get_model(KEY))
- with service.record_edit(KEY):
+ with service._record_edits.edit(KEY):
pass
assert service._record_edits._keys == {}
@@ -473,10 +687,12 @@ def test_rename_then_load_affecting_edit_while_a_load_waits_rejects_it(harness,
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) as rename:
- store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))
- rename.load_affecting = False
- edit = service.record_edit(KEY)
+ # On its own thread: a rename wrongly counted as load-affecting would wait here for the construction lock
+ # to drop the model, and must fail the test rather than deadlock it.
+ editor, errors = _run_change(lambda: _apply(service, store, ModelRecordChanges(name="renamed")))
+ editor.join(timeout=10)
+ assert not editor.is_alive() and not errors, "the rename dropped the model as if it changed how it loads"
+ edit = service._record_edits.edit(KEY)
edit.__enter__()
store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
try:
diff --git a/tests/app/services/model_manager/test_model_record_changes.py b/tests/app/services/model_manager/test_model_record_changes.py
new file mode 100644
index 0000000000..cf7b73f2cd
--- /dev/null
+++ b/tests/app/services/model_manager/test_model_record_changes.py
@@ -0,0 +1,457 @@
+"""Model record edits and re-identification through the model manager: they write the record and drop cached
+instances of the model exactly when the change affects how it loads. The load fence these changes announce
+themselves to is covered by `tests/app/services/model_load/test_stale_model_load_fence.py`."""
+
+import gc
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Iterator, Optional
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.download import DownloadQueueService
+from invokeai.app.services.model_install import ModelInstallService
+from invokeai.app.services.model_load import ModelLoadService
+from invokeai.app.services.model_manager import ModelManagerService
+from invokeai.app.services.model_records import (
+ InvalidModelException,
+ ModelRecordChanges,
+ ModelRecordServiceSQL,
+ UnknownModelException,
+)
+from invokeai.backend.model_manager.configs.clip_embed import CLIPEmbed_Checkpoint_L_Config
+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
+from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI_SD1_Config
+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config, Main_Checkpoint_SDXL_Config
+from invokeai.backend.model_manager.configs.spandrel import Spandrel_Checkpoint_Config
+from invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
+from invokeai.backend.model_manager.taxonomy import (
+ AnyModel,
+ BaseModelType,
+ ModelSourceType,
+ ModelVariantType,
+ SubModelType,
+)
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.backend.model_manager.load.state_dicts import clip_g_comfy_keys, clip_l_comfy_keys
+from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors
+from tests.fixtures.spandrel_models import write_compact_upscaler
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+KEY = "model-key"
+MODEL_PATH = "sd-1/main/model.safetensors"
+
+
+class _RecordingLoader(ModelLoader):
+ """Builds a tiny module and records the config class each construction was built from."""
+
+ built_from: list[str] = []
+
+ def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:
+ self.built_from.append(type(config).__name__)
+ 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 _NoEvents:
+ def emit_model_load_started(self, *_args) -> None:
+ pass
+
+ def emit_model_load_complete(self, *_args) -> None:
+ pass
+
+
+class _Harness:
+ def __init__(self, models_path: Path) -> None:
+ self.models_path = models_path
+ app_config = InvokeAIAppConfig(use_memory_db=True, models_dir=models_path)
+ logger = InvokeAILogger.get_logger()
+ self.store = ModelRecordServiceSQL(create_mock_sqlite_database(app_config, logger), logger)
+ self.caches = [
+ 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,
+ )
+ for _ in range(2)
+ ]
+ load = ModelLoadService(
+ app_config=app_config,
+ ram_cache=self.caches[0],
+ registry=_Registry, # type: ignore[arg-type]
+ ram_caches={"cpu": self.caches[0], "cpu:1": self.caches[1]},
+ )
+ install = ModelInstallService(
+ app_config=app_config, record_store=self.store, download_queue=DownloadQueueService()
+ )
+ self.manager = ModelManagerService(store=self.store, install=install, load=load)
+ # Only the load service is started: it reads the record through the invoker, and the installer's start
+ # would scan the models directory.
+ load.start(SimpleNamespace(services=SimpleNamespace(model_manager=self.manager, events=_NoEvents()))) # type: ignore[arg-type]
+
+ def cache_model(self, key: str = KEY) -> None:
+ """Put a model and one of its submodels into every device cache, beside an unrelated model."""
+ for cache in self.caches:
+ cache.put(key, torch.ones(2))
+ cache.put(f"{key}:vae", torch.ones(2))
+ cache.put("other-model", torch.ones(2))
+
+ def is_cached(self, key: str = KEY) -> bool:
+ """Whether the model is cached, failing the test if the device caches or its entries disagree."""
+ states = {entry in cache._cached_models for cache in self.caches for entry in (key, f"{key}:vae")}
+ assert len(states) == 1, "the change dropped only some of the model's entries"
+ assert all("other-model" in cache._cached_models for cache in self.caches)
+ return states.pop()
+
+
[email protected](autouse=True)
+def _collect_only_this_tests_objects():
+ """Every drop runs gc.collect(), and a full collection walks the worker's whole heap. Freezing what existed
+ before the test leaves each collection to the objects the test created."""
+ gc.freeze()
+ yield
+ gc.unfreeze()
+
+
+def harness(tmp_path: Path) -> Iterator[_Harness]:
+ _RecordingLoader.built_from = []
+ models_path = tmp_path / "models"
+ models_path.mkdir()
+ harness = _Harness(models_path)
+ yield harness
+ for cache in harness.caches:
+ cache.shutdown()
+
+
+def _sd1_record(**fields) -> Main_Checkpoint_SD1_Config:
+ defaults = {
+ "key": KEY,
+ "path": MODEL_PATH,
+ "name": "model",
+ "hash": "hash",
+ "file_size": 1,
+ "source": "local-source",
+ "source_type": ModelSourceType.Path,
+ "prediction_type": "epsilon",
+ "variant": ModelVariantType.Normal,
+ }
+ return Main_Checkpoint_SD1_Config(**{**defaults, **fields})
+
+
+def _write_sd_checkpoint(path: Path, base: BaseModelType) -> Path:
+ """The few keys SD checkpoint identification reads, at the widths that tell SD-1 from SDXL."""
+ cross_attention = {
+ BaseModelType.StableDiffusion1: ("model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2", 768),
+ BaseModelType.StableDiffusionXL: ("model.diffusion_model.input_blocks.4.1.transformer_blocks.0.attn2", 2048),
+ }
+ prefix, width = cross_attention[base]
+ path.parent.mkdir(parents=True, exist_ok=True)
+ save_file(
+ {
+ f"{prefix}.to_k.weight": torch.zeros(1, width),
+ "model.diffusion_model.input_blocks.0.0.weight": torch.zeros(1, 4, 1, 1),
+ },
+ path,
+ )
+ return path
+
+
+def _identify(model_file: Path, overrides: Optional[dict[str, object]] = None, /, **record_fields) -> AnyModelConfig:
+ """The record an install of `model_file` would have written, with `record_fields` then set on it."""
+ config = ModelConfigFactory.from_model_on_disk(
+ model_file,
+ {"source": "local-source", "source_type": ModelSourceType.Path, **(overrides or {})},
+ allow_unknown=False,
+ ).config
+ assert config is not None
+ for field, value in record_fields.items():
+ setattr(config, field, value)
+ return config
+
+
+ ("changes", "load_affecting"),
+ [
+ pytest.param(ModelRecordChanges(name="renamed"), False, id="name"),
+ pytest.param(ModelRecordChanges(description="described"), False, id="description"),
+ pytest.param(ModelRecordChanges(trigger_phrases={"a phrase"}), False, id="trigger_phrases"),
+ pytest.param(
+ ModelRecordChanges(default_settings=MainModelDefaultSettings(steps=12)), False, id="generation_default"
+ ),
+ pytest.param(
+ ModelRecordChanges(default_settings=MainModelDefaultSettings(fp8_storage=True)), True, id="fp8_storage"
+ ),
+ pytest.param(ModelRecordChanges(default_settings=MainModelDefaultSettings(cpu_only=True)), True, id="cpu_only"),
+ pytest.param(ModelRecordChanges(variant=ModelVariantType.Inpaint), True, id="variant"),
+ pytest.param(ModelRecordChanges(base=BaseModelType.StableDiffusionXL), True, id="config_class"),
+ pytest.param(ModelRecordChanges(path="sd-1/main/other.safetensors"), True, id="other_file"),
+ ],
+)
+def test_update_drops_cached_instances_only_when_the_change_affects_loading(
+ harness: _Harness, changes: ModelRecordChanges, load_affecting: bool
+) -> None:
+ harness.store.add_model(_sd1_record())
+ harness.cache_model()
+
+ updated = harness.manager.update_model_record(KEY, changes)
+
+ assert harness.is_cached() is not load_affecting
+ assert harness.store.get_model(KEY) == updated
+ for field in changes.model_fields_set:
+ assert getattr(updated, field) == getattr(changes, field)
+
+
+def test_update_rewriting_a_path_to_the_same_file_in_absolute_form_keeps_cached_instances(harness: _Harness) -> None:
+ """The load fence resolves paths against the models directory, so a models-relative path and the absolute path
+ of the same file load the same model. The edit must compare them the same way, or it evicts a model it did not
+ change and rejects the loads that overlapped it."""
+ harness.store.add_model(_sd1_record())
+ harness.cache_model()
+
+ harness.manager.update_model_record(KEY, ModelRecordChanges(path=str(harness.models_path / MODEL_PATH)))
+
+ assert harness.is_cached()
+
+
+def test_cached_instances_are_dropped_under_the_model_load_write_lock(harness: _Harness) -> None:
+ """Holding the construction lock across the drop keeps a concurrent load from re-registering state it built
+ from the previous record."""
+ harness.store.add_model(_sd1_record())
+ harness.cache_model()
+ drops_under_write_lock: list[bool] = []
+ for cache in harness.caches:
+ cache.on_cache_models_cleared(lambda **_: drops_under_write_lock.append(MODEL_LOAD_LOCK._writer_active))
+
+ harness.manager.update_model_record(
+ KEY, ModelRecordChanges(default_settings=MainModelDefaultSettings(cpu_only=True))
+ )
+
+ assert drops_under_write_lock == [True, True]
+
+
+def test_update_that_the_store_rejects_changes_nothing(harness: _Harness) -> None:
+ record = _sd1_record()
+ harness.store.add_model(record)
+ harness.cache_model()
+
+ with pytest.raises(ValueError, match="at most"):
+ harness.manager.update_model_record(KEY, ModelRecordChanges(path="x" * 800))
+
+ assert harness.store.get_model(KEY) == record
+ assert harness.is_cached()
+
+
+def test_update_of_an_unknown_model_raises_and_drops_nothing(harness: _Harness) -> None:
+ harness.cache_model()
+
+ with pytest.raises(UnknownModelException):
+ harness.manager.update_model_record(KEY, ModelRecordChanges(name="renamed"))
+
+ assert harness.is_cached()
+
+
[email protected]("cpu_only", [True, False, None])
[email protected]("fp8_storage", [True, False, None])
+def test_reidentify_refiles_a_misidentified_model_and_keeps_what_the_user_set(
+ harness: _Harness, cpu_only: Optional[bool], fp8_storage: Optional[bool]
+) -> None:
+ """Re-identification replaces what the files decide (here SD-1 becomes SDXL, a load-affecting change) and keeps
+ the user's fields. False and None are user choices too: probe defaults must not replace them."""
+ _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusionXL)
+ harness.store.add_model(
+ _sd1_record(
+ name="My model",
+ description="mine",
+ cover_image="cover.webp",
+ trigger_phrases={"a phrase"},
+ default_settings=MainModelDefaultSettings(cpu_only=cpu_only, fp8_storage=fp8_storage, steps=12),
+ )
+ )
+ harness.cache_model()
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, Main_Checkpoint_SDXL_Config)
+ assert harness.store.get_model(KEY) == updated
+ assert (updated.key, updated.path, updated.name, updated.description) == (KEY, MODEL_PATH, "My model", "mine")
+ assert updated.trigger_phrases == {"a phrase"}
+ assert updated.cover_image == "cover.webp"
+ assert (updated.source, updated.source_type) == ("local-source", ModelSourceType.Path)
+ assert updated.default_settings is not None
+ assert (updated.default_settings.cpu_only, updated.default_settings.fp8_storage) == (cpu_only, fp8_storage)
+ # Other defaults are the architecture's: only the load preferences are the user's to keep.
+ assert updated.default_settings.width == 1024
+ assert not harness.is_cached()
+ # The probe hands out an architecture's shared defaults; the kept preferences must not leak into them.
+ later_install = _identify(harness.models_path / MODEL_PATH)
+ assert later_install.default_settings is not None
+ assert (later_install.default_settings.cpu_only, later_install.default_settings.fp8_storage) == (None, None)
+
+
+def test_reidentify_while_a_load_of_the_old_record_is_queued_rebuilds_it_from_the_new_record(
+ harness: _Harness,
+) -> None:
+ """A load that checked the SD-1 record and queued for the construction lock while re-identification files the
+ model as SDXL must not build from the record it read: re-identification is announced to loads from before its
+ commit until after its cache drop."""
+ _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusionXL)
+ harness.store.add_model(_sd1_record())
+ stale = harness.store.get_model(KEY)
+ loads: list[object] = []
+ errors: list[BaseException] = []
+
+ def load() -> None:
+ try:
+ loads.append(harness.manager.load.load_model(stale))
+ except BaseException as e:
+ loads.append(e)
+
+ def reidentify() -> None:
+ try:
+ harness.manager.reidentify_model(KEY)
+ except BaseException as e:
+ errors.append(e)
+
+ # Daemon threads: a regression that deadlocks must fail the test, not hang it.
+ loader = threading.Thread(target=load, daemon=True)
+ editor = threading.Thread(target=reidentify, daemon=True)
+ 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)
+ editor.start()
+ # Until re-identification has committed and waits to drop the model, or has ended without dropping it.
+ while MODEL_LOAD_LOCK._writers_waiting < 2 and editor.is_alive():
+ assert time.monotonic() < deadline + 10, "re-identification neither finished nor reached its drop"
+ time.sleep(0.001)
+ editor.join(timeout=10)
+ loader.join(timeout=10)
+
+ assert not editor.is_alive() and not errors
+ assert not loader.is_alive() and len(loads) == 1
+ assert isinstance(loads[0], LoadedModel) and isinstance(loads[0].config, Main_Checkpoint_SDXL_Config)
+ assert _RecordingLoader.built_from == ["Main_Checkpoint_SDXL_Config"]
+
+
+def test_reidentify_that_changes_nothing_that_loads_keeps_cached_instances(harness: _Harness) -> None:
+ path = _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusion1)
+ installed = _identify(path, key=KEY, path=MODEL_PATH, name="My model")
+ harness.store.add_model(installed)
+ harness.cache_model()
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert updated == installed
+ assert harness.is_cached()
+
+
[email protected]("cpu_only", [True, False])
+def test_reidentify_keeps_a_cpu_only_choice_held_on_the_config_itself(harness: _Harness, cpu_only: bool) -> None:
+ """Text encoders keep `cpu_only` beside their other fields rather than in default settings."""
+ path = write_header_only_safetensors(harness.models_path / "clip-l.safetensors", clip_l_comfy_keys.state_dict_keys)
+ installed = _identify(path, key=KEY, path="clip-l.safetensors", name="CLIP-L")
+ assert isinstance(installed, CLIPEmbed_Checkpoint_L_Config)
+ installed.cpu_only = cpu_only
+ harness.store.add_model(installed)
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, CLIPEmbed_Checkpoint_L_Config)
+ assert updated.cpu_only is cpu_only
+
+
+def test_reidentify_keeps_an_ip_adapter_encoder_override_its_files_leave_blank(harness: _Harness) -> None:
+ model_path = harness.models_path / "ip-adapter"
+ model_path.mkdir()
+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, model_path / "ip_adapter.bin")
+ (model_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")
+ installed = _identify(
+ model_path, {"image_encoder_model_id": "custom/image-encoder"}, key=KEY, path="ip-adapter", name="IP-Adapter"
+ )
+ assert isinstance(installed, IPAdapter_InvokeAI_SD1_Config)
+ harness.store.add_model(installed)
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, IPAdapter_InvokeAI_SD1_Config)
+ assert updated.image_encoder_model_id == "custom/image-encoder"
+
+
+def test_reidentify_records_the_scale_of_an_upscaler_installed_before_it_was_recorded(harness: _Harness) -> None:
+ """The recorded scale is part of the record, so the rewrite counts as load-affecting: a cached instance built
+ from the scale-less record is dropped."""
+ path = write_compact_upscaler(harness.models_path / "4x-compact.safetensors", 4)
+ installed = _identify(path, key=KEY, path="4x-compact.safetensors", scale=None)
+ assert isinstance(installed, Spandrel_Checkpoint_Config)
+ harness.store.add_model(installed)
+ harness.cache_model()
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, Spandrel_Checkpoint_Config) and updated.scale == 4
+ assert harness.store.get_model(KEY) == updated
+ assert not harness.is_cached()
+
+
+def test_reidentify_keeps_a_backbone_only_the_install_source_names(harness: _Harness) -> None:
+ """A 16-channel VAE is FLUX.1's or SD3's by its name alone. Copied into the models folder it keeps a generic
+ file name in a folder named for its key, and only the Hugging Face source still says SD3."""
+ path = harness.models_path / "7c1f9d2e" / "diffusion_pytorch_model.safetensors"
+ path.parent.mkdir()
+ save_file(
+ {"encoder.conv_in.weight": torch.zeros(8, 3, 3, 3), "decoder.conv_in.weight": torch.zeros(8, 16, 3, 3)}, path
+ )
+ installed = ModelConfigFactory.from_model_on_disk(
+ path,
+ {
+ "key": KEY,
+ "source": "stabilityai/stable-diffusion-3.5-large::vae/diffusion_pytorch_model.safetensors",
+ "source_type": ModelSourceType.HFRepoID,
+ },
+ allow_unknown=False,
+ ).config
+ assert installed is not None and installed.base is BaseModelType.StableDiffusion3
+ harness.store.add_model(installed)
+
+ assert harness.manager.reidentify_model(KEY).base is BaseModelType.StableDiffusion3
+
+
+def test_reidentify_of_files_no_config_accepts_raises_and_keeps_the_record(harness: _Harness) -> None:
+ keys = dict(clip_g_comfy_keys.state_dict_keys)
+ del keys["text_projection.weight"]
+ write_header_only_safetensors(harness.models_path / "clip-g.safetensors", keys)
+ record = _sd1_record(path="clip-g.safetensors")
+ harness.store.add_model(record)
+ harness.cache_model()
+
+ with pytest.raises(InvalidModelException):
+ harness.manager.reidentify_model(KEY)
+
+ assert harness.store.get_model(KEY) == record
+ assert harness.is_cached()
+
+
+def test_reidentify_of_an_unknown_model_raises(harness: _Harness) -> None:
+ with pytest.raises(UnknownModelException):
+ harness.manager.reidentify_model(KEY)
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 fe6dc18bc3..e3d0556626 100644
--- a/tests/app/services/model_records/test_model_records_sql.py
+++ b/tests/app/services/model_records/test_model_records_sql.py
@@ -155,6 +155,30 @@ def test_rejected_update_preserves_the_complete_stored_record(
assert after.model_dump() == before.model_dump()
[email protected]("new_key", ["key2", "../../pwned"])
+def test_update_refuses_to_change_the_key(store: ModelRecordServiceBase, new_key: str) -> None:
+ """The row keeps its key, so a different key written into the stored config would leave a record that reports
+ a key nothing can look it up by."""
+ original = example_ti_config("key1")
+ store.add_model(original)
+ before = store.get_model(original.key)
+
+ with pytest.raises(ValueError, match="key cannot be changed"):
+ store.update_model(original.key, ModelRecordChanges(key=new_key, name="renamed"), allow_class_change=True)
+
+ assert store.get_model(original.key).model_dump() == before.model_dump()
+ assert not store.exists(new_key)
+
+
+def test_update_accepts_the_unchanged_key_echoed_back(store: ModelRecordServiceBase) -> None:
+ """The edit form posts the whole record back, key included."""
+ store.add_model(example_ti_config("key1"))
+
+ updated = store.update_model("key1", ModelRecordChanges(key="key1", name="renamed"))
+
+ assert (updated.key, updated.name) == ("key1", "renamed")
+
+
def test_rejected_class_change_preserves_the_original_record(store: ModelRecordServiceBase) -> None:
original = example_ti_config("key1")
store.add_model(original)