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 files after installation failures
JPPhoto0f066ee08316
diff --git a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdxindex f1d0e61493..b3eb4d65f0 100644--- a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx@@ -128,6 +128,21 @@ you type in a file path, the button will change to **Scan**. Pressingit will scan the indicated folder and list the installablemodels. Click the model(s) you wish to install.+### Recovering a failed installation++InvokeAI retries temporary file permission errors during installation. If moving+a model fails, it attempts to restore files to their source folder.++If the error reports that installation recovery is required, keep both the+source and destination folders named in the error. Some files may have moved+while others remain at the source. Restore a complete model folder without+overwriting files you need, then use **Scan** to register it. Downloaded files+retained for recovery are not automatically resumed or removed on restart.++If all files moved successfully but registering the model failed, the complete+model remains in the destination folder. Resolve the reported registration+error, then use **Scan** on that folder.+## Editing a ModelOnce a model is installed, it will appear in the left-hand panel. Thediff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex f223c4698c..a503d5806b 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -202,6 +202,7 @@ class ModelInstallJob(BaseModel):_multifile_job: Optional[MultiFileDownloadJob] = PrivateAttr(default=None)_exception: Optional[Exception] = PrivateAttr(default=None)_resume_metadata: Optional[dict] = PrivateAttr(default=None)+ _recovery_required: bool = PrivateAttr(default=False)def set_error(self, e: Exception) -> None:"""Record the error and traceback from an exception."""diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 7f9c917797..4022f60033 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -85,6 +85,10 @@ 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."""++# 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# created; the combined name is only a label, so it is shortened past this point with a count.@@ -186,6 +190,8 @@ class ModelInstallService(ModelInstallServiceBase):"updated_at": get_iso_timestamp(),"files": files,}+ if job._recovery_required:+ marker["recovery_required"] = Truepath = self._marker_path(job._install_tmpdir)path.parent.mkdir(parents=True, exist_ok=True)with open(path, "wt", encoding="utf-8") as f:@@ -224,6 +230,8 @@ class ModelInstallService(ModelInstallServiceBase):if marker.get("source") != source_str:continuestatus = marker.get("status")+ if marker.get("recovery_required") is True:+ continueif status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:continuecandidates.append((marker.get("updated_at", ""), tmpdir))@@ -245,6 +253,9 @@ class ModelInstallService(ModelInstallServiceBase):if not marker:continuestatus = marker.get("status")+ if marker.get("recovery_required") is True:+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continueif status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:continue@@ -477,6 +488,10 @@ class ModelInstallService(ModelInstallServiceBase):move(src, dst)returnexcept PermissionError:+ # shutil.move can leave a partial destination after a cross-filesystem copy. Its contents+ # are unknown, so never retry or remove it.+ if dst.exists() or dst.is_symlink():+ raisegc.collect()if tries_left == 1:raise@@ -497,23 +512,93 @@ class ModelInstallService(ModelInstallServiceBase):if not is_plain_filename(info.key):raise ValueError(f"Invalid model key {info.key!r}: it must be a plain filename")dest_dir = self.app_config.models_path / info.key+ moved: list[tuple[Path, Path]] = []+ source_is_directory = model_path.is_dir()+ destination_created = False+ pending_dest: Optional[Path] = Nonetry:if dest_dir.exists():- raise FileExistsError(+ raise DuplicateModelException(f"Cannot install model {model_path.name} to {dest_dir}: destination already exists")dest_dir.mkdir(parents=True)+ destination_created = Truedest_path = dest_dir / model_path.name if model_path.is_file() else dest_dirif model_path.is_file():- self._move_with_retries(model_path, dest_path) # Windows workaround TODO: fix root cause+ try:+ self._move_with_retries(model_path, dest_path)+ except Exception as move_error:+ if dest_path.exists() or dest_path.is_symlink():+ raise InstallRecoveryRequiredError(+ f"Install recovery required after {move_error}. Source: {model_path.resolve()}; "+ f"destination: {dest_dir.resolve()}. Unrecognized destination artifact: "+ f"{dest_path.resolve()}"+ ) from move_error+ raiseelif model_path.is_dir():# Move the contents of the directory, not the directory itselffor item in model_path.iterdir():- move(item, dest_dir / item.name)- except FileExistsError as e:- raise DuplicateModelException(- f"A model named {model_path.name} is already installed at {dest_dir.as_posix()}"- ) from e+ item_dest = dest_dir / item.name+ pending_dest = item_dest+ self._move_with_retries(item, item_dest)+ moved.append((item, item_dest))+ pending_dest = None+ except InstallRecoveryRequiredError:+ raise+ except Exception as transfer_error:+ if not destination_created:+ if isinstance(transfer_error, FileExistsError):+ raise DuplicateModelException(+ f"A model named {model_path.name} is already installed at {dest_dir.as_posix()}"+ ) from transfer_error+ raise+ if source_is_directory:+ rollback_errors: list[str] = []+ if pending_dest is not None and (pending_dest.exists() or pending_dest.is_symlink()):+ rollback_errors.append(f"unrecognized destination artifact: {pending_dest.resolve()}")+ for moved_source, moved_dest in reversed(moved):+ 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)+ 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)+ raise InstallRecoveryRequiredError(+ f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "+ f"destination: {dest_dir.resolve()}. {details}"+ ) from transfer_error+ moved.clear()+ try:+ remaining = list(dest_dir.iterdir())+ if remaining:+ leftovers = ", ".join(str(path.resolve()) for path in remaining)+ raise OSError(f"unexpected destination artifacts remain: {leftovers}")+ dest_dir.rmdir()+ except Exception as cleanup_error:+ raise InstallRecoveryRequiredError(+ f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "+ f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "+ f"{cleanup_error}"+ ) from transfer_error+ raise+ if dest_dir.exists():+ try:+ remaining = list(dest_dir.iterdir())+ if remaining:+ leftovers = ", ".join(str(path.resolve()) for path in remaining)+ raise OSError(f"unexpected destination artifacts remain: {leftovers}")+ dest_dir.rmdir()+ except Exception as cleanup_error:+ raise InstallRecoveryRequiredError(+ f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "+ f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "+ f"{cleanup_error}"+ ) from transfer_error+ raisereturn self._register(dest_path,@@ -1000,10 +1085,12 @@ class ModelInstallService(ModelInstallServiceBase):# Expected errors include InvalidModelConfigException, DuplicateModelException, OSError, but we must# gracefully handle _any_ error here.self._set_error(job, e)+ if job._recovery_required:+ self._write_install_marker(job, status=InstallStatus.ERROR)finally:# if this is an install of a remote file, then clean up the temporary directory- if job._install_tmpdir is not None:+ if job._install_tmpdir is not None and not job._recovery_required:self._safe_rmtree(job._install_tmpdir, self._logger)self._install_completed_event.set()self._install_queue.task_done()@@ -1029,7 +1116,13 @@ class ModelInstallService(ModelInstallServiceBase):if job.inplace:key = self.register_path(job.local_path, job.config_in)else:- key = self.install_path(job.local_path, job.config_in)+ try:+ key = self.install_path(job.local_path, job.config_in)+ except InstallRecoveryRequiredError:+ job._recovery_required = job._install_tmpdir is not None+ if job._recovery_required:+ self._write_install_marker(job, status=job.status)+ raisejob.config_out = self.record_store.get_model(key)self._signal_job_completed(job)@@ -1128,6 +1221,9 @@ class ModelInstallService(ModelInstallServiceBase):self._safe_rmtree(tmpdir, self._logger)continuestatus = marker.get("status")+ if marker.get("recovery_required") is True:+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continueif status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:self._logger.info(f"Removing completed/errored temporary directory {tmpdir}")self._safe_rmtree(tmpdir, self._logger)diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex ba0d5f802e..16b832b412 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -226,6 +226,168 @@ def test_directory_install_late_move_failure_restores_source_files(assert mm2_installer.record_store.all_models() == []+def test_directory_install_preserves_collision_during_rollback(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ existing_paths = set(mm2_app_config.models_path.iterdir())+ first_item, locked_item, *_ = list(diffusers_dir.iterdir())+ first_item_is_dir = first_item.is_dir()+ real_move = shutil.move+ moved_first_item = False++ def move_with_recreated_source(src: Path, dst: Path):+ nonlocal moved_first_item+ if src == locked_item:+ recreated = diffusers_dir / first_item.name+ if first_item_is_dir:+ recreated.mkdir()+ (recreated / "new-user-file").write_text("new user file")+ else:+ recreated.write_text("new user file")+ raise PermissionError("later source remains locked")+ if src == first_item:+ if dst.exists():+ raise FileExistsError(dst)+ result = real_move(src, dst)+ moved_first_item = True+ return result+ if dst == first_item and dst.exists():+ raise FileExistsError(dst)+ return real_move(src, dst)++ monkeypatch.setattr(model_install_default, "move", move_with_recreated_source)++ with pytest.raises(RuntimeError, match="recovery required") as exc_info:+ mm2_installer.install_path(diffusers_dir)++ assert moved_first_item+ assert "test-diffusers-main" in str(exc_info.value)+ recreated = diffusers_dir / first_item.name+ assert recreated.exists()+ if first_item_is_dir:+ assert (recreated / "new-user-file").read_text() == "new user file"+ 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+ assert len(recovery_paths) == 1+ recovery_dest = recovery_paths.pop()+ preserved_item = recovery_dest / first_item.name+ assert preserved_item.exists()+ assert preserved_item.is_dir() == first_item_is_dir+++def test_directory_install_does_not_retry_partial_copy(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ first_item = next(diffusers_dir.iterdir())+ calls = 0++ def partial_copy_then_fail(src: Path, dst: Path):+ nonlocal calls+ calls += 1+ if src == first_item:+ dst.mkdir(parents=True)+ (dst / "unknown-partial").write_text("partial")+ raise PermissionError("copy failed after destination creation")+ return shutil.move(src, dst)++ monkeypatch.setattr(model_install_default, "move", partial_copy_then_fail)++ with pytest.raises(RuntimeError, match="recovery required") as exc_info:+ mm2_installer.install_path(diffusers_dir)++ assert calls == 1+ assert first_item.exists()+ assert "recovery required" in str(exc_info.value)+++def test_directory_install_retains_unowned_destination_artifact_after_rollback(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ existing_paths = set(mm2_app_config.models_path.iterdir())+ _, locked_item, *_ = list(diffusers_dir.iterdir())++ def fail_after_unowned_destination_artifact(src: Path, dst: Path):+ if src == locked_item:+ (dst.parent / "unowned-artifact").write_text("created concurrently")+ raise PermissionError("later source remains locked")+ return shutil.move(src, dst)++ monkeypatch.setattr(model_install_default, "move", fail_after_unowned_destination_artifact)++ 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+ assert len(recovery_paths) == 1+ recovery_dest = recovery_paths.pop()+ 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)+ assert locked_item.exists()+++def test_remote_install_recovery_survives_cleanup_and_restart(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ mm2_download_queue,+ mm2_session,+ 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.bin"+ downloaded_file.write_bytes(b"downloaded model")+ source = URLModelSource(url=Url("https://example.com/model.bin"))+ job = ModelInstallJob(+ id=991,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ job._install_tmpdir = tmpdir+ mm2_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()}"+ )++ monkeypatch.setattr(mm2_installer, "install_path", fail_install)+ 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"++ restarted_installer = ModelInstallService(+ app_config=mm2_app_config,+ record_store=mm2_installer.record_store,+ download_queue=mm2_download_queue,+ session=mm2_session,+ )+ restarted_installer._remove_dangling_install_dirs()+ restarted_installer._restore_incomplete_installs()++ assert tmpdir.exists()+ assert downloaded_file.read_bytes() == b"downloaded model"+ assert restarted_installer.list_jobs() == []+ shutil.rmtree(tmpdir)++def test_install_registration_failure_preserves_complete_recoverable_files(mm2_installer: ModelInstallServiceBase,diffusers_dir: Path,