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-install): keep restored downloads restartable (#9521)

primorLeea51e26fe24a1
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 72ecf76be8..9f67f85ede 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -317,6 +317,9 @@ class ModelInstallService(ModelInstallServiceBase):
def _resume_remote_download(self, job: ModelInstallJob) -> None:
job.status = InstallStatus.WAITING
+ # Sources whose partial file has vanished. _enqueue_remote_download replaces job.download_parts
+ # with fresh parts, so the flag must be carried onto them or the resume response loses it.
+ restarted_from_scratch: set[str] = set()
if job.download_parts:
for part in job.download_parts:
if part.complete or part.bytes <= 0:
@@ -328,6 +331,7 @@ class ModelInstallService(ModelInstallServiceBase):
part.bytes = 0
part.resume_from_scratch = True
part.resume_message = "Partial file missing. Restarted download from the beginning."
+ restarted_from_scratch.add(str(part.source))
job.bytes = sum(p.bytes for p in job.download_parts)
remote_files, metadata = self._remote_files_from_source(job.source)
subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []
@@ -340,6 +344,7 @@ class ModelInstallService(ModelInstallServiceBase):
subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,
subfolders=subfolders if len(subfolders) > 1 else None,
resume_metadata=job._resume_metadata,
+ restarted_from_scratch=restarted_from_scratch,
)
@property
@@ -1340,6 +1345,7 @@ class ModelInstallService(ModelInstallServiceBase):
subfolders: Optional[List[Path]] = None,
resume_metadata: Optional[dict] = None,
clear_partials: bool = False,
+ restarted_from_scratch: Optional[set[str]] = None,
) -> ModelInstallJob:
job.source_metadata = metadata
job.local_path = destdir
@@ -1382,9 +1388,15 @@ class ModelInstallService(ModelInstallServiceBase):
part.final_url = meta.get("final_url") or part.final_url
if meta.get("download_path"):
part.download_path = Path(meta.get("download_path"))
+ if restarted_from_scratch:
+ for part in multifile_job.download_parts:
+ if str(part.source) in restarted_from_scratch:
+ part.resume_from_scratch = True
+ part.resume_message = "Partial file missing. Restarted download from the beginning."
with self._lock:
self._download_cache[multifile_job.id] = job
job._multifile_job = multifile_job
+ job.download_parts = multifile_job.download_parts
self._write_install_marker(job, status=InstallStatus.WAITING)
files_string = "file" if len(remote_files) == 1 else "files"
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 34417ff09b..03a34fcfeb 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -12,11 +12,13 @@ import uuid
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Dict
+from unittest.mock import MagicMock
import pytest
from pydantic_core import Url
from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.download import DownloadJob, MultiFileDownloadJob
from invokeai.app.services.events.events_base import EventServiceBase
from invokeai.app.services.events.events_common import (
ModelInstallCompleteEvent,
@@ -45,6 +47,7 @@ from invokeai.app.services.model_install.model_install_default import (
)
from invokeai.app.services.model_records import ModelRecordChanges, UnknownModelException
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
+from invokeai.backend.model_manager.metadata import RemoteModelFile
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
ModelFormat,
@@ -1001,6 +1004,106 @@ def test_restore_paused_hf_install_preserves_access_token(
shutil.rmtree(tmpdir, ignore_errors=True)
+def test_restart_failed_uses_parts_created_before_download_started(
+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ part = DownloadJob(
+ source=source.url,
+ dest=tmp_path / "model.safetensors",
+ canonical_url="https://cdn.example.com/model.safetensors",
+ etag='"model-etag"',
+ expected_total_bytes=8,
+ )
+ download_job = MultiFileDownloadJob(id=123, dest=tmp_path, download_parts={part})
+ job = ModelInstallJob(id=99999, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)
+
+ monkeypatch.setattr(mm2_installer, "_multifile_download", lambda **_: download_job)
+ submit_multifile_download = MagicMock()
+ monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", submit_multifile_download)
+ mm2_installer._enqueue_remote_download(
+ job=job,
+ source=source,
+ remote_files=[remote_file],
+ metadata=None,
+ destdir=tmp_path,
+ )
+
+ part.resume_required = True
+ mm2_installer._download_cancelled_callback(download_job)
+
+ assert job.status == InstallStatus.PAUSED
+ assert job.model_dump(mode="json")["download_parts"][0]["resume_required"] is True
+ marker = mm2_installer._read_install_marker(tmp_path)
+ assert marker is not None
+ assert marker["files"][0]["etag"] == '"model-etag"'
+ assert marker["files"][0]["resume_required"] is True
+ submit_multifile_download.assert_called_once_with(download_job)
+
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", lambda _: ([remote_file], None))
+ enqueue_remote_download = MagicMock()
+ monkeypatch.setattr(mm2_installer, "_enqueue_remote_download", enqueue_remote_download)
+ mm2_installer.restart_failed(job)
+
+ assert job.status == InstallStatus.WAITING
+ enqueue_remote_download.assert_called_once()
+ assert enqueue_remote_download.call_args.kwargs["clear_partials"] is True
+
+
+def test_resume_reports_restart_from_scratch_on_fresh_parts(
+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Resuming replaces download_parts; a vanished partial file must still be reported on the new parts."""
+ assert isinstance(mm2_installer, ModelInstallService)
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ old_part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors")
+ old_part.bytes = 4
+ old_part.download_path = tmp_path / "model.safetensors" # no .downloading file on disk
+ job = ModelInstallJob(id=4242, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)
+ job._install_tmpdir = tmp_path
+ job.download_parts = {old_part}
+ job.status = InstallStatus.PAUSED
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", lambda _: ([remote_file], None))
+ submit_multifile_download = MagicMock()
+ monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", submit_multifile_download)
+
+ mm2_installer.resume_job(job)
+
+ submit_multifile_download.assert_called_once()
+ assert old_part not in job.download_parts
+ parts = job.model_dump(mode="json")["download_parts"]
+ assert len(parts) == 1
+ assert parts[0]["resume_from_scratch"] is True
+ assert "Partial file missing" in parts[0]["resume_message"]
+
+
+def test_resume_does_not_report_restart_from_scratch_when_partial_exists(
+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ old_part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors")
+ old_part.bytes = 4
+ old_part.download_path = tmp_path / "model.safetensors"
+ (tmp_path / "model.safetensors.downloading").write_bytes(b"1234")
+ job = ModelInstallJob(id=4243, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)
+ job._install_tmpdir = tmp_path
+ job.download_parts = {old_part}
+ job.status = InstallStatus.PAUSED
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", lambda _: ([remote_file], None))
+ monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", MagicMock())
+
+ mm2_installer.resume_job(job)
+
+ parts = job.model_dump(mode="json")["download_parts"]
+ assert len(parts) == 1
+ assert parts[0]["resume_from_scratch"] is False
+
+
def test_404_download(mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig) -> None:
source = URLModelSource(url=Url("https://test.com/missing_model.safetensors"))
job = mm2_installer.import_model(source)