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 cache): holder-identity check in the grace release, per second review

Lincoln Steine3612c217a13
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.py
index c073dcf70c..f8a4a21a39 100644
--- a/invokeai/backend/model_manager/load/load_base.py
+++ b/invokeai/backend/model_manager/load/load_base.py
@@ -63,16 +63,17 @@ class LoadedModelWithoutConfig:
self._cache_record = cache_record
self._cache = cache
release_first_use_grace = getattr(cache, "release_first_use_grace", None)
- self._first_use_finalizer = (
- finalize(self, release_first_use_grace, cache_record)
- if cache_record.awaiting_first_use and release_first_use_grace is not None
- else None
- )
- if self._first_use_finalizer is not None:
- self._first_use_finalizer.atexit = False
+ if cache_record.awaiting_first_use and release_first_use_grace is not None:
# This handle owns the grace: put()'s sweep keeps a grace whose holder is alive
- # (an in-flight multi-model load) and clears one whose holder is gone.
- cache_record.grace_holder = weakref.ref(self)
+ # (an in-flight multi-model load) and clears one whose holder is gone. The finalizer
+ # carries its own ref so the release can tell whether the grace has since been
+ # re-registered to a newer, still-live handle.
+ holder_ref = weakref.ref(self)
+ cache_record.grace_holder = holder_ref
+ self._first_use_finalizer = finalize(self, release_first_use_grace, cache_record, holder_ref)
+ self._first_use_finalizer.atexit = False
+ else:
+ self._first_use_finalizer = None
def _lock_paced(self, working_mem_bytes: Optional[int]) -> None:
"""Move the model into VRAM in bounded passes, yielding the global load lock between them.
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index 79d0436144..1717b6be79 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -72,6 +72,7 @@ def _run_deferred_work(cache_ref: "weakref.ReferenceType[ModelCache]", work_queu
while True:
work = work_queue.get()
cache = None
+ record = None
try:
if work is _DEFERRED_STOP:
return
@@ -83,6 +84,11 @@ def _run_deferred_work(cache_ref: "weakref.ReferenceType[ModelCache]", work_queu
continue
if work is _DEFERRED_RECONCILE:
cache._reconcile_budget_if_pending()
+ elif isinstance(work, tuple):
+ record, holder_ref = work
+ assert isinstance(record, CacheRecord)
+ cache._release_first_use_grace(record, holder_ref)
+ holder_ref = None
else:
assert isinstance(work, CacheRecord)
cache._release_first_use_grace(work)
@@ -91,13 +97,14 @@ def _run_deferred_work(cache_ref: "weakref.ReferenceType[ModelCache]", work_queu
cache._logger.exception("Error processing deferred model-cache work")
finally:
# Drop both references before blocking on the next get(): locals stay bound for as long
- # as this frame lives. `work` may be a CacheRecord, which transitively holds its model's
+ # as this frame lives. `work` may be (or hold) a CacheRecord, which transitively holds its model's
# CPU weights — and _release_first_use_grace's release hook can evict that very record,
# removing it from the cache AND subtracting its bytes from the RamBudget, so holding it
# would leave the budget under-reporting a model that is still resident. `cache` must go
# for the same reason this function takes a weakref at all.
work = None
cache = None
+ record = None
class _ModelLoadReadWriteLock:
@@ -813,7 +820,9 @@ class ModelCache:
if self._ram_budget is not None and self._budget_reconcile_pending.is_set() and not self._lock._is_owned():
self._dispatch_deferred(_DEFERRED_RECONCILE)
- def release_first_use_grace(self, cache_entry: CacheRecord) -> None:
+ def release_first_use_grace(
+ self, cache_entry: CacheRecord, holder_ref: "weakref.ref[object] | None" = None
+ ) -> None:
"""Make an abandoned, never-locked record available for budget eviction.
Called from a `weakref.finalize` callback (see LoadedModelWithoutConfig), which runs at an
@@ -839,7 +848,7 @@ class ModelCache:
# release. Losing a race here at worst queues work that no-ops under the lock.
if not cache_entry.awaiting_first_use:
return
- self._dispatch_deferred(cache_entry)
+ self._dispatch_deferred((cache_entry, holder_ref))
def _ensure_deferred_worker(self) -> None:
"""Start the background worker if it is not currently running. Caller must hold the lock.
@@ -914,10 +923,25 @@ class ModelCache:
self._deferred_work_queue.put(work)
@synchronized
- def _release_first_use_grace(self, cache_entry: CacheRecord) -> None:
- """Clear an abandoned record's grace, then let the release hook reconcile the budget."""
- if self._cached_models.get(cache_entry.key) is cache_entry and not cache_entry.is_locked:
- cache_entry.awaiting_first_use = False
+ def _release_first_use_grace(
+ self, cache_entry: CacheRecord, holder_ref: "weakref.ref[object] | None" = None
+ ) -> None:
+ """Clear an abandoned record's grace, then let the release hook reconcile the budget.
+
+ `holder_ref` identifies the handle whose death triggered this release. When the record's
+ current `grace_holder` is a DIFFERENT, still-live handle (a newer handle was constructed
+ for the same graced record and re-registered itself), the grace belongs to that handle
+ now — leave it. (Single-slot limitation, documented: if the NEWER handle dies first while
+ an older one lives, the slot points at the dead ref and the grace clears anyway. No
+ current code path constructs two pre-lock handles for one record — one session worker per
+ device cache — so this stays a contract note, not a reachable bug.)
+ """
+ if self._cached_models.get(cache_entry.key) is not cache_entry or cache_entry.is_locked:
+ return
+ current = cache_entry.grace_holder
+ if holder_ref is not None and current is not None and current is not holder_ref and current() is not None:
+ return
+ cache_entry.awaiting_first_use = False
@synchronized
def _get_cache_snapshot(self) -> dict[str, CacheEntrySnapshot]:
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 8165d78d5e..78d0958f30 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -283,9 +283,11 @@ def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, clien
def __init__(self, models_cleared: int, bytes_freed: int) -> None:
self._result = CacheClearResult(models_cleared=models_cleared, bytes_freed=bytes_freed)
self.requested: list[int] = []
+ self.spared_grace: list[bool] = []
def make_room(self, bytes_needed: int, spare_awaiting_first_use: bool = True) -> CacheClearResult:
self.requested.append(bytes_needed)
+ self.spared_grace.append(spare_awaiting_first_use)
return self._result
cache_0 = _Cache(models_cleared=2, bytes_freed=100)
@@ -302,6 +304,9 @@ def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, clien
# Both devices were actually asked to clear, not just the API thread's default cache.
assert len(cache_0.requested) == 1
assert len(cache_1.requested) == 1
+ # A user-requested full clear outranks the admission grace.
+ assert cache_0.spared_grace == [False]
+ assert cache_1.spared_grace == [False]
def test_empty_model_cache_clears_duplicate_cache_objects_once(monkeypatch: Any, client: TestClient) -> None: