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): retire per-model edit tracking once no edit or load needs it

Lincoln Stein774aa8e3539c
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index f7ccf39eac..4012ca53c0 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -2,6 +2,7 @@
import threading
from contextlib import contextmanager
+from dataclasses import dataclass
from pathlib import Path
from typing import Callable, ContextManager, Iterator, Optional, Type
@@ -30,42 +31,71 @@ from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
+@dataclass
+class _KeyEdits:
+ in_progress: int = 0
+ # Loads between their record read and their check under MODEL_LOAD_LOCK.
+ watchers: int = 0
+ # Bumped as each edit that changed how the model loads ends.
+ generation: int = 0
+
+
class _RecordEdits:
- """Per model key: how many record edits are in progress, and a generation bumped as each edit that changed
- how the model loads ends."""
+ """Per model key: record edits in progress, and whether one that changed how the model loads has ended since a
+ load read the record. A key is tracked only while it has edits in progress or loads watching it: a load that
+ starts later waits for in-progress edits, so it reads their result."""
def __init__(self) -> None:
self._changed = threading.Condition(threading.Lock())
- # Never pruned: one int per model key ever edited.
- self._generations: dict[str, int] = {}
- self._in_progress: dict[str, int] = {}
+ self._keys: dict[str, _KeyEdits] = {}
+
+ def _retire_if_unused(self, key: str) -> None:
+ state = self._keys[key]
+ if not state.in_progress and not state.watchers:
+ del self._keys[key]
@contextmanager
def edit(self, key: str) -> Iterator[RecordEdit]:
record_edit = RecordEdit()
with self._changed:
- self._in_progress[key] = self._in_progress.get(key, 0) + 1
+ self._keys.setdefault(key, _KeyEdits()).in_progress += 1
try:
yield record_edit
finally:
with self._changed:
+ state = self._keys[key]
if record_edit.load_affecting:
- self._generations[key] = self._generations.get(key, 0) + 1
- self._in_progress[key] -= 1
- if not self._in_progress[key]:
- del self._in_progress[key]
+ state.generation += 1
+ state.in_progress -= 1
+ if not state.in_progress:
self._changed.notify_all()
+ self._retire_if_unused(key)
- def generation_when_idle(self, key: str) -> int:
- """Wait until no edit of `key` is in progress, then return its generation."""
+ def wait_idle(self, key: str) -> None:
+ """Wait until no edit of `key` is in progress."""
with self._changed:
- self._changed.wait_for(lambda: key not in self._in_progress)
- return self._generations.get(key, 0)
+ self._changed.wait_for(lambda: key not in self._keys or not self._keys[key].in_progress)
- def unchanged_since(self, key: str, generation: int) -> bool:
- """Whether no edit of `key` is in progress and none that changed how it loads has ended since `generation`."""
+ @contextmanager
+ def watch(self, key: str) -> Iterator[Callable[[], bool]]:
+ """Wait until no edit of `key` is in progress, then yield a callable telling whether `key` is still unedited:
+ no edit in progress, and none that changed how it loads ended since the wait."""
with self._changed:
- return key not in self._in_progress and self._generations.get(key, 0) == generation
+ self._changed.wait_for(lambda: key not in self._keys or not self._keys[key].in_progress)
+ state = self._keys.setdefault(key, _KeyEdits())
+ state.watchers += 1
+ generation = state.generation
+
+ def unchanged() -> bool:
+ with self._changed:
+ return not state.in_progress and state.generation == generation
+
+ try:
+ yield unchanged
+ finally:
+ with self._changed:
+ state.watchers -= 1
+ self._retire_if_unused(key)
class ModelLoadService(ModelLoadServiceBase):
@@ -172,7 +202,7 @@ class ModelLoadService(ModelLoadServiceBase):
def _current_record(self, key: str) -> AnyModelConfig:
"""The stored record for `key`, read once no edit of it is in progress."""
- self._record_edits.generation_when_idle(key)
+ self._record_edits.wait_idle(key)
return self._invoker.services.model_manager.store.get_model(key)
def _moved_record(self, config: AnyModelConfig) -> Optional[AnyModelConfig]:
@@ -187,8 +217,9 @@ class ModelLoadService(ModelLoadServiceBase):
return current
return None
- def _check_config(self, config: AnyModelConfig) -> Callable[[], bool]:
- """Check `config` against its record; the returned callable completes the check under MODEL_LOAD_LOCK.
+ @contextmanager
+ def _check_config(self, config: AnyModelConfig) -> Iterator[Callable[[], bool]]:
+ """Check `config` against its record; the yielded callable completes the check under MODEL_LOAD_LOCK.
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
@@ -197,9 +228,9 @@ class ModelLoadService(ModelLoadServiceBase):
progress or has ended; either way the load is rejected, unless it ended having changed nothing that
loads (e.g. a rename).
"""
- generation = self._record_edits.generation_when_idle(config.key)
- current = self._config_is_current(config)
- return lambda: current and self._record_edits.unchanged_since(config.key, generation)
+ with self._record_edits.watch(config.key) as unedited:
+ current = self._config_is_current(config)
+ yield lambda: current and unedited()
def _config_is_current(self, config: AnyModelConfig) -> bool:
"""Whether `config` still loads the same model as the stored record for its key."""
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index cdf7d7236e..3fae1d5a77 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -3,9 +3,10 @@
import copy
import itertools
import re
+from contextlib import nullcontext
from logging import Logger
from pathlib import Path
-from typing import Callable, Optional
+from typing import Callable, ContextManager, Optional
import torch
@@ -248,12 +249,12 @@ 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()`: on a cache miss, called with the caller's config
- # before MODEL_LOAD_LOCK is taken (it may block); the callable it returns is called once construction is
- # serialized against cache invalidation, must not block, and False rejects the load with
- # StaleModelConfigError. An attribute
+ # Optionally set on an instance before `load_model()`: on a cache miss, entered with the caller's config
+ # before MODEL_LOAD_LOCK is taken (entering may block) and exited after it is released; the callable it
+ # yields is called once construction is serialized against cache invalidation, must not block, 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
+ config_check: Optional[Callable[[AnyModelConfig], ContextManager[Callable[[], bool]]]] = None
def __init__(
self,
@@ -372,8 +373,8 @@ class ModelLoader(ModelLoaderBase):
# 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():
+ config_check = self.config_check(config) if self.config_check is not None else nullcontext(None)
+ with config_check as still_current, 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,
# so they will still miss here and construct their own copy — which is intended.)
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 4e69d42e88..26a3d29e9f 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
@@ -6,7 +6,7 @@ import threading
import time
from pathlib import Path
from types import SimpleNamespace
-from typing import Callable, Iterator, Optional
+from typing import Callable, ContextManager, Iterator, Optional
import pytest
import torch
@@ -94,6 +94,12 @@ def _edit_and_invalidate(
cache.drop_model(KEY)
+def _long_transaction(store: ModelRecordServiceSQL) -> ContextManager[object]:
+ """A write transaction held open, as VACUUM holds the database for its whole run; on SQLite it blocks every
+ other transaction, reads included."""
+ return store._queries._database.begin(write=True)
+
+
def _is_cached(cache: ModelCache) -> bool:
try:
cache.get(KEY)
@@ -224,13 +230,19 @@ def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_up
def _waits_for_edits(service: ModelLoadService, monkeypatch) -> threading.Semaphore:
"""Released each time a load starts waiting for edits of its model to finish."""
entered = threading.Semaphore(0)
- generation_when_idle = service._record_edits.generation_when_idle
+ record_edits = service._record_edits
+ watch, wait_idle = record_edits.watch, record_edits.wait_idle
- def observed(key: str) -> int:
+ def observed_watch(key: str):
entered.release()
- return generation_when_idle(key)
+ return watch(key)
- monkeypatch.setattr(service._record_edits, "generation_when_idle", observed)
+ def observed_wait_idle(key: str) -> None:
+ entered.release()
+ wait_idle(key)
+
+ monkeypatch.setattr(record_edits, "watch", observed_watch)
+ monkeypatch.setattr(record_edits, "wait_idle", observed_wait_idle)
return entered
@@ -300,7 +312,7 @@ def test_load_overlapping_an_edit_stuck_on_the_database_does_not_hold_the_model_
editor = threading.Thread(target=edit)
loader = threading.Thread(target=lambda: loads.append(service.load_model(stale)))
other = threading.Thread(target=take_model_load_lock)
- with store._db._lock: # the transaction the edit's commit waits on
+ with _long_transaction(store): # the transaction the edit's commit waits on
editor.start()
assert committing.wait(timeout=10)
loader.start()
@@ -385,7 +397,8 @@ def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold
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
+ transaction = _long_transaction(store)
+ transaction.__enter__()
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.
@@ -395,7 +408,7 @@ def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold
other.start()
lock_was_free = acquired.wait(timeout=5)
finally:
- store._db._lock.release()
+ transaction.__exit__(None, None, None)
loader.join(timeout=10)
other.join(timeout=10)
@@ -424,3 +437,50 @@ def test_missing_files_under_an_unchanged_record_still_fail(harness, tmp_path):
service.load_model(store.get_model(KEY))
assert _RecordingLoader.built_from == []
assert events.log == [("started", "siglip"), ("complete", "siglip")]
+
+
+def test_edit_tracking_is_retired_once_no_edit_or_load_needs_it(harness):
+ """Edited and deleted keys must not accumulate: a key is tracked only while an edit of it is in progress
+ 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}"):
+ pass
+ service.load_model(store.get_model(KEY))
+ with service.record_edit(KEY):
+ pass
+
+ assert service._record_edits._keys == {}
+
+
+def test_rename_then_load_affecting_edit_while_a_load_waits_rejects_it(harness, monkeypatch):
+ """A load stays tracked between its record read and its check: the rename ending must not retire what the
+ load watches, or the load-affecting edit that follows would go unnoticed."""
+ service, store, cache, _ = harness
+ waits = _waits_for_edits(service, monkeypatch)
+ outcome: list[LoadedModel] = []
+ loader = threading.Thread(target=lambda: outcome.append(service.load_model(store.get_model(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)
+ with service.record_edit(KEY) as rename:
+ store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))
+ rename.load_affecting = False
+ edit = service.record_edit(KEY)
+ edit.__enter__()
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ try:
+ # Rejected under the lock, the load waits for the edit before reading the record again.
+ assert waits.acquire(timeout=10) and waits.acquire(timeout=10)
+ with MODEL_LOAD_LOCK.write_lock():
+ cache.drop_model(KEY)
+ finally:
+ edit.__exit__(None, None, None)
+ loader.join(timeout=10)
+
+ assert len(outcome) == 1 and outcome[0].config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]