Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model-manager): harden install lifecycle retries
JPPhoto58781401cefc
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex f224fab44c..fab6f1f4fc 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -572,6 +572,8 @@ The difference between `register_path()` and `install_path()` is that the formerWhen an install transfer cannot be rolled back without risking data loss, the installer raises a recovery-required error and retains both transfer roots for manual recovery. Sibling sentinels keep recovery roots across restart, including when JSON marker writes fail, and prevent cancellation, restart, or orphan cleanup from deleting them. Successfully registering a manually recovered root removes its sentinel. Ordinary markerless staging directories and terminal-state staging directories may be cleaned up at startup. Conversion writes its intermediate model under `models/.convert_tmp`, which the orphan scan skips while the conversion is active. If installation needs recovery, the conversion endpoint reports and retains that source directory; successful conversions and ordinary failures remove their scratch directory.+Remote staging directories are claimed before downloads begin, and startup cleanup skips directories with a live claim. User-paused downloads keep their claim so orphan cleanup cannot expose or delete resumable staging; shutdown releases the claim only after the download queue has quiesced, preserving completed downloads for restart. Local sources under the managed models directory and orphan deletion also take an exclusive active claim, so probing or transfer cannot race with cleanup; startup removes claims from processes that have exited. Install jobs can be cancelled before file transfer starts. Once files are being moved, cancellation returns a conflict so the transfer can finish or preserve its recovery data. During shutdown, the installer waits for its worker to finish before cleaning queued jobs.+#### installer.unregister(key)This will remove the model config record for the model at key, and is equivalent to `installer.record_store.del_model(key)`diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 210e359e3f..3f4ca35843 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -29,7 +29,12 @@ from invokeai.app.services.model_images.model_images_common import (ModelImageFileDeleteException,ModelImageFileNotFoundException,)-from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError, ModelInstallJob+from invokeai.app.services.model_install.model_install_common import (+ InstallCancellationConflictError,+ InstallDownloadConflictError,+ InstallRecoveryRequiredError,+ ModelInstallJob,+)from invokeai.app.services.model_records import (InvalidModelException,ModelRecordChanges,@@ -704,7 +709,7 @@ _MODEL_METADATA_FIELDS: tuple[str, ...] = (def _model_load_fingerprint(config: AnyModelConfig) -> dict[str, Any]:- """Return persisted config values that can change the loaded model instance."""+ """Return record values whose change can make a cached model instance stale."""if model_dump := getattr(config, "model_dump", None):fingerprint = model_dump(mode="python")else:@@ -712,6 +717,9 @@ def _model_load_fingerprint(config: AnyModelConfig) -> dict[str, Any]:for field in _MODEL_METADATA_FIELDS:fingerprint.pop(field, None)+ # Keep hash and file_size: re-identification recomputes them from disk, and a changed value can mean+ # the bytes at an unchanged path no longer match the loaded module.+default_settings = fingerprint.pop("default_settings", None)fingerprint["default_settings"] = {field: default_settings.get(field)@@ -1289,7 +1297,7 @@ def get_model_install_job(responses={201: {"description": "The job was cancelled successfully"},415: {"description": "No such job"},- 409: {"description": "The job has recovery data that must be preserved"},+ 409: {"description": "The job cannot be cancelled safely in its current state"},},status_code=201,)@@ -1305,7 +1313,7 @@ def cancel_model_install_job(raise HTTPException(status_code=415, detail=str(e))try:installer.cancel_job(job)- except InstallRecoveryRequiredError as e:+ except (InstallCancellationConflictError, InstallDownloadConflictError) as e:raise HTTPException(status_code=409, detail=str(e)) from e@@ -1314,6 +1322,7 @@ def cancel_model_install_job(operation_id="pause_model_install_job",responses={201: {"description": "The job was paused successfully"},+ 409: {"description": "The job cannot be paused in its current state"},415: {"description": "No such job"},},status_code=201,@@ -1327,7 +1336,10 @@ def pause_model_install_job(job = installer.get_job_by_id(id)except ValueError as e:raise HTTPException(status_code=415, detail=str(e))- installer.pause_job(job)+ try:+ installer.pause_job(job)+ except InstallDownloadConflictError as e:+ raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1336,6 +1348,7 @@ def pause_model_install_job(operation_id="resume_model_install_job",responses={201: {"description": "The job was resumed successfully"},+ 409: {"description": "A previous download still owns the staging directory"},415: {"description": "No such job"},},status_code=201,@@ -1349,7 +1362,10 @@ def resume_model_install_job(job = installer.get_job_by_id(id)except ValueError as e:raise HTTPException(status_code=415, detail=str(e))- installer.resume_job(job)+ try:+ installer.resume_job(job)+ except InstallDownloadConflictError as e:+ raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1358,7 +1374,7 @@ def resume_model_install_job(operation_id="restart_failed_model_install_job",responses={201: {"description": "Failed files restarted successfully"},- 409: {"description": "The job has recovery data that must be preserved"},+ 409: {"description": "A prior download is active or recovery data must be preserved"},415: {"description": "No such job"},},status_code=201,@@ -1374,7 +1390,7 @@ def restart_failed_model_install_job(raise HTTPException(status_code=415, detail=str(e))try:installer.restart_failed(job)- except InstallRecoveryRequiredError as e:+ except (InstallDownloadConflictError, InstallRecoveryRequiredError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn job@@ -1384,7 +1400,7 @@ def restart_failed_model_install_job(operation_id="restart_model_install_file",responses={201: {"description": "File restarted successfully"},- 409: {"description": "The job has recovery data that must be preserved"},+ 409: {"description": "A prior download is active or recovery data must be preserved"},415: {"description": "No such job"},},status_code=201,@@ -1402,7 +1418,7 @@ def restart_model_install_file(raise HTTPException(status_code=415, detail=str(e))try:installer.restart_file(job, str(file_source))- except InstallRecoveryRequiredError as e:+ except (InstallDownloadConflictError, InstallRecoveryRequiredError) as e:raise HTTPException(status_code=409, detail=str(e)) from ereturn jobdiff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.pyindex f5c7cb046f..2f97014f30 100644--- a/invokeai/app/services/download/download_default.py+++ b/invokeai/app/services/download/download_default.py@@ -121,23 +121,45 @@ class DownloadQueueService(DownloadQueueServiceBase):self._accept_download_requests = Truedef stop(self, *args: Any, **kwargs: Any) -> None:- """Stop the download worker threads."""+ """Stop workers after notifying queued and active jobs of cancellation or pause."""with self._lock:if not self._worker_pool:return- self._accept_download_requests = False # reject attempts to add new jobs to queue+ self._accept_download_requests = Falsequeued_jobs = [x for x in self.list_jobs() if x.status == DownloadJobStatus.WAITING]active_jobs = [x for x in self.list_jobs() if x.status == DownloadJobStatus.RUNNING]if queued_jobs:- self._logger.warning(f"Cancelling {len(queued_jobs)} queued downloads")+ self._logger.warning(f"Stopping {len(queued_jobs)} queued downloads")if active_jobs:self._logger.info(f"Waiting for {len(active_jobs)} active download jobs to complete")- with self._queue.mutex:- self._queue.queue.clear()- self.cancel_all_jobs()+ for job in self._jobs.values():+ if not job.in_terminal_state and not job.paused:+ job.cancel()+ workers = tuple(self._worker_pool)self._stop_event.set()- for thread in self._worker_pool:- thread.join()++ # Jobs removed from the queue have no worker to deliver their terminal callback. Finalize them here so+ # multifile owners can release staging claims after the queue has made them quiescent.+ while True:+ try:+ job = self._queue.get_nowait()+ except Empty:+ break+ try:+ if job.paused:+ self._signal_job_paused(job)+ elif not job.in_terminal_state:+ self._cleanup_cancelled_job(job)+ self._signal_job_cancelled(job)+ finally:+ job.job_ended = get_iso_timestamp()+ self._job_terminated_event.set()+ self._download_part2parent.pop(job.id, None)+ self._queue.task_done()++ for thread in workers:+ thread.join()+ with self._lock:self._worker_pool.clear()def submit_download_job(@@ -150,26 +172,33 @@ class DownloadQueueService(DownloadQueueServiceBase):on_error: Optional[DownloadExceptionHandler] = None,) -> None:"""Enqueue a download job."""- if not self._accept_download_requests:- raise ServiceInactiveException(- "The download service is not currently accepting requests. Please call start() to initialize the service."+ with self._lock:+ if not self._accept_download_requests:+ raise ServiceInactiveException(+ "The download service is not currently accepting requests. Please call start() to initialize the service."+ )+ if job.id == -1:+ job.id = self._next_job_id+ self._next_job_id += 1+ job.set_callbacks(+ on_start=on_start,+ on_progress=on_progress,+ on_complete=on_complete,+ on_cancelled=on_cancelled,+ on_error=on_error,)- if job.id == -1:- job.id = self._next_id()- job.set_callbacks(- on_start=on_start,- on_progress=on_progress,- on_complete=on_complete,- on_cancelled=on_cancelled,- on_error=on_error,- )- self._jobs[job.id] = job- self._queue.put(job)+ self._jobs[job.id] = job+ self._queue.put(job)def pause_job(self, job: DownloadJobBase) -> None:"""Pause the indicated job, preserving partial downloads."""- if job.status in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:- job.pause()+ if job.status not in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:+ return+ job.pause()+ if isinstance(job, MultiFileDownloadJob):+ for part in job.download_parts:+ if part.status in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:+ part.pause()def download(self,@@ -249,26 +278,38 @@ class DownloadQueueService(DownloadQueueServiceBase):def submit_multifile_download(self, job: MultiFileDownloadJob) -> None:pending = sorted(job.download_parts, key=lambda j: str(j.source))- self._mfd_pending[job.id] = list(pending)- self._mfd_active.pop(job.id, None)+ with self._lock:+ self._mfd_pending[job.id] = list(pending)+ self._mfd_active.pop(job.id, None)self._submit_next_mfd_part(job)def _submit_next_mfd_part(self, job: MultiFileDownloadJob) -> None:- pending = self._mfd_pending.get(job.id, [])- if not pending:- return- if self._mfd_active.get(job.id) is not None:- return- download_job = pending.pop(0)- self._mfd_active[job.id] = download_job- self.submit_download_job(- download_job,- on_start=self._mfd_started,- on_progress=self._mfd_progress,- on_complete=self._mfd_complete,- on_cancelled=self._mfd_cancelled,- on_error=self._mfd_error,- )+ with self._lock:+ pending = self._mfd_pending.get(job.id, [])+ if not pending or self._mfd_active.get(job.id) is not None or job.in_terminal_state:+ return+ if not self._accept_download_requests:+ paused = all(part.in_terminal_state or part.paused for part in job.download_parts)+ self._finalize_multifile_cancellation(job, paused=paused)+ return+ download_job = pending.pop(0)+ self._mfd_active[job.id] = download_job++ try:+ self.submit_download_job(+ download_job,+ on_start=self._mfd_started,+ on_progress=self._mfd_progress,+ on_complete=self._mfd_complete,+ on_cancelled=self._mfd_cancelled,+ on_error=self._mfd_error,+ )+ except ServiceInactiveException:+ # Shutdown can close submissions after the active part completes but before its successor is queued.+ with self._lock:+ if not job.in_terminal_state:+ paused = all(part.in_terminal_state or part.paused for part in job.download_parts)+ self._finalize_multifile_cancellation(job, paused=paused)def join(self) -> None:"""Wait for all jobs to complete."""@@ -310,6 +351,10 @@ class DownloadQueueService(DownloadQueueServiceBase):"""if job.status in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:job.cancel()+ if isinstance(job, MultiFileDownloadJob):+ for part in job.download_parts:+ if part.status in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:+ part.cancel()def cancel_all_jobs(self) -> None:"""Cancel all jobs (those not in enqueued, running or paused state)."""@@ -358,8 +403,8 @@ class DownloadQueueService(DownloadQueueServiceBase):if job.paused:self._signal_job_paused(job)else:- self._signal_job_cancelled(job)self._cleanup_cancelled_job(job)+ self._signal_job_cancelled(job)except Exception as excp:job.error_type = excp.__class__.__name__ + f"({str(excp)})"job.error = traceback.format_exc()@@ -794,37 +839,54 @@ class DownloadQueueService(DownloadQueueServiceBase):mf_job.total_bytes = sum(x.total_bytes for x in mf_job.download_parts)mf_job.bytes = sum(x.bytes for x in mf_job.download_parts)- # are there any more active jobs left in this task?- if all(x.complete for x in mf_job.download_parts):+ if mf_job.cancelled:+ self._finalize_multifile_cancellation(mf_job, paused=False)+ elif all(part.complete for part in mf_job.download_parts):+ self._mfd_pending.pop(mf_job.id, None)mf_job.status = DownloadJobStatus.COMPLETEDself._execute_cb(mf_job, "on_complete")- elif not mf_job.in_terminal_state and not mf_job.paused:+ elif all(part.in_terminal_state or part.paused for part in mf_job.download_parts):+ self._finalize_multifile_cancellation(mf_job, paused=True)+ elif not mf_job.in_terminal_state:submit_next = True- # we're done with this sub-jobself._job_terminated_event.set()if submit_next and mf_job is not None:self._submit_next_mfd_part(mf_job)+ def _finalize_multifile_cancellation(self, mf_job: MultiFileDownloadJob, *, paused: bool) -> None:+ """Finalize a multifile transfer after its active part stops touching disk."""+ if mf_job.in_terminal_state:+ return+ self._mfd_active.pop(mf_job.id, None)+ self._mfd_pending.pop(mf_job.id, None)+ for part in mf_job.download_parts:+ if part.in_terminal_state:+ self._download_part2parent.pop(part.id, None)+ continue+ if paused:+ part.pause()+ part.status = DownloadJobStatus.PAUSED+ else:+ part.cancel()+ self._cleanup_cancelled_job(part)+ part.status = DownloadJobStatus.CANCELLED+ part.job_ended = get_iso_timestamp()+ self._download_part2parent.pop(part.id, None)++ if paused:+ mf_job.pause()+ mf_job.status = DownloadJobStatus.PAUSED+ else:+ mf_job.cancel()+ mf_job.status = DownloadJobStatus.CANCELLED+ self._execute_cb(mf_job, "on_cancelled")+ self._job_terminated_event.set()+def _mfd_cancelled(self, download_job: DownloadJob) -> None:with self._lock:mf_job = self._download_part2parent[download_job.id]- assert mf_job is not None- self._mfd_active.pop(mf_job.id, None)-- if not mf_job.in_terminal_state:- if download_job.paused:- self._logger.warning(f"Download paused: {download_job.source}")- mf_job.pause()- else:- self._logger.warning(f"Download cancelled: {download_job.source}")- mf_job.cancel()-- if download_job.paused:- return- for s in mf_job.download_parts:- self.cancel_job(s)- self._mfd_pending.pop(mf_job.id, None)+ self._finalize_multifile_cancellation(mf_job, paused=download_job.paused)def _mfd_error(self, download_job: DownloadJob, excp: Optional[Exception] = None) -> None:with self._lock:@@ -832,16 +894,23 @@ class DownloadQueueService(DownloadQueueServiceBase):assert mf_job is not Noneself._mfd_active.pop(mf_job.id, None)if not mf_job.in_terminal_state:+ self._mfd_pending.pop(mf_job.id, None)+ for part in mf_job.download_parts:+ if part is download_job or part.in_terminal_state:+ continue+ part.cancel()+ self._cleanup_cancelled_job(part)+ part.status = DownloadJobStatus.CANCELLED+ part.job_ended = get_iso_timestamp()+ self._download_part2parent.pop(part.id, None)+mf_job.status = download_job.statusmf_job.error = download_job.errormf_job.error_type = download_job.error_type- self._execute_cb(mf_job, "on_error", excp)self._logger.error(f"Cancelling {mf_job.dest} due to an error while downloading {download_job.source}: {str(excp)}")- for s in [x for x in mf_job.download_parts if x.running]:- self.cancel_job(s)- self._mfd_pending.pop(mf_job.id, None)+ self._execute_cb(mf_job, "on_error", excp)self._job_terminated_event.set()def _execute_cb(diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex 620e73210c..f423a9b0a1 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -1,9 +1,11 @@+import osimport reimport tracebackfrom enum import Enumfrom pathlib import Pathfrom typing import Literal, Optional, Set, Union+import psutilfrom pydantic import BaseModel, Field, PrivateAttr, field_validatorfrom pydantic.networks import AnyHttpUrlfrom typing_extensions import Annotated@@ -22,9 +24,18 @@ class InvalidModelConfigException(Exception):INSTALL_RECOVERY_SENTINEL = ".invokeai_install_recovery_required"+INSTALL_ACTIVE_SENTINEL = ".invokeai_install_active"-class InstallRecoveryRequiredError(RuntimeError):+class InstallCancellationConflictError(RuntimeError):+ """The install cannot be cancelled safely in its current state."""+++class InstallDownloadConflictError(RuntimeError):+ """A prior remote download still owns this install's staging directory."""+++class InstallRecoveryRequiredError(InstallCancellationConflictError):"""Install transfer could not be safely rolled back; preserve both recovery roots."""@@ -33,17 +44,53 @@ def recovery_sentinel_path(root: Path) -> Path:return root.parent / f".{root.name}{INSTALL_RECOVERY_SENTINEL}"+def active_install_sentinel_path(root: Path) -> Path:+ """Return the sidecar marker used to coordinate an active install with orphan cleanup."""+ return root.parent / f".{root.name}{INSTALL_ACTIVE_SENTINEL}"++def has_recovery_sentinel(root: Path) -> bool:"""Return whether an install recovery root has a durable preservation marker."""return recovery_sentinel_path(root).exists()+def has_active_install_sentinel(root: Path) -> bool:+ """Return whether a live install or orphan deletion has claimed this path."""+ return active_install_sentinel_path(root).exists()+++def create_active_install_sentinel(root: Path) -> None:+ """Atomically claim a path against concurrent install or orphan-delete operations."""+ path = active_install_sentinel_path(root)+ path.parent.mkdir(parents=True, exist_ok=True)+ created = False+ try:+ with open(path, "xb") as f:+ created = True+ process = psutil.Process()+ f.write(f"{process.pid} {process.create_time()!r}\n".encode("ascii"))+ f.flush()+ os.fsync(f.fileno())+ except Exception:+ if created:+ path.unlink(missing_ok=True)+ raise+++def delete_active_install_sentinel(root: Path) -> None:+ """Release an active install or orphan-delete claim."""+ try:+ active_install_sentinel_path(root).unlink()+ except FileNotFoundError:+ pass++def is_recovery_protected_path(path: Path, boundary: Path) -> bool:- """Return whether a path or one of its ancestors below the boundary is recovery-protected."""+ """Return whether a path is protected by an active install claim or recovery marker."""boundary = boundary.resolve()current = path.resolve()while current != boundary and current.is_relative_to(boundary):- if has_recovery_sentinel(current):+ if has_recovery_sentinel(current) or has_active_install_sentinel(current):return Truecurrent = current.parentreturn False@@ -227,10 +274,19 @@ class ModelInstallJob(BaseModel):)# internal flags and transitory settings_install_tmpdir: Optional[Path] = PrivateAttr(default=None)+ _install_tmpdir_active_sentinel_created: bool = PrivateAttr(default=False)+ _install_tmpdir_claim_conflict: bool = PrivateAttr(default=False)+ _install_tmpdir_recovery_sentinel_created: bool = PrivateAttr(default=False)_multifile_job: Optional[MultiFileDownloadJob] = PrivateAttr(default=None)_exception: Optional[Exception] = PrivateAttr(default=None)_resume_metadata: Optional[dict] = PrivateAttr(default=None)_recovery_required: bool = PrivateAttr(default=False)+ _cancel_requested: bool = PrivateAttr(default=False)+ _install_phase: Optional[str] = PrivateAttr(default=None)+ _source_protection_root: Optional[Path] = PrivateAttr(default=None)+ _source_active_sentinel_created: bool = PrivateAttr(default=False)+ _source_recovery_sentinel_created: bool = PrivateAttr(default=False)+ _source_recovery_sentinel_preexisting: bool = PrivateAttr(default=False)def set_error(self, e: Exception) -> None:"""Record the error and traceback from an exception."""diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 348afb02be..70160bdee9 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -16,8 +16,9 @@ from pathlib import Pathfrom queue import Empty, Queuefrom shutil import copy2, copytree, move, rmtreefrom tempfile import mkdtemp-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union+import psutilimport torchimport yamlfrom huggingface_hub import get_token as hf_get_token@@ -30,9 +31,12 @@ from invokeai.app.services.download import DownloadQueueServiceBase, MultiFileDofrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.model_install.model_install_base import ModelInstallServiceBasefrom invokeai.app.services.model_install.model_install_common import (+ INSTALL_ACTIVE_SENTINEL,MODEL_SOURCE_TO_TYPE_MAP,ExternalModelSource,HFModelSource,+ InstallCancellationConflictError,+ InstallDownloadConflictError,InstallRecoveryRequiredError,InstallStatus,InvalidModelConfigException,@@ -41,6 +45,9 @@ from invokeai.app.services.model_install.model_install_common import (ModelSource,StringLikeSource,URLModelSource,+ create_active_install_sentinel,+ delete_active_install_sentinel,+ has_active_install_sentinel,has_recovery_sentinel,is_recovery_protected_path,recovery_sentinel_path,@@ -91,6 +98,11 @@ TMPDIR_PREFIX = "tmpinstall_"INSTALL_MARKER_FILENAME = ".invokeai_install.json"INSTALL_MARKER_VERSION = 1++class _InstallCancelledBeforeTransfer(Exception):+ """Raised when a cancellation request wins before file transfer becomes protected."""++# Filesystems cap a single path component at 255 bytes. A source that lists many explicit files# (an LTX-2 component folder names eight) would otherwise produce a folder name that cannot be# created; the combined name is only a label, so it is shortened past this point with a count.@@ -136,6 +148,7 @@ class ModelInstallService(ModelInstallServiceBase):self._install_jobs: List[ModelInstallJob] = []self._install_queue: Queue[ModelInstallJob] = Queue()self._lock = threading.Lock()+ self._active_install_job: Optional[ModelInstallJob] = Noneself._stop_event = threading.Event()self._downloads_changed_event = threading.Event()self._install_completed_event = threading.Event()@@ -145,6 +158,8 @@ class ModelInstallService(ModelInstallServiceBase):self._startup_error: Optional[BaseException] = Noneself._download_queue = download_queueself._download_cache: Dict[int, ModelInstallJob] = {}+ self._remote_download_operations: set[int] = set()+ self._remote_download_condition = threading.Condition(self._lock)# Per-source locks serializing download_and_cache_model() so parallel (multi-GPU) sessions# that need the same remote model (e.g. the LaMa infill model) don't race to download into# the same cache directory. _download_cache_locks_guard protects the dict itself.@@ -198,9 +213,108 @@ class ModelInstallService(ModelInstallServiceBase):except OSError as e:self._logger.warning(f"Failed to remove install recovery sentinel in {tmpdir}: {e}")+ def _protect_managed_source_path(+ self, model_path: Path, *, allow_recovery: bool = False+ ) -> tuple[Optional[Path], bool, bool]:+ """Claim the top-level orphan-scan root containing a local source."""+ source_root = model_path if model_path.is_dir() else model_path.parent+ models_root = self.app_config.models_path.resolve()+ source_root = source_root.resolve()+ if source_root == models_root or not source_root.is_relative_to(models_root):+ return None, False, False+ source_relative = source_root.relative_to(models_root)+ source_root = models_root / source_relative.parts[0]+ has_recovery = False+ current = model_path.resolve() if model_path.is_dir() else model_path.resolve().parent+ while current != models_root and current.is_relative_to(models_root):+ if has_active_install_sentinel(current):+ raise InstallCancellationConflictError(+ f"Cannot use local model source {current}: another install or orphan cleanup is using it."+ )+ has_recovery = has_recovery or self._has_recovery_sentinel(current)+ current = current.parent+ if has_recovery and not allow_recovery:+ raise InstallRecoveryRequiredError(+ f"Cannot use local model source {source_root}: it contains install recovery data."+ )+ try:+ create_active_install_sentinel(source_root)+ except FileExistsError as e:+ raise InstallCancellationConflictError(+ f"Cannot use local model source {source_root}: another install or orphan cleanup is using it."+ ) from e+ return source_root, True, has_recovery++ def _release_job_source_protection(self, job: ModelInstallJob, *, preserve_recovery: bool = False) -> None:+ self._release_install_tmpdir_claim(job)+ if job._source_active_sentinel_created:+ assert job._source_protection_root is not None+ delete_active_install_sentinel(job._source_protection_root)+ job._source_active_sentinel_created = False+ if not preserve_recovery:+ if job._install_tmpdir is not None and job._install_tmpdir_recovery_sentinel_created:+ self._delete_recovery_sentinel(job._install_tmpdir)+ job._install_tmpdir_recovery_sentinel_created = False+ if job._source_recovery_sentinel_created or (job._source_recovery_sentinel_preexisting and job.complete):+ assert job._source_protection_root is not None+ self._delete_recovery_sentinel(job._source_protection_root)+ job._source_recovery_sentinel_created = False++ @staticmethod+ def _release_install_tmpdir_claim(job: ModelInstallJob) -> None:+ if job._install_tmpdir is not None and job._install_tmpdir_active_sentinel_created:+ delete_active_install_sentinel(job._install_tmpdir)+ job._install_tmpdir_active_sentinel_created = False++ def _claim_install_tmpdir(self, job: ModelInstallJob) -> None:+ if job._install_tmpdir is None or job._install_tmpdir_active_sentinel_created:+ return+ try:+ create_active_install_sentinel(job._install_tmpdir)+ except FileExistsError as e:+ job._install_tmpdir_claim_conflict = True+ raise InstallCancellationConflictError(+ f"Cannot use install staging path {job._install_tmpdir}: another install or orphan cleanup is using it."+ ) from e+ job._install_tmpdir_active_sentinel_created = True+ job._install_tmpdir_claim_conflict = False++ def _remove_unclaimed_install_tmpdir(self, tmpdir: Path) -> bool:+ """Remove a stale staging tree only after atomically excluding active install work."""+ try:+ create_active_install_sentinel(tmpdir)+ except FileExistsError:+ self._logger.debug(f"Preserving active install directory {tmpdir}")+ return False+ try:+ self._safe_rmtree(tmpdir, self._logger)+ finally:+ delete_active_install_sentinel(tmpdir)+ return True++ def _remove_stale_install_source_claims(self) -> None:+ """Remove active-claim sidecars left by processes that exited before releasing them."""+ for claim_path in self.app_config.models_path.glob(f"*{INSTALL_ACTIVE_SENTINEL}"):+ try:+ pid_text, create_time_text = claim_path.read_text(encoding="ascii").split()+ pid = int(pid_text)+ create_time = float(create_time_text)+ process = psutil.Process(pid)+ if process.status() == psutil.STATUS_ZOMBIE or process.create_time() != create_time:+ claim_path.unlink(missing_ok=True)+ except (psutil.NoSuchProcess, psutil.ZombieProcess):+ claim_path.unlink(missing_ok=True)+ except psutil.AccessDenied:+ continue+ except ValueError:+ claim_path.unlink(missing_ok=True)+ except OSError:+ # Permission errors mean the owner process may still be active. Unknown failures are conservative too.+ continue+def _retain_recovery_destination(self, dest_dir: Path) -> None:try:- if dest_dir.exists():+ if dest_dir.exists() and not self._has_recovery_sentinel(dest_dir):self._write_recovery_sentinel(dest_dir)except Exception as sentinel_error:self._logger.error(f"Failed to persist destination recovery sentinel in {dest_dir}: {sentinel_error}")@@ -269,7 +383,7 @@ class ModelInstallService(ModelInstallServiceBase):source_str = str(source)candidates: list[tuple[str, Path]] = []for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):- if self._has_recovery_sentinel(tmpdir):+ if has_active_install_sentinel(tmpdir) or self._has_recovery_sentinel(tmpdir):continuemarker = self._read_install_marker(tmpdir)if not marker:@@ -296,6 +410,9 @@ class ModelInstallService(ModelInstallServiceBase):active_sources = {str(j.source) for j in self._install_jobs if not j.in_terminal_state}active_sources.update(str(j.source) for j in self._download_cache.values() if not j.in_terminal_state)for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ if has_active_install_sentinel(tmpdir):+ self._logger.debug(f"Skipping active install directory {tmpdir}")+ continueif self._has_recovery_sentinel(tmpdir):self._logger.warning(f"Preserving install recovery data in {tmpdir}")continue@@ -323,7 +440,7 @@ class ModelInstallService(ModelInstallServiceBase):continueif source_str in seen_sources:self._logger.info(f"Removing duplicate temporary directory {tmpdir}")- self._safe_rmtree(tmpdir, self._logger)+ self._remove_unclaimed_install_tmpdir(tmpdir)continue# Inside the `try`: a marker written by an older version can hold a config that no longer# validates, and that must skip this marker, not abort the restore of every marker after it. Note@@ -344,6 +461,13 @@ class ModelInstallService(ModelInstallServiceBase):local_path=tmpdir,)job._install_tmpdir = tmpdir+ 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.+ self._claim_install_tmpdir(job)+ except InstallCancellationConflictError as e:+ self._logger.info(f"Skipping restore of claimed install directory {tmpdir}: {e}")+ continuefiles_meta = marker.get("files") or []if files_meta:job._resume_metadata = {f.get("url"): f for f in files_meta if f.get("url")}@@ -361,8 +485,12 @@ class ModelInstallService(ModelInstallServiceBase):self._resume_remote_download(job)except Exception as e:self._set_error(job, e)- if job._install_tmpdir is not None:- self._safe_rmtree(job._install_tmpdir, self._logger)+ if job._install_tmpdir is not None and not job._install_tmpdir_claim_conflict:+ if job._install_tmpdir_active_sentinel_created:+ self._safe_rmtree(job._install_tmpdir, self._logger)+ self._release_install_tmpdir_claim(job)+ else:+ self._remove_unclaimed_install_tmpdir(job._install_tmpdir)def _restore_incomplete_installs_async(self) -> None:self._restore_completed_event.clear()@@ -396,37 +524,82 @@ class ModelInstallService(ModelInstallServiceBase):remaining = None if deadline is None else max(0.0, deadline - time.monotonic())return self._restore_completed_event.wait(timeout=remaining)- def _resume_remote_download(self, job: ModelInstallJob) -> None:- job.status = InstallStatus.WAITING- # Sources whose partial file has vanished. _enqueue_remote_download replaces job.download_parts- # with fresh parts, so the flag must be carried onto them or the resume response loses it.- restarted_from_scratch: set[str] = set()- if job.download_parts:- for part in job.download_parts:- if part.complete or part.bytes <= 0:- continue- if not part.download_path:- continue- in_progress_path = part.download_path.with_name(part.download_path.name + ".downloading")- if not in_progress_path.exists():- part.bytes = 0- part.resume_from_scratch = True- part.resume_message = "Partial file missing. Restarted download from the beginning."- restarted_from_scratch.add(str(part.source))- job.bytes = sum(p.bytes for p in job.download_parts)- remote_files, metadata = self._remote_files_from_source(job.source)- subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []- self._enqueue_remote_download(- job=job,- source=job.source,- remote_files=remote_files,- metadata=metadata,- destdir=job._install_tmpdir or job.local_path,- subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,- subfolders=subfolders if len(subfolders) > 1 else None,- resume_metadata=job._resume_metadata,- restarted_from_scratch=restarted_from_scratch,- )+ def _resume_remote_download(self, job: ModelInstallJob, *, operation_reserved: bool = False) -> None:+ if not operation_reserved:+ self._begin_remote_download_operation(job)+ previous_status = job.status+ try:+ # Sources whose partial file has vanished. _enqueue_remote_download replaces job.download_parts+ # with fresh parts, so the flag must be carried onto them or the resume response loses it.+ restarted_from_scratch: set[str] = set()+ if job.download_parts:+ for part in job.download_parts:+ if part.complete or part.bytes <= 0:+ continue+ if not part.download_path:+ continue+ in_progress_path = part.download_path.with_name(part.download_path.name + ".downloading")+ if not in_progress_path.exists():+ part.bytes = 0+ part.resume_from_scratch = True+ part.resume_message = "Partial file missing. Restarted download from the beginning."+ restarted_from_scratch.add(str(part.source))+ job.bytes = sum(p.bytes for p in job.download_parts)+ remote_files, metadata = self._remote_files_from_source(job.source)+ if not remote_files:+ raise RuntimeError("No remote files are available to download")+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ job.status = InstallStatus.WAITING+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder+ if isinstance(job.source, HFModelSource) and len(subfolders) <= 1+ else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ resume_metadata=job._resume_metadata,+ restarted_from_scratch=restarted_from_scratch,+ )+ except BaseException:+ job.status = previous_status+ raise+ finally:+ if not operation_reserved:+ self._end_remote_download_operation(job)++ 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()+ )+ if require_paused:+ if download_active:+ raise InstallDownloadConflictError(+ "A previous download is still active; wait for it to finish before resuming or restarting."+ )+ if not job.paused:+ return False+ if job.cancelled or job.complete:+ raise InstallDownloadConflictError(+ "The install is already terminal and cannot be resumed or restarted."+ )+ if download_active:+ raise InstallDownloadConflictError(+ "A previous download is still active; wait for it to finish before resuming or restarting."+ )+ self._remote_download_operations.add(job.id)+ return True++ def _end_remote_download_operation(self, job: ModelInstallJob) -> None:+ with self._remote_download_condition:+ self._remote_download_operations.discard(job.id)+ self._remote_download_condition.notify_all()@propertydef app_config(self) -> InvokeAIAppConfig: # noqa D102@@ -451,6 +624,7 @@ class ModelInstallService(ModelInstallServiceBase):self._startup_error = Noneself._restore_completed_event.clear()try:+ self._remove_stale_install_source_claims()self._start_installer_thread()self._remove_dangling_install_dirs()self._migrate_yaml()@@ -478,13 +652,23 @@ class ModelInstallService(ModelInstallServiceBase):if not self._running:returnself._logger.debug("calling stop_event.set()")- self._stop_event.set()- self._clear_pending_jobs()with self._lock:- self._download_cache.clear()+ self._stop_event.set()assert self._install_thread is not None- self._install_thread.join()- self._running = False+ try:+ # Let the worker finish (or leave a dequeued job untouched) before cleaning pending jobs. Otherwise+ # shutdown can mistake a job between Queue.get() and _active_install_job assignment for pending work.+ self._install_thread.join()+ finally:+ try:+ with self._remote_download_condition:+ self._remote_download_condition.wait_for(lambda: not self._remote_download_operations)+ self._clear_pending_jobs()+ finally:+ with self._lock:+ # Download cancellation is asynchronous. Keep these job references until their+ # callbacks have stopped touching staging paths and release their active claims.+ self._running = Falsedef _write_invoke_managed_models_dir_readme(self) -> None:"""Write a README file to the Invoke-managed models directory warning users to not fiddle with it."""@@ -495,14 +679,44 @@ class ModelInstallService(ModelInstallServiceBase):)def _clear_pending_jobs(self) -> None:- for job in self.list_jobs():- if not job.in_terminal_state:- if job._multifile_job is not None:- self._logger.warning(f"Pausing job {job.id}")- self.pause_job(job)+ for job in list(self.list_jobs()):+ with self._lock:+ if job.in_terminal_state or self._active_install_job is job:+ continue+ if job._recovery_required or (+ job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)+ ):+ self._logger.warning(f"Preserving recovery data for job {job.id} during shutdown")+ continue+ multifile_job = job._multifile_job+ download_callback_pending = any(cached_job is job for cached_job in self._download_cache.values())+ downloads_complete = multifile_job is not None and multifile_job.complete+ if multifile_job is None:+ job.cancel()+ elif downloads_complete:+ job.status = InstallStatus.DOWNLOADS_DONEelse:- self._logger.warning(f"Cancelling job {job.id}")- self.cancel_job(job)+ job.status = InstallStatus.PAUSED++ if multifile_job is not None and downloads_complete:+ self._write_install_marker(job, status=InstallStatus.DOWNLOADS_DONE)+ if not download_callback_pending:+ self._release_install_tmpdir_claim(job)+ elif multifile_job is not None:+ self._logger.warning(f"Pausing job {job.id}")+ for part in multifile_job.download_parts:+ self._download_queue.pause_job(part)+ self._write_install_marker(job, status=InstallStatus.PAUSED)+ if self._stop_event.is_set() and not download_callback_pending:+ # The pause callback already ran, so no download worker can still touch staging.+ self._release_install_tmpdir_claim(job)+ elif job._install_tmpdir is not None:+ self._logger.warning(f"Cancelling job {job.id}")+ if not job._install_tmpdir_claim_conflict:+ self._write_install_marker(job, status=InstallStatus.CANCELLED)+ self._delete_install_marker(job._install_tmpdir)+ self._safe_rmtree(job._install_tmpdir, self._logger)+ self._release_install_tmpdir_claim(job)while True:try:job = self._install_queue.get(block=False)@@ -511,10 +725,17 @@ class ModelInstallService(ModelInstallServiceBase):breakdef _put_in_queue(self, job: ModelInstallJob) -> None:- if self._stop_event.is_set():+ with self._lock:+ queued = self._queue_install_job_locked(job)+ if not queued:self.cancel_job(job)- else:- self._install_queue.put(job)++ def _queue_install_job_locked(self, job: ModelInstallJob) -> bool:+ """Queue an install while holding _lock, preserving shutdown and wait_for_installs ordering."""+ if self._stop_event.is_set():+ return False+ self._install_queue.put(job)+ return Truedef register_path(self,@@ -526,7 +747,20 @@ class ModelInstallService(ModelInstallServiceBase):if not config.source:config.source = model_path.resolve().as_posix()config.source_type = ModelSourceType.Path- return self._register(model_path, config)+ source_root, active_sentinel_created, had_recovery_sentinel = self._protect_managed_source_path(+ model_path, allow_recovery=True+ )+ had_recovery_sentinel = source_root is not None and had_recovery_sentinel+ registered = False+ try:+ model_id = self._register(model_path, config)+ registered = True+ return model_id+ finally:+ if active_sentinel_created and source_root is not None:+ delete_active_install_sentinel(source_root)+ if registered and had_recovery_sentinel and source_root is not None:+ self._delete_recovery_sentinel(source_root)# TODO: Replace this with a proper fix for underlying problem of Windows holding open# the file when it needs to be moved.@@ -631,13 +865,69 @@ class ModelInstallService(ModelInstallServiceBase):) -> str:model_path = Path(model_path)config = config or ModelRecordChanges()- info: AnyModelConfig = self._probe(Path(model_path), config) # type: ignore+ source_root, active_sentinel_created, had_recovery_sentinel = self._protect_managed_source_path(+ model_path, allow_recovery=True+ )+ source_recovery_sentinel_created = False+ preserve_source = False+ installed = False+ try:+ info: AnyModelConfig = self._probe(Path(model_path), config) # type: ignore+ def begin_transfer() -> bool:+ nonlocal source_recovery_sentinel_created+ if source_root is not None and active_sentinel_created and not self._has_recovery_sentinel(source_root):+ self._write_recovery_sentinel(source_root)+ source_recovery_sentinel_created = True+ return True++ model_id = self._install_path_with_info(model_path, config, info, before_transfer=begin_transfer)+ installed = True+ return model_id+ except InstallRecoveryRequiredError:+ preserve_source = True+ raise+ finally:+ if active_sentinel_created and source_root is not None:+ delete_active_install_sentinel(source_root)+ if (+ active_sentinel_created+ and source_root is not None+ and (installed or (source_recovery_sentinel_created and not preserve_source))+ ):+ self._delete_recovery_sentinel(source_root)++ def _install_path_with_info(+ self,+ model_path: Path,+ config: ModelRecordChanges,+ info: AnyModelConfig,+ before_transfer: Optional[Callable[[], bool]] = None,+ ) -> str:# The key names the directory the model is moved into. `ModelRecordChanges` validates a client-supplied key,# but a caller can build one without validation, so check again here - before anything is created or moved.if not is_plain_filename(info.key):raise ValueError(f"Invalid model key {info.key!r}: it must be a plain filename")dest_dir = self.app_config.models_path / info.key+ try:+ create_active_install_sentinel(dest_dir)+ except FileExistsError as e:+ raise InstallCancellationConflictError(+ f"Cannot install model to {dest_dir}: another install or orphan cleanup is using it."+ ) from e+ try:+ return self._install_path_with_info_claimed(model_path, config, info, before_transfer)+ finally:+ delete_active_install_sentinel(dest_dir)++ def _install_path_with_info_claimed(+ self,+ model_path: Path,+ config: ModelRecordChanges,+ info: AnyModelConfig,+ before_transfer: Optional[Callable[[], bool]],+ ) -> str:+ dest_dir = self.app_config.models_path / info.keymoved: list[tuple[Path, Path]] = []source_is_directory = model_path.is_dir()destination_created = False@@ -652,6 +942,8 @@ class ModelInstallService(ModelInstallServiceBase):# Protect every file in the destination until the model record is committed. An admin can run orphan# cleanup concurrently with this transfer, and the directory is not registered until _register().self._write_recovery_sentinel(dest_dir)+ if before_transfer is not None and not before_transfer():+ raise _InstallCancelledBeforeTransfer()dest_path = dest_dir / model_path.name if model_path.is_file() else dest_dirif model_path.is_file():try:@@ -856,27 +1148,48 @@ class ModelInstallService(ModelInstallServiceBase):def cancel_job(self, job: ModelInstallJob) -> None:"""Cancel the indicated job."""- if job._recovery_required or (- job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)- ):- raise InstallRecoveryRequiredError(- "Cannot cancel an install that requires recovery; preserve its files for manual recovery."- )- job.cancel()+ with self._lock:+ if job.id in self._remote_download_operations:+ raise InstallDownloadConflictError(+ "A remote download is being prepared; wait for it to finish before cancelling."+ )+ if job.complete or job.cancelled:+ return+ if job._recovery_required or (+ job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)+ ):+ raise InstallRecoveryRequiredError(+ "Cannot cancel an install that requires recovery; preserve its files for manual recovery."+ )+ if self._active_install_job is job:+ if job._install_phase == "transferring":+ raise InstallCancellationConflictError(+ "Cannot cancel while install files are being moved; allow the transfer to finish."+ )+ job._cancel_requested = True+ return+ job.cancel()+ download_callback_pending = any(cached_job is job for cached_job in self._download_cache.values())self._logger.warning(f"Cancelling {job.source}")if dj := job._multifile_job:- self._download_queue.cancel_job(dj)- if job._install_tmpdir is not None:- # Mark cancelled before cleanup so we don't reuse the folder if deletion fails.- self._write_install_marker(job, status=InstallStatus.CANCELLED)- self._delete_install_marker(job._install_tmpdir)- self._safe_rmtree(job._install_tmpdir, self._logger)+ if not dj.in_terminal_state or download_callback_pending:+ # The terminal queue callback still owns cleanup while the job remains in _download_cache.+ self._download_queue.cancel_job(dj)+ return+ self._cleanup_cancelled_install(job)def pause_job(self, job: ModelInstallJob) -> None:"""Pause the indicated job, preserving partial downloads."""- if job.in_terminal_state:- return- job.status = InstallStatus.PAUSED+ with self._lock:+ if job.id in self._remote_download_operations:+ raise InstallDownloadConflictError(+ "A remote download is being prepared; wait for it to finish before pausing."+ )+ if job.in_terminal_state:+ 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.")+ job.status = InstallStatus.PAUSEDself._logger.warning(f"Pausing {job.source}")if dj := job._multifile_job:for part in dj.download_parts:@@ -885,10 +1198,13 @@ class ModelInstallService(ModelInstallServiceBase):def resume_job(self, job: ModelInstallJob) -> None:"""Resume a previously paused job."""- if not job.paused:+ if not self._begin_remote_download_operation(job, require_paused=True):returnself._logger.info(f"Resuming {job.source}")- self._resume_remote_download(job)+ try:+ self._resume_remote_download(job, operation_reserved=True)+ finally:+ self._end_remote_download_operation(job)def restart_failed(self, job: ModelInstallJob) -> None:"""Restart failed or non-resumable downloads for a job."""@@ -905,20 +1221,32 @@ class ModelInstallService(ModelInstallServiceBase):sources_to_restart = {str(part.source) for part in job.download_parts if not part.complete}if not sources_to_restart:return- job.status = InstallStatus.WAITING- remote_files, metadata = self._remote_files_from_source(job.source)- remote_files = [rf for rf in remote_files if str(rf.url) in sources_to_restart]- subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []- self._enqueue_remote_download(- job=job,- source=job.source,- remote_files=remote_files,- metadata=metadata,- destdir=job._install_tmpdir or job.local_path,- subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,- subfolders=subfolders if len(subfolders) > 1 else None,- clear_partials=True,- )+ self._begin_remote_download_operation(job)+ previous_status = job.status+ try:+ remote_files, metadata = self._remote_files_from_source(job.source)+ remote_files = [rf for rf in remote_files if str(rf.url) in sources_to_restart]+ if not remote_files:+ raise RuntimeError("No remote files are available to download")+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ job.status = InstallStatus.WAITING+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder+ if isinstance(job.source, HFModelSource) and len(subfolders) <= 1+ else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ clear_partials=True,+ )+ except BaseException:+ job.status = previous_status+ raise+ finally:+ self._end_remote_download_operation(job)def restart_file(self, job: ModelInstallJob, file_source: str) -> None:"""Restart a specific file download for a job."""@@ -928,22 +1256,32 @@ class ModelInstallService(ModelInstallServiceBase):raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")if not isinstance(job.source, (HFModelSource, URLModelSource)):return- job.status = InstallStatus.WAITING- remote_files, metadata = self._remote_files_from_source(job.source)- remote_files = [rf for rf in remote_files if str(rf.url) == file_source]- if not remote_files:- return- subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []- self._enqueue_remote_download(- job=job,- source=job.source,- remote_files=remote_files,- metadata=metadata,- destdir=job._install_tmpdir or job.local_path,- subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,- subfolders=subfolders if len(subfolders) > 1 else None,- clear_partials=True,- )+ self._begin_remote_download_operation(job)+ previous_status = job.status+ try:+ remote_files, metadata = self._remote_files_from_source(job.source)+ remote_files = [rf for rf in remote_files if str(rf.url) == file_source]+ if not remote_files:+ return+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ job.status = InstallStatus.WAITING+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder+ if isinstance(job.source, HFModelSource) and len(subfolders) <= 1+ else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ clear_partials=True,+ )+ except BaseException:+ job.status = previous_status+ raise+ finally:+ self._end_remote_download_operation(job)def prune_jobs(self) -> None:"""Prune all completed and errored jobs."""@@ -1222,8 +1560,15 @@ class ModelInstallService(ModelInstallServiceBase):except Empty:continueassert job.local_path is not None+ with self._lock:+ should_process = not self._stop_event.is_set()+ if should_process:+ self._active_install_job = jobtry:- if job.cancelled:+ if not should_process:+ continue+ if job.cancelled or job._cancel_requested:+ job.cancel()self._signal_job_cancelled(job)elif job.errored:@@ -1245,15 +1590,78 @@ class ModelInstallService(ModelInstallServiceBase):)finally:- # if this is an install of a remote file, then clean up the temporary directory- if job._install_tmpdir is not None and not job._recovery_required:- self._safe_rmtree(job._install_tmpdir, self._logger)+ if should_process:+ with self._lock:+ if self._active_install_job is job:+ self._active_install_job = None+ job._install_phase = None+ # Keep our staging claim until cleanup is finished so orphan cleanup cannot+ # acquire the path in the gap before the directory is removed.+ if (+ job._install_tmpdir is not None+ and not job._recovery_required+ and not job._install_tmpdir_claim_conflict+ ):+ self._safe_rmtree(job._install_tmpdir, self._logger)+ self._release_job_source_protection(+ job,+ preserve_recovery=job._recovery_required+ or (job._source_recovery_sentinel_preexisting and not job.complete),+ )self._install_completed_event.set()self._install_queue.task_done()self._logger.info(f"Installer thread {threading.get_ident()} exiting")+ def _begin_install_transfer(self, job: ModelInstallJob) -> bool:+ with self._lock:+ if job._cancel_requested:+ return False+ if job._install_tmpdir is not None:+ self._claim_install_tmpdir(job)+ self._write_recovery_sentinel(job._install_tmpdir)+ job._install_tmpdir_recovery_sentinel_created = True+ if job._source_protection_root is not None and job._source_active_sentinel_created:+ if not self._has_recovery_sentinel(job._source_protection_root):+ self._write_recovery_sentinel(job._source_protection_root)+ job._source_recovery_sentinel_created = True+ job._install_phase = "transferring"+ return True+def _register_or_install(self, job: ModelInstallJob) -> None:+ with self._lock:+ if job._cancel_requested:+ job.cancel()+ cancel_before_start = True+ else:+ job._install_phase = "preflight"+ cancel_before_start = False+ if cancel_before_start:+ self._signal_job_cancelled(job)+ return++ # A restored completed download has no in-memory claim yet. Claim it before probing or+ # touching its marker so orphan cleanup cannot delete the staging tree concurrently.+ self._claim_install_tmpdir(job)++ if isinstance(job.source, LocalModelSource):+ source_root, active_sentinel_created, recovery_sentinel_preexisting = self._protect_managed_source_path(+ Path(job.source.path), allow_recovery=True+ )+ job._source_protection_root = source_root+ job._source_active_sentinel_created = active_sentinel_created+ job._source_recovery_sentinel_preexisting = recovery_sentinel_preexisting+if isinstance(job.source, ExternalModelSource):+ with self._lock:+ if job._cancel_requested:+ job.cancel()+ cancel_before_registering = True+ else:+ job._install_phase = "transferring"+ cancel_before_registering = False+ if cancel_before_registering:+ self._signal_job_cancelled(job)+ returnself._register_external_model(job)return# local jobs will be in waiting state, remote jobs will be downloading state@@ -1267,17 +1675,39 @@ class ModelInstallService(ModelInstallServiceBase):job.config_in.source_api_response = job.source_metadata.api_responseif job._install_tmpdir is not None:- if not job.inplace:- self._write_recovery_sentinel(job._install_tmpdir)self._delete_install_marker(job._install_tmpdir)if job.inplace:- key = self.register_path(job.local_path, job.config_in)+ with self._lock:+ if job._cancel_requested:+ job.cancel()+ cancel_before_start = True+ else:+ job._install_phase = "transferring"+ cancel_before_start = False+ if cancel_before_start:+ self._signal_job_cancelled(job)+ return+ key = self._register(job.local_path, job.config_in)else:try:- key = self.install_path(job.local_path, job.config_in)+ info = self._probe(Path(job.local_path), job.config_in) # type: ignore+ key = self._install_path_with_info(+ Path(job.local_path),+ job.config_in,+ info,+ before_transfer=lambda: self._begin_install_transfer(job),+ )+ except _InstallCancelledBeforeTransfer:+ with self._lock:+ job._install_phase = None+ job.cancel()+ self._signal_job_cancelled(job)+ returnexcept InstallRecoveryRequiredError:- job._recovery_required = job._install_tmpdir is not None+ job._recovery_required = job._install_tmpdir is not None or (+ job._source_protection_root is not None and self._has_recovery_sentinel(job._source_protection_root)+ )if job._recovery_required:try:self._write_install_marker(job, status=job.status)@@ -1387,6 +1817,9 @@ class ModelInstallService(ModelInstallServiceBase):(path / model.path).resolve() for model in self.record_store.all_models() if model.path}for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ if has_active_install_sentinel(tmpdir):+ self._logger.debug(f"Preserving active install directory {tmpdir}")+ continueresolved_tmpdir = tmpdir.resolve()if any(model_path == resolved_tmpdir or model_path.is_relative_to(resolved_tmpdir)@@ -1400,7 +1833,7 @@ class ModelInstallService(ModelInstallServiceBase):marker = self._read_install_marker(tmpdir)if marker is None:self._logger.info(f"Removing dangling temporary directory {tmpdir}")- self._safe_rmtree(tmpdir, self._logger)+ self._remove_unclaimed_install_tmpdir(tmpdir)continuestatus = marker.get("status")if marker.get("recovery_required") is True:@@ -1408,7 +1841,7 @@ class ModelInstallService(ModelInstallServiceBase):continueif status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:self._logger.info(f"Removing completed/errored temporary directory {tmpdir}")- self._safe_rmtree(tmpdir, self._logger)+ self._remove_unclaimed_install_tmpdir(tmpdir)def _scan_for_missing_models(self) -> list[AnyModelConfig]:"""Scan the models directory for missing models and return a list of them."""@@ -1652,62 +2085,113 @@ class ModelInstallService(ModelInstallServiceBase):clear_partials: bool = False,restarted_from_scratch: Optional[set[str]] = None,) -> ModelInstallJob:- job.source_metadata = metadata- job.local_path = destdir+ previous_source_metadata = job.source_metadata+ previous_status = job.status+ previous_local_path = job.local_path+ previous_install_tmpdir = job._install_tmpdir+ previous_total_bytes = job.total_bytes+ previous_multifile_job = job._multifile_job+ previous_download_parts = job.download_partsjob._install_tmpdir = destdir- job.total_bytes = sum((x.size or 0) for x in remote_files)+ claim_was_already_held = job._install_tmpdir_active_sentinel_created+ self._claim_install_tmpdir(job)- multifile_job = self._multifile_download(- remote_files=remote_files,- dest=destdir,- subfolder=subfolder,- subfolders=subfolders,- access_token=source.access_token,- submit_job=False, # Important! Don't submit the job until we have set our _download_cache dict- )- if clear_partials:- for part in multifile_job.download_parts:- target_path = part.dest- if target_path.exists():- try:- self._logger.info(f"Deleting partial file before restart: {target_path}")- target_path.unlink()- except Exception:- pass- in_progress_path = target_path.with_name(target_path.name + ".downloading")- if in_progress_path.exists():- try:- self._logger.info(f"Deleting partial file before restart: {in_progress_path}")- in_progress_path.unlink()- except Exception:- pass- if resume_metadata:- for part in multifile_job.download_parts:- meta = resume_metadata.get(str(part.source))- if not meta:- continue- part.canonical_url = meta.get("canonical_url") or part.canonical_url- part.etag = meta.get("etag") or part.etag- part.last_modified = meta.get("last_modified") or part.last_modified- part.expected_total_bytes = meta.get("expected_total_bytes") or part.expected_total_bytes- part.final_url = meta.get("final_url") or part.final_url- if meta.get("download_path"):- part.download_path = Path(meta.get("download_path"))- if restarted_from_scratch:- for part in multifile_job.download_parts:- if str(part.source) in restarted_from_scratch:- part.resume_from_scratch = True- part.resume_message = "Partial file missing. Restarted download from the beginning."- with self._lock:- self._download_cache[multifile_job.id] = job- job._multifile_job = multifile_job- job.download_parts = multifile_job.download_parts+ multifile_job: Optional[MultiFileDownloadJob] = None+ try:+ multifile_job = self._multifile_download(+ remote_files=remote_files,+ dest=destdir,+ subfolder=subfolder,+ subfolders=subfolders,+ access_token=source.access_token,+ submit_job=False, # Important! Don't submit the job until we have set our _download_cache dict+ )+ if resume_metadata:+ for part in multifile_job.download_parts:+ meta = resume_metadata.get(str(part.source))+ if not meta:+ continue+ part.canonical_url = meta.get("canonical_url") or part.canonical_url+ part.etag = meta.get("etag") or part.etag+ part.last_modified = meta.get("last_modified") or part.last_modified+ part.expected_total_bytes = meta.get("expected_total_bytes") or part.expected_total_bytes+ part.final_url = meta.get("final_url") or part.final_url+ if meta.get("download_path"):+ part.download_path = Path(meta.get("download_path"))+ if restarted_from_scratch:+ for part in multifile_job.download_parts:+ if str(part.source) in restarted_from_scratch:+ part.resume_from_scratch = True+ part.resume_message = "Partial file missing. Restarted download from the beginning."+ with self._lock:+ if self._stop_event.is_set():+ raise InstallDownloadConflictError(+ "The model install service is stopping; the download was not submitted."+ )+ if job.cancelled or job.paused:+ raise InstallDownloadConflictError(+ "The install changed state before the download could be submitted; retry the operation."+ )+ if clear_partials:+ for part in multifile_job.download_parts:+ target_path = part.dest+ if target_path.exists():+ try:+ self._logger.info(f"Deleting partial file before restart: {target_path}")+ target_path.unlink()+ except Exception:+ pass+ in_progress_path = target_path.with_name(target_path.name + ".downloading")+ if in_progress_path.exists():+ try:+ self._logger.info(f"Deleting partial file before restart: {in_progress_path}")+ in_progress_path.unlink()+ except Exception:+ pass+ job.source_metadata = metadata+ job.local_path = destdir+ job._install_tmpdir = destdir+ job.total_bytes = sum((x.size or 0) for x in remote_files)+ job._multifile_job = multifile_job+ job.download_parts = multifile_job.download_parts+ job.status = InstallStatus.WAITING+ self._write_install_marker(job, status=InstallStatus.WAITING)+ self._download_cache[multifile_job.id] = job+ except BaseException:+ with self._lock:+ if multifile_job is not None:+ if self._download_cache.get(multifile_job.id) is job:+ self._download_cache.pop(multifile_job.id, None)+ job.source_metadata = previous_source_metadata+ job.status = previous_status+ job.local_path = previous_local_path+ job._install_tmpdir = previous_install_tmpdir+ job.total_bytes = previous_total_bytes+ job._multifile_job = previous_multifile_job+ job.download_parts = previous_download_parts+ if not claim_was_already_held:+ self._release_install_tmpdir_claim(job)+ raise- self._write_install_marker(job, status=InstallStatus.WAITING)files_string = "file" if len(remote_files) == 1 else "files"self._logger.info(f"Queueing model install: {source} ({len(remote_files)} {files_string})")self._logger.debug(f"remote_files={remote_files}")- self._download_queue.submit_multifile_download(multifile_job)+ try:+ self._download_queue.submit_multifile_download(multifile_job)+ except BaseException:+ with self._lock:+ if self._download_cache.get(multifile_job.id) is job:+ self._download_cache.pop(multifile_job.id, None)+ job.source_metadata = previous_source_metadata+ job.status = previous_status+ job.local_path = previous_local_path+ job._install_tmpdir = previous_install_tmpdir+ job.total_bytes = previous_total_bytes+ job._multifile_job = previous_multifile_job+ job.download_parts = previous_download_parts+ if not claim_was_already_held:+ self._release_install_tmpdir_claim(job)+ raisereturn jobdef _stat_size(self, path: Path) -> int:@@ -1816,6 +2300,8 @@ class ModelInstallService(ModelInstallServiceBase):def _download_started_callback(self, download_job: MultiFileDownloadJob) -> None:with self._lock:if install_job := self._download_cache.get(download_job.id, None):+ if install_job.cancelled or install_job.paused:+ returninstall_job.status = InstallStatus.DOWNLOADINGif install_job.local_path == install_job._install_tmpdir: # first time@@ -1842,47 +2328,92 @@ class ModelInstallService(ModelInstallServiceBase):self._signal_job_downloading(install_job)def _download_complete_callback(self, download_job: MultiFileDownloadJob) -> None:+ install_job: Optional[ModelInstallJob] = None+ queued = Falsewith self._lock:if install_job := self._download_cache.pop(download_job.id, None):- self._signal_job_downloads_done(install_job)- self._put_in_queue(install_job) # this starts the installation and registration-- # Let other threads know that the number of downloads has changed+ if install_job.cancelled:+ self._cleanup_cancelled_install(install_job)+ elif install_job.paused:+ # A pause requested before this callback must not turn into an automatic install.+ self._write_install_marker(install_job, status=InstallStatus.PAUSED)+ if self._stop_event.is_set():+ self._release_install_tmpdir_claim(install_job)+ else:+ self._signal_job_downloads_done(install_job)+ if self._stop_event.is_set():+ # Every part is complete, so the staging tree is safe to recover without this process's claim.+ self._release_install_tmpdir_claim(install_job)+ queued = True+ else:+ queued = self._queue_install_job_locked(install_job)+ if install_job is not None:self._downloads_changed_event.set()+ if install_job is not None:+ if not queued and not install_job.cancelled and not install_job.paused:+ self.cancel_job(install_job)+ # Let other threads know that the number of downloads has changed.+ self._downloads_changed_event.set()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):assert excp is not None- self._set_error(install_job, excp)- self._download_queue.cancel_job(download_job)- if install_job._install_tmpdir is not None and not self._has_recovery_sentinel(- install_job._install_tmpdir- ):- self._safe_rmtree(install_job._install_tmpdir, self._logger)+ if install_job.cancelled:+ self._cleanup_cancelled_install(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._release_install_tmpdir_claim(install_job)+ else:+ self._set_error(install_job, excp)+ self._download_queue.cancel_job(download_job)+ if install_job._install_tmpdir is not None and not install_job._install_tmpdir_claim_conflict:+ if not self._has_recovery_sentinel(install_job._install_tmpdir):+ self._safe_rmtree(install_job._install_tmpdir, self._logger)+ self._release_install_tmpdir_claim(install_job)# Let other threads know that the number of downloads has changedself._downloads_changed_event.set()+ def _cleanup_cancelled_install(self, install_job: ModelInstallJob) -> None:+ """Remove cancelled staging only after its download callback has stopped using it."""+ if install_job._install_tmpdir is None or install_job._install_tmpdir_claim_conflict:+ return+ if not self._has_recovery_sentinel(install_job._install_tmpdir):+ self._write_install_marker(install_job, status=InstallStatus.CANCELLED)+ self._delete_install_marker(install_job._install_tmpdir)+ self._safe_rmtree(install_job._install_tmpdir, self._logger)+ self._release_install_tmpdir_claim(install_job)+def _download_cancelled_callback(self, download_job: MultiFileDownloadJob) -> None:with self._lock:if install_job := self._download_cache.pop(download_job.id, None):self._downloads_changed_event.set()- if any(part.resume_required for part in download_job.download_parts):+ if install_job.cancelled:+ self._cleanup_cancelled_install(install_job)+ return+ if install_job.paused or any(part.resume_required for part in download_job.download_parts):install_job.status = InstallStatus.PAUSEDself._write_install_marker(install_job, status=InstallStatus.PAUSED)+ # 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():+ self._release_install_tmpdir_claim(install_job)self._downloads_changed_event.set()return# if install job has already registered an error, then do not replace its status with cancelledif not install_job.errored and not install_job.paused:install_job.cancel()- if install_job._install_tmpdir is not None and not self._has_recovery_sentinel(- install_job._install_tmpdir- ):+ if install_job._install_tmpdir is not None and not install_job._install_tmpdir_claim_conflict:# Mark cancelled before cleanup so we don't reuse the folder if deletion fails.- self._write_install_marker(install_job, status=InstallStatus.CANCELLED)- self._delete_install_marker(install_job._install_tmpdir)- self._safe_rmtree(install_job._install_tmpdir, self._logger)+ if not self._has_recovery_sentinel(install_job._install_tmpdir):+ self._write_install_marker(install_job, status=InstallStatus.CANCELLED)+ self._delete_install_marker(install_job._install_tmpdir)+ self._safe_rmtree(install_job._install_tmpdir, self._logger)+ if not install_job._install_tmpdir_claim_conflict:+ self._release_install_tmpdir_claim(install_job)# Let other threads know that the number of downloads has changedself._downloads_changed_event.set()@@ -1933,7 +2464,7 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_errored(self, job: ModelInstallJob) -> None:self._logger.error(f"Model install error: {job.source}\n{job.error_type}: {job.error}")- if job._install_tmpdir is not None:+ if job._install_tmpdir is not None and not job._install_tmpdir_claim_conflict:self._delete_install_marker(job._install_tmpdir)if self._event_bus:assert job.error_type is not Nonediff --git a/invokeai/app/services/orphaned_models/orphaned_models_service.py b/invokeai/app/services/orphaned_models/orphaned_models_service.pyindex 79d9dcfcde..d454c9b001 100644--- a/invokeai/app/services/orphaned_models/orphaned_models_service.py+++ b/invokeai/app/services/orphaned_models/orphaned_models_service.py@@ -13,7 +13,10 @@ from pydantic import BaseModel, Fieldfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.model_install.model_install_common import (+ INSTALL_ACTIVE_SENTINEL,INSTALL_RECOVERY_SENTINEL,+ create_active_install_sentinel,+ delete_active_install_sentinel,is_recovery_protected_path,)from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase@@ -174,20 +177,33 @@ class OrphanedModelsService:continueif self._is_recovery_protected(full_path, models_path):- results[rel_path] = "error: path is reserved for install recovery"+ results[rel_path] = "error: path is reserved by an active install or install recovery"continueif self._contains_recovery_sentinel(full_path):results[rel_path] = "error: path contains install recovery data"continue+ if self._contains_active_install_sentinel(full_path):+ results[rel_path] = "error: path is reserved by an active install or install recovery"+ continue+if not full_path.exists():results[rel_path] = "error: path does not exist"continue- # Delete the directory- shutil.rmtree(full_path)- results[rel_path] = "deleted"+ claim_root = models_path / full_path.relative_to(models_path).parts[0]+ # Claim deletion atomically so a local install cannot start using this source after the marker check.+ try:+ create_active_install_sentinel(claim_root)+ except FileExistsError:+ results[rel_path] = "error: path is reserved by an active install or install recovery"+ continue+ try:+ shutil.rmtree(full_path)+ results[rel_path] = "deleted"+ finally:+ delete_active_install_sentinel(claim_root)except Exception as e:results[rel_path] = f"error: {str(e)}"@@ -202,6 +218,10 @@ class OrphanedModelsService:def _contains_recovery_sentinel(path: Path) -> bool:return path.is_dir() and any(path.rglob(f"*{INSTALL_RECOVERY_SENTINEL}"))+ @staticmethod+ def _contains_active_install_sentinel(path: Path) -> bool:+ return path.is_dir() and any(path.rglob(f"*{INSTALL_ACTIVE_SENTINEL}"))+def _get_registered_model_directories(self, models_dir: Path) -> Set[Path]:"""Get the set of all model directories from the database."""model_directories = set()diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex c23f10e0d9..a59a820f47 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -4514,7 +4514,7 @@"description": "No such job"},"409": {- "description": "The job has recovery data that must be preserved"+ "description": "The job cannot be cancelled safely in its current state"},"422": {"description": "Validation Error",@@ -4564,6 +4564,9 @@}}},+ "409": {+ "description": "The job cannot be paused in its current state"+ },"415": {"description": "No such job"},@@ -4615,6 +4618,9 @@}}},+ "409": {+ "description": "A previous download still owns the staging directory"+ },"415": {"description": "No such job"},@@ -4667,7 +4673,7 @@}},"409": {- "description": "The job has recovery data that must be preserved"+ "description": "A prior download is active or recovery data must be preserved"},"415": {"description": "No such job"@@ -4735,7 +4741,7 @@}},"409": {- "description": "The job has recovery data that must be preserved"+ "description": "A prior download is active or recovery data must be preserved"},"415": {"description": "No such job"diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 043db56d15..2757d223f9 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -53414,7 +53414,7 @@ export interface operations {"application/json": unknown;};};- /** @description The job has recovery data that must be preserved */+ /** @description The job cannot be cancelled safely in its current state */409: {headers: {[name: string]: unknown;@@ -53460,6 +53460,13 @@ export interface operations {"application/json": components["schemas"]["ModelInstallJob"];};};+ /** @description The job cannot be paused in its current state */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description No such job */415: {headers: {@@ -53499,6 +53506,13 @@ export interface operations {"application/json": components["schemas"]["ModelInstallJob"];};};+ /** @description A previous download still owns the staging directory */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description No such job */415: {headers: {@@ -53538,7 +53552,7 @@ export interface operations {"application/json": components["schemas"]["ModelInstallJob"];};};- /** @description The job has recovery data that must be preserved */+ /** @description A prior download is active or recovery data must be preserved */409: {headers: {[name: string]: unknown;@@ -53588,7 +53602,7 @@ export interface operations {"application/json": components["schemas"]["ModelInstallJob"];};};- /** @description The job has recovery data that must be preserved */+ /** @description A prior download is active or recovery data must be preserved */409: {headers: {[name: string]: unknown;diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex 59ea28cda8..b0b790607b 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -577,6 +577,56 @@ def test_restart_recovery_required_install_returns_conflict(monkeypatch: Any, opassert "requires recovery" in exc_info.value.detail[email protected]("operation", ["cancel", "pause", "resume", "restart_failed", "restart_file"])+def test_remote_download_replacement_returns_conflict(monkeypatch: Any, operation: str) -> None:+ from types import SimpleNamespace++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.app.services.model_install.model_install_common import InstallDownloadConflictError++ class Installer:+ def get_job_by_id(self, job_id: int) -> object:+ assert job_id == 42+ return object()++ def resume_job(self, _job: object) -> None:+ raise InstallDownloadConflictError("A previous download is still active")++ def pause_job(self, _job: object) -> None:+ raise InstallDownloadConflictError("A previous download is still active")++ def cancel_job(self, _job: object) -> None:+ raise InstallDownloadConflictError("A previous download is still active")++ def restart_failed(self, _job: object) -> None:+ raise InstallDownloadConflictError("A previous download is still active")++ def restart_file(self, _job: object, _source: str) -> None:+ raise InstallDownloadConflictError("A previous download is still active")++ 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 == "cancel":+ model_manager_router.cancel_model_install_job(current_admin=None, id=42)+ elif operation == "resume":+ model_manager_router.resume_model_install_job(current_admin=None, id=42)+ elif operation == "pause":+ model_manager_router.pause_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 "previous download" in exc_info.value.detail++@pytest.mark.parametrize("install_fails", [False, True])def test_conversion_cleans_scratch_after_success_and_ordinary_failure(monkeypatch: Any, tmp_path: Path, install_fails: bool@@ -697,6 +747,32 @@ def test_cancel_recovery_required_install_returns_conflict(monkeypatch: Any) ->assert "requires recovery" in exc_info.value.detail+def test_cancel_active_install_returns_conflict(monkeypatch: Any) -> None:+ from types import SimpleNamespace++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.app.services.model_install.model_install_common import InstallCancellationConflictError++ class Installer:+ def get_job_by_id(self, job_id: int) -> object:+ assert job_id == 43+ return object()++ def cancel_job(self, _job: object) -> None:+ raise InstallCancellationConflictError("Cannot cancel while install files are being moved")++ services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))++ with pytest.raises(HTTPException) as exc_info:+ model_manager_router.cancel_model_install_job(current_admin=None, id=43)++ assert exc_info.value.status_code == 409+ assert "being moved" in exc_info.value.detail++def test_delete_is_refused_while_the_same_model_is_being_converted() -> None:"""A delete landing mid-conversion must not pull the source out from under it.diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.pyindex 95b8409cb5..928308c3da 100644--- a/tests/app/routers/test_update_model_record_cache_invalidation.py+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py@@ -52,6 +52,14 @@ def test_missing_default_settings_is_handled():assert _load_settings_changed(no_settings, _config(fp8=True)) is True+def test_default_generation_steps_change_does_not_invalidate_model_cache():+ """Generation defaults are read per invocation, not baked into the loaded model module."""+ previous = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=20))+ updated = SimpleNamespace(cpu_only=None, default_settings=SimpleNamespace(fp8_storage=None, steps=40))++ assert _load_settings_changed(previous, updated) is False++@pytest.mark.parametrize("field", ["fp8_storage", "cpu_only"])def test_pydantic_nested_load_setting_changes_trigger_invalidation(field: str) -> None:from pydantic import BaseModel@@ -75,15 +83,33 @@ def test_unrelated_field_does_not_trigger_invalidation():assert _load_settings_changed(bare_a, bare_b) is False[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant"])[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant", "hash", "file_size"])def test_model_identity_changes_trigger_invalidation(field: str):- """Fields exposed by ModelRecordChanges can change the module selected or its source path."""+ """Loader identity or changed on-disk content must evict a module loaded from the previous record."""previous = _config(**{field: "old"})updated = _config(**{field: "new"})assert _load_settings_changed(previous, updated) is True[email protected]("field", ["path", "base", "type", "format", "variant", "repo_variant", "name", "description"])+ "field",+ [+ "path",+ "base",+ "type",+ "format",+ "variant",+ "repo_variant",+ "name",+ "description",+ "cover_image",+ "source",+ "source_type",+ "source_api_response",+ "source_url",+ "trigger_phrases",+ ],+)def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkeypatch: pytest.MonkeyPatch):previous = _config(**{field: "old"})updated = _config(**{field: "new"})@@ -112,12 +138,58 @@ def test_update_only_evicts_caches_for_load_affecting_changes(field: str, monkeyassert result is updatedfor cache in (cache_a, cache_b):- if field in {"name", "description"}:+ if field in {+ "name",+ "description",+ "cover_image",+ "source",+ "source_type",+ "source_api_response",+ "source_url",+ "trigger_phrases",+ }:cache.drop_model.assert_not_called()else:cache.drop_model.assert_called_once_with("model-key")+def test_cache_invalidation_holds_model_load_write_lock(monkeypatch: pytest.MonkeyPatch) -> None:+ from contextlib import contextmanager++ previous = _config(path="old")+ updated = _config(path="new")+ inside_write_lock = False+ observed_drop_under_lock: list[bool] = []++ class TrackingModelLoadLock:+ @contextmanager+ def write_lock(self):+ nonlocal inside_write_lock+ inside_write_lock = True+ try:+ yield+ finally:+ inside_write_lock = False++ def drop_model(_key: str) -> int:+ observed_drop_under_lock.append(inside_write_lock)+ return 1++ cache = SimpleNamespace(drop_model=drop_model)+ services = SimpleNamespace(+ logger=MagicMock(),+ model_manager=SimpleNamespace(load=SimpleNamespace(ram_caches={"cpu": cache})),+ )+ monkeypatch.setattr(model_manager_router, "MODEL_LOAD_LOCK", TrackingModelLoadLock())+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )++ model_manager_router._invalidate_model_load_caches("model-key", previous, updated)++ assert observed_drop_under_lock == [True]++@pytest.mark.parametrize(("field", "expected_eviction"), [("path", True), ("name", False), ("description", False)])def test_record_update_handles_real_cpu_cache_entries(field: str, expected_eviction: bool, monkeypatch: pytest.MonkeyPatchdiff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.pyindex fe72bd745b..2a71453769 100644--- a/tests/app/services/download/test_download_queue.py+++ b/tests/app/services/download/test_download_queue.py@@ -734,3 +734,131 @@ def test_content_disposition_filename_must_be_one_safe_component(filename: str)"""The remote server picks this name; it must never be able to leave `dest`."""queue = DownloadQueueService()assert queue._validate_filename("/tmp", filename) is False++[email protected](timeout=10, method="thread")+def test_multifile_cancel_callback_runs_after_partial_cleanup(tmp_path: Path, monkeypatch: Any) -> None:+ import threading++ from invokeai.app.services.download.download_base import DownloadJobCancelledException++ queue = DownloadQueueService(max_parallel_dl=1)+ download_started = threading.Event()+ release_download = threading.Event()+ in_progress = tmp_path / "model.safetensors.downloading"+ callback_saw_partial: list[bool] = []++ def fake_download(job: DownloadJob) -> None:+ job.download_path = job.dest+ in_progress.write_bytes(b"partial")+ queue._signal_job_started(job)+ download_started.set()+ assert release_download.wait(timeout=5)+ raise DownloadJobCancelledException("cancelled for test")++ monkeypatch.setattr(queue, "_do_download", fake_download)+ queue.start()+ try:+ job = queue.multifile_download(+ parts=[RemoteModelFile(url="https://example.com/model.safetensors", path=Path("model.safetensors"))],+ dest=tmp_path,+ on_cancelled=lambda _job: callback_saw_partial.append(in_progress.exists()),+ )+ assert download_started.wait(timeout=5)+ queue.cancel_job(job)+ part_cancelled = next(iter(job.download_parts)).cancelled+ release_download.set()+ queue.join()+ finally:+ queue.stop()++ assert part_cancelled+ assert callback_saw_partial == [False]+ assert job.status == DownloadJobStatus.CANCELLED++[email protected](timeout=10, method="thread")+def test_stop_notifies_paused_queued_multifile_download(tmp_path: Path, monkeypatch: Any) -> None:+ import threading++ from invokeai.app.services.download.download_base import DownloadJobCancelledException++ queue = DownloadQueueService(max_parallel_dl=1)+ blocker_started = threading.Event()+ pause_callback_statuses: list[DownloadJobStatus] = []++ def fake_download(job: DownloadJob) -> None:+ queue._signal_job_started(job)+ blocker_started.set()+ while not job.cancelled:+ time.sleep(0.005)+ raise DownloadJobCancelledException("cancelled for test")++ monkeypatch.setattr(queue, "_do_download", fake_download)+ queue.start()+ try:+ queue.download(source=AnyHttpUrl("https://example.com/blocker"), dest=tmp_path / "blocker")+ assert blocker_started.wait(timeout=5)+ job = queue.multifile_download(+ parts=[RemoteModelFile(url="https://example.com/model.safetensors", path=Path("model.safetensors"))],+ dest=tmp_path / "staging",+ on_cancelled=lambda paused_job: pause_callback_statuses.append(paused_job.status),+ )+ part = next(iter(job.download_parts))+ queue.pause_job(part)+ queue.stop()+ finally:+ queue.stop()++ assert job.status == DownloadJobStatus.PAUSED+ assert pause_callback_statuses == [DownloadJobStatus.PAUSED]++[email protected](timeout=10, method="thread")+def test_stop_pauses_multifile_download_after_current_part_completes(tmp_path: Path, monkeypatch: Any) -> None:+ import threading++ queue = DownloadQueueService(max_parallel_dl=1)+ part_started = threading.Event()+ release_part = threading.Event()+ callback_statuses: list[DownloadJobStatus] = []++ def fake_download(job: DownloadJob) -> None:+ job.download_path = job.dest+ queue._signal_job_started(job)+ part_started.set()+ assert release_part.wait(timeout=5)+ job.dest.parent.mkdir(parents=True, exist_ok=True)+ job.dest.write_bytes(b"complete part")++ monkeypatch.setattr(queue, "_do_download", fake_download)+ queue.start()+ stop_thread: threading.Thread | None = None+ try:+ job = queue.multifile_download(+ parts=[+ RemoteModelFile(url="https://example.com/part-1", path=Path("model/part-1")),+ RemoteModelFile(url="https://example.com/part-2", path=Path("model/part-2")),+ ],+ dest=tmp_path / "staging",+ on_cancelled=lambda paused_job: callback_statuses.append(paused_job.status),+ )+ parts = {str(part.source): part for part in job.download_parts}+ assert part_started.wait(timeout=5)+ for part in parts.values():+ queue.pause_job(part)++ stop_thread = threading.Thread(target=queue.stop)+ stop_thread.start()+ assert queue._stop_event.wait(timeout=5)+ release_part.set()+ stop_thread.join(timeout=5)+ finally:+ release_part.set()+ if stop_thread is not None:+ stop_thread.join(timeout=5)+ queue.stop()++ assert stop_thread is not None and not stop_thread.is_alive()+ assert job.status == DownloadJobStatus.PAUSED+ assert callback_statuses == [DownloadJobStatus.PAUSED]diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex b5ff2e25d7..6cf8b82669 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -20,7 +20,7 @@ import pytestfrom pydantic_core import Urlfrom invokeai.app.services.config import InvokeAIAppConfig-from invokeai.app.services.download import DownloadJob, MultiFileDownloadJob+from invokeai.app.services.download import DownloadJob, DownloadJobStatus, MultiFileDownloadJobfrom invokeai.app.services.events.events_base import EventServiceBasefrom invokeai.app.services.events.events_common import (ModelInstallCompleteEvent,@@ -38,12 +38,17 @@ from invokeai.app.services.model_install import ()from invokeai.app.services.model_install.model_install_common import (INSTALL_RECOVERY_SENTINEL,+ InstallCancellationConflictError,+ InstallDownloadConflictError,InstallRecoveryRequiredError,InstallStatus,InvalidModelConfigException,LocalModelSource,ModelInstallJob,URLModelSource,+ active_install_sentinel_path,+ create_active_install_sentinel,+ has_active_install_sentinel,)from invokeai.app.services.model_install.model_install_default import (INSTALL_MARKER_FILENAME,@@ -106,8 +111,9 @@ def test_registration_meta_override_succeed(mm2_installer: ModelInstallServiceBaassert model_record.key == "xyzzy"[email protected](("setting", "value"), [("fp8_storage", True), ("steps", 37)])def test_registration_keeps_the_default_settings_sent_with_the_install(- mm2_installer: ModelInstallServiceBase, tmp_path: Path+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, setting: str, value: bool | int) -> None:"""Identification computes a model's default settings; the ones a user picked while installing must survive it."""import torch@@ -119,11 +125,11 @@ def test_registration_keeps_the_default_settings_sent_with_the_install(str(checkpoint),)- key = mm2_installer.register_path(checkpoint, ModelRecordChanges(default_settings={"fp8_storage": True}))+ key = mm2_installer.register_path(checkpoint, ModelRecordChanges(default_settings={setting: value}))record = mm2_installer.record_store.get_model(key)assert record.default_settings is not None- assert record.default_settings.fp8_storage is True+ assert getattr(record.default_settings, setting) == valuedef test_install(@@ -137,6 +143,22 @@ def test_install(assert model_record.source == embedding_file.as_posix()+def test_retain_recovery_destination_does_not_log_when_sentinel_already_exists(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ dest_dir = tmp_path / "model"+ dest_dir.mkdir()+ installer._write_recovery_sentinel(dest_dir)++ with caplog.at_level("ERROR"):+ installer._retain_recovery_destination(dest_dir)++ assert installer._has_recovery_sentinel(dest_dir)+ assert not any("Failed to persist destination recovery sentinel" in record.message for record in caplog.records)++def test_file_install_retries_copy_then_unlink_permission_error(mm2_installer: ModelInstallServiceBase,embedding_file: Path,@@ -173,7 +195,10 @@ def test_destination_is_hidden_from_orphan_cleanup_during_install(mm2_app_config: InvokeAIAppConfig,monkeypatch: pytest.MonkeyPatch,) -> None:- from invokeai.app.services.model_install.model_install_common import has_recovery_sentinel+ from invokeai.app.services.model_install.model_install_common import (+ has_active_install_sentinel,+ has_recovery_sentinel,+ )from invokeai.app.services.orphaned_models import OrphanedModelsServiceorphan_service = OrphanedModelsService(config=mm2_app_config, db=mm2_installer.record_store._db)@@ -183,6 +208,7 @@ def test_destination_is_hidden_from_orphan_cleanup_during_install(def move_then_scan(src: Path, dst: Path):result = real_move(src, dst)destination_root = dst.parent+ assert has_active_install_sentinel(destination_root)orphan_keys = {orphan.path for orphan in orphan_service.find_orphaned_models()}observations.append((destination_root.name, has_recovery_sentinel(destination_root), orphan_keys))return result@@ -198,6 +224,146 @@ def test_destination_is_hidden_from_orphan_cleanup_during_install(assert not has_recovery_sentinel(mm2_app_config.models_path / destination_key)+def test_managed_local_source_is_hidden_from_orphan_cleanup_during_install(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import (+ has_active_install_sentinel,+ has_recovery_sentinel,+ )+ from invokeai.app.services.orphaned_models import OrphanedModelsService++ source_root = mm2_app_config.models_path / f"local-source-{uuid.uuid4().hex}"+ shutil.copytree(diffusers_dir, source_root)+ orphan_service = OrphanedModelsService(config=mm2_app_config, db=mm2_installer.record_store._db)+ observations: list[tuple[bool, set[str], str]] = []+ real_probe = mm2_installer._probe+ real_move_with_retries = mm2_installer._move_with_retries++ def observe_source_during_operation(path: Path, config: ModelRecordChanges):+ assert path == source_root+ protected = has_active_install_sentinel(source_root)+ orphan_keys = {orphan.path for orphan in orphan_service.find_orphaned_models()}+ delete_result = orphan_service.delete_orphaned_models([source_root.name])[source_root.name]+ observations.append((protected, orphan_keys, delete_result))+ return real_probe(path, config)++ def observe_source_during_transfer(src: Path, dst: Path) -> None:+ assert has_active_install_sentinel(source_root)+ real_move_with_retries(src, dst)++ monkeypatch.setattr(mm2_installer, "_probe", observe_source_during_operation)+ monkeypatch.setattr(mm2_installer, "_move_with_retries", observe_source_during_transfer)++ job = mm2_installer.import_model(LocalModelSource(path=source_root, inplace=False))+ assert job is not None+ mm2_installer.wait_for_installs()++ assert observations+ assert observations[0][0]+ assert source_root.name not in observations[0][1]+ assert observations[0][2] == "error: path is reserved by an active install or install recovery"+ assert job.complete+ assert job.config_out is not None+ assert mm2_installer.record_store.get_model(job.config_out.key)+ assert not has_active_install_sentinel(source_root)+ assert not has_recovery_sentinel(source_root)+++def test_orphan_delete_claim_prevents_a_local_install_from_starting(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import has_active_install_sentinel+ from invokeai.app.services.orphaned_models import OrphanedModelsService, orphaned_models_service++ source_root = mm2_app_config.models_path / f"local-source-{uuid.uuid4().hex}"+ shutil.copytree(diffusers_dir, source_root)+ orphan_service = OrphanedModelsService(config=mm2_app_config, db=mm2_installer.record_store._db)+ real_rmtree = orphaned_models_service.shutil.rmtree+ deletion_claimed = threading.Event()+ release_deletion = threading.Event()+ results: dict[str, str] = {}++ def blocked_rmtree(path: Path) -> None:+ deletion_claimed.set()+ assert release_deletion.wait(timeout=5)+ real_rmtree(path)++ monkeypatch.setattr(orphaned_models_service.shutil, "rmtree", blocked_rmtree)+ delete_thread = threading.Thread(+ target=lambda: results.update(orphan_service.delete_orphaned_models([source_root.name]))+ )+ delete_thread.start()+ try:+ assert deletion_claimed.wait(timeout=5)+ assert has_active_install_sentinel(source_root)+ with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):+ mm2_installer.install_path(source_root)+ assert source_root.exists()+ finally:+ release_deletion.set()+ delete_thread.join(timeout=10)++ assert not delete_thread.is_alive()+ assert results[source_root.name] == "deleted"+ assert not source_root.exists()+++def test_start_removes_stale_but_preserves_live_install_claims(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ from invokeai.app.services.model_install.model_install_common import (+ active_install_sentinel_path,+ create_active_install_sentinel,+ )++ assert isinstance(mm2_installer, ModelInstallService)+ stale_root = mm2_app_config.models_path / "stale-claim"+ live_root = mm2_app_config.models_path / "live-claim"+ stale_root.mkdir()+ live_root.mkdir()+ stale_claim = active_install_sentinel_path(stale_root)+ stale_claim.write_text("2147483647 1.0\n", encoding="ascii")+ create_active_install_sentinel(live_root)++ mm2_installer._remove_stale_install_source_claims()++ assert not stale_claim.exists()+ assert active_install_sentinel_path(live_root).exists()+ from invokeai.app.services.model_install.model_install_common import delete_active_install_sentinel++ delete_active_install_sentinel(live_root)+++def test_startup_cleanup_preserves_claimed_remote_staging(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ from invokeai.app.services.model_install.model_install_common import (+ active_install_sentinel_path,+ create_active_install_sentinel,+ )++ assert isinstance(mm2_installer, ModelInstallService)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}live-download-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors.downloading"+ payload.write_bytes(b"partial download")+ create_active_install_sentinel(tmpdir)++ try:+ mm2_installer._remove_dangling_install_dirs()+ assert payload.read_bytes() == b"partial download"+ assert active_install_sentinel_path(tmpdir).exists()+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)++def test_unregistered_destination_remains_protected_after_registration_failure(mm2_installer: ModelInstallServiceBase,embedding_file: Path,@@ -551,12 +717,12 @@ def test_remote_install_recovery_survives_cleanup_and_restart(real_delete_install_marker = mm2_installer._delete_install_marker- def assert_recovery_before_marker_delete(tmpdir_arg: Path) -> None:- assert mm2_installer._has_recovery_sentinel(tmpdir_arg)+ def assert_recovery_state_before_marker_delete(tmpdir_arg: Path) -> None:+ assert mm2_installer._has_recovery_sentinel(tmpdir_arg) is job._recovery_requiredreal_delete_install_marker(tmpdir_arg)monkeypatch.setattr(mm2_installer, "_write_install_marker", fail_recovery_marker)- monkeypatch.setattr(mm2_installer, "_delete_install_marker", assert_recovery_before_marker_delete)+ monkeypatch.setattr(mm2_installer, "_delete_install_marker", assert_recovery_state_before_marker_delete)mm2_installer._put_in_queue(job)mm2_installer.wait_for_job(job, timeout=10)@@ -651,6 +817,170 @@ def test_cancel_recovery_sentinel_protects_data_before_job_flag_is_set(assert mm2_installer._has_recovery_sentinel(tmpdir)+def _queue_downloaded_job(+ installer: ModelInstallService,+ tmpdir: Path,+ job_id: int,+) -> ModelInstallJob:+ job = ModelInstallJob(+ id=job_id,+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ job._install_tmpdir = tmpdir+ installer._install_jobs.append(job)+ installer._install_queue.put(job)+ return job+++def test_service_stop_waits_for_active_install_without_cancelling_it(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ embedding_file: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}shutdown-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ shutil.copy2(embedding_file, tmpdir / embedding_file.name)+ job = _queue_downloaded_job(installer, tmpdir, 996)++ transfer_started = threading.Event()+ release_transfer = threading.Event()+ clear_started = threading.Event()+ stop_finished = threading.Event()+ stop_errors: list[BaseException] = []+ sentinel_during_transfer: list[bool] = []+ real_move_with_retries = installer._move_with_retries+ real_clear_pending_jobs = installer._clear_pending_jobs++ def blocked_move_with_retries(src: Path, dst: Path) -> None:+ sentinel_during_transfer.append(installer._has_recovery_sentinel(tmpdir))+ transfer_started.set()+ assert release_transfer.wait(timeout=5)+ real_move_with_retries(src, dst)++ def observed_clear_pending_jobs() -> None:+ clear_started.set()+ real_clear_pending_jobs()++ def stop_installer() -> None:+ try:+ installer.stop()+ except BaseException as e:+ stop_errors.append(e)+ finally:+ stop_finished.set()++ monkeypatch.setattr(installer, "_move_with_retries", blocked_move_with_retries)+ monkeypatch.setattr(installer, "_clear_pending_jobs", observed_clear_pending_jobs)+ stop_thread = threading.Thread(target=stop_installer)++ try:+ assert transfer_started.wait(timeout=5)+ stop_thread.start()+ assert not stop_finished.wait(timeout=0.05)+ assert not clear_started.is_set()+ finally:+ release_transfer.set()+ if stop_thread.ident is not None:+ stop_thread.join(timeout=10)++ assert not stop_thread.is_alive()+ assert not stop_errors+ assert installer._running is False+ assert job.complete+ assert sentinel_during_transfer == [True]+ assert not tmpdir.exists()+++def test_service_stop_does_not_delete_a_job_between_dequeue_and_worker_activation(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ embedding_file: Path,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}shutdown-dequeued-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ shutil.copy2(embedding_file, tmpdir / embedding_file.name)+ installer._lock.acquire()+ job = _queue_downloaded_job(installer, tmpdir, 998)+ stop_finished = threading.Event()+ stop_errors: list[BaseException] = []++ def stop_installer() -> None:+ try:+ installer.stop()+ except BaseException as e:+ stop_errors.append(e)+ finally:+ stop_finished.set()++ stop_thread = threading.Thread(target=stop_installer)++ try:+ deadline = time.monotonic() + 5+ while not installer._install_queue.empty() and time.monotonic() < deadline:+ time.sleep(0.01)+ assert installer._install_queue.empty()+ installer._stop_event.set()+ stop_thread.start()+ assert not stop_finished.wait(timeout=0.05)+ assert tmpdir.exists()+ assert (tmpdir / embedding_file.name).exists()+ finally:+ installer._lock.release()+ if stop_thread.ident is not None:+ stop_thread.join(timeout=10)++ assert not stop_thread.is_alive()+ assert not stop_errors+ assert stop_finished.is_set()+ assert job.cancelled+ assert not tmpdir.exists()+++def test_cancel_during_install_preflight_waits_for_probe_then_cleans_safely(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ embedding_file: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}cancel-preflight-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ shutil.copy2(embedding_file, tmpdir / embedding_file.name)+ job = _queue_downloaded_job(installer, tmpdir, 997)++ probe_started = threading.Event()+ release_probe = threading.Event()+ real_probe = installer._probe++ def blocked_probe(path: Path, config: ModelRecordChanges):+ probe_started.set()+ assert release_probe.wait(timeout=5)+ return real_probe(path, config)++ monkeypatch.setattr(installer, "_probe", blocked_probe)++ try:+ assert probe_started.wait(timeout=5)+ installer.cancel_job(job)+ assert tmpdir.exists()+ assert (tmpdir / embedding_file.name).exists()+ assert not installer._has_recovery_sentinel(tmpdir)+ finally:+ release_probe.set()++ assert installer.wait_for_job(job, timeout=10).cancelled+ assert not tmpdir.exists()++@pytest.mark.parametrize("operation", ["restart_failed", "restart_file"])def test_restart_refuses_recovery_sentinel(operation: str,@@ -730,6 +1060,23 @@ def test_registering_recovery_root_removes_its_sentinel(assert not sentinel.exists()+def test_installing_recovery_root_clears_source_sentinel_after_transfer(+ mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ recovery_root = mm2_app_config.models_path / "recovery-source"+ recovery_root.mkdir()+ shutil.copy2(embedding_file, recovery_root / embedding_file.name)+ sentinel = mm2_installer._recovery_sentinel_path(recovery_root)+ sentinel.write_text("preserve until transferred", encoding="utf-8")++ key = mm2_installer.install_path(recovery_root)++ assert mm2_installer.record_store.get_model(key).path == key+ assert (mm2_app_config.models_path / key / embedding_file.name).exists()+ assert not sentinel.exists()++def test_startup_scan_skips_recovery_protected_root(mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig) -> None:@@ -1049,12 +1396,13 @@ def test_wait_for_installs_waits_for_download_completion_to_enqueue_install(enqueue_started = threading.Event()release_enqueue = threading.Event()- def blocked_enqueue(install_job: ModelInstallJob) -> None:+ def blocked_enqueue(install_job: ModelInstallJob) -> bool:assert install_job is jobenqueue_started.set()assert release_enqueue.wait(timeout=2)+ return True- monkeypatch.setattr(mm2_installer, "_put_in_queue", blocked_enqueue)+ monkeypatch.setattr(mm2_installer, "_queue_install_job_locked", blocked_enqueue, raising=False)callback_thread = threading.Thread(target=mm2_installer._download_complete_callback,args=(SimpleNamespace(id=job.id),),@@ -1119,7 +1467,7 @@ def test_import_waits_for_startup_restore(return wait_for_restore()monkeypatch.setattr(installer, "_restore_incomplete_installs", _blocked_restore)- monkeypatch.setattr(installer, "_resume_remote_download", lambda job: None)+ monkeypatch.setattr(installer, "_resume_remote_download", lambda job, *, operation_reserved=False: None)try:assert not installer._restore_completed_event.is_set()@@ -1678,10 +2026,11 @@ def test_restore_paused_hf_install_preserves_access_token(assert restored_job.pausedassert isinstance(restored_job.source, HFModelSource)assert restored_job.source.access_token == access_token+ assert has_active_install_sentinel(tmpdir)captured: dict[str, str | None] = {}- def _capture_resume(job: ModelInstallJob) -> None:+ def _capture_resume(job: ModelInstallJob, *, operation_reserved: bool = False) -> None:assert isinstance(job.source, HFModelSource)captured["access_token"] = job.source.access_token@@ -1689,6 +2038,53 @@ def test_restore_paused_hf_install_preserves_access_token(restored_installer.resume_job(restored_job)assert captured["access_token"] == access_tokenfinally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_restore_claims_downloads_done_staging_before_queueing(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ mm2_download_queue,+ mm2_session,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-complete-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ staging_job = ModelInstallJob(+ id=99998,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ staging_job._install_tmpdir = tmpdir+ (tmpdir / "model.safetensors").write_bytes(b"downloaded model")+ mm2_installer._write_install_marker(staging_job, status=InstallStatus.DOWNLOADS_DONE)++ restored_installer = ModelInstallService(+ app_config=mm2_app_config,+ record_store=mm2_installer.record_store,+ download_queue=mm2_download_queue,+ session=mm2_session,+ )+ queued_jobs: list[ModelInstallJob] = []++ def capture_queued_job(job: ModelInstallJob) -> None:+ assert has_active_install_sentinel(tmpdir)+ queued_jobs.append(job)++ monkeypatch.setattr(restored_installer, "_put_in_queue", capture_queued_job)++ try:+ restored_installer._restore_incomplete_installs()+ assert len(queued_jobs) == 1+ assert queued_jobs[0].downloads_done+ assert queued_jobs[0]._install_tmpdir_active_sentinel_created+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -1740,6 +2136,1007 @@ def test_restart_failed_uses_parts_created_before_download_started(assert enqueue_remote_download.call_args.kwargs["clear_partials"] is True[email protected]("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+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}callback-recovery-{callback_name}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"recovery data")+ installer._write_recovery_sentinel(tmpdir)++ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ download_job = MultiFileDownloadJob(id=456, dest=tmpdir, download_parts={part})+ install_job = ModelInstallJob(+ id=456,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ install_job._install_tmpdir = tmpdir+ install_job._multifile_job = download_job+ installer._download_cache[download_job.id] = install_job+ monkeypatch.setattr(installer._download_queue, "cancel_job", MagicMock())++ if callback_name == "_download_error_callback":+ installer._download_error_callback(download_job, RuntimeError("download failed"))+ else:+ installer._download_cancelled_callback(download_job)++ assert installer._has_recovery_sentinel(tmpdir)+ assert payload.read_bytes() == b"recovery data"+++def test_download_completion_during_shutdown_preserves_staging_for_restore(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}shutdown-download-complete"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"downloaded model")++ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.status = DownloadJobStatus.COMPLETED+ download_job = MultiFileDownloadJob(id=457, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.COMPLETED+ install_job = ModelInstallJob(+ id=457,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ install_job._install_tmpdir = tmpdir+ install_job._multifile_job = download_job+ install_job._install_tmpdir_active_sentinel_created = True+ installer._install_jobs.append(install_job)+ installer._download_cache[download_job.id] = install_job+ create_active_install_sentinel(tmpdir)+ monkeypatch.setattr(installer._download_queue, "cancel_job", MagicMock())+ installer._stop_event.set()++ callback_errors: list[BaseException] = []+ callback_done = threading.Event()++ def complete_download() -> None:+ try:+ installer._download_complete_callback(download_job)+ except BaseException as e:+ callback_errors.append(e)+ finally:+ callback_done.set()++ callback_thread = threading.Thread(target=complete_download, daemon=True)+ callback_thread.start()+ callback_thread.join(timeout=2)++ try:+ assert callback_done.is_set(), "download completion deadlocked while cancelling during shutdown"+ assert not callback_thread.is_alive()+ assert not callback_errors+ assert install_job.downloads_done+ assert tmpdir.exists()+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == InstallStatus.DOWNLOADS_DONE.value+ assert not has_active_install_sentinel(tmpdir)+ finally:+ # A deadlocked daemon callback is expected to survive a failed assertion in the regression case; keep fixture+ # teardown from waiting on the same broken lock path.+ installer._running = False+ if installer._install_thread is not None:+ installer._install_thread.join(timeout=2)+++def test_stop_releases_claim_for_completed_downloads_waiting_to_install(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}shutdown-completed-download"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"downloaded model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.status = DownloadJobStatus.COMPLETED+ download_job = MultiFileDownloadJob(id=458, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.COMPLETED+ install_job = ModelInstallJob(+ id=458,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ install_job._install_tmpdir = tmpdir+ install_job._install_tmpdir_active_sentinel_created = True+ install_job._multifile_job = download_job+ installer._install_jobs.append(install_job)+ create_active_install_sentinel(tmpdir)++ installer.stop()++ try:+ assert install_job.downloads_done+ assert tmpdir.exists()+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == InstallStatus.DOWNLOADS_DONE.value+ assert not has_active_install_sentinel(tmpdir)+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_paused_remote_install_stays_hidden_from_orphan_cleanup(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ from invokeai.app.services.orphaned_models import OrphanedModelsService++ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}paused-install-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"paused model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.pause()+ part.status = DownloadJobStatus.PAUSED+ download_job = MultiFileDownloadJob(id=461, dest=tmpdir, download_parts={part})+ download_job.pause()+ download_job.status = DownloadJobStatus.PAUSED+ job = ModelInstallJob(+ id=461,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)+ orphan_service = OrphanedModelsService(config=mm2_app_config, db=installer.record_store._db)++ try:+ installer._download_cancelled_callback(download_job)++ assert has_active_install_sentinel(tmpdir)+ assert tmpdir.name not in {orphan.path for orphan in orphan_service.find_orphaned_models()}+ result = orphan_service.delete_orphaned_models([tmpdir.name])[tmpdir.name]+ assert "reserved" in result+ assert payload.exists()+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_cancel_active_remote_install_waits_for_download_queue_cleanup(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}cancel-active-download"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors.downloading"+ payload.write_bytes(b"partial download")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.RUNNING+ download_job = MultiFileDownloadJob(id=460, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.RUNNING+ job = ModelInstallJob(+ id=460,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)+ cancel_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "cancel_job", cancel_download)++ installer.cancel_job(job)++ try:+ assert cancel_download.call_args.args == (download_job,)+ assert tmpdir.exists()+ assert payload.exists()+ assert has_active_install_sentinel(tmpdir)+ assert installer._download_cache.get(download_job.id) is job++ # Cancellation may race an interrupted part being marked resumable by the queue.+ part.resume_required = True+ installer._download_cancelled_callback(download_job)++ assert job.cancelled+ assert not tmpdir.exists()+ assert not has_active_install_sentinel(tmpdir)+ assert download_job.id not in installer._download_cache+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)++[email protected]("terminal_callback", ["complete", "error"])+def test_cancel_waits_for_pending_terminal_download_callback(+ terminal_callback: str,+ mm2_installer: ModelInstallServiceBase,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}cancel-pending-{terminal_callback}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"downloaded model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.status = DownloadJobStatus.COMPLETED if terminal_callback == "complete" else DownloadJobStatus.ERROR+ download_job = MultiFileDownloadJob(id=4587, dest=tmpdir, download_parts={part})+ download_job.status = part.status+ job = ModelInstallJob(+ id=4587,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ job.download_parts = download_job.download_parts+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)+ cancel_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "cancel_job", cancel_download)++ try:+ installer.cancel_job(job)++ assert job.cancelled+ assert tmpdir.exists()+ assert payload.exists()+ assert has_active_install_sentinel(tmpdir)+ cancel_download.assert_called_once_with(download_job)++ if terminal_callback == "complete":+ installer._download_complete_callback(download_job)+ else:+ installer._download_error_callback(download_job, RuntimeError("late download error"))++ assert job.cancelled+ assert download_job.id not in installer._download_cache+ assert installer._install_queue.qsize() == 0+ assert not tmpdir.exists()+ assert not has_active_install_sentinel(tmpdir)+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)++[email protected]("terminal_callback", ["complete", "error"])+def test_pause_survives_pending_terminal_download_callback(+ terminal_callback: str,+ mm2_installer: ModelInstallServiceBase,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}pause-pending-{terminal_callback}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"downloaded model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.status = DownloadJobStatus.COMPLETED if terminal_callback == "complete" else DownloadJobStatus.ERROR+ download_job = MultiFileDownloadJob(id=4588, dest=tmpdir, download_parts={part})+ download_job.status = part.status+ job = ModelInstallJob(+ id=4588,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ job.download_parts = download_job.download_parts+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)+ monkeypatch.setattr(installer._download_queue, "pause_job", MagicMock())++ try:+ installer.pause_job(job)++ if terminal_callback == "complete":+ installer._download_complete_callback(download_job)+ else:+ installer._download_error_callback(download_job, RuntimeError("late download error"))++ assert job.paused+ assert download_job.id not in installer._download_cache+ assert installer._install_queue.qsize() == 0+ assert tmpdir.exists()+ assert payload.exists()+ assert has_active_install_sentinel(tmpdir)+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None and marker["status"] == InstallStatus.PAUSED.value+ finally:+ installer.cancel_job(job)+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_stop_preserves_staging_claim_until_download_pause_callback(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}shutdown-active-download"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.RUNNING+ download_job = MultiFileDownloadJob(id=459, dest=tmpdir, download_parts={part})+ job = ModelInstallJob(+ id=459,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)++ installer.stop()++ try:+ assert job.paused+ assert installer._download_cache.get(download_job.id) is job+ assert has_active_install_sentinel(tmpdir)++ installer._download_cancelled_callback(download_job)++ assert download_job.id not in installer._download_cache+ assert not has_active_install_sentinel(tmpdir)+ assert tmpdir.exists()+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+++def test_shutdown_releases_claim_when_pause_callback_already_ran(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}shutdown-after-pause-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.PAUSED+ download_job = MultiFileDownloadJob(id=4581, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.PAUSED+ job = ModelInstallJob(+ id=4581,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)++ try:+ # The pause callback proves the queue has stopped touching staging, but a live user-paused job+ # intentionally keeps its claim until shutdown.+ installer._download_cancelled_callback(download_job)+ assert download_job.id not in installer._download_cache+ assert has_active_install_sentinel(tmpdir)++ installer.stop()++ assert not has_active_install_sentinel(tmpdir)+ marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))+ assert marker["status"] == InstallStatus.PAUSED.value+ assert tmpdir.exists()+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_cancel_after_pause_callback_cleans_staging(mm2_installer: ModelInstallServiceBase, tmp_path: Path) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}cancel-after-pause"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors.downloading"+ payload.write_bytes(b"partial model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.PAUSED+ download_job = MultiFileDownloadJob(id=4583, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.PAUSED+ job = ModelInstallJob(+ id=4583,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)++ try:+ installer._download_cancelled_callback(download_job)+ assert has_active_install_sentinel(tmpdir)++ installer.cancel_job(job)++ assert job.cancelled+ assert not tmpdir.exists()+ assert not has_active_install_sentinel(tmpdir)+ finally:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)++[email protected]("operation", ["resume", "restart_failed", "restart_file"])+def test_remote_download_replacement_waits_for_previous_callback(+ operation: str,+ 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"))+ target = tmp_path / "model.safetensors"+ partial = target.with_name(target.name + ".downloading")+ partial.write_bytes(b"partial data")+ part = DownloadJob(source=source.url, dest=target)+ part.bytes = len(b"partial data")+ part.download_path = target+ part.resume_required = True+ old_download = MultiFileDownloadJob(id=4582, dest=tmp_path, download_parts={part})+ old_download.status = DownloadJobStatus.RUNNING+ job = ModelInstallJob(+ id=4582,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmp_path,+ status=InstallStatus.PAUSED if operation == "resume" else InstallStatus.ERROR,+ )+ job._install_tmpdir = tmp_path+ job._multifile_job = old_download+ 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._download_queue, "submit_multifile_download", MagicMock())++ with pytest.raises(InstallDownloadConflictError, match="previous download"):+ if operation == "resume":+ installer.resume_job(job)+ elif operation == "restart_failed":+ installer.restart_failed(job)+ else:+ installer.restart_file(job, str(source.url))++ assert job._multifile_job is old_download+ assert installer._download_cache[old_download.id] is job+ assert partial.read_bytes() == b"partial data"+++def test_concurrent_restart_requests_are_serialized(+ 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"))+ job = ModelInstallJob(+ id=4584,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmp_path,+ status=InstallStatus.ERROR,+ )+ job._install_tmpdir = tmp_path+ job._install_tmpdir_active_sentinel_created = True+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)+ metadata_started = threading.Event()+ release_metadata = threading.Event()++ def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:+ metadata_started.set()+ assert release_metadata.wait(timeout=5)+ return [remote_file], None++ monkeypatch.setattr(installer, "_remote_files_from_source", blocked_metadata)+ submit_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "submit_multifile_download", submit_download)+ errors: list[BaseException] = []++ def restart() -> None:+ try:+ installer.restart_file(job, str(source.url))+ except BaseException as error:+ errors.append(error)++ first_request = threading.Thread(target=restart)+ first_request.start()+ try:+ assert metadata_started.wait(timeout=5)+ with pytest.raises(InstallDownloadConflictError, match="previous download"):+ installer.restart_file(job, str(source.url))+ finally:+ release_metadata.set()+ first_request.join(timeout=5)++ assert not first_request.is_alive()+ assert errors == []+ submit_download.assert_called_once()+ installer._release_install_tmpdir_claim(job)+ (tmp_path / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)+++def test_concurrent_resume_requests_are_serialized(+ 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"))+ job = ModelInstallJob(+ id=4586,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmp_path,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmp_path+ job._install_tmpdir_active_sentinel_created = True+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)+ metadata_started = threading.Event()+ release_metadata = threading.Event()++ def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:+ metadata_started.set()+ assert release_metadata.wait(timeout=5)+ return [remote_file], None++ monkeypatch.setattr(installer, "_remote_files_from_source", blocked_metadata)+ submit_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "submit_multifile_download", submit_download)+ errors: list[BaseException] = []++ def resume() -> None:+ try:+ installer.resume_job(job)+ except BaseException as error:+ errors.append(error)++ first_request = threading.Thread(target=resume)+ first_request.start()+ try:+ assert metadata_started.wait(timeout=5)+ with pytest.raises(InstallDownloadConflictError, match="previous download"):+ installer.resume_job(job)+ finally:+ release_metadata.set()+ first_request.join(timeout=5)++ assert not first_request.is_alive()+ assert errors == []+ submit_download.assert_called_once()+ installer._download_cache.pop(job._multifile_job.id)+ installer._release_install_tmpdir_claim(job)+ (tmp_path / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)+++ ("operation", "initial_status"),+ [+ ("resume", InstallStatus.PAUSED),+ ("restart_failed", InstallStatus.ERROR),+ ("restart_file", InstallStatus.ERROR),+ ],+)+def test_remote_download_preparation_failure_preserves_retryable_state(+ operation: str,+ initial_status: InstallStatus,+ 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")+ part.resume_required = True+ job = ModelInstallJob(+ id=4589,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmp_path,+ status=initial_status,+ download_parts={part},+ )+ job._install_tmpdir = tmp_path+ job._multifile_job = MultiFileDownloadJob(id=4589, dest=tmp_path, download_parts={part})+ monkeypatch.setattr(+ installer,+ "_remote_files_from_source",+ MagicMock(side_effect=RuntimeError("transient metadata failure")),+ )++ with pytest.raises(RuntimeError, match="transient metadata failure"):+ if operation == "resume":+ installer.resume_job(job)+ elif operation == "restart_failed":+ installer.restart_failed(job)+ else:+ installer.restart_file(job, str(source.url))++ assert job.status == initial_status+ assert job.id not in installer._remote_download_operations+ assert not installer._download_cache+++ ("operation", "initial_status"),+ [("resume", InstallStatus.PAUSED), ("restart_failed", InstallStatus.ERROR)],+)+def test_remote_download_retry_with_no_matching_files_preserves_retryable_state(+ operation: str,+ initial_status: InstallStatus,+ 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")+ part.resume_required = True+ job = ModelInstallJob(+ id=4590,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmp_path,+ status=initial_status,+ download_parts={part},+ )+ job._install_tmpdir = tmp_path+ job._multifile_job = MultiFileDownloadJob(id=4590, dest=tmp_path, download_parts={part})+ monkeypatch.setattr(installer, "_remote_files_from_source", lambda _: ([], None))++ with pytest.raises(RuntimeError, match="No remote files are available to download"):+ if operation == "resume":+ installer.resume_job(job)+ else:+ installer.restart_failed(job)++ assert job.status == initial_status+ assert job.id not in installer._remote_download_operations+ assert not installer._download_cache++[email protected]("install_worker_started", [False, True])+def test_pause_conflicts_after_download_install_handoff(+ install_worker_started: bool,+ mm2_installer: ModelInstallServiceBase,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}pause-install-handoff-{install_worker_started}"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"downloaded model")+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=payload)+ part.status = DownloadJobStatus.COMPLETED+ download_job = MultiFileDownloadJob(id=4587, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.COMPLETED+ job = ModelInstallJob(+ id=4587,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ job.download_parts = download_job.download_parts+ installer._install_jobs.append(job)+ installer._download_cache[download_job.id] = job+ create_active_install_sentinel(tmpdir)+ queue_install_job = MagicMock(return_value=True)+ monkeypatch.setattr(installer, "_queue_install_job_locked", queue_install_job)++ try:+ installer._download_complete_callback(download_job)+ expected_status = InstallStatus.DOWNLOADS_DONE+ if install_worker_started:+ job.status = InstallStatus.WAITING+ job._install_phase = "preflight"+ installer._active_install_job = job+ expected_status = InstallStatus.WAITING++ with pytest.raises(InstallDownloadConflictError, match="cannot be paused"):+ installer.pause_job(job)++ assert job.status == expected_status+ queue_install_job.assert_called_once_with(job)+ assert tmpdir.exists()+ assert has_active_install_sentinel(tmpdir)+ finally:+ installer._active_install_job = None+ job._install_phase = None+ job.status = InstallStatus.DOWNLOADS_DONE+ installer.cancel_job(job)+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ shutil.rmtree(tmpdir, ignore_errors=True)++[email protected]("action", ["cancel", "pause"])+def test_install_state_changes_conflict_during_remote_download_handoff(+ action: str,+ mm2_installer: ModelInstallServiceBase,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}handoff-{action}"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.PAUSED+ download_job = MultiFileDownloadJob(id=4585, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.PAUSED+ job = ModelInstallJob(+ id=4585,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ job.download_parts = download_job.download_parts+ installer._install_jobs.append(job)+ create_active_install_sentinel(tmpdir)+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)+ metadata_started = threading.Event()+ release_metadata = threading.Event()++ def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:+ metadata_started.set()+ assert release_metadata.wait(timeout=5)+ return [remote_file], None++ monkeypatch.setattr(installer, "_remote_files_from_source", blocked_metadata)+ submit_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "submit_multifile_download", submit_download)+ operation_errors: list[BaseException] = []++ def resume() -> None:+ try:+ installer.resume_job(job)+ except BaseException as error:+ operation_errors.append(error)++ operation_thread = threading.Thread(target=resume)+ operation_thread.start()+ try:+ assert metadata_started.wait(timeout=5)+ with pytest.raises(InstallDownloadConflictError, match="being prepared"):+ if action == "cancel":+ installer.cancel_job(job)+ else:+ installer.pause_job(job)+ assert tmpdir.exists()+ assert has_active_install_sentinel(tmpdir)+ finally:+ release_metadata.set()+ operation_thread.join(timeout=5)++ assert not operation_thread.is_alive()+ assert operation_errors == []+ submit_download.assert_called_once()+ assert not job.cancelled+ installer._download_cache.pop(job._multifile_job.id)+ installer._release_install_tmpdir_claim(job)+ (tmpdir / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+++def test_shutdown_waits_for_remote_download_handoff_and_preserves_pause(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}shutdown-handoff-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ part = DownloadJob(source=source.url, dest=tmpdir / "model.safetensors")+ part.status = DownloadJobStatus.PAUSED+ download_job = MultiFileDownloadJob(id=4586, dest=tmpdir, download_parts={part})+ download_job.status = DownloadJobStatus.PAUSED+ job = ModelInstallJob(+ id=4586,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ job._install_tmpdir = tmpdir+ job._install_tmpdir_active_sentinel_created = True+ job._multifile_job = download_job+ job.download_parts = download_job.download_parts+ installer._install_jobs.append(job)+ create_active_install_sentinel(tmpdir)+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)+ metadata_started = threading.Event()+ release_metadata = threading.Event()+ stop_finished = threading.Event()++ def blocked_metadata(_source: URLModelSource) -> tuple[list[RemoteModelFile], None]:+ metadata_started.set()+ assert release_metadata.wait(timeout=5)+ return [remote_file], None++ monkeypatch.setattr(installer, "_remote_files_from_source", blocked_metadata)+ submit_download = MagicMock()+ monkeypatch.setattr(installer._download_queue, "submit_multifile_download", submit_download)+ operation_errors: list[BaseException] = []++ def resume() -> None:+ try:+ installer.resume_job(job)+ except BaseException as error:+ operation_errors.append(error)++ operation_thread = threading.Thread(target=resume)+ stop_thread = threading.Thread(target=lambda: (installer.stop(), stop_finished.set()))+ operation_thread.start()+ try:+ assert metadata_started.wait(timeout=5)+ stop_thread.start()+ assert installer._stop_event.wait(timeout=5)+ finally:+ release_metadata.set()+ operation_thread.join(timeout=5)+ if stop_thread.ident is not None:+ stop_thread.join(timeout=5)++ assert not operation_thread.is_alive()+ assert not stop_thread.is_alive()+ assert stop_finished.is_set()+ assert len(operation_errors) == 1+ assert isinstance(operation_errors[0], InstallDownloadConflictError)+ submit_download.assert_not_called()+ assert job.paused+ assert tmpdir.exists()+ assert not has_active_install_sentinel(tmpdir)+ marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))+ assert marker["status"] == InstallStatus.PAUSED.value+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_remote_staging_is_claimed_before_download_submission(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}claim-before-download"+ tmpdir.mkdir()+ source = URLModelSource(url=Url("https://example.com/model.safetensors"))+ payload = tmpdir / "model.safetensors"+ part = DownloadJob(source=source.url, dest=payload)+ download_job = MultiFileDownloadJob(id=457, dest=tmpdir, download_parts={part})+ job = ModelInstallJob(id=457, source=source, config_in=ModelRecordChanges(), local_path=tmpdir)+ remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)+ monkeypatch.setattr(installer, "_multifile_download", lambda **_: download_job)++ def assert_claimed_before_submit(submitted_job: MultiFileDownloadJob) -> None:+ assert submitted_job is download_job+ assert has_active_install_sentinel(tmpdir)+ assert job._install_tmpdir_active_sentinel_created++ monkeypatch.setattr(installer._download_queue, "submit_multifile_download", assert_claimed_before_submit)++ installer._enqueue_remote_download(+ job=job,+ source=source,+ remote_files=[remote_file],+ metadata=None,+ destdir=tmpdir,+ )++ assert has_active_install_sentinel(tmpdir)+ assert active_install_sentinel_path(tmpdir).exists()+ # The fixture does not run a download worker for this synthetic job.+ installer._download_cache.pop(download_job.id)+ installer._release_job_source_protection(job)+++def test_install_worker_preserves_remote_staging_when_claim_conflicts(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ tmpdir = tmp_path / f"{TMPDIR_PREFIX}claim-conflict"+ tmpdir.mkdir()+ payload = tmpdir / "model.safetensors"+ payload.write_bytes(b"owned by another install")+ create_active_install_sentinel(tmpdir)++ job = ModelInstallJob(+ id=458,+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADS_DONE,+ )+ job._install_tmpdir = tmpdir+ installer._install_queue.put(job)++ def attempt_transfer(queued_job: ModelInstallJob) -> None:+ installer._begin_install_transfer(queued_job)++ try:+ monkeypatch.setattr(installer, "_register_or_install", attempt_transfer)+ installer._install_queue.put(job)+ installer._install_queue.join()++ assert job.errored+ assert payload.read_bytes() == b"owned by another install"+ assert has_active_install_sentinel(tmpdir)+ finally:+ # This sidecar belongs to the simulated competing operation.+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)++def test_resume_reports_restart_from_scratch_on_fresh_parts(mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -1949,6 +3346,7 @@ def test_restore_keeps_a_legacy_marker_whose_key_predates_key_validation(assert restored == {"stabilityai/legacy-key", "stabilityai/ordinary"}finally:for tmpdir in tmpdirs:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -2002,4 +3400,5 @@ def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(assert [str(job.source) for job in restored_installer.list_jobs()] == ["stabilityai/ordinary"]finally:for tmpdir in tmpdirs:+ active_install_sentinel_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)