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.

fix(model-manager): read the model record outside MODEL_LOAD_LOCK

Lincoln Stein615c3b99232c
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index b2dff99cd9..dc3238a3ca 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -502,7 +502,9 @@ def _reidentify_model(key: str) -> AnyModelConfig:
result.config.source = config.source
result.config.source_type = config.source_type
- return ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)
+ # The probe resets load-affecting settings (cpu_only, default_settings), so in-flight loads must re-check.
+ with ApiDependencies.invoker.services.model_manager.load.record_edit(config.key):
+ return ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)
class FoundModel(BaseModel):
@@ -637,7 +639,7 @@ def _update_model_record(key: str, changes: ModelRecordChanges) -> AnyModelConfi
# 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):
+ with _claim_model_key(key), ApiDependencies.invoker.services.model_manager.load.record_edit(key):
try:
previous_config = record_store.get_model(key)
config = record_store.update_model(key, changes=changes, allow_class_change=True)
diff --git a/invokeai/app/services/model_load/model_load_base.py b/invokeai/app/services/model_load/model_load_base.py
index 5fa6639297..5f8301c918 100644
--- a/invokeai/app/services/model_load/model_load_base.py
+++ b/invokeai/app/services/model_load/model_load_base.py
@@ -2,7 +2,7 @@
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Callable, Optional
+from typing import Callable, ContextManager, Optional
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load import LoadedModel, LoadedModelWithoutConfig
@@ -29,6 +29,13 @@ class ModelLoadServiceBase(ABC):
events so they can be routed to that user's UI (defaults to the system user).
"""
+ @abstractmethod
+ def record_edit(self, key: str) -> ContextManager[None]:
+ """Bracket a write of `key`'s record that may change how it loads, from before it commits until
+ after any cache invalidation it performs, so that loads which read the record meanwhile re-check it
+ under MODEL_LOAD_LOCK. Every writer of load-affecting settings must use it: a cold load trusts its
+ pre-lock record read unless a bracket was open at that read or opened since."""
+
@property
@abstractmethod
def ram_cache(self) -> ModelCache:
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index 8470f2dee6..87aa0a3e92 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -1,7 +1,9 @@
"""Implementation of model loader service."""
+import threading
+from contextlib import contextmanager
from pathlib import Path
-from typing import Callable, Optional, Type
+from typing import Callable, ContextManager, Iterator, Optional, Type
from picklescan.scanner import scan_file_path
from safetensors.torch import load_file as safetensors_load_file
@@ -28,6 +30,34 @@ from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
+class _RecordEdits:
+ """Per model key: a generation bumped as each record edit starts, and how many edits are in progress."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ # Never pruned: one int per model key ever edited.
+ self._generations: dict[str, int] = {}
+ self._in_progress: dict[str, int] = {}
+
+ @contextmanager
+ def edit(self, key: str) -> Iterator[None]:
+ with self._lock:
+ self._generations[key] = self._generations.get(key, 0) + 1
+ self._in_progress[key] = self._in_progress.get(key, 0) + 1
+ try:
+ yield
+ finally:
+ with self._lock:
+ self._in_progress[key] -= 1
+ if not self._in_progress[key]:
+ del self._in_progress[key]
+
+ def snapshot(self, key: str) -> tuple[int, bool]:
+ """(generation, whether an edit is in progress)."""
+ with self._lock:
+ return self._generations.get(key, 0), key in self._in_progress
+
+
class ModelLoadService(ModelLoadServiceBase):
"""Wrapper around ModelLoaderRegistry."""
@@ -56,6 +86,7 @@ class ModelLoadService(ModelLoadServiceBase):
self._ram_caches: dict[str, ModelCache] = dict(ram_caches) if ram_caches else {}
self._ram_caches.setdefault(str(TorchDevice.normalize(ram_cache.execution_device)), ram_cache)
self._registry = registry
+ self._record_edits = _RecordEdits()
def start(self, invoker: Invoker) -> None:
self._invoker = invoker
@@ -118,16 +149,35 @@ class ModelLoadService(ModelLoadServiceBase):
ram_cache=self.ram_cache,
)
if hasattr(self, "_invoker") and isinstance(loader, ModelLoader):
- loader.config_is_current = self._config_is_current
+ loader.config_check = self._check_config
return loader.load_model(model_config, submodel_type)
- def _config_is_current(self, config: AnyModelConfig) -> bool:
- """Whether `config` still loads the same model as the stored record for its key.
+ def record_edit(self, key: str) -> ContextManager[None]:
+ return self._record_edits.edit(key)
- Runs under the MODEL_LOAD_LOCK write lock, which is what makes it a fence, so the record read
- cannot move ahead of the lock. A long DB transaction (e.g. compaction) therefore stalls every
- MODEL_LOAD_LOCK user process-wide, not just this cold load, until it finishes.
+ def _check_config(self, config: AnyModelConfig) -> Callable[[], bool]:
+ """Check `config` against its record; the returned callable completes the check under MODEL_LOAD_LOCK.
+
+ The record is read here, before the lock, so a long DB transaction (e.g. VACUUM) stalls only this
+ load and not every MODEL_LOAD_LOCK user. An edit brackets its commit and its cache invalidation
+ with `record_edit()`, so an edit that commits after this read was either in progress when the
+ snapshot below was taken or bumped the generation since; only then is the record read again,
+ under the lock, as the invalidation that follows the commit also takes that lock.
"""
+ generation, edit_in_progress = self._record_edits.snapshot(config.key)
+ current = self._config_is_current(config)
+
+ def still_current() -> bool:
+ if not current:
+ return False
+ if edit_in_progress or self._record_edits.snapshot(config.key)[0] != generation:
+ return self._config_is_current(config)
+ return True
+
+ return still_current
+
+ def _config_is_current(self, config: AnyModelConfig) -> bool:
+ """Whether `config` still loads the same model as the stored record for its key."""
try:
current = self._invoker.services.model_manager.store.get_model(config.key)
except UnknownModelException:
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 99fb7f84a1..e87694485a 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -248,11 +248,11 @@ def _model_declared_skip_patterns(model: torch.nn.Module) -> tuple[str, ...]:
class ModelLoader(ModelLoaderBase):
"""Default implementation of ModelLoaderBase."""
- # Optionally set on an instance before `load_model()`: called with the caller's config while
- # construction is serialized against cache invalidation; False rejects the load with
- # StaleModelConfigError. An attribute rather than a constructor argument so that registered
- # loaders overriding `__init__` keep working.
- config_is_current: Optional[Callable[[AnyModelConfig], bool]] = None
+ # Optionally set on an instance before `load_model()`: on a cache miss, called with the caller's config
+ # before MODEL_LOAD_LOCK is taken; the callable it returns is called once construction is serialized
+ # against cache invalidation, and False rejects the load with StaleModelConfigError. An attribute
+ # rather than a constructor argument so that registered loaders overriding `__init__` keep working.
+ config_check: Optional[Callable[[AnyModelConfig], Callable[[], bool]]] = None
def __init__(
self,
@@ -367,6 +367,11 @@ class ModelLoader(ModelLoaderBase):
#
# Lock-ordering: the write lock is acquired before any ModelCache._lock taken below
# (get/make_room/put), matching the readers' order, so there is no AB-BA deadlock.
+ #
+ # The caller read `config` before this point. A record edit commits first and then invalidates the
+ # cache under this lock; building from a record superseded by an edit that has already invalidated
+ # would re-admit what that edit evicted, so the config check is finished under the lock.
+ still_current = self.config_check(config) if self.config_check is not None else None
with MODEL_LOAD_LOCK.write_lock():
# Double-checked locking: another worker sharing this cache may have loaded the same
# entry while we waited for the mutex. (Workers on other devices use a different cache,
@@ -376,11 +381,7 @@ class ModelLoader(ModelLoaderBase):
except IndexError:
pass
- # The caller read `config` before taking this lock. A record edit commits first and then
- # invalidates the cache under this lock, so an edit that has committed by now has either
- # dropped this model already or will drop whatever this load admits; building from the
- # superseded record in the first case would re-admit what that edit evicted.
- if self.config_is_current is not None and not self.config_is_current(config):
+ if still_current is not None and not still_current():
raise StaleModelConfigError(
f"Model '{config.name}' was modified while it was being loaded; retry with the updated model."
)
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 7db26922b9..b580dce296 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -1,7 +1,8 @@
+import contextlib
import logging
import os
from pathlib import Path
-from typing import Any
+from typing import Any, Iterator
import pytest
from fastapi.testclient import TestClient
@@ -378,7 +379,9 @@ async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch
services = SimpleNamespace(
logger=MagicMock(),
- model_manager=SimpleNamespace(store=Store(), load=SimpleNamespace(ram_caches={})),
+ model_manager=SimpleNamespace(
+ store=Store(), load=SimpleNamespace(ram_caches={}, record_edit=lambda key: contextlib.nullcontext())
+ ),
)
invoker = DummyInvoker(services)
monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(invoker))
@@ -395,6 +398,57 @@ async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch
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]]] = []
+
+ @contextlib.contextmanager
+ def record_edit(key: str) -> Iterator[None]:
+ open_edits.append(key)
+ try:
+ yield
+ finally:
+ open_edits.remove(key)
+
+ def settings(cpu_only: bool) -> Any:
+ return SimpleNamespace(cpu_only=cpu_only, default_settings=SimpleNamespace(fp8_storage=False))
+
+ class Store:
+ def get_model(self, key: str) -> Any:
+ return settings(cpu_only=False)
+
+ def update_model(self, key: str, changes: Any, allow_class_change: bool) -> Any:
+ observed.append(("commit", list(open_edits)))
+ return settings(cpu_only=True)
+
+ 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)
+ ),
+ )
+ 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())
+
+ assert observed == [("commit", ["model-key"]), ("drop", ["model-key"])]
+ assert open_edits == []
+
+
def test_convert_model_rejects_a_second_conversion_while_one_is_running() -> None:
"""Conversions are serialized, and the loser is told so instead of being made to wait.
@@ -615,12 +669,35 @@ def test_reidentify_keeps_a_backbone_only_the_install_source_names(
assert installed is not None and installed.base is BaseModelType.StableDiffusion3
mm2_record_store.add_model(installed)
- services = SimpleNamespace(model_manager=SimpleNamespace(store=mm2_record_store), configuration=mm2_app_config)
+ # 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[None]:
+ open_edits.append(key)
+ try:
+ yield
+ 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]]
@pytest.mark.anyio
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 7b3f00afe7..2d68afd01d 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
@@ -83,11 +83,14 @@ def harness(tmp_path: Path):
return service, store, cache, events
-def _edit_and_invalidate(store: ModelRecordServiceSQL, cache: ModelCache, changes: ModelRecordChanges) -> None:
+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."""
- store.update_model(KEY, changes=changes, allow_class_change=True)
- with MODEL_LOAD_LOCK.write_lock():
- cache.drop_model(KEY)
+ with service.record_edit(KEY):
+ store.update_model(KEY, changes=changes, allow_class_change=True)
+ with MODEL_LOAD_LOCK.write_lock():
+ cache.drop_model(KEY)
def _is_cached(cache: ModelCache) -> bool:
@@ -102,7 +105,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(store, cache, ModelRecordChanges(cpu_only=True))
+ _edit_and_invalidate(service, store, cache, ModelRecordChanges(cpu_only=True))
loaded = service.load_model(stale)
assert loaded.config.cpu_only is True
@@ -125,7 +128,7 @@ def test_load_from_record_read_before_metadata_only_edit_still_loads(harness):
def _run_with_edit_while_queued_on_construction_lock(
- store: ModelRecordServiceSQL, cache: ModelCache, load: Callable[[], object]
+ service: ModelLoadService, store: ModelRecordServiceSQL, cache: ModelCache, load: Callable[[], object]
) -> object:
"""The #9674 ordering: `load` reads a current record, then waits for the construction lock while
a `cpu_only` edit commits and invalidates under it. Returns what `load` returned or raised."""
@@ -144,8 +147,9 @@ 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)
- store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
- cache.drop_model(KEY)
+ with service.record_edit(KEY):
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ cache.drop_model(KEY)
loader.join(timeout=10)
assert len(outcome) == 1
return outcome[0]
@@ -155,7 +159,7 @@ def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_up
service, store, cache, events = harness
outcome = _run_with_edit_while_queued_on_construction_lock(
- store, cache, lambda: service.load_model(store.get_model(KEY))
+ service, store, cache, lambda: service.load_model(store.get_model(KEY))
)
assert isinstance(outcome, LoadedModel)
@@ -166,6 +170,30 @@ def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_up
assert events.log == [("started", "siglip"), ("complete", "siglip")]
+def test_edit_committed_while_load_waits_but_invalidating_after_it_is_not_built_from_the_old_record(harness):
+ """The load reads a current record and queues behind an unrelated construction; the edit commits
+ meanwhile but reaches its invalidation only after the load holds the construction lock."""
+ service, store, cache, _ = harness
+ outcome: list[LoadedModel] = []
+ loader = threading.Thread(target=lambda: outcome.append(service.load_model(store.get_model(KEY))))
+
+ with service.record_edit(KEY):
+ with MODEL_LOAD_LOCK.write_lock(): # an unrelated construction in progress
+ loader.start()
+ deadline = time.monotonic() + 10
+ while MODEL_LOAD_LOCK._writers_waiting == 0:
+ assert time.monotonic() < deadline, "loader never queued for the construction lock"
+ time.sleep(0.001)
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ loader.join(timeout=10)
+ with MODEL_LOAD_LOCK.write_lock():
+ cache.drop_model(KEY)
+
+ assert len(outcome) == 1
+ assert outcome[0].config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]
+
+
def test_config_object_reused_after_eviction_still_loads(harness):
"""The loader rewrites `config.path` to an absolute path in place; a service that keeps its config
object across loads must not see that as a load-affecting edit."""
@@ -195,3 +223,54 @@ def test_record_superseded_again_during_retry_raises(harness, monkeypatch):
service.load_model(store.get_model(KEY))
assert fence_checks == [KEY, KEY]
assert _RecordingLoader.built_from == []
+
+
+def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold_the_model_load_lock(
+ harness, monkeypatch
+):
+ """A long DB transaction (e.g. VACUUM) that starts after a cold load read its record, while that load
+ waits for the construction lock, must not leave the load holding MODEL_LOAD_LOCK while it waits on the
+ database: unrelated MODEL_LOAD_LOCK users, such as other devices' VRAM moves, would stall with it."""
+ service, store, cache, _ = harness
+ config = store.get_model(KEY)
+ record_reads = threading.Semaphore(0)
+ store_get_model = store.get_model
+
+ def get_model(key: str) -> AnyModelConfig:
+ record_reads.release()
+ return store_get_model(key)
+
+ monkeypatch.setattr(store, "get_model", get_model)
+ loads: list[LoadedModel] = []
+ acquired = threading.Event()
+
+ def take_model_load_lock() -> None:
+ with MODEL_LOAD_LOCK.write_lock():
+ acquired.set()
+
+ loader = threading.Thread(target=lambda: loads.append(service.load_model(config)))
+ other = threading.Thread(target=take_model_load_lock)
+ with MODEL_LOAD_LOCK.write_lock(): # an unrelated construction in progress
+ loader.start()
+ assert record_reads.acquire(timeout=10)
+ deadline = time.monotonic() + 10
+ while MODEL_LOAD_LOCK._writers_waiting == 0:
+ assert time.monotonic() < deadline, "loader never queued for the construction lock"
+ time.sleep(0.001)
+ store._db._lock.acquire() # the transaction starts; VACUUM holds this for its whole run
+ try:
+ # The loader now holds the construction lock: it either finishes without the database, or reads
+ # its record again under the lock and blocks there.
+ deadline = time.monotonic() + 10
+ while loader.is_alive() and not record_reads.acquire(timeout=0.01):
+ assert time.monotonic() < deadline, "loader neither finished nor read its record again"
+ other.start()
+ lock_was_free = acquired.wait(timeout=5)
+ finally:
+ store._db._lock.release()
+ loader.join(timeout=10)
+ other.join(timeout=10)
+
+ assert lock_was_free
+ assert len(loads) == 1
+ assert _is_cached(cache)