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): keep the stale-load check off the database under MODEL_LOAD_LOCK

Lincoln Stein26f58ea82312
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 888df06891..6a7e3778ca 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -973,7 +973,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. If the record changes again during that retry, it raises `StaleModelConfigError`.
+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).
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:
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index c64f4ffc20..d36ba9ebaa 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -512,9 +512,9 @@ def _reidentify_model(key: str) -> AnyModelConfig:
result.config.source_type = config.source_type
# 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):
+ 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)
- _invalidate_model_load_caches(config.key, config, updated)
+ edit.load_affecting = _invalidate_model_load_caches(config.key, config, updated)
return updated
@@ -650,14 +650,14 @@ 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), ApiDependencies.invoker.services.model_manager.load.record_edit(key):
+ with _claim_model_key(key), ApiDependencies.invoker.services.model_manager.load.record_edit(key) as edit:
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.
- _invalidate_model_load_caches(key, previous_config, config)
+ edit.load_affecting = _invalidate_model_load_caches(key, previous_config, config)
config = prepare_model_config_for_response(config, ApiDependencies)
logger.info(f"Updated model: {key}")
except UnknownModelException as e:
@@ -698,10 +698,10 @@ async def update_model_record(
return await asyncio.to_thread(_update_model_record, key, changes)
-def _invalidate_model_load_caches(key: str, previous: AnyModelConfig, updated: AnyModelConfig) -> None:
- """Drop cached instances when a record change affects how the model is loaded."""
+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
+ 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():
@@ -710,6 +710,7 @@ def _invalidate_model_load_caches(key: str, previous: AnyModelConfig, updated: A
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(
diff --git a/invokeai/app/services/model_load/model_load_base.py b/invokeai/app/services/model_load/model_load_base.py
index 5f8301c918..12c028097e 100644
--- a/invokeai/app/services/model_load/model_load_base.py
+++ b/invokeai/app/services/model_load/model_load_base.py
@@ -4,6 +4,7 @@ from abc import ABC, abstractmethod
from pathlib import Path
from typing import Callable, ContextManager, 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
@@ -30,11 +31,12 @@ class ModelLoadServiceBase(ABC):
"""
@abstractmethod
- def record_edit(self, key: str) -> ContextManager[None]:
+ 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, 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."""
+ 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."""
@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 7b2e250c4f..58b1203fe6 100644
--- a/invokeai/app/services/model_load/model_load_common.py
+++ b/invokeai/app/services/model_load/model_load_common.py
@@ -1,5 +1,6 @@
"""Shared rules for when a model record change invalidates loaded instances of that model."""
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
@@ -56,3 +57,12 @@ def load_settings_changed(
paths after resolving them against it.
"""
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`)."""
+
+ # 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
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index a451fac69f..f7ccf39eac 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -12,7 +12,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 load_settings_changed
+from invokeai.app.services.model_load.model_load_common import RecordEdit, 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,31 +31,41 @@ 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."""
+ """Per model key: how many record edits are in progress, and a generation bumped as each edit that changed
+ how the model loads ends."""
def __init__(self) -> None:
- self._lock = threading.Lock()
+ 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] = {}
@contextmanager
- def edit(self, key: str) -> Iterator[None]:
- with self._lock:
- self._generations[key] = self._generations.get(key, 0) + 1
+ def edit(self, key: str) -> Iterator[RecordEdit]:
+ record_edit = RecordEdit()
+ with self._changed:
self._in_progress[key] = self._in_progress.get(key, 0) + 1
try:
- yield
+ yield record_edit
finally:
- with self._lock:
+ with self._changed:
+ 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]
+ self._changed.notify_all()
- 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
+ def generation_when_idle(self, key: str) -> int:
+ """Wait until no edit of `key` is in progress, then return its generation."""
+ with self._changed:
+ self._changed.wait_for(lambda: key not in self._in_progress)
+ return self._generations.get(key, 0)
+
+ 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`."""
+ with self._changed:
+ return key not in self._in_progress and self._generations.get(key, 0) == generation
class ModelLoadService(ModelLoadServiceBase):
@@ -127,19 +137,24 @@ class ModelLoadService(ModelLoadServiceBase):
self._invoker.services.events.emit_model_load_started(model_config, submodel_type, user_id or "system")
try:
- loaded_model = self._load(model_config, submodel_type)
- except StaleModelConfigError:
- # The edit has already invalidated the cache, so loading what the record says now is what this
- # call would have done had it been made a moment later. Retried here rather than by callers so
- # every caller gets it and the load events stay paired.
- loaded_model = self._load(
- self._invoker.services.model_manager.store.get_model(model_config.key), submodel_type
- )
-
- if hasattr(self, "_invoker"):
- self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")
-
- return loaded_model
+ try:
+ return self._load(model_config, submodel_type)
+ except StaleModelConfigError:
+ # The record changed after the caller read it: loading what it says now is what this call
+ # would have done had it been made a moment later. Retried here rather than by callers so
+ # every caller gets it.
+ return self._load(self._current_record(model_config.key), submodel_type)
+ except FileNotFoundError:
+ # The same, when the model was moved and its record updated to the new path; a missing
+ # file under an unchanged (or deleted) record is the caller's real error.
+ current = self._moved_record(model_config)
+ if current is None:
+ raise
+ return self._load(current, submodel_type)
+ finally:
+ # Sent however the load ends, so a UI showing it as in progress can clear it.
+ if hasattr(self, "_invoker"):
+ self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")
def _load(self, model_config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> LoadedModel:
implementation, model_config, submodel_type = self._registry.get_implementation(model_config, submodel_type) # type: ignore
@@ -152,29 +167,39 @@ class ModelLoadService(ModelLoadServiceBase):
loader.config_check = self._check_config
return loader.load_model(model_config, submodel_type)
- def record_edit(self, key: str) -> ContextManager[None]:
+ def record_edit(self, key: str) -> ContextManager[RecordEdit]:
return self._record_edits.edit(key)
+ 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)
+ return self._invoker.services.model_manager.store.get_model(key)
+
+ def _moved_record(self, config: AnyModelConfig) -> Optional[AnyModelConfig]:
+ """The stored record for `config`'s key if it now loads differently from `config`, else None."""
+ if not hasattr(self, "_invoker"):
+ return None
+ try:
+ current = self._current_record(config.key)
+ except UnknownModelException:
+ return None
+ if load_settings_changed(config, current, models_path=self._app_config.models_path):
+ 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.
- 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.
+ 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
+ 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).
"""
- generation, edit_in_progress = self._record_edits.snapshot(config.key)
+ generation = self._record_edits.generation_when_idle(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
+ return lambda: current and self._record_edits.unchanged_since(config.key, generation)
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 e87694485a..cdf7d7236e 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -249,8 +249,9 @@ 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; the callable it returns is called once construction is serialized
- # against cache invalidation, and False rejects the load with StaleModelConfigError. An attribute
+ # 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
# rather than a constructor argument so that registered loaders overriding `__init__` keep working.
config_check: Optional[Callable[[AnyModelConfig], Callable[[], bool]]] = None
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index b79a2e529f..8ab37672f3 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -10,6 +10,7 @@ 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,
@@ -380,7 +381,8 @@ 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={}, record_edit=lambda key: contextlib.nullcontext())
+ store=Store(),
+ load=SimpleNamespace(ram_caches={}, record_edit=lambda key: contextlib.nullcontext(RecordEdit())),
),
)
invoker = DummyInvoker(services)
@@ -411,10 +413,10 @@ async def test_update_model_record_brackets_commit_and_cache_drop_as_a_record_ed
observed: list[tuple[str, list[str]]] = []
@contextlib.contextmanager
- def record_edit(key: str) -> Iterator[None]:
+ def record_edit(key: str) -> Iterator[RecordEdit]:
open_edits.append(key)
try:
- yield
+ yield RecordEdit()
finally:
open_edits.remove(key)
@@ -1045,10 +1047,10 @@ def test_reidentify_keeps_a_backbone_only_the_install_source_names(
edits_at_replace: list[list[str]] = []
@contextlib.contextmanager
- def record_edit(key: str) -> Iterator[None]:
+ def record_edit(key: str) -> Iterator[RecordEdit]:
open_edits.append(key)
try:
- yield
+ yield RecordEdit()
finally:
open_edits.remove(key)
diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.py
index f0cedc6189..e2fec5ad5a 100644
--- a/tests/app/routers/test_update_model_record_cache_invalidation.py
+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py
@@ -9,11 +9,12 @@ 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[None]:
- return contextlib.nullcontext()
+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):
@@ -44,6 +45,7 @@ def _config(*, fp8: bool | None = None, cpu_only: bool | None = None, **fields):
],
)
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(
@@ -56,7 +58,9 @@ def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkey
logger=MagicMock(),
model_manager=SimpleNamespace(
store=record_store,
- load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={"cuda:0": cache_a, "cuda:1": cache_b}),
+ load=SimpleNamespace(
+ record_edit=lambda _key: contextlib.nullcontext(edit), ram_caches={"cuda:0": cache_a, "cuda:1": cache_b}
+ ),
),
)
monkeypatch.setattr(
@@ -84,6 +88,8 @@ def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkey
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:
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 3e70e575d1..4e69d42e88 100644
--- a/tests/app/services/model_load/test_stale_model_load_fence.py
+++ b/tests/app/services/model_load/test_stale_model_load_fence.py
@@ -1,11 +1,12 @@
"""A load that read a model record before a load-affecting edit must not repopulate the cache after
that edit's invalidation; later loads must build from the updated record."""
+import contextlib
import threading
import time
from pathlib import Path
from types import SimpleNamespace
-from typing import Callable, Optional
+from typing import Callable, Iterator, Optional
import pytest
import torch
@@ -101,6 +102,36 @@ def _is_cached(cache: ModelCache) -> bool:
return True
+def record_reads_under_lock(harness, monkeypatch) -> list[bool]:
+ """For each read of the model record by a worker thread (the test's own edits run on the main thread),
+ whether the reading thread held MODEL_LOAD_LOCK's write lock."""
+ _, store, _, _ = harness
+ holders: set[int] = set()
+ write_lock = MODEL_LOAD_LOCK.write_lock
+
+ @contextlib.contextmanager
+ def tracked_write_lock() -> Iterator[None]:
+ with write_lock():
+ holders.add(threading.get_ident())
+ try:
+ yield
+ finally:
+ holders.discard(threading.get_ident())
+
+ reads: list[bool] = []
+ store_get_model = store.get_model
+
+ def get_model(key: str) -> AnyModelConfig:
+ if threading.current_thread() is not threading.main_thread():
+ reads.append(threading.get_ident() in holders)
+ return store_get_model(key)
+
+ monkeypatch.setattr(MODEL_LOAD_LOCK, "write_lock", tracked_write_lock)
+ monkeypatch.setattr(store, "get_model", get_model)
+ return reads
+
+
def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record(harness):
service, store, cache, events = harness
stale = store.get_model(KEY)
@@ -115,16 +146,31 @@ def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record
assert events.log == [("started", "siglip"), ("complete", "siglip")]
-def test_load_from_record_read_before_metadata_only_edit_still_loads(harness):
- service, store, cache, _ = harness
- previous = store.get_model(KEY)
+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."""
+ service, store, cache, events = harness
+ waits = _waits_for_edits(service, monkeypatch)
+ outcome: list[LoadedModel] = []
+ loader = threading.Thread(target=lambda: outcome.append(service.load_model(store.get_model(KEY))))
- # A rename does not invalidate the cache, so nothing fences a load that read the old name.
- store.update_model(KEY, changes=ModelRecordChanges(name="renamed"))
+ 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)
+ # 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
+ loader.join(timeout=10)
- service.load_model(previous)
+ assert len(outcome) == 1
assert _RecordingLoader.built_from == [None]
assert _is_cached(cache)
+ # Checked once, never retried.
+ assert waits.acquire(timeout=0) and not waits.acquire(timeout=0)
def _run_with_edit_while_queued_on_construction_lock(
@@ -155,7 +201,9 @@ def _run_with_edit_while_queued_on_construction_lock(
return outcome[0]
-def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_updated_record(harness):
+def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_updated_record(
+ harness, record_reads_under_lock
+):
service, store, cache, events = harness
outcome = _run_with_edit_while_queued_on_construction_lock(
@@ -168,30 +216,106 @@ def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_up
assert _RecordingLoader.built_from == [True]
# One load as far as the UI can tell: a retry that re-announced itself would leave a load showing.
assert events.log == [("started", "siglip"), ("complete", "siglip")]
+ # Rejected without reading the record under the lock: that read would stall every MODEL_LOAD_LOCK user
+ # behind any long DB transaction.
+ assert record_reads_under_lock and not any(record_reads_under_lock)
+
+
+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
+
+ def observed(key: str) -> int:
+ entered.release()
+ return generation_when_idle(key)
+ monkeypatch.setattr(service._record_edits, "generation_when_idle", observed)
+ return entered
-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."""
+
[email protected]("commit_before_rejection", [True, False])
+def test_edit_starting_while_load_waits_but_invalidating_after_it_is_not_built_from_the_old_record(
+ harness, monkeypatch, record_reads_under_lock, commit_before_rejection: bool
+):
+ """The load checks a current record and queues behind an unrelated construction; an edit then starts,
+ and reaches its invalidation only after the load holds the construction lock. Its commit lands either
+ before the load is rejected or while the rejected load waits to retry."""
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 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)
+ 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)
+ edit = service.record_edit(KEY)
+ edit.__enter__()
+ if commit_before_rejection:
+ 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)
+ if not commit_before_rejection:
store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
- loader.join(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
assert outcome[0].config.cpu_only is True
assert _RecordingLoader.built_from == [True]
+ assert not any(record_reads_under_lock)
+
+
+def test_load_overlapping_an_edit_stuck_on_the_database_does_not_hold_the_model_load_lock(
+ harness, monkeypatch, record_reads_under_lock
+):
+ """A cold load of a model whose edit is waiting out a long DB transaction (e.g. VACUUM) waits too, but
+ without MODEL_LOAD_LOCK, so unrelated model builds and VRAM moves carry on; it then loads the edit."""
+ service, store, cache, events = harness
+ waits = _waits_for_edits(service, monkeypatch)
+ stale = store.get_model(KEY)
+ committing = threading.Event()
+
+ def edit() -> None:
+ with service.record_edit(KEY):
+ committing.set()
+ store.update_model(KEY, changes=ModelRecordChanges(cpu_only=True))
+ with MODEL_LOAD_LOCK.write_lock():
+ cache.drop_model(KEY)
+
+ loads: list[LoadedModel] = []
+ acquired = threading.Event()
+
+ def take_model_load_lock() -> None:
+ with MODEL_LOAD_LOCK.write_lock():
+ acquired.set()
+
+ 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
+ editor.start()
+ assert committing.wait(timeout=10)
+ loader.start()
+ assert waits.acquire(timeout=10)
+ other.start()
+ lock_was_free = acquired.wait(timeout=5)
+ editor.join(timeout=10)
+ loader.join(timeout=10)
+ other.join(timeout=10)
+
+ assert lock_was_free
+ assert len(loads) == 1 and loads[0].config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]
+ assert not any(record_reads_under_lock)
def test_config_object_reused_after_eviction_still_loads(harness):
@@ -212,7 +336,7 @@ def test_config_object_reused_after_eviction_still_loads(harness):
def test_record_superseded_again_during_retry_raises(harness, monkeypatch):
- service, store, _, _ = harness
+ service, store, _, events = harness
fence_checks: list[str] = []
def never_current(config: AnyModelConfig) -> bool:
@@ -225,6 +349,8 @@ 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 == []
+ # The load ended, so it must not be left showing as in progress.
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]
def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold_the_model_load_lock(
@@ -276,3 +402,25 @@ def test_database_transaction_starting_while_a_cold_load_is_queued_does_not_hold
assert lock_was_free
assert len(loads) == 1
assert _is_cached(cache)
+
+
+def test_load_from_record_read_before_the_model_was_moved_loads_from_its_new_path(harness, tmp_path):
+ 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"))
+
+ loaded = service.load_model(stale)
+
+ assert Path(loaded.config.path) == tmp_path / "moved"
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]
+
+
+def test_missing_files_under_an_unchanged_record_still_fail(harness, tmp_path):
+ service, store, _, events = harness
+ (tmp_path / "siglip").rmdir()
+
+ with pytest.raises(FileNotFoundError):
+ service.load_model(store.get_model(KEY))
+ assert _RecordingLoader.built_from == []
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]