Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model-manager): preserve recovery state (#9915)
Jonathane2256d177391
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 2dfa5d9301..dd3a5680b9 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -512,6 +512,18 @@ Cancel the indicated job.Remove jobs that are in a terminal state (i.e. complete, errored or cancelled) from the job list returned by `list_jobs()` and `get_job()`.+Install jobs are in-memory progress records, not durable history. The install API exposes the jobs still retained by the+current service through `GET /install`; `DELETE /install` removes terminal jobs from that list. An error's type,+traceback, and source are available on the job and error event while they are retained, but pruning or restarting the+service makes that diagnostic history unavailable. Recovery markers may contain some install inputs, but they are not+a supported job-history interface and do not guarantee the original error or the source-to-destination association.++When an install requires manual recovery, recovery sentinels protect the affected directories and their files across+pruning, cleanup, and service restart. The supported recovery contract is artifact preservation: inspect the protected+directories on disk and use `register_path()` after resolving the files. The installer does not restore a terminal+recovery job or provide a history/list endpoint for protected roots after restart. Operators should capture the+reported error and paths before pruning or restarting if they need those diagnostics later.+#### installer.app_config, installer.record_store, installer.event_busProperties that provide access to the installer's `InvokeAIAppConfig`, `ModelRecordServiceBase` and `EventServiceBase` objects.@@ -526,8 +538,20 @@ 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.+Rollback requires an atomic no-replace rename. Linux uses `renameat2(RENAME_NOREPLACE)`, macOS uses `renamex_np(RENAME_EXCL)`, and Windows relies on `os.rename()` refusing an existing destination. If the primitive is unavailable or the filesystem refuses it, rollback stops and reports the source and managed destination; it never substitutes an existence check followed by an overwriting rename. Any artifact still in the managed destination stays protected by its recovery sentinel for manual recovery, and a concurrently recreated source is left untouched. Cross-filesystem restores stage a copy but still require the same no-replace operation to publish it.++When a restore rename crosses filesystems, its temporary copy is created in a hidden `.<source-name>.restore-*` directory beside the original source. That parent may be outside the managed models directory. The copy is published with a no-replace rename before the managed copy is removed; a hard termination can therefore leave a partial or complete staged copy, both published copies, or (for directories) a partially removed managed copy. These scratch paths have no durable ownership record, so startup does not reconcile or delete them. Do not remove a restore scratch directory based on its name or age: first stop install activity, inspect the original source parent and the managed destination, and establish which copies are complete. Preserve every possible sole or incomplete copy until recovery is resolved. For sources outside the managed models directory, InvokeAI cannot discover or protect the original source parent; operators must inspect it directly. After resolving the files, use `register_path()` where appropriate.+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.+Active-claim sidecars accept the legacy `PID process-start-time` payload and new Linux claims append a stable `linux:<boot-id>:<start-ticks>` process identity. A live PID with a legacy timestamp mismatch is ambiguous because wall-clock changes and PID reuse cannot be distinguished; startup preserves that claim for operator recovery. New Linux claims use the boot ID and kernel start ticks, so a reused PID can be reclaimed without comparing wall-clock time. On other platforms, new claims retain the two-field format and a reused live PID is conservatively preserved; a Linux-format sidecar encountered there is unsupported and also preserved. Claim payloads are written and flushed to a temporary file, then atomically published as a no-clobber hard link; a process killed before publication cannot leave an empty canonical claim, though it may leave an ignored temporary file. If the filesystem does not support hard links, claim creation fails rather than exposing a partial sidecar.++Startup serializes stale-claim scans in-process and across processes with the persistent hidden `.invokeai_install_claims.lock` file in the models root; it remains in place so concurrent scanners always lock the same file. The lock covers enumeration through stale-claim removal, so a waiting scan sees claims created after the preceding scan completes. Windows uses repeated nonblocking lock attempts rather than `msvcrt.LK_LOCK`'s finite retry count, which could fail during a long scan. An empty or malformed sidecar, denied process inspection, and other inspection failures do not prove that its owner is gone, so startup preserves the claim and emits at most ten individual warnings plus one summary per scan. The next service startup retries the check. If the claim remains, an operator may remove its sidecar manually only after confirming that no install or orphan deletion is using that path; age alone is not evidence that a claim is stale.++Startup restores nonterminal install markers automatically, except markers with `PAUSED` status. If shutdown interrupts restoration of a marker already visited, that job is saved as `PAUSED`; markers later in the scan remain unchanged. On the next service startup, non-paused markers resume automatically, while both user-paused and shutdown-paused jobs stay paused until `resume_job()` is called. Partial files and resume metadata remain in their staging directories across this cycle.++Before a transfer, the installer flushes the recovery-sentinel file and, on non-Windows platforms, its containing directory. A file or directory `fsync` error aborts the install before source files move; unsupported directory `fsync` is treated as a failure, not as best-effort durability. Sentinel cleanup unlinks the file before syncing the containing directory. If that final sync fails, the installer logs a warning and continues cleanup; the unlink may not survive a crash, so a stale sentinel can reappear and require manual inspection. These steps do not promise crash durability on every filesystem or storage device.+#### 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)`@@ -873,6 +897,10 @@ The base class also has a class method `from_json()` which will take the JSON reWhen initializing one of the metadata fetching classes, you may provide a `requests.Session` argument. This allows you to customize the low-level HTTP fetch requests and is used, for instance, in the testing suite to avoid hitting the internet.+Metadata HTTP calls pass a 15-second timeout to each request. This is a per-request transport timeout, not a total deadline for metadata lookup or service shutdown. Looking up a requested variant may make a second, sequential model-info request at the default revision when that variant is missing; filtering a model that needs `model_index.json` can make another sequential request. InvokeAI's current metadata path does not add an application-level retry loop. A custom session or HTTP client may have its own retries and backoff, which can extend elapsed time; the request timeout does not bound those attempts as one total duration.++The installer checks for shutdown between restore markers and before it submits a prepared download, but it cannot interrupt a metadata request already in progress and does not pass a cancellation signal between the sequential metadata calls. `stop()` waits for the restore worker to finish before clearing jobs or releasing its staging claims. Therefore shutdown latency has no strict maximum: it includes the remaining metadata calls and any retries or waits performed by the configured transport. If shutdown arrives during metadata lookup, that lookup may continue through its fallback or model-index request. The current restore is then saved as `PAUSED`, and its partial files and resume metadata are preserved; later unvisited markers remain unchanged.+The HuggingFace fetcher subclass add additional repo-specific fetching methods:#### HuggingFaceMetadataFetchdiff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 2cc77dfd5f..6e55e415ad 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -510,6 +510,16 @@ def _reidentify_model(key: str) -> AnyModelConfig:result.config.trigger_phrases = config.trigger_phrasesresult.config.source = config.sourceresult.config.source_type = config.source_type+ if hasattr(config, "cpu_only") and hasattr(result.config, "cpu_only"):+ result.config.cpu_only = config.cpu_only+ previous_settings = getattr(config, "default_settings", None)+ updated_settings = getattr(result.config, "default_settings", None)+ if previous_settings is not None and updated_settings is not None:+ updated_settings = deepcopy(updated_settings)+ result.config.default_settings = updated_settings+ for field in ("cpu_only", "fp8_storage"):+ if hasattr(previous_settings, field) and hasattr(updated_settings, field):+ setattr(updated_settings, field, getattr(previous_settings, field))# The probe can reset load-affecting settings (cpu_only, default_settings), so in-flight loads must re-check.with ApiDependencies.invoker.services.model_manager.load.record_edit(config.key) as edit:diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex f423a9b0a1..5556b81122 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -1,9 +1,15 @@+import errnoimport osimport re+import sys+import tempfile+import threading+import timeimport traceback+from contextlib import contextmanagerfrom enum import Enumfrom pathlib import Path-from typing import Literal, Optional, Set, Union+from typing import Iterator, Literal, Optional, Set, Unionimport psutilfrom pydantic import BaseModel, Field, PrivateAttr, field_validator@@ -25,6 +31,46 @@ class InvalidModelConfigException(Exception):INSTALL_RECOVERY_SENTINEL = ".invokeai_install_recovery_required"INSTALL_ACTIVE_SENTINEL = ".invokeai_install_active"+INSTALL_ACTIVE_SCAN_LOCK = ".invokeai_install_claims.lock"+ACTIVE_CLAIM_SCAN_LOCK_RETRY_INTERVAL_SECONDS = 0.05+_active_claim_scan_thread_lock = threading.Lock()+++@contextmanager+def active_install_claim_scan_lock(models_path: Path) -> Iterator[None]:+ """Serialize stale-claim scans across threads and processes using a stable lock file."""+ with _active_claim_scan_thread_lock:+ lock_path = models_path / INSTALL_ACTIVE_SCAN_LOCK+ with open(lock_path, "a+b") as lock_file:+ if os.name == "nt":+ import msvcrt++ lock_file.seek(0, os.SEEK_END)+ if lock_file.tell() == 0:+ lock_file.write(b"\0")+ lock_file.flush()+ lock_file.seek(0)+ while True:+ try:+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)+ break+ except OSError as e:+ if e.errno not in {errno.EACCES, errno.EDEADLK, errno.EAGAIN}:+ raise+ time.sleep(ACTIVE_CLAIM_SCAN_LOCK_RETRY_INTERVAL_SECONDS)+ try:+ yield+ finally:+ lock_file.seek(0)+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)+ try:+ yield+ finally:+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)class InstallCancellationConflictError(RuntimeError):@@ -59,22 +105,46 @@ def has_active_install_sentinel(root: Path) -> bool:return active_install_sentinel_path(root).exists()+def _linux_process_start_identity(pid: int) -> str:+ """Return process identity fields unaffected by wall-clock changes."""+ boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip()+ stat = Path(f"/proc/{pid}/stat").read_bytes()+ fields = stat.rsplit(b")", 1)[1].split()+ if len(fields) <= 19:+ raise ValueError(f"Unexpected /proc/{pid}/stat format")+ start_ticks = fields[19].decode("ascii")+ return f"linux:{boot_id}:{start_ticks}"++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+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)+ temp_path = Path(temp_name)try:- with open(path, "xb") as f:- created = True+ with os.fdopen(fd, "wb") as f:process = psutil.Process()- f.write(f"{process.pid} {process.create_time()!r}\n".encode("ascii"))+ payload = f"{process.pid} {process.create_time()!r}"+ if sys.platform == "linux":+ payload += f" {_linux_process_start_identity(process.pid)}"+ f.write(f"{payload}\n".encode("ascii"))f.flush()os.fsync(f.fileno())- except Exception:- if created:- path.unlink(missing_ok=True)+ # A hard link publishes the complete payload atomically and fails if another owner won.+ os.link(temp_path, path)+ except BaseException:+ try:+ temp_path.unlink(missing_ok=True)+ except OSError:+ passraise+ else:+ # Once linked, cleanup cannot make publication fail for the owner.+ try:+ temp_path.unlink(missing_ok=True)+ except OSError:+ passdef delete_active_install_sentinel(root: Path) -> None:diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 0b81f21676..98c2230c4d 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -6,6 +6,7 @@ import filecmpimport gcimport jsonimport locale+import mathimport osimport reimport sys@@ -45,6 +46,8 @@ from invokeai.app.services.model_install.model_install_common import (ModelSource,StringLikeSource,URLModelSource,+ _linux_process_start_identity,+ active_install_claim_scan_lock,create_active_install_sentinel,delete_active_install_sentinel,has_active_install_sentinel,@@ -98,6 +101,7 @@ TMPDIR_PREFIX = "tmpinstall_"# Marker file used to resume or pause remote model installs across restarts.INSTALL_MARKER_FILENAME = ".invokeai_install.json"INSTALL_MARKER_VERSION = 1+MAX_ACTIVE_CLAIM_DIAGNOSTICS = 10class _InstallCancelledBeforeTransfer(Exception):@@ -302,26 +306,94 @@ class ModelInstallService(ModelInstallServiceBase):return Truedef _remove_stale_install_source_claims(self) -> None:+ """Serialize stale-claim recovery so no scanner can delete a claim published after another scan."""+ models_path = self.app_config.models_path+ if not models_path.is_dir():+ return+ with active_install_claim_scan_lock(models_path):+ self._remove_stale_install_source_claims_locked()++ def _remove_stale_install_source_claims_locked(self) -> None:"""Remove active-claim sidecars left by processes that exited before releasing them."""+ diagnostics: list[tuple[Path, str]] = []+ omitted_diagnostics = 0++ def record_diagnostic(claim_path: Path, detail: str) -> None:+ nonlocal omitted_diagnostics+ if len(diagnostics) < MAX_ACTIVE_CLAIM_DIAGNOSTICS:+ diagnostics.append((claim_path, detail))+ else:+ omitted_diagnostics += 1+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()+ original_stat = claim_path.stat(follow_symlinks=False)+ owner_data = claim_path.read_text(encoding="ascii").split()+ if len(owner_data) not in {2, 3}:+ raise ValueError("expected legacy PID/start-time or PID/start-time/identity payload")+ pid_text, create_time_text = owner_data[:2]+ if not re.fullmatch(r"[0-9]+", pid_text) or not re.fullmatch(+ r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?", create_time_text+ ):+ raise ValueError("malformed PID or process start time")pid = int(pid_text)create_time = float(create_time_text)+ if pid <= 0 or not math.isfinite(create_time) or create_time < 0:+ raise ValueError("invalid PID or process start time")+ if len(owner_data) == 3:+ identity = owner_data[2]+ if not re.fullmatch(r"[a-z][a-z0-9_-]*:.+", identity):+ raise ValueError("malformed process identity")+ if identity.startswith("linux:") and not re.fullmatch(+ r"linux:[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}:[0-9]+", identity+ ):+ raise ValueError("malformed Linux process identity")+ if sys.platform != "linux" or not identity.startswith("linux:"):+ record_diagnostic(claim_path, "its process identity is unsupported here; preserving it")+ continueprocess = psutil.Process(pid)- # On Linux, psutil derives process start time from boot time plus kernel ticks. A small boot-time- # adjustment can change that value for a live process, so exact float equality can remove its claim.- if process.status() == psutil.STATUS_ZOMBIE or abs(process.create_time() - create_time) > 1.0:- claim_path.unlink(missing_ok=True)+ if process.status() == psutil.STATUS_ZOMBIE:+ stale = True+ elif len(owner_data) == 2:+ # A legacy wall-clock timestamp cannot distinguish PID reuse from a clock adjustment.+ stale = False+ else:+ stale = _linux_process_start_identity(pid) != owner_data[2]except (psutil.NoSuchProcess, psutil.ZombieProcess):- claim_path.unlink(missing_ok=True)- except psutil.AccessDenied:+ stale = True+ except psutil.AccessDenied as e:+ record_diagnostic(+ claim_path,+ f"process inspection was denied ({e}); preserving it. Retry on next startup or remove it "+ "manually only after confirming the owner is gone",+ )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.+ except (UnicodeError, ValueError) as e:+ record_diagnostic(+ claim_path,+ f"its owner payload is malformed ({e}); preserving it. Retry on next startup or remove it "+ "manually only after confirming no install or orphan deletion is active",+ )continue+ except OSError as e:+ record_diagnostic(claim_path, f"inspection failed ({e}); preserving it")+ continue++ if stale:+ try:+ current_stat = claim_path.stat(follow_symlinks=False)+ if (original_stat.st_dev, original_stat.st_ino) != (current_stat.st_dev, current_stat.st_ino):+ continue+ claim_path.unlink()+ except FileNotFoundError:+ continue+ except OSError as e:+ record_diagnostic(claim_path, f"stale claim removal failed ({e})")++ for claim_path, detail in diagnostics:+ self._logger.warning(f"Could not verify active install claim {claim_path}: {detail}.")+ if omitted_diagnostics:+ self._logger.warning(f"Could not verify {omitted_diagnostics} additional active install claims.")def _retain_recovery_destination(self, dest_dir: Path) -> None:try:diff --git a/invokeai/backend/model_manager/metadata/fetch/huggingface.py b/invokeai/backend/model_manager/metadata/fetch/huggingface.pyindex 34cce42465..7b49299524 100644--- a/invokeai/backend/model_manager/metadata/fetch/huggingface.py+++ b/invokeai/backend/model_manager/metadata/fetch/huggingface.py@@ -20,7 +20,7 @@ from typing import Optionalimport httpximport requestsfrom huggingface_hub import HfApi, hf_hub_url-from huggingface_hub.errors import RepositoryNotFoundError, RevisionNotFoundError+from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundErrorfrom pydantic.networks import AnyHttpUrlfrom requests.sessions import Session@@ -32,6 +32,7 @@ from invokeai.backend.model_manager.metadata.metadata_base import (ModelMetadataUnavailableError,RemoteModelFile,UnknownMetadataException,+ is_transient_hf_http_error,)from invokeai.backend.model_manager.taxonomy import ModelRepoVariant@@ -65,10 +66,17 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):url += f"/revision/{variant}"resp = self._requests.get(url, params=params, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)if resp.status_code == 404:+ error_response = httpx.Response(+ status_code=resp.status_code,+ headers=resp.headers,+ request=httpx.Request("GET", str(resp.url)),+ )error_code = resp.headers.get("X-Error-Code", "")if error_code == "RevisionNotFound" or (variant is not None):- raise RevisionNotFoundError(f"Revision '{variant}' not found for repo '{repo_id}'.")- raise RepositoryNotFoundError(f"Repository '{repo_id}' not found.")+ raise RevisionNotFoundError(+ f"Revision '{variant}' not found for repo '{repo_id}'.", response=error_response+ )+ raise RepositoryNotFoundError(f"Repository '{repo_id}' not found.", response=error_response)resp.raise_for_status()data = resp.json()# Convert siblings dicts to SimpleNamespace objects matching HfApi.model_info() shape@@ -115,6 +123,10 @@ class HuggingFaceMetadataFetch(ModelMetadataFetchBase):raiseelse:variant = None+ except HfHubHTTPError as e:+ if is_transient_hf_http_error(e):+ raise ModelMetadataUnavailableError(f"Could not fetch Hugging Face metadata for '{repo_id}'") from e+ raisefiles: list[RemoteModelFile] = []diff --git a/invokeai/backend/model_manager/metadata/metadata_base.py b/invokeai/backend/model_manager/metadata/metadata_base.pyindex 3a011850f5..d5dc41825d 100644--- a/invokeai/backend/model_manager/metadata/metadata_base.py+++ b/invokeai/backend/model_manager/metadata/metadata_base.py@@ -16,9 +16,10 @@ from pathlib import Pathfrom typing import List, Literal, Optional, Unionfrom huggingface_hub import hf_hub_url+from huggingface_hub.errors import HfHubHTTPErrorfrom pydantic import BaseModel, Field, TypeAdapterfrom pydantic.networks import AnyHttpUrl-from requests import RequestException+from requests import HTTPError, RequestExceptionfrom requests.sessions import Sessionfrom typing_extensions import Annotated@@ -33,7 +34,13 @@ class UnknownMetadataException(Exception):class ModelMetadataUnavailableError(Exception):- """Raised when a remote metadata request fails at the network layer."""+ """Raised when a remote metadata request fails transiently."""+++def is_transient_hf_http_error(error: HfHubHTTPError | HTTPError) -> bool:+ """Return whether an HF HTTP response can reasonably succeed if retried later."""+ status_code = error.response.status_code if error.response is not None else None+ return status_code == 429 or (status_code is not None and 500 <= status_code < 600)class RemoteModelFile(BaseModel):@@ -130,9 +137,13 @@ class HuggingFaceMetadata(ModelMetadataWithFiles):url = hf_hub_url(self.id, filename="model_index.json", subfolder=str(subfolder) if subfolder else None)try:resp = session.get(url, timeout=HF_METADATA_REQUEST_TIMEOUT_SECONDS)+ resp.raise_for_status()+ except HTTPError as e:+ if is_transient_hf_http_error(e):+ raise ModelMetadataUnavailableError(f"Could not fetch model index for '{self.id}'") from e+ raiseexcept RequestException as e:raise ModelMetadataUnavailableError(f"Could not fetch model index for '{self.id}'") from e- resp.raise_for_status()submodels = resp.json()paths = [Path(subfolder or "", x) for x in paths if Path(x).parent.as_posix() in submodels]paths.insert(0, Path(f"{prefix}model_index.json"))diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.pyindex e2fec5ad5a..3bb03ce618 100644--- a/tests/app/routers/test_update_model_record_cache_invalidation.py+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py@@ -211,8 +211,8 @@ def test_reidentify_invalidates_caches_when_identification_changes_model_class(type=ModelType.Main,format=ModelFormat.Checkpoint,variant="old",- cpu_only=False,- default_settings=None,+ cpu_only=True,+ default_settings=SimpleNamespace(fp8_storage=True),)identified = SimpleNamespace(key="model-key",@@ -227,7 +227,7 @@ def test_reidentify_invalidates_caches_when_identification_changes_model_class(format=ModelFormat.Checkpoint,variant="new",cpu_only=False,- default_settings=None,+ default_settings=SimpleNamespace(fp8_storage=False),)stored = SimpleNamespace(replace_model=MagicMock(return_value=identified), get_model=MagicMock(return_value=previous)@@ -257,11 +257,198 @@ def test_reidentify_invalidates_caches_when_identification_changes_model_class(assert model_manager_router._reidentify_model("model-key") is identifiedassert factory_overrides["image_encoder_model_id"] == "custom/image-encoder"+ assert identified.cpu_only is True+ assert identified.default_settings.fp8_storage is Truefor cache in caches:cache.drop_model.assert_called_once_with("model-key")[email protected]("cpu_only", [False, None])[email protected]("fp8_storage", [False, None])+def test_reidentify_preserves_explicit_unset_preferences(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cpu_only: bool | None, fp8_storage: bool | None+):+ """False and None are user choices too; probe defaults must not replace them."""+ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.backend.model_manager.taxonomy import ModelSourceType++ previous = SimpleNamespace(+ key="model-key",+ path="model.safetensors",+ name="Model",+ description="",+ cover_image=None,+ source="local-source",+ source_type=ModelSourceType.Path,+ cpu_only=cpu_only,+ default_settings=SimpleNamespace(fp8_storage=fp8_storage),+ )+ identified = SimpleNamespace(+ key="model-key",+ path="model.safetensors",+ name="identified name",+ description="identified description",+ cover_image=None,+ source="new-source",+ source_type=ModelSourceType.Path,+ cpu_only=not cpu_only if cpu_only is not None else True,+ default_settings=SimpleNamespace(fp8_storage=not fp8_storage if fp8_storage is not None else True),+ )+ store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)+ services = SimpleNamespace(+ model_manager=SimpleNamespace(+ store=store,+ load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={}),+ ),+ configuration=SimpleNamespace(models_path=tmp_path / "models"),+ logger=MagicMock(),+ )+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )+ monkeypatch.setattr(model_manager_router, "ModelOnDisk", lambda _path: object())+ monkeypatch.setattr(+ model_manager_router.ModelConfigFactory,+ "from_model_on_disk",+ lambda *_args, **_kwargs: SimpleNamespace(config=identified),+ )++ updated = model_manager_router._reidentify_model("model-key")++ assert updated.cpu_only is cpu_only+ assert updated.default_settings.fp8_storage is fp8_storage++[email protected]("cpu_only,fp8_storage", [(True, True), (False, False), (None, None)])+def test_reidentify_preserves_main_model_default_settings(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ cpu_only: bool | None,+ fp8_storage: bool | None,+):+ """Main model CPU and FP8 preferences live in the typed default_settings object."""+ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config+ from invokeai.backend.model_manager.taxonomy import ModelSourceType, ModelVariantType, SchedulerPredictionType++ def main_config(*, name: str, settings: MainModelDefaultSettings) -> Main_Checkpoint_SD1_Config:+ return Main_Checkpoint_SD1_Config(+ hash=f"hash-{name}",+ path="model.safetensors",+ file_size=1,+ name=name,+ source="local-source",+ source_type=ModelSourceType.Path,+ prediction_type=SchedulerPredictionType.Epsilon,+ variant=ModelVariantType.Normal,+ default_settings=settings,+ )++ previous = main_config(+ name="Model",+ settings=MainModelDefaultSettings(cpu_only=cpu_only, fp8_storage=fp8_storage),+ )+ previous.key = "model-key"+ identified = main_config(+ name="Probed model",+ settings=MainModelDefaultSettings(+ cpu_only=not cpu_only if cpu_only is not None else True,+ fp8_storage=not fp8_storage if fp8_storage is not None else True,+ ),+ )+ store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)+ services = SimpleNamespace(+ model_manager=SimpleNamespace(+ store=store,+ load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={}),+ ),+ configuration=SimpleNamespace(models_path=tmp_path / "models"),+ logger=MagicMock(),+ )+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )+ monkeypatch.setattr(model_manager_router, "ModelOnDisk", lambda _path: object())+ monkeypatch.setattr(+ model_manager_router.ModelConfigFactory,+ "from_model_on_disk",+ lambda *_args, **_kwargs: SimpleNamespace(config=identified),+ )++ updated = model_manager_router._reidentify_model("model-key")++ assert isinstance(updated, Main_Checkpoint_SD1_Config)+ assert updated.default_settings is not None+ assert updated.default_settings.cpu_only is cpu_only+ assert updated.default_settings.fp8_storage is fp8_storage+++def test_reidentify_does_not_mutate_shared_architecture_defaults(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+):+ from invokeai.app.api.routers import model_manager as model_manager_router+ from invokeai.backend.architectures.facets.default_settings import DefaultSettingsFacet+ from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config+ from invokeai.backend.model_manager.taxonomy import ModelSourceType, ModelVariantType, SchedulerPredictionType++ shared_defaults = MainModelDefaultSettings(cpu_only=None, fp8_storage=True)+ facet = DefaultSettingsFacet(by_variant={None: shared_defaults})+ assert facet.resolve() is shared_defaults++ def main_config(*, name: str, settings: MainModelDefaultSettings) -> Main_Checkpoint_SD1_Config:+ return Main_Checkpoint_SD1_Config(+ hash=f"hash-{name}",+ path="model.safetensors",+ file_size=1,+ name=name,+ source="local-source",+ source_type=ModelSourceType.Path,+ prediction_type=SchedulerPredictionType.Epsilon,+ variant=ModelVariantType.Normal,+ default_settings=settings,+ )++ previous = main_config(+ name="Model",+ settings=MainModelDefaultSettings(cpu_only=True, fp8_storage=False),+ )+ previous.key = "model-key"+ identified = main_config(name="Probed model", settings=facet.resolve())+ store = SimpleNamespace(get_model=lambda _key: previous, replace_model=lambda _key, updated: updated)+ services = SimpleNamespace(+ model_manager=SimpleNamespace(+ store=store,+ load=SimpleNamespace(record_edit=_no_record_edit, ram_caches={}),+ ),+ configuration=SimpleNamespace(models_path=tmp_path / "models"),+ logger=MagicMock(),+ )+ monkeypatch.setattr(+ model_manager_router.ApiDependencies, "invoker", SimpleNamespace(services=services), raising=False+ )+ monkeypatch.setattr(model_manager_router, "ModelOnDisk", lambda _path: object())+ monkeypatch.setattr(+ model_manager_router.ModelConfigFactory,+ "from_model_on_disk",+ lambda *_args, **_kwargs: SimpleNamespace(config=identified),+ )++ updated = model_manager_router._reidentify_model("model-key")+ later_model_defaults = facet.resolve()++ assert updated.default_settings is not shared_defaults+ assert updated.default_settings is not None+ assert updated.default_settings.cpu_only is True+ assert updated.default_settings.fp8_storage is False+ assert later_model_defaults is shared_defaults+ assert later_model_defaults.cpu_only is None+ assert later_model_defaults.fp8_storage is True++def test_reidentify_preserves_ip_adapter_encoder_override_with_blank_metadata(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:diff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.pyindex c44d97cb5b..911f88efaf 100644--- a/tests/app/services/download/test_download_queue.py+++ b/tests/app/services/download/test_download_queue.py@@ -4,6 +4,7 @@ import reimport timefrom contextlib import contextmanagerfrom pathlib import Path+from threading import Eventfrom typing import Any, Generator, Optionalfrom unittest.mock import MagicMock, patch@@ -335,52 +336,88 @@ def test_multifile_download(tmp_path: Path, mm2_session: Session) -> None:queue.stop()[email protected]("status", [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING, DownloadJobStatus.PAUSED])-def test_multifile_error_preserves_sibling_part_paused_during_callback(- tmp_path: Path, mm2_session: Session, status: DownloadJobStatus[email protected](timeout=10, method="thread")+def test_multifile_error_worker_releases_paused_running_sibling_parent_reference(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True)- failed_part = DownloadJob(- id=10,- source=AnyHttpUrl("https://example.com/failed.safetensors"),- dest=tmp_path / "failed.safetensors",- status=DownloadJobStatus.ERROR,- )+ sibling_source = AnyHttpUrl("https://example.com/paused.safetensors")+ failed_source = AnyHttpUrl("https://example.com/failed.safetensors")sibling_path = tmp_path / "paused.safetensors"partial_path = sibling_path.with_name(f"{sibling_path.name}.downloading")- partial_path.write_bytes(b"paused partial")- paused_sibling = DownloadJob(- id=11,- source=AnyHttpUrl("https://example.com/paused.safetensors"),- dest=sibling_path,- download_path=sibling_path,- status=status,+ sibling_at_pause = Event()+ release_sibling = Event()+ parent_failed = Event()+ parent_errors: list[str] = []++ class ControlledResponse(Response):+ def iter_content(self, chunk_size: int = 1, decode_unicode: bool = False):+ yield b"paused partial"+ sibling_at_pause.set()+ assert release_sibling.wait(timeout=5)+ yield b"discarded after pause"++ sibling_response = ControlledResponse()+ sibling_response.status_code = 200+ sibling_response.url = str(sibling_source)+ sibling_response.headers["content-length"] = "36"+ failed_response = Response()+ failed_response.status_code = 500+ failed_response.url = str(failed_source)+ failed_response.reason = "server error"++ session = Session()++ def controlled_get(url: str, **kwargs: Any) -> Response:+ return sibling_response if url == str(sibling_source) else failed_response++ monkeypatch.setattr(session, "get", controlled_get)+ queue = DownloadQueueService(+ max_parallel_dl=2,+ requests_session=session,+ requests_session_is_trusted=True,)- paused_sibling.pause()+ monkeypatch.setattr(queue, "_validate_url", lambda url: None)+ queue.start()++ failed_part = DownloadJob(id=10, source=failed_source, dest=tmp_path / "failed.safetensors", priority=1)+ paused_sibling = DownloadJob(id=11, source=sibling_source, dest=sibling_path, priority=0)parent = MultiFileDownloadJob(id=12,dest=tmp_path,- status=DownloadJobStatus.RUNNING,download_parts={failed_part, paused_sibling},)+ parent.set_callbacks(on_error=lambda job, excp=None: (parent_errors.append(job.status.value), parent_failed.set()))queue._download_part2parent[failed_part.id] = parentqueue._download_part2parent[paused_sibling.id] = parent- queue._mfd_error(failed_part, RuntimeError("sibling failed"))-- assert paused_sibling.paused- assert partial_path.read_bytes() == b"paused partial"- if status == DownloadJobStatus.RUNNING:- # The active worker owns cleanup of its mapping after its pause callback returns.+ callbacks = {+ "on_start": queue._mfd_started,+ "on_progress": queue._mfd_progress,+ "on_complete": queue._mfd_complete,+ "on_cancelled": queue._mfd_cancelled,+ "on_error": queue._mfd_error,+ }+ try:+ queue.submit_download_job(paused_sibling, **callbacks)+ assert sibling_at_pause.wait(timeout=5)+ queue.pause_job(paused_sibling)+ queue.submit_download_job(failed_part, **callbacks)++ assert parent_failed.wait(timeout=5)+ assert parent.status == DownloadJobStatus.ERROR+ assert paused_sibling.status == DownloadJobStatus.RUNNINGassert paused_sibling.id in queue._download_part2parent- else:- # No worker remains to release a queued or already-paused part's mapping.- assert paused_sibling.id not in queue._download_part2parent- # A pending worker may deliver the pause callback after the parent has already failed.- queue._mfd_cancelled(paused_sibling)- queue._download_part2parent.pop(paused_sibling.id, None)- assert paused_sibling.id not in queue._download_part2parent+ release_sibling.set()+ queue.join()++ assert paused_sibling.status == DownloadJobStatus.PAUSED+ assert partial_path.read_bytes() == b"paused partial"+ assert paused_sibling.id not in queue._download_part2parent+ assert parent_errors == [DownloadJobStatus.ERROR.value]+ finally:+ release_sibling.set()+ queue.stop()@pytest.mark.timeout(timeout=10, method="thread")diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex a9b78fea72..d0d746de1d 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -8,6 +8,7 @@ import jsonimport platformimport shutilimport sqlite3+import statimport threadingimport timeimport uuid@@ -18,7 +19,7 @@ from unittest.mock import MagicMockimport pytestfrom pydantic_core import Url-from requests import Timeout+from requests import Request, Response, Timeoutfrom requests_testadapter import TestAdapterfrom invokeai.app.services.config import InvokeAIAppConfig@@ -60,6 +61,7 @@ from invokeai.app.services.model_install.model_install_default import (from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL, UnknownModelExceptionfrom invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfigfrom invokeai.backend.model_manager.metadata import RemoteModelFile+from invokeai.backend.model_manager.metadata.metadata_base import HF_METADATA_REQUEST_TIMEOUT_SECONDSfrom invokeai.backend.model_manager.taxonomy import (BaseModelType,ModelFormat,@@ -350,7 +352,7 @@ def test_start_removes_stale_but_preserves_live_install_claims(delete_active_install_sentinel(live_root)-def test_start_preserves_claim_for_small_process_start_time_drift(+def test_start_preserves_ambiguous_legacy_claim_after_large_start_time_drift(mm2_installer: ModelInstallServiceBase,mm2_app_config: InvokeAIAppConfig,monkeypatch: pytest.MonkeyPatch,@@ -383,6 +385,483 @@ def test_start_preserves_claim_for_small_process_start_time_drift(observed_start_time[0] = 102.0mm2_installer._remove_stale_install_source_claims()+ assert claim.exists()++[email protected](platform.system() != "Linux", reason="Linux process start ticks are used for stable claim identity")+def test_start_reclaims_linux_claim_when_pid_has_been_reused(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import os++ from invokeai.app.services.model_install import model_install_common+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "claim-pid-reuse"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ current_identity = model_install_common._linux_process_start_identity(os.getpid())+ boot_id = current_identity.rsplit(":", 1)[0]+ claim.write_text(f"{os.getpid()} 100.0 {boot_id}:111\n", encoding="ascii")++ class LiveProcess:+ def __init__(self, _pid: int) -> None:+ pass++ def status(self) -> str:+ return model_install_default.psutil.STATUS_RUNNING++ monkeypatch.setattr(model_install_default.psutil, "Process", LiveProcess)+ monkeypatch.setattr(model_install_default, "_linux_process_start_identity", lambda _pid: f"{boot_id}:222")++ mm2_installer._remove_stale_install_source_claims()++ assert not claim.exists()+++def test_start_preserves_claim_while_its_payload_is_being_published(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install import model_install_common+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "claim-being-published"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim_created = threading.Event()+ release_publish = threading.Event()+ creator_errors: list[Exception] = []+ real_process = model_install_common.psutil.Process++ class BlockedProcess:+ def __init__(self) -> None:+ self._process = real_process()++ @property+ def pid(self) -> int:+ return self._process.pid++ def create_time(self) -> float:+ if threading.current_thread().name == "blocked-claim-creator":+ claim_created.set()+ assert release_publish.wait(timeout=5)+ return self._process.create_time()++ monkeypatch.setattr(model_install_common.psutil, "Process", BlockedProcess)++ def create_claim() -> None:+ try:+ create_active_install_sentinel(root)+ except Exception as e:+ creator_errors.append(e)++ creator = threading.Thread(target=create_claim, name="blocked-claim-creator")+ creator.start()+ try:+ assert claim_created.wait(timeout=5)+ assert not claim.exists()+ mm2_installer._remove_stale_install_source_claims()+ create_active_install_sentinel(root)+ assert len(claim.read_text(encoding="ascii").split()) >= 2+ finally:+ release_publish.set()+ creator.join(timeout=10)++ assert not creator.is_alive()+ assert len(creator_errors) == 1+ assert isinstance(creator_errors[0], FileExistsError)+ assert claim.read_text(encoding="ascii").split()+ claim.unlink(missing_ok=True)+++def test_claim_creation_interrupted_before_publication_leaves_no_final_sidecar(+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install import model_install_common+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ root = mm2_app_config.models_path / "interrupted-claim-publication"+ root.mkdir()+ claim = active_install_sentinel_path(root)++ def exit_before_publication() -> None:+ raise SystemExit("simulated process exit before claim publication")++ monkeypatch.setattr(model_install_common.psutil, "Process", exit_before_publication)++ with pytest.raises(SystemExit, match="simulated process exit"):+ create_active_install_sentinel(root)++ assert not claim.exists()+++ "payload",+ [+ "2147483647 100.0 linux:malformed\n",+ "2147483647 100.0 windows:unsupported\n",+ "not-a-pid 100.0 linux:11111111-1111-1111-1111-111111111111:1\n",+ "2147483647 nan linux:11111111-1111-1111-1111-111111111111:1\n",+ ],+)+def test_startup_preserves_malformed_claim_before_inspecting_owner(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ payload: str,+) -> None:+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "malformed-claim"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text(payload, encoding="ascii")+ inspected_pids: list[int] = []++ def inspect_process(pid: int) -> Any:+ inspected_pids.append(pid)+ raise model_install_default.psutil.NoSuchProcess(pid)++ monkeypatch.setattr(model_install_default.psutil, "Process", inspect_process)++ mm2_installer._remove_stale_install_source_claims()++ assert claim.exists()+ assert inspected_pids == []+ assert "could not verify" in caplog.text.lower()+++def test_claim_publication_survives_temporary_unlink_failure(+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install import model_install_common+ from invokeai.app.services.model_install.model_install_common import delete_active_install_sentinel++ root = mm2_app_config.models_path / "claim-temp-cleanup-failure"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ temp_paths: list[Path] = []+ real_link = model_install_common.os.link+ real_unlink = Path.unlink++ def publish(temp_path: Path, claim_path: Path) -> None:+ temp_paths.append(Path(temp_path))+ real_link(temp_path, claim_path)++ def fail_temp_unlink(path: Path, *args: Any, **kwargs: Any) -> None:+ if temp_paths and path == temp_paths[0]:+ raise OSError("simulated temporary sidecar cleanup failure")+ real_unlink(path, *args, **kwargs)++ try:+ with monkeypatch.context() as patch:+ patch.setattr(model_install_common.os, "link", publish)+ patch.setattr(Path, "unlink", fail_temp_unlink)+ create_active_install_sentinel(root)+ assert claim.exists()+ assert len(claim.read_text(encoding="ascii").split()) >= 2+ delete_active_install_sentinel(root)+ assert not claim.exists()+ finally:+ for temp_path in temp_paths:+ real_unlink(temp_path, missing_ok=True)+++def test_startup_bounds_unknown_claim_diagnostics(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ caplog: pytest.LogCaptureFixture,+) -> None:+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ claims = []+ for index in range(model_install_default.MAX_ACTIVE_CLAIM_DIAGNOSTICS + 2):+ root = mm2_app_config.models_path / f"malformed-claim-{index}"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text("unknown owner", encoding="ascii")+ claims.append(claim)++ mm2_installer._remove_stale_install_source_claims()++ claim_warnings = [+ record.message for record in caplog.records if "Could not verify active install claim" in record.message+ ]+ assert len(claim_warnings) == model_install_default.MAX_ACTIVE_CLAIM_DIAGNOSTICS+ assert any("2 additional active install claims" in record.message for record in caplog.records)+ assert all(claim.exists() for claim in claims)+++def test_startup_does_not_delete_replacement_claim_after_process_inspection(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "replaced-claim"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text("2147483647 1.0\n", encoding="ascii")+ replacement = "2147483646 2.0\n"+ replacement_path = root / "replacement-claim"+ replacement_path.write_text(replacement, encoding="ascii")++ class DeadProcess:+ def __init__(self, _pid: int) -> None:+ claim.unlink()+ replacement_path.replace(claim)+ raise model_install_default.psutil.NoSuchProcess(pid=_pid)++ monkeypatch.setattr(model_install_default.psutil, "Process", DeadProcess)++ mm2_installer._remove_stale_install_source_claims()++ assert claim.read_text(encoding="ascii") == replacement+++def test_serialized_stale_claim_scans_preserve_a_claim_created_after_reap(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import (+ active_install_sentinel_path,+ create_active_install_sentinel,+ )++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "serialized-claim-scan"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text("2147483647 1.0\n", encoding="ascii")+ final_unlink_started = threading.Event()+ release_first_unlink = threading.Event()+ first_claim_unlinked = threading.Event()+ release_first_scan = threading.Event()+ second_scan_waiting_for_lock = threading.Event()+ second_scan_finished = threading.Event()+ scan_errors: list[Exception] = []+ condition = threading.Condition()+ real_unlink = Path.unlink++ def signal(event: threading.Event) -> None:+ event.set()+ with condition:+ condition.notify_all()++ def blocked_unlink(path: Path, *args: Any, **kwargs: Any) -> None:+ if path == claim and threading.current_thread().name == "first-stale-scan":+ signal(final_unlink_started)+ assert release_first_unlink.wait(timeout=5)+ real_unlink(path, *args, **kwargs)+ signal(first_claim_unlinked)+ assert release_first_scan.wait(timeout=5)+ return+ real_unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", blocked_unlink)+ real_claim_scan_lock = getattr(model_install_default, "active_install_claim_scan_lock", None)+ if real_claim_scan_lock is not None:++ class ObservedClaimScanLock:+ def __init__(self, models_path: Path) -> None:+ self._lock = real_claim_scan_lock(models_path)++ def __enter__(self) -> "ObservedClaimScanLock":+ if threading.current_thread().name == "second-stale-scan":+ signal(second_scan_waiting_for_lock)+ self._lock.__enter__()+ return self++ def __exit__(self, *args: Any) -> Any:+ return self._lock.__exit__(*args)++ monkeypatch.setattr(model_install_default, "active_install_claim_scan_lock", ObservedClaimScanLock)++ def run_scan() -> None:+ try:+ mm2_installer._remove_stale_install_source_claims()+ except Exception as e:+ scan_errors.append(e)++ def run_second_scan() -> None:+ run_scan()+ signal(second_scan_finished)++ first_scan = threading.Thread(target=run_scan, name="first-stale-scan")+ second_scan = threading.Thread(target=run_second_scan, name="second-stale-scan")+ first_scan.start()+ try:+ assert final_unlink_started.wait(timeout=5)+ second_scan.start()+ with condition:+ assert condition.wait_for(+ lambda: second_scan_finished.is_set() or second_scan_waiting_for_lock.is_set(), timeout=5+ )++ claim_recreated_before_first_scan_released = second_scan_finished.is_set()+ if claim_recreated_before_first_scan_released:+ # The uncoordinated implementation reaps the observed claim while scanner A still holds its stale view.+ create_active_install_sentinel(root)+ release_first_unlink.set()+ assert first_claim_unlinked.wait(timeout=5)+ else:+ # A owns the scan lock. Let it unlink, publish a new owner before releasing that lock, then let B scan it.+ release_first_unlink.set()+ assert first_claim_unlinked.wait(timeout=5)+ create_active_install_sentinel(root)++ release_first_scan.set()+ first_scan.join(timeout=10)+ second_scan.join(timeout=10)+ assert not first_scan.is_alive()+ assert not second_scan.is_alive()+ assert scan_errors == []++ assert claim.read_text(encoding="ascii").split()[0] == str(model_install_default.psutil.Process().pid)+ mm2_installer._remove_stale_install_source_claims()+ assert claim.exists()+ finally:+ release_first_unlink.set()+ release_first_scan.set()+ first_scan.join(timeout=10)+ if second_scan.ident is not None:+ second_scan.join(timeout=10)+ claim.unlink(missing_ok=True)+++def test_stale_claim_scan_lock_is_released_after_inspection_error(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.model_install.model_install_common import (+ INSTALL_ACTIVE_SCAN_LOCK,+ active_install_sentinel_path,+ )++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "claim-scan-lock-lifecycle"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text("2147483647 1.0\n", encoding="ascii")+ real_process = model_install_default.psutil.Process++ def fail_process_inspection(_pid: int) -> None:+ raise RuntimeError("simulated process inspection failure")++ monkeypatch.setattr(model_install_default.psutil, "Process", fail_process_inspection)+ with pytest.raises(RuntimeError, match="simulated process inspection failure"):+ mm2_installer._remove_stale_install_source_claims()++ lock_path = mm2_app_config.models_path / INSTALL_ACTIVE_SCAN_LOCK+ assert lock_path.exists()+ monkeypatch.setattr(model_install_default.psutil, "Process", real_process)+ scan_finished = threading.Event()++ def run_scan() -> None:+ try:+ mm2_installer._remove_stale_install_source_claims()+ finally:+ scan_finished.set()++ scan_thread = threading.Thread(target=run_scan)+ scan_thread.start()+ scan_thread.join(timeout=10)++ assert not scan_thread.is_alive()+ assert scan_finished.is_set()+ assert not claim.exists()+ assert lock_path.exists()+++def test_windows_claim_scan_lock_retries_past_crt_finite_lock_attempts(+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import sys++ from invokeai.app.services.model_install import model_install_common++ models_path = mm2_app_config.models_path+ calls: list[int] = []++ class ContendedWindowsLock:+ LK_NBLCK = 1+ LK_UNLCK = 2++ @staticmethod+ def locking(_fd: int, mode: int, _nbytes: int) -> None:+ calls.append(mode)+ if mode == ContendedWindowsLock.LK_NBLCK and calls.count(ContendedWindowsLock.LK_NBLCK) <= 12:+ raise OSError(errno.EACCES, "simulated lock contention")++ monkeypatch.setattr(model_install_common.os, "name", "nt")+ monkeypatch.setitem(sys.modules, "msvcrt", ContendedWindowsLock)+ monkeypatch.setattr(model_install_common.time, "sleep", lambda _seconds: None)++ with model_install_common.active_install_claim_scan_lock(models_path):+ pass++ assert calls == [*([ContendedWindowsLock.LK_NBLCK] * 13), ContendedWindowsLock.LK_UNLCK]+++def test_startup_preserves_access_denied_claim_then_reclaims_confirmed_dead_owner(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ from invokeai.app.services.model_install.model_install_common import active_install_sentinel_path++ assert isinstance(mm2_installer, ModelInstallService)+ root = mm2_app_config.models_path / "inaccessible-claim"+ root.mkdir()+ claim = active_install_sentinel_path(root)+ claim.write_text("12345 100.0\n", encoding="ascii")++ class InaccessibleProcess:+ def __init__(self, _pid: int) -> None:+ raise model_install_default.psutil.AccessDenied(pid=_pid)++ monkeypatch.setattr(model_install_default.psutil, "Process", InaccessibleProcess)+ mm2_installer._remove_stale_install_source_claims()+ assert claim.exists()+ assert "could not verify" in caplog.text.lower()++ class LiveProcess:+ def __init__(self, _pid: int) -> None:+ pass++ def status(self) -> str:+ return model_install_default.psutil.STATUS_RUNNING++ def create_time(self) -> float:+ return 100.0++ monkeypatch.setattr(model_install_default.psutil, "Process", LiveProcess)+ mm2_installer._remove_stale_install_source_claims()+ assert claim.exists()++ class DeadProcess:+ def __init__(self, _pid: int) -> None:+ raise model_install_default.psutil.NoSuchProcess(pid=_pid)++ monkeypatch.setattr(model_install_default.psutil, "Process", DeadProcess)+ mm2_installer._remove_stale_install_source_claims()assert not claim.exists()@@ -472,6 +951,105 @@ def test_rollback_restores_source_across_filesystems_without_overwriting(assert original.read_bytes() == b"model weights"+def test_startup_cleanup_preserves_interrupted_exdev_restore_artifacts(+ tmp_path: Path,+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+) -> None:+ """Restore scratch has no durable owner record, so startup must leave it for manual inspection."""+ external_source_root = tmp_path / "external-source"+ managed_source_root = mm2_app_config.models_path / "local-source"+ managed_copy_root = mm2_app_config.models_path / "managed-copy"+ external_source_root.mkdir()+ managed_source_root.mkdir()+ managed_copy_root.mkdir()++ artifacts: list[tuple[Path, bytes]] = []+ for source_root in (external_source_root, managed_source_root):+ source = source_root / "model"+ source.write_bytes(b"original source")++ # A hard stop during copy can leave partial bytes, or a complete copy before publication.+ for name, content in (("partial", b"partial"), ("complete", b"complete copy"), ("lookalike", b"unknown owner")):+ scratch = source_root / f".model.restore-{name}-{uuid.uuid4().hex}"+ staged_copy = scratch / "restored"+ staged_copy.parent.mkdir()+ staged_copy.write_bytes(content)+ artifacts.append((staged_copy, content))++ # Publication precedes deletion of the managed copy. A crash can therefore leave both copies.+ managed_copy = managed_copy_root / source_root.name+ managed_copy.write_bytes(b"published copy")+ published = source_root / "published-model"+ published.write_bytes(b"published copy")+ artifacts.extend(((managed_copy, b"published copy"), (published, b"published copy")))++ mm2_installer._remove_dangling_install_dirs()++ assert all(path.read_bytes() == expected for path, expected in artifacts)+++def test_startup_cleanup_preserves_live_exdev_restore_lookalike(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ source_root = mm2_app_config.models_path / "local-source"+ managed_copy_root = mm2_app_config.models_path / "managed-copy"+ source_root.mkdir()+ managed_copy_root.mkdir()+ original = source_root / "model"+ moved = managed_copy_root / "model"+ moved.write_bytes(b"managed copy")++ copy_started = threading.Event()+ finish_copy = threading.Event()+ real_copy2 = shutil.copy2+ real_rename_noreplace = ModelInstallService._rename_noreplace++ def pause_copy(src: Path, dst: Path) -> Path:+ real_copy2(src, dst)+ copy_started.set()+ assert finish_copy.wait(timeout=10)+ return dst++ def raise_exdev_for_managed_copy(src: Path, dst: Path) -> None:+ if src == moved:+ raise OSError(errno.EXDEV, "cross-device link")+ real_rename_noreplace(src, dst)++ monkeypatch.setattr(model_install_default, "copy2", pause_copy)+ monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(raise_exdev_for_managed_copy))+ errors: list[Exception] = []++ def restore() -> None:+ try:+ ModelInstallService._restore_moved_path(moved, original)+ except Exception as error:+ errors.append(error)++ restore_thread = threading.Thread(target=restore)+ restore_thread.start()+ try:+ assert copy_started.wait(timeout=10)+ staging_dirs = list(source_root.glob(".model.restore-*"))+ assert len(staging_dirs) == 1+ staged_copy = staging_dirs[0] / "restored"++ mm2_installer._remove_dangling_install_dirs()++ assert staged_copy.read_bytes() == b"managed copy"+ assert moved.read_bytes() == b"managed copy"+ finally:+ finish_copy.set()+ restore_thread.join(timeout=10)++ assert not restore_thread.is_alive()+ assert errors == []+ assert original.read_bytes() == b"managed copy"+ assert not moved.exists()++def test_directory_install_retries_windows_move_failures(mm2_installer: ModelInstallServiceBase,diffusers_dir: Path,@@ -713,6 +1291,65 @@ def test_directory_install_rollback_race_preserves_both_source_artifacts(assert preserved[0].read_bytes() == original_bytes+ "unsupported_errno",+ [None, errno.ENOSYS, errno.EOPNOTSUPP],+ ids=["primitive-unavailable", "not-implemented", "operation-unsupported"],+)+def test_directory_install_preserves_recreated_source_when_no_replace_rename_fails(+ mm2_installer: ModelInstallServiceBase,+ diffusers_dir: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+ unsupported_errno: int | None,+) -> None:+ real_iterdir = Path.iterdir++ def files_first(path: Path):+ items = real_iterdir(path)+ if path == diffusers_dir:+ return iter(sorted(items, key=lambda item: (not item.is_file(), item.name)))+ return items++ monkeypatch.setattr(Path, "iterdir", files_first)+ first_item = next(path for path in diffusers_dir.iterdir() if path.is_file())+ locked_item = list(diffusers_dir.iterdir())[-1]+ original_bytes = first_item.read_bytes()+ existing_paths = set(mm2_app_config.models_path.iterdir())++ def fail_later_move(src: Path, dst: Path):+ if src == locked_item:+ raise PermissionError("later source remains locked")+ return shutil.move(src, dst)++ def fail_no_replace_after_source_recreation(src: Path, dst: Path) -> None:+ assert src.name == first_item.name+ assert src.parent != diffusers_dir+ assert dst == first_item+ dst.write_bytes(b"concurrently recreated source")+ if unsupported_errno is None:+ raise OSError("atomic no-replace rename is unavailable")+ raise OSError(unsupported_errno, "atomic no-replace rename unsupported", str(dst))++ _fake_move(monkeypatch, fail_later_move)+ monkeypatch.setattr(+ ModelInstallService,+ "_rename_noreplace",+ staticmethod(fail_no_replace_after_source_recreation),+ )++ with pytest.raises(InstallRecoveryRequiredError, match="recovery required") as exc_info:+ mm2_installer.install_path(diffusers_dir)++ assert "atomic no-replace rename" in str(exc_info.value)+ assert first_item.read_bytes() == b"concurrently recreated source"+ recovery_dirs = [path for path in set(mm2_app_config.models_path.iterdir()) - existing_paths if path.is_dir()]+ assert len(recovery_dirs) == 1+ recovery_destination = recovery_dirs[0]+ assert mm2_installer._has_recovery_sentinel(recovery_destination)+ assert (recovery_destination / first_item.name).read_bytes() == original_bytes++def test_directory_install_does_not_retry_partial_copy(mm2_installer: ModelInstallServiceBase,diffusers_dir: Path,@@ -827,10 +1464,13 @@ def test_remote_install_recovery_survives_cleanup_and_restart(monkeypatch.setattr(mm2_installer, "_write_install_marker", fail_recovery_marker)monkeypatch.setattr(mm2_installer, "_delete_install_marker", assert_recovery_state_before_marker_delete)+ mm2_installer._install_jobs.append(job)mm2_installer._put_in_queue(job)mm2_installer.wait_for_job(job, timeout=10)assert job.errored+ assert job.error+ assert job in mm2_installer.list_jobs()assert mm2_installer._has_recovery_sentinel(tmpdir)assert INSTALL_RECOVERY_SENTINEL not in {path.name for path in real_iterdir(tmpdir)}assert {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files@@ -845,6 +1485,12 @@ def test_remote_install_recovery_survives_cleanup_and_restart(assert mm2_installer._has_recovery_sentinel(recovery_dir)assert (recovery_dir / failure_file.name).read_bytes() == b"unrecognized partial destination bytes"+ # Pruning removes terminal job diagnostics from the live service, but it must not remove the recovery roots.+ mm2_installer.prune_jobs()+ assert job not in mm2_installer.list_jobs()+ assert tmpdir.exists()+ assert recovery_dir.exists()+dangling_tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}dangling-{uuid.uuid4().hex}"dangling_tmpdir.mkdir()(dangling_tmpdir / "ordinary.tmp").write_bytes(b"discard me")@@ -855,15 +1501,17 @@ def test_remote_install_recovery_survives_cleanup_and_restart(download_queue=mm2_download_queue,session=mm2_session,)- restarted_installer._remove_dangling_install_dirs()- restarted_installer._restore_incomplete_installs()-- assert tmpdir.exists()- assert {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files- assert recovery_dir.exists()- assert (recovery_dir / failure_file.name).read_bytes() == b"unrecognized partial destination bytes"- assert dangling_tmpdir.exists() is False- assert restarted_installer.list_jobs() == []+ restarted_installer.start()+ try:+ assert restarted_installer._wait_for_restore_complete(timeout=10)+ assert tmpdir.exists()+ assert {path.name: path.read_bytes() for path in real_iterdir(tmpdir) if path.is_file()} == source_files+ assert recovery_dir.exists()+ assert (recovery_dir / failure_file.name).read_bytes() == b"unrecognized partial destination bytes"+ assert dangling_tmpdir.exists() is False+ assert restarted_installer.list_jobs() == []+ finally:+ restarted_installer.stop()shutil.rmtree(tmpdir)@@ -1001,6 +1649,98 @@ def test_restore_metadata_timeout_preserves_partial_download_for_retry(assert active_install_sentinel_path(tmpdir).exists()[email protected]("status_code", [429, 503])+def test_restore_model_info_http_error_preserves_partial_download_for_retry(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+ status_code: int,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ installer = mm2_installer+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-model-info-{uuid.uuid4().hex}"+ partial_path = tmpdir / "text_encoder" / "model.safetensors.downloading"+ partial_path.parent.mkdir(parents=True)+ partial_path.write_bytes(b"partial model")+ source = HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default)+ weights_url = "https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/text_encoder/model.safetensors"+ resume_metadata = {+ weights_url: {+ "url": weights_url,+ "canonical_url": weights_url,+ "etag": "retained-etag",+ "last_modified": "retained-last-modified",+ "expected_total_bytes": 12,+ "final_url": weights_url,+ "download_path": partial_path.as_posix(),+ "resume_required": True,+ "resume_message": "Resuming previous download.",+ }+ }+ job = ModelInstallJob(+ id=9907,+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.DOWNLOADING,+ )+ job._install_tmpdir = tmpdir+ job._resume_metadata = resume_metadata+ installer._write_install_marker(job, status=InstallStatus.DOWNLOADING)++ api_url = "https://huggingface.co/api/models/stabilityai/sdxl-turbo"+ api_body = b'{"id":"stabilityai/sdxl-turbo","siblings":[{"rfilename":"text_encoder/model.safetensors","size":12}]}'+ real_get = installer._session.get+ api_attempts = 0++ def _response(url: str, code: int, body: bytes = b"") -> Response:+ response = Response()+ response.status_code = code+ response.url = url+ response._content = body+ response.request = Request("GET", url).prepare()+ return response++ def _get(url: str, *args: Any, **kwargs: Any) -> Response:+ nonlocal api_attempts+ if str(url) == api_url:+ api_attempts += 1+ if api_attempts == 1:+ return _response(api_url, status_code)+ return _response(api_url, 200, api_body)+ return real_get(url, *args, **kwargs)++ assert installer._session is not None+ monkeypatch.setattr(installer._session, "get", _get)++ installer._restore_incomplete_installs()++ restored_job = installer.get_job_by_source(source)[-1]+ assert restored_job.status == InstallStatus.PAUSED+ assert partial_path.read_bytes() == b"partial model"+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None+ assert marker["status"] == InstallStatus.PAUSED.value+ assert marker["files"][0]["etag"] == "retained-etag"+ assert active_install_sentinel_path(tmpdir).exists()++ queued: dict[str, Any] = {}++ def _capture_download(**kwargs: Any) -> ModelInstallJob:+ queued.update(kwargs)+ return restored_job++ monkeypatch.setattr(installer._session, "get", _get)+ monkeypatch.setattr(installer, "_enqueue_remote_download", _capture_download)+ installer.resume_job(restored_job)++ assert api_attempts == 2+ assert queued["resume_metadata"] == restored_job._resume_metadata+ assert queued["resume_metadata"][weights_url]["download_path"] == partial_path.as_posix()+ assert partial_path.read_bytes() == b"partial model"++def test_queue_rejection_during_shutdown_preserves_completed_download(mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig) -> None:@@ -1075,6 +1815,231 @@ def test_stop_during_startup_restore_preserves_the_current_download(assert mm2_installer._restore_completed_event.is_set()+def test_metadata_chain_falls_back_to_default_revision_after_stop_requested(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The metadata call chain has no stop checkpoint before the variant fallback request."""+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ assert installer._wait_for_restore_complete(timeout=10)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restore-stop-metadata-{uuid.uuid4().hex}"+ partial_path = tmpdir / "text_encoder" / "model.safetensors.downloading"+ partial_path.parent.mkdir(parents=True)+ partial_path.write_bytes(b"partial model")+ source = HFModelSource(repo_id="org/repo", variant=ModelRepoVariant.FP16)++ metadata_started = threading.Event()+ release_variant_request = threading.Event()+ requests: list[tuple[str, float]] = []+ metadata_results: list[tuple[list[RemoteModelFile], Any]] = []+ metadata_errors: list[BaseException] = []++ def response(status_code: int, content: bytes = b"", headers: dict[str, str] | None = None) -> Response:+ result = Response()+ result.status_code = status_code+ result.url = "https://huggingface.co/api/models/org/repo"+ result._content = content+ result.headers.update(headers or {})+ result.request = Request("GET", result.url).prepare()+ return result++ def scripted_get(url: str, *, params: dict[str, str] | None = None, timeout: float) -> Response:+ requests.append((url, timeout))+ if len(requests) == 1:+ metadata_started.set()+ assert release_variant_request.wait(timeout=5)+ return response(404, headers={"X-Error-Code": "RevisionNotFound"})+ if len(requests) == 2:+ assert installer._stop_event.is_set()+ return response(+ 200,+ content=(b'{"id":"org/repo","siblings":[{"rfilename":"model.safetensors","size":10}]}'),+ )+ raise AssertionError(f"Unexpected metadata request: {url}")++ assert installer._session is not None+ monkeypatch.setattr(installer._session, "get", scripted_get)++ def fetch_metadata() -> None:+ try:+ metadata_results.append(installer._remote_files_from_source(source))+ except BaseException as error:+ metadata_errors.append(error)++ metadata_thread = threading.Thread(target=fetch_metadata)+ metadata_thread.start()+ assert metadata_started.wait(timeout=5)++ try:+ installer._stop_event.set()+ finally:+ release_variant_request.set()+ metadata_thread.join(timeout=10)++ assert not metadata_thread.is_alive()+ assert metadata_errors == []+ assert len(metadata_results) == 1+ assert len(requests) == 2+ assert "/revision/" in requests[0][0]+ assert "/revision/" not in requests[1][0]+ assert all(timeout == HF_METADATA_REQUEST_TIMEOUT_SECONDS for _, timeout in requests)+ assert partial_path.read_bytes() == b"partial model"+++def test_shutdown_restore_policy_persists_current_and_resumes_unvisited_on_next_start(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ mm2_session: Any,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Shutdown pauses the current restore, leaves unvisited markers alone, and startup resumes only non-paused."""+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ assert installer._wait_for_restore_complete(timeout=10)++ markers: dict[Path, tuple[InstallStatus, bytes]] = {}+ for name, status in (+ ("restore-policy-a", InstallStatus.DOWNLOADING),+ ("restore-policy-b", InstallStatus.DOWNLOADING),+ ("restore-policy-user-paused", InstallStatus.PAUSED),+ ):+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}{name}-{uuid.uuid4().hex}"+ partial_path = tmpdir / "weights.safetensors.downloading"+ tmpdir.mkdir()+ partial_path.write_bytes(name.encode())+ source = URLModelSource(url=Url(f"https://example.com/{name}.safetensors"))+ job = ModelInstallJob(+ id=9910 + len(markers),+ source=source,+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=status,+ )+ job._install_tmpdir = tmpdir+ installer._write_install_marker(job, status=status)+ markers[tmpdir] = (status, partial_path.read_bytes())++ ordered_active_markers = [+ path+ for path in mm2_app_config.models_path.glob(f"{TMPDIR_PREFIX}*")+ if path in markers and markers[path][0] != InstallStatus.PAUSED+ ]+ assert len(ordered_active_markers) == 2+ interrupted_tmpdir = ordered_active_markers[0]+ interrupted_restore_started = threading.Event()+ original_resume = installer._resume_remote_download++ def interrupt_first_restore(job: ModelInstallJob, *, operation_reserved: bool = False) -> None:+ if job._install_tmpdir == interrupted_tmpdir:+ interrupted_restore_started.set()+ assert installer._stop_event.wait(timeout=5)+ original_resume(job, operation_reserved=operation_reserved)++ monkeypatch.setattr(installer, "_resume_remote_download", interrupt_first_restore)+ installer._restore_incomplete_installs_async()+ assert interrupted_restore_started.wait(timeout=5)+ installer.stop()++ for tmpdir, (original_status, expected_bytes) in markers.items():+ marker = installer._read_install_marker(tmpdir)+ assert marker is not None+ assert (tmpdir / "weights.safetensors.downloading").read_bytes() == expected_bytes+ assert not active_install_sentinel_path(tmpdir).exists()+ if tmpdir == interrupted_tmpdir:+ assert marker["status"] == InstallStatus.PAUSED.value+ else:+ assert marker["status"] == original_status.value++ next_installer = ModelInstallService(+ app_config=mm2_app_config,+ record_store=installer.record_store,+ download_queue=installer._download_queue,+ event_bus=installer.event_bus,+ session=mm2_session,+ )+ resumed_sources: list[str] = []++ def observe_resume(job: ModelInstallJob, *, operation_reserved: bool = False) -> None:+ resumed_sources.append(str(job.source))++ monkeypatch.setattr(next_installer, "_resume_remote_download", observe_resume)+ next_installer.start()+ try:+ assert next_installer._wait_for_restore_complete(timeout=10)+ explicitly_paused_tmpdir = next(path for path, (status, _) in markers.items() if status == InstallStatus.PAUSED)+ unvisited_tmpdir = next(path for path in ordered_active_markers if path != interrupted_tmpdir)+ assert resumed_sources == [json.loads((unvisited_tmpdir / INSTALL_MARKER_FILENAME).read_text())["source"]]+ restored = {str(job.source): job for job in next_installer.list_jobs()}+ paused_source = json.loads((explicitly_paused_tmpdir / INSTALL_MARKER_FILENAME).read_text())["source"]+ interrupted_source = json.loads((interrupted_tmpdir / INSTALL_MARKER_FILENAME).read_text())["source"]+ assert restored[paused_source].status == InstallStatus.PAUSED+ assert restored[interrupted_source].status == InstallStatus.PAUSED+ assert next_installer._read_install_marker(explicitly_paused_tmpdir)["status"] == InstallStatus.PAUSED.value+ assert next_installer._read_install_marker(interrupted_tmpdir)["status"] == InstallStatus.PAUSED.value+ assert next_installer._read_install_marker(unvisited_tmpdir)["status"] == InstallStatus.DOWNLOADING.value+ for tmpdir, (_, expected_bytes) in markers.items():+ assert (tmpdir / "weights.safetensors.downloading").read_bytes() == expected_bytes+ finally:+ next_installer.stop()++[email protected](timeout=30, method="thread")+def test_stop_waits_for_startup_restore_exception_handler_before_pending_cleanup(+ mm2_installer: ModelInstallServiceBase,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ installer = mm2_installer+ handler_started = threading.Event()+ release_handler = threading.Event()+ restore_join_started = threading.Event()+ cleanup_started = threading.Event()+ stop_finished = threading.Event()+ real_error = installer._logger.error++ def _fail_restore() -> None:+ raise RuntimeError("restore failed")++ def _blocked_error(message: str, *args: Any, **kwargs: Any) -> None:+ handler_started.set()+ assert release_handler.wait(timeout=5)+ real_error(message, *args, **kwargs)++ def _observe_cleanup() -> None:+ cleanup_started.set()++ monkeypatch.setattr(installer, "_restore_incomplete_installs", _fail_restore)+ monkeypatch.setattr(installer._logger, "error", _blocked_error)+ monkeypatch.setattr(installer, "_clear_pending_jobs", _observe_cleanup)++ installer._restore_incomplete_installs_async()+ restore_thread = installer._restore_thread+ assert restore_thread is not None+ real_join = restore_thread.join++ def _observe_join(timeout: float | None = None) -> None:+ restore_join_started.set()+ real_join(timeout)++ monkeypatch.setattr(restore_thread, "join", _observe_join)+ try:+ assert handler_started.wait(timeout=5)+ stop_thread = threading.Thread(target=lambda: (installer.stop(), stop_finished.set()))+ stop_thread.start()+ assert restore_join_started.wait(timeout=5)+ assert not cleanup_started.is_set()+ assert not stop_finished.is_set()+ release_handler.set()+ assert cleanup_started.wait(timeout=5)+ assert stop_finished.wait(timeout=5)+ stop_thread.join(timeout=5)+ assert not stop_thread.is_alive()+ finally:+ release_handler.set()++@pytest.mark.parametrize("status", [InstallStatus.PAUSED, InstallStatus.DOWNLOADS_DONE])def test_stop_preserves_restored_downloads_without_a_multifile_job(mm2_installer: ModelInstallServiceBase,@@ -1444,6 +2409,80 @@ def test_install_registration_failure_preserves_complete_recoverable_files(assert mm2_installer.record_store.get_model(recovered_key).key == recovered_key+ ("failure_target", "error_number"),+ [+ pytest.param(+ "directory",+ errno.EINVAL,+ marks=pytest.mark.skipif(+ model_install_default.os.name == "nt", reason="installer skips directory fsync on Windows"+ ),+ ),+ ("file", errno.EIO),+ ],+)+def test_install_fsync_failure_preserves_source_before_transfer(+ failure_target: str,+ error_number: int,+ mm2_installer: ModelInstallServiceBase,+ embedding_file: Path,+ mm2_app_config: InvokeAIAppConfig,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ source_bytes = embedding_file.read_bytes()+ destination_key = f"fsync-{failure_target}"+ real_fsync = model_install_default.os.fsync++ def failing_fsync(fd: int) -> None:+ is_directory = stat.S_ISDIR(model_install_default.os.fstat(fd).st_mode)+ if (failure_target == "directory" and is_directory) or (failure_target == "file" and not is_directory):+ raise OSError(error_number, "scripted fsync failure")+ real_fsync(fd)++ monkeypatch.setattr(model_install_default.os, "fsync", failing_fsync)++ with pytest.raises(OSError) as error:+ mm2_installer.install_path(embedding_file, ModelRecordChanges(key=destination_key))++ destination = mm2_app_config.models_path / destination_key+ assert error.value.errno == error_number+ assert embedding_file.read_bytes() == source_bytes+ assert not mm2_installer.record_store.exists(destination_key)+ assert not destination.exists()+ assert not mm2_installer._recovery_sentinel_path(destination).exists()++[email protected]("error_number", [errno.EINVAL, errno.EIO])[email protected](model_install_default.os.name == "nt", reason="installer skips directory fsync on Windows")+def test_delete_recovery_sentinel_logs_directory_fsync_failure(+ error_number: int,+ mm2_installer: ModelInstallServiceBase,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ sentinel_root = tmp_path / "recovery-root"+ sentinel_root.mkdir()+ sentinel = mm2_installer._recovery_sentinel_path(sentinel_root)+ sentinel.write_text("preserve until cleanup", encoding="utf-8")+ real_fsync = model_install_default.os.fsync++ def failing_directory_fsync(fd: int) -> None:+ if stat.S_ISDIR(model_install_default.os.fstat(fd).st_mode):+ raise OSError(error_number, "scripted directory fsync failure")+ real_fsync(fd)++ monkeypatch.setattr(model_install_default.os, "fsync", failing_directory_fsync)++ mm2_installer._delete_recovery_sentinel(sentinel_root)++ assert not sentinel.exists()+ assert "Failed to remove install recovery sentinel" in caplog.text++def test_rename(mm2_installer: ModelInstallServiceBase, embedding_file: Path, mm2_app_config: InvokeAIAppConfig) -> None:@@ -2068,14 +3107,22 @@ def test_prune_jobs_rebind_preserves_existing_iterators()for index in range(3)]- mm2_installer._install_jobs.extend(jobs)+ active_job = ModelInstallJob(+ id=99010,+ source=URLModelSource(url=Url("https://www.test.foo/download/active.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=mm2_app_config.models_path,+ status=InstallStatus.RUNNING,+ )+ mm2_installer._install_jobs.extend([*jobs, active_job])existing_iterator = iter(mm2_installer.list_jobs())assert next(existing_iterator) is jobs[0]mm2_installer.prune_jobs()- assert list(existing_iterator) == jobs[1:]+ assert list(existing_iterator) == [*jobs[1:], active_job]assert all(job not in mm2_installer.list_jobs() for job in jobs)+ assert mm2_installer.list_jobs() == [active_job]@pytest.mark.timeout(timeout=30, method="thread")diff --git a/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.pyindex f15714d292..41dc89a99a 100644--- a/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py+++ b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py@@ -14,7 +14,7 @@ from pathlib import Pathimport pytestfrom invokeai.app.services.config.config_default import InvokeAIAppConfig-from invokeai.app.services.model_install.model_install_common import INSTALL_RECOVERY_SENTINEL+from invokeai.app.services.model_install.model_install_common import INSTALL_ACTIVE_SENTINEL, INSTALL_RECOVERY_SENTINELfrom invokeai.app.services.model_records import ModelRecordServiceSQLfrom invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelsServicefrom invokeai.app.services.shared.database.database import Database@@ -159,6 +159,24 @@ def test_install_recovery_root_is_not_reported_or_deleted(assert sentinel.exists()+def test_empty_active_install_claim_protects_a_model_during_claim_publication(+ models_path: Path, store: ModelRecordServiceSQL+) -> None:+ root_name = "claim-being-published"+ root = models_path / root_name+ _write_model_file(root)+ claim = models_path / f".{root_name}{INSTALL_ACTIVE_SENTINEL}"+ claim.touch()+ service = _service(models_path, store)++ assert service.find_orphaned_models() == []+ result = service.delete_orphaned_models([root_name])++ assert result[root_name].startswith("error:")+ assert (root / "model.safetensors").exists()+ assert claim.exists()++def test_parent_of_recovery_root_cannot_be_deleted(models_path: Path, store: ModelRecordServiceSQL) -> None:parent = models_path / "model-group"_write_model_file(parent / "ordinary-orphan")diff --git a/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.pyindex 20f55a0377..b400a34182 100644--- a/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py+++ b/tests/backend/model_manager/test_huggingface_metadata_fetch_timeout.py@@ -4,14 +4,28 @@ from unittest.mock import Mockimport httpximport pytest-from requests import Timeout+from huggingface_hub.errors import HfHubHTTPError+from requests import HTTPError, Request, Response, Timeoutfrom invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetchfrom invokeai.backend.model_manager.metadata.metadata_base import (+ HF_METADATA_REQUEST_TIMEOUT_SECONDS,HuggingFaceMetadata,ModelMetadataUnavailableError,RemoteModelFile,+ UnknownMetadataException,)+from invokeai.backend.model_manager.taxonomy import ModelRepoVariant+++def _requests_response(status_code: int, content: bytes = b"", headers: dict[str, str] | None = None) -> Response:+ response = Response()+ response.status_code = status_code+ response.url = "https://huggingface.co/api/models/org/repo"+ response._content = content+ response.headers.update(headers or {})+ response.request = Request("GET", response.url).prepare()+ return response@pytest.mark.parametrize("use_custom_session", [False, True])@@ -62,8 +76,7 @@ def test_model_index_request_has_a_finite_timeout() -> None:metadata.download_urls(session=session)timeout = session.get.call_args.kwargs["timeout"]- assert isinstance(timeout, (int, float))- assert timeout > 0+ assert timeout == HF_METADATA_REQUEST_TIMEOUT_SECONDS@pytest.mark.parametrize("use_custom_session", [False, True])@@ -84,6 +97,29 @@ def test_model_info_transport_errors_are_retryable_metadata_failures(fetcher.from_id("org/repo")[email protected]("status_code", [429, 500, 503])+def test_hf_hub_http_errors_are_retryable_metadata_failures(monkeypatch: pytest.MonkeyPatch, status_code: int) -> None:+ request = httpx.Request("GET", "https://huggingface.co/api/models/org/repo")+ response = httpx.Response(status_code, request=request)+ api = Mock()+ api.model_info.side_effect = HfHubHTTPError("Hugging Face request failed", response=response)+ monkeypatch.setattr("invokeai.backend.model_manager.metadata.fetch.huggingface.HfApi", lambda: api)+ fetcher = HuggingFaceMetadataFetch()++ with pytest.raises(ModelMetadataUnavailableError):+ fetcher.from_id("org/repo")++[email protected]("status_code", [429, 500, 503])+def test_injected_session_model_info_http_errors_are_retryable_metadata_failures(status_code: int) -> None:+ session = Mock()+ session.get.return_value = _requests_response(status_code)+ fetcher = HuggingFaceMetadataFetch(session)++ with pytest.raises(ModelMetadataUnavailableError):+ fetcher.from_id("org/repo")++def test_model_index_transport_errors_are_retryable_metadata_failures() -> None:session = Mock()session.get.side_effect = Timeout("network timeout")@@ -104,3 +140,89 @@ def test_model_index_transport_errors_are_retryable_metadata_failures() -> None:with pytest.raises(ModelMetadataUnavailableError):metadata.download_urls(session=session)++[email protected]("status_code", [429, 500, 503])+def test_model_index_http_errors_are_retryable_metadata_failures(status_code: int) -> None:+ session = Mock()+ session.get.return_value = _requests_response(status_code)+ metadata = HuggingFaceMetadata(+ id="org/repo",+ name="repo",+ files=[+ RemoteModelFile(+ url="https://huggingface.co/org/repo/resolve/main/model_index.json",+ path=Path("model_index.json"),+ ),+ RemoteModelFile(+ url="https://huggingface.co/org/repo/resolve/main/text_encoder/config.json",+ path=Path("text_encoder/config.json"),+ ),+ ],+ )++ with pytest.raises(ModelMetadataUnavailableError):+ metadata.download_urls(session=session)+++def test_model_index_nontransient_http_error_is_not_reclassified() -> None:+ session = Mock()+ session.get.return_value = _requests_response(403)+ metadata = HuggingFaceMetadata(+ id="org/repo",+ name="repo",+ files=[+ RemoteModelFile(+ url="https://huggingface.co/org/repo/resolve/main/model_index.json",+ path=Path("model_index.json"),+ ),+ RemoteModelFile(+ url="https://huggingface.co/org/repo/resolve/main/text_encoder/config.json",+ path=Path("text_encoder/config.json"),+ ),+ ],+ )++ with pytest.raises(HTTPError):+ metadata.download_urls(session=session)+++def test_repository_not_found_remains_a_permanent_metadata_error() -> None:+ session = Mock()+ session.get.return_value = _requests_response(404)++ with pytest.raises(UnknownMetadataException):+ HuggingFaceMetadataFetch(session).from_id("org/repo")+++def test_missing_variant_revision_falls_back_to_default_revision() -> None:+ session = Mock()+ session.get.side_effect = [+ _requests_response(404, headers={"X-Error-Code": "RevisionNotFound"}),+ _requests_response(200, b'{"id":"org/repo","siblings":[]}'),+ ]++ metadata = HuggingFaceMetadataFetch(session).from_id("org/repo", variant=ModelRepoVariant.FP16)++ assert metadata.id == "org/repo"+ assert session.get.call_count == 2+ assert "/revision/" in session.get.call_args_list[0].args[0]+ assert "/revision/" not in session.get.call_args_list[1].args[0]+++def test_variant_fallback_gives_each_model_info_request_its_timeout() -> None:+ session = Mock()+ variant_not_found = _requests_response(404, headers={"X-Error-Code": "RevisionNotFound"})+ model_info_response = _requests_response(+ 200,+ content=b'{"id":"org/repo","siblings":[]}',+ )+ session.get.side_effect = [variant_not_found, model_info_response]++ HuggingFaceMetadataFetch(session).from_id("org/repo", variant=ModelRepoVariant.FP16)++ assert session.get.call_count == 2+ assert [call.kwargs["timeout"] for call in session.get.call_args_list] == [+ HF_METADATA_REQUEST_TIMEOUT_SECONDS,+ HF_METADATA_REQUEST_TIMEOUT_SECONDS,+ ]