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): fence stale in-flight loads out of the cache

Lincoln Stein68b3a6ce750d
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 49dc7c866a..94cde57a8d 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -969,6 +969,8 @@ 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()` raises `StaleModelConfigError` rather than caching a model built from the superseded record. Read the record again and retry; an invocation's `context.models.load()` does this once itself.
+
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:
| Attribute Name | Type | Description |
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 9a7cca0ad3..b2dff99cd9 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -29,6 +29,7 @@ from invokeai.app.services.model_images.model_images_common import (
ModelImageFileNotFoundException,
)
from invokeai.app.services.model_install.model_install_common import ModelInstallJob
+from invokeai.app.services.model_load.model_load_common import load_settings_changed
from invokeai.app.services.model_records import (
InvalidModelException,
ModelRecordChanges,
@@ -643,7 +644,7 @@ def _update_model_record(key: str, changes: ModelRecordChanges) -> AnyModelConfi
# 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.
- if _load_settings_changed(previous_config, config):
+ if load_settings_changed(previous_config, config):
# Drop the model from every per-device cache so the next load on any GPU rebuilds it.
# Hold the model-load write lock so no worker is mid-construction while we invalidate:
# a concurrent load could otherwise peek the old shared CPU weights before the drop and
@@ -698,26 +699,6 @@ async def update_model_record(
return await asyncio.to_thread(_update_model_record, key, changes)
-_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")
-
-
-def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
- """Return True if any setting that influences how the model is loaded changed.
-
- Such settings are read by the loader during `_load_model` and baked into the resulting
- nn.Module, so a cached entry built under the old value must be evicted for the change
- to take effect.
- """
- if getattr(previous, "cpu_only", None) != getattr(updated, "cpu_only", None):
- return True
- previous_settings = getattr(previous, "default_settings", None)
- updated_settings = getattr(updated, "default_settings", None)
- for field in _LOAD_AFFECTING_SETTINGS:
- if getattr(previous_settings, field, None) != getattr(updated_settings, field, None):
- return True
- return False
-
-
@model_manager_router.get(
"/i/{key}/image",
operation_id="get_model_image",
diff --git a/invokeai/app/services/model_load/model_load_common.py b/invokeai/app/services/model_load/model_load_common.py
new file mode 100644
index 0000000000..cca3c2ecc2
--- /dev/null
+++ b/invokeai/app/services/model_load/model_load_common.py
@@ -0,0 +1,23 @@
+"""Shared rules for when a model record change invalidates loaded instances of that model."""
+
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig
+
+_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")
+
+
+def load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
+ """Return True if any setting that influences how the model is loaded changed.
+
+ Such settings are read by the loader during `_load_model` and baked into the resulting
+ nn.Module, so a cached entry built under the old value must be evicted for the change
+ to take effect, and a load that started from the old value must not be admitted after
+ that eviction.
+ """
+ if getattr(previous, "cpu_only", None) != getattr(updated, "cpu_only", None):
+ return True
+ previous_settings = getattr(previous, "default_settings", None)
+ updated_settings = getattr(updated, "default_settings", None)
+ for field in _LOAD_AFFECTING_SETTINGS:
+ if getattr(previous_settings, field, None) != getattr(updated_settings, field, None):
+ return True
+ return False
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index 4d519e381d..4274f0fab5 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -10,10 +10,13 @@ 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_records import UnknownModelException
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load import (
LoadedModel,
LoadedModelWithoutConfig,
+ ModelLoader,
ModelLoaderRegistry,
ModelLoaderRegistryBase,
)
@@ -92,17 +95,34 @@ class ModelLoadService(ModelLoadServiceBase):
self._invoker.services.events.emit_model_load_started(model_config, submodel_type, user_id or "system")
implementation, model_config, submodel_type = self._registry.get_implementation(model_config, submodel_type) # type: ignore
- loaded_model: LoadedModel = implementation(
+ loader = implementation(
app_config=self._app_config,
logger=self._logger,
ram_cache=self.ram_cache,
- ).load_model(model_config, submodel_type)
+ )
+ if hasattr(self, "_invoker") and isinstance(loader, ModelLoader):
+ loader.config_is_current = self._config_is_current
+ loaded_model: LoadedModel = loader.load_model(model_config, 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
+ def _config_is_current(self, config: AnyModelConfig) -> bool:
+ """Whether `config` still loads the same model as the stored record for its 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.
+ """
+ try:
+ current = self._invoker.services.model_manager.store.get_model(config.key)
+ except UnknownModelException:
+ # Nothing newer to load instead, and the key can no longer be requested.
+ return True
+ return not load_settings_changed(config, current)
+
def load_model_from_path(
self, model_path: Path, loader: Optional[Callable[[Path], AnyModel]] = None
) -> LoadedModelWithoutConfig:
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 2be9fc0103..8d36b035f0 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -25,7 +25,7 @@ from invokeai.app.services.wildcard_records.wildcard_records_common import build
from invokeai.app.util.step_callback import diffusion_step_callback
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
-from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig
+from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig, StaleModelConfigError
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
@@ -601,7 +601,7 @@ class ModelsInterface(InvocationContextInterface):
if submodel_type:
message += f" ({submodel_type.value})"
self._util.signal_progress(message)
- return self._services.model_manager.load.load_model(model, submodel_type, user_id=self._data.queue_item.user_id)
+ return self._load_current(model, submodel_type)
def load_by_attrs(
self, name: str, base: BaseModelType, type: ModelType, submodel_type: Optional[SubModelType] = None
@@ -631,9 +631,20 @@ class ModelsInterface(InvocationContextInterface):
if submodel_type:
message += f" ({submodel_type.value})"
self._util.signal_progress(message)
- return self._services.model_manager.load.load_model(
- configs[0], submodel_type, user_id=self._data.queue_item.user_id
- )
+ return self._load_current(configs[0], submodel_type)
+
+ def _load_current(self, model: AnyModelConfig, submodel_type: Optional[SubModelType]) -> LoadedModel:
+ """Load `model`, re-reading its record once if a load-affecting edit superseded it mid-load."""
+ load = self._services.model_manager.load
+ user_id = self._data.queue_item.user_id
+ try:
+ return load.load_model(model, submodel_type, user_id=user_id)
+ except StaleModelConfigError:
+ # The edit has already invalidated the cache; loading what the record says now is what
+ # this call would have done had it been made a moment later.
+ model = self._services.model_manager.store.get_model(model.key)
+ self._raise_if_external(model)
+ return load.load_model(model, submodel_type, user_id=user_id)
def offload_from_vram(self, identifier: Union[str, "ModelIdentifierField"]) -> int:
"""Move a model (and all of its submodels) from VRAM to RAM, freeing its VRAM but keeping it cached.
diff --git a/invokeai/backend/model_manager/load/__init__.py b/invokeai/backend/model_manager/load/__init__.py
index 04ef0fa1db..249d4dbcd2 100644
--- a/invokeai/backend/model_manager/load/__init__.py
+++ b/invokeai/backend/model_manager/load/__init__.py
@@ -5,7 +5,12 @@ Init file for the model loader.
from importlib import import_module
from pathlib import Path
-from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig, ModelLoaderBase
+from invokeai.backend.model_manager.load.load_base import (
+ LoadedModel,
+ LoadedModelWithoutConfig,
+ ModelLoaderBase,
+ StaleModelConfigError,
+)
from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry, ModelLoaderRegistryBase
@@ -23,4 +28,5 @@ __all__ = [
"ModelLoader",
"ModelLoaderRegistryBase",
"ModelLoaderRegistry",
+ "StaleModelConfigError",
]
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.py
index 24caf60a58..84a8d53951 100644
--- a/invokeai/backend/model_manager/load/load_base.py
+++ b/invokeai/backend/model_manager/load/load_base.py
@@ -297,6 +297,14 @@ class LoadedModel(LoadedModelWithoutConfig):
self.config = config
+class StaleModelConfigError(RuntimeError):
+ """The model record changed in a load-affecting way after the caller read it.
+
+ Raised instead of admitting a model built from the superseded record: the edit has already
+ invalidated the cache, so admitting it would serve the old weights to later requests.
+ """
+
+
class ModelLoaderBase(ABC):
"""Abstract base class for loading models into RAM/VRAM."""
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 34d3593004..99fb7f84a1 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -13,7 +13,7 @@ from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.backend.model_manager.configs.base import Diffusers_Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load.fp8_capability import fp8_storage_verdict
-from invokeai.backend.model_manager.load.load_base import LoadedModel, ModelLoaderBase
+from invokeai.backend.model_manager.load.load_base import LoadedModel, ModelLoaderBase, StaleModelConfigError
from invokeai.backend.model_manager.load.memory_snapshot import GB, MemorySnapshot
from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord
from invokeai.backend.model_manager.load.model_cache.model_cache import (
@@ -248,6 +248,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()`: 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
+
def __init__(
self,
app_config: InvokeAIAppConfig,
@@ -370,6 +376,15 @@ 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):
+ raise StaleModelConfigError(
+ f"Model '{config.name}' was modified while it was being loaded; retry with the updated model."
+ )
+
config.path = str(self._get_model_path(config))
self._report_inert_fp8_request(config, submodel_type)
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 ba4961f094..0000000000
--- a/tests/app/routers/test_update_model_record_cache_invalidation.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""Tests for `_load_settings_changed` — the predicate that decides whether to evict cached
-model entries after an `update_model_record` call. Settings like `fp8_storage` and `cpu_only`
-are baked into the loaded nn.Module at load time, so toggling them silently has no effect
-until the cached entry is evicted. The predicate must catch changes to those settings while
-ignoring changes that don't affect how the model loads (e.g. name, description).
-"""
-
-from types import SimpleNamespace
-
-from invokeai.app.api.routers.model_manager import _load_settings_changed
-
-
-def _config(*, fp8: bool | None = None, cpu_only: bool | None = None):
- return SimpleNamespace(
- cpu_only=cpu_only,
- default_settings=SimpleNamespace(fp8_storage=fp8),
- )
-
-
-def test_no_change_returns_false():
- assert _load_settings_changed(_config(fp8=True), _config(fp8=True)) is False
- assert _load_settings_changed(_config(fp8=None), _config(fp8=None)) is False
-
-
-def test_fp8_storage_toggle_returns_true():
- """The primary motivating case: a user toggling FP8 storage in the Model Manager must
- drop the cached entry, otherwise inference keeps using the old (non-FP8) module."""
- assert _load_settings_changed(_config(fp8=False), _config(fp8=True)) is True
- assert _load_settings_changed(_config(fp8=True), _config(fp8=False)) is True
- assert _load_settings_changed(_config(fp8=None), _config(fp8=True)) is True
- assert _load_settings_changed(_config(fp8=True), _config(fp8=None)) is True
-
-
-def test_cpu_only_toggle_returns_true():
- """`cpu_only` is also read by the loader (in `_get_execution_device`) and baked into the
- cache entry's execution device — toggling it after load is a silent no-op without eviction."""
- assert _load_settings_changed(_config(cpu_only=False), _config(cpu_only=True)) is True
- assert _load_settings_changed(_config(cpu_only=True), _config(cpu_only=None)) is True
-
-
-def test_missing_default_settings_is_handled():
- """default_settings can legitimately be None (e.g. a freshly identified config)."""
- no_settings = SimpleNamespace(cpu_only=None, default_settings=None)
- assert _load_settings_changed(no_settings, no_settings) is False
- assert _load_settings_changed(no_settings, _config(fp8=True)) is True
-
-
-def test_unrelated_field_does_not_trigger_invalidation():
- """A config missing the fp8/cpu_only attributes entirely (e.g. a model type with no such
- fields) must not falsely report a change."""
- bare_a = SimpleNamespace()
- bare_b = SimpleNamespace()
- assert _load_settings_changed(bare_a, bare_b) is False
diff --git a/tests/app/services/model_load/test_model_load_common.py b/tests/app/services/model_load/test_model_load_common.py
new file mode 100644
index 0000000000..b1133fdfe7
--- /dev/null
+++ b/tests/app/services/model_load/test_model_load_common.py
@@ -0,0 +1,54 @@
+"""Tests for `load_settings_changed` — the predicate that decides both whether an `update_model_record`
+call evicts cached model entries and whether a load that read the record before that edit may still be
+admitted to the cache. Settings like `fp8_storage` and `cpu_only` are baked into the loaded nn.Module at
+load time, so toggling them silently has no effect until the cached entry is evicted. The predicate must
+catch changes to those settings while ignoring changes that don't affect how the model loads (e.g. name,
+description).
+"""
+
+from types import SimpleNamespace
+
+from invokeai.app.services.model_load.model_load_common import load_settings_changed
+
+
+def _config(*, fp8: bool | None = None, cpu_only: bool | None = None):
+ return SimpleNamespace(
+ cpu_only=cpu_only,
+ default_settings=SimpleNamespace(fp8_storage=fp8),
+ )
+
+
+def test_no_change_returns_false():
+ assert load_settings_changed(_config(fp8=True), _config(fp8=True)) is False
+ assert load_settings_changed(_config(fp8=None), _config(fp8=None)) is False
+
+
+def test_fp8_storage_toggle_returns_true():
+ """The primary motivating case: a user toggling FP8 storage in the Model Manager must
+ drop the cached entry, otherwise inference keeps using the old (non-FP8) module."""
+ assert load_settings_changed(_config(fp8=False), _config(fp8=True)) is True
+ assert load_settings_changed(_config(fp8=True), _config(fp8=False)) is True
+ assert load_settings_changed(_config(fp8=None), _config(fp8=True)) is True
+ assert load_settings_changed(_config(fp8=True), _config(fp8=None)) is True
+
+
+def test_cpu_only_toggle_returns_true():
+ """`cpu_only` is also read by the loader (in `_get_execution_device`) and baked into the
+ cache entry's execution device — toggling it after load is a silent no-op without eviction."""
+ assert load_settings_changed(_config(cpu_only=False), _config(cpu_only=True)) is True
+ assert load_settings_changed(_config(cpu_only=True), _config(cpu_only=None)) is True
+
+
+def test_missing_default_settings_is_handled():
+ """default_settings can legitimately be None (e.g. a freshly identified config)."""
+ no_settings = SimpleNamespace(cpu_only=None, default_settings=None)
+ assert load_settings_changed(no_settings, no_settings) is False
+ assert load_settings_changed(no_settings, _config(fp8=True)) is True
+
+
+def test_unrelated_field_does_not_trigger_invalidation():
+ """A config missing the fp8/cpu_only attributes entirely (e.g. a model type with no such
+ fields) must not falsely report a change."""
+ bare_a = SimpleNamespace()
+ bare_b = SimpleNamespace()
+ assert load_settings_changed(bare_a, bare_b) is False
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
new file mode 100644
index 0000000000..2b1afb1692
--- /dev/null
+++ b/tests/app/services/model_load/test_stale_model_load_fence.py
@@ -0,0 +1,186 @@
+"""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 threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Callable, Optional
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.model_load.model_load_default import ModelLoadService
+from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL
+from invokeai.app.services.shared.invocation_context import ModelsInterface
+from invokeai.backend.model_manager.configs.factory import AnyModelConfig
+from invokeai.backend.model_manager.configs.siglip import SigLIP_Diffusers_Config
+from invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader, StaleModelConfigError
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
+from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+KEY = "siglip-key"
+
+
+class _RecordingLoader(ModelLoader):
+ """Builds a tiny module and records the `cpu_only` value each construction was built from."""
+
+ built_from: list[Optional[bool]] = []
+
+ def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:
+ self.built_from.append(getattr(config, "cpu_only", None))
+ return torch.nn.Linear(2, 2)
+
+
+class _Registry:
+ @classmethod
+ def get_implementation(cls, config: AnyModelConfig, submodel_type: Optional[SubModelType]):
+ return _RecordingLoader, config, submodel_type
+
+
+def _noop(*args, **kwargs) -> None:
+ return None
+
+
+def harness(tmp_path: Path):
+ _RecordingLoader.built_from = []
+ app_config = InvokeAIAppConfig(use_memory_db=True)
+ logger = InvokeAILogger.get_logger()
+ store = ModelRecordServiceSQL(create_mock_sqlite_database(app_config, logger), logger)
+ model_dir = tmp_path / "siglip"
+ model_dir.mkdir()
+ store.add_model(
+ SigLIP_Diffusers_Config(
+ key=KEY, path=str(model_dir), name="siglip", hash="abc", file_size=1, source="test", source_type="path"
+ )
+ )
+ cache = 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,
+ )
+ service = ModelLoadService(app_config=app_config, ram_cache=cache, registry=_Registry) # type: ignore[arg-type]
+ events = SimpleNamespace(emit_model_load_started=_noop, emit_model_load_complete=_noop)
+ service.start(SimpleNamespace(services=SimpleNamespace(events=events, model_manager=SimpleNamespace(store=store)))) # type: ignore[arg-type]
+ return service, store, cache
+
+
+def _edit_and_invalidate(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)
+
+
+def _is_cached(cache: ModelCache) -> bool:
+ try:
+ cache.get(KEY)
+ except IndexError:
+ return False
+ return True
+
+
+def test_load_from_record_read_before_invalidating_edit_is_rejected_and_not_cached(harness):
+ service, store, cache = harness
+ stale = store.get_model(KEY)
+
+ _edit_and_invalidate(store, cache, ModelRecordChanges(cpu_only=True))
+
+ with pytest.raises(StaleModelConfigError):
+ service.load_model(stale)
+ assert not _is_cached(cache)
+ assert _RecordingLoader.built_from == []
+
+ loaded = service.load_model(store.get_model(KEY))
+ assert loaded.config.cpu_only is True
+ assert _RecordingLoader.built_from == [True]
+ assert _is_cached(cache)
+
+
+def test_load_from_record_read_before_metadata_only_edit_still_loads(harness):
+ service, store, cache = harness
+ previous = 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"))
+
+ service.load_model(previous)
+ assert _RecordingLoader.built_from == [None]
+ assert _is_cached(cache)
+
+
+def _run_with_edit_while_queued_on_construction_lock(
+ 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."""
+ outcome: list[object] = []
+
+ def run() -> None:
+ try:
+ outcome.append(load())
+ except BaseException as e:
+ outcome.append(e)
+
+ loader = threading.Thread(target=run)
+ with MODEL_LOAD_LOCK.write_lock():
+ 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))
+ cache.drop_model(KEY)
+ loader.join(timeout=10)
+ assert len(outcome) == 1
+ return outcome[0]
+
+
+def test_load_waiting_on_construction_lock_during_invalidating_edit_is_rejected(harness):
+ service, store, cache = harness
+
+ outcome = _run_with_edit_while_queued_on_construction_lock(
+ store, cache, lambda: service.load_model(store.get_model(KEY))
+ )
+
+ assert isinstance(outcome, StaleModelConfigError)
+ assert _RecordingLoader.built_from == []
+ assert not _is_cached(cache)
+
+
+def test_invocation_load_superseded_mid_load_loads_the_updated_record(harness):
+ service, store, cache = harness
+ services = SimpleNamespace(model_manager=SimpleNamespace(store=store, load=service))
+ models = ModelsInterface(services=services, data=MagicMock(), util=MagicMock()) # type: ignore[arg-type]
+
+ outcome = _run_with_edit_while_queued_on_construction_lock(store, cache, lambda: models.load(KEY))
+
+ assert isinstance(outcome, LoadedModel)
+ assert outcome.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."""
+ service, store, cache = harness
+ config = store.get_model(KEY)
+ # Use it once so its first-use hold is released and the drop below evicts it outright.
+ with service.load_model(config):
+ pass
+ with MODEL_LOAD_LOCK.write_lock():
+ cache.drop_model(KEY)
+
+ service.load_model(config)
+ assert _RecordingLoader.built_from == [None, None]