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): preserve install tmpdir when a single multi-file part fails (#9591)

lorenzozaneef2be36c455f
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index e355fb6b83..e16d973cca 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -315,18 +315,19 @@ source6 = HFModelSource(repo_id='runwayml/stable-diffusion-v1-5', subfolder='Ora
source7 = URLModelSource(url='https://civitai.com/api/download/models/63006') # model located at a URL
source8 = URLModelSource(url='https://civitai.com/api/download/models/63006', access_token='letmein') # with an access token
-for source in [source1, source2, source3, source4, source5, source6, source7]:
- install_job = installer.install_model(source)
-
-source2job = installer.wait_for_installs(timeout=120)
-for source in sources:
- job = source2job[source]
- if job.complete:
- model_config = job.config_out
- model_key = model_config.key
- print(f"{source} installed as {model_key}")
- elif job.errored:
- print(f"{source}: {job.error_type}.\nStack trace:\n{job.error}")
+for source in [source1, source2, source3, source4, source5, source6, source7, source8]:
+ installer.import_model(source)
+
+jobs = installer.wait_for_installs(timeout=120)
+for job in jobs:
+ if job.complete:
+ model_config = job.config_out
+ model_key = model_config.key
+ print(f"{job.source} installed as {model_key}")
+ elif job.errored:
+ print(f"{job.source}: {job.error_type}: {job.error}\nStack trace:\n{job.error_traceback}")
+ elif job.paused:
+ print(f"{job.source} paused; resume or retry its download to finish installation")
```
@@ -336,7 +337,7 @@ Each call to `import_model()` return a `ModelInstallJob` job, an object which tr
If a remote model is requested, the model's files are downloaded in parallel across a multiple set of threads using the download queue. During the download process, the `ModelInstallJob` is updated to provide status and progress information. After the files (if any) are downloaded, the remainder of the installation runs in a single serialized background thread. These are the model probing, file copying, and config record database update steps.
-Multiple install jobs can be queued up. You may block until all install jobs are completed (or errored) by calling the `wait_for_installs()` method as shown in the code example. `wait_for_installs()` will return a `dict` that maps the requested source to its job. This object can be interrogated to determine its status. If the job errored out, then the error type and details can be recovered from `job.error_type` and `job.error`.
+Multiple install jobs can be queued up. Call `wait_for_installs()` to wait for pending download and install work to quiesce. Its returned list contains the tracked jobs and may include a recoverably paused, nonterminal job; resume or retry that job before treating installation as complete. If a job errored out, its exception class, message and traceback are available as `job.error_type`, `job.error` and `job.error_traceback`.
The full list of arguments to `import_model()` is as follows:
@@ -402,6 +403,8 @@ If `subfolder` is specified, then the requested model resides in a subfolder of
Some models require you to be registered with HuggingFace and logged in. To download these files, you must provide an `access_token`. Internally, if no access token is provided, then `HfFolder.get_token()` will be called to fill it in with the cached one.
+A Hugging Face install is pinned to the commit the repository is at when it starts. That covers an `HFModelSource`, a `URLModelSource` naming a repository page on `huggingface.co` (repository pages on a configured `HF_ENDPOINT` mirror are not recognized), and a `URLModelSource` naming one file by branch, tag or pull request (`{endpoint}/{org}/{repo}/resolve/{revision}/{file}`, http or https, on `huggingface.co` or the configured `HF_ENDPOINT` mirror; `/blob/` page URLs on those hosts are converted to `/resolve/` first), which is what `/install/huggingface` passes for a single-checkpoint repository. A repository's commit comes from its metadata. A single file's comes from the `X-Repo-Commit` header of a `HEAD` request to the URL's own host. The request goes through the download queue (`DownloadQueueServiceBase.head()`), so it takes the downloads' `download_proxy` and private-address policy. Like `huggingface_hub`, it follows redirects on the same host until a response names the commit (a renamed repository answers a relative `307`, a small file one to its cache, `http://` a `301` to `https://`), and never follows one to another host, such as the CDN serving large files. It is sent with the token the download sends: the source's own token, else the `remote_api_tokens` entry matching the URL as given. That token is then sent explicitly with the download, whose URL names the commit instead of the branch. A file URL that already names a commit is used as given. If the host names no commit or refuses the request, the file is downloaded as given, unpinned, and the download reports any failure; a 429, 5xx or connection failure raises `ModelMetadataUnavailableError`, as a repository lookup does. Runtime downloads through `download_and_cache_model()` are not installs and never look up a commit. The install's internal download URLs name the commit, and the install marker records it as `revision`. Resuming, retrying failed files and restoring after a restart all download from that commit, so a repository whose branch moves while the install is paused cannot have files from two commits mixed into one model. The install's source, and URLs that users and model records see, such as the checkpoint URLs a repository lookup returns, keep naming the branch. If the pinned commit is no longer available (a repository lookup reports it missing, or a single file's commit URL answers `404` with `X-Error-Code` `EntryNotFound` or `RevisionNotFound`), its staged files can never be completed: the resume or retry raises `ModelRevisionUnavailableError` (HTTP 409 from the API), the install ends in `ERROR` with a message saying to start it again, and its staging directory is removed. Any other answer for a pinned single file (a refusal such as `401 GatedRepo`, a `404 RepoNotFound`, a bare `404` from a mirror or proxy, an unreachable host) is left to the download, which keeps its staged files. The errored job keeps no `download_parts`, and resuming or restarting it does nothing; a retry submits the source again, which starts a new install pinned to the repository's current commit. An install restored at startup errors the same way. Only a full commit hash pins an install: a branch can move after files were staged from it. So when a restored Hugging Face install's marker names no commit (written before installs were pinned, a null `revision`, a branch, or an install whose host named no commit), restore deletes its staged files and partials, keeping the staging directory and marker, and the download starts over, pinned to the current commit if the host names one; a new install never reuses such staging. A resume, retry or restart of a Hugging Face install that is not pinned to a commit deletes its staged files the same way and downloads again, pinned if the host now names a commit, so an unpinned install never keeps a partial file. The marker of a Hugging Face file URL records the `hf_endpoint` it was recognized on, so after `HF_ENDPOINT` changes the install is still treated as Hugging Face: its unpinned staging is discarded, and its pinned download continues on the endpoint it started on. Downloads that have finished (markers with `DOWNLOADS_DONE` or `RUNNING` status) and sources without repository revisions keep their staged files.
+
#### Monitoring the install job process
When you create an install job with `import_model()`, it launches the download and installation process in the background and returns a `ModelInstallJob` object for monitoring the process.
@@ -411,56 +414,64 @@ The `ModelInstallJob` class has the following structure:
| Attribute | Type | Description |
|-----------|------|-------------|
| `id` | `int` | Integer ID for this job |
-| `status` | `InstallStatus` | An enum of [`waiting`, `downloading`, `running`, `completed`, `error` and `cancelled`] |
+| `status` | `InstallStatus` | An enum of [`waiting`, `downloading`, `running`, `paused`, `completed`, `error` and `cancelled`] |
| `config_in` | `dict` | Overriding configuration values provided by the caller |
| `config_out` | `AnyModelConfig` | After successful completion, contains the configuration record written to the database |
| `inplace` | `boolean` | True if the caller asked to install the model in place using its local path |
| `source` | `ModelSource` | The local path, remote URL or repo_id of the model to be installed |
| `local_path` | `Path` | If a remote model, holds the path of the model after it is downloaded; if a local model, same as `source` |
| `error_type` | `str` | Name of the exception that led to an error status |
-| `error` | `str` | Traceback of the error |
+| `error` | `str` | Message of the exception that led to an error status |
+| `error_traceback` | `str` | Traceback of that exception |
-If the `event_bus` argument was provided, events will also be broadcast to the InvokeAI event bus. The events will appear on the bus as an event of type `EventServiceBase.model_event`, a timestamp and the following event names:
+If the `event_bus` argument was provided, the installer also dispatches the following events through it (`EventServiceBase.dispatch()`), and clients receive them under these names. Every payload also carries a `timestamp`.
-##### `model_install_downloading`
+##### `model_install_download_started` and `model_install_download_progress`
-For remote models only, `model_install_downloading` events will be issued at regular intervals as the download progresses. The event's payload contains the following keys:
+For remote models, `model_install_download_started` is emitted when downloading begins, and `model_install_download_progress` is emitted as it progresses. Both payloads contain these keys:
| Key | Type | Description |
|-----|------|-------------|
-|`source`|str|String representation of the requested source|
-|`local_path`|str|String representation of the path to the downloading model (usually a temporary directory)|
+|`id`|int|ID of the install job|
+|`source`|ModelSource|Requested model source|
+|`local_path`|str|Path where the model is downloading to (usually a temporary directory)|
|`bytes`|int|How many bytes downloaded so far|
|`total_bytes`|int|Total size of all the files that make up the model|
|`parts`|List[Dict]|Information on the progress of the individual files that make up the model|
-The parts is a list of dictionaries that give information on each of the components pieces of the download. The dictionary's keys are `source`, `local_path`, `bytes` and `total_bytes`, and correspond to the like-named keys in the main event.
+Each item in `parts` contains `url`, `local_path`, `bytes` and `total_bytes`.
+
+These download events are not issued for local models. They occur before `model_install_started`.
+
+##### `model_install_downloads_complete`
+
+`model_install_downloads_complete` is emitted after all required downloads finish. Its payload contains `id` and `source`.
-Note that downloading events will not be issued for local models, and that downloading events occur _before_ the running event.
+##### `model_install_paused`
-##### `model_install_running`
+`model_install_paused` is emitted when a remote install is paused, including when a transient file-download error preserves staging for resume or retry. Its payload contains `id` and `source`.
-`model_install_running` is issued when all the required downloads have completed (if applicable) and the model probing, copying and registration process has now started.
+##### `model_install_started`
-The payload will contain the key `source`.
+`model_install_started` is emitted after any download, when model probing, copying and registration begin. Its payload contains `id` and `source`.
-##### `model_install_completed`
+##### `model_install_complete`
-`model_install_completed` is issued once at the end of a successful installation. The payload will contain the keys `source`, `total_bytes` and `key`, where `key` is the ID under which the model has been registered.
+`model_install_complete` is emitted once an installation succeeds. Its payload contains `id`, `source`, `key`, `total_bytes` and `config`; `key` is the ID under which the model has been registered, and `total_bytes` may be `null` for a local model.
##### `model_install_error`
-`model_install_error` is emitted if the installation process fails for some reason. The payload will contain the keys `source`, `error_type` and `error`. `error_type` is a short message indicating the nature of the error, and `error` is the long traceback to help debug the problem.
+`model_install_error` is emitted if the installation process fails. Its payload contains `id`, `source`, `error_type` and `error`.
##### `model_install_cancelled`
-`model_install_cancelled` is issued if the model installation is cancelled, or if one or more of its files' downloads are cancelled. The payload will contain `source`.
+`model_install_cancelled` is emitted when the installation is cancelled. Its payload contains `id` and `source`.
##### Following the model status
-You may poll the `ModelInstallJob` object returned by `import_model()` to ascertain the state of the install. The job status can be read from the job's `status` attribute, an `InstallStatus` enum which has the enumerated values `WAITING`, `DOWNLOADING`, `RUNNING`, `COMPLETED`, `ERROR` and `CANCELLED`.
+You may poll the `ModelInstallJob` object returned by `import_model()` to ascertain the state of the install. The job status can be read from the job's `status` attribute, an `InstallStatus` enum which has the enumerated values `WAITING`, `DOWNLOADING`, `RUNNING`, `PAUSED`, `COMPLETED`, `ERROR` and `CANCELLED`. A paused remote install can be resumed or its failed files retried while its staging data is retained.
-For convenience, install jobs also provided the following boolean properties: `waiting`, `downloading`, `running`, `complete`, `errored` and `cancelled`, as well as `in_terminal_state`. The last will return True if the job is in the complete, errored or cancelled states.
+For convenience, install jobs also provide the following boolean properties: `waiting`, `downloading`, `running`, `paused`, `complete`, `errored` and `cancelled`, as well as `in_terminal_state`. The last will return True if the job is in the complete, errored or cancelled states.
#### Model configuration and probing
@@ -486,15 +497,19 @@ This section describes additional methods provided by the installer class.
#### jobs = installer.wait_for_installs([timeout])
-Block until all pending installs are completed or errored and then returns a list of completed jobs. The optional `timeout` argument will return from the call if jobs aren't completed in the specified time. An argument of 0 (the default) will block indefinitely.
+Wait until pending download and install work has quiesced, then return the tracked jobs. Transient download failures can leave a job in `PAUSED`; this nonterminal job is returned and does not block the method. Resume or retry it before treating installation as complete. The optional `timeout` argument raises if work does not quiesce in time; 0 (the default) waits indefinitely.
#### jobs = installer.wait_for_job(job, [timeout])
-Like `wait_for_installs()`, but block until a specific job has completed or errored, and then return the job. The optional `timeout` argument will return from the call if the job doesn't complete in the specified time. An argument of 0 (the default) will block indefinitely.
+Block until a specific job reaches a terminal state or pauses, then return it. While a resume or retry of a paused job is being set up, or the callback of its last download is still finishing, this keeps waiting for that to settle. A paused job is nonterminal and stays paused until it is resumed or its failed files are retried, so check `job.paused` before treating the install as finished. The optional `timeout` argument raises if the job neither finishes nor pauses in time; 0 (the default) waits indefinitely.
+
+#### job = installer.resume_and_wait_for_job(job, [timeout])
+
+For callers that need the model rather than a progress report, such as an invocation that installs a missing dependency. Resume the job if it is paused, then wait for it like `wait_for_job()`. `resume_job()` itself never waits: it raises `InstallDownloadConflictError` at once when another resume is underway or the job's last download callback has not finished. This method waits out the callback and resumes the job afterwards if it is still paused; when another caller is resuming the job, it waits for that attempt's outcome instead of starting a second one. A resume refused for any other reason, such as a stopping service or a partial file that must restart but cannot be deleted, is not retried: the job is returned paused. If the job's pinned revision is gone, the job is returned in `ERROR` rather than raising. The optional `timeout` bounds the whole call.
#### jobs = installer.list_jobs()
-Return a list of all active and complete `ModelInstallJobs`.
+Return a list of all tracked `ModelInstallJob` objects, including queued, paused, and terminal jobs.
#### jobs = installer.get_job_by_source(source)
@@ -555,7 +570,7 @@ Startup serializes stale-claim scans in-process and across processes with the pe
| Path | Meaning |
| --- | --- |
| `tmpinstall_*/` | A remote install's staging directory. Downloads land here before the install moves them. |
-| `tmpinstall_*/.invokeai_install.json` | The staging marker, format version 1: `version`, `source`, `access_token` (Hugging Face and URL sources only), `config_in`, `status`, `updated_at`, per-file resume metadata in `files` (see below), and `recovery_required: true` once a transfer failed in a way that needs manual recovery. |
+| `tmpinstall_*/.invokeai_install.json` | The staging marker, format version 1: `version`, `source`, `access_token` (Hugging Face and URL sources only), `config_in`, `status`, `updated_at`, per-file resume metadata in `files` (see below), the repository `revision` its downloads are pinned to (null for a source without one; absent in markers written before installs were pinned), `hf_endpoint` for a Hugging Face install (the endpoint its URLs were recognized on), and `recovery_required: true` once a transfer failed in a way that needs manual recovery. |
| `.<name>.invokeai_install_active` | An active claim on the sibling `<name>`, held by a live install or orphan deletion. |
| `.<name>.invokeai_install_recovery_required` | A recovery sentinel: `<name>` holds data a failed transfer could not roll back. |
| `.invokeai_install_claims.lock` | Serializes the startup sweep of stale claims. |
@@ -572,7 +587,9 @@ At startup the installer sweeps stale claims, then removes staging directories t
Each `files` entry records one download part: its `url`, `canonical_url` and `final_url`, the validators `etag` and `last_modified`, `expected_total_bytes`, the `download_path` it writes, and `resume_required`, `resume_refused` and `resume_message`. The installer rewrites the marker as each part starts, once its response headers arrived, so a crash leaves the running part's validator and file name on disk. On a resume or a restore, the download queue's `DownloadJob` names the partial file a part would continue (`resumable_partial()`) and whether it may (`may_resume_partial()`): only with a recorded validator, sent as If-Range, and only if the server has not already refused to continue it. A server whose file changed answers with the whole file, and the part pauses as restart-required instead of splicing two revisions. Any other partial is deleted and its part reported with `resume_from_scratch`, as is a part that had started but whose partial and finished file are both gone. A recorded `download_path` outside the staging directory is ignored. Entries written before `resume_refused` existed count as refused when `resume_required` is set and the message is the queue's refusal message. When a partial that must restart cannot be deleted (on Windows, while another process holds it open), the resume or restart fails with a conflict rather than continue it without a validator; during startup restore the job stays paused.
-Startup restores nonterminal install markers automatically, except markers with `PAUSED` status. If shutdown interrupts restoration of a marker already visited, that job is saved as `PAUSED`; markers later in the scan remain unchanged. On the next service startup, non-paused markers resume automatically, while both user-paused and shutdown-paused jobs stay paused until `resume_job()` is called. Partial files and resume metadata remain in their staging directories across this cycle.
+A failed-file retry (`restart_failed()`) or explicit file restart (`restart_file()`) deletes the affected file's partial before downloading it again. Valid completed sibling files in staging remain reusable; a pinned Hugging Face install keeps downloading from its recorded commit. An unpinned Hugging Face install instead discards all staged files and resume metadata before retrying, then pins the new download if its host supplies a commit.
+
+Startup restores nonterminal install markers automatically, except markers with `PAUSED` status. If shutdown interrupts restoration of a marker already visited, that job is saved as `PAUSED`; markers later in the scan remain unchanged. On the next service startup, non-paused markers resume automatically, while both user-paused and shutdown-paused jobs stay paused until `resume_job()` is called. Partial files and resume metadata are retained across this cycle, except that restoring a Hugging Face install without a full commit hash discards its staged files and resume metadata unless its downloads have finished (marker status `DOWNLOADS_DONE` or `RUNNING`).
Before a transfer, the installer flushes the recovery-sentinel file and, on non-Windows platforms, its containing directory. A file or directory `fsync` error aborts the install before source files move; unsupported directory `fsync` is treated as a failure, not as best-effort durability. Sentinel cleanup unlinks the file before syncing the containing directory. If that final sync fails, the installer logs a warning and continues cleanup; the unlink may not survive a crash, so a stale sentinel can reappear and require manual inspection. These steps do not promise crash durability on every filesystem or storage device.
@@ -653,7 +670,7 @@ The `status` field is updated by the queue to indicate where the job is in its l
In case of an error, the Exception that caused the error will be placed in the `error` field, and the job's status will be set to `DownloadJobStatus.ERROR`.
-After an error occurs, any partially downloaded files will be deleted from disk, unless `preserve_partial_downloads` was set to True at job creation time (or set to True any time before the error occurred). Note that since all InvokeAI model install operations involve downloading files to a temporary directory that has a limited lifetime, this flag is not used by the model installer.
+Download errors can leave a `.downloading` file behind; cleanup is owned by the caller. When a part of a model install fails with a transient error (a connection failure or timeout, an interrupted transfer including a dropped TLS connection, HTTP 408, 429 or 5xx, or the `.downloading` file vanishing before its final rename) and the install's staging directory holds downloaded bytes a resume would keep (a non-empty completed file, or a partial file with a recorded validator its server has not refused, from this attempt or an earlier one; a resume deletes any other partial), the installer pauses the install and preserves its staging directory and marker for resume or restart. The failed part keeps its `error_type` and `error` in the job's `download_parts`. Any other error (for example HTTP 401, 403 or 404, a TLS certificate that fails verification, insufficient disk space, or an unsafe filename), or a transient one with no recoverable data, errors the install and removes the temporary staging directory.
There are a series of subclasses of `DownloadJobBase` that provide support for specific types of downloads. These are:
@@ -915,7 +932,7 @@ This is a discriminated Union of `HuggingFaceMetadata`.
### Fetching Metadata from Online Repos
-The `HuggingFaceMetadataFetch` class will retrieve metadata from its corresponding repository and return `AnyModelRepoMetadata` objects. Their base class `ModelMetadataFetchBase` is an abstract class that defines two methods: `from_url()` and `from_id()`. The former accepts the type of model URLs that the user will try to cut and paste into the model import form. The latter accepts a string ID in the format recognized by the repository of choice. Both methods return an `AnyModelRepoMetadata`.
+The `HuggingFaceMetadataFetch` class will retrieve metadata from its corresponding repository and return `AnyModelRepoMetadata` objects. Their base class `ModelMetadataFetchBase` is an abstract class that defines two methods: `from_url()` and `from_id()`. The former accepts the type of model URLs that the user will try to cut and paste into the model import form. The latter accepts a string ID in the format recognized by the repository of choice. Both methods return an `AnyModelRepoMetadata`, and both accept an optional `revision` and `pin_to_commit`. By default, `HuggingFaceMetadata` file URLs name the branch (the variant's, or `main`). `pin_to_commit=True` makes them name the commit that branch points to now; the installer uses it for its downloads. With `revision`, the files and URLs come from that revision, and a missing revision raises `ModelRevisionUnavailableError`. The returned metadata's `revision` property holds the revision its URLs name; it is not serialized, so metadata read back from JSON takes it from its file URLs.
The base class also has a class method `from_json()` which will take the JSON representation of a `ModelMetadata` object, validate it, and return the corresponding `AnyModelRepoMetadata` object.
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 6e55e415ad..ba86975477 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -59,7 +59,11 @@ from invokeai.backend.model_manager.load.fp8_capability import Fp8StorageSupport
from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetch
-from invokeai.backend.model_manager.metadata.metadata_base import ModelMetadataWithFiles, UnknownMetadataException
+from invokeai.backend.model_manager.metadata.metadata_base import (
+ ModelMetadataWithFiles,
+ ModelRevisionUnavailableError,
+ UnknownMetadataException,
+)
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.search import ModelSearch, ModelSearchCancelled
from invokeai.backend.model_manager.starter_models import (
@@ -1333,7 +1337,7 @@ def resume_model_install_job(
raise HTTPException(status_code=415, detail=str(e))
try:
installer.resume_job(job)
- except (InstallCancellationConflictError, InstallDownloadConflictError) as e:
+ except (InstallCancellationConflictError, InstallDownloadConflictError, ModelRevisionUnavailableError) as e:
raise HTTPException(status_code=409, detail=str(e)) from e
return job
@@ -1359,7 +1363,7 @@ def restart_failed_model_install_job(
raise HTTPException(status_code=415, detail=str(e))
try:
installer.restart_failed(job)
- except (InstallCancellationConflictError, InstallDownloadConflictError) as e:
+ except (InstallCancellationConflictError, InstallDownloadConflictError, ModelRevisionUnavailableError) as e:
raise HTTPException(status_code=409, detail=str(e)) from e
return job
@@ -1387,7 +1391,7 @@ def restart_model_install_file(
raise HTTPException(status_code=415, detail=str(e))
try:
installer.restart_file(job, str(file_source))
- except (InstallCancellationConflictError, InstallDownloadConflictError) as e:
+ except (InstallCancellationConflictError, InstallDownloadConflictError, ModelRevisionUnavailableError) as e:
raise HTTPException(status_code=409, detail=str(e)) from e
return job
@@ -1395,15 +1399,16 @@ def restart_model_install_file(
@model_manager_router.delete(
"/install",
operation_id="prune_model_install_jobs",
+ response_model=list[int],
+ status_code=200,
responses={
- 204: {"description": "All completed and errored jobs have been pruned"},
+ 200: {"description": "IDs of completed and errored jobs that were pruned"},
400: {"description": "Bad request"},
},
)
-def prune_model_install_jobs(current_admin: AdminUserOrDefault) -> Response:
+def prune_model_install_jobs(current_admin: AdminUserOrDefault) -> list[int]:
"""Prune all completed and errored jobs from the install job list."""
- ApiDependencies.invoker.services.model_manager.install.prune_jobs()
- return Response(status_code=204)
+ return ApiDependencies.invoker.services.model_manager.install.prune_jobs()
@model_manager_router.put(
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py
index bb7e7fc9c1..f96d02057f 100644
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@ -46,6 +46,7 @@ from invokeai.app.services.events.events_common import (
ModelInstallDownloadsCompleteEvent,
ModelInstallDownloadStartedEvent,
ModelInstallErrorEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
ModelLoadCompleteEvent,
ModelLoadStartedEvent,
@@ -126,6 +127,7 @@ MODEL_EVENTS = {
ModelInstallDownloadStartedEvent,
ModelInstallDownloadProgressEvent,
ModelInstallDownloadsCompleteEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
ModelInstallCompleteEvent,
ModelInstallCancelledEvent,
@@ -144,6 +146,7 @@ MODEL_INSTALL_EVENTS = (
ModelInstallDownloadStartedEvent,
ModelInstallDownloadProgressEvent,
ModelInstallDownloadsCompleteEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
ModelInstallCompleteEvent,
ModelInstallCancelledEvent,
diff --git a/invokeai/app/invocations/flux/flux_redux.py b/invokeai/app/invocations/flux/flux_redux.py
index 0bc9fdf1d8..e953467941 100644
--- a/invokeai/app/invocations/flux/flux_redux.py
+++ b/invokeai/app/invocations/flux/flux_redux.py
@@ -153,10 +153,22 @@ class FluxReduxInvocation(BaseInvocation):
config_overrides = ModelRecordChanges(name=siglip.name, type=ModelType.SigLIP)
# Queue the job
- job = context._services.model_manager.install.heuristic_import(siglip.source, config=config_overrides)
-
+ installer = context._services.model_manager.install
+ job = installer.heuristic_import(siglip.source, config=config_overrides)
+ # An earlier run's install may have paused on a download error; retrying is what this call is for.
# Wait for up to 10 minutes - model is ~3.5GB
- context._services.model_manager.install.wait_for_job(job, timeout=600)
+ try:
+ installer.resume_and_wait_for_job(job, timeout=600)
+ except TimeoutError:
+ # Model-specific failure below includes the install state and recovery path.
+ pass
+
+ if not job.complete:
+ raise RuntimeError(
+ f"Could not install the SigLIP model required by FLUX Redux ({siglip.name}): install status is "
+ f"'{job.status.value}'{f' ({job.error})' if job.error else ''}. "
+ "A paused install can be resumed or retried from the Model Manager."
+ )
siglip_models = context.models.search_by_attrs(
name=siglip.name,
diff --git a/invokeai/app/invocations/sd/ip_adapter.py b/invokeai/app/invocations/sd/ip_adapter.py
index c6a45a0bb3..f46cd8c330 100644
--- a/invokeai/app/invocations/sd/ip_adapter.py
+++ b/invokeai/app/invocations/sd/ip_adapter.py
@@ -220,7 +220,20 @@ class IPAdapterInvocation(BaseInvocation):
job = installer.heuristic_import(
image_encoder_model_id, ModelRecordChanges(name=image_encoder_model_name, type=ModelType.CLIPVision)
)
- installer.wait_for_job(job, timeout=600) # Wait for up to 10 minutes
+ # An earlier run's install may have paused on a download error; retrying is what this call is for.
+ # Wait for up to 10 minutes
+ try:
+ installer.resume_and_wait_for_job(job, timeout=600)
+ except TimeoutError:
+ # Model-specific failure below includes the install state and recovery path.
+ pass
+
+ if not job.complete:
+ raise RuntimeError(
+ f"Could not install the image encoder required by this IP Adapter ({image_encoder_model_name}): "
+ f"install status is '{job.status.value}'{f' ({job.error})' if job.error else ''}. "
+ "A paused install can be resumed or retried from the Model Manager."
+ )
image_encoder_models = context.models.search_by_attrs(
name=image_encoder_model_name, base=BaseModelType.Any, type=ModelType.CLIPVision
)
diff --git a/invokeai/app/services/download/download_base.py b/invokeai/app/services/download/download_base.py
index 4bc0f9075c..5d8b06a3bb 100644
--- a/invokeai/app/services/download/download_base.py
+++ b/invokeai/app/services/download/download_base.py
@@ -6,6 +6,7 @@ from functools import total_ordering
from pathlib import Path
from typing import Any, Callable, List, Optional, Set, Union
+import requests
from pydantic import BaseModel, Field, PrivateAttr, field_serializer
from pydantic.networks import AnyHttpUrl
@@ -283,6 +284,11 @@ class DownloadQueueServiceBase(ABC):
def stop(self, *args: Any, **kwargs: Any) -> None:
"""Stop the download worker threads."""
+ @abstractmethod
+ def head(self, url: str, headers: Optional[dict[str, str]] = None, timeout: float = 15) -> "requests.Response":
+ """Send one HEAD request for `url` the way downloads are sent: through the configured download proxy and
+ address policy. Redirects are not followed; a URL the policy refuses raises `UnsafeDownloadURLException`."""
+
@abstractmethod
def download(
self,
diff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.py
index 750f7fcbcc..27e9163bef 100644
--- a/invokeai/app/services/download/download_default.py
+++ b/invokeai/app/services/download/download_default.py
@@ -491,14 +491,7 @@ class DownloadQueueService(DownloadQueueServiceBase):
return
self._refuse_resume(job)
if not resp.ok:
- host = urlparse(str(resp.url or url)).netloc
- status = resp.status_code
- reason = resp.reason
- if status >= 500:
- self._logger.error(f"Remote server error from {host}: HTTP {status} {reason}")
- raise HTTPError(reason)
- self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")
- raise HTTPError(reason)
+ self._raise_http_error(resp, url)
if resume_from > 0 and resp.status_code == 200:
# The server ignored Range, or If-Range found the file changed. This response's validators describe the
@@ -599,14 +592,7 @@ class DownloadQueueService(DownloadQueueServiceBase):
# some other error
elif resp.status_code != 200:
- host = urlparse(str(resp.url or url)).netloc
- status = resp.status_code
- reason = resp.reason
- if status >= 500:
- self._logger.error(f"Remote server error from {host}: HTTP {status} {reason}")
- raise HTTPError(reason)
- self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")
- raise HTTPError(reason)
+ self._raise_http_error(resp, url)
self._logger.debug(f"{job.source}: Downloading {job.download_path}")
report_delta = job.total_bytes / 100 # report every 1% change
@@ -642,6 +628,25 @@ class DownloadQueueService(DownloadQueueServiceBase):
job.pause()
raise DownloadJobCancelledException(RESUME_REFUSED_MESSAGE)
+ def _raise_http_error(self, resp: requests.Response, url: str) -> NoReturn:
+ host = urlparse(str(resp.url or url)).netloc
+ status = resp.status_code
+ reason = resp.reason
+ if status >= 500:
+ self._logger.error(f"Remote server error from {host}: HTTP {status} {reason}")
+ else:
+ self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")
+ # Release the pooled connection now: the exception, which carries the response so callers can read its
+ # status code, may outlive this download.
+ resp.close()
+ raise HTTPError(reason, response=resp)
+
+ def head(self, url: str, headers: Optional[dict[str, str]] = None, timeout: float = 15) -> requests.Response:
+ self._validate_url(url)
+ return self._requests.head(
+ url, headers=headers or {}, allow_redirects=False, timeout=timeout, proxies=self._request_proxies
+ )
+
def _validate_url(self, url: str) -> None:
"""Refuse to fetch URLs that point at addresses only the server can reach."""
validate_download_url(str(url), allow_private_urls=self._app_config.allow_private_download_urls)
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index d305374bfd..668c249de0 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -30,6 +30,7 @@ from invokeai.app.services.events.events_common import (
ModelInstallDownloadsCompleteEvent,
ModelInstallDownloadStartedEvent,
ModelInstallErrorEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
ModelLoadCompleteEvent,
ModelLoadStartedEvent,
@@ -272,6 +273,10 @@ class EventServiceBase:
def emit_model_install_downloads_complete(self, job: "ModelInstallJob") -> None:
self.dispatch(ModelInstallDownloadsCompleteEvent.build(job))
+ def emit_model_install_paused(self, job: "ModelInstallJob") -> None:
+ """Emitted when a model install is paused and can be resumed."""
+ self.dispatch(ModelInstallPausedEvent.build(job))
+
def emit_model_install_started(self, job: "ModelInstallJob") -> None:
"""Emitted once when an install job is started (after any download)."""
self.dispatch(ModelInstallStartedEvent.build(job))
diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.py
index f70056a4f3..0a1d9d354a 100644
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@ -721,6 +721,20 @@ class ModelInstallDownloadsCompleteEvent(ModelEventBase):
return cls(id=job.id, source=job.source)
+@payload_schema.register
+class ModelInstallPausedEvent(ModelEventBase):
+ """Emitted when a model install is paused and can be resumed."""
+
+ __event_name__ = "model_install_paused"
+
+ id: int = Field(description="The ID of the install job")
+ source: ModelSource = Field(description="Source of the model; local path, repo_id or url")
+
+ @classmethod
+ def build(cls, job: "ModelInstallJob") -> "ModelInstallPausedEvent":
+ return cls(id=job.id, source=job.source)
+
+
@payload_schema.register
class ModelInstallStartedEvent(ModelEventBase):
"""Event model for model_install_started"""
diff --git a/invokeai/app/services/model_install/install_staging_ledger.py b/invokeai/app/services/model_install/install_staging_ledger.py
index b3da969dd9..afe43ca30f 100644
--- a/invokeai/app/services/model_install/install_staging_ledger.py
+++ b/invokeai/app/services/model_install/install_staging_ledger.py
@@ -6,7 +6,10 @@ needs. The ledger owns every piece of that state (paths relative to the models d
- ``tmpinstall_*/``: a remote install's staging directory. Downloads land here before the install moves them.
- ``tmpinstall_*/.invokeai_install.json``: the staging directory's marker (format version 1), what a restart needs to
resume the install: source, access token (Hugging Face and URL sources only), requested config, status, timestamp,
- per-file resume metadata, and ``recovery_required`` once a failed transfer left data that needs a person. Each
+ per-file resume metadata, the repository ``revision`` its downloads are pinned to (null when the source has none or
+ the marker predates pinning), for a Hugging Face file URL the ``hf_endpoint`` it was recognized on (so a later
+ ``HF_ENDPOINT`` change cannot hide that it came from a repository), and ``recovery_required`` once a failed transfer
+ left data that needs a person. Each
write replaces the marker atomically (temporary file, fsync, rename, directory fsync off Windows). A staging
directory whose marker exists but is unusable (torn, or an unknown format version) is kept and reported: it may hold
the only copy of a download. Orphaned model cleanup, or a person, removes it.
@@ -171,6 +174,17 @@ def _has_terminal_status(marker: Optional[dict[str, Any]]) -> bool:
return marker is not None and marker.get("status") in {status.value for status in _TERMINAL_STATUSES}
+def _marker_revision(marker: dict[str, Any]) -> Optional[str]:
+ """The revision a marker's downloads are pinned to; None when it names none, or predates pinning."""
+ revision = marker.get("revision")
+ return revision if isinstance(revision, str) else None
+
+
+def _marker_hf_endpoint(marker: dict[str, Any]) -> Optional[str]:
+ endpoint = marker.get("hf_endpoint")
+ return endpoint if isinstance(endpoint, str) else None
+
+
def _write_marker(path: Path, marker: dict[str, Any], logger: logging.Logger) -> None:
"""Replace a marker atomically: readers and a crash see the previous marker or the new one, never a torn one."""
fd, temp_name = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)
@@ -347,6 +361,8 @@ class RecoverableInstall:
access_token: Any
config_in: Any
files: list[Any]
+ revision: Optional[str]
+ hf_endpoint: Optional[str]
class InstallStaging:
@@ -441,6 +457,8 @@ class InstallStaging:
download_parts: Iterable[DownloadJob],
resume_files: Optional[dict[str, dict[str, Any]]],
recovery_required: bool,
+ revision: Optional[str] = None,
+ hf_endpoint: Optional[str] = None,
) -> None:
"""Write the staging directory's marker so a restart can resume the install."""
if self._tmpdir is None:
@@ -456,7 +474,10 @@ class InstallStaging:
"status": status.value,
"updated_at": get_iso_timestamp(),
"files": files,
+ "revision": revision,
}
+ if hf_endpoint is not None:
+ marker["hf_endpoint"] = hf_endpoint
if recovery_required:
marker["recovery_required"] = True
self._tmpdir.mkdir(parents=True, exist_ok=True)
@@ -486,6 +507,23 @@ class InstallStaging:
except Exception as e:
self._ledger._logger.warning(f"Failed to remove install marker {leftover}: {e}")
+ def discard_files(self) -> None:
+ """Delete everything staged in the directory except its marker, keeping the directory and its claim.
+
+ For staged files that can no longer be trusted, so the download starts over in the same place. Raises when an
+ entry cannot be deleted.
+ """
+ if self._tmpdir is None:
+ return
+ marker_path = self._tmpdir / INSTALL_MARKER_FILENAME
+ for entry in self._tmpdir.iterdir():
+ if entry == marker_path:
+ continue
+ if entry.is_dir() and not entry.is_symlink():
+ rmtree(entry)
+ else:
+ entry.unlink()
+
def requires_recovery(self) -> bool:
"""Whether the staging directory is marked as holding recovery data."""
return self._tmpdir is not None and _requires_recovery(self._tmpdir)
@@ -569,11 +607,18 @@ class InstallStagingLedger:
self._models_path = models_path
self._logger = logger
- def create_staging(self, source: str) -> InstallStaging:
+ def create_staging(
+ self,
+ source: str,
+ revision: Optional[str] = None,
+ reusable: Callable[[Optional[str]], bool] = lambda hf_endpoint: True,
+ ) -> InstallStaging:
"""Return an unclaimed handle on a staging directory for a new remote install of source.
- Reuses the newest resumable staging directory left by an earlier install of the same source, so its partial
- downloads resume; otherwise creates a new one.
+ Reuses the newest resumable staging directory left by an earlier install of the same source pinned to the same
+ ``revision``, so its partial downloads resume; otherwise creates a new one. Staged files from another revision
+ would be accepted by size and mixed into the install. ``reusable`` gets each candidate's recorded
+ ``hf_endpoint`` and may refuse it.
"""
candidates: list[tuple[str, Path]] = []
for tmpdir in self._models_path.glob(f"{TMPDIR_PREFIX}*"):
@@ -582,6 +627,8 @@ class InstallStagingLedger:
marker = self._read_marker(tmpdir)
if not marker or marker.get("source") != source or marker.get("recovery_required") is True:
continue
+ if _marker_revision(marker) != revision or not reusable(_marker_hf_endpoint(marker)):
+ continue
if marker.get("status") in {status.value for status in _TERMINAL_STATUSES}:
continue
candidates.append((marker.get("updated_at", ""), tmpdir))
@@ -801,6 +848,8 @@ class InstallStagingLedger:
access_token=marker.get("access_token"),
config_in=marker.get("config_in"),
files=[_restored_file_entry(entry) for entry in marker.get("files") or []],
+ revision=_marker_revision(marker),
+ hf_endpoint=_marker_hf_endpoint(marker),
)
def _read_marker(self, tmpdir: Path) -> Optional[dict[str, Any]]:
diff --git a/invokeai/app/services/model_install/model_install_base.py b/invokeai/app/services/model_install/model_install_base.py
index 64846d506b..8f8a077e50 100644
--- a/invokeai/app/services/model_install/model_install_base.py
+++ b/invokeai/app/services/model_install/model_install_base.py
@@ -165,8 +165,9 @@ class ModelInstallServiceBase(ABC):
thread and will issue the following events on the event bus:
- model_install_started
+ - model_install_paused
- model_install_error
- - model_install_completed
+ - model_install_complete
The `inplace` flag does not affect the behavior of downloaded
models, which are always moved into the `models` directory.
@@ -197,7 +198,7 @@ class ModelInstallServiceBase(ABC):
"""
@abstractmethod
- def prune_jobs(self) -> None:
+ def prune_jobs(self) -> List[int]:
"""Prune all completed and errored jobs."""
@abstractmethod
@@ -221,28 +222,46 @@ class ModelInstallServiceBase(ABC):
"""Restart a specific file download for a job."""
@abstractmethod
- def wait_for_job(self, job: ModelInstallJob, timeout: int = 0) -> ModelInstallJob:
- """Wait for the indicated job to reach a terminal state.
+ def wait_for_job(self, job: ModelInstallJob, timeout: float = 0) -> ModelInstallJob:
+ """Wait for the indicated job to reach a terminal state or pause.
- This will block until the indicated install job has completed,
- been cancelled, or errored out.
+ This will block until the indicated install job has completed, been cancelled, errored out, or paused.
+ A paused job is returned at once unless a resume or retry of it is being set up, in which case this waits for
+ that to hand the job back to the download queue. A paused job is nonterminal and stays paused until it is
+ resumed or its failed files are retried, so callers must check its status rather than assume the install
+ finished.
:param job: The job to wait on.
:param timeout: Wait up to indicated number of seconds. Raise a TimeoutError if
- the job hasn't completed within the indicated time.
+ the job hasn't finished or paused within the indicated time.
+ """
+
+ @abstractmethod
+ def resume_and_wait_for_job(self, job: ModelInstallJob, timeout: float = 0) -> ModelInstallJob:
+ """Resume the job if it is paused, then wait for it as wait_for_job() does.
+
+ For callers that need the model rather than a report, such as an invocation that installs a missing
+ dependency. A resume refused because the job's previous download is still finishing is retried once that
+ settles, if the job is still paused. A resume refused because another caller is already resuming or
+ retrying the job is not retried: this waits for that attempt's outcome instead. A job whose pinned repository
+ revision is gone is returned in ERROR, as resume_job() leaves it, rather than raising.
+
+ :param job: The job to resume and wait on.
+ :param timeout: Wait up to indicated number of seconds in total. Raise a TimeoutError if
+ the job hasn't finished or paused within the indicated time.
"""
@abstractmethod
def wait_for_installs(self, timeout: int = 0) -> List[ModelInstallJob]:
"""
- Wait for all pending installs to complete.
+ Wait for pending download and install work to quiesce.
- This will block until all pending installs have
- completed, been cancelled, or errored out.
+ Returns the tracked jobs, which may include PAUSED nonterminal jobs after a recoverable download failure.
+ Paused jobs do not block this method; callers must resume or retry them before treating installation as done.
:param timeout: Wait up to indicated number of seconds. Raise an Exception('timeout') if
- installs do not complete within the indicated time. A timeout of zero (the default)
- will block indefinitely until the installs complete.
+ work does not quiesce within the indicated time. A timeout of zero (the default) will block indefinitely until
+ download and install work quiesces.
"""
@abstractmethod
diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.py
index c37c99ba3a..826fc8a98b 100644
--- a/invokeai/app/services/model_install/model_install_common.py
+++ b/invokeai/app/services/model_install/model_install_common.py
@@ -218,6 +218,12 @@ class ModelInstallJob(BaseModel):
_multifile_job: Optional[MultiFileDownloadJob] = PrivateAttr(default=None)
_exception: Optional[Exception] = PrivateAttr(default=None)
_resume_metadata: Optional[dict] = PrivateAttr(default=None)
+ # Repository revision the download is pinned to, so a resume or retry cannot mix files from a newer commit.
+ _source_revision: Optional[str] = PrivateAttr(default=None)
+ # Direct HF file URLs retain the mirror that was trusted when their marker was written.
+ _source_hf_endpoint: Optional[str] = PrivateAttr(default=None)
+ # The pinned revision vanished and the staged files were given up: nothing of this job can be restarted.
+ _pinned_revision_vanished: bool = PrivateAttr(default=False)
_recovery_required: bool = PrivateAttr(default=False)
_cancel_requested: bool = PrivateAttr(default=False)
_install_phase: Optional[str] = PrivateAttr(default=None)
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 64a0315d28..fee4083d4c 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -7,6 +7,7 @@ import gc
import locale
import os
import re
+import ssl
import sys
import threading
import time
@@ -15,14 +16,18 @@ from pathlib import Path
from queue import Empty, Queue
from shutil import copy2, copytree, move, rmtree
from tempfile import mkdtemp
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union
+from urllib.parse import urljoin, urlparse
+import requests
import torch
import yaml
+from huggingface_hub import constants as hf_constants
from huggingface_hub import get_token as hf_get_token
from pydantic.networks import AnyHttpUrl
from pydantic_core import Url
from requests import Session
+from urllib3.util.ssl_match_hostname import CertificateError
from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.app.services.download import (
@@ -33,6 +38,7 @@ from invokeai.app.services.download import (
)
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_install.install_staging_ledger import (
+ INSTALL_MARKER_FILENAME,
InstallStaging,
InstallStagingLedger,
part_resume_metadata,
@@ -56,6 +62,7 @@ from invokeai.app.services.model_install.model_install_common import (
from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelException
from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
from invokeai.app.util.path_safety import is_plain_filename
+from invokeai.app.util.ssrf import UnsafeDownloadURLException
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base
from invokeai.backend.model_manager.configs.external_api import (
ExternalApiModelConfig,
@@ -75,7 +82,13 @@ from invokeai.backend.model_manager.metadata import (
ModelMetadataWithFiles,
RemoteModelFile,
)
-from invokeai.backend.model_manager.metadata.metadata_base import HuggingFaceMetadata
+from invokeai.backend.model_manager.metadata.metadata_base import (
+ HF_METADATA_REQUEST_TIMEOUT_SECONDS,
+ HuggingFaceMetadata,
+ ModelRevisionUnavailableError,
+ is_commit_hash,
+ revision_unavailable_message,
+)
from invokeai.backend.model_manager.search import ModelSearch
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
@@ -94,6 +107,46 @@ if TYPE_CHECKING:
from invokeai.app.services.events.events_base import EventServiceBase
+class _HFFileURL(NamedTuple):
+ """A Hugging Face file URL, `{endpoint}{org}/{repo}/{resolve|blob}/{revision}/{file}`, split into its parts."""
+
+ endpoint: str
+ repo_id: str
+ kind: str # "resolve" or "blob"
+ revision: str # as written in the URL
+ filename: str
+ tail: str # query and fragment
+
+ def with_revision(self, revision: str) -> str:
+ """This file's download URL at `revision`, every other character of the URL unchanged."""
+ return f"{self.endpoint}{self.repo_id}/resolve/{revision}/{self.filename}{self.tail}"
+
+
+# `refs/pr/<n>` and `refs/convert/<name>` are revisions with slashes that the hub accepts unencoded.
+_HF_FILE_PATH = re.compile(
+ r"^([^/?#]+/[^/?#]+)/(resolve|blob)/(refs/pr/\d+|refs/convert/[^/?#]+|[^/?#]+)/([^?#]+)(.*)$", re.DOTALL
+)
+
+
+def _hf_file_url_parts(url: str, trusted_endpoint: Optional[str] = None) -> Optional[_HFFileURL]:
+ """Split a Hugging Face file URL on huggingface.co, the configured HF_ENDPOINT mirror, or `trusted_endpoint` (the
+ endpoint an install recorded for its source); None for any other URL. Unknown hosts are never inferred from their
+ path."""
+ configured = hf_constants.HUGGINGFACE_CO_URL_TEMPLATE.split("{repo_id}", 1)[0]
+ endpoints = ("https://huggingface.co/", "http://huggingface.co/", configured, trusted_endpoint)
+ for endpoint in dict.fromkeys(item for item in endpoints if item):
+ if url[: len(endpoint)].lower() == endpoint.lower() and (match := _HF_FILE_PATH.match(url[len(endpoint) :])):
+ return _HFFileURL(url[: len(endpoint)], *match.groups())
+ return None
+
+
+_HF_HEAD_MAX_REDIRECTS = 5
+
+
+class _DownloadCallbackPendingError(InstallDownloadConflictError):
+ """The job's previous download has ended but its callback has not yet run; a retry once it has can succeed."""
+
+
class _InstallCancelledBeforeTransfer(Exception):
"""Raised when a cancellation request wins before file transfer becomes protected."""
@@ -107,6 +160,9 @@ _MAX_COMBINED_SUBFOLDER_NAME = 96
# stop() waits.
_INSTALL_QUEUE_POLL_SECONDS = 1.0
+# How long wait_for_job() sleeps between status checks when no job-state signal wakes it first.
+_JOB_WAIT_POLL_SECONDS = 5.0
+
# First wait before retrying a move that hit a locked file; each further retry doubles it.
_MOVE_RETRY_DELAY_SECONDS = 0.5
@@ -131,6 +187,52 @@ def _combined_subfolder_name(subfolder_names: List[str]) -> str:
return "_".join(kept) + (f"_and_{remaining}_more" if remaining else "")
+_TRANSIENT_HTTP_STATUSES = frozenset({408, 429})
+
+
+def _is_certificate_failure(excp: BaseException) -> bool:
+ """Return True if a TLS error was caused by the server's certificate failing verification.
+
+ requests and urllib3 wrap the ssl error as an exception argument (requests' and urllib3's SSLError) or as a
+ MaxRetryError's reason.
+ """
+ pending: List[object] = [excp]
+ seen: set[int] = set()
+ while pending:
+ current = pending.pop()
+ if not isinstance(current, BaseException) or id(current) in seen:
+ continue
+ seen.add(id(current))
+ if isinstance(current, (ssl.SSLCertVerificationError, CertificateError)):
+ return True
+ pending.extend((getattr(current, "reason", None), *current.args))
+ return False
+
+
+def _is_transient_download_error(excp: BaseException) -> bool:
+ """Return True for a download failure that a later resume or retry can plausibly get past.
+
+ A paused install waits for someone to resume it, so anything not known to be transient (auth and missing-file
+ responses, a full disk, an unsafe filename, TLS verification) is treated as permanent and errors the install.
+ """
+ if isinstance(excp, requests.exceptions.SSLError) and _is_certificate_failure(excp):
+ return False
+ if isinstance(excp, (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError)):
+ return True
+ if isinstance(excp, requests.HTTPError):
+ if excp.response is None:
+ return False
+ status = excp.response.status_code
+ return status in _TRANSIENT_HTTP_STATUSES or 500 <= status < 600
+ # The download queue promotes a part's `.downloading` sidecar with a rename; something else removing the
+ # sidecar between its size check and that rename raises this. The part is fetched again on retry.
+ return (
+ isinstance(excp, FileNotFoundError)
+ and excp.filename2 is not None
+ and str(excp.filename).endswith(".downloading")
+ )
+
+
class ModelInstallService(ModelInstallServiceBase):
"""class for InvokeAI model installation."""
@@ -197,6 +299,8 @@ class ModelInstallService(ModelInstallServiceBase):
download_parts=job.download_parts,
resume_files=job._resume_metadata,
recovery_required=job._recovery_required,
+ revision=job._source_revision,
+ hf_endpoint=job._source_hf_endpoint or self._hf_endpoint_of(job.source, []),
)
def _requires_recovery(self, job: ModelInstallJob) -> bool:
@@ -278,6 +382,9 @@ class ModelInstallService(ModelInstallServiceBase):
local_path=tmpdir,
)
job._staging = staging
+ job._source_revision = entry.revision
+ # A marker written before endpoints were recorded names none; an endpoint recognized now is recorded.
+ job._source_hf_endpoint = entry.hf_endpoint or self._hf_endpoint_of(source, [])
try:
# Protect paused and completed downloads as soon as they are restored, before any
# later orphan scan can mistake finalized staging files for unregistered models.
@@ -285,9 +392,36 @@ class ModelInstallService(ModelInstallServiceBase):
except InstallCancellationConflictError as e:
self._logger.info(f"Skipping restore of claimed install directory {tmpdir}: {e}")
continue
- if entry.files:
+ # A Hugging Face download can only be resumed if its staged files are known to come from the commit it
+ # resumes from. A marker that names no commit - written before installs were pinned, or pinned to a
+ # branch because the hub reported no commit - may hold files from an older state of a branch that has
+ # since moved; they would be accepted by size or appended to, mixing two commits. They are discarded and
+ # the download starts over, pinned to the commit the resume fetches. Finished downloads are kept: they
+ # need no more files.
+ discard_staging = (
+ not is_commit_hash(job._source_revision)
+ and entry.status not in {InstallStatus.DOWNLOADS_DONE, InstallStatus.RUNNING}
+ and self._is_hf_source(source, job._source_hf_endpoint)
+ )
+ if discard_staging:
+ job._source_revision = None
+ elif entry.files:
job._resume_metadata = {f.get("url"): f for f in entry.files if f.get("url")}
job.status = entry.status
+ if discard_staging:
+ # Before the job is listed, so no resume can start a download into the directory being emptied.
+ self._logger.warning(
+ f"Discarding the partial download of {source_str} in {tmpdir}: the repository revision it came "
+ "from is unknown. It will download again from the beginning."
+ )
+ try:
+ staging.discard_files()
+ self._write_install_marker(job)
+ except Exception as e:
+ # Errored before it is listed, so no resume can reach a job whose staging is being removed.
+ self._fail_restored_install(job, e)
+ self._install_jobs.append(job)
+ continue
self._install_jobs.append(job)
if job.paused:
@@ -304,6 +438,7 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.warning(f"Could not resume install {source_str}: {e}")
job.status = InstallStatus.PAUSED
self._write_install_marker(job, status=InstallStatus.PAUSED)
+ self._signal_job_paused(job)
if self._stop_event.is_set():
return
except Exception as e:
@@ -311,8 +446,157 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.info(f"Leaving interrupted install in {tmpdir} for next startup")
job.status = InstallStatus.PAUSED
return
- self._set_error(job, e)
- staging.discard()
+ self._fail_restored_install(job, e)
+
+ def _fail_restored_install(self, job: ModelInstallJob, error: Exception) -> None:
+ if isinstance(error, ModelRevisionUnavailableError):
+ job._pinned_revision_vanished = True
+ self._set_error(job, error)
+ self._staging_of(job).discard()
+
+ def _is_hf_source(self, source: ModelSource, trusted_endpoint: Optional[str] = None) -> bool:
+ """Whether the source's files come from a Hugging Face repository, whose files change between commits."""
+ if isinstance(source, HFModelSource):
+ return True
+ if isinstance(source, URLModelSource):
+ try:
+ self.get_fetcher_from_url(str(source.url))
+ except ValueError:
+ return _hf_file_url_parts(str(source.url), trusted_endpoint) is not None
+ return True
+ return False
+
+ @staticmethod
+ def _hf_endpoint_of(source: ModelSource, remote_files: List[RemoteModelFile]) -> Optional[str]:
+ """The Hugging Face endpoint a URL source, or else its file URLs, are on now; None if not Hugging Face.
+
+ Recorded with the install, so a later HF_ENDPOINT change cannot hide that its files came from a repository.
+ """
+ if isinstance(source, URLModelSource) and (parts := _hf_file_url_parts(str(source.url))) is not None:
+ return parts.endpoint
+ return next((parts.endpoint for item in remote_files if (parts := _hf_file_url_parts(str(item.url)))), None)
+
+ def _discard_unpinned_hf_staging(self, job: ModelInstallJob) -> bool:
+ """Before a Hugging Face download that is not pinned to a commit is fetched again, delete everything it staged.
+
+ Its branch may have moved since the previous transfer, and nothing tells which commit staged files came from.
+ Returns whether the job was such a download.
+ """
+ if job._source_revision is not None or not self._is_hf_source(job.source, job._source_hf_endpoint):
+ return False
+ if job.download_parts or job._resume_metadata:
+ self._staging_of(job).discard_files()
+ job.download_parts = set()
+ job._resume_metadata = None
+ job.bytes = 0
+ return True
+
+ def _single_hf_file(self, source: ModelSource, trusted_endpoint: Optional[str] = None) -> Optional[_HFFileURL]:
+ """The file URL of a source that names one file of a Hugging Face repository."""
+ if not isinstance(source, URLModelSource):
+ return None
+ try:
+ self.get_fetcher_from_url(str(source.url))
+ except ValueError:
+ return _hf_file_url_parts(str(source.url), trusted_endpoint)
+ return None
+
+ def _download_access_token(
+ self, source: HFModelSource | URLModelSource, trusted_endpoint: Optional[str] = None
+ ) -> Optional[str]:
+ if isinstance(source, HFModelSource):
+ return source.access_token or hf_get_token()
+ if self._single_hf_file(source, trusted_endpoint) is not None:
+ return self._single_hf_file_token(source)
+ return source.access_token
+
+ def _single_hf_file_token(self, source: URLModelSource) -> Optional[str]:
+ """The token a download of this source's file sends: the source's own, else the configured `remote_api_tokens`
+ entry matching the URL as the user gave it. The download URL names a commit instead, so the token is resolved
+ here, once, and sent explicitly."""
+ if source.access_token:
+ return source.access_token
+ for pair in self._app_config.remote_api_tokens or []:
+ if re.search(pair.url_regex, str(source.url)):
+ return pair.token
+ return None
+
+ @staticmethod
+ def _download_revision(
+ metadata: Optional[AnyModelRepoMetadata],
+ remote_files: List[RemoteModelFile],
+ trusted_endpoint: Optional[str] = None,
+ ) -> Optional[str]:
+ """The commit `_remote_files_from_source` pinned these files to, if any; a branch is no pin."""
+ if isinstance(metadata, HuggingFaceMetadata):
+ return metadata.revision if is_commit_hash(metadata.revision) else None
+ if (
+ len(remote_files) == 1
+ and (parts := _hf_file_url_parts(str(remote_files[0].url), trusted_endpoint)) is not None
+ ):
+ return parts.revision if is_commit_hash(parts.revision) else None
+ return None
+
+ def _pin_new_hf_file_download(
+ self, source: ModelSource, remote_files: List[RemoteModelFile], trusted_endpoint: Optional[str] = None
+ ) -> List[RemoteModelFile]:
+ """Point a download of one Hugging Face file, about to start with nothing staged, at the commit its branch or
+ tag names now, so a resume cannot get a newer version of the file.
+
+ The commit comes from the `X-Repo-Commit` header the hub sends for the file, asked of the URL's own host with
+ the token the download will send. A URL that already names a commit is left as it is. If the host names no
+ commit or refuses the request, the download goes ahead unpinned and reports any failure itself; a transient
+ failure raises `ModelMetadataUnavailableError`.
+ """
+ if len(remote_files) != 1 or not isinstance(source, URLModelSource):
+ return remote_files
+ parts = _hf_file_url_parts(str(remote_files[0].url), trusted_endpoint)
+ if parts is None or self._single_hf_file(source, trusted_endpoint) is None or is_commit_hash(parts.revision):
+ return remote_files
+ response = self._head_hf_file(parts.with_revision(parts.revision), self._single_hf_file_token(source))
+ if response is None:
+ return remote_files
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ModelMetadataUnavailableError(f"Could not look up {parts.repo_id}: HTTP {response.status_code}")
+ commit = response.headers.get("X-Repo-Commit")
+ if not is_commit_hash(commit):
+ self._logger.warning(f"Downloading {source} unpinned: its host named no commit for it.")
+ return remote_files
+ assert commit is not None
+ return [remote_files[0].model_copy(update={"url": Url(parts.with_revision(commit))})]
+
+ def _head_hf_file(self, url: str, token: Optional[str]) -> Optional[requests.Response]:
+ """HEAD a Hugging Face file URL as downloads are sent (the download queue's proxy and address policy).
+
+ Like huggingface_hub, follow redirects on the same host until a response names the commit: a renamed repo
+ answers a relative 307, a small file one to its cache, and `http://` a 301 to `https://`. A redirect to another
+ host (the CDN serving large files) is not followed, so the token never leaves the URL's host. None when the
+ address policy refuses the URL; the download then refuses it too.
+ """
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ for _ in range(_HF_HEAD_MAX_REDIRECTS + 1):
+ try:
+ response = self._download_queue.head(url, headers=headers, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)
+ except UnsafeDownloadURLException:
+ return None
+ except requests.RequestException as e:
+ raise ModelMetadataUnavailableError(f"Could not reach {url}") from e
+ location = response.headers.get("Location")
+ if "X-Repo-Commit" in response.headers or not response.is_redirect or not location:
+ return response
+ target = urljoin(url, location)
+ source, destination = urlparse(url), urlparse(target)
+ # The same host and scheme, or an upgrade to https on it; never a downgrade that would send the token
+ # over plain http.
+ same_host = (destination.scheme, destination.hostname, destination.port) == (
+ source.scheme,
+ source.hostname,
+ source.port,
+ ) or (destination.hostname == source.hostname and (source.scheme, destination.scheme) == ("http", "https"))
+ if not same_host:
+ return response
+ url = target
+ return response
def _restore_incomplete_installs_async(self) -> None:
self._restore_completed_event.clear()
@@ -352,9 +636,15 @@ class ModelInstallService(ModelInstallServiceBase):
self._begin_remote_download_operation(job)
previous_status = job.status
try:
- remote_files, metadata = self._remote_files_from_source(job.source)
+ self._discard_unpinned_hf_staging(job)
+ remote_files, metadata = self._remote_files_from_source(job.source, **self._revision_kwargs(job))
if not remote_files:
raise RuntimeError("No remote files are available to download")
+ resume_metadata = self._recorded_resume_metadata(job)
+ if job._source_revision is None and not resume_metadata:
+ # Nothing staged: the download starts over, pinned to the commit the repository is at now.
+ remote_files = self._pin_new_hf_file_download(job.source, remote_files, job._source_hf_endpoint)
+ job._source_revision = self._download_revision(metadata, remote_files, job._source_hf_endpoint)
subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []
job.status = InstallStatus.WAITING
self._enqueue_remote_download(
@@ -366,7 +656,7 @@ class ModelInstallService(ModelInstallServiceBase):
if isinstance(job.source, HFModelSource) and len(subfolders) <= 1
else None,
subfolders=subfolders if len(subfolders) > 1 else None,
- resume_metadata=self._recorded_resume_metadata(job),
+ resume_metadata=resume_metadata,
report_missing_partials=True,
)
except BaseException:
@@ -376,17 +666,25 @@ class ModelInstallService(ModelInstallServiceBase):
if not operation_reserved:
self._end_remote_download_operation(job)
+ @staticmethod
+ def _revision_kwargs(job: ModelInstallJob) -> dict[str, Any]:
+ """`_remote_files_from_source` arguments that keep a job's download on its pinned revision and endpoint."""
+ kwargs: dict[str, Any] = {"revision": job._source_revision}
+ if job._source_hf_endpoint:
+ kwargs["trusted_endpoint"] = job._source_hf_endpoint
+ return kwargs
+
def _begin_remote_download_operation(self, job: ModelInstallJob, *, require_paused: bool = False) -> bool:
"""Serialize resume/restart handoffs and reject replacements before old callbacks finish."""
with self._remote_download_condition:
if self._stop_event.is_set():
raise InstallDownloadConflictError("The model install service is stopping; retry after it starts.")
- download_active = job.id in self._remote_download_operations or any(
- cached_job is job for cached_job in self._download_cache.values()
- )
+ operation_active = job.id in self._remote_download_operations
+ callback_pending = any(cached_job is job for cached_job in self._download_cache.values())
+ download_active = operation_active or callback_pending
if require_paused:
if download_active:
- raise InstallDownloadConflictError(
+ raise (InstallDownloadConflictError if operation_active else _DownloadCallbackPendingError)(
"A previous download is still active; wait for it to finish before resuming or restarting."
)
if not job.paused:
@@ -406,6 +704,13 @@ class ModelInstallService(ModelInstallServiceBase):
with self._remote_download_condition:
self._remote_download_operations.discard(job.id)
self._remote_download_condition.notify_all()
+ self._install_completed_event.set() # wake wait_for_job(), which waits out a resume of a paused job
+
+ def _remote_download_in_progress(self, job: ModelInstallJob) -> bool:
+ with self._lock:
+ return job.id in self._remote_download_operations or any(
+ cached_job is job for cached_job in self._download_cache.values()
+ )
@property
def app_config(self) -> InvokeAIAppConfig: # noqa D102
@@ -917,18 +1222,51 @@ class ModelInstallService(ModelInstallServiceBase):
assert isinstance(jobs[0], ModelInstallJob)
return jobs[0]
- def wait_for_job(self, job: ModelInstallJob, timeout: int = 0) -> ModelInstallJob:
- """Block until the indicated job has reached terminal state, or when timeout limit reached."""
- start = time.time()
- while not job.in_terminal_state:
- if self._install_completed_event.wait(timeout=5): # in case we miss an event
+ def wait_for_job(self, job: ModelInstallJob, timeout: float = 0) -> ModelInstallJob:
+ """Block until the indicated job is terminal or settled in pause, or the timeout limit is reached."""
+ deadline = time.time() + timeout if timeout > 0 else None
+ # A paused job needs a resume or retry from outside, so waiting on it would only run out the timeout. One whose
+ # resume or retry is still being set up, or whose last download callback is still running, has not settled.
+ while not (job.in_terminal_state or (job.paused and not self._remote_download_in_progress(job))):
+ poll = _JOB_WAIT_POLL_SECONDS
+ if deadline is not None:
+ remaining = deadline - time.time()
+ if remaining <= 0:
+ raise TimeoutError("Timeout exceeded")
+ poll = min(poll, remaining)
+ if self._install_completed_event.wait(timeout=poll): # in case we miss an event
self._install_completed_event.clear()
- if timeout > 0 and time.time() - start > timeout:
- raise TimeoutError("Timeout exceeded")
return job
+ def resume_and_wait_for_job(self, job: ModelInstallJob, timeout: float = 0) -> ModelInstallJob: # noqa D102
+ deadline = time.time() + timeout if timeout > 0 else None
+ while True:
+ retry_after_wait = False
+ if job.paused:
+ try:
+ self.resume_job(job)
+ except ModelRevisionUnavailableError:
+ pass # resume_job() errored the job; its error says why and wait_for_job() returns it
+ except _DownloadCallbackPendingError:
+ # Only an unfinished download callback is worth outlasting: wait_for_job() waits for it, and the
+ # resume is tried again if the job is still paused. A stopping service will not accept the resume.
+ retry_after_wait = not self._stop_event.is_set()
+ except InstallDownloadConflictError:
+ # A concurrent resume or restart decides this job's outcome itself, which wait_for_job() waits
+ # for. Any other refusal (a stopping service, a partial file that cannot be deleted) is not
+ # resolved by trying again; the job is returned paused.
+ pass
+ remaining = 0.0
+ if deadline is not None:
+ remaining = deadline - time.time()
+ if remaining <= 0:
+ raise TimeoutError("Timeout exceeded")
+ self.wait_for_job(job, timeout=remaining)
+ if not (retry_after_wait and job.paused):
+ return job
+
def wait_for_installs(self, timeout: int = 0) -> List[ModelInstallJob]: # noqa D102
- """Block until all installation jobs are done."""
+ """Wait for active download and install work; recoverably paused jobs are returned without being completed."""
start = time.time()
restore_timeout = timeout if timeout > 0 else None
if not self._wait_for_restore_complete(timeout=restore_timeout):
@@ -991,12 +1329,15 @@ class ModelInstallService(ModelInstallServiceBase):
return
if job.downloads_done or job.running or self._active_install_job is job:
raise InstallDownloadConflictError("The install has started and cannot be paused.")
+ was_paused = job.paused
job.status = InstallStatus.PAUSED
self._logger.warning(f"Pausing {job.source}")
if dj := job._multifile_job:
for part in dj.download_parts:
self._download_queue.pause_job(part)
self._write_install_marker(job, status=InstallStatus.PAUSED)
+ if not was_paused:
+ self._signal_job_paused(job)
def resume_job(self, job: ModelInstallJob) -> None:
"""Resume a previously paused job."""
@@ -1005,9 +1346,25 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.info(f"Resuming {job.source}")
try:
self._resume_remote_download(job, operation_reserved=True)
+ except ModelRevisionUnavailableError as e:
+ self._fail_install_pinned_to_vanished_revision(job, e)
+ raise
finally:
self._end_remote_download_operation(job)
+ def _fail_install_pinned_to_vanished_revision(self, job: ModelInstallJob, error: Exception) -> None:
+ """Error an install whose pinned repository revision is gone: its staged files can never be completed.
+
+ The staged files are deleted, so the job keeps no download parts: there is nothing left to resume or restart,
+ and a retry has to start a new install from the source, which pins the repository's current commit.
+ """
+ with self._lock:
+ job._pinned_revision_vanished = True
+ job.download_parts = set()
+ job._resume_metadata = None
+ self._set_error(job, error)
+ self._staging_of(job).discard()
+
def restart_failed(self, job: ModelInstallJob) -> None:
"""Restart failed or non-resumable downloads for a job, with every other file missing from staging."""
if self._requires_recovery(job):
@@ -1036,8 +1393,9 @@ class ModelInstallService(ModelInstallServiceBase):
) -> None:
"""Re-queue `requested_file` and every file of the source whose staged file is not on disk.
- Disk decides, not `job.download_parts`: a failed download deletes the whole staging tree, completed files
- included, and a previous restart leaves `download_parts` holding only the files it re-queued.
+ Disk decides, not `job.download_parts`: a download that errored deleted the whole staging tree, completed files
+ included; one that paused after a transient failure kept it; and a previous restart leaves `download_parts`
+ holding only the files it re-queued.
Only the files being restarted lose their partial download: the requested file, or, without one, every part
the backend could not resume; and any part that errored. Every other missing file resumes from its partial
@@ -1046,9 +1404,18 @@ class ModelInstallService(ModelInstallServiceBase):
self._begin_remote_download_operation(job)
previous_status = job.status
try:
- remote_files, metadata = self._remote_files_from_source(source)
+ if job._pinned_revision_vanished:
+ # Its staging was given up; downloading files into it would install an incomplete model.
+ return
+ discarded_unpinned_hf_staging = self._discard_unpinned_hf_staging(job)
+ remote_files, metadata = self._remote_files_from_source(source, **self._revision_kwargs(job))
if requested_file is not None and all(str(rf.url) != requested_file for rf in remote_files):
return
+ if discarded_unpinned_hf_staging:
+ # Nothing is staged any more: every file downloads again, pinned to the commit the repository is at now.
+ remote_files = self._pin_new_hf_file_download(source, remote_files, job._source_hf_endpoint)
+ job._source_revision = self._download_revision(metadata, remote_files, job._source_hf_endpoint)
+ requested_file = None
subfolders = source.subfolders if isinstance(source, HFModelSource) else []
subfolder = source.subfolder if isinstance(source, HFModelSource) and len(subfolders) <= 1 else None
subfolders_arg = subfolders if len(subfolders) > 1 else None
@@ -1081,20 +1448,29 @@ class ModelInstallService(ModelInstallServiceBase):
subfolders=subfolders_arg,
resume_metadata=self._recorded_resume_metadata(job),
restart_from_zero=restart_from_zero,
+ # A paused install kept its staging, so a partial missing from it vanished; an errored one deleted it.
+ report_missing_partials=previous_status == InstallStatus.PAUSED,
)
- except BaseException:
+ except BaseException as e:
job.status = previous_status
+ if isinstance(e, ModelRevisionUnavailableError):
+ self._fail_install_pinned_to_vanished_revision(job, e)
raise
finally:
self._end_remote_download_operation(job)
- def prune_jobs(self) -> None:
+ def prune_jobs(self) -> List[int]:
"""Prune all completed and errored jobs."""
# Filter and rebind under the condition. Unlocked, a registration made by a concurrent import_model()
# between the two would be dropped, leaving a live install invisible to the duplicate check. Rebind rather
# than mutating in place so that readers already iterating the old list are not silently truncated.
with self._install_condition:
- self._install_jobs = [x for x in self._install_jobs if not x.in_terminal_state]
+ pruned = []
+ retained = []
+ for job in self._install_jobs:
+ (pruned if job.in_terminal_state else retained).append(job)
+ self._install_jobs = retained
+ return [job.id for job in pruned]
def _migrate_yaml(self) -> None:
db_models = self.record_store.all_models()
@@ -1252,11 +1628,21 @@ class ModelInstallService(ModelInstallServiceBase):
return lock
def _remote_files_from_source(
- self, source: ModelSource
+ self,
+ source: ModelSource,
+ revision: Optional[str] = None,
+ trusted_endpoint: Optional[str] = None,
) -> Tuple[List[RemoteModelFile], Optional[AnyModelRepoMetadata]]:
+ """List the files to download for a remote source, from repository `revision` when one is given.
+
+ Without a revision, Hugging Face file URLs name the commit the repository is at now, never a branch, so the
+ files of one install all come from one commit however often it is resumed or retried.
+ """
metadata = None
if isinstance(source, HFModelSource):
- metadata = HuggingFaceMetadataFetch(self._session).from_id(source.repo_id, source.variant)
+ metadata = HuggingFaceMetadataFetch(self._session).from_id(
+ source.repo_id, source.variant, revision, pin_to_commit=True
+ )
assert isinstance(metadata, ModelMetadataWithFiles)
# Use subfolders property which handles '+' separated multiple subfolders
subfolders = source.subfolders
@@ -1274,16 +1660,40 @@ class ModelInstallService(ModelInstallServiceBase):
try:
fetcher = self.get_fetcher_from_url(str(source.url))
kwargs: dict[str, Any] = {"session": self._session}
- metadata = fetcher(**kwargs).from_url(source.url)
+ metadata = fetcher(**kwargs).from_url(source.url, revision=revision, pin_to_commit=True)
assert isinstance(metadata, ModelMetadataWithFiles)
return metadata.download_urls(session=self._session), metadata
except ValueError:
pass
- return [RemoteModelFile(url=self._normalize_huggingface_blob_url(source.url), path=Path("."), size=0)], None
+ file_url = self._normalize_huggingface_blob_url(source.url, trusted_endpoint)
+ parts = _hf_file_url_parts(str(file_url), trusted_endpoint)
+ if revision is not None and parts is not None and is_commit_hash(revision):
+ file_url = self._pinned_hf_file_url(source, parts, revision)
+ return [RemoteModelFile(url=file_url, path=Path("."), size=0)], None
raise Exception(f"No files associated with {source}")
+ def _pinned_hf_file_url(self, source: URLModelSource, parts: _HFFileURL, commit: str) -> Url:
+ """The download URL of a Hugging Face file at the commit its install is pinned to.
+
+ A commit the hub reports gone (404 with `X-Error-Code` `EntryNotFound` or `RevisionNotFound`) raises
+ `ModelRevisionUnavailableError`. Nothing else is decided here - not a refusal, not a 404 without that code
+ (from a mirror or proxy), not a failed request: the download reports those itself, and keeps its staged files.
+ """
+ url = parts.with_revision(commit)
+ try:
+ response = self._head_hf_file(url, self._single_hf_file_token(source))
+ except ModelMetadataUnavailableError:
+ return Url(url)
+ if (
+ response is not None
+ and response.status_code == 404
+ and response.headers.get("X-Error-Code") in {"EntryNotFound", "RevisionNotFound"}
+ ):
+ raise ModelRevisionUnavailableError(revision_unavailable_message(parts.repo_id, commit))
+ return Url(url)
+
def _guess_source(self, source: str) -> ModelSource:
"""Turn a source string into a ModelSource object."""
variants = "|".join(ModelRepoVariant.__members__.values())
@@ -1725,7 +2135,7 @@ class ModelInstallService(ModelInstallServiceBase):
source=source,
config=config,
metadata=metadata,
- remote_files=remote_files,
+ remote_files=self._pin_new_hf_file_download(source, remote_files),
)
def _import_external_model(
@@ -1752,7 +2162,18 @@ class ModelInstallService(ModelInstallServiceBase):
) -> ModelInstallJob:
if len(remote_files) == 0:
raise ValueError(f"{source}: No downloadable files found")
- staging = self._ledger.create_staging(str(source))
+ source_hf_endpoint = self._hf_endpoint_of(source, remote_files)
+ revision = self._download_revision(metadata, remote_files, source_hf_endpoint)
+ # Hugging Face staging is reused only from the same commit: a branch moves, so files staged from it may be
+ # older than the ones this install would download. A staging directory's recorded endpoint still identifies
+ # it as Hugging Face staging after HF_ENDPOINT changes.
+ staging = self._ledger.create_staging(
+ str(source),
+ revision,
+ reusable=lambda staged_endpoint: (
+ is_commit_hash(revision) or not self._is_hf_source(source, staged_endpoint or source_hf_endpoint)
+ ),
+ )
assert staging.tmpdir is not None
install_job = ModelInstallJob(
id=self._next_id(),
@@ -1764,6 +2185,8 @@ class ModelInstallService(ModelInstallServiceBase):
total_bytes=0,
)
install_job._staging = staging
+ install_job._source_hf_endpoint = source_hf_endpoint
+ install_job._source_revision = revision
# Handle multiple subfolders for HFModelSource
subfolders = source.subfolders if isinstance(source, HFModelSource) else []
@@ -1797,8 +2220,9 @@ class ModelInstallService(ModelInstallServiceBase):
reported as restarted from scratch. The URLs in `restart_from_zero` start over at the caller's request.
With `report_missing_partials`, a part that had started (its recorded download path is set) but has neither a
- partial nor a finished file is reported as restarted from scratch too. A resume sets it; a restart after an
- error does not, as the error deleted the staging folder.
+ partial nor a finished file is reported as restarted from scratch too. A resume sets it, and so does a restart of
+ a paused install, whose staging folder was kept; a restart after an error does not, as the error deleted the
+ staging folder.
"""
previous_source_metadata = job.source_metadata
previous_status = job.status
@@ -1822,7 +2246,7 @@ class ModelInstallService(ModelInstallServiceBase):
# The source holds only a token sent with the install. The Hugging Face login is read on every
# (re)queue so a retry after logging in uses it; it is never copied onto the source, which the
# install marker persists and a resubmit sends back as an explicit token.
- access_token=source.access_token or (hf_get_token() if isinstance(source, HFModelSource) else None),
+ access_token=self._download_access_token(source, job._source_hf_endpoint),
submit_job=False, # Important! Don't submit the job until we have set our _download_cache dict
)
resume_metadata = resume_metadata or {}
@@ -2100,6 +2524,7 @@ class ModelInstallService(ModelInstallServiceBase):
queued = False
with self._lock:
if install_job := self._download_cache.pop(download_job.id, None):
+ self._install_completed_event.set() # wake wait_for_job(), which waits out this callback
if install_job.cancelled:
self._discard_cancelled_staging(install_job)
elif install_job.paused:
@@ -2123,17 +2548,62 @@ class ModelInstallService(ModelInstallServiceBase):
# Let other threads know that the number of downloads has changed.
self._downloads_changed_event.set()
+ def _staging_has_recoverable_data(self, job: ModelInstallJob) -> bool:
+ """Return True if the staging tree holds downloaded bytes a resume would keep: a completed file, or a partial
+ file the resume would continue.
+
+ This reads the disk rather than the current download's parts: a retry enqueues only the files that had not
+ finished, so its parts do not know about the ones completed by an earlier attempt. A partial counts only with
+ a recorded validator its server has not refused, since a resume deletes any other partial and starts over.
+ Empty files are skipped because they cost nothing to fetch again.
+ """
+ tmpdir = self._staging_of(job).tmpdir
+ if tmpdir is None:
+ return False
+ resumable_partials = {
+ in_progress_path(Path(meta["download_path"])).resolve()
+ for meta in self._recorded_resume_metadata(job).values()
+ if meta.get("download_path")
+ and (meta.get("etag") or meta.get("last_modified"))
+ and not meta.get("resume_refused")
+ }
+ for root, _dirs, files in os.walk(tmpdir):
+ for name in files:
+ if name == INSTALL_MARKER_FILENAME or name.startswith(f"{INSTALL_MARKER_FILENAME}."):
+ continue
+ path = Path(root, name)
+ try:
+ if path.stat().st_size == 0:
+ continue
+ except OSError:
+ continue
+ if not name.endswith(".downloading") or path.resolve() in resumable_partials:
+ return True
+ return False
+
def _download_error_callback(self, download_job: MultiFileDownloadJob, excp: Optional[Exception] = None) -> None:
with self._lock:
if install_job := self._download_cache.pop(download_job.id, None):
+ self._install_completed_event.set() # wake wait_for_job(), which waits out this callback
assert excp is not None
+ staging = self._staging_of(install_job)
if install_job.cancelled:
self._discard_cancelled_staging(install_job)
elif install_job.paused:
# Preserve the explicit pause even if an already-terminal download reports its error late.
self._write_install_marker(install_job, status=InstallStatus.PAUSED)
if self._stop_event.is_set():
- self._staging_of(install_job).release_claim()
+ staging.release_claim()
+ elif _is_transient_download_error(excp) and self._staging_has_recoverable_data(install_job):
+ # A transient part failure must not discard completed parts and resumable partials.
+ # Mirror the pause path: mark the install paused and persist the marker so the tmpdir
+ # survives the startup dangling-dir sweep and restart_failed()/resume_job() can recover
+ # the failed parts. The failed part keeps its error in download_parts.
+ install_job.status = InstallStatus.PAUSED
+ self._write_install_marker(install_job, status=InstallStatus.PAUSED)
+ self._signal_job_paused(install_job)
+ if self._stop_event.is_set():
+ staging.release_claim()
else:
self._set_error(install_job, excp)
self._download_queue.cancel_job(download_job)
@@ -2145,13 +2615,17 @@ class ModelInstallService(ModelInstallServiceBase):
def _download_cancelled_callback(self, download_job: MultiFileDownloadJob) -> None:
with self._lock:
if install_job := self._download_cache.pop(download_job.id, None):
+ self._install_completed_event.set() # wake wait_for_job(), which waits out this callback
self._downloads_changed_event.set()
if install_job.cancelled:
self._discard_cancelled_staging(install_job)
return
if install_job.paused or any(part.resume_required for part in download_job.download_parts):
+ was_paused = install_job.paused
install_job.status = InstallStatus.PAUSED
self._write_install_marker(install_job, status=InstallStatus.PAUSED)
+ if not was_paused:
+ self._signal_job_paused(install_job)
# A user-paused install remains protected from orphan cleanup until resumed or cancelled.
# Shutdown releases only after the download queue has quiesced this callback.
if self._stop_event.is_set():
@@ -2200,6 +2674,11 @@ class ModelInstallService(ModelInstallServiceBase):
if self._event_bus:
self._event_bus.emit_model_install_downloads_complete(job)
+ def _signal_job_paused(self, job: ModelInstallJob) -> None:
+ if self._event_bus:
+ self._event_bus.emit_model_install_paused(job)
+ self._install_completed_event.set() # wake wait_for_job(), which returns paused jobs
+
def _signal_job_completed(self, job: ModelInstallJob) -> None:
job.status = InstallStatus.COMPLETED
assert job.config_out
@@ -2218,6 +2697,7 @@ class ModelInstallService(ModelInstallServiceBase):
assert job.error_type is not None
assert job.error is not None
self._event_bus.emit_model_install_error(job)
+ self._install_completed_event.set() # wake wait_for_job()
def _signal_job_cancelled(self, job: ModelInstallJob) -> None:
self._logger.info(f"Model install canceled: {job.source}")
@@ -2238,13 +2718,9 @@ class ModelInstallService(ModelInstallServiceBase):
raise ValueError(f"Unsupported model source: '{url}'")
@staticmethod
- def _normalize_huggingface_blob_url(url: AnyHttpUrl) -> Url:
- """Convert Hugging Face file page URLs to direct download URLs."""
- return Url(
- re.sub(
- r"^(https?://huggingface\.co/[^/]+/[^/]+)/blob/([^?#]+)([?#].*)?$",
- r"\1/resolve/\2\3",
- str(url),
- flags=re.IGNORECASE,
- )
- )
+ def _normalize_huggingface_blob_url(url: AnyHttpUrl, trusted_endpoint: Optional[str] = None) -> Url:
+ """Convert Hugging Face file page URLs (on huggingface.co or the configured mirror) to download URLs."""
+ parts = _hf_file_url_parts(str(url), trusted_endpoint)
+ if parts is None or parts.kind != "blob":
+ return Url(str(url))
+ return Url(parts.with_revision(parts.revision))
diff --git a/invokeai/backend/model_manager/metadata/__init__.py b/invokeai/backend/model_manager/metadata/__init__.py
index 2aa371e2e0..1acd596248 100644
--- a/invokeai/backend/model_manager/metadata/__init__.py
+++ b/invokeai/backend/model_manager/metadata/__init__.py
@@ -24,6 +24,7 @@ from invokeai.backend.model_manager.metadata.metadata_base import (
HuggingFaceMetadata,
ModelMetadataUnavailableError,
ModelMetadataWithFiles,
+ ModelRevisionUnavailableError,
RemoteModelFile,
UnknownMetadataException,
)
@@ -35,6 +36,7 @@ __all__ = [
"HuggingFaceMetadataFetch",
"ModelMetadataFetchBase",
"ModelMetadataUnavailableError",
+ "ModelRevisionUnavailableError",
"BaseMetadata",
"ModelMetadataWithFiles",
"RemoteModelFile",
diff --git a/invokeai/backend/model_manager/metadata/fetch/fetch_base.py b/invokeai/backend/model_manager/metadata/fetch/fetch_base.py
index dc9befa230..7be47ecf8e 100644
--- a/invokeai/backend/model_manager/metadata/fetch/fetch_base.py
+++ b/invokeai/backend/model_manager/metadata/fetch/fetch_base.py
@@ -37,22 +37,35 @@ class ModelMetadataFetchBase(ABC):
pass
@abstractmethod
- def from_url(self, url: AnyHttpUrl) -> AnyModelRepoMetadata:
+ def from_url(
+ self, url: AnyHttpUrl, revision: Optional[str] = None, pin_to_commit: bool = False
+ ) -> AnyModelRepoMetadata:
"""
Given a URL to a model repository, return a ModelMetadata object.
+ :param revision: Fetch this repository revision rather than the current default.
+ :param pin_to_commit: Without `revision`, name the current commit in file URLs rather than the branch.
+
This method will raise a `UnknownMetadataException`
in the event that the requested model metadata is not found at the provided location.
"""
pass
@abstractmethod
- def from_id(self, id: str, variant: Optional[ModelRepoVariant] = None) -> AnyModelRepoMetadata:
+ def from_id(
+ self,
+ id: str,
+ variant: Optional[ModelRepoVariant] = None,
+ revision: Optional[str] = None,
+ pin_to_commit: bool = False,
+ ) -> AnyModelRepoMetadata:
"""
Given an ID for a model, return a ModelMetadata object.
:param id: An ID.
:param variant: A model variant from the ModelRepoVariant enum.
+ :param revision: Fetch this repository revision rather than the current default.
+ :param pin_to_commit: Without `revision`, name the current commit in file URLs rather than the branch.
This method will raise a `UnknownMetadataException`
in the event that the requested model's metadata is not found at the provided id.
diff --git a/invokeai/backend/model_manager/metadata/fetch/huggingface.py b/invokeai/backend/model_manager/metadata/fetch/huggingface.py
index 7b49299524..2ddef4c0e6 100644
--- a/invokeai/backend/model_manager/metadata/fetch/huggingface.py
+++ b/invokeai/backend/model_manager/metadata/fetch/huggingface.py
@@ -16,6 +16,7 @@ import re
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
+from urllib.parse import quote
import httpx
import requests
@@ -30,9 +31,11 @@ from invokeai.backend.model_manager.metadata.metadata_base import (
AnyModelRepoMetadata,
HuggingFaceMetadata,
ModelMetadataUnavailableError,
+ ModelRevisionUnavailableError,
RemoteModelFile,
UnknownMetadataException,
is_transient_hf_http_error,
+ revision_unavailable_message,
)
from invokeai.backend.model_manager.taxonomy import ModelRepoVariant
@@ -58,12 +61,12 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
metadata = HuggingFaceMetadata.model_validate_json(json)
return metadata
- def _model_info_via_session(self, repo_id: str, variant: Optional[ModelRepoVariant] = None) -> SimpleNamespace:
+ def _model_info_via_session(self, repo_id: str, revision: Optional[str] = None) -> SimpleNamespace:
"""Fetch model info using the injected requests session (for testing/custom backends)."""
params = {"blobs": "true"}
url = f"https://huggingface.co/api/models/{repo_id}"
- if variant is not None:
- url += f"/revision/{variant}"
+ if revision is not None:
+ url += f"/revision/{quote(revision, safe='')}"
resp = self._requests.get(url, params=params, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)
if resp.status_code == 404:
error_response = httpx.Response(
@@ -72,9 +75,9 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
request=httpx.Request("GET", str(resp.url)),
)
error_code = resp.headers.get("X-Error-Code", "")
- if error_code == "RevisionNotFound" or (variant is not None):
+ if error_code == "RevisionNotFound" or (revision is not None):
raise RevisionNotFoundError(
- f"Revision '{variant}' not found for repo '{repo_id}'.", response=error_response
+ f"Revision '{revision}' not found for repo '{repo_id}'.", response=error_response
)
raise RepositoryNotFoundError(f"Repository '{repo_id}' not found.", response=error_response)
resp.raise_for_status()
@@ -89,44 +92,66 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
lfs=s.get("lfs"),
)
)
- return SimpleNamespace(id=data["id"], siblings=siblings)
-
- def from_id(self, id: str, variant: Optional[ModelRepoVariant] = None) -> AnyModelRepoMetadata:
- """Return a HuggingFaceMetadata object given the model's repo_id."""
- # Little loop which tries fetching a revision corresponding to the selected variant.
- # If not available, then set variant to None and get the default.
- # If this too fails, raise exception.
-
- model_info = None
-
+ return SimpleNamespace(id=data["id"], siblings=siblings, sha=data.get("sha"))
+
+ def _model_info(self, repo_id: str, revision: Optional[str]) -> SimpleNamespace:
+ try:
+ # Use the injected session when provided (supports testing with mock adapters).
+ # Otherwise use HfApi which uses httpx internally.
+ if self._has_custom_session:
+ return self._model_info_via_session(repo_id, revision)
+ return HfApi().model_info(
+ repo_id=repo_id,
+ files_metadata=True,
+ revision=revision,
+ timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS,
+ )
+ # ConnectionError includes huggingface_hub's OfflineModeIsEnabled (HF_HUB_OFFLINE=1).
+ except (requests.RequestException, httpx.TransportError, ConnectionError) 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:
+ raise
+ except HfHubHTTPError as e:
+ if is_transient_hf_http_error(e):
+ raise ModelMetadataUnavailableError(f"Could not fetch Hugging Face metadata for '{repo_id}'") from e
+ raise
+
+ def from_id(
+ self,
+ id: str,
+ variant: Optional[ModelRepoVariant] = None,
+ revision: Optional[str] = None,
+ pin_to_commit: bool = False,
+ ) -> AnyModelRepoMetadata:
+ """Return a HuggingFaceMetadata object given the model's repo_id.
+
+ Without `revision`, the files come from the branch named by `variant` if the repo has one, else from the
+ default branch, and their URLs name that branch, as users and model records know them. `pin_to_commit`
+ makes the URLs name the commit the branch points to now instead, so a download resumed later cannot mix in
+ files from a newer commit. With `revision`, the files and URLs come from that revision.
+ """
# Handling for our special syntax - we only want the base HF `org/repo` here.
repo_id = id.split("::")[0] or id
- while not model_info:
+
+ if revision is not None:
try:
- # Use the injected session when provided (supports testing with mock adapters).
- # Otherwise use HfApi which uses httpx internally.
- 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,
- 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
+ model_info = self._model_info(repo_id, revision)
+ except RevisionNotFoundError as e:
+ raise ModelRevisionUnavailableError(revision_unavailable_message(repo_id, revision)) from e
+ url_revision = revision
+ else:
+ # Try the revision named by the selected variant; if the repo has none, fall back to the default branch.
+ try:
+ model_info = self._model_info(repo_id, variant)
except RevisionNotFoundError:
if variant is None:
raise
- else:
- variant = None
- except HfHubHTTPError as e:
- if is_transient_hf_http_error(e):
- raise ModelMetadataUnavailableError(f"Could not fetch Hugging Face metadata for '{repo_id}'") from e
- raise
+ variant = None
+ model_info = self._model_info(repo_id, None)
+ branch = variant or "main"
+ url_revision = (getattr(model_info, "sha", None) or branch) if pin_to_commit else branch
files: list[RemoteModelFile] = []
@@ -137,7 +162,7 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
assert s.size is not None
files.append(
RemoteModelFile(
- url=hf_hub_url(repo_id, s.rfilename, revision=variant or "main"),
+ url=hf_hub_url(repo_id, s.rfilename, revision=url_revision),
path=Path(name, s.rfilename),
size=s.size,
sha256=s.lfs.get("sha256") if s.lfs else None,
@@ -166,7 +191,7 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
]
)
- return HuggingFaceMetadata(
+ metadata = HuggingFaceMetadata(
id=model_info.id,
name=name,
files=files,
@@ -174,8 +199,12 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
is_diffusers=is_diffusers,
ckpt_urls=ckpt_urls,
)
+ metadata._revision = url_revision
+ return metadata
- def from_url(self, url: AnyHttpUrl) -> AnyModelRepoMetadata:
+ def from_url(
+ self, url: AnyHttpUrl, revision: Optional[str] = None, pin_to_commit: bool = False
+ ) -> AnyModelRepoMetadata:
"""
Return a HuggingFaceMetadata object given the model's web page URL.
@@ -183,6 +212,6 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):
"""
if match := re.match(HF_MODEL_RE, str(url), re.IGNORECASE):
repo_id = match.group(1)
- return self.from_id(repo_id)
+ return self.from_id(repo_id, revision=revision, pin_to_commit=pin_to_commit)
else:
raise UnknownMetadataException(f"'{url}' does not look like a HuggingFace model page")
diff --git a/invokeai/backend/model_manager/metadata/metadata_base.py b/invokeai/backend/model_manager/metadata/metadata_base.py
index d5dc41825d..b2566ef866 100644
--- a/invokeai/backend/model_manager/metadata/metadata_base.py
+++ b/invokeai/backend/model_manager/metadata/metadata_base.py
@@ -12,12 +12,14 @@ versions of these fields are intended to be kept in sync with the
remote repo.
"""
+import re
from pathlib import Path
-from typing import List, Literal, Optional, Union
+from typing import Any, List, Literal, Optional, Union
+from urllib.parse import unquote, urlparse
from huggingface_hub import hf_hub_url
from huggingface_hub.errors import HfHubHTTPError
-from pydantic import BaseModel, Field, TypeAdapter
+from pydantic import BaseModel, Field, PrivateAttr, TypeAdapter
from pydantic.networks import AnyHttpUrl
from requests import HTTPError, RequestException
from requests.sessions import Session
@@ -37,6 +39,23 @@ class ModelMetadataUnavailableError(Exception):
"""Raised when a remote metadata request fails transiently."""
+class ModelRevisionUnavailableError(Exception):
+ """Raised when the repository revision an install is pinned to no longer exists."""
+
+
+def is_commit_hash(revision: Optional[str]) -> bool:
+ """Whether `revision` is a full Git commit hash, the only kind of revision whose files never change."""
+ return revision is not None and re.fullmatch(r"[0-9a-fA-F]{40}", revision) is not None
+
+
+def revision_unavailable_message(repo_id: str, revision: str) -> str:
+ return (
+ f"The files of '{repo_id}' changed after this download started: revision '{revision}' is no longer available "
+ "on Hugging Face, so the downloaded files cannot be completed. Start the install again to download the "
+ "current version."
+ )
+
+
def is_transient_hf_http_error(error: HfHubHTTPError | HTTPError) -> bool:
"""Return whether an HF HTTP response can reasonably succeed if retried later."""
status_code = error.response.status_code if error.response is not None else None
@@ -92,6 +111,11 @@ class ModelMetadataWithFiles(ModelMetadataBase):
return self.files
+# The revision segment of a Hugging Face file URL path: the first `/resolve/{revision}/` after an org and repo segment,
+# behind any path prefix a mirror endpoint adds. An encoded revision (`refs%2Fpr%2F1`) is one segment.
+_RESOLVE_PATH = re.compile(r"^(?:/.*?)??/[^/]+/[^/]+/resolve/([^/]+)/")
+
+
class HuggingFaceMetadata(ModelMetadataWithFiles):
"""Extended metadata fields provided by HuggingFace."""
@@ -102,6 +126,25 @@ class HuggingFaceMetadata(ModelMetadataWithFiles):
ckpt_urls: Optional[List[AnyHttpUrl]] = Field(
description="URLs for all checkpoint format models in the metadata", default=None
)
+ # The revision the file URLs name: a branch, or the commit hash when the fetch pinned it. Private so the API
+ # schema is unchanged.
+ _revision: Optional[str] = PrivateAttr(default=None)
+
+ def model_post_init(self, context: Any) -> None:
+ # A private attribute is not serialized, so metadata read back from JSON recovers the revision from its file
+ # URLs (`.../{org}/{repo}/resolve/{revision}/...` on any endpoint); otherwise model_index.json would be read
+ # from the default branch while the files come from the pinned commit. The URLs' repo is not compared with
+ # `id`: they name the repo as it was asked for, `id` as the hub reports it, which can differ in case or after
+ # a rename.
+ super().model_post_init(context)
+ revisions = {match.group(1) for f in self.files if (match := _RESOLVE_PATH.match(urlparse(str(f.url)).path))}
+ if len(revisions) == 1:
+ self._revision = unquote(revisions.pop())
+
+ @property
+ def revision(self) -> Optional[str]:
+ """The revision the file URLs name, or None if this metadata was not fetched from the repository."""
+ return self._revision
def download_urls(
self,
@@ -134,7 +177,12 @@ class HuggingFaceMetadata(ModelMetadataWithFiles):
# the next step reads model_index.json to determine which subdirectories belong
# 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)
+ url = hf_hub_url(
+ self.id,
+ filename="model_index.json",
+ subfolder=str(subfolder) if subfolder else None,
+ revision=self._revision,
+ )
try:
resp = session.get(url, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)
resp.raise_for_status()
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 8c219acf01..cb42543e7e 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -4523,16 +4523,19 @@
],
"responses": {
"200": {
- "description": "Successful Response",
+ "description": "IDs of completed and errored jobs that were pruned",
"content": {
"application/json": {
- "schema": {}
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "integer"
+ },
+ "title": "Response Prune Model Install Jobs"
+ }
}
}
},
- "204": {
- "description": "All completed and errored jobs have been pruned"
- },
"400": {
"description": "Bad request"
}
@@ -88584,6 +88587,51 @@
"title": "ModelInstallJob",
"description": "Object that tracks the current status of an install request."
},
+ "ModelInstallPausedEvent": {
+ "description": "Emitted when a model install is paused and can be resumed.",
+ "properties": {
+ "timestamp": {
+ "description": "The timestamp of the event",
+ "title": "Timestamp",
+ "type": "integer"
+ },
+ "id": {
+ "description": "The ID of the install job",
+ "title": "Id",
+ "type": "integer"
+ },
+ "source": {
+ "description": "Source of the model; local path, repo_id or url",
+ "discriminator": {
+ "mapping": {
+ "external": "#/components/schemas/ExternalModelSource",
+ "hf": "#/components/schemas/HFModelSource",
+ "local": "#/components/schemas/LocalModelSource",
+ "url": "#/components/schemas/URLModelSource"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/LocalModelSource"
+ },
+ {
+ "$ref": "#/components/schemas/HFModelSource"
+ },
+ {
+ "$ref": "#/components/schemas/URLModelSource"
+ },
+ {
+ "$ref": "#/components/schemas/ExternalModelSource"
+ }
+ ],
+ "title": "Source"
+ }
+ },
+ "required": ["timestamp", "id", "source"],
+ "title": "ModelInstallPausedEvent",
+ "type": "object"
+ },
"ModelInstallStartedEvent": {
"description": "Event model for model_install_started",
"properties": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index e4d311e8d4..ce3e700a89 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -37925,6 +37925,27 @@ export type components = {
*/
error_traceback?: string | null;
};
+ /**
+ * ModelInstallPausedEvent
+ * @description Emitted when a model install is paused and can be resumed.
+ */
+ ModelInstallPausedEvent: {
+ /**
+ * Timestamp
+ * @description The timestamp of the event
+ */
+ timestamp: number;
+ /**
+ * Id
+ * @description The ID of the install job
+ */
+ id: number;
+ /**
+ * Source
+ * @description Source of the model; local path, repo_id or url
+ */
+ source: components["schemas"]["LocalModelSource"] | components["schemas"]["HFModelSource"] | components["schemas"]["URLModelSource"] | components["schemas"]["ExternalModelSource"];
+ };
/**
* ModelInstallStartedEvent
* @description Event model for model_install_started
@@ -55744,22 +55765,15 @@ export interface operations {
};
requestBody?: never;
responses: {
- /** @description Successful Response */
+ /** @description IDs of completed and errored jobs that were pruned */
200: {
headers: {
[name: string]: unknown;
};
content: {
- "application/json": unknown;
+ "application/json": number[];
};
};
- /** @description All completed and errored jobs have been pruned */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
/** @description Bad request */
400: {
headers: {
diff --git a/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx
index b2bad4c386..56ba239260 100644
--- a/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx
+++ b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx
@@ -39,6 +39,7 @@ import {
import type { ModelInstallJob, ModelInstallStatus } from 'services/api/types';
import { $isConnected } from 'services/events/stores';
+import { canResumeDownload, describeDownloadPartError, getProblemDownloadParts } from './modelInstallParts';
import { ModelInstallQueueBadge } from './ModelInstallQueueBadge';
type ModelListItemProps = {
@@ -361,9 +362,7 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {
return '';
}, [displayStatus, installJob.bytes, installJob.download_parts, installJob.total_bytes]);
- const restartRequiredParts = useMemo(() => {
- return installJob.download_parts?.filter((part) => part.resume_required || part.status === 'error') ?? [];
- }, [installJob.download_parts]);
+ const restartRequiredParts = useMemo(() => getProblemDownloadParts(installJob), [installJob]);
useEffect(() => {
if (resumeFromScratchShown.current) {
@@ -383,7 +382,7 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {
const hasRestartRequired = isRestartableStatus(displayStatus) && restartRequiredParts.length > 0;
const canPause = displayStatus === 'downloading' || displayStatus === 'waiting';
- const canResume = displayStatus === 'paused' && !hasRestartRequired;
+ const canResume = displayStatus === 'paused' && canResumeDownload(installJob);
const canCancel =
displayStatus === 'downloading' ||
displayStatus === 'waiting' ||
@@ -468,8 +467,8 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {
<Badge colorScheme={isResumeRequired ? 'orange' : 'red'} fontSize="10px">
{isResumeRequired ? t('modelManager.restartRequired') : t('queue.failed')}
</Badge>
- <Text fontSize="xs" color="warning.400">
- {isResumeRequired ? t('modelManager.resumeRefused') : t('queue.failed')}
+ <Text fontSize="xs" color="warning.400" noOfLines={2} wordBreak="break-word">
+ {isResumeRequired ? t('modelManager.resumeRefused') : describeDownloadPartError(part)}
</Text>
<IconButton
size="xs"
@@ -500,7 +499,7 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {
</Tooltip>
)}
<ModelInstallQueueBadge status={displayStatus} label={hasVisibleError} />
- {hasRestartRequired && (
+ {hasRestartRequired && !canResume && (
<Tooltip label={t('modelManager.restartRequiredTooltip')}>
<Box>
<Badge colorScheme="red">{t('modelManager.restartRequired')}</Badge>
diff --git a/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.test.ts b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.test.ts
new file mode 100644
index 0000000000..3d3c09ca8f
--- /dev/null
+++ b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.test.ts
@@ -0,0 +1,40 @@
+import type { ModelInstallJob } from 'services/api/types';
+import { describe, expect, it } from 'vitest';
+
+import { canResumeDownload, describeDownloadPartError, getProblemDownloadParts } from './modelInstallParts';
+
+type DownloadPart = NonNullable<ModelInstallJob['download_parts']>[number];
+
+const part = (overrides: Partial<DownloadPart>): DownloadPart =>
+ ({
+ bytes: 4,
+ source: 'https://example.com/a.safetensors',
+ status: 'running',
+ total_bytes: 10,
+ ...overrides,
+ }) as DownloadPart;
+
+const pausedJob = (download_parts: DownloadPart[]): ModelInstallJob =>
+ ({ download_parts, id: 1, source: { type: 'url', url: 'https://example.com' }, status: 'paused' }) as ModelInstallJob;
+
+const traceback = 'Traceback (most recent call last):\n File "x.py", line 1\nConnectionError: reset by peer\n';
+
+describe('model install download parts', () => {
+ it('resumes past a transiently failed part, but not past a refused range', () => {
+ const failed = part({ error: traceback, error_type: 'ConnectionError(reset by peer)', status: 'error' });
+ const refused = part({ resume_required: true, status: 'paused' });
+
+ expect(getProblemDownloadParts(pausedJob([part({}), failed]))).toEqual([failed]);
+ expect(canResumeDownload(pausedJob([part({}), failed]))).toBe(true);
+ expect(canResumeDownload(pausedJob([failed, refused]))).toBe(false);
+ });
+
+ it("explains an errored part by its exception, falling back to the traceback's last line", () => {
+ expect(describeDownloadPartError(part({ error: traceback, error_type: 'ConnectionError(reset by peer)' }))).toBe(
+ 'ConnectionError(reset by peer)'
+ );
+ expect(describeDownloadPartError(part({ error: traceback }))).toBe('ConnectionError: reset by peer');
+ expect(describeDownloadPartError(part({ resume_message: 'Partial file missing.' }))).toBe('Partial file missing.');
+ expect(describeDownloadPartError(part({}))).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.ts b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.ts
new file mode 100644
index 0000000000..d99aefa58e
--- /dev/null
+++ b/invokeai/frontend/webv1/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/modelInstallParts.ts
@@ -0,0 +1,27 @@
+import type { ModelInstallJob } from 'services/api/types';
+
+type DownloadPart = NonNullable<ModelInstallJob['download_parts']>[number];
+
+const nonEmptyLines = (text: string | null | undefined): string[] =>
+ (text ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+/** Parts that errored or whose server refused to resume them. */
+export const getProblemDownloadParts = (job: ModelInstallJob): DownloadPart[] =>
+ job.download_parts?.filter((part) => part.resume_required || part.status === 'error') ?? [];
+
+/**
+ * Why an errored part failed: `error_type` names the exception and its message, `error` is a traceback whose last
+ * line does the same. Resume-required parts are explained by the caller.
+ */
+export const describeDownloadPartError = (part: DownloadPart): string | null =>
+ nonEmptyLines(part.error_type)[0] ?? nonEmptyLines(part.error).at(-1) ?? part.resume_message ?? null;
+
+/**
+ * Resume keeps partial files and re-requests the rest by range, which also recovers parts that failed transiently.
+ * Only a part whose server refused the range needs a restart, which discards partial files.
+ */
+export const canResumeDownload = (job: ModelInstallJob): boolean =>
+ !(job.download_parts ?? []).some((part) => part.resume_required);
diff --git a/invokeai/frontend/webv1/src/services/api/endpoints/models.ts b/invokeai/frontend/webv1/src/services/api/endpoints/models.ts
index db563ff6ec..79fbad0029 100644
--- a/invokeai/frontend/webv1/src/services/api/endpoints/models.ts
+++ b/invokeai/frontend/webv1/src/services/api/endpoints/models.ts
@@ -73,6 +73,46 @@ type InstallModelResponse = paths['/api/v2/models/install']['post']['responses']
type ListModelInstallsResponse =
paths['/api/v2/models/install']['get']['responses']['200']['content']['application/json'];
+type ModelInstallStatus = NonNullable<ModelInstallJob['status']>;
+
+let modelInstallStatusEventSequence = 0;
+const modelInstallStatusEventsById = new Map<number, { sequence: number; status: ModelInstallStatus }>();
+const modelInstallPausedIds = new Set<number>();
+const modelInstallListRequestSequences = new Map<string, number>();
+
+const clearSettledModelInstallStatusEvents = () => {
+ for (const [id, { sequence }] of modelInstallStatusEventsById) {
+ const hasOlderRequest = [...modelInstallListRequestSequences.values()].some(
+ (requestSequence) => requestSequence < sequence
+ );
+ if (!hasOlderRequest) {
+ modelInstallStatusEventsById.delete(id);
+ }
+ }
+};
+
+export const recordModelInstallStatus = (id: number, status: ModelInstallStatus) => {
+ const sequence = ++modelInstallStatusEventSequence;
+ if ([...modelInstallListRequestSequences.values()].some((requestSequence) => requestSequence < sequence)) {
+ modelInstallStatusEventsById.set(id, { sequence, status });
+ } else {
+ modelInstallStatusEventsById.delete(id);
+ }
+
+ if (status === 'paused') {
+ modelInstallPausedIds.add(id);
+ } else {
+ modelInstallPausedIds.delete(id);
+ }
+};
+
+export const clearModelInstallStatusEvents = () => {
+ modelInstallPausedIds.clear();
+ clearSettledModelInstallStatusEvents();
+};
+
+export const isModelInstallPaused = (id: number) => modelInstallPausedIds.has(id);
+
type CancelModelInstallResponse =
paths['/api/v2/models/install/{id}']['delete']['responses']['201']['content']['application/json'];
type PauseModelInstallResponse = ModelInstallJob;
@@ -285,6 +325,53 @@ export const modelsApi = api.injectEndpoints({
url: buildModelsUrl('install'),
};
},
+ async onQueryStarted(_, { dispatch, requestId, queryFulfilled }) {
+ const requestSequence = modelInstallStatusEventSequence;
+ modelInstallListRequestSequences.set(requestId, requestSequence);
+
+ try {
+ const { data } = await queryFulfilled;
+ if ([...modelInstallStatusEventsById.values()].some(({ sequence }) => sequence > requestSequence)) {
+ dispatch(api.util.invalidateTags([{ type: 'ModelInstalls' }]));
+ }
+
+ for (const install of data) {
+ const statusEvent = modelInstallStatusEventsById.get(install.id);
+ if (!statusEvent || statusEvent.sequence <= requestSequence) {
+ if (install.status === 'paused') {
+ modelInstallPausedIds.add(install.id);
+ } else {
+ modelInstallPausedIds.delete(install.id);
+ }
+ }
+ }
+ } catch {
+ // A failed request is not authoritative and must not clear pause state.
+ } finally {
+ modelInstallListRequestSequences.delete(requestId);
+ clearSettledModelInstallStatusEvents();
+ }
+ },
+ merge(currentCache, incoming, { requestId }) {
+ const requestSequence = modelInstallListRequestSequences.get(requestId) ?? modelInstallStatusEventSequence;
+ const incomingIds = new Set(incoming.map((install) => install.id));
+ const statusEventsDuringRequest = new Map(
+ [...modelInstallStatusEventsById].filter(([, event]) => event.sequence > requestSequence)
+ );
+ const merged = incoming.map((install) => {
+ const statusEvent = statusEventsDuringRequest.get(install.id);
+ return statusEvent ? { ...install, status: statusEvent.status } : install;
+ });
+
+ for (const currentInstall of currentCache) {
+ const statusEvent = statusEventsDuringRequest.get(currentInstall.id);
+ if (statusEvent && !incomingIds.has(currentInstall.id)) {
+ merged.push({ ...currentInstall, status: statusEvent.status });
+ }
+ }
+
+ return merged;
+ },
providesTags: ['ModelInstalls'],
}),
cancelModelInstall: build.mutation<CancelModelInstallResponse, number>({
diff --git a/invokeai/frontend/webv1/src/services/events/setEventListeners.test.ts b/invokeai/frontend/webv1/src/services/events/setEventListeners.test.ts
index d8a231a7a0..aea89ae952 100644
--- a/invokeai/frontend/webv1/src/services/events/setEventListeners.test.ts
+++ b/invokeai/frontend/webv1/src/services/events/setEventListeners.test.ts
@@ -1,7 +1,10 @@
+import { configureStore } from '@reduxjs/toolkit';
import { $nodeExecutionStates } from 'features/nodes/hooks/useNodeExecutionState';
import { toast } from 'features/toast/toast';
-import { LIST_TAG } from 'services/api';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { api, LIST_TAG } from 'services/api';
+import { clearModelInstallStatusEvents, modelsApi } from 'services/api/endpoints/models';
+import type { ModelInstallJob } from 'services/api/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setEventListeners } from './setEventListeners';
import { $lastProgressEvent } from './stores';
@@ -63,6 +66,193 @@ const createMockSocket = () => {
};
describe('setEventListeners workflow live updates', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ clearModelInstallStatusEvents();
+ mockOnInvocationComplete.dispose.mockClear();
+ });
+
+ const jsonResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });
+
+ /** Wires listeners to a real API store whose list requests stay pending until the test answers them. */
+ const setUpModelInstalls = () => {
+ const store = configureStore({
+ reducer: { [api.reducerPath]: api.reducer },
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+ });
+ const pendingResponses: Array<(response: Response) => void> = [];
+ const fetchMock = vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ pendingResponses.push(resolve);
+ })
+ );
+ vi.stubGlobal('window', { location: { origin: 'http://localhost' } });
+ vi.stubGlobal('localStorage', { getItem: () => null });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const socket = createMockSocket();
+ const dispose = setEventListeners({ socket: socket as never, store: store as never, setIsConnected: vi.fn() });
+
+ const respond = (index: number, body: unknown) => {
+ const resolve = pendingResponses[index];
+ if (!resolve) {
+ throw new Error(`No pending response resolver at index ${index}`);
+ }
+ resolve(jsonResponse(body));
+ };
+ const installs = () => modelsApi.endpoints.listModelInstalls.select()(store.getState()).data;
+ /** Subscribes like the install queue does, answering the first list request with jobs. */
+ const subscribe = async (jobs: ModelInstallJob[]) => {
+ const request = store.dispatch(modelsApi.endpoints.listModelInstalls.initiate());
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respond(0, jobs);
+ await request.unwrap();
+ };
+
+ return { dispose, fetchMock, installs, respond, socket, store, subscribe };
+ };
+
+ const PART_URL = 'https://example.com/model.safetensors';
+ const healthyJob: ModelInstallJob = {
+ id: 42,
+ local_path: '/models/staging/model',
+ source: { url: PART_URL, type: 'url' },
+ status: 'downloading',
+ download_parts: [{ source: PART_URL, status: 'running', bytes: 4, total_bytes: 10 }] as never,
+ };
+ const autoPausedJob: ModelInstallJob = {
+ ...healthyJob,
+ status: 'paused',
+ download_parts: [{ source: PART_URL, status: 'error', bytes: 4, total_bytes: 10 }] as never,
+ };
+
+ it('refetches a paused install so the failed part reaches the queue, and keeps it paused', async () => {
+ const { fetchMock, installs, respond, socket, subscribe } = setUpModelInstalls();
+ await subscribe([healthyJob]);
+
+ socket.trigger('model_install_paused', { id: healthyJob.id, source: healthyJob.source });
+ socket.trigger('model_install_download_progress', { id: healthyJob.id, bytes: 5, total_bytes: 10 });
+
+ expect(installs()).toEqual([{ ...healthyJob, bytes: 5, status: 'paused', total_bytes: 10 }]);
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respond(1, [autoPausedJob]);
+ await vi.waitFor(() => expect(installs()).toEqual([autoPausedJob]));
+
+ socket.trigger('model_install_download_progress', { id: healthyJob.id, bytes: 6, total_bytes: 10 });
+ expect(installs()?.[0]?.status).toBe('paused');
+
+ socket.trigger('model_install_download_started', { id: healthyJob.id, source: healthyJob.source });
+ expect(installs()?.[0]?.status).toBe('downloading');
+ });
+
+ it('accepts downloads-complete when the resume-start event was missed', async () => {
+ const { fetchMock, installs, respond, socket, subscribe } = setUpModelInstalls();
+ await subscribe([healthyJob]);
+
+ socket.trigger('model_install_paused', { id: healthyJob.id, source: healthyJob.source });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respond(1, [autoPausedJob]);
+ await vi.waitFor(() => expect(installs()?.[0]?.status).toBe('paused'));
+
+ socket.trigger('model_install_downloads_complete', { id: healthyJob.id });
+
+ expect(installs()?.[0]?.status).toBe('downloads_done');
+ });
+
+ it.each(['stale active row', 'omitted row'] as const)(
+ 'fences a pre-pause %s response and accepts a post-pause authoritative response',
+ async (staleResponseType) => {
+ const { fetchMock, installs, respond, socket, store, subscribe } = setUpModelInstalls();
+ await subscribe([healthyJob]);
+
+ void store.dispatch(modelsApi.endpoints.listModelInstalls.initiate(undefined, { forceRefetch: true }));
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+
+ // The event's own refetch is dropped while this request is pending; the request's completion refetches.
+ socket.trigger('model_install_paused', { id: healthyJob.id, source: healthyJob.source });
+ respond(1, staleResponseType === 'stale active row' ? [healthyJob] : []);
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
+ expect(installs()).toEqual([{ ...healthyJob, status: 'paused' }]);
+
+ respond(2, [{ ...healthyJob, status: 'completed' }]);
+ await vi.waitFor(() => expect(installs()).toEqual([{ ...healthyJob, status: 'completed' }]));
+ }
+ );
+
+ const settleEvents = {
+ cancelled: (id: number) => ['model_install_cancelled', { id, source: healthyJob.source }] as const,
+ completed: (id: number) => ['model_install_complete', { id, config: { type: 'main' } }] as const,
+ error: (id: number) =>
+ ['model_install_error', { id, error: 'boom', error_type: 'RuntimeError', source: healthyJob.source }] as const,
+ };
+
+ it.each(Object.keys(settleEvents) as Array<keyof typeof settleEvents>)(
+ 'keeps %s over a list response delayed across pause, resume, and settle, then trusts the next response',
+ async (settledStatus) => {
+ const { fetchMock, installs, respond, socket, store, subscribe } = setUpModelInstalls();
+ await subscribe([healthyJob]);
+
+ void store.dispatch(modelsApi.endpoints.listModelInstalls.initiate(undefined, { forceRefetch: true }));
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+
+ socket.trigger('model_install_paused', { id: healthyJob.id, source: healthyJob.source });
+ socket.trigger('model_install_download_started', { id: healthyJob.id, source: healthyJob.source });
+ const [settleEvent, settlePayload] = settleEvents[settledStatus](healthyJob.id);
+ socket.trigger(settleEvent, settlePayload);
+ expect(installs()?.[0]?.status).toBe(settledStatus);
+
+ respond(1, [healthyJob]);
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
+ expect(installs()?.[0]?.status).toBe(settledStatus);
+
+ // Started after the settle event, so it wins even where it disagrees (e.g. retried from another client).
+ respond(2, [{ ...healthyJob, status: 'waiting', bytes: 0 }]);
+ await vi.waitFor(() => expect(installs()?.[0]).toMatchObject({ status: 'waiting', bytes: 0 }));
+ }
+ );
+
+ it('fences each job by its own latest event, and keeps the fence across listener teardown', async () => {
+ const other: ModelInstallJob = { ...healthyJob, id: 77, source: { url: 'https://example.com/b', type: 'url' } };
+ const { dispose, fetchMock, installs, respond, socket, store, subscribe } = setUpModelInstalls();
+ await subscribe([healthyJob, other]);
+
+ void store.dispatch(modelsApi.endpoints.listModelInstalls.initiate(undefined, { forceRefetch: true }));
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+
+ socket.trigger('model_install_paused', { id: healthyJob.id, source: healthyJob.source });
+ socket.trigger('model_install_complete', { id: other.id, config: { type: 'main' } });
+ dispose();
+
+ respond(1, [healthyJob, other]);
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
+ expect(installs()?.map(({ id, status }) => ({ id, status }))).toEqual([
+ { id: healthyJob.id, status: 'paused' },
+ { id: other.id, status: 'completed' },
+ ]);
+
+ respond(2, [autoPausedJob, { ...other, status: 'completed' }]);
+ await vi.waitFor(() => expect(installs()).toEqual([autoPausedJob, { ...other, status: 'completed' }]));
+ });
+
+ it('refetches when a pause event arrives during the initial model-install list request', async () => {
+ const { fetchMock, installs, respond, socket, store } = setUpModelInstalls();
+
+ void store.dispatch(modelsApi.endpoints.listModelInstalls.initiate());
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+
+ socket.trigger('model_install_paused', { id: autoPausedJob.id, source: autoPausedJob.source });
+ respond(0, []);
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respond(1, [autoPausedJob]);
+
+ await vi.waitFor(() => expect(installs()).toEqual([autoPausedJob]));
+ });
+
it('invalidates workflow list caches on workflow_created', () => {
const socket = createMockSocket();
const dispatch = vi.fn();
diff --git a/invokeai/frontend/webv1/src/services/events/setEventListeners.tsx b/invokeai/frontend/webv1/src/services/events/setEventListeners.tsx
index 5c4c8f9932..2b0278fc6e 100644
--- a/invokeai/frontend/webv1/src/services/events/setEventListeners.tsx
+++ b/invokeai/frontend/webv1/src/services/events/setEventListeners.tsx
@@ -36,7 +36,12 @@ import { Trans } from 'react-i18next';
import type { ApiTagDescription } from 'services/api';
import { api, LIST_TAG } from 'services/api';
import { imagesApi } from 'services/api/endpoints/images';
-import { modelsApi } from 'services/api/endpoints/models';
+import {
+ clearModelInstallStatusEvents,
+ isModelInstallPaused,
+ modelsApi,
+ recordModelInstallStatus,
+} from 'services/api/endpoints/models';
import { queueApi } from 'services/api/endpoints/queue';
import { getEventScope } from 'services/events/eventScope';
import { buildOnForeignInvocationComplete, buildOnInvocationComplete } from 'services/events/onInvocationComplete';
@@ -325,6 +330,7 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
log.debug({ data }, 'Model install started');
const { id } = data;
+ recordModelInstallStatus(id, 'running');
const installs = selectModelInstalls(getState()).data;
if (!installs?.find((install) => install.id === id)) {
@@ -346,6 +352,7 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
log.debug({ data }, 'Model install download started');
const { id } = data;
+ recordModelInstallStatus(id, 'downloading');
const installs = selectModelInstalls(getState()).data;
if (!installs?.find((install) => install.id === id)) {
@@ -368,6 +375,9 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
const { bytes, total_bytes, id } = data;
const installs = selectModelInstalls(getState()).data;
+ if (!isModelInstallPaused(id)) {
+ recordModelInstallStatus(id, 'downloading');
+ }
if (!installs?.find((install) => install.id === id)) {
dispatch(api.util.invalidateTags([{ type: 'ModelInstalls' }]));
@@ -378,7 +388,9 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
if (modelImport) {
modelImport.bytes = bytes;
modelImport.total_bytes = total_bytes;
- modelImport.status = 'downloading';
+ if (!isModelInstallPaused(id)) {
+ modelImport.status = 'downloading';
+ }
}
return draft;
})
@@ -390,6 +402,7 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
log.debug({ data }, 'Model install downloads complete');
const { id } = data;
+ recordModelInstallStatus(id, 'downloads_done');
const installs = selectModelInstalls(getState()).data;
if (!installs?.find((install) => install.id === id)) {
@@ -407,10 +420,30 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
}
});
+ socket.on('model_install_paused', (data) => {
+ log.debug({ data }, 'Model install paused');
+
+ const { id } = data;
+ recordModelInstallStatus(id, 'paused');
+ dispatch(
+ modelsApi.util.updateQueryData('listModelInstalls', undefined, (draft) => {
+ const modelImport = draft.find((m) => m.id === id);
+ if (modelImport) {
+ modelImport.status = 'paused';
+ }
+ return draft;
+ })
+ );
+ // The event carries only id/source. Refetch for download_parts, which name the part whose failure auto-paused it.
+ // If a list request is already in flight, its merge keeps the newer socket status and onQueryStarted refetches.
+ dispatch(api.util.invalidateTags([{ type: 'ModelInstalls' }]));
+ });
+
socket.on('model_install_complete', (data) => {
log.debug({ data }, 'Model install complete');
const { id, config } = data;
+ recordModelInstallStatus(id, 'completed');
if (config.type === 'unknown') {
toast({
@@ -456,12 +489,29 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
});
const onModelInstallError = buildOnModelInstallError(getState, dispatch);
- socket.on('model_install_error', onModelInstallError);
+ socket.on('model_install_error', (data) => {
+ recordModelInstallStatus(data.id, 'error');
+ const installs = selectModelInstalls(getState()).data;
+ if (!installs?.find((install) => install.id === data.id)) {
+ dispatch(api.util.invalidateTags([{ type: 'ModelInstalls' }]));
+ } else {
+ dispatch(
+ modelsApi.util.updateQueryData('listModelInstalls', undefined, (draft) => {
+ const modelImport = draft.find((install) => install.id === data.id);
+ if (modelImport) {
+ modelImport.status = 'error';
+ }
+ })
+ );
+ }
+ onModelInstallError(data);
+ });
socket.on('model_install_cancelled', (data) => {
log.warn({ data }, 'Model install cancelled');
const { id } = data;
+ recordModelInstallStatus(id, 'cancelled');
const installs = selectModelInstalls(getState()).data;
if (!installs?.find((install) => install.id === id)) {
@@ -1050,6 +1100,7 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
// Ends this socket's session for the completion handler: its queued refetches are dropped, and
// anything it already has in flight is barred from dispatching into whatever session replaces
// this one.
+ clearModelInstallStatusEvents();
onInvocationComplete.dispose();
};
};
diff --git a/invokeai/frontend/webv1/src/services/events/types.ts b/invokeai/frontend/webv1/src/services/events/types.ts
index 6679ee5956..3f949c7ca6 100644
--- a/invokeai/frontend/webv1/src/services/events/types.ts
+++ b/invokeai/frontend/webv1/src/services/events/types.ts
@@ -30,6 +30,7 @@ export type ServerToClientEvents = {
model_install_download_started: (payload: S['ModelInstallDownloadStartedEvent']) => void;
model_install_download_progress: (payload: S['ModelInstallDownloadProgressEvent']) => void;
model_install_downloads_complete: (payload: S['ModelInstallDownloadsCompleteEvent']) => void;
+ model_install_paused: (payload: S['ModelInstallPausedEvent']) => void;
model_install_complete: (payload: S['ModelInstallCompleteEvent']) => void;
model_install_error: (payload: S['ModelInstallErrorEvent']) => void;
model_install_cancelled: (payload: S['ModelInstallCancelledEvent']) => void;
diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.ts
index a7f3100098..1bdb5d300a 100644
--- a/invokeai/frontend/webv2/src/features/models/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts
@@ -200,6 +200,10 @@ export interface ModelInstallDownloadPart {
resume_message?: string | null;
/** The part was silently restarted from the beginning after a failed resume. */
resume_from_scratch?: boolean;
+ /** Exception class and message of an errored part, e.g. `HTTPError(503 Server Error)`. */
+ error_type?: string | null;
+ /** Full traceback of an errored part. */
+ error?: string | null;
}
/** A model install job as returned by `/api/v2/models/install`. */
diff --git a/invokeai/frontend/webv2/src/features/models/data/api.test.ts b/invokeai/frontend/webv2/src/features/models/data/api.test.ts
index 7471c32529..4b87770809 100644
--- a/invokeai/frontend/webv2/src/features/models/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/api.test.ts
@@ -1,3 +1,4 @@
+import { ApiError } from '@platform/transport/http';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ModelsDataPort } from './transport';
@@ -55,6 +56,32 @@ describe('installModel', () => {
});
});
+describe('cancelModelInstall', () => {
+ it('returns the job state after the delete so a completed no-op is visible', async () => {
+ mocks.request.mockReset().mockResolvedValue(new Response());
+ const completed = { id: 4, source: 'org/model', status: 'completed' };
+ mocks.apiFetchJson.mockReset().mockResolvedValue(completed);
+ const { cancelModelInstall } = await import('./api');
+ const controller = new AbortController();
+
+ await expect(cancelModelInstall(4, controller.signal)).resolves.toEqual(completed);
+
+ expect(mocks.request).toHaveBeenCalledWith('/api/v2/models/install/4', {
+ method: 'DELETE',
+ signal: controller.signal,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v2/models/install/4', { signal: controller.signal });
+ });
+
+ it('treats a post-delete 404 as a successfully pruned job', async () => {
+ mocks.request.mockReset().mockResolvedValue(new Response());
+ mocks.apiFetchJson.mockReset().mockRejectedValue(new ApiError('Not found', 404));
+ const { cancelModelInstall } = await import('./api');
+
+ await expect(cancelModelInstall(4)).resolves.toBeNull();
+ });
+});
+
describe('account-owned model requests', () => {
beforeEach(() => {
mocks.request.mockReset().mockResolvedValue(new Response());
@@ -77,7 +104,7 @@ describe('account-owned model requests', () => {
await getExternalProviderConfigs(controller.signal);
await deleteOrphanedModels(['/models/orphan'], controller.signal);
await addModelRelationship('model-a', 'model-b', controller.signal);
- await pruneCompletedModelInstalls(controller.signal);
+ await expect(pruneCompletedModelInstalls(controller.signal)).resolves.toEqual([]);
await updateModelImage('model-a', image, controller.signal);
expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(
@@ -100,12 +127,12 @@ describe('account-owned model requests', () => {
method: 'POST',
signal: controller.signal,
});
- expect(mocks.request).toHaveBeenNthCalledWith(2, '/api/v2/models/install', {
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v2/models/install', {
method: 'DELETE',
signal: controller.signal,
});
expect(mocks.request).toHaveBeenNthCalledWith(
- 3,
+ 2,
'/api/v2/models/i/model-a/image',
expect.objectContaining({ method: 'PATCH', signal: controller.signal })
);
diff --git a/invokeai/frontend/webv2/src/features/models/data/api.ts b/invokeai/frontend/webv2/src/features/models/data/api.ts
index 54525b7889..5e3cca337d 100644
--- a/invokeai/frontend/webv2/src/features/models/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/api.ts
@@ -12,6 +12,8 @@ import type {
StarterModelResponse,
} from '@features/models/core/types';
+import { ApiError } from '@platform/transport/http';
+
import { browserModelsDataPort } from './transport';
/** REST client for the backend model manager (`/api/v2/models`). */
@@ -139,8 +141,18 @@ export const installModel = (
export const listModelInstalls = (signal?: AbortSignal): Promise<ModelInstallJob[]> =>
requestJson<ModelInstallJob[]>(`${MODELS_BASE}/install`, { signal });
-export const cancelModelInstall = async (id: number, signal?: AbortSignal): Promise<void> => {
+export const cancelModelInstall = async (id: number, signal?: AbortSignal): Promise<ModelInstallJob | null> => {
await request(`${MODELS_BASE}/install/${id}`, { method: 'DELETE', signal });
+ try {
+ return await requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}`, { signal });
+ } catch (error) {
+ // A successful DELETE may prune a settled job before this follow-up GET reaches it.
+ if (error instanceof ApiError && error.status === 404) {
+ return null;
+ }
+
+ throw error;
+ }
};
export const pauseModelInstall = (id: number, signal?: AbortSignal): Promise<ModelInstallJob> =>
@@ -164,9 +176,8 @@ export const restartModelInstallFile = (
signal,
});
-export const pruneCompletedModelInstalls = async (signal?: AbortSignal): Promise<void> => {
- await request(`${MODELS_BASE}/install`, { method: 'DELETE', signal });
-};
+export const pruneCompletedModelInstalls = (signal?: AbortSignal): Promise<number[]> =>
+ requestJson<number[]>(`${MODELS_BASE}/install`, { method: 'DELETE', signal });
export const scanFolderForModels = (scanPath: string, signal?: AbortSignal): Promise<FoundModel[]> =>
requestJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`, { signal });
diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
index fe1f653ecc..4172697d75 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
@@ -59,6 +59,522 @@ describe('model install event interpretation', () => {
expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
});
+ it('projects a paused install event immediately and refetches the job for its failed parts', async () => {
+ const pausedWithFailedPart = {
+ download_parts: [{ source: 'https://example.com/a.safetensors', status: 'error' }],
+ id: 9,
+ source: 'org/model',
+ status: 'paused',
+ };
+ dependencies.listModelInstalls.mockReset().mockResolvedValue([pausedWithFailedPart]);
+
+ const store = await import('./installsStore');
+
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'paused' }]);
+
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+ expect(store.getInstallsSnapshot().jobs).toEqual([pausedWithFailedPart]);
+ });
+
+ it('keeps a pause over an in-flight stale list response and trusts the refetch started after it', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+ const fresh = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ const refresh = store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ expect(store.getInstallsSnapshot().jobs[0]?.status).toBe('paused');
+
+ stale.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'paused' }]);
+
+ await vi.advanceTimersByTimeAsync(250);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+
+ // Started after the event, so its status is authoritative (e.g. resumed from another client).
+ fresh.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ });
+
+ it('reruns the refetch after a stale list request that outlives the coalescing window', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+ const pausedWithFailedPart = {
+ download_parts: [{ source: 'https://example.com/a.safetensors', status: 'error' }],
+ id: 9,
+ source: 'org/model',
+ status: 'paused',
+ };
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockResolvedValueOnce([pausedWithFailedPart]);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ void store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ await vi.advanceTimersByTimeAsync(250);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+
+ stale.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([pausedWithFailedPart]);
+ });
+
+ it.each([
+ ['model_install_complete', 'completed'],
+ ['model_install_error', 'error'],
+ ['model_install_cancelled', 'cancelled'],
+ ] as const)(
+ 'converges on the settled status after a list response delayed across pause, resume, and %s',
+ async (settleEvent, settledStatus) => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockResolvedValueOnce([{ id: 9, source: 'org/model', status: settledStatus }]);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ void store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ store.handleModelInstallSocketEvent('model_install_download_started', { id: 9, source: 'org/model' });
+ store.handleModelInstallSocketEvent(settleEvent, { config: {}, id: 9, source: 'org/model' });
+
+ stale.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await vi.advanceTimersByTimeAsync(250);
+
+ // Every install event schedules a refresh that starts after it, so the stale snapshot never sticks.
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: settledStatus }]);
+ }
+ );
+
+ it.each([
+ ['model_install_complete', 'completed'],
+ ['model_install_error', 'error'],
+ ['model_install_cancelled', 'cancelled'],
+ ] as const)(
+ 'keeps the %s status over a list response delayed across pause and resume when the refetch fails',
+ async (settleEvent, settledStatus) => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ const refresh = store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ store.handleModelInstallSocketEvent('model_install_download_started', { id: 9, source: 'org/model' });
+ store.handleModelInstallSocketEvent(settleEvent, { config: {}, id: 9, source: 'org/model' });
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: settledStatus }]);
+
+ stale.resolve([{ id: 9, source: 'org/model', status: 'paused' }]);
+ await refresh;
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: settledStatus }]);
+
+ await vi.advanceTimersByTimeAsync(250);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: settledStatus }]);
+ }
+ );
+
+ it('keeps a resume action result over a list response that started while the job was paused', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(stale.promise);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'paused' });
+ const refresh = store.refreshInstalls();
+
+ store.replaceInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ stale.resolve([{ id: 9, source: 'org/model', status: 'paused' }]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'waiting' }]);
+ });
+
+ it('trusts a cancelled list status over an older download fence when the trailing refresh fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ // The trailing rerun and the event's scheduled refresh both fail.
+ .mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ void store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_download_started', { id: 9, source: 'org/model' });
+ // Cancelling during download emits no event; the UI refreshes, joining the in-flight request.
+ void store.refreshInstalls();
+ // The backend served the in-flight request after the cancel.
+ stale.resolve([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(3);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+ });
+
+ it('drops a pruned settled job omitted by an in-flight response when the trailing refresh fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ // The trailing rerun and the event's scheduled refresh both fail.
+ .mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'running' });
+ void store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_complete', { config: {}, id: 9, source: 'org/model' });
+ // Pruning settled jobs emits no event; the UI refreshes, joining the in-flight request.
+ void store.refreshInstalls();
+ stale.resolve([]);
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(3);
+ expect(store.getInstallsSnapshot().jobs).toEqual([]);
+ });
+
+ it('keeps a job first seen after an in-flight response started when it settles before that response lands', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ void store.refreshInstalls();
+
+ store.addInstallJob({ id: 5, source: 'org/new', status: 'waiting' });
+ store.handleModelInstallSocketEvent('model_install_complete', { config: {}, id: 5, source: 'org/new' });
+ // The backend served the request before the job existed.
+ stale.resolve([]);
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 5, source: 'org/new', status: 'completed' }]);
+ });
+
+ it('keeps a completion that lands before a no-op cancel response', async () => {
+ dependencies.listModelInstalls.mockReset().mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'running' });
+
+ store.handleModelInstallSocketEvent('model_install_complete', { config: {}, id: 9, source: 'org/model' });
+ // The backend treats cancelling a completed job as a successful no-op.
+ store.projectInstallCancelled(9);
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'completed' }]);
+ });
+
+ it('keeps a cancel action over an in-flight active status when the trailing refresh fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ void store.refreshInstalls();
+
+ // Cancelling a waiting job emits no event and the cancel route returns no job.
+ store.projectInstallCancelled(9);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+ void store.refreshInstalls();
+ stale.resolve([{ id: 9, source: 'org/model', status: 'waiting' }]);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+ });
+
+ it('keeps a cancel action over successful active refreshes until REST reports a terminal status', async () => {
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce([{ id: 9, source: 'org/model', status: 'downloading' }])
+ .mockResolvedValueOnce([{ id: 9, source: 'org/model', status: 'completed' }]);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ store.projectInstallCancelled(9);
+
+ await store.refreshInstalls();
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+
+ await store.refreshInstalls();
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'completed' }]);
+ });
+
+ it.each([
+ ['cancel action', 'model_install_started'],
+ ['cancel action', 'model_install_download_started'],
+ ['cancel response', 'model_install_started'],
+ ['cancel response', 'model_install_download_started'],
+ ] as const)('keeps a %s over a delayed %s event when the refetch fails', async (cancelSource, event) => {
+ dependencies.listModelInstalls.mockReset().mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+
+ if (cancelSource === 'cancel action') {
+ // DELETE succeeded before the worker observed cancellation; GET still returned an active row.
+ store.replaceInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ store.projectInstallCancelled(9);
+ } else {
+ store.replaceInstallJob({ id: 9, source: 'org/model', status: 'cancelled' });
+ }
+
+ store.handleModelInstallSocketEvent(event, { id: 9, source: 'org/model' });
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+ expect(store.getInstallsSnapshot().error).toBe('temporary list failure');
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'cancelled' }]);
+ });
+
+ it('keeps a completed cancel response over an older in-flight active row when refresh fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValue(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ void store.refreshInstalls();
+
+ // DELETE can succeed as a no-op after completion; GET returns the current completed row.
+ store.replaceInstallJob({ id: 9, source: 'org/model', status: 'completed' });
+ void store.refreshInstalls();
+ stale.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'completed' }]);
+ });
+
+ it('keeps all fields from a restart action over an older in-flight job row', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string; [key: string]: unknown }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(stale.promise);
+
+ const store = await import('./installsStore');
+ const oldPart = {
+ bytes: 40,
+ error: 'old failure',
+ source: 'https://example.com/weights.safetensors',
+ status: 'error',
+ total_bytes: 100,
+ };
+ store.addInstallJob({
+ bytes: 40,
+ download_parts: [oldPart],
+ error: 'old failure',
+ id: 9,
+ source: 'org/model',
+ status: 'error',
+ total_bytes: 100,
+ });
+ const refresh = store.refreshInstalls();
+
+ const restarted = {
+ bytes: 0,
+ download_parts: [],
+ error: null,
+ id: 9,
+ source: 'org/model',
+ status: 'waiting' as const,
+ total_bytes: 100,
+ };
+ store.replaceInstallJob(restarted);
+ stale.resolve([
+ {
+ bytes: 40,
+ download_parts: [oldPart],
+ error: 'old failure',
+ id: 9,
+ source: 'org/model',
+ status: 'error',
+ total_bytes: 100,
+ },
+ ]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([restarted]);
+ });
+
+ it('keeps a newly created job that an in-flight list response omits', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(stale.promise);
+
+ const store = await import('./installsStore');
+ const refresh = store.refreshInstalls();
+
+ store.addInstallJob({ id: 5, source: 'org/new', status: 'waiting' });
+ stale.resolve([]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 5, source: 'org/new', status: 'waiting' }]);
+ });
+
+ it('keeps an install error that arrived before the late creation response', async () => {
+ const list = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(list.promise);
+
+ const store = await import('./installsStore');
+ store.handleModelInstallSocketEvent('model_install_error', { error: 'boom', id: 5, source: 'org/new' });
+ await vi.advanceTimersByTimeAsync(250);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+
+ store.addInstallJob({ id: 5, source: 'org/new', status: 'waiting' });
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 5, source: 'org/new', status: 'error' }]);
+
+ list.resolve([{ id: 5, source: 'org/new', status: 'error' }]);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 5, source: 'org/new', status: 'error' }]);
+ });
+
+ it('keeps a locally known paused job when a stale response omits it and the trailing refresh fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ const refresh = store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ stale.resolve([]);
+ await refresh;
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'paused' }]);
+ });
+
+ it('does not let late download progress clear a pause fence', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValueOnce(new Error('outage'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'downloading' });
+ const refresh = store.refreshInstalls();
+
+ store.handleModelInstallSocketEvent('model_install_paused', { id: 9, source: 'org/model' });
+ store.handleModelInstallSocketEvent('model_install_download_progress', { bytes: 50, id: 9, total_bytes: 100 });
+ stale.resolve([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ await refresh;
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'paused' }]);
+ });
+
+ it('does not let stale progress fence a locally confirmed completion', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ const refresh = store.refreshInstalls();
+
+ store.replaceInstallJob({ id: 9, source: 'org/model', status: 'completed' });
+ store.handleModelInstallSocketEvent('model_install_download_progress', { bytes: 50, id: 9, total_bytes: 100 });
+ stale.resolve([{ id: 9, source: 'org/model', status: 'waiting' }]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'completed' }]);
+ });
+
+ it('keeps progress after reconnect over an older waiting list row', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(stale.promise);
+
+ const store = await import('./installsStore');
+ store.addInstallJob({ id: 9, source: 'org/model', status: 'waiting' });
+ const refresh = store.refreshInstalls();
+
+ // The download-start event was missed during reconnect; progress proves this job is downloading.
+ store.handleModelInstallSocketEvent('model_install_download_progress', { bytes: 50, id: 9, total_bytes: 100 });
+ stale.resolve([{ id: 9, source: 'org/model', status: 'waiting' }]);
+ await refresh;
+
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ });
+
+ it('keeps progress for an unknown job over an older waiting list row when the refetch fails', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+
+ const store = await import('./installsStore');
+ const refresh = store.refreshInstalls();
+
+ // Another client created this job; the first event seen here is a progress tick.
+ store.handleModelInstallSocketEvent('model_install_download_progress', { bytes: 50, id: 9, total_bytes: 100 });
+ stale.resolve([{ id: 9, source: 'org/model', status: 'waiting' }]);
+ await refresh;
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().error).toBe('temporary list failure');
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 9, source: 'org/model', status: 'downloading' }]);
+ expect(store.getInstallProgress(9)).toEqual({ bytes: 50, bytesPerSecond: null, totalBytes: 100 });
+ });
+
it('records completion identity and refreshes catalog capabilities', async () => {
const store = await import('./installsStore');
diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
index dba945b8b2..e26374d69a 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
@@ -90,6 +90,29 @@ let nextOutcomeId = 1;
const progressByJobId = createKeyedTransientStore<number, InstallDownloadProgress>();
const rateSamplesByJobId = new Map<number, { bytes: number; at: number }>();
+/**
+ * Latest locally known status per job, from a socket event or an action result, stamped with a sequence. A list
+ * request that started before the stamp may predate that status, so it must not overwrite it; the first list request
+ * started after it is authoritative and clears the fence. Starting earlier does not prove the backend served it
+ * earlier, though, and some transitions emit no event (cancelling a download, pruning settled jobs). So a final list
+ * status always wins, and a stale response may drop a job whose fence is settled, since pruning removes only those,
+ * but only when this client knew the job before the request started; otherwise the backend may have served it before
+ * the job existed.
+ */
+const statusFenceByJobId = new Map<number, { sequence: number; status: ModelInstallStatus }>();
+/** Sequence at which this client first saw each job, from a list response, a socket event, or a creation result. */
+const firstSeenSequenceByJobId = new Map<number, number>();
+let nextStatusFenceSequence = 1;
+/** No backend transition leaves these; `error` is excluded because a failed install can be restarted. */
+const FINAL_STATUSES: ReadonlySet<ModelInstallStatus> = new Set(['completed', 'cancelled']);
+const SETTLED_STATUSES: ReadonlySet<ModelInstallStatus> = new Set(['completed', 'error', 'cancelled']);
+const CANCELLATION_ACTIVE_STATUSES: ReadonlySet<ModelInstallStatus> = new Set([
+ 'waiting',
+ 'downloading',
+ 'downloads_done',
+ 'running',
+ 'paused',
+]);
const refreshFlight = createTrailingSingleFlight();
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
@@ -111,6 +134,9 @@ registerAccountOwnedResource({
nextOutcomeId = 1;
progressByJobId.clear();
rateSamplesByJobId.clear();
+ statusFenceByJobId.clear();
+ firstSeenSequenceByJobId.clear();
+ nextStatusFenceSequence = 1;
outcomesStore.setSnapshot(EMPTY_INSTALL_OUTCOMES);
store.setSnapshot(EMPTY_INSTALLS_SNAPSHOT);
},
@@ -119,6 +145,7 @@ registerAccountOwnedResource({
export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Promise<void> =>
refreshFlight.run(() => {
+ const startSequence = nextStatusFenceSequence;
store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
return listModelInstalls(owner.signal)
@@ -128,6 +155,60 @@ export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Pr
}
const activeJobIds = new Set(jobs.map((job) => job.id));
+ const reconciledJobs: ModelInstallJob[] = jobs.map((job) => {
+ const fence = statusFenceByJobId.get(job.id);
+
+ if (fence === undefined) {
+ return job;
+ }
+
+ if (fence.status === 'cancelled' && CANCELLATION_ACTIVE_STATUSES.has(job.status)) {
+ // DELETE can succeed before the worker observes cancellation. Keep the optimistic result until REST
+ // reports a terminal state; otherwise a successful refresh can revive the row if its socket was missed.
+ const current = store.getSnapshot().jobs.find((candidate) => candidate.id === job.id) ?? job;
+ return current.status === 'cancelled' ? current : { ...current, status: 'cancelled' };
+ }
+
+ if (fence.sequence >= startSequence && !FINAL_STATUSES.has(job.status)) {
+ // This request predates the fenced status, so its status is stale.
+ const current = store.getSnapshot().jobs.find((candidate) => candidate.id === job.id) ?? job;
+ return current.status === fence.status ? current : { ...current, status: fence.status };
+ }
+
+ // A request started after the fence, or a final status, is authoritative.
+ statusFenceByJobId.delete(job.id);
+ return job;
+ });
+
+ for (const [jobId, fence] of statusFenceByJobId) {
+ if (activeJobIds.has(jobId)) {
+ continue;
+ }
+
+ const knownBeforeStart = (firstSeenSequenceByJobId.get(jobId) ?? Infinity) < startSequence;
+
+ if (fence.sequence >= startSequence && !(SETTLED_STATUSES.has(fence.status) && knownBeforeStart)) {
+ // The job may have been created after the backend served this request.
+ const locallyKnownJob = store.getSnapshot().jobs.find((job) => job.id === jobId);
+
+ if (locallyKnownJob) {
+ reconciledJobs.push({ ...locallyKnownJob, status: fence.status });
+ activeJobIds.add(jobId);
+ }
+ } else {
+ statusFenceByJobId.delete(jobId);
+ }
+ }
+
+ for (const jobId of activeJobIds) {
+ noteJobSeen(jobId);
+ }
+
+ for (const jobId of firstSeenSequenceByJobId.keys()) {
+ if (!activeJobIds.has(jobId) && !statusFenceByJobId.has(jobId)) {
+ firstSeenSequenceByJobId.delete(jobId);
+ }
+ }
for (const [jobId] of progressByJobId.entries()) {
if (!activeJobIds.has(jobId)) {
@@ -143,7 +224,7 @@ export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Pr
dismissedJobIds:
retainedDismissed.length === dismissedJobIds.size ? dismissedJobIds : new Set(retainedDismissed),
error: null,
- jobs,
+ jobs: reconciledJobs,
status: 'loaded',
});
})
@@ -197,13 +278,58 @@ const scheduleCatalogRefresh = (): void => {
}, REFRESH_COALESCE_MS);
};
-/** Optimistically replace one job (e.g. after pause/resume API calls). */
-export const replaceInstallJob = (job: ModelInstallJob): void => {
+const noteJobSeen = (jobId: number): void => {
+ if (!firstSeenSequenceByJobId.has(jobId)) {
+ firstSeenSequenceByJobId.set(jobId, nextStatusFenceSequence++);
+ }
+};
+
+const fenceJobStatus = (jobId: number, status: ModelInstallStatus): void => {
+ statusFenceByJobId.set(jobId, { sequence: nextStatusFenceSequence++, status });
+};
+
+const patchJob = (job: ModelInstallJob): void => {
store.patchSnapshot({
jobs: store.getSnapshot().jobs.map((existing) => (existing.id === job.id ? job : existing)),
});
};
+const projectJobStatus = (jobId: number, status: ModelInstallStatus): void => {
+ if (statusFenceByJobId.get(jobId)?.status === 'cancelled' && CANCELLATION_ACTIVE_STATUSES.has(status)) {
+ return;
+ }
+
+ fenceJobStatus(jobId, status);
+
+ const job = store.getSnapshot().jobs.find((candidate) => candidate.id === jobId);
+
+ if (job && job.status !== status) {
+ patchJob({ ...job, status });
+ }
+};
+
+/** Replace one job with a backend action result (e.g. pause/resume), newer than any list request in flight. */
+export const replaceInstallJob = (job: ModelInstallJob): void => {
+ fenceJobStatus(job.id, job.status);
+ patchJob(job);
+};
+
+/** Project a successful cancel action: the cancel route returns no job, and cancelling a job that is not downloading
+ * emits no event. Cancelling a completed job succeeds as a no-op, so a known completion stands. */
+export const projectInstallCancelled = (jobId: number, owner: AccountScope = captureAccountScope()): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const isCompleted =
+ statusFenceByJobId.get(jobId)?.status === 'completed' ||
+ store.getSnapshot().jobs.some((job) => job.id === jobId && job.status === 'completed');
+
+ if (!isCompleted) {
+ projectJobStatus(jobId, 'cancelled');
+ }
+};
+
/** Hide a settled job locally until the backend stops listing it. */
export const dismissInstallJob = (jobId: number): void => {
const { dismissedJobIds } = store.getSnapshot();
@@ -213,6 +339,13 @@ export const dismissInstallJob = (jobId: number): void => {
}
};
+/** Hide only the jobs included in a successful prune request. */
+export const dismissInstallJobs = (ids: number[]): void => {
+ if (ids.length > 0) {
+ store.patchSnapshot({ dismissedJobIds: new Set([...store.getSnapshot().dismissedJobIds, ...ids]) });
+ }
+};
+
/** Optimistically add a freshly created job so the queue updates instantly. */
export const addInstallJob = (job: ModelInstallJob): void => {
if (store.getSnapshot().jobs.some((existing) => existing.id === job.id)) {
@@ -220,7 +353,17 @@ export const addInstallJob = (job: ModelInstallJob): void => {
return;
}
- store.patchSnapshot({ jobs: [job, ...store.getSnapshot().jobs], status: 'loaded' });
+ noteJobSeen(job.id);
+
+ // Any event for the job is at least as new as its creation result, so an existing fence keeps its status.
+ const fence = statusFenceByJobId.get(job.id);
+
+ if (fence === undefined) {
+ fenceJobStatus(job.id, job.status);
+ }
+
+ const added = fence === undefined || fence.status === job.status ? job : { ...job, status: fence.status };
+ store.patchSnapshot({ jobs: [added, ...store.getSnapshot().jobs], status: 'loaded' });
};
const installLogger = createLogger({ area: 'install', namespace: 'models' });
@@ -290,6 +433,7 @@ export const MODEL_INSTALL_SOCKET_EVENTS = [
'model_install_download_started',
'model_install_download_progress',
'model_install_downloads_complete',
+ 'model_install_paused',
'model_install_complete',
'model_install_error',
'model_install_cancelled',
@@ -297,6 +441,16 @@ export const MODEL_INSTALL_SOCKET_EVENTS = [
export type ModelInstallSocketEvent = (typeof MODEL_INSTALL_SOCKET_EVENTS)[number];
+const EVENT_STATUS: Record<Exclude<ModelInstallSocketEvent, 'model_install_download_progress'>, ModelInstallStatus> = {
+ model_install_cancelled: 'cancelled',
+ model_install_complete: 'completed',
+ model_install_download_started: 'downloading',
+ model_install_downloads_complete: 'downloads_done',
+ model_install_error: 'error',
+ model_install_paused: 'paused',
+ model_install_started: 'running',
+};
+
/** Socket sink — wired into the backend socket by the queue coordinator. */
export const handleModelInstallSocketEvent = (
event: ModelInstallSocketEvent,
@@ -313,6 +467,8 @@ export const handleModelInstallSocketEvent = (
return;
}
+ noteJobSeen(data.id);
+
if (event === 'model_install_download_progress') {
const bytes = data.bytes ?? 0;
@@ -323,20 +479,31 @@ export const handleModelInstallSocketEvent = (
});
const job = store.getSnapshot().jobs.find((candidate) => candidate.id === data.id);
+ const fence = statusFenceByJobId.get(data.id);
+
+ if ((!job || job.status === 'waiting') && (fence === undefined || fence.status === 'waiting')) {
+ // Progress proves a waiting job is downloading; preserve newer pause, cancel, or terminal state.
+ fenceJobStatus(data.id, 'downloading');
+ }
if (!job) {
// The first progress tick may arrive for a job created in another
// client; make sure the row exists without refetching on every tick.
scheduleRefresh();
- } else if (job.status === 'waiting') {
+ } else if (job.status === 'waiting' && (fence === undefined || fence.status === 'waiting')) {
// Bytes are flowing, so the REST snapshot's `waiting` is stale. Patch
// locally so download controls (pause/cancel) appear immediately.
- replaceInstallJob({ ...job, status: 'downloading' });
+ patchJob({ ...job, status: 'downloading' });
}
return;
}
+ // Project the status each event implies (the backend's job status when it emits) and fence it, so a list response
+ // that started before the event cannot replace it with an older status. The scheduled refresh then fills in the
+ // fields events omit, such as a paused job's download_parts naming the part whose failure auto-paused it.
+ projectJobStatus(data.id, EVENT_STATUS[event]);
+
if (event === 'model_install_complete' || event === 'model_install_error' || event === 'model_install_cancelled') {
// Retain settled jobs until cleared, but release their inactive byte-progress state.
progressByJobId.delete(data.id);
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
index 2f34672b7b..2dd7a9346c 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
@@ -28,6 +28,7 @@ import type { InstallQueueRow, InstallRowStatus } from './queueModel';
import { InstallProgressCell } from './InstallProgressCell';
import {
canRestartFailedParts,
+ canResumeInstall,
getInstallJobDisplayName,
getInstallJobSourceLabel,
getProblemDownloadParts,
@@ -159,26 +160,33 @@ export const InstallJobRow = ({ row }: { row: InstallQueueRow }) => {
</HStack>
) : null}
{problemParts.map((part) => (
- <HStack key={part.key} gap="1.5" pt="0.5">
- <Icon
- as={TriangleAlertIcon}
- boxSize="3"
- color={part.resumeRequired ? 'fg.warning' : 'fg.error'}
- flexShrink={0}
- />
- <MiddleTruncate color="fg" fontFamily="mono" fontSize="xs" minW="0" text={part.fileName} />
- <Text color="fg.muted" fontSize="xs" whiteSpace="nowrap">
- {part.message ?? (part.resumeRequired ? t('models.resumeRequired') : t('common.failed'))}
- </Text>
- {part.url ? (
- <RowAction
- disabled={actions.isBusy}
- icon={RotateCcwIcon}
- label={t('models.restartThisFile')}
- onClick={() => actions.restartFile(part.url!)}
+ <Stack key={part.key} gap="0" pt="0.5">
+ <HStack gap="1.5">
+ <Icon
+ as={TriangleAlertIcon}
+ boxSize="3"
+ color={part.resumeRequired ? 'fg.warning' : 'fg.error'}
+ flexShrink={0}
/>
+ <MiddleTruncate color="fg" fontFamily="mono" fontSize="xs" minW="0" text={part.fileName} />
+ <Text color="fg.muted" fontSize="xs" whiteSpace="nowrap">
+ {part.resumeRequired ? t('models.resumeRequired') : t('common.failed')}
+ </Text>
+ {part.url ? (
+ <RowAction
+ disabled={actions.isBusy}
+ icon={RotateCcwIcon}
+ label={t('models.restartThisFile')}
+ onClick={() => actions.restartFile(part.url!)}
+ />
+ ) : null}
+ </HStack>
+ {part.message ? (
+ <Text color="fg" fontSize="xs" lineClamp={2} overflowWrap="anywhere" ps="4.5">
+ {part.message}
+ </Text>
) : null}
- </HStack>
+ </Stack>
))}
</Stack>
</Table.Cell>
@@ -220,12 +228,20 @@ export const InstallJobRow = ({ row }: { row: InstallQueueRow }) => {
onClick={actions.pause}
/>
) : null}
- {status === 'paused' ? (
+ {canResumeInstall(job) ? (
+ <RowAction
+ disabled={actions.isBusy}
+ icon={PlayIcon}
+ label={t('models.resumeDownload')}
+ onClick={actions.resume}
+ />
+ ) : null}
+ {status === 'paused' && canRestartFailedParts(job) ? (
<RowAction
disabled={actions.isBusy}
- icon={canRestartFailedParts(job) ? RotateCcwIcon : PlayIcon}
- label={canRestartFailedParts(job) ? t('models.retryFailedDownload') : t('models.resumeDownload')}
- onClick={canRestartFailedParts(job) ? actions.retry : actions.resume}
+ icon={RotateCcwIcon}
+ label={t('models.retryFailedDownload')}
+ onClick={actions.retry}
/>
) : null}
{isSettledRowStatus(status) && status !== 'installed' ? (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
index 22cb40d80a..c637a4f77c 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
@@ -1,12 +1,13 @@
import type { ModelConfig, ModelInstallJob } from '@features/models/core/types';
import { ChakraProvider } from '@chakra-ui/react';
-import { handleModelInstallSocketEvent } from '@features/models/data/installsStore';
+import { handleModelInstallSocketEvent, refreshInstalls } from '@features/models/data/installsStore';
import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';
import { getModelsUiSnapshotForTests, updateModelsUi } from '@features/models/ui/uiStore';
import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { setConnectionStatus } from '@platform/transport/connectionStore';
+import { ApiError } from '@platform/transport/http';
import { applyThemeToRoot } from '@theme/applyTheme';
import { DEFAULT_THEME_ID, system } from '@theme/system';
import { createInstance } from 'i18next';
@@ -25,6 +26,7 @@ const api = vi.hoisted(() => ({
pauseModelInstall: vi.fn(),
pruneCompletedModelInstalls: vi.fn(),
restartFailedModelInstall: vi.fn(),
+ resumeModelInstall: vi.fn(),
}));
vi.mock('@features/models/data/api', async (importOriginal) => ({
@@ -157,8 +159,10 @@ beforeEach(async () => {
mock.mockReset();
}
api.listModelInstalls.mockResolvedValue(JOBS);
- api.pruneCompletedModelInstalls.mockResolvedValue(undefined);
- api.cancelModelInstall.mockResolvedValue(undefined);
+ api.pruneCompletedModelInstalls.mockResolvedValue([3, 4, 5, 6]);
+ api.cancelModelInstall.mockImplementation((id: number) =>
+ Promise.resolve({ ...JOBS.find((job) => job.id === id)!, status: 'cancelled' })
+ );
api.pauseModelInstall.mockImplementation((id: number) =>
Promise.resolve({ ...JOBS.find((job) => job.id === id)!, status: 'paused' })
);
@@ -217,6 +221,97 @@ describe('InstallQueueBar', () => {
expect(await auditAccessibility(host!)).toEqual([]);
});
+ it('refetches an auto-paused download to show the failed file and its cause, and resumes it', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ const healthyPart = { bytes: 4, source: 'https://example.com/weights.safetensors', total_bytes: 100 };
+ api.listModelInstalls.mockResolvedValue(
+ JOBS.map((job) => (job.id === 1 ? { ...job, download_parts: [{ ...healthyPart, status: 'running' }] } : job))
+ );
+ api.resumeModelInstall.mockResolvedValue({ ...JOBS[0], status: 'waiting' });
+ await render();
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(1);
+ expect(rowByStatus('downloading')?.textContent).not.toContain('weights.safetensors');
+
+ // The backend auto-paused the job after the part failed; only the refetch carries the errored part.
+ api.listModelInstalls.mockResolvedValue(
+ JOBS.map((job) =>
+ job.id === 1
+ ? {
+ ...job,
+ download_parts: [
+ {
+ ...healthyPart,
+ error: 'Traceback (most recent call last):\nConnectionError: reset by peer',
+ error_type: 'ConnectionError(reset by peer)',
+ status: 'error',
+ },
+ ],
+ status: 'paused' as const,
+ }
+ : job
+ )
+ );
+ await act(() => {
+ handleModelInstallSocketEvent('model_install_paused', { id: 1, source: JOBS[0].source });
+ });
+ await vi.waitFor(() => expect(api.listModelInstalls).toHaveBeenCalledTimes(2));
+ await settle();
+
+ expect(rowByStatus('downloading')).toBeUndefined();
+ const pausedRow = rowByStatus('paused');
+ expect(pausedRow?.textContent).toContain('weights.safetensors');
+ expect(pausedRow?.textContent).toContain('ConnectionError(reset by peer)');
+ expect(pausedRow?.textContent).not.toContain('Traceback');
+ // A transient failure keeps its partial file: resume first, restarts stay available but explicit.
+ expect(pausedRow?.querySelector('button[aria-label="Resume download"]')).not.toBeNull();
+ expect(pausedRow?.querySelector('button[aria-label="Restart this file"]')).not.toBeNull();
+ expect(pausedRow?.querySelector('button[aria-label="Retry failed download"]')).not.toBeNull();
+ const header = host?.querySelector('[aria-expanded="true"]')?.parentElement;
+ expect(header?.textContent).toContain('3 need attention');
+ expect(header?.textContent).not.toContain('paused');
+ expect(await auditAccessibility(host!)).toEqual([]);
+
+ await click('Resume download', pausedRow);
+ await settle();
+
+ expect(api.resumeModelInstall).toHaveBeenCalledWith(1, expect.any(AbortSignal));
+ expect(api.restartFailedModelInstall).not.toHaveBeenCalled();
+ });
+
+ it('offers only a restart for a paused download whose server refused to resume', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls.mockResolvedValue(
+ JOBS.map((job) =>
+ job.id === 1
+ ? {
+ ...job,
+ download_parts: [
+ {
+ bytes: 4,
+ resume_message: 'Resume refused by server. Restart required.',
+ resume_required: true,
+ source: 'https://example.com/weights.safetensors',
+ status: 'paused',
+ total_bytes: 100,
+ },
+ ],
+ status: 'paused' as const,
+ }
+ : job
+ )
+ );
+ api.restartFailedModelInstall.mockResolvedValue({ ...JOBS[0], status: 'waiting' });
+ await render();
+
+ const pausedRow = rowByStatus('paused');
+ expect(pausedRow?.textContent).toContain('Resume refused by server. Restart required.');
+ expect(pausedRow?.querySelector('button[aria-label="Resume download"]')).toBeNull();
+ await click('Retry failed download', pausedRow);
+ await settle();
+
+ expect(api.restartFailedModelInstall).toHaveBeenCalledWith(1, expect.any(AbortSignal));
+ });
+
it('reflects live progress with a rate and ETA on the downloading row and the collapsed bar', async () => {
updateModelsUi({ queueExpanded: true, queueMaximized: false });
await render();
@@ -284,6 +379,225 @@ describe('InstallQueueBar', () => {
expect(api.pruneCompletedModelInstalls).toHaveBeenCalledTimes(1);
});
+ it('does not restore finished rows from a list request started before successful pruning', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ let resolveStale!: (jobs: ModelInstallJob[]) => void;
+ const stale = new Promise<ModelInstallJob[]>((resolve) => {
+ resolveStale = resolve;
+ });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS)
+ .mockReturnValueOnce(stale)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+ api.pruneCompletedModelInstalls.mockResolvedValue([1, 3, 4, 5, 6]);
+ await render();
+
+ act(() => {
+ void refreshInstalls();
+ });
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(2);
+ await click('Clear finished');
+ await settle();
+ expect(api.pruneCompletedModelInstalls).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveStale(JOBS);
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(3);
+ expect(
+ rows().some((row) =>
+ ['installed', 'cancelled', 'failed', 'unauthorized'].includes(row.dataset.installStatus ?? '')
+ )
+ ).toBe(false);
+ });
+
+ it('dismisses jobs the server prunes even when their completion socket event was missed', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.pruneCompletedModelInstalls.mockResolvedValue([1, 3, 4, 5, 6]);
+ await render();
+
+ await click('Clear finished');
+ await settle();
+
+ expect(rowByStatus('installed')).toBeUndefined();
+ expect(api.pruneCompletedModelInstalls).toHaveBeenCalledTimes(1);
+ });
+
+ it('removes finished rows when pruning succeeds on the server but its response is lost', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS)
+ .mockResolvedValueOnce(JOBS.filter(({ status }) => !['completed', 'error'].includes(status)));
+ api.pruneCompletedModelInstalls.mockRejectedValue(new Error('Prune response lost'));
+ await render();
+ expect(rows()).toHaveLength(JOBS.length);
+
+ await click('Clear finished');
+ await settle();
+
+ expect(rows().map((row) => row.dataset.installStatus)).toEqual(['downloading', 'queued', 'cancelled']);
+ expect(api.pruneCompletedModelInstalls).toHaveBeenCalledTimes(1);
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps a job that another client restarted before pruning', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls.mockResolvedValue(
+ JOBS.map((job) => (job.id === 3 ? { ...job, status: 'waiting' as const } : job))
+ );
+ api.pruneCompletedModelInstalls.mockResolvedValue([4, 5, 6]);
+ await render();
+
+ await click('Clear finished');
+ await settle();
+
+ expect(rowByStatus('queued')).toBeDefined();
+ expect(rowByStatus('failed')).toBeUndefined();
+ });
+
+ it('keeps jobs that settle after a prune request started', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ let resolvePrune!: (jobIds: number[]) => void;
+ const afterPrune = [{ ...JOBS[0]!, status: 'completed' as const }, JOBS[1]!];
+ api.listModelInstalls.mockReset().mockResolvedValueOnce(JOBS).mockResolvedValueOnce(afterPrune);
+ api.pruneCompletedModelInstalls.mockReturnValue(
+ new Promise<number[]>((resolve) => {
+ resolvePrune = resolve;
+ })
+ );
+ await render();
+
+ await click('Clear finished');
+ act(() => handleModelInstallSocketEvent('model_install_complete', { id: 1, source: 'org/model', config: {} }));
+ await act(async () => {
+ resolvePrune([3, 4, 5, 6]);
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+ expect(rowByStatus('installed')).toBeDefined();
+ expect(rows()).toHaveLength(2);
+ });
+
+ it('keeps a completed cancel response over an older list row when the refresh fails', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ let resolveStale!: (jobs: ModelInstallJob[]) => void;
+ const stale = new Promise<ModelInstallJob[]>((resolve) => {
+ resolveStale = resolve;
+ });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS)
+ .mockReturnValueOnce(stale)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+ api.cancelModelInstall.mockResolvedValue({ ...JOBS[0]!, config_out: INSTALLED_LORA, status: 'completed' });
+ await render();
+
+ act(() => {
+ void refreshInstalls();
+ });
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(2);
+ await click('Cancel install', rowByStatus('downloading'));
+ await settle();
+
+ await act(async () => {
+ resolveStale(JOBS);
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+ expect(api.cancelModelInstall).toHaveBeenCalledWith(1, expect.any(AbortSignal));
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(3);
+ expect(rowByStatus('installed')).toBeDefined();
+ expect(rowByStatus('downloading')).toBeUndefined();
+ });
+
+ it('projects an active cancel response as cancelled over an older list when refresh fails', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ let resolveStale!: (jobs: ModelInstallJob[]) => void;
+ const stale = new Promise<ModelInstallJob[]>((resolve) => {
+ resolveStale = resolve;
+ });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS)
+ .mockReturnValueOnce(stale)
+ .mockRejectedValueOnce(new Error('temporary list failure'));
+ api.cancelModelInstall.mockResolvedValue({ ...JOBS[0]!, status: 'downloading' });
+ await render();
+
+ act(() => {
+ void refreshInstalls();
+ });
+ await click('Cancel install', rowByStatus('downloading'));
+ await settle();
+ await act(async () => {
+ resolveStale(JOBS);
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+ expect(rowByStatus('cancelled')).toBeDefined();
+ expect(rowByStatus('downloading')).toBeUndefined();
+ });
+
+ it('refreshes after cancel succeeds but its follow-up state fetch fails', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS)
+ .mockResolvedValueOnce(JOBS.map((job) => (job.id === 1 ? { ...job, status: 'cancelled' as const } : job)));
+ api.cancelModelInstall.mockRejectedValue(new ApiError('Could not fetch cancel state', 500));
+ await render();
+
+ await click('Cancel install', rowByStatus('downloading'));
+ await settle();
+
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(rowByStatus('cancelled')).toBeDefined();
+ expect(rowByStatus('downloading')).toBeUndefined();
+ });
+
+ it('refreshes after a concurrent prune makes cancel return 415', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls.mockReset().mockResolvedValueOnce(JOBS).mockResolvedValueOnce(JOBS.slice(1));
+ api.cancelModelInstall.mockRejectedValue(new ApiError('Install job is no longer available', 415));
+ await render();
+
+ await click('Cancel install', rowByStatus('downloading'));
+ await settle();
+
+ expect(api.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(rowByStatus('downloading')).toBeUndefined();
+ expect(rows()).toHaveLength(JOBS.length - 1);
+ });
+
+ it('refreshes after a 409 resume response that may have changed backend status', async () => {
+ updateModelsUi({ queueExpanded: true, queueMaximized: false });
+ api.listModelInstalls
+ .mockReset()
+ .mockResolvedValueOnce(JOBS.map((job) => (job.id === 6 ? { ...job, status: 'paused' } : job)))
+ .mockResolvedValue(JOBS.map((job) => (job.id === 6 ? { ...job, status: 'error' } : job)));
+ api.resumeModelInstall.mockRejectedValue(new ApiError('Install changed state', 409));
+ await render();
+
+ const before = api.listModelInstalls.mock.calls.length;
+ await click('Resume download', rowByStatus('paused'));
+ await settle();
+
+ expect(api.listModelInstalls.mock.calls.length).toBeGreaterThan(before);
+ expect(rowByStatus('failed')).toBeDefined();
+ });
+
it('expands to fill the pane and restores', async () => {
updateModelsUi({ queueExpanded: true, queueMaximized: false });
await render();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
index 81565b2640..d906bd3a92 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
@@ -9,7 +9,11 @@ import {
} from '@features/models/data/api';
import {
ensureInstallsLoaded,
+ dismissInstallJob,
+ dismissInstallJobs,
+ projectInstallCancelled,
refreshInstalls,
+ replaceInstallJob,
useInstallProgress,
useInstallsSelector,
} from '@features/models/data/installsStore';
@@ -95,14 +99,20 @@ export const InstallQueueBar = () => {
const runBulk = useCallback(
(
run: ReturnType<typeof useScopedAction>['run'],
- call: (id: number, signal: AbortSignal) => Promise<unknown>,
- targets: ModelInstallJob[]
+ call: (id: number, signal: AbortSignal) => Promise<ModelInstallJob | null>,
+ targets: ModelInstallJob[],
+ onSucceeded?: (id: number, result: ModelInstallJob | null) => void
) =>
run(
async (owner) => {
// allSettled: one failure must not hide the others' outcomes, and the rest still deserve a fresh list.
const results = await Promise.allSettled(targets.map((job) => call(job.id, owner.signal)));
assertAccountScopeCurrent(owner);
+ results.forEach((result, index) => {
+ if (result.status === 'fulfilled') {
+ onSucceeded?.(targets[index]!.id, result.value);
+ }
+ });
await refreshInstalls(owner);
assertAccountScopeCurrent(owner);
@@ -130,11 +140,15 @@ export const InstallQueueBar = () => {
const handlePrune = () =>
runPrune(
async (owner) => {
- await pruneCompletedModelInstalls(owner.signal);
+ const prunedJobIds = await pruneCompletedModelInstalls(owner.signal);
assertAccountScopeCurrent(owner);
+ dismissInstallJobs(prunedJobIds);
await refreshInstalls(owner);
},
- (message) => notify.error(t('models.pruneFailed'), message)
+ (message) => {
+ notify.error(t('models.pruneFailed'), message);
+ void refreshInstalls();
+ }
);
return (
@@ -215,7 +229,18 @@ export const InstallQueueBar = () => {
label={t('models.cancelAll')}
tone="danger"
value="cancel-all"
- onSelect={() => void runBulk(runCancelAll, cancelModelInstall, cancellableJobs)}
+ onSelect={() =>
+ void runBulk(runCancelAll, cancelModelInstall, cancellableJobs, (id, result) => {
+ if (result === null) {
+ dismissInstallJob(id);
+ } else {
+ replaceInstallJob(result);
+ if (!['completed', 'error', 'cancelled'].includes(result.status)) {
+ projectInstallCancelled(id);
+ }
+ }
+ })
+ }
/>
</MenuContent>
</Menu.Positioner>
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.test.ts b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.test.ts
index 132171648e..307f34919b 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';
import {
buildInstallQueueRows,
canRestartFailedParts,
+ canResumeInstall,
describeEta,
getInstallJobDisplayName,
getInstallJobSourceLabel,
@@ -81,6 +82,28 @@ describe('problem download parts', () => {
]);
});
+ it("explains an errored part by its exception, falling back to the traceback's last line", () => {
+ const messageFor = (part: Record<string, unknown>) =>
+ getProblemDownloadParts(
+ job({ download_parts: [{ bytes: 0, source: 'https://x/d.bin', total_bytes: 1, ...part }], id: 1 })
+ )[0]?.message;
+ const traceback = 'Traceback (most recent call last):\n File "x.py", line 1\nConnectionError: reset by peer\n';
+
+ expect(messageFor({ error: traceback, error_type: 'ConnectionError(reset by peer)', status: 'error' })).toBe(
+ 'ConnectionError(reset by peer)'
+ );
+ expect(messageFor({ error: traceback, status: 'error' })).toBe('ConnectionError: reset by peer');
+ expect(messageFor({ resume_message: 'Partial file missing.', status: 'error' })).toBe('Partial file missing.');
+ });
+
+ it('resumes a paused job past transient part failures, but not past a refused range', () => {
+ const transient = parts.filter((part) => part.resume_required !== true);
+
+ expect(canResumeInstall(job({ download_parts: transient, id: 1, status: 'paused' }))).toBe(true);
+ expect(canResumeInstall(job({ download_parts: parts, id: 1, status: 'paused' }))).toBe(false);
+ expect(canResumeInstall(job({ download_parts: transient, id: 1, status: 'error' }))).toBe(false);
+ });
+
it('only offers a part restart for live jobs', () => {
expect(canRestartFailedParts(job({ download_parts: parts, id: 1, status: 'error' }))).toBe(true);
expect(canRestartFailedParts(job({ download_parts: parts, id: 1, status: 'cancelled' }))).toBe(false);
@@ -133,22 +156,27 @@ describe('install queue rows', () => {
job({ id: 6, status: 'cancelled' }),
job({ id: 7, status: 'paused' }),
job({ id: 8, status: 'running' }),
+ job({
+ download_parts: [{ bytes: 4, source: 'https://x/a.bin', status: 'error', total_bytes: 10 }],
+ id: 9,
+ status: 'paused',
+ }),
];
it('orders downloads, installs, queued in run order, paused, attention, installed, then cancelled', () => {
const rows = buildInstallQueueRows(jobs, new Set());
- expect(rows.map((row) => row.job.id)).toEqual([3, 8, 2, 5, 7, 4, 1, 6]);
+ expect(rows.map((row) => row.job.id)).toEqual([3, 8, 2, 5, 9, 7, 4, 1, 6]);
expect(rows.find((row) => row.job.id === 5)?.queuePosition).toBe(2);
expect(rows.find((row) => row.job.id === 3)?.queuePosition).toBeNull();
});
- it('hides dismissed jobs and summarises the rest', () => {
+ it('hides dismissed jobs and summarises the rest, counting a paused job with a failed file as attention', () => {
const rows = buildInstallQueueRows(jobs, new Set([6]));
expect(rows.some((row) => row.job.id === 6)).toBe(false);
expect(summarizeInstallQueue(rows)).toEqual({
- attention: 1,
+ attention: 2,
downloading: 1,
installed: 1,
installing: 1,
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.ts b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.ts
index 427ae595dd..b05df446d3 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueModel.ts
@@ -1,4 +1,4 @@
-import type { ModelInstallJob } from '@features/models/core/types';
+import type { ModelInstallDownloadPart, ModelInstallJob } from '@features/models/core/types';
import { getInstallSourceLabel, type InstallDownloadProgress } from '@features/models/data/installsStore';
@@ -122,28 +122,46 @@ export interface ProblemDownloadPart {
/** The part's download URL, which `restart_file` matches against; null for parts without one. */
url: string | null;
resumeRequired: boolean;
+ /** Why the part failed or cannot resume, when the backend says. */
message: string | null;
}
-/** Parts the backend could not resume or that errored; each needs a manual restart. */
+const nonEmptyLines = (text: string | null | undefined): string[] =>
+ (text ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+/** `error_type` names the exception and its message; `error` is a traceback whose last line does the same. */
+const describePartError = (part: ModelInstallDownloadPart): string | null =>
+ nonEmptyLines(part.error_type)[0] ?? nonEmptyLines(part.error).at(-1) ?? null;
+
+/** Parts the backend could not resume or that errored. */
export const getProblemDownloadParts = (job: ModelInstallJob): ProblemDownloadPart[] =>
(job.download_parts ?? [])
.filter((part) => part.resume_required === true || part.status === 'error')
.map((part) => ({
fileName: partFileName(part),
key: part.source ?? part.local_path ?? partFileName(part),
- message: part.resume_message ?? null,
+ message: (part.resume_required === true ? null : describePartError(part)) ?? part.resume_message ?? null,
resumeRequired: part.resume_required === true,
url: typeof part.source === 'string' ? part.source : null,
}));
/**
* `restart_failed` only acts on errored or paused jobs with restartable parts; a cancelled job's temp dir is gone,
- * so it and anything else must be resubmitted.
+ * so it and anything else must be resubmitted. Restarting discards every incomplete part's partial file.
*/
export const canRestartFailedParts = (job: ModelInstallJob): boolean =>
job.status !== 'cancelled' && getProblemDownloadParts(job).length > 0;
+/**
+ * Resume keeps partial files and re-requests the rest by range, which also recovers parts that failed transiently.
+ * Only a part whose server refused the range needs a restart instead.
+ */
+export const canResumeInstall = (job: ModelInstallJob): boolean =>
+ job.status === 'paused' && !(job.download_parts ?? []).some((part) => part.resume_required === true);
+
/** A one-off token saved with the source wins over the stored provider key. */
export const getInstallJobAccessToken = (job: ModelInstallJob): string | undefined =>
typeof job.source === 'object' && typeof job.source.access_token === 'string' && job.source.access_token
@@ -225,16 +243,17 @@ export const summarizeInstallQueue = (rows: readonly InstallQueueRow[]): Install
settled: 0,
};
- for (const { status } of rows) {
+ for (const { job, status } of rows) {
if (status === 'downloading') {
summary.downloading += 1;
} else if (status === 'installing') {
summary.installing += 1;
} else if (status === 'queued') {
summary.queued += 1;
- } else if (status === 'paused') {
+ } else if (status === 'paused' && getProblemDownloadParts(job).length === 0) {
summary.paused += 1;
- } else if (status === 'failed' || status === 'unauthorized') {
+ } else if (status === 'paused' || status === 'failed' || status === 'unauthorized') {
+ // A paused job with a failed or unresumable file was stopped by the backend and needs a decision.
summary.attention += 1;
} else if (status === 'installed') {
summary.installed += 1;
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/useInstallJobActions.ts b/invokeai/frontend/webv2/src/features/models/ui/install-queue/useInstallJobActions.ts
index 15019bcd1d..fe3a33a431 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/useInstallJobActions.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/useInstallJobActions.ts
@@ -12,6 +12,7 @@ import { getAccessTokenForSource } from '@features/models/data/apiKeys';
import {
addInstallJob,
dismissInstallJob,
+ projectInstallCancelled,
refreshInstalls,
replaceInstallJob,
} from '@features/models/data/installsStore';
@@ -31,14 +32,21 @@ export const useInstallJobActions = (job: ModelInstallJob) => {
const notify = useNotify();
const { isBusy, run } = useScopedAction();
- const runAction = (action: (owner: AccountScope) => Promise<unknown>, failureTitle: string) =>
+ const runAction = (
+ action: (owner: AccountScope) => Promise<unknown>,
+ failureTitle: string,
+ onSuccess?: (result: unknown, owner: AccountScope) => void
+ ) =>
run(
async (owner) => {
const result = await action(owner);
assertAccountScopeCurrent(owner);
- if (isInstallJob(result)) {
+ if (onSuccess) {
+ onSuccess(result, owner);
+ void refreshInstalls(owner);
+ } else if (isInstallJob(result)) {
replaceInstallJob(result);
// A coalesced refresh already in flight can clobber the optimistic row; revalidate to converge.
void refreshInstalls(owner);
@@ -46,7 +54,10 @@ export const useInstallJobActions = (job: ModelInstallJob) => {
await refreshInstalls(owner);
}
},
- (message) => notify.error(failureTitle, message)
+ (message) => {
+ notify.error(failureTitle, message);
+ void refreshInstalls();
+ }
);
const resubmit = async (owner: AccountScope) => {
@@ -67,7 +78,21 @@ export const useInstallJobActions = (job: ModelInstallJob) => {
};
return {
- cancel: () => void runAction((owner) => cancelModelInstall(job.id, owner.signal), t('models.cancelFailed')),
+ cancel: () =>
+ void runAction(
+ (owner) => cancelModelInstall(job.id, owner.signal),
+ t('models.cancelFailed'),
+ (value, owner) => {
+ if (value === null) {
+ dismissInstallJob(job.id);
+ } else if (isInstallJob(value)) {
+ replaceInstallJob(value);
+ if (!['completed', 'error', 'cancelled'].includes(value.status)) {
+ projectInstallCancelled(job.id, owner);
+ }
+ }
+ }
+ ),
dismiss: () => dismissInstallJob(job.id),
isBusy,
pause: () => void runAction((owner) => pauseModelInstall(job.id, owner.signal), t('models.pauseFailed')),
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 2ce2b5942b..45b2b01b3d 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -599,6 +599,28 @@ def test_cancel_model_install_does_not_map_unrelated_value_error_to_conflict(mon
model_manager_router.cancel_model_install_job(current_admin=None, id=42)
+def test_prune_model_install_jobs_returns_exact_pruned_ids(monkeypatch: Any) -> None:
+ from types import SimpleNamespace
+
+ from invokeai.app.api.routers import model_manager as model_manager_router
+
+ installer = SimpleNamespace(prune_jobs=lambda: [41, 42])
+ services = SimpleNamespace(model_manager=SimpleNamespace(install=installer))
+ dependencies = MockApiDependencies(DummyInvoker(services))
+ monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", dependencies)
+
+ result = model_manager_router.prune_model_install_jobs(current_admin=None)
+
+ assert result == [41, 42]
+ prune_route = next(
+ route
+ for route in model_manager_router.model_manager_router.routes
+ if route.path.endswith("/models/install") and "DELETE" in route.methods
+ )
+ assert prune_route.status_code == 200
+ assert prune_route.response_model == list[int]
+
+
@pytest.mark.parametrize("operation", ["restart_failed", "restart_file"])
def test_restart_recovery_required_install_returns_conflict(monkeypatch: Any, operation: str) -> None:
from types import SimpleNamespace
@@ -684,6 +706,38 @@ def test_remote_download_replacement_returns_conflict(monkeypatch: Any, operatio
assert "previous download" in exc_info.value.detail
[email protected]("operation", ["resume", "restart_failed", "restart_file"])
+def test_vanished_pinned_revision_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.backend.model_manager.metadata import ModelRevisionUnavailableError
+
+ def refuse(*_args: object) -> None:
+ raise ModelRevisionUnavailableError("Revision 'abc' of 'org/repo' is no longer available")
+
+ installer = SimpleNamespace(
+ get_job_by_id=lambda _id: object(), resume_job=refuse, restart_failed=refuse, restart_file=refuse
+ )
+ 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 "no longer available" in exc_info.value.detail
+
+
@pytest.mark.parametrize("operation", ["resume", "restart_failed", "restart_file"])
def test_install_path_claim_conflict_returns_conflict(monkeypatch: Any, operation: str) -> None:
from types import SimpleNamespace
diff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.py
index 4841b651ae..4294bb70f0 100644
--- a/tests/app/services/download/test_download_queue.py
+++ b/tests/app/services/download/test_download_queue.py
@@ -785,6 +785,38 @@ def test_private_opt_in_still_honors_explicit_download_proxy(monkeypatch: Any) -
queue._requests.close()
+def test_head_request_is_sent_like_a_download(monkeypatch: Any) -> None:
+ """The installer asks a host for a file's commit with `head()`; it must take the downloads' address policy and
+ explicit download proxy, and must not follow redirects."""
+ session = TestSession()
+ session.mount(
+ "https://hub.example/file", TestAdapter(b"", status=302, headers={"Location": "https://cdn.example/x"})
+ )
+ queue = DownloadQueueService(
+ app_config=InvokeAIAppConfig(allow_private_download_urls=True, download_proxy="http://proxy.internal:3128"),
+ requests_session=session,
+ requests_session_is_trusted=True,
+ )
+ queue._request_proxies = {"http": "http://proxy.internal:3128", "https": "http://proxy.internal:3128"}
+ sent: list[dict[str, Any]] = []
+ real_send = session.send
+ monkeypatch.setattr(session, "send", lambda request, **kwargs: sent.append(kwargs) or real_send(request, **kwargs))
+
+ response = queue.head("https://hub.example/file", headers={"Authorization": "Bearer t"})
+
+ assert response.status_code == 302
+ assert sent[0]["proxies"]["https"] == "http://proxy.internal:3128"
+ assert sent[0]["allow_redirects"] is False
+
+ guarded = DownloadQueueService(
+ app_config=InvokeAIAppConfig(allow_private_download_urls=False),
+ requests_session=TestSession(),
+ requests_session_is_trusted=True,
+ )
+ with pytest.raises(UnsafeDownloadURLException):
+ guarded.head("http://127.0.0.1:19191/file")
+
+
@pytest.mark.timeout(timeout=10, method="thread")
def test_download_refuses_non_public_source(tmp_path: Path) -> None:
"""A job whose source points at loopback errors out without issuing the request."""
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 959eec4025..a2bfd00932 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -7,8 +7,10 @@ import gc
import json
import os
import platform
+import re
import shutil
import sqlite3
+import ssl
import stat
import threading
import time
@@ -20,10 +22,19 @@ from unittest.mock import MagicMock
import pytest
from pydantic_core import Url
-from requests import Request, Response, Timeout
+from requests import ConnectionError as RequestsConnectionError
+from requests import HTTPError, Request, Response, Timeout
+from requests.adapters import BaseAdapter
+from requests.exceptions import SSLError
from requests_testadapter import TestAdapter
+from urllib3.exceptions import MaxRetryError, ProtocolError
+from urllib3.exceptions import SSLError as Urllib3SSLError
+from urllib3.util.ssl_match_hostname import CertificateError
+from invokeai.app.invocations.flux.flux_redux import FluxReduxInvocation
+from invokeai.app.invocations.sd.ip_adapter import IPAdapterInvocation
from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.config.config_default import URLRegexTokenPair
from invokeai.app.services.download import DownloadJob, DownloadJobStatus, MultiFileDownloadJob
from invokeai.app.services.events.events_base import EventServiceBase
from invokeai.app.services.events.events_common import (
@@ -32,12 +43,14 @@ from invokeai.app.services.events.events_common import (
ModelInstallDownloadsCompleteEvent,
ModelInstallDownloadStartedEvent,
ModelInstallErrorEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
)
from invokeai.app.services.model_install import (
HFModelSource,
ModelInstallService,
ModelInstallServiceBase,
+ install_staging_ledger,
model_install_default,
)
from invokeai.app.services.model_install.install_staging_ledger import (
@@ -58,11 +71,17 @@ from invokeai.app.services.model_install.model_install_common import (
InvalidModelConfigException,
LocalModelSource,
ModelInstallJob,
+ ModelSource,
URLModelSource,
)
from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL, UnknownModelException
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
-from invokeai.backend.model_manager.metadata import RemoteModelFile
+from invokeai.backend.model_manager.metadata import (
+ HuggingFaceMetadata,
+ ModelMetadataUnavailableError,
+ ModelRevisionUnavailableError,
+ RemoteModelFile,
+)
from invokeai.backend.model_manager.metadata.metadata_base import HF_METADATA_REQUEST_TIMEOUT_SECONDS
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
@@ -74,6 +93,8 @@ from invokeai.backend.model_manager.taxonomy import (
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
from tests.backend.model_manager.model_manager_fixtures import * # noqa F403
+from tests.backend.model_manager.model_manager_fixtures import SDXL_TURBO_COMMIT, TEXTUAL_INVERSION_TESTS_COMMIT
+from tests.backend.model_manager.model_metadata.metadata_examples import RepoHFMetadata1
from tests.test_nodes import TestEventService
OS = platform.uname().system
@@ -112,6 +133,8 @@ def _write_v1_marker(job: ModelInstallJob, status: InstallStatus) -> None:
"updated_at": "2026-01-01T00:00:00",
"files": list((job._resume_metadata or {}).values()),
}
+ if job._source_revision is not None:
+ marker["revision"] = job._source_revision
if job._recovery_required:
marker["recovery_required"] = True
(job._staging.tmpdir / ".invokeai_install.json").write_text(json.dumps(marker), encoding="utf-8")
@@ -1117,6 +1140,7 @@ def test_restore_metadata_timeout_preserves_partial_download_for_retry(
status=InstallStatus.DOWNLOADING,
)
_stage(job, tmpdir)
+ job._source_revision = SDXL_TURBO_COMMIT
_write_v1_marker(job, InstallStatus.DOWNLOADING)
def raise_metadata_timeout(*args: Any, **kwargs: Any) -> None:
@@ -1134,6 +1158,9 @@ def test_restore_metadata_timeout_preserves_partial_download_for_retry(
assert marker is not None
assert marker["status"] == InstallStatus.PAUSED.value
assert _claim_path(tmpdir).exists()
+ bus = mm2_installer.event_bus
+ assert isinstance(bus, TestEventService)
+ assert any(isinstance(event, ModelInstallPausedEvent) and event.id == restored_job.id for event in bus.events)
@pytest.mark.parametrize("status_code", [429, 503])
@@ -1151,7 +1178,9 @@ def test_restore_model_info_http_error_preserves_partial_download_for_retry(
partial_path.parent.mkdir(parents=True)
partial_path.write_bytes(b"partial model")
source = HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default)
- weights_url = "https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/text_encoder/model.safetensors"
+ weights_url = (
+ f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/{SDXL_TURBO_COMMIT}/text_encoder/model.safetensors"
+ )
resume_metadata = {
weights_url: {
"url": weights_url,
@@ -1174,9 +1203,10 @@ def test_restore_model_info_http_error_preserves_partial_download_for_retry(
)
_stage(job, tmpdir)
job._resume_metadata = resume_metadata
+ job._source_revision = SDXL_TURBO_COMMIT
_write_v1_marker(job, InstallStatus.DOWNLOADING)
- api_url = "https://huggingface.co/api/models/stabilityai/sdxl-turbo"
+ api_url = f"https://huggingface.co/api/models/stabilityai/sdxl-turbo/revision/{SDXL_TURBO_COMMIT}"
api_body = b'{"id":"stabilityai/sdxl-turbo","siblings":[{"rfilename":"text_encoder/model.safetensors","size":12}]}'
real_get = installer._session.get
api_attempts = 0
@@ -2575,9 +2605,10 @@ def test_prune_jobs_rebind_preserves_existing_iterators(
existing_iterator = iter(mm2_installer.list_jobs())
assert next(existing_iterator) is jobs[0]
- mm2_installer.prune_jobs()
+ pruned_job_ids = mm2_installer.prune_jobs()
assert list(existing_iterator) == [*jobs[1:], active_job]
+ assert pruned_job_ids == [job.id for job in jobs]
assert all(job not in mm2_installer.list_jobs() for job in jobs)
assert mm2_installer.list_jobs() == [active_job]
@@ -2846,7 +2877,8 @@ def test_restore_paused_hf_install_preserves_access_token(
_HF_EMBEDDING_SOURCE = "InvokeAI-test/textual_inversion_tests::learned_embeds-steps-1000.safetensors"
_HF_EMBEDDING_URL = (
- "https://huggingface.co/InvokeAI-test/textual_inversion_tests/resolve/main/learned_embeds-steps-1000.safetensors"
+ "https://huggingface.co/InvokeAI-test/textual_inversion_tests/resolve/"
+ f"{TEXTUAL_INVERSION_TESTS_COMMIT}/learned_embeds-steps-1000.safetensors"
)
_URL_EMBEDDING_URL = "https://www.test.foo/download/test_embedding.safetensors"
@@ -2930,7 +2962,8 @@ def test_download_authorization_while_logged_in_to_hf(
_SDXL_TURBO_SOURCE = HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default)
-_SDXL_TURBO_FILES_URL = "https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/"
+# Installs download from the commit the repository is at when they start.
+_SDXL_TURBO_FILES_URL = f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/{SDXL_TURBO_COMMIT}/"
# Downloads run in URL order, so every other file of the repo is complete before this one starts. The file list
# assumes full-precision weights, which `sdxl_turbo_server` pins.
_SDXL_TURBO_LAST_FILE = "vae/diffusion_pytorch_model.safetensors"
@@ -2939,7 +2972,7 @@ _SDXL_TURBO_LAST_FILE = "vae/diffusion_pytorch_model.safetensors"
class _RepoFileServer:
"""Serves the sdxl-turbo repo files, records every download, and scripts failures per file.
- A "fail" attempt answers HTTP 500, which errors the install. A "short" attempt announces one byte more than it
+ A "fail" attempt answers HTTP 404, which errors the install (a transient 5xx would pause it instead). A "short" attempt announces one byte more than it
sends, which pauses the install with a resume-required part. (The repo's weight files are empty.)
Each file carries an ETag naming its revision, unless `validators` is off. A Range request is recorded in
@@ -2993,7 +3026,7 @@ class _RepoFileAdapter(TestAdapter):
attempts = self.server.scripted.get(self.name)
attempt = attempts.pop(0) if attempts else None
if attempt == "fail":
- return TestAdapter(b"", status=500).send(request, stream=stream, **kwargs)
+ return TestAdapter(b"", status=404).send(request, stream=stream, **kwargs)
if attempt == "short":
headers["Content-Length"] = len(data) + 1
elif byte_range := request.headers.get("Range"):
@@ -3100,6 +3133,29 @@ def test_restart_of_a_paused_install_fetches_only_files_missing_from_staging(
assert _installed_files(mm2_app_config, job) == set(repo_files)
[email protected](timeout=20, method="thread")
+def test_restart_of_a_paused_install_reports_a_staged_file_that_vanished(
+ mm2_installer: ModelInstallServiceBase,
+ sdxl_turbo_server: _RepoFileServer,
+) -> None:
+ """A paused install keeps its staging, so a file missing from it on restart vanished and is fetched anew."""
+ server = sdxl_turbo_server
+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]
+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)
+ mm2_installer.wait_for_installs(timeout=10)
+ assert job.status is InstallStatus.PAUSED
+ vanished = "scheduler/scheduler_config.json"
+ (job.local_path / vanished).unlink()
+
+ mm2_installer.restart_file(job, _SDXL_TURBO_FILES_URL + _SDXL_TURBO_LAST_FILE)
+
+ [part] = [part for part in job.download_parts if str(part.source) == _SDXL_TURBO_FILES_URL + vanished]
+ assert part.resume_from_scratch
+ assert part.resume_message == "Partial file missing. Restarted download from the beginning."
+ mm2_installer.wait_for_installs(timeout=10)
+ assert job.complete, job.error
+
+
@pytest.mark.timeout(timeout=20, method="thread")
def test_retry_after_a_partial_restart_failed_fetches_every_file(
mm2_installer: ModelInstallServiceBase,
@@ -3714,8 +3770,12 @@ def test_restore_claims_downloads_done_staging_before_queueing(
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
[email protected]("operation", ["restart_failed", "restart_file"])
+def test_restart_clears_partials_before_retry(
+ operation: str,
+ mm2_installer: ModelInstallServiceBase,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
assert isinstance(mm2_installer, ModelInstallService)
source = URLModelSource(url=Url("https://example.com/model.safetensors"))
@@ -3752,16 +3812,187 @@ def test_restart_failed_uses_parts_created_before_download_started(
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))
+ monkeypatch.setattr(
+ mm2_installer, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None)
+ )
enqueue_remote_download = MagicMock()
monkeypatch.setattr(mm2_installer, "_enqueue_remote_download", enqueue_remote_download)
- mm2_installer.restart_failed(job)
+ if operation == "restart_failed":
+ mm2_installer.restart_failed(job)
+ else:
+ mm2_installer.restart_file(job, str(source.url))
assert job.status == InstallStatus.WAITING
enqueue_remote_download.assert_called_once()
assert enqueue_remote_download.call_args.kwargs["restart_from_zero"] == {str(source.url)}
+ ("validator_field", "validator_value"),
+ [("etag", '"original-etag"'), ("last_modified", "Wed, 01 Jan 2025 00:00:00 GMT")],
+)
+def test_resume_restored_partial_keeps_if_range_when_part_fails_before_started_callback(
+ mm2_installer: ModelInstallServiceBase,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ monkeypatch: pytest.MonkeyPatch,
+ validator_field: str,
+ validator_value: str,
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ source = URLModelSource(url=Url("https://test.com/resume/model.safetensors"))
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}resume-validator-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ partial_path = tmpdir / "model.safetensors.downloading"
+ partial_path.write_bytes(b"part")
+
+ old_part = DownloadJob(
+ source=source.url,
+ dest=tmpdir / "model.safetensors",
+ download_path=tmpdir / "model.safetensors",
+ canonical_url=str(source.url),
+ expected_total_bytes=100,
+ bytes=4,
+ **{validator_field: validator_value},
+ )
+ paused_job = ModelInstallJob(
+ id=98765,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.PAUSED,
+ download_parts={old_part},
+ )
+ _stage(paused_job, tmpdir)
+ mm2_installer._write_install_marker(paused_job, status=InstallStatus.PAUSED)
+
+ class CapturingErrorAdapter(TestAdapter):
+ def __init__(self) -> None:
+ super().__init__(b"server error", status=500)
+ self.requests = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ return super().send(request, **kwargs)
+
+ adapter = CapturingErrorAdapter()
+ mm2_session.mount(str(source.url), adapter)
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=100)
+ restored_events = TestEventService()
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=restored_events,
+ session=mm2_session,
+ )
+ monkeypatch.setattr(
+ restored_installer, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None)
+ )
+
+ try:
+ restored_installer._restore_incomplete_installs()
+ [restored_job] = restored_installer.list_jobs()
+ assert restored_job.paused
+
+ restored_installer.resume_job(restored_job)
+ mm2_download_queue.join()
+
+ assert len(adapter.requests) == 1
+ assert adapter.requests[0].headers["Range"] == "bytes=4-"
+ assert adapter.requests[0].headers["If-Range"] == validator_value
+ assert not any(isinstance(event, ModelInstallDownloadStartedEvent) for event in restored_events.events)
+ assert restored_job.status == InstallStatus.PAUSED
+ marker = _read_marker(tmpdir)
+ assert marker is not None
+ assert marker["files"][0][validator_field] == validator_value
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+ ("validator_field", "validator_value"),
+ [("etag", '"original-etag"'), ("last_modified", "Wed, 01 Jan 2025 00:00:00 GMT")],
+)
+def test_resume_live_paused_partial_sends_if_range(
+ mm2_installer: ModelInstallServiceBase,
+ mm2_download_queue,
+ mm2_session,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ validator_field: str,
+ validator_value: str,
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ source = URLModelSource(url=Url("https://test.com/resume/live-model.safetensors"))
+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}live-resume-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ partial_path = tmpdir / "model.safetensors.downloading"
+ partial_path.write_bytes(b"part")
+ part = DownloadJob(
+ source=source.url,
+ dest=tmpdir / "model.safetensors",
+ download_path=tmpdir / "model.safetensors",
+ canonical_url=str(source.url),
+ expected_total_bytes=100,
+ bytes=4,
+ **{validator_field: validator_value},
+ )
+ download_job = MultiFileDownloadJob(id=98766, dest=tmpdir, download_parts={part})
+ install_job = ModelInstallJob(
+ id=download_job.id,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.DOWNLOADING,
+ )
+ _stage(install_job, tmpdir)
+ install_job._multifile_job = download_job
+ install_job.download_parts = download_job.download_parts
+ mm2_installer._download_cache[download_job.id] = install_job
+ mm2_installer._download_error_callback(download_job, RequestsConnectionError("connection reset"))
+
+ assert install_job.status == InstallStatus.PAUSED
+ assert install_job.download_parts == {part}
+ marker = _read_marker(tmpdir)
+ assert marker is not None
+ assert marker["files"][0][validator_field] == validator_value
+
+ class CapturingErrorAdapter(TestAdapter):
+ def __init__(self) -> None:
+ super().__init__(b"server error", status=500)
+ self.requests = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ return super().send(request, **kwargs)
+
+ adapter = CapturingErrorAdapter()
+ mm2_session.mount(str(source.url), adapter)
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=100)
+ monkeypatch.setattr(
+ mm2_installer, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None)
+ )
+
+ try:
+ mm2_installer.resume_job(install_job)
+ mm2_download_queue.join()
+
+ assert len(adapter.requests) == 1
+ assert adapter.requests[0].headers["Range"] == "bytes=4-"
+ assert adapter.requests[0].headers["If-Range"] == validator_value
+ assert install_job.status == InstallStatus.PAUSED
+ marker = _read_marker(tmpdir)
+ assert marker is not None
+ assert marker["files"][0][validator_field] == validator_value
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
@pytest.mark.parametrize("callback_name", ["_download_error_callback", "_download_cancelled_callback"])
def test_download_terminal_callbacks_preserve_recovery_protected_staging(
callback_name: str, mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@@ -4264,7 +4495,7 @@ def test_remote_download_replacement_waits_for_previous_callback(
job.download_parts = old_download.download_parts
installer._download_cache[old_download.id] = job
remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)
- monkeypatch.setattr(installer, "_remote_files_from_source", lambda _: ([remote_file], None))
+ monkeypatch.setattr(installer, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None))
monkeypatch.setattr(installer._download_queue, "submit_multifile_download", MagicMock())
with pytest.raises(InstallDownloadConflictError, match="previous download"):
@@ -4299,7 +4530,7 @@ def test_concurrent_restart_requests_are_serialized(
metadata_started = threading.Event()
release_metadata = threading.Event()
- def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:
+ def blocked_metadata(_source: URLModelSource, revision: str | None = None) -> tuple[list[RemoteModelFile], None]:
metadata_started.set()
assert release_metadata.wait(timeout=5)
return [remote_file], None
@@ -4351,7 +4582,7 @@ def test_concurrent_resume_requests_are_serialized(
metadata_started = threading.Event()
release_metadata = threading.Event()
- def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:
+ def blocked_metadata(_source: URLModelSource, revision: str | None = None) -> tuple[list[RemoteModelFile], None]:
metadata_started.set()
assert release_metadata.wait(timeout=5)
return [remote_file], None
@@ -4460,7 +4691,7 @@ def test_remote_download_retry_with_no_matching_files_preserves_retryable_state(
)
_stage(job, tmp_path)
job._multifile_job = MultiFileDownloadJob(id=4590, dest=tmp_path, download_parts={part})
- monkeypatch.setattr(installer, "_remote_files_from_source", lambda _: ([], None))
+ monkeypatch.setattr(installer, "_remote_files_from_source", lambda _source, revision=None: ([], None))
with pytest.raises(RuntimeError, match="No remote files are available to download"):
if operation == "resume":
@@ -4564,7 +4795,7 @@ def test_install_state_changes_conflict_during_remote_download_handoff(
metadata_started = threading.Event()
release_metadata = threading.Event()
- def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:
+ def blocked_metadata(_source: URLModelSource, revision: str | None = None) -> tuple[list[RemoteModelFile], None]:
metadata_started.set()
assert release_metadata.wait(timeout=5)
return [remote_file], None
@@ -4636,7 +4867,7 @@ def test_shutdown_waits_for_remote_download_handoff_and_preserves_pause(
release_metadata = threading.Event()
stop_finished = threading.Event()
- def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:
+ def blocked_metadata(_source: URLModelSource, revision: str | None = None) -> tuple[list[RemoteModelFile], None]:
metadata_started.set()
assert release_metadata.wait(timeout=5)
return [remote_file], None
@@ -4766,7 +4997,9 @@ def test_resume_reports_restart_from_scratch_on_fresh_parts(
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, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None)
+ )
submit_multifile_download = MagicMock()
monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", submit_multifile_download)
@@ -4796,7 +5029,9 @@ def test_resume_reports_restart_from_scratch_only_for_a_partial_it_cannot_valida
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, "_remote_files_from_source", lambda _source, revision=None: ([remote_file], None)
+ )
monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", MagicMock())
mm2_installer.resume_job(job)
@@ -4850,6 +5085,2156 @@ def test_other_error_during_install(
assert job.error == "Test error"
+GOOD_URL = "https://test.com/aaa_good_part.safetensors"
+BAD_URL = "https://test.com/zzz_bad_part.safetensors"
+
+
+class _WaitObservingEvent(threading.Event):
+ """The installer's wake-up event; `waiting` is set once wait_for_job() first blocks on it."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.waiting = threading.Event()
+
+ def wait(self, timeout: float | None = None) -> bool:
+ self.waiting.set()
+ return super().wait(timeout)
+
+
+class _GatedAdapter(BaseAdapter):
+ """Holds a request until the test is blocked in wait_for_job(), so the failure has to wake it."""
+
+ def __init__(self, inner: BaseAdapter, gate: threading.Event) -> None:
+ super().__init__()
+ self._inner = inner
+ self._gate = gate
+
+ def send(self, request, **kwargs):
+ assert self._gate.wait(timeout=10)
+ return self._inner.send(request, **kwargs)
+
+ def close(self) -> None:
+ self._inner.close()
+
+
+class _RaisingAdapter(BaseAdapter):
+ def __init__(self, excp: Exception) -> None:
+ super().__init__()
+ self._excp = excp
+
+ def send(self, request, **kwargs):
+ raise self._excp
+
+ def close(self) -> None:
+ pass
+
+
+class _BrokenStream:
+ """A response body that yields `body` and then drops the connection with `error`."""
+
+ def __init__(self, body: bytes, error: Exception) -> None:
+ self._body = body
+ self._error = error
+
+ def stream(self, chunk_size: int, decode_content: bool = True):
+ if self._body:
+ yield self._body
+ raise self._error
+
+ def close(self) -> None:
+ pass
+
+
+class _BrokenStreamAdapter(BaseAdapter):
+ def __init__(
+ self,
+ body: bytes = b"partial-progress-bytes",
+ total: int = 100,
+ error: Exception | None = None,
+ etag: str | None = None,
+ ) -> None:
+ super().__init__()
+ self._body = body
+ self._total = total
+ self._error = error or ProtocolError("Connection broken: IncompleteRead")
+ self._etag = etag
+
+ def send(self, request, **kwargs):
+ response = Response()
+ response.status_code = 200
+ response.headers["Content-Length"] = str(self._total)
+ if self._etag is not None:
+ response.headers["ETag"] = self._etag
+ response.url = request.url
+ response.request = request
+ response.raw = _BrokenStream(self._body, self._error)
+ return response
+
+ def close(self) -> None:
+ pass
+
+
+def _install_with_failing_part(
+ installer: ModelInstallService,
+ session,
+ monkeypatch: pytest.MonkeyPatch,
+ failing_adapter: BaseAdapter,
+ completed_part_data: bytes | None,
+) -> tuple[ModelInstallJob, ModelInstallJob, Path]:
+ """Install a model whose last part fails while the caller is blocked in wait_for_job().
+
+ Parts download one at a time in URL order, so the optional good part completes before the failing one starts.
+ """
+ files = []
+ if completed_part_data is not None:
+ session.mount(
+ GOOD_URL,
+ TestAdapter(
+ completed_part_data,
+ headers={"Content-Type": "application/octet-stream", "Content-Length": len(completed_part_data)},
+ ),
+ )
+ files.append(
+ RemoteModelFile(url=Url(GOOD_URL), path=Path("good_part.safetensors"), size=len(completed_part_data))
+ )
+ files.append(RemoteModelFile(url=Url(BAD_URL), path=Path("bad_part.safetensors"), size=100))
+ monkeypatch.setattr(installer, "_remote_files_from_source", lambda _source, revision=None: (files, None))
+
+ # Without a wake-up signal wait_for_job() would sleep a whole poll and then hit its timeout.
+ wake = _WaitObservingEvent()
+ monkeypatch.setattr(installer, "_install_completed_event", wake)
+ monkeypatch.setattr("invokeai.app.services.model_install.model_install_default._JOB_WAIT_POLL_SECONDS", 30.0)
+ session.mount(BAD_URL, _GatedAdapter(failing_adapter, wake.waiting))
+
+ job = installer.import_model(URLModelSource(url=Url(BAD_URL)))
+ tmpdir = job._staging.tmpdir
+ assert tmpdir is not None
+ returned = installer.wait_for_job(job, timeout=10)
+ # The callback that settled the job may still be cleaning up; let the download worker finish it.
+ installer._download_queue.join()
+ return job, returned, tmpdir
+
+
+def test_wait_for_paused_job_waits_for_download_callback(
+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert isinstance(mm2_installer, ModelInstallService)
+ installer = mm2_installer
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors")
+ download_job = MultiFileDownloadJob(id=6101, dest=tmp_path, download_parts={part})
+ job = ModelInstallJob(
+ id=6101,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmp_path,
+ status=InstallStatus.PAUSED,
+ )
+ _stage(job, tmp_path)
+ job._multifile_job = download_job
+ installer._download_cache[download_job.id] = job
+
+ wake = _WaitObservingEvent()
+ monkeypatch.setattr(installer, "_install_completed_event", wake)
+ monkeypatch.setattr("invokeai.app.services.model_install.model_install_default._JOB_WAIT_POLL_SECONDS", 30.0)
+ returned: list[ModelInstallJob] = []
+ waiter = threading.Thread(target=lambda: returned.append(installer.wait_for_job(job, timeout=10)))
+ waiter.start()
+ try:
+ assert wake.waiting.wait(timeout=5)
+ assert waiter.is_alive()
+ installer._download_cancelled_callback(download_job)
+ waiter.join(timeout=5)
+ assert not waiter.is_alive()
+ assert returned == [job]
+ assert job.paused
+ assert download_job.id not in installer._download_cache
+ finally:
+ if waiter.is_alive():
+ wake.set()
+ waiter.join(timeout=5)
+
+
+def test_resume_and_wait_honours_its_timeout_while_a_download_callback_is_pending(
+ mm2_installer: ModelInstallService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors")
+ pending_callback = MultiFileDownloadJob(id=6104, dest=tmp_path, download_parts={part})
+ job = ModelInstallJob(
+ id=6104, source=source, config_in=ModelRecordChanges(), local_path=tmp_path, status=InstallStatus.PAUSED
+ )
+ _stage(job, tmp_path)
+ job._multifile_job = pending_callback
+ mm2_installer._download_cache[pending_callback.id] = job
+ # Only the timeout can end this wait: nothing signals, and the poll is longer than the test allows.
+ monkeypatch.setattr("invokeai.app.services.model_install.model_install_default._JOB_WAIT_POLL_SECONDS", 30.0)
+ try:
+ started = time.monotonic()
+ with pytest.raises(TimeoutError):
+ mm2_installer.resume_and_wait_for_job(job, timeout=0.2)
+ assert time.monotonic() - started < 5
+ assert job.paused
+ finally:
+ mm2_installer._download_cache.pop(pending_callback.id, None)
+
+
+def test_resume_and_wait_returns_a_paused_job_while_the_service_is_stopping(
+ mm2_installer: ModelInstallService, tmp_path: Path
+) -> None:
+ job = ModelInstallJob(
+ id=6105,
+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),
+ config_in=ModelRecordChanges(),
+ local_path=tmp_path,
+ status=InstallStatus.PAUSED,
+ )
+ _stage(job, tmp_path)
+ mm2_installer._stop_event.set()
+ try:
+ # A stopping service refuses every resume; retrying would spin until the timeout.
+ assert mm2_installer.resume_and_wait_for_job(job, timeout=2) is job
+ assert job.paused
+ finally:
+ mm2_installer._stop_event.clear()
+
+
+def test_resume_and_wait_returns_a_paused_job_whose_partial_cannot_be_deleted(
+ mm2_installer: ModelInstallService, mm2_app_config: InvokeAIAppConfig, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A resume refused because a partial it must restart is locked (Windows) is not retried in a loop."""
+ url = "https://example.com/model.safetensors"
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}locked-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ partial = tmpdir / "model.safetensors.downloading"
+ partial.write_bytes(b"x" * 10)
+ job = ModelInstallJob(
+ id=98771,
+ source=URLModelSource(url=Url(url)),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.PAUSED,
+ )
+ _stage(job, tmpdir).claim()
+ # No validator was recorded, so the resume must delete the partial before downloading again.
+ job._resume_metadata = {url: {"url": url, "download_path": (tmpdir / "model.safetensors").as_posix()}}
+ calls: list[str] = []
+
+ def remote_files(_source: ModelSource, revision: str | None = None) -> tuple[list[RemoteModelFile], None]:
+ calls.append(str(_source))
+ return [RemoteModelFile(url=Url(url), path=Path("model.safetensors"), size=10)], None
+
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", remote_files)
+ real_unlink = Path.unlink
+
+ def locked_unlink(self: Path, *args: Any, **kwargs: Any) -> None:
+ if self == partial:
+ raise PermissionError(13, "The process cannot access the file", str(self))
+ real_unlink(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", locked_unlink)
+ mm2_installer._install_jobs.append(job)
+ try:
+ started = time.monotonic()
+ assert mm2_installer.resume_and_wait_for_job(job, timeout=10) is job
+ assert time.monotonic() - started < 5
+ assert job.paused
+ assert len(calls) == 1
+ assert partial.exists()
+ finally:
+ monkeypatch.undo()
+ mm2_installer._install_jobs.remove(job)
+ job._staging.release_claim()
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def _tls_eof_mid_stream() -> Urllib3SSLError:
+ """The urllib3 error a CDN closing TLS without close_notify raises while the body streams."""
+ return Urllib3SSLError(ssl.SSLEOFError(8, "EOF occurred in violation of protocol"))
+
+
+ ("failing_adapter", "completed_part", "error_type"),
+ [
+ (lambda: TestAdapter(b"forbidden", status=403), True, "HTTPError"),
+ (lambda: TestAdapter(b"missing", status=404), True, "HTTPError"),
+ (lambda: TestAdapter(b"", headers={"Content-Length": str(2**62)}), True, "RuntimeError"),
+ (lambda: _RaisingAdapter(RequestsConnectionError("connection refused")), False, "ConnectionError"),
+ (lambda: _BrokenStreamAdapter(body=b""), False, "ChunkedEncodingError"),
+ # A resume deletes a partial its server sent no validator for, so it is nothing to keep.
+ (_BrokenStreamAdapter, False, "ChunkedEncodingError"),
+ ],
+ ids=[
+ "http-403",
+ "http-404",
+ "out-of-disk",
+ "transient-with-nothing-staged",
+ "transient-with-empty-partial",
+ "transient-with-unvalidated-partial",
+ ],
+)
+def test_part_error_fails_install_unless_transient_with_staged_data(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ failing_adapter: Callable[[], BaseAdapter],
+ completed_part: bool,
+ error_type: str,
+) -> None:
+ tmpdir: Path | None = None
+ try:
+ job, returned, tmpdir = _install_with_failing_part(
+ mm2_installer,
+ mm2_session,
+ monkeypatch,
+ failing_adapter(),
+ embedding_file.read_bytes() if completed_part else None,
+ )
+
+ assert returned is job
+ assert job.status == InstallStatus.ERROR
+ assert job.error_type == error_type
+ assert not tmpdir.exists()
+ events = mm2_installer.event_bus
+ assert isinstance(events, TestEventService)
+ assert any(isinstance(event, ModelInstallErrorEvent) and event.id == job.id for event in events.events)
+ assert not any(isinstance(event, ModelInstallPausedEvent) for event in events.events)
+ finally:
+ if tmpdir is not None:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+ ("failing_adapter", "completed_part", "failed_part_error_type"),
+ [
+ (lambda: TestAdapter(b"server error", status=503), True, "HTTPError("),
+ (lambda: _RaisingAdapter(RequestsConnectionError("connection reset")), True, "ConnectionError("),
+ (lambda: _BrokenStreamAdapter(etag=_FILE_ETAG), False, "ChunkedEncodingError("),
+ (lambda: _BrokenStreamAdapter(error=_tls_eof_mid_stream(), etag=_FILE_ETAG), False, "SSLError("),
+ ],
+ ids=[
+ "http-503-after-completed-part",
+ "connection-error-after-completed-part",
+ "dropped-stream-partial-only",
+ "tls-dropped-mid-stream-partial-only",
+ ],
+)
+def test_transient_part_error_pauses_install_and_keeps_staging(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ failing_adapter: Callable[[], BaseAdapter],
+ completed_part: bool,
+ failed_part_error_type: str,
+) -> None:
+ """Issue #9481: a transient part failure keeps completed parts and resumable partials for resume or retry."""
+ good_data = embedding_file.read_bytes()
+ tmpdir: Path | None = None
+ try:
+ job, returned, tmpdir = _install_with_failing_part(
+ mm2_installer, mm2_session, monkeypatch, failing_adapter(), good_data if completed_part else None
+ )
+
+ assert returned is job
+ assert job.status == InstallStatus.PAUSED
+ assert job.error is None
+ if completed_part:
+ assert (tmpdir / "good_part.safetensors").read_bytes() == good_data
+ else:
+ assert (tmpdir / "bad_part.safetensors.downloading").read_bytes() == b"partial-progress-bytes"
+ marker = _read_marker(tmpdir)
+ assert marker is not None and marker["status"] == InstallStatus.PAUSED.value
+
+ # The list-installs route serializes the job, so the UI can name the failed part and its cause.
+ [failed_part] = [part for part in job.model_dump(mode="json")["download_parts"] if part["source"] == BAD_URL]
+ assert failed_part["status"] == DownloadJobStatus.ERROR.value
+ assert failed_part["error_type"].startswith(failed_part_error_type)
+ assert failed_part["error"]
+
+ events = mm2_installer.event_bus
+ assert isinstance(events, TestEventService)
+ assert any(isinstance(event, ModelInstallPausedEvent) and event.id == job.id for event in events.events)
+ assert not any(isinstance(event, ModelInstallErrorEvent) for event in events.events)
+ finally:
+ if tmpdir is not None:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_retry_that_fails_again_keeps_parts_completed_by_earlier_attempt(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Retrying only re-downloads unfinished files, so a repeat failure must not judge staging by those alone."""
+ good_data = embedding_file.read_bytes()
+ tmpdir: Path | None = None
+ try:
+ job, _, tmpdir = _install_with_failing_part(
+ mm2_installer, mm2_session, monkeypatch, TestAdapter(b"server error", status=503), good_data
+ )
+ assert job.paused
+
+ mm2_session.mount(BAD_URL, _RaisingAdapter(RequestsConnectionError("network still down")))
+ mm2_installer.restart_failed(job)
+ mm2_installer.wait_for_job(job, timeout=10)
+ mm2_installer._download_queue.join()
+
+ assert job.status == InstallStatus.PAUSED
+ assert {str(part.source) for part in job.download_parts} == {BAD_URL}
+ assert (tmpdir / "good_part.safetensors").read_bytes() == good_data
+ finally:
+ if tmpdir is not None:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+_FILE_ETAG = '"file-v1"'
+
+
+class _DropThenResumeAdapter(BaseAdapter):
+ """Drops the first transfer of `data` after `cut` bytes, then serves the rest to a range request.
+
+ Every response carries the file's ETag, which a resume sends back as If-Range.
+ """
+
+ def __init__(self, data: bytes, cut: int) -> None:
+ super().__init__()
+ self._data = data
+ self._cut = cut
+ self.requests: list = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ if len(self.requests) == 1:
+ return _BrokenStreamAdapter(body=self._data[: self._cut], total=len(self._data), etag=_FILE_ETAG).send(
+ request
+ )
+ if "Range" not in request.headers or request.headers.get("If-Range") != _FILE_ETAG:
+ return TestAdapter(self._data, headers={"Content-Length": len(self._data), "ETag": _FILE_ETAG}).send(
+ request, **kwargs
+ )
+ rest = self._data[self._cut :]
+ return TestAdapter(
+ rest,
+ status=206,
+ headers={
+ "Content-Range": f"bytes {self._cut}-{len(self._data) - 1}/{len(self._data)}",
+ "Content-Length": len(rest),
+ "ETag": _FILE_ETAG,
+ },
+ ).send(request, **kwargs)
+
+ def close(self) -> None:
+ pass
+
+
+def test_transient_pause_resumes_to_completed_install(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ diffusers_dir: Path,
+) -> None:
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ cut = 100
+ flaky = _DropThenResumeAdapter(unet_config, cut)
+ mm2_session.mount(
+ f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/{SDXL_TURBO_COMMIT}/unet/config.json", flaky
+ )
+
+ job = mm2_installer.import_model(URLModelSource(url=Url("https://huggingface.co/stabilityai/sdxl-turbo")))
+ mm2_installer.wait_for_job(job, timeout=10)
+ mm2_installer._download_queue.join()
+ assert job.status == InstallStatus.PAUSED
+ tmpdir = job._staging.tmpdir
+ assert tmpdir is not None
+ [staged_index] = tmpdir.rglob("model_index.json")
+ # An old timestamp shows whether the resume rewrote this already-downloaded file.
+ os.utime(staged_index, ns=(1_000_000_000_000_000_000, 1_000_000_000_000_000_000))
+
+ mm2_installer.resume_job(job)
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED
+ assert len(flaky.requests) == 2
+ assert flaky.requests[1].headers["Range"] == f"bytes={cut}-"
+ assert job.config_out is not None
+ installed = mm2_app_config.models_path / job.config_out.path
+ assert (installed / "unet" / "config.json").read_bytes() == unet_config
+ assert (installed / "model_index.json").stat().st_mtime_ns == 1_000_000_000_000_000_000
+
+
+class _CountingAdapter(BaseAdapter):
+ def __init__(self, inner: BaseAdapter) -> None:
+ super().__init__()
+ self._inner = inner
+ self.requests: list = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ return self._inner.send(request, **kwargs)
+
+ def close(self) -> None:
+ self._inner.close()
+
+
+_SDXL_TURBO_URL = "https://huggingface.co/stabilityai/sdxl-turbo"
+_SDXL_TURBO_API = "https://huggingface.co/api/models/stabilityai/sdxl-turbo"
+_NEWER_COMMIT = "1111111111111111111111111111111111111111"
+
+
+def _pause_sdxl_turbo_install_in_unet_config(
+ installer: ModelInstallService, session, unet_config: bytes, cut: int, source: ModelSource | None = None
+):
+ """Start the sdxl-turbo install and let unet/config.json drop after `cut` bytes, pausing the install."""
+ flaky = _DropThenResumeAdapter(unet_config, cut)
+ session.mount(f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/unet/config.json", flaky)
+ job = installer.import_model(source or URLModelSource(url=Url(_SDXL_TURBO_URL)))
+ installer.wait_for_job(job, timeout=10)
+ installer._download_queue.join()
+ assert job.status == InstallStatus.PAUSED
+ return job, flaky
+
+
+class _RepoFilesAdapter(BaseAdapter):
+ """Serves repository files under `prefix` from `files` (relative path -> bytes), recording each request.
+
+ Like the Hugging Face CDN, it honours a Range request and sends an ETag (`_FILE_ETAG`, whatever the contents), so
+ a resume can send If-Range and has it accepted.
+ """
+
+ def __init__(self, prefix: str, files: dict[str, bytes]) -> None:
+ super().__init__()
+ self._prefix = prefix
+ self._files = files
+ self.requests: list = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ data = self._files.get(request.url.removeprefix(self._prefix))
+ if data is None:
+ return TestAdapter(b"", status=404).send(request, **kwargs)
+ if match := re.fullmatch(r"bytes=(\d+)-", request.headers.get("Range", "")):
+ start = int(match.group(1))
+ headers = {
+ "Content-Length": len(data) - start,
+ "Content-Range": f"bytes {start}-{len(data) - 1}/{len(data)}",
+ "ETag": _FILE_ETAG,
+ }
+ return TestAdapter(data[start:], status=206, headers=headers).send(request, **kwargs)
+ return TestAdapter(data, headers={"Content-Length": len(data), "ETag": _FILE_ETAG}).send(request, **kwargs)
+
+ def close(self) -> None:
+ pass
+
+
+def _move_sdxl_turbo_main_to_newer_commit(session, diffusers_dir: Path) -> list[_RepoFilesAdapter]:
+ """Point main at a newer commit whose files keep their sizes but change their contents."""
+ newer_metadata = RepoHFMetadata1.replace(SDXL_TURBO_COMMIT.encode(), _NEWER_COMMIT.encode())
+ # These match unpinned metadata requests only (the default variant asks for "/revision/" with no name); a pinned
+ # request names the commit after "/revision/".
+ for unpinned in (f"{_SDXL_TURBO_API}?", f"{_SDXL_TURBO_API}/revision/?"):
+ session.mount(unpinned, TestAdapter(newer_metadata, headers={"Content-Length": len(newer_metadata)}))
+ changed = { # same sizes, different bytes
+ path.relative_to(diffusers_dir).as_posix(): bytes(b ^ 0x20 for b in path.read_bytes())
+ for path in diffusers_dir.rglob("*")
+ if path.is_file()
+ }
+ newer_files = []
+ for revision in (_NEWER_COMMIT, "main"):
+ prefix = f"{_SDXL_TURBO_URL}/resolve/{revision}/"
+ newer_files.append(_RepoFilesAdapter(prefix, changed))
+ for name in changed: # outrank the fixture's per-file mounts
+ session.mount(prefix + name, newer_files[-1])
+ return newer_files
+
+
[email protected]("operation", ["resume", "restart_failed", "restart_file"])
+ "source",
+ [
+ URLModelSource(url=Url(_SDXL_TURBO_URL)),
+ HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default),
+ ],
+ ids=["url-source", "hf-source"],
+)
+def test_resume_keeps_the_hugging_face_commit_the_install_started_from(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ diffusers_dir: Path,
+ source: ModelSource,
+ operation: str,
+) -> None:
+ """A repo whose main moves while an install is paused must not get files from both commits."""
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ job, flaky = _pause_sdxl_turbo_install_in_unet_config(
+ mm2_installer, mm2_session, unet_config, cut=100, source=source
+ )
+ assert job._staging.tmpdir is not None
+ marker = _read_marker(job._staging.tmpdir)
+ assert marker is not None and marker["revision"] == SDXL_TURBO_COMMIT
+
+ newer_files = _move_sdxl_turbo_main_to_newer_commit(mm2_session, diffusers_dir)
+ pinned_metadata = _CountingAdapter(TestAdapter(RepoHFMetadata1, headers={"Content-Length": len(RepoHFMetadata1)}))
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", pinned_metadata)
+
+ if operation == "resume":
+ mm2_installer.resume_job(job)
+ elif operation == "restart_failed":
+ mm2_installer.restart_failed(job)
+ else:
+ mm2_installer.restart_file(job, f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/unet/config.json")
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert len(pinned_metadata.requests) == 1
+ assert [adapter.requests for adapter in newer_files] == [[], []]
+ if operation == "resume":
+ assert flaky.requests[1].headers["Range"] == "bytes=100-"
+ assert job.config_out is not None
+ installed = mm2_app_config.models_path / job.config_out.path
+ installed_files = [path for path in installed.rglob("*") if path.is_file()]
+ assert installed / "unet" / "config.json" in installed_files
+ for path in installed_files:
+ assert path.read_bytes() == (diffusers_dir / path.relative_to(installed)).read_bytes(), path
+
+
+ ("staged_revision", "reused"), [(SDXL_TURBO_COMMIT, True), ("0" * 40, False)], ids=["same-commit", "other-commit"]
+)
+def test_new_install_reuses_staging_only_from_the_same_commit(
+ mm2_installer: ModelInstallService, mm2_app_config: InvokeAIAppConfig, staged_revision: str, reused: bool
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ staged = mm2_app_config.models_path / f"{TMPDIR_PREFIX}staged-{uuid.uuid4().hex}"
+ staged.mkdir()
+ staged_job = ModelInstallJob(
+ id=98768,
+ source=URLModelSource(url=Url(_SDXL_TURBO_URL)),
+ config_in=ModelRecordChanges(),
+ local_path=staged,
+ status=InstallStatus.PAUSED,
+ )
+ _stage(staged_job, staged)
+ staged_job._source_revision = staged_revision
+ mm2_installer._write_install_marker(staged_job, status=InstallStatus.PAUSED)
+ try:
+ job = mm2_installer.import_model(URLModelSource(url=Url(_SDXL_TURBO_URL)))
+ assert (job._staging.tmpdir == staged) is reused
+ mm2_installer.wait_for_job(job, timeout=10)
+ assert job.complete, job.error
+ finally:
+ _claim_path(staged).unlink(missing_ok=True)
+ shutil.rmtree(staged, ignore_errors=True)
+
+
+_VANISHED_REVISION_ERROR = "changed after this download started"
+
+
[email protected]("operation", ["resume", "restart_failed", "restart_file"])
+def test_resume_errors_an_install_pinned_to_a_vanished_commit(
+ mm2_installer: ModelInstallService, mm2_session, diffusers_dir: Path, operation: str
+) -> None:
+ """Staged files from a commit that no longer exists can never be completed, so the install ends in error."""
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ job, flaky = _pause_sdxl_turbo_install_in_unet_config(mm2_installer, mm2_session, unet_config, cut=100)
+ tmpdir = job._staging.tmpdir
+ assert tmpdir is not None
+ _move_sdxl_turbo_main_to_newer_commit(mm2_session, diffusers_dir)
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", TestAdapter(b"", status=404))
+
+ with pytest.raises(ModelRevisionUnavailableError, match=_VANISHED_REVISION_ERROR):
+ if operation == "resume":
+ mm2_installer.resume_job(job)
+ elif operation == "restart_failed":
+ mm2_installer.restart_failed(job)
+ else:
+ mm2_installer.restart_file(job, f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/unet/config.json")
+
+ assert job.status == InstallStatus.ERROR
+ assert job.error is not None and _VANISHED_REVISION_ERROR in job.error
+ assert not tmpdir.exists()
+ assert not _claim_path(tmpdir).exists()
+ assert len(flaky.requests) == 1
+ events = mm2_installer.event_bus
+ assert isinstance(events, TestEventService)
+ assert any(isinstance(event, ModelInstallErrorEvent) and event.id == job.id for event in events.events)
+
+
[email protected]("staging_removed", [True, False], ids=["staging-removed", "staging-left-behind"])
+def test_retry_after_a_vanished_commit_starts_a_new_install_at_the_current_head(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ diffusers_dir: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ staging_removed: bool,
+) -> None:
+ """The errored install keeps no parts, so Retry resubmits the source instead of restarting the vanished commit.
+
+ That holds even when its staging could not be removed (a Windows file lock fails the removal silently).
+ """
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ job, flaky = _pause_sdxl_turbo_install_in_unet_config(mm2_installer, mm2_session, unet_config, cut=100)
+ staging = job._staging.tmpdir
+ assert staging is not None
+ if not staging_removed:
+ monkeypatch.setattr(install_staging_ledger, "_remove_tree", lambda _path, _logger: None)
+ newer_files = _move_sdxl_turbo_main_to_newer_commit(mm2_session, diffusers_dir)
+ vanished = _CountingAdapter(TestAdapter(b"", status=404))
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", vanished)
+ with pytest.raises(ModelRevisionUnavailableError, match=_VANISHED_REVISION_ERROR):
+ mm2_installer.restart_failed(job)
+ assert job.status == InstallStatus.ERROR
+ assert job.download_parts == set()
+ assert staging.exists() is not staging_removed
+
+ # Nothing is left to restart: these leave the errored job alone instead of asking for the vanished commit again.
+ mm2_installer.resume_job(job)
+ mm2_installer.restart_failed(job)
+ mm2_installer.restart_file(job, f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/unet/config.json")
+ assert job.status == InstallStatus.ERROR
+ assert len(vanished.requests) == 1
+ assert len(flaky.requests) == 1
+
+ fresh = mm2_installer.import_model(URLModelSource(url=Url(_SDXL_TURBO_URL)))
+ try:
+ assert fresh is not job
+ assert fresh._source_revision == _NEWER_COMMIT
+ assert fresh._staging.tmpdir != job._staging.tmpdir
+ assert fresh.download_parts
+ assert all(f"/resolve/{_NEWER_COMMIT}/" in str(part.source) for part in fresh.download_parts)
+ mm2_installer.wait_for_job(fresh, timeout=10)
+ assert newer_files[0].requests
+ finally:
+ if not fresh.in_terminal_state:
+ mm2_installer.cancel_job(fresh)
+ mm2_installer.wait_for_job(fresh, timeout=10)
+ shutil.rmtree(staging, ignore_errors=True)
+
+
+def test_auto_install_of_a_vanished_commit_fails_once_then_installs_afresh(
+ mm2_installer: ModelInstallService, mm2_session, diffusers_dir: Path
+) -> None:
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ job, _ = _pause_sdxl_turbo_install_in_unet_config(mm2_installer, mm2_session, unet_config, cut=100)
+ _move_sdxl_turbo_main_to_newer_commit(mm2_session, diffusers_dir)
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", TestAdapter(b"", status=404))
+ context = SimpleNamespace(
+ models=SimpleNamespace(search_by_attrs=lambda **_kwargs: []),
+ logger=MagicMock(),
+ _services=SimpleNamespace(model_manager=SimpleNamespace(install=mm2_installer)),
+ )
+
+ with pytest.raises(RuntimeError, match=rf"turbo-encoder.*'error'.*{_VANISHED_REVISION_ERROR}"):
+ IPAdapterInvocation.get_clip_image_encoder(context, _SDXL_TURBO_URL, "turbo-encoder")
+ assert job.status == InstallStatus.ERROR
+
+ # The next run is no longer tied to the errored job: it starts a new install at the repository's new head.
+ fresh = mm2_installer.heuristic_import(_SDXL_TURBO_URL)
+ try:
+ assert fresh is not job
+ assert fresh._source_revision == _NEWER_COMMIT
+ finally:
+ mm2_installer.cancel_job(fresh)
+ mm2_installer.wait_for_job(fresh, timeout=10)
+
+
+def test_restored_install_resumes_from_its_pinned_commit(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ diffusers_dir: Path,
+) -> None:
+ unet_config = (diffusers_dir / "unet" / "config.json").read_bytes()
+ job, flaky = _pause_sdxl_turbo_install_in_unet_config(mm2_installer, mm2_session, unet_config, cut=100)
+ # A restart: the old process's job and claim go away; its staging and marker stay for the next one to restore.
+ mm2_installer._install_jobs.remove(job)
+ job._staging.release_claim()
+ newer_files = _move_sdxl_turbo_main_to_newer_commit(mm2_session, diffusers_dir)
+ pinned_metadata = _CountingAdapter(TestAdapter(RepoHFMetadata1, headers={"Content-Length": len(RepoHFMetadata1)}))
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", pinned_metadata)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ assert restored_job.paused
+ restored_installer.resume_job(restored_job)
+ restored_installer.wait_for_job(restored_job, timeout=10)
+
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ assert len(pinned_metadata.requests) == 1
+ assert [adapter.requests for adapter in newer_files] == [[], []]
+ assert flaky.requests[1].headers["Range"] == "bytes=100-"
+ assert restored_job.config_out is not None
+ installed = mm2_app_config.models_path / restored_job.config_out.path
+ installed_files = [path for path in installed.rglob("*") if path.is_file()]
+ assert installed / "unet" / "config.json" in installed_files
+ for path in installed_files:
+ assert path.read_bytes() == (diffusers_dir / path.relative_to(installed)).read_bytes(), path
+ finally:
+ restored_installer.stop()
+
+
+_MIRROR = "https://hf-mirror.example"
+
+
+ ("marker_revision", "file_url", "restored_revision", "endpoint"),
+ [
+ (SDXL_TURBO_COMMIT, f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/model_index.json", SDXL_TURBO_COMMIT, None),
+ # A marker written before installs were pinned names no commit: its staging is discarded and the resume
+ # pins the commit it fetches.
+ ("<absent>", f"{_SDXL_TURBO_URL}/resolve/main/model_index.json", None, None),
+ ("<absent>", f"{_MIRROR}/stabilityai/sdxl-turbo/resolve/main/model_index.json", None, _MIRROR),
+ # An install from a source without repository revisions stays unpinned.
+ (None, "https://example.com/model_index.json", None, None),
+ ],
+ ids=["pinned", "legacy-marker", "legacy-marker-from-mirror", "unpinned"],
+)
+def test_restore_keeps_the_revision_an_install_is_pinned_to(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ monkeypatch: pytest.MonkeyPatch,
+ marker_revision: str | None,
+ file_url: str,
+ restored_revision: str | None,
+ endpoint: str | None,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ if endpoint is not None:
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}pinned-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ part = DownloadJob(source=Url(file_url), dest=tmpdir / "sdxl-turbo" / "model_index.json")
+ paused_job = ModelInstallJob(
+ id=98767,
+ source=URLModelSource(url=Url(_SDXL_TURBO_URL)),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.PAUSED,
+ download_parts={part},
+ )
+ _stage(paused_job, tmpdir)
+ paused_job._source_revision = None if marker_revision == "<absent>" else marker_revision
+ mm2_installer._write_install_marker(paused_job, status=InstallStatus.PAUSED)
+ if marker_revision == "<absent>":
+ marker_path = tmpdir / INSTALL_MARKER_FILENAME
+ marker = json.loads(marker_path.read_text())
+ del marker["revision"]
+ marker_path.write_text(json.dumps(marker))
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ try:
+ restored_installer._restore_incomplete_installs()
+ [restored_job] = restored_installer.list_jobs()
+ assert restored_job.paused
+ assert restored_job._source_revision == restored_revision
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def _write_legacy_marker(
+ installer: ModelInstallService,
+ tmpdir: Path,
+ source: ModelSource,
+ status: InstallStatus,
+ staged: dict[str, Path],
+ revision: str | None = "<absent>",
+) -> None:
+ """Write an install marker that names no commit; `staged` maps file url -> dest.
+
+ By default it has no "revision", as versions before pinning wrote it; `revision` writes that value instead.
+ """
+ parts = set()
+ for url, dest in staged.items():
+ part = DownloadJob(source=Url(url), dest=dest)
+ part.download_path = dest
+ part.etag = _FILE_ETAG # what the server sent for the partial, so a resume may send If-Range
+ parts.add(part)
+ job = ModelInstallJob(
+ id=98770,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=status,
+ download_parts=parts,
+ )
+ _stage(job, tmpdir)
+ installer._write_install_marker(job, status=status)
+ marker_path = tmpdir / INSTALL_MARKER_FILENAME
+ marker = json.loads(marker_path.read_text())
+ if revision == "<absent>":
+ del marker["revision"]
+ else:
+ marker["revision"] = revision
+ marker_path.write_text(json.dumps(marker))
+
+
+ "source",
+ [
+ URLModelSource(url=Url(_SDXL_TURBO_URL)),
+ HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default),
+ ],
+ ids=["url-source", "hf-source"],
+)
+ ("files_endpoint", "marker_revision"),
+ [
+ (_SDXL_TURBO_URL, "<absent>"),
+ ("https://old-mirror.example/stabilityai/sdxl-turbo", "<absent>"),
+ (_SDXL_TURBO_URL, None),
+ (_SDXL_TURBO_URL, "main"),
+ ],
+ ids=["pre-pinning-marker", "pre-pinning-marker-from-another-endpoint", "null-revision", "branch-revision"],
+)
+def test_restore_discards_a_download_not_pinned_to_a_commit(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ diffusers_dir: Path,
+ source: ModelSource,
+ files_endpoint: str,
+ marker_revision: str | None,
+) -> None:
+ """A marker that names no commit holds files from a branch that may have moved since they were staged.
+
+ Here the branch has moved: the staged files came from an older commit than the one the restore downloads, and
+ keeping them would install a model mixing both, so the download starts over.
+ """
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}legacy-{uuid.uuid4().hex}"
+ staged_root = tmpdir / "sdxl-turbo"
+ old_endpoint = f"{files_endpoint}/resolve/main"
+ complete = staged_root / "vae" / "config.json"
+ partial = staged_root / "unet" / "config.json"
+ complete.parent.mkdir(parents=True)
+ partial.parent.mkdir(parents=True)
+ # The older commit's bytes: the same sizes as the current commit's files, different contents.
+ complete.write_bytes(bytes(b ^ 0x20 for b in (diffusers_dir / "vae" / "config.json").read_bytes()))
+ stale_prefix = bytes(b ^ 0x20 for b in (diffusers_dir / "unet" / "config.json").read_bytes()[:100])
+ partial.with_name("config.json.downloading").write_bytes(stale_prefix)
+ _write_legacy_marker(
+ mm2_installer,
+ tmpdir,
+ source,
+ InstallStatus.DOWNLOADING,
+ {f"{old_endpoint}/vae/config.json": complete, f"{old_endpoint}/unet/config.json": partial},
+ revision=marker_revision,
+ )
+ current = {
+ path.relative_to(diffusers_dir).as_posix(): path.read_bytes()
+ for path in diffusers_dir.rglob("*")
+ if path.is_file()
+ }
+ prefix = f"{_SDXL_TURBO_URL}/resolve/{SDXL_TURBO_COMMIT}/"
+ served = _RepoFilesAdapter(prefix, current)
+ for name in current:
+ mm2_session.mount(prefix + name, served)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ restored_installer.wait_for_job(restored_job, timeout=10)
+
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ assert restored_job._source_revision == SDXL_TURBO_COMMIT
+ requested = {request.url.removeprefix(prefix) for request in served.requests}
+ assert {"vae/config.json", "unet/config.json"} <= requested
+ assert [request.url for request in served.requests if "Range" in request.headers] == []
+ assert restored_job.config_out is not None
+ installed = mm2_app_config.models_path / restored_job.config_out.path
+ installed_files = [path for path in installed.rglob("*") if path.is_file()]
+ assert installed / "vae" / "config.json" in installed_files
+ for path in installed_files:
+ assert path.read_bytes() == (diffusers_dir / path.relative_to(installed)).read_bytes(), path
+ finally:
+ restored_installer.stop()
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_restore_keeps_the_partial_download_of_a_source_without_revisions(
+ mm2_installer: ModelInstallService, mm2_app_config: InvokeAIAppConfig, mm2_download_queue, mm2_session
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}legacy-url-{uuid.uuid4().hex}"
+ dest = tmpdir / "model.safetensors"
+ tmpdir.mkdir()
+ dest.with_name("model.safetensors.downloading").write_bytes(b"partial")
+ url = "https://example.com/model.safetensors"
+ _write_legacy_marker(mm2_installer, tmpdir, URLModelSource(url=Url(url)), InstallStatus.PAUSED, {url: dest})
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ try:
+ restored_installer._restore_incomplete_installs()
+ [restored_job] = restored_installer.list_jobs()
+ assert restored_job.paused
+ assert restored_job._resume_metadata is not None and url in restored_job._resume_metadata
+ assert dest.with_name("model.safetensors.downloading").read_bytes() == b"partial"
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+_TI_REPO = "https://huggingface.co/InvokeAI-test/textual_inversion_tests"
+_TI_FILE = "learned_embeds-steps-1000.safetensors"
+_TI_COMMIT = TEXTUAL_INVERSION_TESTS_COMMIT
+
+
+class _HFFileAdapter(BaseAdapter):
+ """One Hugging Face file URL. A HEAD gets `head_status` and, like the hub, the commit the URL's revision names in
+ `X-Repo-Commit`; a GET is answered by `get`, or with the whole file."""
+
+ def __init__(
+ self,
+ data: bytes,
+ commit: str | None = None,
+ head_status: int = 200,
+ get: BaseAdapter | None = None,
+ head_headers: dict[str, str] | None = None,
+ ) -> None:
+ """`head_headers` can carry a `Location`, with a 3xx `head_status`, to redirect the HEAD."""
+ super().__init__()
+ self._data = data
+ self._commit = commit
+ self._head_status = head_status
+ self._get = get
+ self._head_headers = head_headers or {}
+ self.requests: list = []
+
+ @property
+ def heads(self) -> list:
+ return [r for r in self.requests if r.method == "HEAD"]
+
+ @property
+ def gets(self) -> list:
+ return [r for r in self.requests if r.method == "GET"]
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ if request.method == "HEAD":
+ headers = {**({"X-Repo-Commit": self._commit} if self._commit else {}), **self._head_headers}
+ return TestAdapter(b"", status=self._head_status, headers=headers).send(request, **kwargs)
+ if self._get is not None:
+ return self._get.send(request, **kwargs)
+ return TestAdapter(self._data, headers={"Content-Length": len(self._data)}).send(request, **kwargs)
+
+ def close(self) -> None:
+ pass
+
+
+def _ti_url(revision: str, repo: str = _TI_REPO) -> str:
+ return f"{repo}/resolve/{revision}/{_TI_FILE}"
+
+
+def _pause_single_file_hf_install(
+ installer: ModelInstallService, session, data: bytes, cut: int, revision: str = "main"
+) -> tuple[ModelInstallJob, _DropThenResumeAdapter, _HFFileAdapter]:
+ """Install a Hugging Face file by a branch or tag URL and drop its download after `cut` bytes, pausing it."""
+ flaky = _DropThenResumeAdapter(data, cut)
+ pinned = _HFFileAdapter(data, _TI_COMMIT, get=flaky)
+ session.mount(_ti_url(revision), _HFFileAdapter(data, _TI_COMMIT))
+ session.mount(_ti_url(_TI_COMMIT), pinned)
+ job = installer.import_model(URLModelSource(url=Url(_ti_url(revision))))
+ installer.wait_for_job(job, timeout=10)
+ installer._download_queue.join()
+ assert job.status == InstallStatus.PAUSED, job.error
+ return job, flaky, pinned
+
+
+def _move_textual_inversion_branch(session, data: bytes, revision: str = "main") -> list[_HFFileAdapter]:
+ """Point the branch at a newer commit whose file has the same size but other contents."""
+ newer = bytes(b ^ 0x20 for b in data)
+ adapters = [_HFFileAdapter(newer, _NEWER_COMMIT), _HFFileAdapter(newer, _NEWER_COMMIT)]
+ session.mount(_ti_url(revision), adapters[0])
+ session.mount(_ti_url(_NEWER_COMMIT), adapters[1])
+ return adapters
+
+
[email protected]("revision", ["main", "v1+fix", "refs/pr/1"], ids=["branch", "tag-with-plus", "pull-request"])
[email protected]("operation", ["resume", "restart_failed", "restart_file"])
+def test_single_file_hugging_face_install_keeps_the_commit_it_started_from(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ embedding_file: Path,
+ operation: str,
+ revision: str,
+) -> None:
+ """A file URL naming a branch or tag is downloaded from the commit it named at install start, however it moves."""
+ data = embedding_file.read_bytes()
+ job, flaky, pinned = _pause_single_file_hf_install(mm2_installer, mm2_session, data, cut=1000, revision=revision)
+ assert job._staging.tmpdir is not None
+ marker = _read_marker(job._staging.tmpdir)
+ assert marker is not None and marker["revision"] == _TI_COMMIT
+ [part] = job.download_parts
+ assert str(part.source) == _ti_url(_TI_COMMIT)
+ newer = _move_textual_inversion_branch(mm2_session, data, revision)
+
+ if operation == "resume":
+ mm2_installer.resume_job(job)
+ elif operation == "restart_failed":
+ mm2_installer.restart_failed(job)
+ else:
+ mm2_installer.restart_file(job, _ti_url(_TI_COMMIT))
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert str(job.source) == _ti_url(revision)
+ assert len(flaky.requests) == 2
+ if operation == "resume":
+ assert flaky.requests[1].headers["Range"] == "bytes=1000-"
+ assert [adapter.requests for adapter in newer] == [[], []]
+ assert job.config_out is not None
+ assert job.config_out.source == _ti_url(revision)
+ assert (mm2_app_config.models_path / job.config_out.path).read_bytes() == data
+
+
+# What the hub answers a HEAD of a file at a commit: a vanished commit is a 404 with EntryNotFound (RevisionNotFound
+# from the API). Anything else is left to the download: a repo the token cannot see, a gated repo, or a bare 404
+# from a mirror or proxy that says nothing about the commit.
+_PINNED_HEAD_ANSWERS = pytest.mark.parametrize(
+ ("head_status", "error_code", "vanished"),
+ [
+ (404, "EntryNotFound", True),
+ (404, "RevisionNotFound", True),
+ (404, "RepoNotFound", False),
+ (401, "GatedRepo", False),
+ (404, None, False),
+ ],
+ ids=["entry-not-found", "revision-not-found", "repo-not-found", "gated", "bare-404"],
+)
+
+
+@_PINNED_HEAD_ANSWERS
+def test_single_file_hugging_face_resume_errors_only_when_the_hub_reports_its_commit_gone(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ head_status: int,
+ error_code: str | None,
+ vanished: bool,
+) -> None:
+ data = embedding_file.read_bytes()
+ job, flaky, _ = _pause_single_file_hf_install(mm2_installer, mm2_session, data, cut=1000)
+ tmpdir = job._staging.tmpdir
+ assert tmpdir is not None
+ _move_textual_inversion_branch(mm2_session, data)
+ headers = {"X-Error-Code": error_code} if error_code else {}
+ mm2_session.mount(
+ _ti_url(_TI_COMMIT), _HFFileAdapter(data, head_status=head_status, head_headers=headers, get=flaky)
+ )
+
+ if vanished:
+ with pytest.raises(ModelRevisionUnavailableError, match=_VANISHED_REVISION_ERROR):
+ mm2_installer.resume_job(job)
+ assert job.status == InstallStatus.ERROR
+ assert job.download_parts == set()
+ assert not tmpdir.exists()
+ assert len(flaky.requests) == 1
+ else:
+ mm2_installer.resume_job(job)
+ mm2_installer.wait_for_job(job, timeout=10)
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert flaky.requests[1].headers["Range"] == "bytes=1000-"
+
+
+ ("head_status", "head_headers"),
+ [(200, {}), (401, {}), (404, {"X-Error-Code": "EntryNotFound"})],
+ ids=["no-commit-header", "refused", "not-found"],
+)
+def test_single_file_hugging_face_install_the_host_cannot_pin_downloads_the_url_as_given(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ embedding_file: Path,
+ head_status: int,
+ head_headers: dict[str, str],
+) -> None:
+ data = embedding_file.read_bytes()
+ branch = _HFFileAdapter(data, head_status=head_status, head_headers=head_headers)
+ mm2_session.mount(_ti_url("main"), branch)
+
+ job = mm2_installer.import_model(URLModelSource(url=Url(_ti_url("main"))))
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job._source_revision is None
+ assert [str(part.source) for part in job.download_parts] == [_ti_url("main")]
+ assert len(branch.gets) == 1
+ assert job.status == InstallStatus.COMPLETED, job.error
+
+
+def test_single_file_hugging_face_resume_does_not_append_a_moved_unpinned_branch(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ mm2_app_config: InvokeAIAppConfig,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ data = embedding_file.read_bytes()
+ moved_data = bytes(b ^ 0x20 for b in data)
+ cut = 1000
+ transfer = _DropThenResumeAdapter(data, cut)
+ branch = _HFFileAdapter(data, get=transfer)
+ mm2_session.mount(_ti_url("main"), branch)
+
+ real_probe = mm2_installer._probe
+ monkeypatch.setattr(mm2_installer, "_probe", lambda _path, config=None: real_probe(embedding_file, config))
+
+ job = mm2_installer.import_model(URLModelSource(url=Url(_ti_url("main"))))
+ mm2_installer.wait_for_job(job, timeout=10)
+ mm2_installer._download_queue.join()
+ assert job.status == InstallStatus.PAUSED
+ assert job._source_revision is None
+ assert len(branch.heads) == 1
+
+ # The same branch now serves another commit, with no validator that could make Range safe.
+ transfer._data = moved_data
+ mm2_installer.resume_job(job)
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert len(transfer.requests) == 2
+ assert "Range" not in transfer.requests[1].headers
+ assert job.config_out is not None
+ installed = mm2_app_config.models_path / job.config_out.path
+ assert installed.read_bytes() == moved_data
+
+
+def test_restore_does_not_reuse_direct_hf_file_staging_from_an_old_endpoint(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ old_endpoint = "https://old-hf-mirror.example"
+ new_endpoint = "https://new-hf-mirror.example"
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ old_endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ url = f"{old_endpoint}/InvokeAI-test/textual_inversion_tests/resolve/main/{_TI_FILE}"
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}old-endpoint-file-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ dest = tmpdir / _TI_FILE
+ data = embedding_file.read_bytes()
+ moved_data = bytes(b ^ 0x20 for b in data)
+ dest.with_name(dest.name + ".downloading").write_bytes(data[:1000])
+ source = URLModelSource(url=Url(url))
+ _write_legacy_marker(mm2_installer, tmpdir, source, InstallStatus.DOWNLOADING, {url: dest}, revision=None)
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ new_endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ served = _RepoFilesAdapter(url, {"": moved_data})
+ mm2_session.mount(url, served)
+
+ real_probe = mm2_installer._probe
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ monkeypatch.setattr(restored_installer, "_probe", lambda _path, config=None: real_probe(embedding_file, config))
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ restored_installer.wait_for_job(restored_job, timeout=10)
+
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ get_requests = [request for request in served.requests if request.method == "GET"]
+ assert len(get_requests) == 1
+ assert "Range" not in get_requests[0].headers
+ assert restored_job.config_out is not None
+ installed = mm2_app_config.models_path / restored_job.config_out.path
+ assert installed.read_bytes() == moved_data
+ finally:
+ restored_installer.stop()
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_restore_direct_hf_file_uses_recorded_old_mirror_endpoint(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ old_endpoint = "https://old-pinned-mirror.example/prefix"
+ new_endpoint = "https://new-pinned-mirror.example"
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ old_endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ branch_url = f"{old_endpoint}/InvokeAI-test/textual_inversion_tests/resolve/main/{_TI_FILE}"
+ commit_url = f"{old_endpoint}/InvokeAI-test/textual_inversion_tests/resolve/{_TI_COMMIT}/{_TI_FILE}"
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}old-pinned-endpoint-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ data = embedding_file.read_bytes()
+ partial = tmpdir / _TI_FILE
+ partial.with_name(partial.name + ".downloading").write_bytes(data[:1000])
+ job = ModelInstallJob(
+ id=98768,
+ source=URLModelSource(url=Url(branch_url)),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.DOWNLOADING,
+ )
+ _stage(job, tmpdir)
+ job._source_revision = _TI_COMMIT
+ # The validator the server sent for the partial, which lets the resume continue it.
+ job.download_parts = {DownloadJob(source=Url(commit_url), dest=partial, etag=_FILE_ETAG)}
+ mm2_installer._write_install_marker(job, status=InstallStatus.DOWNLOADING)
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ new_endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ pinned = _HFFileAdapter(data, _TI_COMMIT, get=_RepoFilesAdapter(commit_url, {"": data}))
+ mm2_session.mount(commit_url, pinned)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ real_probe = restored_installer._probe
+ monkeypatch.setattr(restored_installer, "_probe", lambda _path, config=None: real_probe(embedding_file, config))
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ restored_installer.wait_for_job(restored_job, timeout=10)
+
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ assert restored_job._source_revision == _TI_COMMIT
+ assert [str(part.source) for part in restored_job.download_parts] == [commit_url]
+ assert [request.headers.get("Range") for request in pinned.gets] == ["bytes=1000-"]
+ finally:
+ restored_installer.stop()
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_restore_keeps_partial_for_legacy_ordinary_url_with_hf_shaped_path(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ url = "https://downloads.example/InvokeAI-test/model/resolve/main/weights.safetensors"
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}ordinary-url-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ dest = tmpdir / "weights.safetensors"
+ partial = dest.with_name(dest.name + ".downloading")
+ partial.write_bytes(b"valid ordinary URL partial")
+ _write_legacy_marker(
+ mm2_installer,
+ tmpdir,
+ URLModelSource(url=Url(url)),
+ InstallStatus.DOWNLOADING,
+ {url: dest},
+ revision=None,
+ )
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ try:
+ restored_installer._restore_incomplete_installs()
+ [restored_job] = restored_installer.list_jobs()
+
+ assert restored_job._source_hf_endpoint is None
+ assert restored_job._resume_metadata is not None
+ assert partial.read_bytes() == b"valid ordinary URL partial"
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+ restored_installer.stop()
+
+
+def test_hugging_face_metadata_branch_revision_is_not_a_pinned_download_revision(
+ mm2_installer: ModelInstallService,
+) -> None:
+ metadata = HuggingFaceMetadata(
+ name="model",
+ id="org/model",
+ files=[
+ RemoteModelFile(
+ url=Url("https://huggingface.co/org/model/resolve/main/weights.safetensors"),
+ path=Path("weights.safetensors"),
+ size=10,
+ )
+ ],
+ )
+ assert metadata.revision == "main"
+
+ assert mm2_installer._download_revision(metadata, metadata.files) is None
+
+
+def test_failed_partial_cleanup_does_not_submit_a_restart(
+ mm2_installer: ModelInstallService,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ destination = tmp_path / "model.safetensors"
+ partial = destination.with_name(destination.name + ".downloading")
+ partial.write_bytes(b"stale partial")
+ job = ModelInstallJob(
+ id=98769,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmp_path,
+ status=InstallStatus.ERROR,
+ )
+ _stage(job, tmp_path)
+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=10)
+ submit = MagicMock()
+ monkeypatch.setattr(mm2_installer._download_queue, "submit_multifile_download", submit)
+ original_unlink = Path.unlink
+
+ def _unlink(path: Path, *args: Any, **kwargs: Any) -> None:
+ if path == partial:
+ raise PermissionError("partial file is locked")
+ original_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", _unlink)
+
+ with pytest.raises(InstallDownloadConflictError, match="partial file is locked"):
+ mm2_installer._enqueue_remote_download(
+ job=job,
+ source=source,
+ remote_files=[remote_file],
+ metadata=None,
+ restart_from_zero={str(source.url)},
+ )
+
+ submit.assert_not_called()
+ assert job.status == InstallStatus.ERROR
+ assert partial.read_bytes() == b"stale partial"
+
+
[email protected]("failure", [503, 429, "connection"])
+def test_single_file_hugging_face_install_fails_to_start_while_its_host_is_unavailable(
+ mm2_installer: ModelInstallService, mm2_session, embedding_file: Path, failure: int | str
+) -> None:
+ data = embedding_file.read_bytes()
+ if failure == "connection":
+ adapter: BaseAdapter = _RaisingAdapter(RequestsConnectionError("unreachable"))
+ else:
+ adapter = _HFFileAdapter(data, head_status=int(failure))
+ mm2_session.mount(_ti_url("main"), adapter)
+
+ with pytest.raises(ModelMetadataUnavailableError):
+ mm2_installer.import_model(URLModelSource(url=Url(_ti_url("main"))))
+ assert mm2_installer.get_job_by_source(URLModelSource(url=Url(_ti_url("main")))) == []
+
+
+def test_download_and_cache_model_never_looks_up_a_commit(
+ mm2_installer: ModelInstallService, mm2_session, embedding_file: Path
+) -> None:
+ """Runtime downloads of auxiliary files must not depend on an extra request to the hub."""
+ data = embedding_file.read_bytes()
+ branch = _HFFileAdapter(data, _TI_COMMIT)
+ url = _ti_url("main") + "?download=true"
+ mm2_session.mount(url, branch)
+
+ path = mm2_installer.download_and_cache_model(url)
+
+ assert path.read_bytes() == data
+ assert branch.heads == []
+ assert len(branch.gets) == 1
+
+
+def test_single_file_hugging_face_install_sends_its_configured_token_to_the_pinned_url(
+ mm2_installer: ModelInstallService, mm2_session, embedding_file: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A `remote_api_tokens` entry written for the URL the user gave still authorizes the download of its commit."""
+ data = embedding_file.read_bytes()
+ monkeypatch.setattr(
+ mm2_installer.app_config,
+ "remote_api_tokens",
+ [URLRegexTokenPair(url_regex=r"textual_inversion_tests/resolve/main/", token="configured-token")],
+ )
+ branch = _HFFileAdapter(data, _TI_COMMIT)
+ pinned = _HFFileAdapter(data, _TI_COMMIT)
+ mm2_session.mount(_ti_url("main"), branch)
+ mm2_session.mount(_ti_url(_TI_COMMIT), pinned)
+ # As in production, the installer has no session of its own: the commit lookup goes through the download
+ # queue's session, with its proxy and address policy.
+ monkeypatch.setattr(mm2_installer, "_session", None)
+
+ job = mm2_installer.import_model(URLModelSource(url=Url(_ti_url("main"))))
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert [r.headers.get("Authorization") for r in branch.heads] == ["Bearer configured-token"]
+ assert [r.headers.get("Authorization") for r in pinned.gets] == ["Bearer configured-token"]
+ assert branch.gets == []
+
+
+ ("repo", "endpoint"),
+ [
+ (f"{_MIRROR}/InvokeAI-test/textual_inversion_tests", _MIRROR),
+ ("http://huggingface.co/InvokeAI-test/textual_inversion_tests", None),
+ ],
+ ids=["mirror", "http"],
+)
+def test_single_file_hugging_face_install_is_pinned_on_the_host_it_names(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ repo: str,
+ endpoint: str | None,
+) -> None:
+ """The commit is asked of the URL's own host, and the download of a file page URL uses its download URL."""
+ if endpoint is not None:
+ monkeypatch.setattr(
+ "huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
+ endpoint + "/{repo_id}/resolve/{revision}/{filename}",
+ )
+ data = embedding_file.read_bytes()
+ branch = _HFFileAdapter(data, _TI_COMMIT)
+ pinned = _HFFileAdapter(data, _TI_COMMIT)
+ if repo.startswith("http://"):
+ # The hub answers http with a 301 to https that names no commit.
+ https_url = _ti_url("main", repo.replace("http://", "https://", 1)) + "?download=true"
+ mm2_session.mount(https_url, branch)
+ branch = _HFFileAdapter(data, head_status=301, head_headers={"Location": https_url})
+ mm2_session.mount(_ti_url("main", repo) + "?download=true", branch)
+ mm2_session.mount(_ti_url(_TI_COMMIT, repo) + "?download=true", pinned)
+ source_url = f"{repo}/blob/main/{_TI_FILE}?download=true"
+
+ job = mm2_installer.import_model(URLModelSource(url=Url(source_url)))
+ mm2_installer.wait_for_job(job, timeout=10)
+
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert str(job.source) == source_url
+ assert len(branch.heads) == 1 and branch.gets == []
+ assert len(pinned.gets) == 1
+ assert job._source_revision == _TI_COMMIT
+ assert job._source_hf_endpoint == (endpoint + "/" if endpoint else "http://huggingface.co/")
+
+
+def test_single_file_hugging_face_install_follows_a_renamed_repo_on_its_host_only(
+ mm2_installer: ModelInstallService, mm2_session, embedding_file: Path
+) -> None:
+ """A renamed repo answers a relative redirect, followed for the commit; a redirect to another host is not, so the
+ token stays on the hub."""
+ data = embedding_file.read_bytes()
+ renamed = "https://huggingface.co/InvokeAI-test/renamed"
+ old_branch = _HFFileAdapter(
+ data, head_status=307, head_headers={"Location": f"/InvokeAI-test/renamed/resolve/main/{_TI_FILE}"}
+ )
+ new_branch = _HFFileAdapter(data, _TI_COMMIT)
+ mm2_session.mount(_ti_url("main"), old_branch)
+ mm2_session.mount(_ti_url("main", renamed), new_branch)
+ mm2_session.mount(_ti_url(_TI_COMMIT), _HFFileAdapter(data, _TI_COMMIT))
+ source = URLModelSource(url=Url(_ti_url("main")), access_token="user-token")
+
+ job = mm2_installer.import_model(source)
+ mm2_installer.wait_for_job(job, timeout=10)
+ assert job.status == InstallStatus.COMPLETED, job.error
+ assert job._source_revision == _TI_COMMIT
+ assert [r.headers.get("Authorization") for r in new_branch.heads] == ["Bearer user-token"]
+
+ elsewhere = _HFFileAdapter(data, _TI_COMMIT)
+ mm2_session.mount("https://elsewhere.example/file", elsewhere)
+ mm2_session.mount(
+ _ti_url("v2"),
+ _HFFileAdapter(data, head_status=302, head_headers={"Location": "https://elsewhere.example/file"}),
+ )
+ unpinned = mm2_installer._pin_new_hf_file_download(
+ URLModelSource(url=Url(_ti_url("v2")), access_token="user-token"),
+ [RemoteModelFile(url=Url(_ti_url("v2")), path=Path("."), size=0)],
+ )
+ assert [str(f.url) for f in unpinned] == [_ti_url("v2")]
+ assert elsewhere.requests == []
+
+ downgraded = _HFFileAdapter(data, _TI_COMMIT)
+ mm2_session.mount(_ti_url("v3", "http://huggingface.co/InvokeAI-test/textual_inversion_tests"), downgraded)
+ mm2_session.mount(
+ _ti_url("v3"),
+ _HFFileAdapter(
+ data,
+ head_status=307,
+ head_headers={"Location": _ti_url("v3", "http://huggingface.co/InvokeAI-test/textual_inversion_tests")},
+ ),
+ )
+ unpinned = mm2_installer._pin_new_hf_file_download(
+ URLModelSource(url=Url(_ti_url("v3")), access_token="user-token"),
+ [RemoteModelFile(url=Url(_ti_url("v3")), path=Path("."), size=0)],
+ )
+ assert [str(f.url) for f in unpinned] == [_ti_url("v3")]
+ assert downgraded.requests == [] # the token is never sent over plain http
+
+
+def test_new_install_never_reuses_hugging_face_staging_from_a_branch(
+ mm2_installer: ModelInstallService, mm2_app_config: InvokeAIAppConfig, mm2_session, embedding_file: Path
+) -> None:
+ """When the host names no commit, the install follows the branch; staging from that branch may be older."""
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ mm2_session.mount(_ti_url("main"), _HFFileAdapter(embedding_file.read_bytes()))
+ source = URLModelSource(url=Url(_ti_url("main")))
+ staged = mm2_app_config.models_path / f"{TMPDIR_PREFIX}branch-{uuid.uuid4().hex}"
+ staged.mkdir()
+ _write_legacy_marker(
+ mm2_installer, staged, source, InstallStatus.PAUSED, {_ti_url("main"): staged / _TI_FILE}, revision="main"
+ )
+ try:
+ job = mm2_installer.import_model(source)
+ assert job._source_revision is None
+ assert job._staging.tmpdir != staged
+ mm2_installer.wait_for_job(job, timeout=10)
+ assert job.complete, job.error
+ finally:
+ shutil.rmtree(staged, ignore_errors=True)
+
+
+ ("marker_revision", "kept"),
+ [(_TI_COMMIT, True), (None, False), ("main", False), ("<absent>", False)],
+ ids=["commit", "null-revision", "branch-revision", "pre-pinning-marker"],
+)
+def test_restore_keeps_a_single_file_download_only_when_pinned_to_a_commit(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ embedding_file: Path,
+ marker_revision: str | None,
+ kept: bool,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ data = embedding_file.read_bytes()
+ stale = bytes(b ^ 0x20 for b in data)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}single-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ dest = tmpdir / _TI_FILE
+ staged_url = _ti_url(_TI_COMMIT if kept else "main")
+ # A pinned partial holds the commit's own bytes; an unpinned one an older state of the branch.
+ dest.with_name(_TI_FILE + ".downloading").write_bytes((data if kept else stale)[:1000])
+ source = URLModelSource(url=Url(_ti_url("main")))
+ _write_legacy_marker(
+ mm2_installer, tmpdir, source, InstallStatus.DOWNLOADING, {staged_url: dest}, revision=marker_revision
+ )
+ pinned = _HFFileAdapter(data, _TI_COMMIT, get=_RepoFilesAdapter(_ti_url(_TI_COMMIT), {"": data}))
+ mm2_session.mount(_ti_url("main"), _HFFileAdapter(stale, _TI_COMMIT))
+ mm2_session.mount(_ti_url(_TI_COMMIT), pinned)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ restored_installer.wait_for_job(restored_job, timeout=10)
+
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ assert restored_job._source_revision == _TI_COMMIT
+ assert [r.headers.get("Range") for r in pinned.gets] == (["bytes=1000-"] if kept else [None])
+ assert restored_job.config_out is not None
+ assert (mm2_app_config.models_path / restored_job.config_out.path).read_bytes() == data
+ finally:
+ restored_installer.stop()
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+@_PINNED_HEAD_ANSWERS
+def test_restore_errors_a_single_file_download_only_when_the_hub_reports_its_commit_gone(
+ mm2_installer: ModelInstallService,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+ embedding_file: Path,
+ head_status: int,
+ error_code: str | None,
+ vanished: bool,
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ data = embedding_file.read_bytes()
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}single-vanished-{uuid.uuid4().hex}"
+ tmpdir.mkdir()
+ dest = tmpdir / _TI_FILE
+ dest.with_name(_TI_FILE + ".downloading").write_bytes(data[:1000])
+ source = URLModelSource(url=Url(_ti_url("main")))
+ _write_legacy_marker(
+ mm2_installer, tmpdir, source, InstallStatus.DOWNLOADING, {_ti_url(_TI_COMMIT): dest}, revision=_TI_COMMIT
+ )
+ headers = {"X-Error-Code": error_code} if error_code else {}
+ files = _RepoFilesAdapter(_ti_url(_TI_COMMIT), {"": data})
+ pinned = _HFFileAdapter(data, head_status=head_status, head_headers=headers, get=files)
+ mm2_session.mount(_ti_url(_TI_COMMIT), pinned)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ restored_installer.start()
+ try:
+ assert restored_installer._wait_for_restore_complete(timeout=10)
+ [restored_job] = restored_installer.list_jobs()
+ restored_installer.wait_for_job(restored_job, timeout=10)
+ if vanished:
+ assert restored_job.status == InstallStatus.ERROR
+ assert restored_job.error is not None and _VANISHED_REVISION_ERROR in restored_job.error
+ assert not tmpdir.exists()
+ assert pinned.gets == []
+ else:
+ assert restored_job.status == InstallStatus.COMPLETED, restored_job.error
+ assert [r.headers.get("Range") for r in pinned.gets] == ["bytes=1000-"]
+ finally:
+ restored_installer.stop()
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_restore_errors_an_interrupted_install_pinned_to_a_vanished_commit(
+ mm2_installer: ModelInstallService, mm2_app_config: InvokeAIAppConfig, mm2_download_queue, mm2_session
+) -> None:
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}vanished-{uuid.uuid4().hex}"
+ (tmpdir / "sdxl-turbo").mkdir(parents=True)
+ (tmpdir / "sdxl-turbo" / "model_index.json").write_bytes(b"{}")
+ interrupted_job = ModelInstallJob(
+ id=98769,
+ source=URLModelSource(url=Url(_SDXL_TURBO_URL)),
+ config_in=ModelRecordChanges(),
+ local_path=tmpdir,
+ status=InstallStatus.DOWNLOADING,
+ )
+ _stage(interrupted_job, tmpdir)
+ interrupted_job._source_revision = SDXL_TURBO_COMMIT
+ mm2_installer._write_install_marker(interrupted_job, status=InstallStatus.DOWNLOADING)
+ mm2_session.mount(f"{_SDXL_TURBO_API}/revision/{SDXL_TURBO_COMMIT}", TestAdapter(b"", status=404))
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+ try:
+ restored_installer._restore_incomplete_installs()
+ [restored_job] = restored_installer.list_jobs()
+ assert restored_job.status == InstallStatus.ERROR
+ assert restored_job.error is not None and _VANISHED_REVISION_ERROR in restored_job.error
+ assert not tmpdir.exists()
+ finally:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_auto_install_retries_a_paused_install_and_names_the_model_when_it_fails(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An invocation that auto-installs its encoder resumes the install an earlier run left paused."""
+ good_data = embedding_file.read_bytes()
+ tmpdir: Path | None = None
+ try:
+ job, _, tmpdir = _install_with_failing_part(
+ mm2_installer, mm2_session, monkeypatch, TestAdapter(b"server error", status=503), good_data
+ )
+ assert job.paused
+ pending_callback = job._multifile_job
+ assert pending_callback is not None
+ mm2_installer._download_cache[pending_callback.id] = job
+ retry = _CountingAdapter(TestAdapter(b"server error", status=503))
+ mm2_session.mount(BAD_URL, retry)
+ context = SimpleNamespace(
+ models=SimpleNamespace(search_by_attrs=lambda **_kwargs: []),
+ logger=MagicMock(),
+ _services=SimpleNamespace(model_manager=SimpleNamespace(install=mm2_installer)),
+ )
+
+ # The invocation's resume is refused while the callback is pending; it must wait it out, then resume.
+ callback_wait = _WaitObservingEvent()
+ monkeypatch.setattr(mm2_installer, "_install_completed_event", callback_wait)
+ results: list[object] = []
+
+ def invoke() -> None:
+ try:
+ results.append(IPAdapterInvocation.get_clip_image_encoder(context, BAD_URL, "missing-encoder"))
+ except Exception as error:
+ results.append(error)
+
+ invocation = threading.Thread(target=invoke)
+ invocation.start()
+ blocked_on_callback = callback_wait.waiting.wait(timeout=10)
+ was_waiting = invocation.is_alive()
+ if pending_callback.id in mm2_installer._download_cache:
+ mm2_installer._download_cancelled_callback(pending_callback)
+ invocation.join(timeout=15)
+ mm2_installer._download_queue.join()
+
+ assert blocked_on_callback
+ assert was_waiting
+ assert not invocation.is_alive()
+ assert len(results) == 1
+ assert isinstance(results[0], RuntimeError)
+ assert "missing-encoder" in str(results[0])
+ assert "'paused'" in str(results[0]) and "Model Manager" in str(results[0])
+
+ assert len(retry.requests) == 1
+ assert mm2_installer.list_jobs() == [job]
+ assert (tmpdir / "good_part.safetensors").read_bytes() == good_data
+ finally:
+ if tmpdir is not None:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+class _HeldFirstRequestAdapter(BaseAdapter):
+ """Serves `data`, holding the first request until released so the test can act while it is in flight."""
+
+ def __init__(self, data: bytes) -> None:
+ super().__init__()
+ self._data = data
+ self.entered = threading.Event()
+ self.release = threading.Event()
+ self.requests: list = []
+
+ def send(self, request, **kwargs):
+ self.requests.append(request)
+ if len(self.requests) == 1:
+ self.entered.set()
+ assert self.release.wait(timeout=10)
+ return TestAdapter(self._data, headers={"Content-Length": len(self._data)}).send(request, **kwargs)
+
+ def close(self) -> None:
+ pass
+
+
+def test_auto_install_resumes_a_user_pause_once_its_download_callback_settles(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ data = embedding_file.read_bytes()
+ held = _HeldFirstRequestAdapter(data)
+ mm2_session.mount(BAD_URL, held)
+ files = [RemoteModelFile(url=Url(BAD_URL), path=Path("encoder.safetensors"), size=len(data))]
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", lambda _source, revision=None: (files, None))
+ monkeypatch.setattr("invokeai.app.services.model_install.model_install_default._JOB_WAIT_POLL_SECONDS", 30.0)
+
+ job = mm2_installer.import_model(URLModelSource(url=Url(BAD_URL)))
+ assert held.entered.wait(timeout=10)
+ # The download worker still owns the job, so its callback has not run when the pause lands.
+ mm2_installer.pause_job(job)
+ assert job.paused
+ with pytest.raises(InstallDownloadConflictError):
+ mm2_installer.resume_job(job)
+
+ callback_wait = _WaitObservingEvent()
+ monkeypatch.setattr(mm2_installer, "_install_completed_event", callback_wait)
+ context = SimpleNamespace(
+ models=SimpleNamespace(search_by_attrs=lambda **_kwargs: [job.config_out] if job.complete else []),
+ logger=MagicMock(),
+ _services=SimpleNamespace(model_manager=SimpleNamespace(install=mm2_installer)),
+ )
+ results: list[object] = []
+
+ def invoke() -> None:
+ try:
+ results.append(IPAdapterInvocation.get_clip_image_encoder(context, BAD_URL, "paused-encoder"))
+ except Exception as error:
+ results.append(error)
+
+ invocation = threading.Thread(target=invoke)
+ invocation.start()
+ assert callback_wait.waiting.wait(timeout=10)
+ assert invocation.is_alive()
+ held.release.set()
+ invocation.join(timeout=15)
+
+ assert not invocation.is_alive()
+ assert job.complete
+ assert results == [job.config_out]
+ assert len(held.requests) == 2
+
+
[email protected]("caller", ["ip_adapter", "flux_redux"])
+def test_auto_install_timeout_uses_model_specific_error(
+ caller: str, mm2_installer: ModelInstallService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ source = URLModelSource(url=Url(BAD_URL))
+ job = ModelInstallJob(
+ id=6103,
+ source=source,
+ config_in=ModelRecordChanges(),
+ local_path=tmp_path,
+ status=InstallStatus.PAUSED,
+ )
+ _stage(job, tmp_path)
+ monkeypatch.setattr(mm2_installer, "heuristic_import", lambda *_args, **_kwargs: job)
+ monkeypatch.setattr(
+ mm2_installer, "resume_and_wait_for_job", MagicMock(side_effect=TimeoutError("Timeout exceeded"))
+ )
+ context = SimpleNamespace(
+ models=SimpleNamespace(search_by_attrs=lambda **_kwargs: []),
+ logger=MagicMock(),
+ _services=SimpleNamespace(model_manager=SimpleNamespace(install=mm2_installer)),
+ )
+
+ with pytest.raises(RuntimeError) as exc_info:
+ if caller == "ip_adapter":
+ IPAdapterInvocation.get_clip_image_encoder(context, BAD_URL, "missing-encoder")
+ else:
+ FluxReduxInvocation.model_construct()._get_siglip_model(context)
+
+ assert "status is 'paused'" in str(exc_info.value)
+ assert "Timeout exceeded" not in str(exc_info.value)
+
+
[email protected]("resume_succeeds", [True, False], ids=["resume-completes", "resume-fails"])
+def test_concurrent_auto_installs_share_one_resume_of_a_paused_install(
+ mm2_installer: ModelInstallService,
+ mm2_session,
+ embedding_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ resume_succeeds: bool,
+) -> None:
+ """A second invocation that loses the race to resume the install waits for that resume's outcome."""
+ flaky = _DropThenResumeAdapter(embedding_file.read_bytes(), cut=100)
+ tmpdir: Path | None = None
+ try:
+ job, _, tmpdir = _install_with_failing_part(mm2_installer, mm2_session, monkeypatch, flaky, None)
+ assert job.paused
+
+ # Hold the first resumer inside its metadata fetch, when it owns the resume but the job is still PAUSED.
+ files = mm2_installer._remote_files_from_source(job.source)
+ fetching, release = threading.Event(), threading.Event()
+
+ def blocking_remote_files(_source, revision=None):
+ fetching.set()
+ assert release.wait(timeout=10)
+ if not resume_succeeds:
+ raise RuntimeError("metadata service unavailable")
+ return files
+
+ monkeypatch.setattr(mm2_installer, "_remote_files_from_source", blocking_remote_files)
+ context = SimpleNamespace(
+ models=SimpleNamespace(search_by_attrs=lambda **_kwargs: [job.config_out] if job.complete else []),
+ logger=MagicMock(),
+ _services=SimpleNamespace(model_manager=SimpleNamespace(install=mm2_installer)),
+ )
+ results: dict[str, object] = {}
+
+ def invoke(name: str) -> None:
+ try:
+ results[name] = IPAdapterInvocation.get_clip_image_encoder(context, BAD_URL, "shared-encoder")
+ except Exception as e:
+ results[name] = e
+
+ first = threading.Thread(target=invoke, args=("first",))
+ first.start()
+ assert fetching.wait(timeout=10)
+ # Only the second invocation can block on this fresh event while the first is held in the fetch.
+ second_waiting = _WaitObservingEvent()
+ monkeypatch.setattr(mm2_installer, "_install_completed_event", second_waiting)
+ second = threading.Thread(target=invoke, args=("second",))
+ second.start()
+ assert second_waiting.waiting.wait(timeout=10)
+ release.set()
+ first.join(timeout=15)
+ second.join(timeout=15)
+
+ assert not first.is_alive() and not second.is_alive()
+ if resume_succeeds:
+ assert job.complete
+ assert results == {"first": job.config_out, "second": job.config_out}
+ assert len(flaky.requests) == 2
+ else:
+ # The failed resume leaves the job paused with nothing else to signal; the second caller must not sleep
+ # through a whole poll before reporting it.
+ assert job.paused
+ assert str(results["first"]) == "metadata service unavailable"
+ assert isinstance(results["second"], RuntimeError)
+ assert "shared-encoder" in str(results["second"]) and "'paused'" in str(results["second"])
+ assert len(flaky.requests) == 1
+ finally:
+ if tmpdir is not None:
+ _claim_path(tmpdir).unlink(missing_ok=True)
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def _http_error(status: int) -> HTTPError:
+ response = Response()
+ response.status_code = status
+ return HTTPError(f"HTTP {status}", response=response)
+
+
+def _tls_error_from_connect(cause: Exception) -> SSLError:
+ """The shape requests raises when the TLS handshake fails: urllib3's SSLError as a MaxRetryError's reason."""
+ return SSLError(MaxRetryError(None, "https://example.com/model.safetensors", reason=Urllib3SSLError(cause)))
+
+
+def _tls_error_from_stream() -> SSLError:
+ """The shape requests raises when TLS drops while the body streams, with the ssl error as cause and context."""
+ try:
+ try:
+ raise ssl.SSLEOFError(8, "EOF occurred in violation of protocol")
+ except ssl.SSLEOFError as eof:
+ raise Urllib3SSLError(eof) from eof
+ except Urllib3SSLError as wrapped:
+ try:
+ raise SSLError(wrapped)
+ except SSLError as raised:
+ return raised
+
+
+ ("excp", "expected_status"),
+ [
+ (_http_error(408), InstallStatus.PAUSED),
+ (_http_error(429), InstallStatus.PAUSED),
+ (_http_error(500), InstallStatus.PAUSED),
+ (Timeout("read timed out"), InstallStatus.PAUSED),
+ (_tls_error_from_stream(), InstallStatus.PAUSED),
+ # The download queue's rename of a vanished `.downloading` sidecar.
+ (
+ FileNotFoundError(errno.ENOENT, "No such file", "/x/model.downloading", None, "/x/model"),
+ InstallStatus.PAUSED,
+ ),
+ (_http_error(401), InstallStatus.ERROR),
+ (_http_error(416), InstallStatus.ERROR),
+ (HTTPError("no response attached"), InstallStatus.ERROR),
+ (
+ _tls_error_from_connect(ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED]")),
+ InstallStatus.ERROR,
+ ),
+ (_tls_error_from_connect(CertificateError("hostname 'a' doesn't match 'b'")), InstallStatus.ERROR),
+ (FileNotFoundError(errno.ENOENT, "No such file", "/x/model.downloading"), InstallStatus.ERROR),
+ (FileNotFoundError(errno.ENOENT, "No such file", "/x/model", None, "/y/model"), InstallStatus.ERROR),
+ (OSError("[Errno 17] File /x/model exists"), InstallStatus.ERROR),
+ (ValueError("Cannot derive a safe filename"), InstallStatus.ERROR),
+ ],
+ ids=[
+ "http-408",
+ "http-429",
+ "http-500",
+ "timeout",
+ "tls-dropped-mid-stream",
+ "sidecar-rename-race",
+ "http-401",
+ "http-416",
+ "http-error-without-response",
+ "tls-certificate-verification",
+ "tls-hostname-mismatch",
+ "missing-sidecar-without-rename",
+ "rename-of-non-sidecar",
+ "file-exists",
+ "unsafe-filename",
+ ],
+)
+def test_download_error_pauses_only_transient_failures(
+ mm2_installer: ModelInstallService,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ excp: Exception,
+ expected_status: InstallStatus,
+) -> None:
+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}classify"
+ tmpdir.mkdir()
+ completed = tmpdir / "config.json"
+ completed.write_text("{}")
+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))
+ done_part = DownloadJob(source=Url("https://example.com/config.json"), dest=completed)
+ done_part.status = DownloadJobStatus.COMPLETED
+ failed_part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")
+ failed_part.status = DownloadJobStatus.ERROR
+ download_job = MultiFileDownloadJob(id=4600, dest=tmpdir, download_parts={done_part, failed_part})
+ install_job = ModelInstallJob(
+ id=4600, source=source, config_in=ModelRecordChanges(), local_path=tmpdir, status=InstallStatus.DOWNLOADING
+ )
+ _stage(install_job, tmpdir)
+ install_job._multifile_job = download_job
+ install_job.download_parts = download_job.download_parts
+ mm2_installer._download_cache[download_job.id] = install_job
+ monkeypatch.setattr(mm2_installer._download_queue, "cancel_job", MagicMock())
+
+ mm2_installer._download_error_callback(download_job, excp)
+
+ assert install_job.status == expected_status
+ assert tmpdir.exists() is (expected_status == InstallStatus.PAUSED)
+ assert mm2_installer.wait_for_job(install_job, timeout=1) is install_job
+
+
@pytest.mark.parametrize(
"model_params",
[
diff --git a/tests/app/test_invocation_event_socketio.py b/tests/app/test_invocation_event_socketio.py
index e6d4919d5e..f6af11de5a 100644
--- a/tests/app/test_invocation_event_socketio.py
+++ b/tests/app/test_invocation_event_socketio.py
@@ -22,6 +22,7 @@ from invokeai.app.services.events.events_common import (
InvocationErrorEvent,
InvocationProgressEvent,
InvocationStartedEvent,
+ ModelInstallPausedEvent,
ModelInstallStartedEvent,
)
from invokeai.app.services.model_install.model_install_common import URLModelSource
@@ -192,19 +193,22 @@ async def test_model_load_events_are_emitted_only_to_triggering_user() -> None:
@pytest.mark.anyio
-async def test_model_install_events_are_emitted_only_to_admins() -> None:
- from invokeai.app.services.events.events_common import ModelInstallStartedEvent
-
+ ("event_class", "event_name"),
+ [
+ (ModelInstallStartedEvent, "model_install_started"),
+ (ModelInstallPausedEvent, "model_install_paused"),
+ ],
+)
+async def test_model_install_events_are_emitted_only_to_admins(event_class: type, event_name: str) -> None:
socketio = SocketIO(FastAPI())
socketio._sio.emit = AsyncMock()
- event = ModelInstallStartedEvent(id=1, source={"type": "url", "url": "https://example.com/model.safetensors"})
+ event = event_class(id=1, source={"type": "url", "url": "https://example.com/model.safetensors"})
- await socketio._handle_model_event(("model_install_started", event))
+ await socketio._handle_model_event((event_name, event))
- socketio._sio.emit.assert_awaited_once_with(
- event="model_install_started", data=event.model_dump(mode="json"), room="admin"
- )
+ socketio._sio.emit.assert_awaited_once_with(event=event_name, data=event.model_dump(mode="json"), room="admin")
@pytest.mark.anyio
diff --git a/tests/backend/model_manager/model_manager_fixtures.py b/tests/backend/model_manager/model_manager_fixtures.py
index 4f8da686d0..00a748d172 100644
--- a/tests/backend/model_manager/model_manager_fixtures.py
+++ b/tests/backend/model_manager/model_manager_fixtures.py
@@ -40,6 +40,10 @@ from tests.backend.model_manager.model_metadata.metadata_examples import (
from tests.fixtures.sqlite_database import create_mock_sqlite_database
from tests.test_nodes import TestEventService
+# The commits the mocked Hugging Face metadata reports as each repo's "sha".
+SDXL_TURBO_COMMIT = "f4b0486b498f84668e828044de1d0c8ba486e05b"
+TEXTUAL_INVERSION_TESTS_COMMIT = "b4221947b01eb61658972c43e33250820d8e3411"
+
# Create a temporary directory using the contents of `./data/invokeai_root` as the template
@pytest.fixture
@@ -262,15 +266,17 @@ def mm2_session(embedding_file: Path, diffusers_dir: Path) -> Session:
},
),
)
- sess.mount(
- "https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/model_index.json",
- TestAdapter(
- RepoHFModelJson1,
- headers={
- "Content-Length": len(RepoHFModelJson1),
- },
- ),
- )
+ # Installs name the commit the metadata reports (its "sha"); tests that build their own metadata use main.
+ for revision in ("main", SDXL_TURBO_COMMIT):
+ sess.mount(
+ f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/{revision}/model_index.json",
+ TestAdapter(
+ RepoHFModelJson1,
+ headers={
+ "Content-Length": len(RepoHFModelJson1),
+ },
+ ),
+ )
with open(embedding_file, "rb") as f:
data = f.read() # file is small - just 15K
sess.mount(
@@ -284,37 +290,42 @@ def mm2_session(embedding_file: Path, diffusers_dir: Path) -> Session:
headers={"Content-Type": "application/json; charset=utf-8", "Content-Length": len(RepoHFMetadata1)},
),
)
- sess.mount(
+ for api_url in (
"https://huggingface.co/api/models/InvokeAI-test/textual_inversion_tests?blobs=True",
- TestAdapter(
- HFTestLoraMetadata,
- headers={"Content-Type": "application/json; charset=utf-8", "Content-Length": len(HFTestLoraMetadata)},
- ),
- )
- sess.mount(
- "https://huggingface.co/InvokeAI-test/textual_inversion_tests/resolve/main/learned_embeds-steps-1000.safetensors",
- TestAdapter(
- data,
- headers={"Content-Type": "application/json; charset=utf-8", "Content-Length": len(data)},
- ),
- )
+ f"https://huggingface.co/api/models/InvokeAI-test/textual_inversion_tests/revision/{TEXTUAL_INVERSION_TESTS_COMMIT}",
+ ):
+ sess.mount(
+ api_url,
+ TestAdapter(
+ HFTestLoraMetadata,
+ headers={"Content-Type": "application/json; charset=utf-8", "Content-Length": len(HFTestLoraMetadata)},
+ ),
+ )
+ for revision in ("main", TEXTUAL_INVERSION_TESTS_COMMIT):
+ sess.mount(
+ f"https://huggingface.co/InvokeAI-test/textual_inversion_tests/resolve/{revision}/learned_embeds-steps-1000.safetensors",
+ TestAdapter(
+ data,
+ headers={"Content-Type": "application/json; charset=utf-8", "Content-Length": len(data)},
+ ),
+ )
for root, _, files in os.walk(diffusers_dir):
for name in files:
path = Path(root, name)
url_base = path.relative_to(diffusers_dir).as_posix()
- url = f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/{url_base}"
with open(path, "rb") as f:
data = f.read()
- sess.mount(
- url,
- TestAdapter(
- data,
- headers={
- "Content-Type": "application/json; charset=utf-8",
- "Content-Length": len(data),
- },
- ),
- )
+ for revision in ("main", SDXL_TURBO_COMMIT):
+ sess.mount(
+ f"https://huggingface.co/stabilityai/sdxl-turbo/resolve/{revision}/{url_base}",
+ TestAdapter(
+ data,
+ headers={
+ "Content-Type": "application/json; charset=utf-8",
+ "Content-Length": len(data),
+ },
+ ),
+ )
for i in ["12345", "9999", "54321"]:
content = (
diff --git a/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py
index b400a34182..ecf87a2ab8 100644
--- a/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py
+++ b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py
@@ -4,7 +4,7 @@ from unittest.mock import Mock
import httpx
import pytest
-from huggingface_hub.errors import HfHubHTTPError
+from huggingface_hub.errors import HfHubHTTPError, OfflineModeIsEnabled, RevisionNotFoundError
from requests import HTTPError, Request, Response, Timeout
from invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetch
@@ -12,6 +12,7 @@ from invokeai.backend.model_manager.metadata.metadata_base import (
HF_METADATA_REQUEST_TIMEOUT_SECONDS,
HuggingFaceMetadata,
ModelMetadataUnavailableError,
+ ModelRevisionUnavailableError,
RemoteModelFile,
UnknownMetadataException,
)
@@ -97,6 +98,16 @@ def test_model_info_transport_errors_are_retryable_metadata_failures(
fetcher.from_id("org/repo")
+def test_offline_mode_is_an_unavailable_metadata_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ """With HF_HUB_OFFLINE=1 the hub client refuses every request; that must read as metadata being unavailable."""
+ api = Mock()
+ api.model_info.side_effect = OfflineModeIsEnabled("offline")
+ monkeypatch.setattr("invokeai.backend.model_manager.metadata.fetch.huggingface.HfApi", lambda: api)
+
+ with pytest.raises(ModelMetadataUnavailableError):
+ HuggingFaceMetadataFetch().from_id("org/repo")
+
+
@pytest.mark.parametrize("status_code", [429, 500, 503])
def test_hf_hub_http_errors_are_retryable_metadata_failures(monkeypatch: pytest.MonkeyPatch, status_code: int) -> None:
request = httpx.Request("GET", "https://huggingface.co/api/models/org/repo")
@@ -226,3 +237,129 @@ def test_variant_fallback_gives_each_model_info_request_its_timeout() -> None:
HF_METADATA_REQUEST_TIMEOUT_SECONDS,
HF_METADATA_REQUEST_TIMEOUT_SECONDS,
]
+
+
+def _hf_api_returning(monkeypatch: pytest.MonkeyPatch, **model_info_kwargs) -> Mock:
+ api = Mock()
+ api.model_info.return_value = SimpleNamespace(
+ id="org/repo", siblings=[SimpleNamespace(rfilename="model.safetensors", size=4, lfs=None)], **model_info_kwargs
+ )
+ monkeypatch.setattr("invokeai.backend.model_manager.metadata.fetch.huggingface.HfApi", lambda: api)
+ return api
+
+
+ ("variant", "branch"), [(None, "main"), (ModelRepoVariant.FP16, "fp16")], ids=["default-branch", "variant-branch"]
+)
+def test_lookup_urls_name_the_branch_users_install_from(
+ monkeypatch: pytest.MonkeyPatch, variant: ModelRepoVariant | None, branch: str
+) -> None:
+ """URLs a lookup returns become install sources and model records, which must keep naming the branch."""
+ api = _hf_api_returning(monkeypatch, sha="abc123")
+
+ metadata = HuggingFaceMetadataFetch().from_id("org/repo", variant)
+
+ assert api.model_info.call_args.kwargs["revision"] == variant
+ assert isinstance(metadata, HuggingFaceMetadata)
+ expected = [f"https://huggingface.co/org/repo/resolve/{branch}/model.safetensors"]
+ assert [str(f.url) for f in metadata.files] == expected
+ assert [str(url) for url in metadata.ckpt_urls or []] == expected
+
+
+def test_pinned_to_commit_lookup_names_the_current_commit_in_file_urls(monkeypatch: pytest.MonkeyPatch) -> None:
+ api = _hf_api_returning(monkeypatch, sha="abc123")
+
+ metadata = HuggingFaceMetadataFetch().from_id("org/repo", pin_to_commit=True)
+
+ assert api.model_info.call_args.kwargs["revision"] is None
+ assert isinstance(metadata, HuggingFaceMetadata)
+ assert metadata.revision == "abc123"
+ assert [str(f.url) for f in metadata.files] == ["https://huggingface.co/org/repo/resolve/abc123/model.safetensors"]
+
+
+def test_pinned_lookup_reads_and_names_that_revision(monkeypatch: pytest.MonkeyPatch) -> None:
+ api = _hf_api_returning(monkeypatch, sha="abc123")
+
+ metadata = HuggingFaceMetadataFetch().from_id("org/repo", ModelRepoVariant.FP16, revision="abc123")
+
+ assert api.model_info.call_args.kwargs["revision"] == "abc123"
+ assert isinstance(metadata, HuggingFaceMetadata)
+ assert [str(f.url) for f in metadata.files] == ["https://huggingface.co/org/repo/resolve/abc123/model.safetensors"]
+
+
+def test_pinned_lookup_of_a_vanished_revision_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
+ api = _hf_api_returning(monkeypatch)
+ response = httpx.Response(404, request=httpx.Request("GET", "https://huggingface.co/api/models/org/repo"))
+ api.model_info.side_effect = RevisionNotFoundError("Revision not found", response=response)
+
+ with pytest.raises(ModelRevisionUnavailableError, match="abc123"):
+ HuggingFaceMetadataFetch().from_id("org/repo", revision="abc123")
+
+ assert api.model_info.call_count == 1
+
+
+def test_custom_session_looks_up_slash_revision_as_one_path_segment() -> None:
+ revision = "refs/pr/1"
+ expected_url = "https://huggingface.co/api/models/org/repo/revision/refs%2Fpr%2F1"
+ session = Mock()
+ response = _requests_response(200, b'{"id":"org/repo","siblings":[]}')
+
+ def respond_to_encoded_revision(url: str, **_kwargs):
+ if url == expected_url:
+ return response
+ return _requests_response(404, headers={"X-Error-Code": "RevisionNotFound"})
+
+ session.get.side_effect = respond_to_encoded_revision
+
+ metadata = HuggingFaceMetadataFetch(session).from_id("org/repo", revision=revision)
+
+ assert metadata.revision == revision
+ assert session.get.call_args.args[0] == expected_url
+
+
+def test_model_index_is_read_from_the_metadata_revision() -> 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/abc123/model_index.json", path=Path("model_index.json")
+ ),
+ ],
+ )
+ metadata._revision = "abc123"
+
+ metadata.download_urls(session=session)
+
+ assert session.get.call_args.args[0] == "https://huggingface.co/org/repo/resolve/abc123/model_index.json"
+
+
+ "url_repo",
+ ["org/repo", "ORG/Repo", "org/old-name"],
+ ids=["same-id", "id-in-another-case", "renamed-repo"],
+)
+def test_metadata_read_back_from_json_reads_the_model_index_of_its_pinned_commit(url_repo: str) -> None:
+ """Install jobs persist their metadata as JSON; the pinned commit must survive it, or model_index.json would be
+ read from the default branch while every file comes from the commit. File URLs name the repo as it was asked
+ for, which can differ from the id the hub reports."""
+ commit = "a" * 40
+ pinned = HuggingFaceMetadata(
+ id="org/repo",
+ name="repo",
+ files=[
+ RemoteModelFile(url=f"https://huggingface.co/{url_repo}/resolve/{commit}/{path}", path=Path(path))
+ for path in ("model_index.json", "unet/config.json")
+ ],
+ )
+ pinned._revision = commit
+ session = Mock()
+ session.get.return_value.json.return_value = {"unet": []}
+
+ HuggingFaceMetadataFetch.from_json(pinned.model_dump_json()).download_urls(session=session)
+
+ assert session.get.call_args.args[0] == f"https://huggingface.co/org/repo/resolve/{commit}/model_index.json"