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): harden recovery and cache invalidation

JPPhoto295566279705
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 67c58081d1..f224fab44c 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -570,7 +570,7 @@ Both methods accept a Path object corresponding to a checkpoint or diffusers fol
The difference between `register_path()` and `install_path()` is that the former creates a model configuration record without changing the location of the model in the filesystem. The latter moves the model into the InvokeAI models directory before registering it.
-When an install transfer cannot be rolled back without risking data loss, the installer raises a recovery-required error and retains both transfer roots for manual recovery. Sibling sentinels keep recovery roots across restart, including when JSON marker writes fail, and prevent cancellation from deleting them. Ordinary markerless staging directories and terminal-state staging directories may be cleaned up at startup. Conversion writes its intermediate model under `models/.convert_tmp`, which the orphan scan skips while the conversion is active. If installation needs recovery, the conversion endpoint reports and retains that source directory; successful conversions and ordinary failures remove their scratch directory.
+When an install transfer cannot be rolled back without risking data loss, the installer raises a recovery-required error and retains both transfer roots for manual recovery. Sibling sentinels keep recovery roots across restart, including when JSON marker writes fail, and prevent cancellation, restart, or orphan cleanup from deleting them. Successfully registering a manually recovered root removes its sentinel. Ordinary markerless staging directories and terminal-state staging directories may be cleaned up at startup. Conversion writes its intermediate model under `models/.convert_tmp`, which the orphan scan skips while the conversion is active. If installation needs recovery, the conversion endpoint reports and retains that source directory; successful conversions and ordinary failures remove their scratch directory.
#### installer.unregister(key)
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 608f2a9c36..210e359e3f 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -487,7 +487,10 @@ def _reidentify_model(key: str) -> AnyModelConfig:
# backbone (a 16-channel VAE, a PiD decoder), the HF repo or URL may. A file copied into the models
# folder has also lost the folder it came from, so without the source a re-probe refiles it under
# the default.
- result = ModelConfigFactory.from_model_on_disk(mod, {"source": config.source, "source_type": config.source_type})
+ override_fields = {"source": config.source, "source_type": config.source_type}
+ if encoder_id := getattr(config, "image_encoder_model_id", None):
+ override_fields["image_encoder_model_id"] = encoder_id
+ result = ModelConfigFactory.from_model_on_disk(mod, override_fields)
if result.config is None:
raise InvalidModelException("Unable to identify model format")
@@ -502,7 +505,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)
+ updated = ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)
+ _invalidate_model_load_caches(config.key, config, updated)
+ return updated
class FoundModel(BaseModel):
@@ -644,21 +649,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):
- # 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
- # re-register them as canonical after it. Acquiring the lock can wait on an in-flight
- # load/VRAM transfer, but this entire helper already runs off the event loop.
- with MODEL_LOAD_LOCK.write_lock():
- dropped = sum(
- cache.drop_model(key)
- for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values()
- )
- if dropped:
- logger.info(
- f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."
- )
+ _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:
@@ -700,7 +691,35 @@ async def update_model_record(
_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")
-_LOAD_AFFECTING_MODEL_FIELDS: tuple[str, ...] = ("path", "base", "type", "format", "variant")
+_MODEL_METADATA_FIELDS: tuple[str, ...] = (
+ "name",
+ "description",
+ "cover_image",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "trigger_phrases",
+)
+
+
+def _model_load_fingerprint(config: AnyModelConfig) -> dict[str, Any]:
+ """Return persisted config values that can change the loaded model instance."""
+ if model_dump := getattr(config, "model_dump", None):
+ fingerprint = model_dump(mode="python")
+ else:
+ fingerprint = vars(config).copy()
+ for field in _MODEL_METADATA_FIELDS:
+ fingerprint.pop(field, None)
+
+ default_settings = fingerprint.pop("default_settings", None)
+ fingerprint["default_settings"] = {
+ field: default_settings.get(field)
+ if isinstance(default_settings, dict)
+ else getattr(default_settings, field, None)
+ for field in _LOAD_AFFECTING_SETTINGS
+ }
+ return fingerprint
def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
@@ -710,16 +729,21 @@ def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) ->
nn.Module, so a cached entry built under the old value must be evicted for the change
to take effect.
"""
- if any(getattr(previous, field, None) != getattr(updated, field, None) for field in _LOAD_AFFECTING_MODEL_FIELDS):
- return True
- 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
+ return _model_load_fingerprint(previous) != _model_load_fingerprint(updated)
+
+
+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."""
+ if not _load_settings_changed(previous, updated):
+ return
+ services = ApiDependencies.invoker.services
+ # Prevent a concurrent load from re-registering state built from the previous model identity.
+ with MODEL_LOAD_LOCK.write_lock():
+ dropped = sum(cache.drop_model(key) for cache in services.model_manager.load.ram_caches.values())
+ if dropped:
+ services.logger.info(
+ f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."
+ )
@model_manager_router.get(
@@ -1281,7 +1305,7 @@ def cancel_model_install_job(
raise HTTPException(status_code=415, detail=str(e))
try:
installer.cancel_job(job)
- except ValueError as e:
+ except InstallRecoveryRequiredError as e:
raise HTTPException(status_code=409, detail=str(e)) from e
@@ -1334,6 +1358,7 @@ def resume_model_install_job(
operation_id="restart_failed_model_install_job",
responses={
201: {"description": "Failed files restarted successfully"},
+ 409: {"description": "The job has recovery data that must be preserved"},
415: {"description": "No such job"},
},
status_code=201,
@@ -1347,7 +1372,10 @@ def restart_failed_model_install_job(
job = installer.get_job_by_id(id)
except ValueError as e:
raise HTTPException(status_code=415, detail=str(e))
- installer.restart_failed(job)
+ try:
+ installer.restart_failed(job)
+ except InstallRecoveryRequiredError as e:
+ raise HTTPException(status_code=409, detail=str(e)) from e
return job
@@ -1356,6 +1384,7 @@ def restart_failed_model_install_job(
operation_id="restart_model_install_file",
responses={
201: {"description": "File restarted successfully"},
+ 409: {"description": "The job has recovery data that must be preserved"},
415: {"description": "No such job"},
},
status_code=201,
@@ -1371,7 +1400,10 @@ def restart_model_install_file(
job = installer.get_job_by_id(id)
except ValueError as e:
raise HTTPException(status_code=415, detail=str(e))
- installer.restart_file(job, str(file_source))
+ try:
+ installer.restart_file(job, str(file_source))
+ except InstallRecoveryRequiredError as e:
+ raise HTTPException(status_code=409, detail=str(e)) from e
return job
diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.py
index f41c9ba12b..620e73210c 100644
--- a/invokeai/app/services/model_install/model_install_common.py
+++ b/invokeai/app/services/model_install/model_install_common.py
@@ -21,10 +21,34 @@ class InvalidModelConfigException(Exception):
pass
+INSTALL_RECOVERY_SENTINEL = ".invokeai_install_recovery_required"
+
+
class InstallRecoveryRequiredError(RuntimeError):
"""Install transfer could not be safely rolled back; preserve both recovery roots."""
+def recovery_sentinel_path(root: Path) -> Path:
+ """Return the sidecar marker path that protects an install recovery root."""
+ return root.parent / f".{root.name}{INSTALL_RECOVERY_SENTINEL}"
+
+
+def has_recovery_sentinel(root: Path) -> bool:
+ """Return whether an install recovery root has a durable preservation marker."""
+ return recovery_sentinel_path(root).exists()
+
+
+def is_recovery_protected_path(path: Path, boundary: Path) -> bool:
+ """Return whether a path or one of its ancestors below the boundary is recovery-protected."""
+ boundary = boundary.resolve()
+ current = path.resolve()
+ while current != boundary and current.is_relative_to(boundary):
+ if has_recovery_sentinel(current):
+ return True
+ current = current.parent
+ return False
+
+
class InstallStatus(str, Enum):
"""State of an install job running in the background."""
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 9af51aff4c..348afb02be 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -1,6 +1,7 @@
"""Model installation class."""
import ctypes
+import errno
import filecmp
import gc
import json
@@ -13,7 +14,7 @@ import time
from copy import deepcopy
from pathlib import Path
from queue import Empty, Queue
-from shutil import move, rmtree
+from shutil import copy2, copytree, move, rmtree
from tempfile import mkdtemp
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
@@ -40,6 +41,9 @@ from invokeai.app.services.model_install.model_install_common import (
ModelSource,
StringLikeSource,
URLModelSource,
+ has_recovery_sentinel,
+ is_recovery_protected_path,
+ recovery_sentinel_path,
)
from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelException
from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
@@ -86,7 +90,6 @@ TMPDIR_PREFIX = "tmpinstall_"
# Marker file used to resume or pause remote model installs across restarts.
INSTALL_MARKER_FILENAME = ".invokeai_install.json"
INSTALL_MARKER_VERSION = 1
-INSTALL_RECOVERY_SENTINEL = ".invokeai_install_recovery_required"
# Filesystems cap a single path component at 255 bytes. A source that lists many explicit files
# (an LTX-2 component folder names eight) would otherwise produce a folder name that cannot be
@@ -160,10 +163,10 @@ class ModelInstallService(ModelInstallServiceBase):
return tmpdir / INSTALL_MARKER_FILENAME
def _recovery_sentinel_path(self, tmpdir: Path) -> Path:
- return tmpdir.parent / f".{tmpdir.name}{INSTALL_RECOVERY_SENTINEL}"
+ return recovery_sentinel_path(tmpdir)
def _has_recovery_sentinel(self, tmpdir: Path) -> bool:
- return self._recovery_sentinel_path(tmpdir).exists()
+ return has_recovery_sentinel(tmpdir)
def _write_recovery_sentinel(self, tmpdir: Path) -> None:
# Keep recovery state outside the tree being transferred into the managed model directory.
@@ -196,8 +199,6 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.warning(f"Failed to remove install recovery sentinel in {tmpdir}: {e}")
def _retain_recovery_destination(self, dest_dir: Path) -> None:
- if not dest_dir.name.startswith(TMPDIR_PREFIX):
- return
try:
if dest_dir.exists():
self._write_recovery_sentinel(dest_dir)
@@ -597,7 +598,31 @@ class ModelInstallService(ModelInstallServiceBase):
def _restore_moved_path(cls, src: Path, dst: Path) -> None:
if dst.exists() or dst.is_symlink():
raise FileExistsError(f"Refusing to overwrite recreated source {dst}")
- cls._rename_noreplace(src, dst)
+ try:
+ cls._rename_noreplace(src, dst)
+ except OSError as e:
+ if e.errno != errno.EXDEV:
+ raise
+ # Local imports can span filesystems. Stage a full copy beside the original source, then
+ # atomically claim its name with a no-replace rename before removing the managed copy.
+ staging_dir = Path(mkdtemp(prefix=f".{dst.name}.restore-", dir=dst.parent))
+ staged_path = staging_dir / "restored"
+ try:
+ if src.is_symlink():
+ os.symlink(os.readlink(src), staged_path)
+ elif src.is_dir():
+ copytree(src, staged_path, symlinks=True)
+ elif src.is_file():
+ copy2(src, staged_path)
+ else:
+ raise OSError(f"Cannot restore unsupported filesystem object {src}")
+ cls._rename_noreplace(staged_path, dst)
+ if src.is_dir() and not src.is_symlink():
+ rmtree(src)
+ else:
+ src.unlink()
+ finally:
+ rmtree(staging_dir, ignore_errors=True)
def install_path(
self,
@@ -624,6 +649,9 @@ class ModelInstallService(ModelInstallServiceBase):
)
dest_dir.mkdir(parents=True)
destination_created = True
+ # Protect every file in the destination until the model record is committed. An admin can run orphan
+ # cleanup concurrently with this transfer, and the directory is not registered until _register().
+ self._write_recovery_sentinel(dest_dir)
dest_path = dest_dir / model_path.name if model_path.is_file() else dest_dir
if model_path.is_file():
try:
@@ -683,6 +711,7 @@ class ModelInstallService(ModelInstallServiceBase):
leftovers = ", ".join(str(path.resolve()) for path in remaining)
raise OSError(f"unexpected destination artifacts remain: {leftovers}")
dest_dir.rmdir()
+ self._delete_recovery_sentinel(dest_dir)
except Exception as cleanup_error:
self._retain_recovery_destination(dest_dir)
raise InstallRecoveryRequiredError(
@@ -698,6 +727,7 @@ class ModelInstallService(ModelInstallServiceBase):
leftovers = ", ".join(str(path.resolve()) for path in remaining)
raise OSError(f"unexpected destination artifacts remain: {leftovers}")
dest_dir.rmdir()
+ self._delete_recovery_sentinel(dest_dir)
except Exception as cleanup_error:
self._retain_recovery_destination(dest_dir)
raise InstallRecoveryRequiredError(
@@ -826,8 +856,12 @@ class ModelInstallService(ModelInstallServiceBase):
def cancel_job(self, job: ModelInstallJob) -> None:
"""Cancel the indicated job."""
- if job._recovery_required:
- raise ValueError("Cannot cancel an install that requires recovery; preserve its files for manual recovery.")
+ if job._recovery_required or (
+ job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)
+ ):
+ raise InstallRecoveryRequiredError(
+ "Cannot cancel an install that requires recovery; preserve its files for manual recovery."
+ )
job.cancel()
self._logger.warning(f"Cancelling {job.source}")
if dj := job._multifile_job:
@@ -858,6 +892,10 @@ class ModelInstallService(ModelInstallServiceBase):
def restart_failed(self, job: ModelInstallJob) -> None:
"""Restart failed or non-resumable downloads for a job."""
+ if job._recovery_required or (
+ job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)
+ ):
+ raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")
if not isinstance(job.source, (HFModelSource, URLModelSource)):
return
if not job.download_parts:
@@ -884,6 +922,10 @@ class ModelInstallService(ModelInstallServiceBase):
def restart_file(self, job: ModelInstallJob, file_source: str) -> None:
"""Restart a specific file download for a job."""
+ if job._recovery_required or (
+ job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)
+ ):
+ raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")
if not isinstance(job.source, (HFModelSource, URLModelSource)):
return
job.status = InstallStatus.WAITING
@@ -1341,7 +1383,17 @@ class ModelInstallService(ModelInstallServiceBase):
def _remove_dangling_install_dirs(self) -> None:
"""Remove leftover tmpdirs from aborted installs."""
path = self._app_config.models_path
+ registered_model_paths = {
+ (path / model.path).resolve() for model in self.record_store.all_models() if model.path
+ }
for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):
+ resolved_tmpdir = tmpdir.resolve()
+ if any(
+ model_path == resolved_tmpdir or model_path.is_relative_to(resolved_tmpdir)
+ for model_path in registered_model_paths
+ ):
+ self._logger.debug(f"Preserving registered model directory {tmpdir}")
+ continue
if self._has_recovery_sentinel(tmpdir):
self._logger.warning(f"Preserving install recovery data in {tmpdir}")
continue
@@ -1377,10 +1429,14 @@ class ModelInstallService(ModelInstallServiceBase):
installed_model_paths = {
(self._app_config.models_path / x.path).resolve() for x in self.record_store.all_models()
}
+ models_path = self._app_config.models_path.resolve()
# The bool returned by this callback determines if the model is added to the list of models found by the search
def on_model_found(model_path: Path) -> bool:
resolved_path = model_path.resolve()
+ if is_recovery_protected_path(resolved_path, models_path):
+ self._logger.warning(f"Skipping recovery-protected model path {model_path}")
+ return False
# Already registered models should be in the list of found models, but not re-registered.
if resolved_path in installed_model_paths:
return True
@@ -1458,6 +1514,7 @@ class ModelInstallService(ModelInstallServiceBase):
apply_lora_metadata(info, model_path.resolve(), model_images_path)
model_path = model_path.resolve()
+ recovery_root = model_path if model_path.is_dir() else model_path.parent
# Models in the Invoke-managed models dir should use relative paths.
if model_path.is_relative_to(self.app_config.models_path):
@@ -1473,6 +1530,8 @@ class ModelInstallService(ModelInstallServiceBase):
legacy_config_path = legacy_config_path.relative_to(self.app_config.legacy_conf_path)
info.config_path = legacy_config_path.as_posix()
self.record_store.add_model(info)
+ if self._has_recovery_sentinel(recovery_root):
+ self._delete_recovery_sentinel(recovery_root)
return info.key
def _next_id(self) -> int:
@@ -1797,7 +1856,9 @@ class ModelInstallService(ModelInstallServiceBase):
assert excp is not None
self._set_error(install_job, excp)
self._download_queue.cancel_job(download_job)
- if install_job._install_tmpdir is not None:
+ if install_job._install_tmpdir is not None and not self._has_recovery_sentinel(
+ install_job._install_tmpdir
+ ):
self._safe_rmtree(install_job._install_tmpdir, self._logger)
# Let other threads know that the number of downloads has changed
@@ -1815,7 +1876,9 @@ class ModelInstallService(ModelInstallServiceBase):
# if install job has already registered an error, then do not replace its status with cancelled
if not install_job.errored and not install_job.paused:
install_job.cancel()
- if install_job._install_tmpdir is not None:
+ if install_job._install_tmpdir is not None and not self._has_recovery_sentinel(
+ install_job._install_tmpdir
+ ):
# Mark cancelled before cleanup so we don't reuse the folder if deletion fails.
self._write_install_marker(install_job, status=InstallStatus.CANCELLED)
self._delete_install_marker(install_job._install_tmpdir)
diff --git a/invokeai/app/services/orphaned_models/orphaned_models_service.py b/invokeai/app/services/orphaned_models/orphaned_models_service.py
index fd1b1053b9..79d9dcfcde 100644
--- a/invokeai/app/services/orphaned_models/orphaned_models_service.py
+++ b/invokeai/app/services/orphaned_models/orphaned_models_service.py
@@ -12,6 +12,10 @@ from typing import Set
from pydantic import BaseModel, Field
from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.model_install.model_install_common import (
+ INSTALL_RECOVERY_SENTINEL,
+ is_recovery_protected_path,
+)
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
# Scratch area for operations that must build a model on the models volume before registering it -
@@ -72,7 +76,7 @@ class OrphanedModelsService:
Returns:
List of OrphanedModelInfo objects describing orphaned directories
"""
- models_path = self._config.models_path
+ models_path = self._config.models_path.resolve()
# Get all model directories registered in the database
db_model_directories = self._get_registered_model_directories(models_path)
@@ -115,6 +119,8 @@ class OrphanedModelsService:
# Convert to OrphanedModelInfo objects
result = []
for dir_path, files in orphaned_dirs_map.items():
+ if self._contains_recovery_sentinel(dir_path):
+ continue
# Calculate total size
total_size = sum(f.stat().st_size for f in files if f.exists())
@@ -155,6 +161,10 @@ class OrphanedModelsService:
results[rel_path] = "error: path is not under models directory"
continue
+ if full_path == models_path:
+ results[rel_path] = "error: cannot delete the models directory"
+ continue
+
try:
full_path.relative_to(conversion_scratch_path)
except ValueError:
@@ -163,6 +173,14 @@ class OrphanedModelsService:
results[rel_path] = "error: path is reserved for active conversion"
continue
+ if self._is_recovery_protected(full_path, models_path):
+ results[rel_path] = "error: path is reserved for install recovery"
+ continue
+
+ if self._contains_recovery_sentinel(full_path):
+ results[rel_path] = "error: path contains install recovery data"
+ continue
+
if not full_path.exists():
results[rel_path] = "error: path does not exist"
continue
@@ -176,6 +194,14 @@ class OrphanedModelsService:
return results
+ @staticmethod
+ def _is_recovery_protected(path: Path, models_path: Path) -> bool:
+ return is_recovery_protected_path(path, models_path)
+
+ @staticmethod
+ def _contains_recovery_sentinel(path: Path) -> bool:
+ return path.is_dir() and any(path.rglob(f"*{INSTALL_RECOVERY_SENTINEL}"))
+
def _get_registered_model_directories(self, models_dir: Path) -> Set[Path]:
"""Get the set of all model directories from the database."""
model_directories = set()
@@ -222,7 +248,11 @@ class OrphanedModelsService:
if any(skip_dir in item.parts for skip_dir in self.SKIP_DIRS):
continue
- if item.is_file() and item.suffix.lower() in self.MODEL_EXTENSIONS:
+ if (
+ item.is_file()
+ and item.suffix.lower() in self.MODEL_EXTENSIONS
+ and not self._is_recovery_protected(item.parent, models_path)
+ ):
model_files.add(item.resolve())
return model_files
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.py
index 27d1cc4d6d..3e612eec4c 100644
--- a/invokeai/backend/model_manager/configs/factory.py
+++ b/invokeai/backend/model_manager/configs/factory.py
@@ -863,7 +863,8 @@ class ModelConfigFactory:
candidate_name = candidate_class.__name__
try:
candidate_fields = fields
- # This config value comes from metadata, but its explicit override must reach its own probe.
+ # Preserve the explicit encoder choice for InvokeAI IP-Adapter probes; this field is not part of
+ # the common model record changes, but re-identification can carry it from the stored config.
if (
override_fields is not None
and "image_encoder_model_id" in override_fields
diff --git a/invokeai/backend/model_manager/configs/ip_adapter.py b/invokeai/backend/model_manager/configs/ip_adapter.py
index d0ca67fa60..47db5eaa18 100644
--- a/invokeai/backend/model_manager/configs/ip_adapter.py
+++ b/invokeai/backend/model_manager/configs/ip_adapter.py
@@ -67,12 +67,17 @@ class IPAdapter_InvokeAI_Config_Base(IPAdapter_Config_Base):
@classmethod
def _get_image_encoder_model_id(cls, mod: ModelOnDisk, override_fields: dict[str, Any]) -> str:
+ if "image_encoder_model_id" in override_fields:
+ override = override_fields["image_encoder_model_id"]
+ if not isinstance(override, str) or not override.strip():
+ raise NotAMatchError("empty image_encoder_model_id override")
+ return override.strip()
+
image_encoder_metadata_file = mod.path / "image_encoder.txt"
if not image_encoder_metadata_file.exists():
raise NotAMatchError("missing image_encoder.txt metadata file")
- if "image_encoder_model_id" in override_fields:
- return override_fields["image_encoder_model_id"]
- image_encoder_model_id = image_encoder_metadata_file.read_text(encoding="utf-8").strip()
+ with image_encoder_metadata_file.open(encoding="utf-8") as metadata:
+ image_encoder_model_id = metadata.readline().strip()
if not image_encoder_model_id:
raise NotAMatchError("empty image_encoder.txt metadata")
return image_encoder_model_id
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 214e42886e..9979a78019 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -4666,6 +4666,9 @@
}
}
},
+ "409": {
+ "description": "The job has recovery data that must be preserved"
+ },
"415": {
"description": "No such job"
},
@@ -4731,6 +4734,9 @@
}
}
},
+ "409": {
+ "description": "The job has recovery data that must be preserved"
+ },
"415": {
"description": "No such job"
},
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 14c2630cd1..2d637c0df8 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -53405,6 +53405,13 @@ export interface operations {
"application/json": components["schemas"]["ModelInstallJob"];
};
};
+ /** @description The job has recovery data that must be preserved */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
/** @description No such job */
415: {
headers: {
@@ -53448,6 +53455,13 @@ export interface operations {
"application/json": components["schemas"]["ModelInstallJob"];
};
};
+ /** @description The job has recovery data that must be preserved */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
/** @description No such job */
415: {
headers: {
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 2a35e92105..59ea28cda8 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -523,12 +523,161 @@ def test_convert_model_retains_recovery_source_and_restores_model_name(monkeypat
assert model_config.name == "Original Model"
+def test_cancel_model_install_does_not_map_unrelated_value_error_to_conflict(monkeypatch: Any) -> None:
+ from types import SimpleNamespace
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+
+ class Installer:
+ def get_job_by_id(self, _job_id: int) -> object:
+ return object()
+
+ def cancel_job(self, _job: object) -> None:
+ raise ValueError("unrelated service failure")
+
+ services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
+
+ with pytest.raises(ValueError, match="unrelated service failure"):
+ model_manager_router.cancel_model_install_job(current_admin=None, id=42)
+
+
[email protected]("operation", ["restart_failed", "restart_file"])
+def test_restart_recovery_required_install_returns_conflict(monkeypatch: Any, operation: str) -> None:
+ from types import SimpleNamespace
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+ from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError
+
+ class Installer:
+ def get_job_by_id(self, job_id: int) -> object:
+ assert job_id == 42
+ return object()
+
+ def restart_failed(self, _job: object) -> None:
+ raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery")
+
+ def restart_file(self, _job: object, _source: str) -> None:
+ raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery")
+
+ services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
+
+ with pytest.raises(HTTPException) as exc_info:
+ if operation == "restart_failed":
+ model_manager_router.restart_failed_model_install_job(current_admin=None, id=42)
+ else:
+ model_manager_router.restart_model_install_file(
+ current_admin=None, id=42, file_source="https://example.com/model.safetensors"
+ )
+
+ assert exc_info.value.status_code == 409
+ assert "requires recovery" in exc_info.value.detail
+
+
[email protected]("install_fails", [False, True])
+def test_conversion_cleans_scratch_after_success_and_ordinary_failure(
+ monkeypatch: Any, tmp_path: Path, install_fails: bool
+) -> None:
+ from types import SimpleNamespace
+ from unittest.mock import MagicMock
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+ from invokeai.app.services.model_images.model_images_common import ModelImageFileNotFoundException
+ from invokeai.app.services.model_records import ModelRecordChanges
+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
+ from invokeai.backend.model_manager.taxonomy import (
+ BaseModelType,
+ ModelFormat,
+ ModelSourceType,
+ ModelType,
+ ModelVariantType,
+ SchedulerPredictionType,
+ )
+
+ models_path = tmp_path / "models"
+ models_path.mkdir()
+ original = Main_Checkpoint_SD1_Config(
+ key="model-key",
+ path="original.safetensors",
+ name="Original Model",
+ format=ModelFormat.Checkpoint,
+ base=BaseModelType.StableDiffusion1,
+ type=ModelType.Main,
+ config_path="model.yaml",
+ variant=ModelVariantType.Normal,
+ hash="111222333444",
+ file_size=8192,
+ source="local-source",
+ source_type=ModelSourceType.Path,
+ prediction_type=SchedulerPredictionType.Epsilon,
+ )
+ converted = SimpleNamespace(key="converted-key")
+
+ class Store:
+ def get_model(self, key: str) -> Any:
+ return original if key == original.key else converted
+
+ def update_model(self, key: str, changes: ModelRecordChanges) -> None:
+ if changes.name is not None:
+ original.name = changes.name
+
+ def save_pretrained(path: Path) -> None:
+ path.mkdir()
+ (path / "weights.safetensors").write_bytes(b"weights")
+
+ class Installer:
+ def install_path(self, _path: Path, *, config: ModelRecordChanges) -> str:
+ if install_fails:
+ raise ValueError("ordinary install failure")
+ return converted.key
+
+ def delete(self, _key: str) -> None:
+ return None
+
+ def model_image(_key: str) -> None:
+ raise ModelImageFileNotFoundException()
+
+ services = SimpleNamespace(
+ model_manager=SimpleNamespace(
+ store=Store(),
+ load=SimpleNamespace(
+ load_model=lambda *_args, **_kwargs: SimpleNamespace(
+ model=SimpleNamespace(save_pretrained=save_pretrained)
+ )
+ ),
+ install=Installer(),
+ ),
+ configuration=SimpleNamespace(models_path=models_path),
+ model_images=SimpleNamespace(get=model_image),
+ logger=MagicMock(),
+ )
+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
+ monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _deps: config)
+
+ if install_fails:
+ with pytest.raises(HTTPException) as exc_info:
+ model_manager_router._convert_model(original.key, user_id="test-user")
+ assert exc_info.value.status_code == 409
+ else:
+ assert model_manager_router._convert_model(original.key, user_id="test-user") is converted
+
+ scratch_dir = models_path / model_manager_router.CONVERSION_SCRATCH_DIRNAME
+ assert scratch_dir.exists()
+ assert list(scratch_dir.iterdir()) == []
+
+
def test_cancel_recovery_required_install_returns_conflict(monkeypatch: Any) -> None:
from types import SimpleNamespace
from starlette.exceptions import HTTPException
from invokeai.app.api.routers import model_manager as model_manager_router
+ from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError
class Installer:
def get_job_by_id(self, job_id: int) -> object:
@@ -536,7 +685,7 @@ def test_cancel_recovery_required_install_returns_conflict(monkeypatch: Any) ->
return object()
def cancel_job(self, _job: object) -> None:
- raise ValueError("Cannot cancel an install that requires recovery")
+ raise InstallRecoveryRequiredError("Cannot cancel an install that requires recovery")
services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
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 e2e7ac4890..95b8409cb5 100644
--- a/tests/app/routers/test_update_model_record_cache_invalidation.py
+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py
@@ -5,6 +5,7 @@ until the cached entry is evicted. The predicate must catch changes to those set
ignoring changes that don't affect how the model loads (e.g. name, description).
"""
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -51,6 +52,21 @@ def test_missing_default_settings_is_handled():
assert _load_settings_changed(no_settings, _config(fp8=True)) is True
[email protected]("field", ["fp8_storage", "cpu_only"])
+def test_pydantic_nested_load_setting_changes_trigger_invalidation(field: str) -> None:
+ from pydantic import BaseModel
+
+ from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
+
+ class PydanticConfig(BaseModel):
+ default_settings: MainModelDefaultSettings | None = None
+
+ previous = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: False}))
+ updated = PydanticConfig(default_settings=MainModelDefaultSettings(**{field: True}))
+
+ assert _load_settings_changed(previous, updated) 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."""
@@ -59,7 +75,7 @@ def test_unrelated_field_does_not_trigger_invalidation():
assert _load_settings_changed(bare_a, bare_b) is False
[email protected]("field", ["path", "base", "type", "format", "variant"])
[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant"])
def test_model_identity_changes_trigger_invalidation(field: str):
"""Fields exposed by ModelRecordChanges can change the module selected or its source path."""
previous = _config(**{field: "old"})
@@ -67,7 +83,7 @@ def test_model_identity_changes_trigger_invalidation(field: str):
assert _load_settings_changed(previous, updated) is True
[email protected]("field", ["path", "base", "type", "format", "variant", "name", "description"])
[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant", "name", "description"])
def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkeypatch: pytest.MonkeyPatch):
previous = _config(**{field: "old"})
updated = _config(**{field: "new"})
@@ -160,3 +176,115 @@ def test_record_update_handles_real_cpu_cache_entries(
finally:
for cache in caches:
cache.shutdown()
+
+
+def test_reidentify_invalidates_caches_when_identification_changes_model_class(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+):
+ """Re-probing can change loader identity just like an explicit model-record edit."""
+ from types import SimpleNamespace
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelSourceType, ModelType
+
+ previous = SimpleNamespace(
+ key="model-key",
+ path="model.safetensors",
+ name="Model",
+ description="",
+ cover_image=None,
+ source="local-source",
+ source_type=ModelSourceType.Path,
+ image_encoder_model_id="custom/image-encoder",
+ base=BaseModelType.StableDiffusion1,
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant="old",
+ cpu_only=False,
+ default_settings=None,
+ )
+ identified = SimpleNamespace(
+ key="model-key",
+ path="model.safetensors",
+ name="identified name",
+ description="identified description",
+ cover_image=None,
+ source="new-source",
+ source_type=ModelSourceType.Path,
+ base=BaseModelType.StableDiffusionXL,
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant="new",
+ cpu_only=False,
+ default_settings=None,
+ )
+ stored = SimpleNamespace(
+ replace_model=MagicMock(return_value=identified), get_model=MagicMock(return_value=previous)
+ )
+ caches = [SimpleNamespace(drop_model=MagicMock(return_value=1)) for _ in range(2)]
+ services = SimpleNamespace(
+ model_manager=SimpleNamespace(
+ store=stored, load=SimpleNamespace(ram_caches={str(i): cache for i, cache in enumerate(caches)})
+ ),
+ configuration=SimpleNamespace(models_path=tmp_path / "models"),
+ logger=MagicMock(),
+ )
+ monkeypatch.setattr(
+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False
+ )
+ monkeypatch.setattr(model_manager_router, "ModelOnDisk", lambda _path: object())
+ factory_overrides: dict[str, object] = {}
+
+ def identify(_model_on_disk: object, override_fields: dict[str, object]) -> object:
+ factory_overrides.update(override_fields)
+ return SimpleNamespace(config=identified)
+
+ monkeypatch.setattr(model_manager_router.ModelConfigFactory, "from_model_on_disk", identify)
+
+ assert model_manager_router._reidentify_model("model-key") is identified
+ assert factory_overrides["image_encoder_model_id"] == "custom/image-encoder"
+
+ for cache in caches:
+ cache.drop_model.assert_called_once_with("model-key")
+
+
+def test_reidentify_preserves_ip_adapter_encoder_override_with_blank_metadata(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ import torch
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+ from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
+ from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI_SD1_Config
+ from invokeai.backend.model_manager.taxonomy import ModelSourceType
+
+ models_path = tmp_path / "models"
+ model_path = models_path / "ip-adapter"
+ model_path.mkdir(parents=True)
+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, model_path / "ip_adapter.bin")
+ (model_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")
+ result = ModelConfigFactory.from_model_on_disk(
+ model_path, override_fields={"image_encoder_model_id": "custom/image-encoder"}, allow_unknown=False
+ )
+ assert isinstance(result.config, IPAdapter_InvokeAI_SD1_Config)
+ previous = result.config
+ previous.key = "ip-adapter-key"
+ previous.path = "ip-adapter"
+ previous.name = "IP-Adapter"
+ previous.source = "local-source"
+ previous.source_type = ModelSourceType.Path
+
+ store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)
+ services = SimpleNamespace(
+ model_manager=SimpleNamespace(store=store, load=SimpleNamespace(ram_caches={})),
+ configuration=SimpleNamespace(models_path=models_path),
+ logger=MagicMock(),
+ )
+ monkeypatch.setattr(
+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False
+ )
+
+ updated = model_manager_router._reidentify_model("ip-adapter-key")
+
+ assert isinstance(updated, IPAdapter_InvokeAI_SD1_Config)
+ assert updated.image_encoder_model_id == "custom/image-encoder"
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 600c1fbfc3..b5ff2e25d7 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -2,6 +2,7 @@
Test the model installer
"""
+import errno
import gc
import json
import platform
@@ -36,6 +37,8 @@ from invokeai.app.services.model_install import (
model_install_default,
)
from invokeai.app.services.model_install.model_install_common import (
+ INSTALL_RECOVERY_SENTINEL,
+ InstallRecoveryRequiredError,
InstallStatus,
InvalidModelConfigException,
LocalModelSource,
@@ -164,6 +167,100 @@ def test_file_install_retries_copy_then_unlink_permission_error(
assert calls == 1
+def test_destination_is_hidden_from_orphan_cleanup_during_install(
+ mm2_installer: ModelInstallServiceBase,
+ embedding_file: Path,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from invokeai.app.services.model_install.model_install_common import has_recovery_sentinel
+ from invokeai.app.services.orphaned_models import OrphanedModelsService
+
+ orphan_service = OrphanedModelsService(config=mm2_app_config, db=mm2_installer.record_store._db)
+ observations: list[tuple[str, bool, set[str]]] = []
+ real_move = shutil.move
+
+ def move_then_scan(src: Path, dst: Path):
+ result = real_move(src, dst)
+ destination_root = dst.parent
+ orphan_keys = {orphan.path for orphan in orphan_service.find_orphaned_models()}
+ observations.append((destination_root.name, has_recovery_sentinel(destination_root), orphan_keys))
+ return result
+
+ monkeypatch.setattr(model_install_default, "move", move_then_scan)
+
+ mm2_installer.install_path(embedding_file)
+
+ assert len(observations) == 1
+ destination_key, has_sentinel, orphan_keys = observations[0]
+ assert has_sentinel
+ assert destination_key not in orphan_keys
+ assert not has_recovery_sentinel(mm2_app_config.models_path / destination_key)
+
+
+def test_unregistered_destination_remains_protected_after_registration_failure(
+ mm2_installer: ModelInstallServiceBase,
+ embedding_file: Path,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from invokeai.app.services.model_install.model_install_common import has_recovery_sentinel
+ from invokeai.app.services.orphaned_models import OrphanedModelsService
+
+ orphan_service = OrphanedModelsService(config=mm2_app_config, db=mm2_installer.record_store._db)
+
+ def fail_recording(_config: Any) -> None:
+ raise RuntimeError("simulated model record failure")
+
+ monkeypatch.setattr(mm2_installer.record_store, "add_model", fail_recording)
+
+ with pytest.raises(RuntimeError, match="simulated model record failure"):
+ mm2_installer.install_path(embedding_file)
+
+ protected_roots = [
+ path for path in mm2_app_config.models_path.iterdir() if path.is_dir() and has_recovery_sentinel(path)
+ ]
+ assert len(protected_roots) == 1
+ recovery_root = protected_roots[0]
+ assert list(recovery_root.iterdir())
+ assert recovery_root.name not in {orphan.path for orphan in orphan_service.find_orphaned_models()}
+
+
[email protected]("is_directory", [False, True])
+def test_rollback_restores_source_across_filesystems_without_overwriting(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, is_directory: bool
+) -> None:
+ source_root = tmp_path / "source"
+ destination_root = tmp_path / "models"
+ source_root.mkdir()
+ destination_root.mkdir()
+ original = source_root / "model"
+ if is_directory:
+ original.mkdir()
+ (original / "weights.safetensors").write_bytes(b"model weights")
+ else:
+ original.write_bytes(b"model weights")
+ moved = destination_root / "model"
+ shutil.move(original, moved)
+ real_rename_noreplace = ModelInstallService._rename_noreplace
+
+ def raise_exdev_for_original(src: Path, dst: Path) -> None:
+ if src == moved:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename_noreplace(src, dst)
+
+ monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(raise_exdev_for_original))
+
+ ModelInstallService._restore_moved_path(moved, original)
+
+ assert original.exists()
+ assert not moved.exists()
+ if is_directory:
+ assert (original / "weights.safetensors").read_bytes() == b"model weights"
+ else:
+ assert original.read_bytes() == b"model weights"
+
+
def test_directory_install_retries_windows_move_failures(
mm2_installer: ModelInstallServiceBase,
diffusers_dir: Path,
@@ -302,12 +399,13 @@ def test_directory_install_preserves_collision_during_rollback(
else:
assert recreated.read_text() == "new user file"
assert str(mm2_app_config.models_path.resolve()) in str(exc_info.value)
- recovery_paths = set(mm2_app_config.models_path.iterdir()) - existing_paths
+ recovery_paths = [path for path in set(mm2_app_config.models_path.iterdir()) - existing_paths if path.is_dir()]
assert len(recovery_paths) == 1
- recovery_dest = recovery_paths.pop()
+ recovery_dest = recovery_paths[0]
preserved_item = recovery_dest / first_item.name
assert preserved_item.exists()
assert preserved_item.is_dir() == first_item_is_dir
+ assert mm2_installer._has_recovery_sentinel(recovery_dest)
def test_directory_install_rollback_race_preserves_both_source_artifacts(
@@ -393,9 +491,10 @@ def test_directory_install_retains_unowned_destination_artifact_after_rollback(
with pytest.raises(RuntimeError, match="recovery required") as exc_info:
mm2_installer.install_path(diffusers_dir)
- recovery_paths = set(mm2_app_config.models_path.iterdir()) - existing_paths
+ recovery_paths = [path for path in set(mm2_app_config.models_path.iterdir()) - existing_paths if path.is_dir()]
assert len(recovery_paths) == 1
- recovery_dest = recovery_paths.pop()
+ recovery_dest = recovery_paths[0]
+ assert mm2_installer._has_recovery_sentinel(recovery_dest)
assert (recovery_dest / "unowned-artifact").read_text() == "created concurrently"
assert str(diffusers_dir.resolve()) in str(exc_info.value)
assert str(recovery_dest.resolve()) in str(exc_info.value)
@@ -463,7 +562,7 @@ def test_remote_install_recovery_survives_cleanup_and_restart(
assert job.errored
assert mm2_installer._has_recovery_sentinel(tmpdir)
- assert model_install_default.INSTALL_RECOVERY_SENTINEL not in {path.name for path in real_iterdir(tmpdir)}
+ assert INSTALL_RECOVERY_SENTINEL not in {path.name for path in real_iterdir(tmpdir)}
assert {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files
recovery_files = [
path
@@ -518,7 +617,7 @@ def test_cancel_recovery_required_install_preserves_recovery_data(
job._recovery_required = True
mm2_installer._write_recovery_sentinel(tmpdir)
- with pytest.raises(ValueError, match="requires recovery"):
+ with pytest.raises(InstallRecoveryRequiredError, match="requires recovery"):
mm2_installer.cancel_job(job)
assert not job.cancelled
@@ -526,6 +625,144 @@ def test_cancel_recovery_required_install_preserves_recovery_data(
assert mm2_installer._has_recovery_sentinel(tmpdir)
+def test_cancel_recovery_sentinel_protects_data_before_job_flag_is_set(
+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}recovery-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ downloaded_file = tmpdir / "model.safetensors"
+ downloaded_file.write_bytes(b"recoverable source")
+ job = ModelInstallJob(
+ id=993,
+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),
+ config_in=ModelRecordChanges(),
+ local_path=downloaded_file,
+ status=InstallStatus.RUNNING,
+ )
+ job._install_tmpdir = tmpdir
+ mm2_installer._write_recovery_sentinel(tmpdir)
+
+ with pytest.raises(InstallRecoveryRequiredError, match="requires recovery"):
+ mm2_installer.cancel_job(job)
+
+ assert not job.cancelled
+ assert downloaded_file.read_bytes() == b"recoverable source"
+ assert mm2_installer._has_recovery_sentinel(tmpdir)
+
+
[email protected]("operation", ["restart_failed", "restart_file"])
+def test_restart_refuses_recovery_sentinel(
+ operation: str,
+ mm2_installer: ModelInstallServiceBase,
+ mm2_app_config: InvokeAIAppConfig,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}recovery-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ downloaded_file = tmpdir / "model.safetensors"
+ downloaded_file.write_bytes(b"recoverable source")
+ job = ModelInstallJob(
+ id=994,
+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.ERROR,
+ )
+ job._install_tmpdir = tmpdir
+ mm2_installer._write_recovery_sentinel(tmpdir)
+ monkeypatch.setattr(
+ mm2_installer, "_remote_files_from_source", lambda *_args, **_kwargs: pytest.fail("restart reached source")
+ )
+
+ with pytest.raises(InstallRecoveryRequiredError, match="requires recovery"):
+ if operation == "restart_failed":
+ mm2_installer.restart_failed(job)
+ else:
+ mm2_installer.restart_file(job, str(job.source))
+
+ assert job.status is InstallStatus.ERROR
+ assert downloaded_file.read_bytes() == b"recoverable source"
+ assert mm2_installer._has_recovery_sentinel(tmpdir)
+
+
+def test_recovery_required_marker_round_trips_and_preserves_staging_dir(
+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}recovery-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ downloaded_file = tmpdir / "model.safetensors"
+ downloaded_file.write_bytes(b"recoverable source")
+ job = ModelInstallJob(
+ id=995,
+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.ERROR,
+ )
+ job._install_tmpdir = tmpdir
+ job._recovery_required = True
+
+ mm2_installer._write_install_marker(job)
+ marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))
+ mm2_installer._remove_dangling_install_dirs()
+
+ assert marker["recovery_required"] is True
+ assert downloaded_file.read_bytes() == b"recoverable source"
+ assert tmpdir.exists()
+
+
+def test_registering_recovery_root_removes_its_sentinel(
+ mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ recovery_root = mm2_app_config.models_path / "recovered-model"
+ recovery_root.mkdir()
+ shutil.copy2(embedding_file, recovery_root / embedding_file.name)
+ sentinel = mm2_installer._recovery_sentinel_path(recovery_root)
+ sentinel.write_text("preserve until registered", encoding="utf-8")
+
+ key = mm2_installer.register_path(recovery_root)
+
+ assert mm2_installer.record_store.get_model(key).path == "recovered-model"
+ assert not sentinel.exists()
+
+
+def test_startup_scan_skips_recovery_protected_root(
+ mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ recovery_root = mm2_app_config.models_path / "recovered-model"
+ recovery_root.mkdir()
+ shutil.copy2(embedding_file, recovery_root / embedding_file.name)
+ sentinel = mm2_installer._recovery_sentinel_path(recovery_root)
+ sentinel.write_text("preserve until manually registered", encoding="utf-8")
+
+ mm2_installer._register_orphaned_models()
+
+ assert mm2_installer.record_store.all_models() == []
+ assert sentinel.exists()
+ assert (recovery_root / embedding_file.name).exists()
+
+
+def test_registered_model_with_temporary_prefix_survives_startup_cleanup(
+ mm2_installer: ModelInstallServiceBase,
+ embedding_file: Path,
+ mm2_app_config: InvokeAIAppConfig,
+) -> None:
+ model_key = f"{TMPDIR_PREFIX}registered-model"
+
+ installed_key = mm2_installer.install_path(embedding_file, config=ModelRecordChanges(key=model_key))
+ installed_path = mm2_app_config.models_path / mm2_installer.record_store.get_model(installed_key).path
+
+ mm2_installer._remove_dangling_install_dirs()
+
+ assert installed_path.exists()
+ assert mm2_installer.record_store.exists(model_key)
+
+
def test_install_registration_failure_preserves_complete_recoverable_files(
mm2_installer: ModelInstallServiceBase,
diffusers_dir: Path,
diff --git a/tests/app/services/model_records/test_model_records_sql.py b/tests/app/services/model_records/test_model_records_sql.py
index 68e28a3017..25b052d772 100644
--- a/tests/app/services/model_records/test_model_records_sql.py
+++ b/tests/app/services/model_records/test_model_records_sql.py
@@ -172,6 +172,12 @@ def test_rejected_class_change_preserves_the_original_record(store: ModelRecordS
assert after.model_dump() == before.model_dump()
[email protected]("field", ["type", "base"])
+def test_model_record_changes_reject_invalid_classification_values(field: str) -> None:
+ with pytest.raises(ValidationError):
+ ModelRecordChanges.model_validate({field: "not-a-model-classification"})
+
+
def test_unknown_key(store: ModelRecordServiceBase):
config = example_ti_config("key1")
store.add_model(config)
diff --git a/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py b/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py
index 15a566347e..373d31a4ff 100644
--- a/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py
+++ b/tests/app/services/model_relationship_records/test_model_relationship_records_sqlite.py
@@ -2,33 +2,42 @@
import logging
import sqlite3
+from pathlib import Path
import pytest
+from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.model_records import ModelRecordServiceSQL
from invokeai.app.services.model_relationship_records.model_relationship_records_sqlite import (
SqliteModelRelationshipRecordStorage,
)
-from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
+from invokeai.backend.model_manager.configs.textual_inversion import TI_File_SD1_Config
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelSourceType, ModelType
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
@pytest.fixture
-def storage() -> SqliteModelRelationshipRecordStorage:
- db = SqliteDatabase(db_path=None, logger=logging.getLogger(__name__))
- with db.transaction() as cursor:
- cursor.execute("CREATE TABLE models (id TEXT PRIMARY KEY NOT NULL)")
- cursor.execute(
- """
- CREATE TABLE model_relationships (
- model_key_1 TEXT NOT NULL,
- model_key_2 TEXT NOT NULL,
- created_at TEXT NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
- PRIMARY KEY (model_key_1, model_key_2),
- FOREIGN KEY (model_key_1) REFERENCES models(id) ON DELETE CASCADE,
- FOREIGN KEY (model_key_2) REFERENCES models(id) ON DELETE CASCADE
+def storage(tmp_path: Path) -> SqliteModelRelationshipRecordStorage:
+ logger = logging.getLogger(__name__)
+ config = InvokeAIAppConfig()
+ config._root = tmp_path
+ db = create_mock_sqlite_database(config, logger)
+ records = ModelRecordServiceSQL(db, logger)
+ for key in ("model-a", "model-b"):
+ records.add_model(
+ TI_File_SD1_Config(
+ key=key,
+ source=f"test/{key}",
+ source_type=ModelSourceType.Path,
+ path=f"/tmp/{key}.safetensors",
+ file_size=1,
+ name=key,
+ base=BaseModelType.StableDiffusion1,
+ type=ModelType.TextualInversion,
+ format=ModelFormat.EmbeddingFile,
+ hash=f"hash-{key}",
)
- """
)
- cursor.executemany("INSERT INTO models (id) VALUES (?)", [("model-a",), ("model-b",)])
return SqliteModelRelationshipRecordStorage(db)
@@ -55,10 +64,9 @@ def test_remove_missing_relationship_is_idempotent(storage: SqliteModelRelations
assert storage.get_related_model_keys("model-a") == []
-def test_delete_model_cascades_relationship(storage: SqliteModelRelationshipRecordStorage) -> None:
+def test_delete_model_cascades_relationship_in_migrated_schema(storage: SqliteModelRelationshipRecordStorage) -> None:
storage.add_model_relationship("model-a", "model-b")
- db = storage._db
- with db.transaction() as cursor:
+ with storage._db.transaction() as cursor:
cursor.execute("DELETE FROM models WHERE id = ?", ("model-a",))
assert storage.get_related_model_keys("model-b") == []
diff --git a/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py
index e4bf1c211e..afe636a452 100644
--- a/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py
+++ b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py
@@ -14,6 +14,7 @@ from pathlib import Path
import pytest
from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.model_install.model_install_common import INSTALL_RECOVERY_SENTINEL
from invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelsService
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -74,3 +75,49 @@ def test_conversion_scratch_directory_cannot_be_deleted(models_path: Path, db: S
assert result[CONVERSION_SCRATCH_DIRNAME].startswith("error:")
assert (models_path / CONVERSION_SCRATCH_DIRNAME).exists()
+
+
[email protected]("root_name", ["tmpinstall_recovery", "recovered-model"])
+def test_install_recovery_root_is_not_reported_or_deleted(
+ root_name: str, models_path: Path, db: SqliteDatabase
+) -> None:
+ recovery_root = models_path / root_name
+ _write_model_file(recovery_root)
+ sentinel = models_path / f".{root_name}{INSTALL_RECOVERY_SENTINEL}"
+ sentinel.write_text("preserve", encoding="utf-8")
+ service = _service(models_path, db)
+
+ assert service.find_orphaned_models() == []
+ result = service.delete_orphaned_models([root_name])
+
+ assert result[root_name].startswith("error:")
+ assert (recovery_root / "model.safetensors").exists()
+ assert sentinel.exists()
+
+
+def test_parent_of_recovery_root_cannot_be_deleted(models_path: Path, db: SqliteDatabase) -> None:
+ parent = models_path / "model-group"
+ _write_model_file(parent / "ordinary-orphan")
+ recovery_root = parent / "recovered-model"
+ _write_model_file(recovery_root)
+ sentinel = parent / f".{recovery_root.name}{INSTALL_RECOVERY_SENTINEL}"
+ sentinel.write_text("preserve", encoding="utf-8")
+
+ service = _service(models_path, db)
+
+ assert "model-group" not in {orphan.path for orphan in service.find_orphaned_models()}
+ result = service.delete_orphaned_models(["model-group"])
+
+ assert result["model-group"].startswith("error:")
+ assert (parent / "ordinary-orphan" / "model.safetensors").exists()
+ assert (recovery_root / "model.safetensors").exists()
+ assert sentinel.exists()
+
+
+def test_models_root_cannot_be_deleted_as_an_orphan(models_path: Path, db: SqliteDatabase) -> None:
+ _write_model_file(models_path / "real-model")
+
+ result = _service(models_path, db).delete_orphaned_models(["."])
+
+ assert result["."].startswith("error:")
+ assert (models_path / "real-model" / "model.safetensors").exists()
diff --git a/tests/backend/model_manager/configs/test_ip_adapter_config.py b/tests/backend/model_manager/configs/test_ip_adapter_config.py
index 68314b3249..8d6d7ce1fd 100644
--- a/tests/backend/model_manager/configs/test_ip_adapter_config.py
+++ b/tests/backend/model_manager/configs/test_ip_adapter_config.py
@@ -11,7 +11,11 @@ from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI
@pytest.mark.parametrize(
"metadata",
- ["InvokeAI/ip_adapter_sd_image_encoder\n", " InvokeAI/ip_adapter_sd_image_encoder \r\n"],
+ [
+ "InvokeAI/ip_adapter_sd_image_encoder\n",
+ " InvokeAI/ip_adapter_sd_image_encoder \r\n",
+ "InvokeAI/ip_adapter_sd_image_encoder\nignored second line\n",
+ ],
)
def test_invokeai_ip_adapter_probe_normalizes_image_encoder_metadata(tmp_path: Path, metadata: str) -> None:
torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")
@@ -33,7 +37,7 @@ def test_invokeai_ip_adapter_probe_rejects_empty_image_encoder_metadata(tmp_path
assert any("empty image_encoder.txt metadata" in str(error) for error in result.details.values())
-def test_invokeai_ip_adapter_probe_uses_encoder_override_without_mutating_it(tmp_path: Path) -> None:
+def test_invokeai_ip_adapter_probe_applies_encoder_override_without_mutating_it(tmp_path: Path) -> None:
torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")
(tmp_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")
overrides = {"image_encoder_model_id": "custom/image-encoder"}
@@ -45,6 +49,18 @@ def test_invokeai_ip_adapter_probe_uses_encoder_override_without_mutating_it(tmp
assert overrides == {"image_encoder_model_id": "custom/image-encoder"}
+def test_invokeai_ip_adapter_probe_rejects_empty_encoder_override(tmp_path: Path) -> None:
+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")
+ (tmp_path / "image_encoder.txt").write_text("custom/image-encoder\n", encoding="utf-8")
+
+ result = ModelConfigFactory.from_model_on_disk(
+ tmp_path, override_fields={"image_encoder_model_id": " "}, allow_unknown=False
+ )
+
+ assert result.config is None
+ assert any("empty image_encoder_model_id override" in str(error) for error in result.details.values())
+
+
def test_invokeai_ip_adapter_probe_rejects_missing_image_encoder_metadata(tmp_path: Path) -> None:
torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")