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): preserve retryable restores

JPPhoto3d174c368da1
diff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.py
index 7458855d8e..7fe1eceb9b 100644
--- a/invokeai/app/services/download/download_default.py
+++ b/invokeai/app/services/download/download_default.py
@@ -885,7 +885,9 @@ class DownloadQueueService(DownloadQueueServiceBase):
def _mfd_cancelled(self, download_job: DownloadJob) -> None:
with self._lock:
- mf_job = self._download_part2parent[download_job.id]
+ mf_job = self._download_part2parent.get(download_job.id)
+ if mf_job is None:
+ return
self._finalize_multifile_cancellation(mf_job, paused=download_job.paused)
def _mfd_error(self, download_job: DownloadJob, excp: Optional[Exception] = None) -> None:
@@ -896,11 +898,15 @@ class DownloadQueueService(DownloadQueueServiceBase):
if not mf_job.in_terminal_state:
self._mfd_pending.pop(mf_job.id, None)
for part in mf_job.download_parts:
- if part is download_job or part.in_terminal_state:
+ if part is download_job:
continue
- if part.paused:
+ if part.paused or part.status == DownloadJobStatus.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.
+ # partial file. A non-running part has no worker left to remove its parent link.
+ if part.status != DownloadJobStatus.RUNNING:
+ self._download_part2parent.pop(part.id, None)
+ continue
+ if part.in_terminal_state:
continue
part.cancel()
self._cleanup_cancelled_job(part)
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 2deaf58ea2..651ed29a9a 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -71,6 +71,7 @@ from invokeai.backend.model_manager.metadata import (
AnyModelRepoMetadata,
HuggingFaceMetadataFetch,
ModelMetadataFetchBase,
+ ModelMetadataUnavailableError,
ModelMetadataWithFiles,
RemoteModelFile,
)
@@ -341,6 +342,8 @@ class ModelInstallService(ModelInstallServiceBase):
"resume_message": part.resume_message,
}
)
+ elif job._resume_metadata:
+ files.extend(dict(metadata) for metadata in job._resume_metadata.values())
marker = {
"version": INSTALL_MARKER_VERSION,
"source": str(job.source),
@@ -488,6 +491,12 @@ class ModelInstallService(ModelInstallServiceBase):
else:
try:
self._resume_remote_download(job)
+ except ModelMetadataUnavailableError as e:
+ self._logger.warning(f"Could not resume install {source_str} because metadata is unavailable: {e}")
+ job.status = InstallStatus.PAUSED
+ self._write_install_marker(job, status=InstallStatus.PAUSED)
+ if self._stop_event.is_set():
+ return
except Exception as e:
if self._stop_event.is_set():
self._logger.info(f"Leaving interrupted install in {job._install_tmpdir} for next startup")
diff --git a/invokeai/backend/model_manager/metadata/__init__.py b/invokeai/backend/model_manager/metadata/__init__.py
index 76da268153..2aa371e2e0 100644
--- a/invokeai/backend/model_manager/metadata/__init__.py
+++ b/invokeai/backend/model_manager/metadata/__init__.py
@@ -22,6 +22,7 @@ from invokeai.backend.model_manager.metadata.metadata_base import (
AnyModelRepoMetadataValidator,
BaseMetadata,
HuggingFaceMetadata,
+ ModelMetadataUnavailableError,
ModelMetadataWithFiles,
RemoteModelFile,
UnknownMetadataException,
@@ -33,6 +34,7 @@ __all__ = [
"HuggingFaceMetadata",
"HuggingFaceMetadataFetch",
"ModelMetadataFetchBase",
+ "ModelMetadataUnavailableError",
"BaseMetadata",
"ModelMetadataWithFiles",
"RemoteModelFile",
diff --git a/invokeai/backend/model_manager/metadata/fetch/huggingface.py b/invokeai/backend/model_manager/metadata/fetch/huggingface.py
index 67f1bd8ef8..34cce42465 100644
--- a/invokeai/backend/model_manager/metadata/fetch/huggingface.py
+++ b/invokeai/backend/model_manager/metadata/fetch/huggingface.py
@@ -17,6 +17,7 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Optional
+import httpx
import requests
from huggingface_hub import HfApi, hf_hub_url
from huggingface_hub.errors import RepositoryNotFoundError, RevisionNotFoundError
@@ -25,8 +26,10 @@ from requests.sessions import Session
from invokeai.backend.model_manager.metadata.fetch.fetch_base import ModelMetadataFetchBase
from invokeai.backend.model_manager.metadata.metadata_base import (
+ HF_METADATA_REQUEST_TIMEOUT_SECONDS,
AnyModelRepoMetadata,
HuggingFaceMetadata,
+ ModelMetadataUnavailableError,
RemoteModelFile,
UnknownMetadataException,
)
@@ -60,7 +63,7 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
url = f"https://huggingface.co/api/models/{repo_id}"
if variant is not None:
url += f"/revision/{variant}"
- resp = self._requests.get(url, params=params)
+ resp = self._requests.get(url, params=params, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)
if resp.status_code == 404:
error_code = resp.headers.get("X-Error-Code", "")
if error_code == "RevisionNotFound" or (variant is not None):
@@ -97,7 +100,14 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
if self._has_custom_session:
model_info = self._model_info_via_session(repo_id, variant)
else:
- model_info = HfApi().model_info(repo_id=repo_id, files_metadata=True, revision=variant)
+ model_info = HfApi().model_info(
+ repo_id=repo_id,
+ files_metadata=True,
+ revision=variant,
+ timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS,
+ )
+ except (requests.RequestException, httpx.TransportError) as e:
+ raise ModelMetadataUnavailableError(f"Could not fetch Hugging Face metadata for '{repo_id}'") from e
except RepositoryNotFoundError as excp:
raise UnknownMetadataException(f"'{repo_id}' not found. See trace for details.") from excp
except RevisionNotFoundError:
diff --git a/invokeai/backend/model_manager/metadata/metadata_base.py b/invokeai/backend/model_manager/metadata/metadata_base.py
index 6b30089797..3a011850f5 100644
--- a/invokeai/backend/model_manager/metadata/metadata_base.py
+++ b/invokeai/backend/model_manager/metadata/metadata_base.py
@@ -18,17 +18,24 @@ from typing import List, Literal, Optional, Union
from huggingface_hub import hf_hub_url
from pydantic import BaseModel, Field, TypeAdapter
from pydantic.networks import AnyHttpUrl
+from requests import RequestException
from requests.sessions import Session
from typing_extensions import Annotated
from invokeai.backend.model_manager.taxonomy import ModelRepoVariant
from invokeai.backend.model_manager.util.select_hf_files import filter_files
+HF_METADATA_REQUEST_TIMEOUT_SECONDS = 15
+
class UnknownMetadataException(Exception):
"""Raised when no metadata is available for a model."""
+class ModelMetadataUnavailableError(Exception):
+ """Raised when a remote metadata request fails at the network layer."""
+
+
class RemoteModelFile(BaseModel):
"""Information about a downloadable file that forms part of a model."""
@@ -121,7 +128,10 @@ class HuggingFaceMetadata(ModelMetadataWithFiles):
# to the model (only for single subfolder case)
if Path(f"{prefix}model_index.json") in paths:
url = hf_hub_url(self.id, filename="model_index.json", subfolder=str(subfolder) if subfolder else None)
- resp = session.get(url)
+ try:
+ resp = session.get(url, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)
+ except RequestException as e:
+ raise ModelMetadataUnavailableError(f"Could not fetch model index for '{self.id}'") from e
resp.raise_for_status()
submodels = resp.json()
paths = [Path(subfolder or "", x) for x in paths if Path(x).parent.as_posix() in submodels]
diff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.py
index 5e18b44ccf..c44d97cb5b 100644
--- a/tests/app/services/download/test_download_queue.py
+++ b/tests/app/services/download/test_download_queue.py
@@ -335,7 +335,10 @@ 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:
[email protected]("status", [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING, DownloadJobStatus.PAUSED])
+def test_multifile_error_preserves_sibling_part_paused_during_callback(
+ tmp_path: Path, mm2_session: Session, status: DownloadJobStatus
+) -> None:
queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True)
failed_part = DownloadJob(
id=10,
@@ -351,7 +354,7 @@ def test_multifile_error_preserves_sibling_part_paused_during_callback(tmp_path:
source=AnyHttpUrl("https://example.com/paused.safetensors"),
dest=sibling_path,
download_path=sibling_path,
- status=DownloadJobStatus.RUNNING,
+ status=status,
)
paused_sibling.pause()
parent = MultiFileDownloadJob(
@@ -367,6 +370,17 @@ def test_multifile_error_preserves_sibling_part_paused_during_callback(tmp_path:
assert paused_sibling.paused
assert partial_path.read_bytes() == b"paused partial"
+ if status == DownloadJobStatus.RUNNING:
+ # The active worker owns cleanup of its mapping after its pause callback returns.
+ assert paused_sibling.id in queue._download_part2parent
+ else:
+ # No worker remains to release a queued or already-paused part's mapping.
+ assert paused_sibling.id not in queue._download_part2parent
+
+ # A pending worker may deliver the pause callback after the parent has already failed.
+ queue._mfd_cancelled(paused_sibling)
+ queue._download_part2parent.pop(paused_sibling.id, None)
+ assert paused_sibling.id not in queue._download_part2parent
@pytest.mark.timeout(timeout=10, method="thread")
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 57f9ca6fba..f06423953e 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -18,6 +18,7 @@ from unittest.mock import MagicMock
import pytest
from pydantic_core import Url
+from requests import Timeout
from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.app.services.download import DownloadJob, DownloadJobStatus, MultiFileDownloadJob
@@ -943,6 +944,44 @@ def _write_remote_install_marker(
return download_path
+def test_restore_metadata_timeout_preserves_partial_download_for_retry(
+ 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}restore-timeout-{uuid.uuid4().hex}"
+ tmpdir.mkdir(parents=True)
+ partial_path = tmpdir / "weights.safetensors.downloading"
+ partial_path.write_bytes(b"partial model")
+ source = HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default)
+ job = ModelInstallJob(
+ id=9906,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.DOWNLOADING,
+ )
+ job._install_tmpdir = tmpdir
+ mm2_installer._write_install_marker(job, status=InstallStatus.DOWNLOADING)
+
+ def raise_metadata_timeout(*args: Any, **kwargs: Any) -> None:
+ raise Timeout("Hugging Face metadata request timed out")
+
+ assert mm2_installer._session is not None
+ monkeypatch.setattr(mm2_installer._session, "get", raise_metadata_timeout)
+
+ mm2_installer._restore_incomplete_installs()
+
+ restored_job = mm2_installer.get_job_by_source(source)[-1]
+ assert restored_job.status == InstallStatus.PAUSED
+ assert partial_path.read_bytes() == b"partial model"
+ marker = mm2_installer._read_install_marker(tmpdir)
+ assert marker is not None
+ assert marker["status"] == InstallStatus.PAUSED.value
+ assert active_install_sentinel_path(tmpdir).exists()
+
+
def test_queue_rejection_during_shutdown_preserves_completed_download(
mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig
) -> None:
@@ -1028,6 +1067,24 @@ def test_stop_preserves_restored_downloads_without_a_multifile_job(
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)
+ resume_metadata = [
+ {
+ "url": "https://example.com/weights.safetensors",
+ "canonical_url": "https://cdn.example.com/weights-v1.safetensors",
+ "etag": '"model-v1"',
+ "last_modified": "Wed, 01 Jan 2025 00:00:00 GMT",
+ "expected_total_bytes": 4096,
+ "final_url": "https://cdn.example.com/weights-v1.safetensors",
+ "download_path": (tmpdir / "weights.safetensors").as_posix(),
+ "resume_required": False,
+ "resume_message": None,
+ }
+ ]
+ if status == InstallStatus.PAUSED:
+ marker_path = tmpdir / INSTALL_MARKER_FILENAME
+ marker = json.loads(marker_path.read_text(encoding="utf-8"))
+ marker["files"] = resume_metadata
+ marker_path.write_text(json.dumps(marker), encoding="utf-8")
queued_jobs: list[ModelInstallJob] = []
monkeypatch.setattr(mm2_installer, "_put_in_queue", queued_jobs.append)
@@ -1043,6 +1100,8 @@ def test_stop_preserves_restored_downloads_without_a_multifile_job(
marker = mm2_installer._read_install_marker(tmpdir)
assert marker is not None
assert marker["status"] == status.value
+ if status == InstallStatus.PAUSED:
+ assert marker["files"] == resume_metadata
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()
diff --git a/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py
new file mode 100644
index 0000000000..20f55a0377
--- /dev/null
+++ b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py
@@ -0,0 +1,106 @@
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import httpx
+import pytest
+from requests import Timeout
+
+from invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetch
+from invokeai.backend.model_manager.metadata.metadata_base import (
+ HuggingFaceMetadata,
+ ModelMetadataUnavailableError,
+ RemoteModelFile,
+)
+
+
[email protected]("use_custom_session", [False, True])
+def test_model_info_requests_have_a_finite_timeout(monkeypatch: pytest.MonkeyPatch, use_custom_session: bool) -> None:
+ expected_model_info = SimpleNamespace(id="org/repo", siblings=[])
+
+ if use_custom_session:
+ session = Mock()
+ response = Mock(status_code=200)
+ response.json.return_value = {"id": "org/repo", "siblings": []}
+ session.get.return_value = response
+ fetcher = HuggingFaceMetadataFetch(session)
+ get_model_info = session.get
+ else:
+ api = Mock()
+ api.model_info.return_value = expected_model_info
+ monkeypatch.setattr("invokeai.backend.model_manager.metadata.fetch.huggingface.HfApi", lambda: api)
+ fetcher = HuggingFaceMetadataFetch()
+ get_model_info = api.model_info
+
+ fetcher.from_id("org/repo")
+
+ timeout = get_model_info.call_args.kwargs["timeout"]
+ assert isinstance(timeout, (int, float))
+ assert timeout > 0
+
+
+def test_model_index_request_has_a_finite_timeout() -> None:
+ session = Mock()
+ response = Mock(status_code=200)
+ response.json.return_value = {"text_encoder": []}
+ session.get.return_value = response
+ metadata = HuggingFaceMetadata(
+ id="org/repo",
+ name="repo",
+ files=[
+ RemoteModelFile(
+ url="https://huggingface.co/org/repo/resolve/main/model_index.json",
+ path=Path("model_index.json"),
+ ),
+ RemoteModelFile(
+ url="https://huggingface.co/org/repo/resolve/main/text_encoder/config.json",
+ path=Path("text_encoder/config.json"),
+ ),
+ ],
+ )
+
+ metadata.download_urls(session=session)
+
+ timeout = session.get.call_args.kwargs["timeout"]
+ assert isinstance(timeout, (int, float))
+ assert timeout > 0
+
+
[email protected]("use_custom_session", [False, True])
+def test_model_info_transport_errors_are_retryable_metadata_failures(
+ monkeypatch: pytest.MonkeyPatch, use_custom_session: bool
+) -> None:
+ if use_custom_session:
+ session = Mock()
+ session.get.side_effect = Timeout("network timeout")
+ fetcher = HuggingFaceMetadataFetch(session)
+ else:
+ api = Mock()
+ api.model_info.side_effect = httpx.TimeoutException("network timeout")
+ monkeypatch.setattr("invokeai.backend.model_manager.metadata.fetch.huggingface.HfApi", lambda: api)
+ fetcher = HuggingFaceMetadataFetch()
+
+ with pytest.raises(ModelMetadataUnavailableError):
+ fetcher.from_id("org/repo")
+
+
+def test_model_index_transport_errors_are_retryable_metadata_failures() -> None:
+ session = Mock()
+ session.get.side_effect = Timeout("network timeout")
+ metadata = HuggingFaceMetadata(
+ id="org/repo",
+ name="repo",
+ files=[
+ RemoteModelFile(
+ url="https://huggingface.co/org/repo/resolve/main/model_index.json",
+ path=Path("model_index.json"),
+ ),
+ RemoteModelFile(
+ url="https://huggingface.co/org/repo/resolve/main/text_encoder/config.json",
+ path=Path("text_encoder/config.json"),
+ ),
+ ],
+ )
+
+ with pytest.raises(ModelMetadataUnavailableError):
+ metadata.download_urls(session=session)