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 restored downloads on shutdown
JPPhoto910f10bec1d1
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 3f4ca35843..39a26bd25b 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -1338,7 +1338,7 @@ def pause_model_install_job(raise HTTPException(status_code=415, detail=str(e))try:installer.pause_job(job)- except InstallDownloadConflictError as e:+ except (InstallCancellationConflictError, InstallDownloadConflictError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1364,7 +1364,7 @@ def resume_model_install_job(raise HTTPException(status_code=415, detail=str(e))try:installer.resume_job(job)- except InstallDownloadConflictError as e:+ except (InstallCancellationConflictError, InstallDownloadConflictError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1390,7 +1390,7 @@ def restart_failed_model_install_job(raise HTTPException(status_code=415, detail=str(e))try:installer.restart_failed(job)- except (InstallDownloadConflictError, InstallRecoveryRequiredError) as e:+ except (InstallCancellationConflictError, InstallDownloadConflictError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1418,7 +1418,7 @@ def restart_model_install_file(raise HTTPException(status_code=415, detail=str(e))try:installer.restart_file(job, str(file_source))- except (InstallDownloadConflictError, InstallRecoveryRequiredError) as e:+ except (InstallCancellationConflictError, InstallDownloadConflictError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn jobdiff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.pyindex 2f97014f30..7458855d8e 100644--- a/invokeai/app/services/download/download_default.py+++ b/invokeai/app/services/download/download_default.py@@ -898,6 +898,10 @@ class DownloadQueueService(DownloadQueueServiceBase):for part in mf_job.download_parts:if part is download_job or part.in_terminal_state:continue+ if part.paused:+ # A pause can be requested while the worker still reports RUNNING. Preserve that user's+ # partial file; its worker will finish the pause callback and remove its own parent link.+ continuepart.cancel()self._cleanup_cancelled_job(part)part.status = DownloadJobStatus.CANCELLEDdiff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex fbd7d8f618..2deaf58ea2 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -156,6 +156,7 @@ class ModelInstallService(ModelInstallServiceBase):# _restore_incomplete_installs_async() finishes so an import racing start() cannot pass the barrier early.self._restore_completed_event = threading.Event()self._startup_error: Optional[BaseException] = None+ self._restore_thread: Optional[threading.Thread] = Noneself._download_queue = download_queueself._download_cache: Dict[int, ModelInstallJob] = {}self._remote_download_operations: set[int] = set()@@ -300,7 +301,9 @@ class ModelInstallService(ModelInstallServiceBase):pid = int(pid_text)create_time = float(create_time_text)process = psutil.Process(pid)- if process.status() == psutil.STATUS_ZOMBIE or process.create_time() != create_time:+ # On Linux, psutil derives process start time from boot time plus kernel ticks. A small boot-time+ # adjustment can change that value for a live process, so exact float equality can remove its claim.+ if process.status() == psutil.STATUS_ZOMBIE or abs(process.create_time() - create_time) > 1.0:claim_path.unlink(missing_ok=True)except (psutil.NoSuchProcess, psutil.ZombieProcess):claim_path.unlink(missing_ok=True)@@ -410,6 +413,8 @@ 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._stop_event.is_set():+ returnif has_active_install_sentinel(tmpdir):self._logger.debug(f"Skipping active install directory {tmpdir}")continue@@ -484,6 +489,10 @@ class ModelInstallService(ModelInstallServiceBase):try:self._resume_remote_download(job)except Exception as e:+ if self._stop_event.is_set():+ self._logger.info(f"Leaving interrupted install in {job._install_tmpdir} for next startup")+ job.status = InstallStatus.PAUSED+ returnself._set_error(job, e)if job._install_tmpdir is not None and not job._install_tmpdir_claim_conflict:if job._install_tmpdir_active_sentinel_created:@@ -505,7 +514,8 @@ class ModelInstallService(ModelInstallServiceBase):finally:self._restore_completed_event.set()- threading.Thread(target=_run, daemon=True).start()+ self._restore_thread = threading.Thread(target=_run, daemon=True)+ self._restore_thread.start()def _wait_for_restore_complete(self, timeout: Optional[float] = None) -> bool:deadline = time.monotonic() + timeout if timeout is not None else None@@ -659,6 +669,9 @@ class ModelInstallService(ModelInstallServiceBase):# Let the worker finish (or leave a dequeued job untouched) before cleaning pending jobs. Otherwise# shutdown can mistake a job between Queue.get() and _active_install_job assignment for pending work.self._install_thread.join()+ restore_thread = self._restore_thread+ if restore_thread is not None and restore_thread is not threading.current_thread():+ restore_thread.join()finally:try:with self._remote_download_condition:@@ -691,14 +704,23 @@ class ModelInstallService(ModelInstallServiceBase):multifile_job = job._multifile_jobdownload_callback_pending = any(cached_job is job for cached_job in self._download_cache.values())downloads_complete = multifile_job is not None and multifile_job.complete- if multifile_job is None:+ preserve_download_status = (+ job.status+ if multifile_job is None and job.status in {InstallStatus.PAUSED, InstallStatus.DOWNLOADS_DONE}+ else None+ )+ if preserve_download_status is None and multifile_job is None:job.cancel()- elif downloads_complete:+ elif preserve_download_status is None and downloads_complete:job.status = InstallStatus.DOWNLOADS_DONE- else:+ elif preserve_download_status is None:job.status = InstallStatus.PAUSED- if multifile_job is not None and downloads_complete:+ if preserve_download_status is not None:+ self._write_install_marker(job, status=preserve_download_status)+ if not download_callback_pending:+ self._release_install_tmpdir_claim(job)+ elif multifile_job is not None and downloads_complete:self._write_install_marker(job, status=InstallStatus.DOWNLOADS_DONE)if not download_callback_pending:self._release_install_tmpdir_claim(job)@@ -728,7 +750,11 @@ class ModelInstallService(ModelInstallServiceBase):with self._lock:queued = self._queue_install_job_locked(job)if not queued:- self.cancel_job(job)+ if self._stop_event.is_set():+ # A completed download that races shutdown remains resumable on the next start.+ job.status = InstallStatus.DOWNLOADS_DONE+ else:+ self.cancel_job(job)def _queue_install_job_locked(self, job: ModelInstallJob) -> bool:"""Queue an install while holding _lock, preserving shutdown and wait_for_installs ordering."""diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex b0b790607b..0de53e29d5 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -627,6 +627,46 @@ def test_remote_download_replacement_returns_conflict(monkeypatch: Any, operatioassert "previous download" in exc_info.value.detail[email protected]("operation", ["resume", "restart_failed", "restart_file"])+def test_install_path_claim_conflict_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 InstallCancellationConflictError++ class Installer:+ def get_job_by_id(self, job_id: int) -> object:+ assert job_id == 42+ return object()++ def resume_job(self, _job: object) -> None:+ raise InstallCancellationConflictError("Another operation owns the install path")++ def restart_failed(self, _job: object) -> None:+ raise InstallCancellationConflictError("Another operation owns the install path")++ def restart_file(self, _job: object, _source: str) -> None:+ raise InstallCancellationConflictError("Another operation owns the install path")++ 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 == "resume":+ model_manager_router.resume_model_install_job(current_admin=None, id=42)+ elif 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 "owns the install path" in exc_info.value.detail++@pytest.mark.parametrize("install_fails", [False, True])def test_conversion_cleans_scratch_after_success_and_ordinary_failure(monkeypatch: Any, tmp_path: Path, install_fails: booldiff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.pyindex 2a71453769..5e18b44ccf 100644--- a/tests/app/services/download/test_download_queue.py+++ b/tests/app/services/download/test_download_queue.py@@ -335,6 +335,40 @@ def test_multifile_download(tmp_path: Path, mm2_session: Session) -> None:queue.stop()+def test_multifile_error_preserves_sibling_part_paused_during_callback(tmp_path: Path, mm2_session: Session) -> None:+ queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True)+ failed_part = DownloadJob(+ id=10,+ source=AnyHttpUrl("https://example.com/failed.safetensors"),+ dest=tmp_path / "failed.safetensors",+ status=DownloadJobStatus.ERROR,+ )+ sibling_path = tmp_path / "paused.safetensors"+ partial_path = sibling_path.with_name(f"{sibling_path.name}.downloading")+ partial_path.write_bytes(b"paused partial")+ paused_sibling = DownloadJob(+ id=11,+ source=AnyHttpUrl("https://example.com/paused.safetensors"),+ dest=sibling_path,+ download_path=sibling_path,+ status=DownloadJobStatus.RUNNING,+ )+ paused_sibling.pause()+ parent = MultiFileDownloadJob(+ id=12,+ dest=tmp_path,+ status=DownloadJobStatus.RUNNING,+ download_parts={failed_part, paused_sibling},+ )+ queue._download_part2parent[failed_part.id] = parent+ queue._download_part2parent[paused_sibling.id] = parent++ queue._mfd_error(failed_part, RuntimeError("sibling failed"))++ assert paused_sibling.paused+ assert partial_path.read_bytes() == b"paused partial"++@pytest.mark.timeout(timeout=10, method="thread")def test_multifile_download_error(tmp_path: Path, mm2_session: Session) -> None:fetcher = HuggingFaceMetadataFetch(mm2_session)diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex f39cff59b8..57f9ca6fba 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -341,6 +341,42 @@ def test_start_removes_stale_but_preserves_live_install_claims(delete_active_install_sentinel(live_root)+def test_start_preserves_claim_for_small_process_start_time_drift(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ claimed_root = mm2_app_config.models_path / "claim-time-drift"+ claimed_root.mkdir()+ claim = active_install_sentinel_path(claimed_root)+ claim.write_text("12345 100.0\n", encoding="ascii")+ observed_start_time = [100.75]++ class Process:+ def __init__(self, _pid: int) -> None:+ pass++ def status(self) -> str:+ return model_install_default.psutil.STATUS_RUNNING++ def create_time(self) -> float:+ return observed_start_time[0]++ monkeypatch.setattr(model_install_default.psutil, "Process", Process)++ mm2_installer._remove_stale_install_source_claims()++ assert claim.exists()++ observed_start_time[0] = 102.0+ mm2_installer._remove_stale_install_source_claims()++ assert not claim.exists()++def test_startup_cleanup_preserves_claimed_remote_staging(mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig) -> None:@@ -884,6 +920,134 @@ def _queue_downloaded_job(return job+def _write_remote_install_marker(+ installer: ModelInstallService,+ tmpdir: Path,+ job_id: int,+ status: InstallStatus,+) -> Path:+ tmpdir.mkdir(parents=True, exist_ok=True)+ download_path = tmpdir / (+ "weights.safetensors" if status == InstallStatus.DOWNLOADS_DONE else "weights.safetensors.downloading"+ )+ download_path.write_bytes(b"downloaded model" if status == InstallStatus.DOWNLOADS_DONE else b"partial download")+ job = ModelInstallJob(+ id=job_id,+ source=URLModelSource(url=Url("https://example.com/weights.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=status,+ )+ job._install_tmpdir = tmpdir+ installer._write_install_marker(job, status=status)+ return download_path+++def test_queue_rejection_during_shutdown_preserves_completed_download(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}queue-stop-{uuid.uuid4().hex}"+ partial_path = _write_remote_install_marker(mm2_installer, tmpdir, 9905, InstallStatus.DOWNLOADS_DONE)+ job = ModelInstallJob(+ id=9905,+ source=URLModelSource(url=Url("https://example.com/weights.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ job._install_tmpdir = tmpdir+ mm2_installer._install_jobs.append(job)+ mm2_installer._stop_event.set()++ mm2_installer._put_in_queue(job)++ assert job.status == InstallStatus.DOWNLOADS_DONE+ assert partial_path.read_bytes() == b"downloaded model"+ assert mm2_installer._read_install_marker(tmpdir) is not None+++def test_restore_leaves_unvisited_markers_untouched_when_stopping(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ first_tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-stop-first-{uuid.uuid4().hex}"+ second_tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-stop-second-{uuid.uuid4().hex}"+ first_partial = _write_remote_install_marker(mm2_installer, first_tmpdir, 9901, InstallStatus.DOWNLOADING)+ second_partial = _write_remote_install_marker(mm2_installer, second_tmpdir, 9902, InstallStatus.DOWNLOADING)+ mm2_installer._stop_event.set()++ mm2_installer._restore_incomplete_installs()++ assert first_partial.read_bytes() == b"partial download"+ assert second_partial.read_bytes() == b"partial download"+ assert mm2_installer._read_install_marker(first_tmpdir) is not None+ assert mm2_installer._read_install_marker(second_tmpdir) is not None+++def test_stop_during_startup_restore_preserves_the_current_download(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-stop-active-{uuid.uuid4().hex}"+ partial_path = _write_remote_install_marker(mm2_installer, tmpdir, 9903, InstallStatus.DOWNLOADING)+ restore_started = threading.Event()+ resume_remote_download = mm2_installer._resume_remote_download++ def wait_until_stopping(job: ModelInstallJob, *, operation_reserved: bool = False) -> None:+ restore_started.set()+ assert mm2_installer._stop_event.wait(timeout=5)+ resume_remote_download(job, operation_reserved=operation_reserved)++ monkeypatch.setattr(mm2_installer, "_resume_remote_download", wait_until_stopping)+ mm2_installer._restore_incomplete_installs_async()+ assert restore_started.wait(timeout=5)++ mm2_installer.stop()++ marker = mm2_installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == InstallStatus.PAUSED.value+ assert partial_path.read_bytes() == b"partial download"+ assert not active_install_sentinel_path(tmpdir).exists()+ assert mm2_installer._restore_completed_event.is_set()++[email protected]("status", [InstallStatus.PAUSED, InstallStatus.DOWNLOADS_DONE])+def test_stop_preserves_restored_downloads_without_a_multifile_job(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+ status: InstallStatus,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-stop-{status.value}-{uuid.uuid4().hex}"+ partial_path = _write_remote_install_marker(mm2_installer, tmpdir, 9904, status)+ queued_jobs: list[ModelInstallJob] = []+ monkeypatch.setattr(mm2_installer, "_put_in_queue", queued_jobs.append)++ mm2_installer._restore_incomplete_installs()+ jobs = mm2_installer.list_jobs()+ assert len(jobs) == 1+ assert jobs[0].status == status+ if status == InstallStatus.DOWNLOADS_DONE:+ assert queued_jobs == jobs++ mm2_installer.stop()++ marker = mm2_installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == status.value+ expected_payload = b"downloaded model" if status == InstallStatus.DOWNLOADS_DONE else b"partial download"+ assert partial_path.read_bytes() == expected_payload+ assert not active_install_sentinel_path(tmpdir).exists()++def test_service_stop_waits_for_active_install_without_cancelling_it(mm2_installer: ModelInstallServiceBase,mm2_app_config: InvokeAIAppConfig,@@ -946,7 +1110,7 @@ def test_service_stop_waits_for_active_install_without_cancelling_it(assert not tmpdir.exists()-def test_service_stop_does_not_delete_a_job_between_dequeue_and_worker_activation(+def test_service_stop_preserves_a_job_between_dequeue_and_worker_activation(mm2_installer: ModelInstallServiceBase,mm2_app_config: InvokeAIAppConfig,embedding_file: Path,@@ -989,8 +1153,12 @@ def test_service_stop_does_not_delete_a_job_between_dequeue_and_worker_activatioassert not stop_thread.is_alive()assert not stop_errorsassert stop_finished.is_set()- assert job.cancelled- assert not tmpdir.exists()+ assert job.downloads_done+ assert tmpdir.exists()+ assert (tmpdir / embedding_file.name).exists()+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == InstallStatus.DOWNLOADS_DONE.valuedef test_cancel_during_install_preflight_waits_for_probe_then_cleans_safely(