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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model-manager): preserve recovery data across failures
JPPhoto1dd411fb39c9
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 49dc7c866a..67c58081d1 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -568,7 +568,9 @@ These methods bypass the download queue and directly register or install the modBoth methods accept a Path object corresponding to a checkpoint or diffusers folder, and an optional dict of config attributes to use to override the values derived from model probing.-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 makes a copy of the model inside the InvokeAI models directory before registering it.+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.#### installer.unregister(key)diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 0b8942b122..608f2a9c36 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -4,13 +4,14 @@ import asyncioimport contextlibimport ioimport pathlib+import shutilimport threadingimport tracebackimport unicodedatafrom collections.abc import Generatorfrom copy import deepcopyfrom enum import Enum-from tempfile import TemporaryDirectory+from tempfile import mkdtempfrom typing import Any, List, Optional, Typeimport huggingface_hub@@ -28,7 +29,7 @@ from invokeai.app.services.model_images.model_images_common import (ModelImageFileDeleteException,ModelImageFileNotFoundException,)-from invokeai.app.services.model_install.model_install_common import ModelInstallJob+from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError, ModelInstallJobfrom invokeai.app.services.model_records import (InvalidModelException,ModelRecordChanges,@@ -1264,6 +1265,7 @@ def get_model_install_job(responses={201: {"description": "The job was cancelled successfully"},415: {"description": "No such job"},+ 409: {"description": "The job has recovery data that must be preserved"},},status_code=201,)@@ -1277,7 +1279,10 @@ def cancel_model_install_job(job = installer.get_job_by_id(id)except ValueError as e:raise HTTPException(status_code=415, detail=str(e))- installer.cancel_job(job)+ try:+ installer.cancel_job(job)+ except ValueError as e:+ raise HTTPException(status_code=409, detail=str(e)) from e@model_manager_router.post(@@ -1455,8 +1460,10 @@ def _convert_model(key: str, user_id: str) -> AnyModelConfig:scratch_dir = ApiDependencies.invoker.services.configuration.models_path / CONVERSION_SCRATCH_DIRNAMEscratch_dir.mkdir(parents=True, exist_ok=True)- with TemporaryDirectory(dir=scratch_dir) as tmpdir:- convert_path = pathlib.Path(tmpdir) / pathlib.Path(model_config.path).stem+ tmpdir = pathlib.Path(mkdtemp(dir=scratch_dir))+ preserve_scratch = False+ try:+ convert_path = tmpdir / pathlib.Path(model_config.path).stemconverted_model = loader.load_model(model_config, user_id=user_id)# write the converted file to the convert pathraw_model = converted_model.model@@ -1485,6 +1492,14 @@ def _convert_model(key: str, user_id: str) -> AnyModelConfig:),))+ except InstallRecoveryRequiredError as e:+ preserve_scratch = True+ logger.error(str(e))+ store.update_model(key, changes=ModelRecordChanges(name=original_name))+ raise HTTPException(+ status_code=409,+ detail=f"{e} Conversion recovery source retained at {tmpdir.resolve()}.",+ ) from eexcept Exception as e:logger.error(str(e))store.update_model(key, changes=ModelRecordChanges(name=original_name))@@ -1505,6 +1520,9 @@ def _convert_model(key: str, user_id: str) -> AnyModelConfig:new_config = store.get_model(new_key)new_config = prepare_model_config_for_response(new_config, ApiDependencies)return new_config+ finally:+ if not preserve_scratch:+ shutil.rmtree(tmpdir, ignore_errors=True)class StarterModelResponse(BaseModel):diff --git a/invokeai/app/services/model_install/__init__.py b/invokeai/app/services/model_install/__init__.pyindex d96e86cbfe..21ad8382c2 100644--- a/invokeai/app/services/model_install/__init__.py+++ b/invokeai/app/services/model_install/__init__.py@@ -3,6 +3,7 @@from invokeai.app.services.model_install.model_install_base import ModelInstallServiceBasefrom invokeai.app.services.model_install.model_install_common import (HFModelSource,+ InstallRecoveryRequiredError,InstallStatus,LocalModelSource,ModelInstallJob,@@ -16,6 +17,7 @@ __all__ = ["ModelInstallServiceBase","ModelInstallService","InstallStatus",+ "InstallRecoveryRequiredError","ModelInstallJob","UnknownInstallJobException","ModelSource",diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex a503d5806b..f41c9ba12b 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -21,6 +21,10 @@ class InvalidModelConfigException(Exception):pass+class InstallRecoveryRequiredError(RuntimeError):+ """Install transfer could not be safely rolled back; preserve both recovery roots."""++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.pyindex 4022f60033..6e5e13fcc7 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -1,5 +1,6 @@"""Model installation class."""+import ctypesimport gcimport jsonimport locale@@ -30,6 +31,7 @@ from invokeai.app.services.model_install.model_install_common import (MODEL_SOURCE_TO_TYPE_MAP,ExternalModelSource,HFModelSource,+ InstallRecoveryRequiredError,InstallStatus,InvalidModelConfigException,LocalModelSource,@@ -83,11 +85,7 @@ 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---class InstallRecoveryRequiredError(RuntimeError):- """Install transfer could not be safely rolled back; preserve both recovery roots."""-+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,6 +158,51 @@ class ModelInstallService(ModelInstallServiceBase):def _marker_path(self, tmpdir: Path) -> Path:return tmpdir / INSTALL_MARKER_FILENAME+ def _recovery_sentinel_path(self, tmpdir: Path) -> Path:+ return tmpdir.parent / f".{tmpdir.name}{INSTALL_RECOVERY_SENTINEL}"++ def _has_recovery_sentinel(self, tmpdir: Path) -> bool:+ return self._recovery_sentinel_path(tmpdir).exists()++ def _write_recovery_sentinel(self, tmpdir: Path) -> None:+ # Keep recovery state outside the tree being transferred into the managed model directory.+ path = self._recovery_sentinel_path(tmpdir)+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "xb") as f:+ f.write(b"Install transfer recovery required. Preserve this directory.\n")+ f.flush()+ os.fsync(f.fileno())+ # Persist the directory entry before moving any source data where directory fsync is supported.+ if os.name != "nt":+ fd = os.open(path.parent, os.O_RDONLY)+ try:+ os.fsync(fd)+ finally:+ os.close(fd)++ def _delete_recovery_sentinel(self, tmpdir: Path) -> None:+ try:+ self._recovery_sentinel_path(tmpdir).unlink()+ if os.name != "nt":+ fd = os.open(tmpdir.parent, os.O_RDONLY)+ try:+ os.fsync(fd)+ finally:+ os.close(fd)+ except FileNotFoundError:+ pass+ except OSError as e:+ 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)+ except Exception as sentinel_error:+ self._logger.error(f"Failed to persist destination recovery sentinel in {dest_dir}: {sentinel_error}")+def _write_install_marker(self, job: ModelInstallJob, status: Optional[InstallStatus] = None) -> None:if job._install_tmpdir is None:return@@ -224,6 +267,8 @@ class ModelInstallService(ModelInstallServiceBase):source_str = str(source)candidates: list[tuple[str, Path]] = []for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ if self._has_recovery_sentinel(tmpdir):+ continuemarker = self._read_install_marker(tmpdir)if not marker:continue@@ -249,6 +294,9 @@ class ModelInstallService(ModelInstallServiceBase):active_sources = {str(j.source) for j in self._install_jobs if not j.in_terminal_state}active_sources.update(str(j.source) for j in self._download_cache.values() if not j.in_terminal_state)for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ if self._has_recovery_sentinel(tmpdir):+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continuemarker = self._read_install_marker(tmpdir)if not marker:continue@@ -498,6 +546,45 @@ class ModelInstallService(ModelInstallServiceBase):time.sleep(delay)delay *= 2 # Exponential backoff+ @staticmethod+ def _rename_noreplace(src: Path, dst: Path) -> None:+ """Atomically restore a path only if its destination is still absent."""+ if sys.platform.startswith("linux"):+ libc = ctypes.CDLL(None, use_errno=True)+ renameat2 = getattr(libc, "renameat2", None)+ if renameat2 is None:+ raise OSError("atomic no-replace rename is unavailable")+ renameat2.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]+ renameat2.restype = ctypes.c_int+ result = renameat2(-100, os.fsencode(src), -100, os.fsencode(dst), 1) # AT_FDCWD, RENAME_NOREPLACE+ if result != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error), str(dst))+ return+ if sys.platform == "darwin":+ libc = ctypes.CDLL(None, use_errno=True)+ renamex_np = getattr(libc, "renamex_np", None)+ if renamex_np is None:+ raise OSError("atomic no-replace rename is unavailable")+ renamex_np.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]+ renamex_np.restype = ctypes.c_int+ result = renamex_np(os.fsencode(src), os.fsencode(dst), 0x00000004) # RENAME_EXCL+ if result != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error), str(dst))+ return+ if os.name == "nt":+ # Windows rename fails when the destination already exists.+ os.rename(src, dst)+ return+ raise OSError("atomic no-replace rename is unavailable on this platform")++ @classmethod+ 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)+def install_path(self,model_path: Union[Path, str],@@ -544,6 +631,9 @@ class ModelInstallService(ModelInstallServiceBase):moved.append((item, item_dest))pending_dest = Noneexcept InstallRecoveryRequiredError:+ # Recovery destinations can share TMPDIR_PREFIX with remote staging dirs. Keep their artifacts out of+ # startup's dangling-install cleanup even when the configured model key uses that prefix.+ self._retain_recovery_destination(dest_dir)raiseexcept Exception as transfer_error:if not destination_created:@@ -560,13 +650,14 @@ class ModelInstallService(ModelInstallServiceBase):try:if moved_source.exists() or moved_source.is_symlink():raise FileExistsError(f"Refusing to overwrite recreated source {moved_source}")- self._move_with_retries(moved_dest, moved_source)+ self._restore_moved_path(moved_dest, moved_source)except Exception as rollback_error:rollback_errors.append(f"could not restore {moved_dest.resolve()} to {moved_source.resolve()}: {rollback_error}")if rollback_errors:details = "; ".join(rollback_errors)+ self._retain_recovery_destination(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. {details}"@@ -579,6 +670,7 @@ class ModelInstallService(ModelInstallServiceBase):raise OSError(f"unexpected destination artifacts remain: {leftovers}")dest_dir.rmdir()except Exception as cleanup_error:+ self._retain_recovery_destination(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "@@ -593,6 +685,7 @@ class ModelInstallService(ModelInstallServiceBase):raise OSError(f"unexpected destination artifacts remain: {leftovers}")dest_dir.rmdir()except Exception as cleanup_error:+ self._retain_recovery_destination(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "@@ -719,6 +812,8 @@ 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.")job.cancel()self._logger.warning(f"Cancelling {job.source}")if dj := job._multifile_job:@@ -1086,7 +1181,12 @@ class ModelInstallService(ModelInstallServiceBase):# gracefully handle _any_ error here.self._set_error(job, e)if job._recovery_required:- self._write_install_marker(job, status=InstallStatus.ERROR)+ try:+ self._write_install_marker(job, status=InstallStatus.ERROR)+ except Exception as marker_error:+ self._logger.error(+ f"Failed to persist install recovery marker in {job._install_tmpdir}: {marker_error}"+ )finally:# if this is an install of a remote file, then clean up the temporary directory@@ -1111,6 +1211,8 @@ class ModelInstallService(ModelInstallServiceBase):job.config_in.source_api_response = job.source_metadata.api_responseif job._install_tmpdir is not None:+ if not job.inplace:+ self._write_recovery_sentinel(job._install_tmpdir)self._delete_install_marker(job._install_tmpdir)if job.inplace:@@ -1121,8 +1223,19 @@ class ModelInstallService(ModelInstallServiceBase):except InstallRecoveryRequiredError:job._recovery_required = job._install_tmpdir is not Noneif job._recovery_required:- self._write_install_marker(job, status=job.status)+ try:+ self._write_install_marker(job, status=job.status)+ except Exception as marker_error:+ self._logger.error(+ f"Failed to persist install recovery marker in {job._install_tmpdir}: {marker_error}"+ )+ raise+ except Exception:+ if job._install_tmpdir is not None:+ self._delete_recovery_sentinel(job._install_tmpdir)raise+ if job._install_tmpdir is not None:+ self._delete_recovery_sentinel(job._install_tmpdir)job.config_out = self.record_store.get_model(key)self._signal_job_completed(job)@@ -1215,6 +1328,9 @@ class ModelInstallService(ModelInstallServiceBase):"""Remove leftover tmpdirs from aborted installs."""path = self._app_config.models_pathfor tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ if self._has_recovery_sentinel(tmpdir):+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continuemarker = self._read_install_marker(tmpdir)if marker is None:self._logger.info(f"Removing dangling temporary directory {tmpdir}")diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex 7db26922b9..2a35e92105 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -442,6 +442,112 @@ def test_convert_model_releases_the_lock_when_the_conversion_fails() -> None:assert exc_info.value.status_code == 424+def test_convert_model_retains_recovery_source_and_restores_model_name(monkeypatch: Any, tmp_path: Path) -> 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_install.model_install_common import InstallRecoveryRequiredError+ 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,+ )++ model_config = Main_Checkpoint_SD1_Config(+ key="model-key",+ path="/models/original.safetensors",+ name="Original Model",+ format=ModelFormat.Checkpoint,+ base=BaseModelType.StableDiffusion1,+ type=ModelType.Main,+ config_path="/configs/model.yaml",+ variant=ModelVariantType.Normal,+ hash="111222333444",+ file_size=8192,+ source="/models/original.safetensors",+ source_type=ModelSourceType.Path,+ prediction_type=SchedulerPredictionType.Epsilon,+ )++ class Store:+ def get_model(self, key: str) -> Main_Checkpoint_SD1_Config:+ assert key == model_config.key+ return model_config++ def update_model(self, key: str, changes: ModelRecordChanges) -> None:+ assert key == model_config.key+ if changes.name is not None:+ model_config.name = changes.name++ def save_pretrained(path: Path) -> None:+ path.mkdir()+ (path / "weights.safetensors").write_text("converted")++ def reject_recovery_source(path: Path, *, config: ModelRecordChanges) -> str:+ raise InstallRecoveryRequiredError(f"Install recovery required. Source: {path}; destination: /models/recovery")++ services = SimpleNamespace(+ model_manager=SimpleNamespace(+ store=Store(),+ load=SimpleNamespace(+ load_model=lambda *_args, **_kwargs: SimpleNamespace(+ model=SimpleNamespace(save_pretrained=save_pretrained)+ )+ ),+ install=SimpleNamespace(install_path=reject_recovery_source),+ ),+ configuration=SimpleNamespace(models_path=tmp_path),+ logger=MagicMock(),+ )+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))++ with pytest.raises(HTTPException) as exc_info:+ model_manager_router.convert_model(+ current_admin=SimpleNamespace(user_id="test-user"),+ key=model_config.key,+ )++ assert exc_info.value.status_code == 409+ assert "Source:" in exc_info.value.detail+ recovery_path = Path(exc_info.value.detail.rsplit("retained at ", 1)[1].rstrip("."))+ assert recovery_path.is_dir()+ assert (recovery_path / "original" / "weights.safetensors").read_text() == "converted"+ assert model_config.name == "Original Model"+++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++ class Installer:+ def get_job_by_id(self, job_id: int) -> object:+ assert job_id == 42+ return object()++ def cancel_job(self, _job: object) -> None:+ raise ValueError("Cannot cancel 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:+ model_manager_router.cancel_model_install_job(current_admin=None, id=42)++ assert exc_info.value.status_code == 409+ assert "requires recovery" in exc_info.value.detail++def test_delete_is_refused_while_the_same_model_is_being_converted() -> None:"""A delete landing mid-conversion must not pull the source out from under it.diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex 16b832b412..0b14c936cf 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -280,6 +280,42 @@ def test_directory_install_preserves_collision_during_rollback(assert preserved_item.is_dir() == first_item_is_dir+def test_directory_install_rollback_race_preserves_both_source_artifacts(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ items = list(diffusers_dir.iterdir())+ locked_item = items[-1]+ first_item = next(path for path in items[:-1] if path.is_file())+ original_bytes = first_item.read_bytes()+ real_move = shutil.move+ real_rename_noreplace = ModelInstallService._rename_noreplace++ def fail_later_move(src: Path, dst: Path):+ if src == locked_item:+ raise PermissionError("later source remains locked")+ return real_move(src, dst)++ def recreate_after_absence_check(src: Path, dst: Path) -> None:+ if dst == first_item:+ dst.write_bytes(b"new user bytes")+ real_rename_noreplace(src, dst)++ monkeypatch.setattr(model_install_default, "move", fail_later_move)+ monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(recreate_after_absence_check))++ with pytest.raises(model_install_default.InstallRecoveryRequiredError, match="recovery required"):+ mm2_installer.install_path(diffusers_dir)++ assert first_item.read_bytes() == b"new user bytes"+ recovery_dirs = [path for path in mm2_app_config.models_path.iterdir() if path.is_dir() and path.name != "tmp"]+ preserved = [path / first_item.name for path in recovery_dirs if (path / first_item.name).exists()]+ assert len(preserved) == 1+ assert preserved[0].read_bytes() == original_bytes++def test_directory_install_does_not_retry_partial_copy(mm2_installer: ModelInstallServiceBase,diffusers_dir: Path,@@ -338,40 +374,81 @@ def test_directory_install_retains_unowned_destination_artifact_after_rollback(def test_remote_install_recovery_survives_cleanup_and_restart(mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,mm2_app_config: InvokeAIAppConfig,mm2_download_queue,mm2_session,monkeypatch: pytest.MonkeyPatch,) -> None:assert isinstance(mm2_installer, ModelInstallService)+ existing_paths = set(mm2_app_config.models_path.iterdir())tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}recovery-{uuid.uuid4().hex}"tmpdir.mkdir()- downloaded_file = tmpdir / "model.bin"- downloaded_file.write_bytes(b"downloaded model")+ shutil.copytree(diffusers_dir, tmpdir, dirs_exist_ok=True)+ failure_file = tmpdir / "zz_partial_failure.txt"+ failure_file.write_bytes(b"source bytes")+ source_files = {path.name: path.read_bytes() for path in tmpdir.iterdir() if path.is_file()}source = URLModelSource(url=Url("https://example.com/model.bin"))job = ModelInstallJob(id=991,source=source,- config_in=ModelRecordChanges(),+ config_in=ModelRecordChanges(key="tmpinstall_recovery"),local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)job._install_tmpdir = tmpdirmm2_installer._write_install_marker(job, status=InstallStatus.DOWNLOADS_DONE)- def fail_install(*_args, **_kwargs):- raise model_install_default.InstallRecoveryRequiredError(- f"Install recovery required. Source: {tmpdir.resolve()}; destination: {mm2_app_config.models_path.resolve()}"- )+ def fail_after_partial_transfer(src: Path, dst: Path):+ if src == failure_file:+ dst.write_bytes(b"unrecognized partial destination bytes")+ raise PermissionError("simulated transfer failure after partial destination creation")+ return shutil.move(src, dst)- monkeypatch.setattr(mm2_installer, "install_path", fail_install)+ real_iterdir = Path.iterdir++ def sorted_source_files(path: Path):+ entries = list(real_iterdir(path))+ return iter(sorted(entries, key=lambda entry: entry.name)) if path == tmpdir else iter(entries)++ monkeypatch.setattr(Path, "iterdir", sorted_source_files)+ monkeypatch.setattr(model_install_default, "move", fail_after_partial_transfer)+ real_write_install_marker = mm2_installer._write_install_marker++ def fail_recovery_marker(job_arg, *args, **kwargs):+ if job_arg._recovery_required:+ raise OSError("simulated marker write failure")+ return real_write_install_marker(job_arg, *args, **kwargs)++ real_delete_install_marker = mm2_installer._delete_install_marker++ def assert_recovery_before_marker_delete(tmpdir_arg: Path) -> None:+ assert mm2_installer._has_recovery_sentinel(tmpdir_arg)+ real_delete_install_marker(tmpdir_arg)++ monkeypatch.setattr(mm2_installer, "_write_install_marker", fail_recovery_marker)+ monkeypatch.setattr(mm2_installer, "_delete_install_marker", assert_recovery_before_marker_delete)mm2_installer._put_in_queue(job)mm2_installer.wait_for_job(job, timeout=10)- marker = mm2_installer._read_install_marker(tmpdir)assert job.errored- assert marker is not None and marker.get("recovery_required") is True- assert downloaded_file.read_bytes() == b"downloaded model"+ 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 {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files+ recovery_files = [+ path+ for path in set(mm2_app_config.models_path.iterdir()) - existing_paths+ if path != tmpdir and path.is_dir() and (path / failure_file.name).exists()+ ]+ assert len(recovery_files) == 1+ recovery_dir = recovery_files[0]+ assert recovery_dir.name == "tmpinstall_recovery"+ assert mm2_installer._has_recovery_sentinel(recovery_dir)+ assert (recovery_dir / failure_file.name).read_bytes() == b"unrecognized partial destination bytes"++ dangling_tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}dangling-{uuid.uuid4().hex}"+ dangling_tmpdir.mkdir()+ (dangling_tmpdir / "ordinary.tmp").write_bytes(b"discard me")restarted_installer = ModelInstallService(app_config=mm2_app_config,@@ -383,11 +460,42 @@ def test_remote_install_recovery_survives_cleanup_and_restart(restarted_installer._restore_incomplete_installs()assert tmpdir.exists()- assert downloaded_file.read_bytes() == b"downloaded model"+ assert {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files+ assert recovery_dir.exists()+ assert (recovery_dir / failure_file.name).read_bytes() == b"unrecognized partial destination bytes"+ assert dangling_tmpdir.exists() is Falseassert restarted_installer.list_jobs() == []shutil.rmtree(tmpdir)+def test_cancel_recovery_required_install_preserves_recovery_data(+ 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=992,+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=downloaded_file,+ status=InstallStatus.ERROR,+ )+ job._install_tmpdir = tmpdir+ job._recovery_required = True+ mm2_installer._write_recovery_sentinel(tmpdir)++ with pytest.raises(ValueError, 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)++def test_install_registration_failure_preserves_complete_recoverable_files(mm2_installer: ModelInstallServiceBase,diffusers_dir: Path,