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
refactor(model-install): move install staging state into one ledger (#9939)
Josh Corbett286ca1348c35
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex dd3a5680b9..4e599833db 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -536,7 +536,7 @@ Both methods accept a Path object corresponding to a checkpoint or diffusers folThe difference between `register_path()` and `install_path()` is that the former creates a model configuration record without changing the location of the model in the filesystem. The latter moves the model into the InvokeAI models directory before registering it.-When 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.+When 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. 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.@@ -548,6 +548,28 @@ Active-claim sidecars accept the legacy `PID process-start-time` payload and newStartup 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.+#### Install staging ledger++`invokeai/app/services/model_install/install_staging_ledger.py` owns everything an install keeps on disk under the models directory. Paths are relative to the models directory:++| Path | Meaning |+| --- | --- |+| `tmpinstall_*/` | A remote install's staging directory. Downloads land here before the install moves them. |+| `tmpinstall_*/.invokeai_install.json` | The staging marker, format version 1: `version`, `source`, `access_token` (Hugging Face and URL sources only), `config_in`, `status`, `updated_at`, per-file resume metadata in `files`, and `recovery_required: true` once a transfer failed in a way that needs manual recovery. |+| `.<name>.invokeai_install_active` | An active claim on the sibling `<name>`, held by a live install or orphan deletion. |+| `.<name>.invokeai_install_recovery_required` | A recovery sentinel: `<name>` holds data a failed transfer could not roll back. |+| `.invokeai_install_claims.lock` | Serializes the startup sweep of stale claims. |++Sidecars sit beside the root they protect, never inside it, so they do not travel with the files an install moves. The installer gives each install job one `InstallStaging` handle when it creates the job. The handle covers the job's staging directory and, for a local source under the models directory, the claim on that source's top-level root. It claims, persists the marker, marks both roots as recovery data before files move, and on release drops its claims before it clears the recovery marks it no longer needs, so a crash between the two steps leaves data protected rather than claimed. A job whose source already held recovery data keeps every mark until the job completes. A staging tree is only ever removed under a claim, taken first if the install does not hold one; a tree marked as recovery data is never removed, and cleanup checks the tree again once it holds the claim.++The destination root `<key>/` is not part of the handle: the transfer code claims it through the ledger before creating it, marks it as recovery data as soon as it exists, and keeps the claim until the model is registered or the transfer has rolled back. A failed rollback retains the mark; a clean rollback removes the empty destination and clears the mark; registering the model clears it.++The orphaned models service asks the ledger one question before it lists or deletes a path: is it protected? A path is protected when it, an ancestor below the models directory, or anything beneath it is claimed or marked as recovery data. Protected directories are neither listed nor deleted. Startup registration of unregistered models skips protected paths the same way. A deletion claims the path's top-level root for its duration, so an install cannot start using it meanwhile.++Marker writes replace the marker atomically: the new content goes to a temporary file in the staging directory, which is flushed, renamed over the marker, and followed by a sync of the directory on non-Windows platforms. Readers and a crash see the previous marker or the new one. On Windows a rename that a concurrent reader blocks is retried briefly. A temporary file left by a process killed mid-write is ignored and removed with the marker.++At startup the installer sweeps stale claims, then removes staging directories that no install can resume: those without a marker and those whose marker has a terminal status. It keeps claimed directories, directories holding a registered model, and recovery data. A staging directory whose marker exists but is unusable (torn, not JSON, or a format version this release does not know, for example after a downgrade) may hold the only copy of a download, so startup keeps it, logs a warning naming it, and never restores or reuses it. Orphaned model cleanup lists such a directory, unless it is claimed, holds recovery data, or holds a registered model, so it can be deleted once it is not needed.+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.diff --git a/invokeai/app/services/model_install/install_staging_ledger.py b/invokeai/app/services/model_install/install_staging_ledger.pynew file mode 100644index 0000000000..b9d7e37e7d--- /dev/null+++ b/invokeai/app/services/model_install/install_staging_ledger.py@@ -0,0 +1,824 @@+"""The install staging ledger: what model installs keep on disk under the models directory, and its lifecycle.++An install's on-disk state must survive a crash or restart, and orphan cleanup must never delete files an install still+needs. The ledger owns every piece of that state (paths relative to the models directory):++- ``tmpinstall_*/``: a remote install's staging directory. Downloads land here before the install moves them.+- ``tmpinstall_*/.invokeai_install.json``: the staging directory's marker (format version 1), what a restart needs to+ resume the install: source, access token (Hugging Face and URL sources only), requested config, status, timestamp,+ per-file resume metadata, and ``recovery_required`` once a failed transfer left data that needs a person. Each+ write replaces the marker atomically (temporary file, fsync, rename, directory fsync off Windows). A staging+ directory whose marker exists but is unusable (torn, or an unknown format version) is kept and reported: it may hold+ the only copy of a download. Orphaned model cleanup, or a person, removes it.+- ``.<name>.invokeai_install_active`` beside a root: an active claim, ``"<pid> <create-time>[ linux:<boot-id>:<start-+ ticks>]"``. A live install or orphan deletion owns the root. Claims are published atomically and refused when taken.+- ``.<name>.invokeai_install_recovery_required`` beside a root: the root holds data a failed transfer could not roll+ back. Nothing deletes, reuses or restores it; a person resolves it and registers the result.+- ``.invokeai_install_claims.lock``: serializes the startup sweep that removes claims whose process has exited.++Sidecars sit beside the root they protect rather than inside it, so they never travel with the files an install moves.+"""++import errno+import gc+import json+import logging+import math+import os+import re+import sys+import tempfile+import threading+import time+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from shutil import rmtree+from types import TracebackType+from typing import Any, Callable, Iterable, Iterator, Optional++import psutil++from invokeai.app.services.download import DownloadJob+from invokeai.app.services.model_install.model_install_common import (+ HFModelSource,+ InstallCancellationConflictError,+ InstallStatus,+ ModelSource,+ URLModelSource,+)+from invokeai.app.services.model_records import ModelRecordChanges+from invokeai.app.util.misc import get_iso_timestamp++TMPDIR_PREFIX = "tmpinstall_"+INSTALL_MARKER_FILENAME = ".invokeai_install.json"+INSTALL_MARKER_VERSION = 1+INSTALL_RECOVERY_SENTINEL = ".invokeai_install_recovery_required"+INSTALL_ACTIVE_SENTINEL = ".invokeai_install_active"+INSTALL_ACTIVE_SCAN_LOCK = ".invokeai_install_claims.lock"+MAX_ACTIVE_CLAIM_DIAGNOSTICS = 10+ACTIVE_CLAIM_SCAN_LOCK_RETRY_INTERVAL_SECONDS = 0.05+_MARKER_REPLACE_ATTEMPTS = 5+_MARKER_REPLACE_RETRY_SECONDS = 0.05++_TERMINAL_STATUSES = {InstallStatus.COMPLETED, InstallStatus.ERROR, InstallStatus.CANCELLED}+_active_claim_scan_thread_lock = threading.Lock()+++def _recovery_sentinel_path(root: Path) -> Path:+ return root.parent / f".{root.name}{INSTALL_RECOVERY_SENTINEL}"+++def _active_claim_path(root: Path) -> Path:+ return root.parent / f".{root.name}{INSTALL_ACTIVE_SENTINEL}"+++def _is_claimed(root: Path) -> bool:+ return _active_claim_path(root).exists()+++def _requires_recovery(root: Path) -> bool:+ return _recovery_sentinel_path(root).exists()+++def _holds_registered_model(tmpdir: Path, registered_paths: list[Path]) -> bool:+ resolved_tmpdir = tmpdir.resolve()+ return any(path == resolved_tmpdir or path.is_relative_to(resolved_tmpdir) for path in registered_paths)+++def _fsync_directory(path: Path) -> None:+ # Windows cannot open a directory for fsync; its directory entries are not synced separately.+ if os.name != "nt":+ fd = os.open(path, os.O_RDONLY)+ try:+ os.fsync(fd)+ finally:+ os.close(fd)+++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 _publish_claim(root: Path) -> None:+ """Atomically claim root; raises FileExistsError when another install or orphan deletion holds it."""+ path = _active_claim_path(root)+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)+ temp_path = Path(temp_name)+ try:+ with os.fdopen(fd, "wb") as f:+ process = psutil.Process()+ 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())+ # 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:+ pass+ raise+ else:+ # Once linked, cleanup cannot make publication fail for the owner.+ try:+ temp_path.unlink(missing_ok=True)+ except OSError:+ pass+++def _drop_claim(root: Path) -> None:+ try:+ _active_claim_path(root).unlink()+ except FileNotFoundError:+ pass+++def _write_recovery_sentinel(root: Path) -> None:+ """Durably mark root as recovery data; raises FileExistsError when it is already marked."""+ path = _recovery_sentinel_path(root)+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "xb") as f:+ f.write(b"Install transfer recovery required. Preserve this directory.\n")+ f.flush()+ os.fsync(f.fileno())+ # Persist the directory entry before any source data moves.+ _fsync_directory(path.parent)+++def _delete_recovery_sentinel(root: Path, logger: logging.Logger) -> None:+ try:+ _recovery_sentinel_path(root).unlink()+ _fsync_directory(root.parent)+ except FileNotFoundError:+ pass+ except OSError as e:+ logger.warning(f"Failed to remove install recovery sentinel in {root}: {e}")+++def _has_terminal_status(marker: Optional[dict[str, Any]]) -> bool:+ return marker is not None and marker.get("status") in {status.value for status in _TERMINAL_STATUSES}+++def _write_marker(path: Path, marker: dict[str, Any], logger: logging.Logger) -> None:+ """Replace a marker atomically: readers and a crash see the previous marker or the new one, never a torn one."""+ fd, temp_name = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)+ temp_path = Path(temp_name)+ try:+ with os.fdopen(fd, "wt", encoding="utf-8") as f:+ json.dump(marker, f)+ f.flush()+ os.fsync(f.fileno())+ # Windows refuses to replace a file another handle has open, e.g. a concurrent reader; retry briefly.+ delay = _MARKER_REPLACE_RETRY_SECONDS+ for attempts_left in range(_MARKER_REPLACE_ATTEMPTS - 1, -1, -1):+ try:+ os.replace(temp_path, path)+ break+ except PermissionError:+ if attempts_left == 0:+ raise+ time.sleep(delay)+ delay *= 2+ except BaseException:+ try:+ temp_path.unlink(missing_ok=True)+ except OSError:+ pass+ raise+ try:+ _fsync_directory(path.parent)+ except OSError as e:+ # The new marker is in place; only its survival across a crash is uncertain.+ logger.warning(f"Could not sync install marker directory {path.parent}: {e}")+++def _remove_tree(path: Path, logger: logging.Logger) -> None:+ """Remove a staging tree, retrying the file-handle races Windows reports as PermissionError.++ A failure is logged, not raised: startup removes the leftover tree once its marker and claim are gone.+ """+ max_retries = 3+ retry_delay = 0.5 # seconds+ for attempt in range(max_retries):+ try:+ # Release lingering references to files in the tree before removing it.+ gc.collect()+ rmtree(path)+ return+ except PermissionError as e:+ if attempt < max_retries - 1 and sys.platform == "win32":+ logger.warning(+ f"Failed to remove {path} (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {retry_delay}s..."+ )+ time.sleep(retry_delay)+ retry_delay *= 2+ else:+ logger.error(f"Failed to remove temporary directory {path}: {e}")+ return+ except Exception as e:+ logger.error(f"Unexpected error removing {path}: {e}")+ return+++@contextmanager+def _claim_scan_lock(models_path: Path) -> Iterator[None]:+ """Serialize stale-claim sweeps 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)+ # LK_LOCK gives up after a fixed number of attempts, which a long sweep can exceed.+ 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 HeldClaim:+ """An active claim this process published on a root; leaving the ``with`` block releases it."""++ def __init__(self, root: Path) -> None:+ _publish_claim(root)+ self._root = root+ self._released = False++ def release(self) -> None:+ """Release the claim; later calls do nothing, so a claim published since by another owner survives."""+ if not self._released:+ self._released = True+ _drop_claim(self._root)++ def __enter__(self) -> "HeldClaim":+ return self++ def __exit__(+ self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]+ ) -> None:+ self.release()+++@dataclass+class _SourceClaim:+ root: Path+ recovery_preexisting: bool+ claimed: bool = True+ owns_recovery_sentinel: bool = False+++@dataclass(frozen=True)+class RecoverableInstall:+ """A staging directory startup may resume: unclaimed, not under recovery, with a readable non-terminal marker.++ The marker's other fields are as written; the installer validates them before it trusts them.+ """++ staging: "InstallStaging"+ status: InstallStatus+ source: Any+ access_token: Any+ config_in: Any+ files: list[Any]+++class InstallStaging:+ """One install's footprint under the models directory: its staging directory and the local source it moves.++ A remote install has a staging directory; a local install of a source under the models directory protects that+ source's top-level root. Either part may be absent, and operations on an absent part do nothing. The installer+ creates the handle with its job and keeps it for the job's life.++ The handle has no lock. The installer reaches it from its worker, download callbacks and API calls, and relies on the+ job's lifecycle instead: one transfer at a time, and download callbacks quiesced before the staging tree is cleaned.+ """++ def __init__(self, ledger: "InstallStagingLedger", tmpdir: Optional[Path] = None) -> None:+ self._ledger = ledger+ self._tmpdir = tmpdir+ self._claimed = False+ self._claim_conflict = False+ self._owns_recovery_sentinel = False+ self._transferring = False+ self._source: Optional[_SourceClaim] = None++ @property+ def tmpdir(self) -> Optional[Path]:+ return self._tmpdir++ @property+ def claimed(self) -> bool:+ return self._claimed++ @property+ def claim_conflict(self) -> bool:+ """Whether the last claim attempt found another owner, which then owns the staging tree's cleanup."""+ return self._claim_conflict++ def claim(self) -> None:+ """Claim the staging directory against orphan cleanup and other installs; does nothing if already held."""+ if self._tmpdir is None or self._claimed:+ return+ try:+ _publish_claim(self._tmpdir)+ except FileExistsError as e:+ self._claim_conflict = True+ raise InstallCancellationConflictError(+ f"Cannot use install staging path {self._tmpdir}: another install or orphan cleanup is using it."+ ) from e+ self._claimed = True+ self._claim_conflict = False++ def release_claim(self) -> None:+ """Release the staging claim, leaving the tree for a later resume or startup restore."""+ if self._tmpdir is not None and self._claimed:+ _drop_claim(self._tmpdir)+ self._claimed = False++ def protect_source(self, model_path: Path) -> None:+ """Claim the top-level root under the models directory that contains a local source.++ A source outside the models directory, or the models directory itself, is not claimed. A source holding+ recovery data may be used, which is how a person registers what they recovered. Raises+ InstallCancellationConflictError when another install or orphan deletion holds the source or a root above it.+ """+ assert self._source is None, "the source is already protected"+ models_root = self._ledger._models_path.resolve()+ source_dir = (model_path if model_path.is_dir() else model_path.parent).resolve()+ if source_dir == models_root or not source_dir.is_relative_to(models_root):+ return+ source_root = models_root / source_dir.relative_to(models_root).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 _is_claimed(current):+ raise InstallCancellationConflictError(+ f"Cannot use local model source {current}: another install or orphan cleanup is using it."+ )+ has_recovery = has_recovery or _requires_recovery(current)+ current = current.parent+ try:+ _publish_claim(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+ self._source = _SourceClaim(root=source_root, recovery_preexisting=has_recovery)++ def persist(+ self,+ *,+ source: ModelSource,+ config_in: ModelRecordChanges,+ status: InstallStatus,+ download_parts: Iterable[DownloadJob],+ resume_files: Optional[dict[str, dict[str, Any]]],+ recovery_required: bool,+ ) -> None:+ """Write the staging directory's marker so a restart can resume the install."""+ if self._tmpdir is None:+ return+ files: list[dict[str, Any]] = [+ {+ "url": str(part.source),+ "canonical_url": part.canonical_url,+ "etag": part.etag,+ "last_modified": part.last_modified,+ "expected_total_bytes": part.expected_total_bytes,+ "final_url": part.final_url,+ "download_path": part.download_path.as_posix() if part.download_path else None,+ "resume_required": part.resume_required,+ "resume_message": part.resume_message,+ }+ for part in download_parts+ ]+ if not files and resume_files:+ files.extend(dict(metadata) for metadata in resume_files.values())+ marker: dict[str, Any] = {+ "version": INSTALL_MARKER_VERSION,+ "source": str(source),+ "access_token": source.access_token if isinstance(source, (HFModelSource, URLModelSource)) else None,+ "config_in": config_in.model_dump(),+ "status": status.value,+ "updated_at": get_iso_timestamp(),+ "files": files,+ }+ if recovery_required:+ marker["recovery_required"] = True+ self._tmpdir.mkdir(parents=True, exist_ok=True)+ _write_marker(self._tmpdir / INSTALL_MARKER_FILENAME, marker, self._ledger._logger)++ def delete_marker(self) -> None:+ """Remove the marker once the install no longer needs a restart to resume it.++ Does nothing after a claim conflict: the staging directory's other owner keeps its marker.+ """+ if self._tmpdir is None or self._claim_conflict:+ return+ path = self._tmpdir / INSTALL_MARKER_FILENAME+ # A process killed mid-write leaves its temporary file; it must not travel with the files an install moves.+ for leftover in [path, *self._tmpdir.glob(f"{INSTALL_MARKER_FILENAME}.*.tmp")]:+ if leftover.exists():+ try:+ leftover.unlink()+ except Exception as e:+ self._ledger._logger.warning(f"Failed to remove install marker {leftover}: {e}")++ def requires_recovery(self) -> bool:+ """Whether the staging directory is marked as holding recovery data."""+ return self._tmpdir is not None and _requires_recovery(self._tmpdir)++ def discard(self) -> None:+ """Remove the staging tree under this install's claim, then release the claim.++ A tree marked as recovery data is kept. Without a held claim, the tree is claimed for the removal first and kept+ if another owner holds it. Does nothing after a claim conflict, since the other owner then owns the tree.+ """+ if self._tmpdir is None or self._claim_conflict:+ return+ assert not self._transferring, "end the transfer before discarding its staging tree"+ if self.requires_recovery():+ self.release_claim()+ elif self._claimed:+ _remove_tree(self._tmpdir, self._ledger._logger)+ self.release_claim()+ else:+ self._ledger._remove_unclaimed_staging(self._tmpdir)++ def begin_transfer(self) -> None:+ """Mark both roots as recovery data before any file moves, so an interrupted transfer is preserved.++ Raises when the staging claim or a sentinel cannot be made durable; nothing has moved yet.+ """+ if self._tmpdir is not None:+ self.claim()+ _write_recovery_sentinel(self._tmpdir)+ self._owns_recovery_sentinel = True+ self._transferring = True+ source = self._source+ if source is not None and source.claimed and not _requires_recovery(source.root):+ _write_recovery_sentinel(source.root)+ source.owns_recovery_sentinel = True++ def end_transfer(self) -> None:+ """Clear the staging directory's recovery mark once its transfer finished or rolled back cleanly."""+ if self._tmpdir is not None:+ _delete_recovery_sentinel(self._tmpdir, self._ledger._logger)+ self._transferring = False++ def finish(self, *, recovery_required: bool, completed: bool) -> None:+ """Release an install job's claims and the recovery marks it no longer needs.++ A job whose source already held recovery data keeps every mark until it completes. ``install_path()`` uses+ ``release()`` directly and clears a mark it made even then.+ """+ source_recovery_preexisting = self._source is not None and self._source.recovery_preexisting+ self.release(+ preserve_recovery=recovery_required or (source_recovery_preexisting and not completed),+ completed=completed,+ )++ def release(self, *, preserve_recovery: bool, completed: bool) -> None:+ """Release every claim this install holds, then clear the recovery marks it no longer needs.++ Claims go first: a crash in between leaves recovery marks, which preserve the data, rather than claims.+ Unless ``preserve_recovery``, the marks this install made are cleared, and a mark the source already had is+ cleared once the install ``completed``.+ """+ self.release_claim()+ source = self._source+ if source is not None and source.claimed:+ _drop_claim(source.root)+ source.claimed = False+ if preserve_recovery:+ return+ if self._tmpdir is not None and self._owns_recovery_sentinel:+ _delete_recovery_sentinel(self._tmpdir, self._ledger._logger)+ self._owns_recovery_sentinel = False+ if source is not None and (source.owns_recovery_sentinel or (source.recovery_preexisting and completed)):+ _delete_recovery_sentinel(source.root, self._ledger._logger)+ source.owns_recovery_sentinel = False+++class InstallStagingLedger:+ """The models directory's install staging state; see the module docstring for the on-disk format."""++ def __init__(self, models_path: Path, logger: logging.Logger) -> None:+ self._models_path = models_path+ self._logger = logger++ def create_staging(self, source: str) -> InstallStaging:+ """Return an unclaimed handle on a staging directory for a new remote install of source.++ Reuses the newest resumable staging directory left by an earlier install of the same source, so its partial+ downloads resume; otherwise creates a new one.+ """+ candidates: list[tuple[str, Path]] = []+ for tmpdir in self._models_path.glob(f"{TMPDIR_PREFIX}*"):+ if _is_claimed(tmpdir) or _requires_recovery(tmpdir):+ continue+ marker = self._read_marker(tmpdir)+ if not marker or marker.get("source") != source or marker.get("recovery_required") is True:+ continue+ if marker.get("status") in {status.value for status in _TERMINAL_STATUSES}:+ continue+ candidates.append((marker.get("updated_at", ""), tmpdir))+ if candidates:+ candidates.sort(key=lambda item: item[0], reverse=True)+ return InstallStaging(self, candidates[0][1])+ return InstallStaging(self, Path(tempfile.mkdtemp(dir=self._models_path, prefix=TMPDIR_PREFIX)))++ def claim(self, root: Path) -> HeldClaim:+ """Claim root for an operation; raises FileExistsError when another install or orphan deletion holds it."""+ return HeldClaim(root)++ def mark_recovery_required(self, root: Path) -> None:+ """Durably mark root as recovery data; raises if the mark cannot be made durable or already exists."""+ _write_recovery_sentinel(root)++ def retain_recovery(self, root: Path) -> None:+ """Mark an existing root as recovery data if it is not already; failures are logged, not raised."""+ try:+ if root.exists() and not _requires_recovery(root):+ _write_recovery_sentinel(root)+ except Exception as sentinel_error:+ self._logger.error(f"Failed to persist destination recovery sentinel in {root}: {sentinel_error}")++ def clear_recovery(self, root: Path) -> None:+ """Remove root's recovery mark, if any; failures are logged."""+ _delete_recovery_sentinel(root, self._logger)++ def is_protected(self, path: Path) -> bool:+ """Whether deleting path could destroy data an install owns.++ True when path or an ancestor below the models directory is claimed or marked as recovery data, or when+ anything beneath path is.+ """+ boundary = self._models_path.resolve()+ current = path.resolve()+ while current != boundary and current.is_relative_to(boundary):+ if _requires_recovery(current) or _is_claimed(current):+ return True+ current = current.parent+ if not path.is_dir():+ return False+ suffixes = (INSTALL_RECOVERY_SENTINEL, INSTALL_ACTIVE_SENTINEL)+ return any(entry.name.endswith(suffixes) for entry in path.rglob("*.invokeai_install_*"))++ def sweep_stale_claims(self) -> None:+ """Remove active claims whose owning process has exited.++ Sweeps are serialized across threads and processes, so no sweep can delete a claim published after another+ sweep inspected its predecessor. A claim whose owner cannot be proven gone is kept and reported.+ """+ if not self._models_path.is_dir():+ return+ with _claim_scan_lock(self._models_path):+ self._sweep_stale_claims_locked()++ def _sweep_stale_claims_locked(self) -> None:+ 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._models_path.glob(f"*{INSTALL_ACTIVE_SENTINEL}"):+ try:+ 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")+ continue+ process = psutil.Process(pid)+ 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):+ 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 (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 remove_dangling_staging(self, registered_paths: Iterable[Path]) -> None:+ """Remove staging directories no install can resume: no marker, or a terminal one.++ Keeps claimed directories, directories holding a registered model (resolved paths), recovery data, and+ directories whose marker exists but is unusable, which it reports instead.+ """+ registered = list(registered_paths)+ for tmpdir in self._models_path.glob(f"{TMPDIR_PREFIX}*"):+ if _is_claimed(tmpdir):+ self._logger.debug(f"Preserving active install directory {tmpdir}")+ continue+ if _holds_registered_model(tmpdir, registered):+ self._logger.debug(f"Preserving registered model directory {tmpdir}")+ continue+ if _requires_recovery(tmpdir):+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continue+ marker, unusable = self._load_marker(tmpdir)+ if unusable is not None:+ # It may still hold the only copy of a download, and a newer release may be able to resume it.+ self._logger.warning(+ f"Preserving install staging directory {tmpdir}: its marker {unusable}. Nothing will resume or "+ "remove it; orphaned model cleanup lists it for deletion once it is not needed."+ )+ continue+ if marker is None:+ self._logger.info(f"Removing dangling temporary directory {tmpdir}")+ self._remove_unclaimed_staging(tmpdir, still_removable=lambda marker: marker is None)+ continue+ if marker.get("recovery_required") is True:+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continue+ if marker.get("status") in {status.value for status in _TERMINAL_STATUSES}:+ self._logger.info(f"Removing completed/errored temporary directory {tmpdir}")+ self._remove_unclaimed_staging(tmpdir, still_removable=_has_terminal_status)++ def abandoned_staging(self, registered_paths: Iterable[Path]) -> list[Path]:+ """Return the staging directories startup keeps only because their marker is unusable.++ Nothing resumes or removes them, so orphaned model cleanup offers them for deletion. Claimed directories,+ directories holding a registered model (resolved paths), and recovery data are not abandoned.+ """+ registered = list(registered_paths)+ return [+ tmpdir+ for tmpdir in self._models_path.glob(f"{TMPDIR_PREFIX}*")+ if tmpdir.is_dir()+ and not self.is_protected(tmpdir)+ and not _holds_registered_model(tmpdir, registered)+ and self._load_marker(tmpdir)[1] is not None+ ]++ def recoverable_installs(self) -> Iterator[RecoverableInstall]:+ """Yield the staging directories startup should resume, reading each one only when the caller asks for it."""+ for tmpdir in self._models_path.glob(f"{TMPDIR_PREFIX}*"):+ if _is_claimed(tmpdir):+ self._logger.debug(f"Skipping active install directory {tmpdir}")+ continue+ if _requires_recovery(tmpdir):+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continue+ marker = self._read_marker(tmpdir)+ if not marker:+ continue+ if marker.get("recovery_required") is True:+ self._logger.warning(f"Preserving install recovery data in {tmpdir}")+ continue+ raw_status = marker.get("status")+ try:+ status = InstallStatus(raw_status) if raw_status else InstallStatus.WAITING+ except Exception as e:+ self._logger.warning(f"Skipping install marker in {tmpdir}: {e}")+ continue+ if status in _TERMINAL_STATUSES:+ continue+ yield RecoverableInstall(+ staging=InstallStaging(self, tmpdir),+ status=status,+ source=marker.get("source"),+ access_token=marker.get("access_token"),+ config_in=marker.get("config_in"),+ files=marker.get("files") or [],+ )++ def _read_marker(self, tmpdir: Path) -> Optional[dict[str, Any]]:+ """Return a staging directory's usable marker, or None when it has none or cannot use the one it has."""+ return self._load_marker(tmpdir)[0]++ @staticmethod+ def _load_marker(tmpdir: Path) -> tuple[Optional[dict[str, Any]], Optional[str]]:+ """Return ``(marker, None)``, ``(None, None)`` without a marker, or ``(None, reason)`` for an unusable one.++ An unusable marker is unreadable, torn, or written in a format version this release does not know (for+ example by a newer release before a downgrade).+ """+ path = tmpdir / INSTALL_MARKER_FILENAME+ if not path.exists():+ return None, None+ try:+ with open(path, "rt", encoding="utf-8") as f:+ marker = json.load(f)+ except Exception as e:+ return None, f"cannot be read ({e})"+ if not isinstance(marker, dict):+ return None, "is not a JSON object"+ if marker.get("version") != INSTALL_MARKER_VERSION:+ return None, f"has unsupported format version {marker.get('version')!r}"+ return marker, None++ def _remove_unclaimed_staging(+ self, tmpdir: Path, still_removable: Callable[[Optional[dict[str, Any]]], bool] = lambda marker: True+ ) -> None:+ """Remove a staging tree only after atomically excluding active install work.++ Under the claim, the tree is checked again: it is kept if it gained recovery data, or if its marker no longer+ allows ``still_removable``, since another owner may have changed it between the decision and the claim.+ """+ try:+ claim = HeldClaim(tmpdir)+ except FileExistsError:+ self._logger.debug(f"Preserving active install directory {tmpdir}")+ return+ with claim:+ marker, unusable = self._load_marker(tmpdir)+ recovery_marked = _requires_recovery(tmpdir) or (+ marker is not None and marker.get("recovery_required") is True+ )+ if recovery_marked or unusable is not None or not still_removable(marker):+ self._logger.debug(f"Preserving install directory {tmpdir}: it changed before it could be removed")+ return+ _remove_tree(tmpdir, self._logger)diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex 5556b81122..c37c99ba3a 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -1,17 +1,9 @@-import errno-import osimport re-import sys-import tempfile-import threading-import timeimport traceback-from contextlib import contextmanagerfrom enum import Enumfrom pathlib import Path-from typing import Iterator, Literal, Optional, Set, Union+from typing import TYPE_CHECKING, Literal, Optional, Set, Union-import psutilfrom pydantic import BaseModel, Field, PrivateAttr, field_validatorfrom pydantic.networks import AnyHttpUrlfrom typing_extensions import Annotated@@ -22,6 +14,9 @@ from invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.metadata import AnyModelRepoMetadatafrom invokeai.backend.model_manager.taxonomy import ModelRepoVariant, ModelSourceType+if TYPE_CHECKING:+ from invokeai.app.services.model_install.install_staging_ledger import InstallStaging+class InvalidModelConfigException(Exception):"""Raised when a model configuration is invalid."""@@ -29,50 +24,6 @@ class InvalidModelConfigException(Exception):pass-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):"""The install cannot be cancelled safely in its current state."""@@ -85,87 +36,6 @@ class InstallRecoveryRequiredError(InstallCancellationConflictError):"""Install transfer could not be safely rolled back; preserve both recovery roots."""-def recovery_sentinel_path(root: Path) -> Path:- """Return the sidecar marker path that protects an install recovery root."""- 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 _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)- fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)- temp_path = Path(temp_name)- try:- with os.fdopen(fd, "wb") as f:- process = psutil.Process()- 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())- # 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:- pass- raise- else:- # Once linked, cleanup cannot make publication fail for the owner.- try:- temp_path.unlink(missing_ok=True)- except OSError:- pass---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 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) or has_active_install_sentinel(current):- return True- current = current.parent- return False--class InstallStatus(str, Enum):"""State of an install job running in the background."""@@ -343,20 +213,14 @@ class ModelInstallJob(BaseModel):default=None, description="On an error condition, this field will contain the exception traceback")# 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)+ # The install's staging directory, local source claim and recovery marks; the installer owns its lifecycle.+ _staging: Optional["InstallStaging"] = PrivateAttr(default=None)_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 98c2230c4d..038a7e2f14 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -4,9 +4,7 @@ import ctypesimport errnoimport filecmpimport gc-import jsonimport locale-import mathimport osimport reimport sys@@ -19,7 +17,6 @@ from shutil import copy2, copytree, move, rmtreefrom tempfile import mkdtempfrom 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 +27,9 @@ from requests import Sessionfrom invokeai.app.services.config import InvokeAIAppConfigfrom invokeai.app.services.download import DownloadQueueServiceBase, MultiFileDownloadJobfrom invokeai.app.services.invoker import Invoker+from invokeai.app.services.model_install.install_staging_ledger import InstallStaging, InstallStagingLedgerfrom 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,@@ -46,18 +43,9 @@ 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,- has_recovery_sentinel,- is_recovery_protected_path,- recovery_sentinel_path,)from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelExceptionfrom invokeai.app.services.model_records.model_records_base import ModelRecordChanges-from invokeai.app.util.misc import get_iso_timestampfrom invokeai.app.util.path_safety import is_plain_filenamefrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Basefrom invokeai.backend.model_manager.configs.external_api import (@@ -97,13 +85,6 @@ if TYPE_CHECKING:from invokeai.app.services.events.events_base import EventServiceBase-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 = 10--class _InstallCancelledBeforeTransfer(Exception):"""Raised when a cancellation request wins before file transfer becomes protected."""@@ -186,356 +167,83 @@ class ModelInstallService(ModelInstallServiceBase):self._session = sessionself._install_thread: Optional[threading.Thread] = Noneself._next_job_id = 0-- def _marker_path(self, tmpdir: Path) -> Path:- return tmpdir / INSTALL_MARKER_FILENAME-- def _recovery_sentinel_path(self, tmpdir: Path) -> Path:- return recovery_sentinel_path(tmpdir)-- def _has_recovery_sentinel(self, tmpdir: Path) -> bool:- return has_recovery_sentinel(tmpdir)-- def _write_recovery_sentinel(self, tmpdir: Path) -> None:- # Keep recovery state outside the tree being transferred into the managed model directory.- path = self._recovery_sentinel_path(tmpdir)- path.parent.mkdir(parents=True, exist_ok=True)- with open(path, "xb") as f:- f.write(b"Install transfer recovery required. Preserve this directory.\n")- f.flush()- os.fsync(f.fileno())- # Persist the directory entry before moving any source data where directory fsync is supported.- if os.name != "nt":- fd = os.open(path.parent, os.O_RDONLY)- try:- os.fsync(fd)- finally:- os.close(fd)-- def _delete_recovery_sentinel(self, tmpdir: Path) -> None:- try:- self._recovery_sentinel_path(tmpdir).unlink()- if os.name != "nt":- fd = os.open(tmpdir.parent, os.O_RDONLY)- try:- os.fsync(fd)- finally:- os.close(fd)- except FileNotFoundError:- pass- 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+ self._ledger = InstallStagingLedger(app_config.models_path, self._logger)@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 _staging_of(job: ModelInstallJob) -> InstallStaging:+ assert job._staging is not None, "every install job gets its staging handle when it is created"+ return job._staging- def _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:- 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")- continue- process = psutil.Process(pid)- 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):- 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 (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})")+ def _write_install_marker(self, job: ModelInstallJob, status: Optional[InstallStatus] = None) -> None:+ self._staging_of(job).persist(+ source=job.source,+ config_in=job.config_in,+ status=status or job.status,+ download_parts=job.download_parts,+ resume_files=job._resume_metadata,+ recovery_required=job._recovery_required,+ )- 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 _requires_recovery(self, job: ModelInstallJob) -> bool:+ return job._recovery_required or self._staging_of(job).requires_recovery()- def _retain_recovery_destination(self, dest_dir: Path) -> None:- try:- 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}")+ def _discard_cancelled_staging(self, job: ModelInstallJob) -> None:+ """Remove a cancelled install's staging tree unless it holds recovery data, and release its claim.- def _write_install_marker(self, job: ModelInstallJob, status: Optional[InstallStatus] = None) -> None:- if job._install_tmpdir is None:+ Call only after the job's download callback has stopped using the tree.+ """+ staging = self._staging_of(job)+ if staging.claim_conflict:+ return+ if staging.requires_recovery():+ staging.release_claim()return- files: list[dict] = []- if job.download_parts:- for part in job.download_parts:- files.append(- {- "url": str(part.source),- "canonical_url": part.canonical_url,- "etag": part.etag,- "last_modified": part.last_modified,- "expected_total_bytes": part.expected_total_bytes,- "final_url": part.final_url,- "download_path": part.download_path.as_posix() if part.download_path else None,- "resume_required": part.resume_required,- "resume_message": part.resume_message,- }- )- elif job._resume_metadata:- files.extend(dict(metadata) for metadata in job._resume_metadata.values())- marker = {- "version": INSTALL_MARKER_VERSION,- "source": str(job.source),- "access_token": (- job.source.access_token if isinstance(job.source, (HFModelSource, URLModelSource)) else None- ),- "config_in": job.config_in.model_dump(),- "status": (status or job.status).value,- "updated_at": get_iso_timestamp(),- "files": files,- }- if job._recovery_required:- marker["recovery_required"] = True- path = self._marker_path(job._install_tmpdir)- path.parent.mkdir(parents=True, exist_ok=True)- with open(path, "wt", encoding="utf-8") as f:- json.dump(marker, f)-- def _read_install_marker(self, tmpdir: Path) -> Optional[dict]:- path = self._marker_path(tmpdir)- if not path.exists():- return Nonetry:- with open(path, "rt", encoding="utf-8") as f:- marker = json.load(f)- if marker.get("version") != INSTALL_MARKER_VERSION:- return None- return marker- except Exception as e:- self._logger.warning(f"Invalid install marker in {tmpdir}: {e}")- return None-- def _delete_install_marker(self, tmpdir: Path) -> None:- path = self._marker_path(tmpdir)- if path.exists():- try:- path.unlink()- except Exception as e:- self._logger.warning(f"Failed to remove install marker {path}: {e}")-- def _find_reusable_tmpdir(self, source: ModelSource) -> Optional[Path]:- path = self._app_config.models_path- source_str = str(source)- candidates: list[tuple[str, Path]] = []- for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):- if has_active_install_sentinel(tmpdir) or self._has_recovery_sentinel(tmpdir):- continue- marker = self._read_install_marker(tmpdir)- if not marker:- continue- if marker.get("source") != source_str:- continue- status = marker.get("status")- if marker.get("recovery_required") is True:- continue- if status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:- continue- candidates.append((marker.get("updated_at", ""), tmpdir))- if not candidates:- return None- candidates.sort(key=lambda item: item[0], reverse=True)- return candidates[0][1]+ # Touch neither the marker nor the tree of a staging directory another owner holds.+ staging.claim()+ except InstallCancellationConflictError:+ self._logger.debug(f"Leaving cancelled install directory {staging.tmpdir} to its current owner")+ return+ # Mark cancelled before cleanup so a tree whose removal fails is never reused.+ self._write_install_marker(job, status=InstallStatus.CANCELLED)+ staging.delete_marker()+ staging.discard()def _restore_incomplete_installs(self) -> None:- path = self._app_config.models_pathseen_sources: set[str] = set()# Collect sources already tracked by active jobs (including those being downloaded right now).# We must not re-queue these or delete their tmpdirs.with self._lock: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}*"):+ for entry in self._ledger.recoverable_installs():if self._stop_event.is_set():return- if has_active_install_sentinel(tmpdir):- self._logger.debug(f"Skipping active install directory {tmpdir}")- continue- if self._has_recovery_sentinel(tmpdir):- self._logger.warning(f"Preserving install recovery data in {tmpdir}")- continue- marker = self._read_install_marker(tmpdir)- if not marker:- continue- status = marker.get("status")- if marker.get("recovery_required") is True:- self._logger.warning(f"Preserving install recovery data in {tmpdir}")- continue+ staging = entry.staging+ tmpdir = staging.tmpdir+ assert tmpdir is not Nonetry:- parsed_status = InstallStatus(status) if status else InstallStatus.WAITING- if parsed_status in {InstallStatus.COMPLETED, InstallStatus.ERROR, InstallStatus.CANCELLED}:- continue- source_str = marker.get("source")+ source_str = entry.sourceif not isinstance(source_str, str):raise ValueError("Missing source in install marker")source = self._guess_source(source_str)- access_token = marker.get("access_token")- if isinstance(source, (HFModelSource, URLModelSource)) and isinstance(access_token, str):- source.access_token = access_token+ if isinstance(source, (HFModelSource, URLModelSource)) and isinstance(entry.access_token, str):+ source.access_token = entry.access_tokenif source_str in active_sources:# This tmpdir belongs to an install already in progress; leave it alone.self._logger.debug(f"Skipping restore for {source_str} - already being tracked")continueif source_str in seen_sources:self._logger.info(f"Removing duplicate temporary directory {tmpdir}")- self._remove_unclaimed_install_tmpdir(tmpdir)+ staging.discard()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# that an unsafe *key* is no longer such a case - `ModelRecordChanges` deliberately accepts one so# the install is restored and then fails at the join in `install_path()`, which errors the job and# reclaims its tmpdir. Skipping it here would strand the partial download instead: no job is- # created to clean up, and `_remove_dangling_install_dirs` keeps any readable non-terminal marker.- config_in = ModelRecordChanges(**(marker.get("config_in") or {}))+ # created to clean up, and startup cleanup keeps any readable non-terminal marker.+ config_in = ModelRecordChanges(**(entry.config_in or {}))seen_sources.add(source_str)except Exception as e:self._logger.warning(f"Skipping install marker in {tmpdir}: {e}")@@ -547,18 +255,17 @@ class ModelInstallService(ModelInstallServiceBase):config_in=config_in,local_path=tmpdir,)- job._install_tmpdir = tmpdir+ job._staging = stagingtry:# 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)+ staging.claim()except InstallCancellationConflictError as e:self._logger.info(f"Skipping restore of claimed install directory {tmpdir}: {e}")continue- files_meta = marker.get("files") or []- if files_meta:- job._resume_metadata = {f.get("url"): f for f in files_meta if f.get("url")}- job.status = parsed_status+ if entry.files:+ job._resume_metadata = {f.get("url"): f for f in entry.files if f.get("url")}+ job.status = entry.statusself._install_jobs.append(job)if job.paused:@@ -578,16 +285,11 @@ class ModelInstallService(ModelInstallServiceBase):returnexcept Exception as e:if self._stop_event.is_set():- self._logger.info(f"Leaving interrupted install in {job._install_tmpdir} for next startup")+ self._logger.info(f"Leaving interrupted install in {tmpdir} for next startup")job.status = InstallStatus.PAUSEDreturnself._set_error(job, e)- 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)+ staging.discard()def _restore_incomplete_installs_async(self) -> None:self._restore_completed_event.clear()@@ -653,7 +355,6 @@ class ModelInstallService(ModelInstallServiceBase):source=job.source,remote_files=remote_files,metadata=metadata,- destdir=job._install_tmpdir or job.local_path,subfolder=job.source.subfolderif isinstance(job.source, HFModelSource) and len(subfolders) <= 1else None,@@ -722,9 +423,13 @@ class ModelInstallService(ModelInstallServiceBase):self._startup_error = Noneself._restore_completed_event.clear()try:- self._remove_stale_install_source_claims()+ self._ledger.sweep_stale_claims()self._start_installer_thread()- self._remove_dangling_install_dirs()+ self._ledger.remove_dangling_staging(+ (self._app_config.models_path / model.path).resolve()+ for model in self.record_store.all_models()+ if model.path+ )self._migrate_yaml()# In normal use, we do not want to scan the models directory - it should never have orphaned models.# We should only do the scan when the flag is set (which should only be set when testing).@@ -784,9 +489,7 @@ class ModelInstallService(ModelInstallServiceBase):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)- ):+ if self._requires_recovery(job):self._logger.warning(f"Preserving recovery data for job {job.id} during shutdown")continuemultifile_job = job._multifile_job@@ -804,14 +507,15 @@ class ModelInstallService(ModelInstallServiceBase):elif preserve_download_status is None:job.status = InstallStatus.PAUSED+ staging = self._staging_of(job)if preserve_download_status is not None:self._write_install_marker(job, status=preserve_download_status)if not download_callback_pending:- self._release_install_tmpdir_claim(job)+ staging.release_claim()elif 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)+ staging.release_claim()elif multifile_job is not None:self._logger.warning(f"Pausing job {job.id}")for part in multifile_job.download_parts:@@ -819,14 +523,10 @@ class ModelInstallService(ModelInstallServiceBase):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:+ staging.release_claim()+ elif staging.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)+ self._discard_cancelled_staging(job)while True:try:job = self._install_queue.get(block=False)@@ -861,20 +561,16 @@ class ModelInstallService(ModelInstallServiceBase):if not config.source:config.source = model_path.resolve().as_posix()config.source_type = ModelSourceType.Path- 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+ staging = InstallStaging(self._ledger)+ staging.protect_source(model_path)registered = Falsetry:model_id = self._register(model_path, config)registered = Truereturn model_idfinally:- 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)+ # Registering a recovered source resolves the recovery data it held.+ staging.release(preserve_recovery=False, completed=registered)# TODO: Replace this with a proper fix for underlying problem of Windows holding open# the file when it needs to be moved.@@ -980,20 +676,15 @@ class ModelInstallService(ModelInstallServiceBase):) -> str:model_path = Path(model_path)config = config or ModelRecordChanges()- source_root, active_sentinel_created, had_recovery_sentinel = self._protect_managed_source_path(- model_path, allow_recovery=True- )- source_recovery_sentinel_created = False+ staging = InstallStaging(self._ledger)+ staging.protect_source(model_path)preserve_source = Falseinstalled = Falsetry:info: AnyModelConfig = self._probe(Path(model_path), config) # type: ignoredef 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+ staging.begin_transfer()return Truemodel_id = self._install_path_with_info(model_path, config, info, before_transfer=begin_transfer)@@ -1003,14 +694,7 @@ class ModelInstallService(ModelInstallServiceBase):preserve_source = Trueraisefinally:- 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)+ staging.release(preserve_recovery=preserve_source, completed=installed)def _install_path_with_info(self,@@ -1025,15 +709,13 @@ class ModelInstallService(ModelInstallServiceBase):raise ValueError(f"Invalid model key {info.key!r}: it must be a plain filename")dest_dir = self.app_config.models_path / info.keytry:- create_active_install_sentinel(dest_dir)+ dest_claim = self._ledger.claim(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:+ with dest_claim: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,@@ -1056,7 +738,7 @@ class ModelInstallService(ModelInstallServiceBase):destination_created = True# 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)+ self._ledger.mark_recovery_required(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_dir@@ -1082,7 +764,7 @@ class ModelInstallService(ModelInstallServiceBase):except InstallRecoveryRequiredError:# Recovery destinations can share TMPDIR_PREFIX with remote staging dirs. Keep their artifacts out of# startup's dangling-install cleanup even when the configured model key uses that prefix.- self._retain_recovery_destination(dest_dir)+ self._ledger.retain_recovery(dest_dir)raiseexcept Exception as transfer_error:if not destination_created:@@ -1106,7 +788,7 @@ class ModelInstallService(ModelInstallServiceBase):)if rollback_errors:details = "; ".join(rollback_errors)- self._retain_recovery_destination(dest_dir)+ self._ledger.retain_recovery(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. {details}"@@ -1118,9 +800,9 @@ class ModelInstallService(ModelInstallServiceBase):leftovers = ", ".join(str(path.resolve()) for path in remaining)raise OSError(f"unexpected destination artifacts remain: {leftovers}")dest_dir.rmdir()- self._delete_recovery_sentinel(dest_dir)+ self._ledger.clear_recovery(dest_dir)except Exception as cleanup_error:- self._retain_recovery_destination(dest_dir)+ self._ledger.retain_recovery(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "@@ -1134,9 +816,9 @@ class ModelInstallService(ModelInstallServiceBase):leftovers = ", ".join(str(path.resolve()) for path in remaining)raise OSError(f"unexpected destination artifacts remain: {leftovers}")dest_dir.rmdir()- self._delete_recovery_sentinel(dest_dir)+ self._ledger.clear_recovery(dest_dir)except Exception as cleanup_error:- self._retain_recovery_destination(dest_dir)+ self._ledger.retain_recovery(dest_dir)raise InstallRecoveryRequiredError(f"Install recovery required after {transfer_error}. Source: {model_path.resolve()}; "f"destination: {dest_dir.resolve()}. Could not remove owned empty destination: "@@ -1270,9 +952,7 @@ class ModelInstallService(ModelInstallServiceBase):)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)- ):+ if self._requires_recovery(job):raise InstallRecoveryRequiredError("Cannot cancel an install that requires recovery; preserve its files for manual recovery.")@@ -1291,7 +971,7 @@ class ModelInstallService(ModelInstallServiceBase):# 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)+ self._discard_cancelled_staging(job)def pause_job(self, job: ModelInstallJob) -> None:"""Pause the indicated job, preserving partial downloads."""@@ -1323,9 +1003,7 @@ class ModelInstallService(ModelInstallServiceBase):def restart_failed(self, job: ModelInstallJob) -> None:"""Restart failed or non-resumable downloads for a job."""- if job._recovery_required or (- job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)- ):+ if self._requires_recovery(job):raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")if not isinstance(job.source, (HFModelSource, URLModelSource)):return@@ -1350,7 +1028,6 @@ class ModelInstallService(ModelInstallServiceBase):source=job.source,remote_files=remote_files,metadata=metadata,- destdir=job._install_tmpdir or job.local_path,subfolder=job.source.subfolderif isinstance(job.source, HFModelSource) and len(subfolders) <= 1else None,@@ -1365,9 +1042,7 @@ class ModelInstallService(ModelInstallServiceBase):def restart_file(self, job: ModelInstallJob, file_source: str) -> None:"""Restart a specific file download for a job."""- if job._recovery_required or (- job._install_tmpdir is not None and self._has_recovery_sentinel(job._install_tmpdir)- ):+ if self._requires_recovery(job):raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")if not isinstance(job.source, (HFModelSource, URLModelSource)):return@@ -1385,7 +1060,6 @@ class ModelInstallService(ModelInstallServiceBase):source=job.source,remote_files=remote_files,metadata=metadata,- destdir=job._install_tmpdir or job.local_path,subfolder=job.source.subfolderif isinstance(job.source, HFModelSource) and len(subfolders) <= 1else None,@@ -1631,39 +1305,6 @@ class ModelInstallService(ModelInstallServiceBase):self._install_thread.start()self._running = True- @staticmethod- def _safe_rmtree(path: Path, logger: Any) -> None:- """Remove a directory tree with retry logic for Windows file locking issues.-- On Windows, memory-mapped files may not be immediately released even after- the file handle is closed. This function retries the removal with garbage- collection to help release any lingering references.- """- max_retries = 3- retry_delay = 0.5 # seconds-- for attempt in range(max_retries):- try:- # Force garbage collection to release any lingering file references- gc.collect()- rmtree(path)- return- except PermissionError as e:- if attempt < max_retries - 1 and sys.platform == "win32":- logger.warning(- f"Failed to remove {path} (attempt {attempt + 1}/{max_retries}): {e}. "- f"Retrying in {retry_delay}s..."- )- time.sleep(retry_delay)- retry_delay *= 2 # Exponential backoff- else:- logger.error(f"Failed to remove temporary directory {path}: {e}")- # On final failure, don't raise - the temp dir will be cleaned up on next startup- return- except Exception as e:- logger.error(f"Unexpected error removing {path}: {e}")- return-def _install_next_item(self) -> None:self._logger.debug(f"Installer thread {threading.get_ident()} starting")while True:@@ -1701,7 +1342,7 @@ class ModelInstallService(ModelInstallServiceBase):self._write_install_marker(job, status=InstallStatus.ERROR)except Exception as marker_error:self._logger.error(- f"Failed to persist install recovery marker in {job._install_tmpdir}: {marker_error}"+ f"Failed to persist install recovery marker in {self._staging_of(job).tmpdir}: {marker_error}")finally:@@ -1710,19 +1351,12 @@ class ModelInstallService(ModelInstallServiceBase):if self._active_install_job is job:self._active_install_job = Nonejob._install_phase = None- # Keep our staging claim until cleanup is finished so orphan cleanup cannot+ # Discarding keeps our staging claim until the tree is gone, 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),- )+ staging = self._staging_of(job)+ if not job._recovery_required:+ staging.discard()+ staging.finish(recovery_required=job._recovery_required, completed=job.complete)self._install_completed_event.set()self._install_queue.task_done()self._logger.info(f"Installer thread {threading.get_ident()} exiting")@@ -1731,14 +1365,7 @@ class ModelInstallService(ModelInstallServiceBase):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+ self._staging_of(job).begin_transfer()job._install_phase = "transferring"return True@@ -1756,15 +1383,11 @@ class ModelInstallService(ModelInstallServiceBase):# 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)+ staging = self._staging_of(job)+ staging.claim()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+ staging.protect_source(Path(job.source.path))if isinstance(job.source, ExternalModelSource):with self._lock:@@ -1789,8 +1412,7 @@ class ModelInstallService(ModelInstallServiceBase):if isinstance(job.source_metadata, (HuggingFaceMetadata)):job.config_in.source_api_response = job.source_metadata.api_response- if job._install_tmpdir is not None:- self._delete_install_marker(job._install_tmpdir)+ staging.delete_marker()if job.inplace:with self._lock:@@ -1821,20 +1443,15 @@ class ModelInstallService(ModelInstallServiceBase):returnexcept InstallRecoveryRequiredError:job._recovery_required = True- if job._install_tmpdir is not None:- try:- self._write_install_marker(job, status=job.status)- except Exception as marker_error:- self._logger.error(- f"Failed to persist install recovery marker in {job._install_tmpdir}: {marker_error}"- )+ try:+ self._write_install_marker(job, status=job.status)+ except Exception as marker_error:+ self._logger.error(f"Failed to persist install recovery marker in {staging.tmpdir}: {marker_error}")raiseexcept Exception:- if job._install_tmpdir is not None:- self._delete_recovery_sentinel(job._install_tmpdir)+ staging.end_transfer()raise- if job._install_tmpdir is not None:- self._delete_recovery_sentinel(job._install_tmpdir)+ staging.end_transfer()job.config_out = self.record_store.get_model(key)self._signal_job_completed(job)@@ -1923,39 +1540,6 @@ class ModelInstallService(ModelInstallServiceBase):# --------------------------------------------------------------------------------------------# Internal functions that manage the models directory# --------------------------------------------------------------------------------------------- def _remove_dangling_install_dirs(self) -> None:- """Remove leftover tmpdirs from aborted installs."""- path = self._app_config.models_path- registered_model_paths = {- (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}")- continue- resolved_tmpdir = tmpdir.resolve()- if any(- model_path == resolved_tmpdir or model_path.is_relative_to(resolved_tmpdir)- for model_path in registered_model_paths- ):- self._logger.debug(f"Preserving registered model directory {tmpdir}")- continue- if self._has_recovery_sentinel(tmpdir):- self._logger.warning(f"Preserving install recovery data in {tmpdir}")- continue- marker = self._read_install_marker(tmpdir)- if marker is None:- self._logger.info(f"Removing dangling temporary directory {tmpdir}")- self._remove_unclaimed_install_tmpdir(tmpdir)- continue- status = marker.get("status")- if marker.get("recovery_required") is True:- self._logger.warning(f"Preserving install recovery data in {tmpdir}")- continue- if status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:- self._logger.info(f"Removing completed/errored temporary directory {tmpdir}")- 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."""missing_models: list[AnyModelConfig] = []@@ -1975,12 +1559,11 @@ class ModelInstallService(ModelInstallServiceBase):installed_model_paths = {(self._app_config.models_path / x.path).resolve() for x in self.record_store.all_models()}- models_path = self._app_config.models_path.resolve()# The bool returned by this callback determines if the model is added to the list of models found by the searchdef on_model_found(model_path: Path) -> bool:resolved_path = model_path.resolve()- if is_recovery_protected_path(resolved_path, models_path):+ if self._ledger.is_protected(resolved_path):self._logger.warning(f"Skipping recovery-protected model path {model_path}")return False# Already registered models should be in the list of found models, but not re-registered.@@ -2076,8 +1659,7 @@ class ModelInstallService(ModelInstallServiceBase):legacy_config_path = legacy_config_path.relative_to(self.app_config.legacy_conf_path)info.config_path = legacy_config_path.as_posix()self.record_store.add_model(info)- if self._has_recovery_sentinel(recovery_root):- self._delete_recovery_sentinel(recovery_root)+ self._ledger.clear_recovery(recovery_root)return info.keydef _next_id(self) -> int:@@ -2094,13 +1676,15 @@ class ModelInstallService(ModelInstallServiceBase):def _import_local_model(self, source: LocalModelSource, config: Optional[ModelRecordChanges] = None) -> ModelInstallJob:- return ModelInstallJob(+ job = ModelInstallJob(id=self._next_id(),source=source,config_in=config or ModelRecordChanges(),local_path=Path(source.path),inplace=source.inplace or False,)+ job._staging = InstallStaging(self._ledger)+ return jobdef _import_from_hf(self,@@ -2133,13 +1717,15 @@ class ModelInstallService(ModelInstallServiceBase):source: ExternalModelSource,config: Optional[ModelRecordChanges] = None,) -> ModelInstallJob:- return ModelInstallJob(+ job = ModelInstallJob(id=self._next_id(),source=source,config_in=config or ModelRecordChanges(),local_path=self._app_config.models_path,inplace=True,)+ job._staging = InstallStaging(self._ledger)+ return jobdef _import_remote_model(self,@@ -2150,25 +1736,18 @@ class ModelInstallService(ModelInstallServiceBase):) -> ModelInstallJob:if len(remote_files) == 0:raise ValueError(f"{source}: No downloadable files found")- destdir = self._find_reusable_tmpdir(source)- if destdir is None:- destdir = Path(- mkdtemp(- dir=self._app_config.models_path,- prefix=TMPDIR_PREFIX,- )- )+ staging = self._ledger.create_staging(str(source))+ assert staging.tmpdir is not Noneinstall_job = ModelInstallJob(id=self._next_id(),source=source,config_in=config or ModelRecordChanges(),source_metadata=metadata,- local_path=destdir, # local path may change once the download has started due to content-disposition handling+ local_path=staging.tmpdir, # local path may change once the download has started due to content-disposition handlingbytes=0,total_bytes=0,)- # remember the temporary directory for later removal- install_job._install_tmpdir = destdir+ install_job._staging = staging# Handle multiple subfolders for HFModelSourcesubfolders = source.subfolders if isinstance(source, HFModelSource) else []@@ -2177,7 +1756,6 @@ class ModelInstallService(ModelInstallServiceBase):source=source,remote_files=remote_files,metadata=metadata,- destdir=destdir,subfolder=source.subfolder if isinstance(source, HFModelSource) and len(subfolders) <= 1 else None,subfolders=subfolders if len(subfolders) > 1 else None,)@@ -2188,7 +1766,6 @@ class ModelInstallService(ModelInstallServiceBase):source: HFModelSource | URLModelSource,remote_files: List[RemoteModelFile],metadata: Optional[AnyModelRepoMetadata],- destdir: Path,subfolder: Optional[Path] = None,subfolders: Optional[List[Path]] = None,resume_metadata: Optional[dict] = None,@@ -2198,13 +1775,14 @@ class ModelInstallService(ModelInstallServiceBase):previous_source_metadata = job.source_metadataprevious_status = job.statusprevious_local_path = job.local_path- previous_install_tmpdir = job._install_tmpdirprevious_total_bytes = job.total_bytesprevious_multifile_job = job._multifile_jobprevious_download_parts = job.download_parts- job._install_tmpdir = destdir- claim_was_already_held = job._install_tmpdir_active_sentinel_created- self._claim_install_tmpdir(job)+ staging = self._staging_of(job)+ destdir = staging.tmpdir+ assert destdir is not None, "a remote install downloads into its staging directory"+ claim_was_already_held = staging.claimed+ staging.claim()multifile_job: Optional[MultiFileDownloadJob] = Nonetry:@@ -2263,7 +1841,6 @@ class ModelInstallService(ModelInstallServiceBase):passjob.source_metadata = metadatajob.local_path = destdir- job._install_tmpdir = destdirjob.total_bytes = sum((x.size or 0) for x in remote_files)job._multifile_job = multifile_jobjob.download_parts = multifile_job.download_parts@@ -2278,12 +1855,11 @@ class ModelInstallService(ModelInstallServiceBase):job.source_metadata = previous_source_metadatajob.status = previous_statusjob.local_path = previous_local_path- job._install_tmpdir = previous_install_tmpdirjob.total_bytes = previous_total_bytesjob._multifile_job = previous_multifile_jobjob.download_parts = previous_download_partsif not claim_was_already_held:- self._release_install_tmpdir_claim(job)+ staging.release_claim()raisefiles_string = "file" if len(remote_files) == 1 else "files"@@ -2298,12 +1874,11 @@ class ModelInstallService(ModelInstallServiceBase):job.source_metadata = previous_source_metadatajob.status = previous_statusjob.local_path = previous_local_path- job._install_tmpdir = previous_install_tmpdirjob.total_bytes = previous_total_bytesjob._multifile_job = previous_multifile_jobjob.download_parts = previous_download_partsif not claim_was_already_held:- self._release_install_tmpdir_claim(job)+ staging.release_claim()raisereturn job@@ -2417,7 +1992,7 @@ class ModelInstallService(ModelInstallServiceBase):returninstall_job.status = InstallStatus.DOWNLOADING- if install_job.local_path == install_job._install_tmpdir: # first time+ if install_job.local_path == self._staging_of(install_job).tmpdir: # first timeassert download_job.download_pathinstall_job.local_path = download_job.download_pathinstall_job.download_parts = download_job.download_parts@@ -2446,17 +2021,17 @@ class ModelInstallService(ModelInstallServiceBase):with self._lock:if install_job := self._download_cache.pop(download_job.id, None):if install_job.cancelled:- self._cleanup_cancelled_install(install_job)+ self._discard_cancelled_staging(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)+ self._staging_of(install_job).release_claim()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)+ self._staging_of(install_job).release_claim()queued = Trueelse:queued = self._queue_install_job_locked(install_job)@@ -2473,39 +2048,26 @@ class ModelInstallService(ModelInstallServiceBase):if install_job := self._download_cache.pop(download_job.id, None):assert excp is not Noneif install_job.cancelled:- self._cleanup_cancelled_install(install_job)+ self._discard_cancelled_staging(install_job)elif install_job.paused:# Preserve the explicit pause even if an already-terminal download reports its error late.self._write_install_marker(install_job, status=InstallStatus.PAUSED)if self._stop_event.is_set():- self._release_install_tmpdir_claim(install_job)+ self._staging_of(install_job).release_claim()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)+ self._staging_of(install_job).discard()# 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 install_job.cancelled:- self._cleanup_cancelled_install(install_job)+ self._discard_cancelled_staging(install_job)returnif install_job.paused or any(part.resume_required for part in download_job.download_parts):install_job.status = InstallStatus.PAUSED@@ -2513,20 +2075,15 @@ class ModelInstallService(ModelInstallServiceBase):# 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._staging_of(install_job).release_claim()self._downloads_changed_event.set()return+ staging = self._staging_of(install_job)# 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 install_job._install_tmpdir_claim_conflict:- # Mark cancelled before cleanup so we don't reuse the folder if deletion fails.- 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)+ self._discard_cancelled_staging(install_job)+ staging.release_claim()# Let other threads know that the number of downloads has changedself._downloads_changed_event.set()@@ -2568,8 +2125,7 @@ class ModelInstallService(ModelInstallServiceBase):assert job.config_outself._logger.info(f"Model install complete: {job.source}")self._logger.debug(f"{job.local_path} registered key {job.config_out.key}")- if job._install_tmpdir is not None:- self._delete_install_marker(job._install_tmpdir)+ self._staging_of(job).delete_marker()if self._event_bus:assert job.local_path is not Noneassert job.config_out is not None@@ -2577,8 +2133,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 and not job._install_tmpdir_claim_conflict:- self._delete_install_marker(job._install_tmpdir)+ self._staging_of(job).delete_marker()if self._event_bus:assert job.error_type is not Noneassert job.error is not None@@ -2586,8 +2141,7 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_cancelled(self, job: ModelInstallJob) -> None:self._logger.info(f"Model install canceled: {job.source}")- if job._install_tmpdir is not None:- self._delete_install_marker(job._install_tmpdir)+ self._staging_of(job).delete_marker()if self._event_bus:self._event_bus.emit_model_install_cancelled(job)diff --git a/invokeai/app/services/orphaned_models/orphaned_models_service.py b/invokeai/app/services/orphaned_models/orphaned_models_service.pyindex 6892b7482e..74d6a472a6 100644--- a/invokeai/app/services/orphaned_models/orphaned_models_service.py+++ b/invokeai/app/services/orphaned_models/orphaned_models_service.py@@ -11,13 +11,8 @@ from typing import TYPE_CHECKING, Setfrom pydantic import BaseModel, Fieldfrom invokeai.app.services.config.config_default import InvokeAIAppConfig-from 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.model_install.install_staging_ledger import InstallStagingLedger+from invokeai.backend.util.logging import InvokeAILoggerif TYPE_CHECKING:from invokeai.app.services.model_records import ModelRecordServiceBase@@ -73,6 +68,7 @@ class OrphanedModelsService:"""self._config = configself._store = store+ self._logger = InvokeAILogger.get_logger(self.__class__.__name__)def find_orphaned_models(self) -> list[OrphanedModelInfo]:"""Find all orphaned model directories.@@ -81,6 +77,7 @@ class OrphanedModelsService:List of OrphanedModelInfo objects describing orphaned directories"""models_path = self._config.models_path.resolve()+ ledger = InstallStagingLedger(models_path, self._logger)# Get all model directories registered in the databasedb_model_directories = self._get_registered_model_directories(models_path)@@ -123,7 +120,8 @@ class OrphanedModelsService:# Convert to OrphanedModelInfo objectsresult = []for dir_path, files in orphaned_dirs_map.items():- if self._contains_recovery_sentinel(dir_path):+ # An install or orphan deletion owns the directory or something in it, or it holds recovery data.+ if ledger.is_protected(dir_path):continue# Calculate total sizetotal_size = sum(f.stat().st_size for f in files if f.exists())@@ -140,6 +138,33 @@ class OrphanedModelsService:))+ # A staging directory whose install marker is unusable holds no resumable install and no model files yet, often+ # only partial downloads. Startup keeps it rather than guess, so it is offered here.+ reported = {Path(info.absolute_path) for info in result}+ for staging_dir in ledger.abandoned_staging(db_model_directories):+ staging_dir = staging_dir.resolve()+ if staging_dir in reported:+ continue+ staged_files: list[str] = []+ staged_size = 0+ for path in staging_dir.rglob("*"):+ # A concurrent orphan deletion may remove files while this lists them.+ try:+ if not path.is_file():+ continue+ staged_size += path.stat().st_size+ except OSError:+ continue+ staged_files.append(str(path.relative_to(staging_dir)))+ result.append(+ OrphanedModelInfo(+ path=str(staging_dir.relative_to(models_path)),+ absolute_path=str(staging_dir),+ files=staged_files,+ size_bytes=staged_size,+ )+ )+return resultdef delete_orphaned_models(self, orphaned_paths: list[str]) -> dict[str, str]:@@ -152,6 +177,7 @@ class OrphanedModelsService:Dictionary mapping paths to status messages ("deleted" or error message)"""models_path = self._config.models_path.resolve()+ ledger = InstallStagingLedger(models_path, self._logger)conversion_scratch_path = (models_path / CONVERSION_SCRATCH_DIRNAME).resolve()results = {}@@ -177,15 +203,7 @@ class OrphanedModelsService:results[rel_path] = "error: path is reserved for active conversion"continue- if self._is_recovery_protected(full_path, models_path):- results[rel_path] = "error: path is reserved by an active install or install recovery"- continue-- if self._contains_recovery_sentinel(full_path):- results[rel_path] = "error: path contains install recovery data"- continue-- if self._contains_active_install_sentinel(full_path):+ if ledger.is_protected(full_path):results[rel_path] = "error: path is reserved by an active install or install recovery"continue@@ -194,35 +212,21 @@ class OrphanedModelsService:continueclaim_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.+ # Claim deletion atomically so a local install cannot start using this source after the check.try:- create_active_install_sentinel(claim_root)+ claim = ledger.claim(claim_root)except FileExistsError:results[rel_path] = "error: path is reserved by an active install or install recovery"continue- try:+ with claim: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)}"return results- @staticmethod- def _is_recovery_protected(path: Path, models_path: Path) -> bool:- return is_recovery_protected_path(path, models_path)-- @staticmethod- 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()@@ -260,11 +264,7 @@ class OrphanedModelsService:if any(skip_dir in item.parts for skip_dir in self.SKIP_DIRS):continue- if (- item.is_file()- and item.suffix.lower() in self.MODEL_EXTENSIONS- and not self._is_recovery_protected(item.parent, models_path)- ):+ if item.is_file() and item.suffix.lower() in self.MODEL_EXTENSIONS:model_files.add(item.resolve())return model_filesdiff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.pyindex 3bb03ce618..f99c69826c 100644--- a/tests/app/routers/test_update_model_record_cache_invalidation.py+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py@@ -462,7 +462,7 @@ def test_reidentify_preserves_ip_adapter_encoder_override_with_blank_metadata(models_path = tmp_path / "models"model_path = models_path / "ip-adapter"model_path.mkdir(parents=True)- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, model_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, model_path / "ip_adapter.bin")(model_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")result = ModelConfigFactory.from_model_on_disk(model_path, override_fields={"image_encoder_model_id": "custom/image-encoder"}, allow_unknown=Falsediff --git a/tests/app/services/model_install/test_install_staging_ledger.py b/tests/app/services/model_install/test_install_staging_ledger.pynew file mode 100644index 0000000000..1abd9acf16--- /dev/null+++ b/tests/app/services/model_install/test_install_staging_ledger.py@@ -0,0 +1,1131 @@+"""The install staging ledger on a real models directory: claims, markers, recovery marks and startup recovery.++Expected on-disk names are spelled out here rather than taken from the ledger: they are the format version 1 contract+that markers and sidecars written by earlier releases rely on.+"""++import errno+import gc+import json+import os+import platform+import stat+import sys+import threading+from pathlib import Path+from typing import Any, Optional++import pytest++from invokeai.app.services.model_install import install_staging_ledger+from invokeai.app.services.model_install.install_staging_ledger import (+ INSTALL_ACTIVE_SCAN_LOCK,+ MAX_ACTIVE_CLAIM_DIAGNOSTICS,+ InstallStaging,+ InstallStagingLedger,+)+from invokeai.app.services.model_install.model_install_common import (+ InstallCancellationConflictError,+ InstallStatus,+ URLModelSource,+)+from invokeai.app.services.model_records import ModelRecordChanges+from invokeai.backend.util.logging import InvokeAILogger++SOURCE = "https://example.com/weights.safetensors"+# A PID above any real pid_max, so its owner is reliably gone.+DEAD_OWNER = "2147483647 1.0\n"++[email protected](autouse=True)+def _collect_only_this_tests_objects():+ """Removing a staging tree runs gc.collect() to release file handles. A full collection walks the worker's whole+ heap; freezing what existed before the test leaves each collection to the objects the test created."""+ gc.freeze()+ yield+ gc.unfreeze()+++def models_path(tmp_path: Path) -> Path:+ path = tmp_path / "models"+ path.mkdir()+ return path+++def ledger(models_path: Path) -> InstallStagingLedger:+ return InstallStagingLedger(models_path, InvokeAILogger.get_logger("InstallStagingLedgerTest"))+++def _claim_path(root: Path) -> Path:+ return root.parent / f".{root.name}.invokeai_install_active"+++def _recovery_path(root: Path) -> Path:+ return root.parent / f".{root.name}.invokeai_install_recovery_required"+++def _marker_path(tmpdir: Path) -> Path:+ return tmpdir / ".invokeai_install.json"+++def _staging_dir(models_path: Path, name: str, payload: bytes = b"partial download") -> Path:+ tmpdir = models_path / f"tmpinstall_{name}"+ tmpdir.mkdir()+ (tmpdir / "weights.safetensors.downloading").write_bytes(payload)+ return tmpdir+++def _write_v1_marker(tmpdir: Path, status: str = "downloading", **fields: Any) -> dict[str, Any]:+ """Write a marker as releases with format version 1 wrote it."""+ marker: dict[str, Any] = {+ "version": 1,+ "source": SOURCE,+ "access_token": None,+ "config_in": {},+ "status": status,+ "updated_at": "2026-01-01T00:00:00",+ "files": [],+ **fields,+ }+ _marker_path(tmpdir).write_text(json.dumps(marker), encoding="utf-8")+ return marker+++def _persist(staging: InstallStaging, status: InstallStatus, **overrides: Any) -> None:+ arguments: dict[str, Any] = {+ "source": URLModelSource(url=SOURCE),+ "config_in": ModelRecordChanges(),+ "status": status,+ "download_parts": [],+ "resume_files": None,+ "recovery_required": False,+ **overrides,+ }+ staging.persist(**arguments)+++def _read_marker(tmpdir: Path) -> Optional[dict[str, Any]]:+ path = _marker_path(tmpdir)+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None+++# --------------------------------------------------------------------------------------------------------------------+# Markers and startup recovery+# --------------------------------------------------------------------------------------------------------------------++[email protected]("recovery_field", [{}, {"recovery_required": False}], ids=["no-flag", "flag-false"])+def test_a_v1_marker_from_an_earlier_release_is_restored_as_written(+ ledger: InstallStagingLedger, models_path: Path, recovery_field: dict[str, Any]+) -> None:+ tmpdir = _staging_dir(models_path, "legacy")+ files = [{"url": SOURCE, "etag": '"v1"', "download_path": (tmpdir / "weights.safetensors").as_posix()}]+ _write_v1_marker(+ tmpdir, status="paused", access_token="secret", config_in={"name": "kept"}, files=files, **recovery_field+ )++ [entry] = ledger.recoverable_installs()++ assert entry.staging.tmpdir == tmpdir+ assert not entry.staging.claimed+ assert entry.status is InstallStatus.PAUSED+ assert (entry.source, entry.access_token, entry.config_in, entry.files) == (+ SOURCE,+ "secret",+ {"name": "kept"},+ files,+ )+++def test_a_marker_without_status_restores_as_waiting(ledger: InstallStagingLedger, models_path: Path) -> None:+ _write_v1_marker(_staging_dir(models_path, "no-status"), status="")++ [entry] = ledger.recoverable_installs()++ assert entry.status is InstallStatus.WAITING+++def test_persisted_state_round_trips_through_startup_recovery(ledger: InstallStagingLedger) -> None:+ staging = ledger.create_staging(SOURCE)+ assert staging.tmpdir is not None and staging.tmpdir.name.startswith("tmpinstall_")+ resume_files = {SOURCE: {"url": SOURCE, "etag": '"v2"', "resume_required": True}}++ _persist(+ staging,+ InstallStatus.DOWNLOADING,+ source=URLModelSource(url=SOURCE, access_token="token"),+ config_in=ModelRecordChanges(name="my model"),+ resume_files=resume_files,+ )++ marker = _read_marker(staging.tmpdir)+ assert marker is not None+ assert marker["version"] == 1+ assert marker["status"] == "downloading"+ assert marker["access_token"] == "token"+ assert "recovery_required" not in marker+ [entry] = ledger.recoverable_installs()+ assert entry.staging.tmpdir == staging.tmpdir+ assert entry.status is InstallStatus.DOWNLOADING+ assert entry.source == SOURCE+ assert entry.access_token == "token"+ assert entry.config_in["name"] == "my model"+ assert entry.files == list(resume_files.values())+++def test_a_failed_marker_write_keeps_the_previous_marker(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ staging = InstallStaging(ledger, _staging_dir(models_path, "failed-write"))+ assert staging.tmpdir is not None+ _persist(staging, InstallStatus.DOWNLOADING)+ previous = _marker_path(staging.tmpdir).read_bytes()++ def write_half_then_fail(marker: dict[str, Any], f: Any) -> None:+ f.write(json.dumps(marker)[:10])+ raise OSError(errno.ENOSPC, "simulated disk full")++ monkeypatch.setattr(install_staging_ledger.json, "dump", write_half_then_fail)++ with pytest.raises(OSError, match="simulated disk full"):+ _persist(staging, InstallStatus.PAUSED)++ assert _marker_path(staging.tmpdir).read_bytes() == previous+ assert sorted(path.name for path in staging.tmpdir.iterdir()) == [+ ".invokeai_install.json",+ "weights.safetensors.downloading",+ ]+++def test_a_marker_replace_refused_by_an_open_reader_is_retried(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Windows refuses os.replace onto a file another handle holds open."""+ staging = InstallStaging(ledger, _staging_dir(models_path, "contended-write"))+ assert staging.tmpdir is not None+ _persist(staging, InstallStatus.DOWNLOADING)+ real_replace = os.replace+ refusals = 2++ def refuse_then_replace(src: Any, dst: Any) -> None:+ nonlocal refusals+ if refusals:+ refusals -= 1+ raise PermissionError(errno.EACCES, "file is open in another process")+ real_replace(src, dst)++ monkeypatch.setattr(install_staging_ledger.os, "replace", refuse_then_replace)+ monkeypatch.setattr(install_staging_ledger, "_MARKER_REPLACE_RETRY_SECONDS", 0.0)++ _persist(staging, InstallStatus.PAUSED)++ assert refusals == 0+ assert _read_marker(staging.tmpdir)["status"] == "paused" # type: ignore[index]+++def test_a_temporary_marker_left_by_a_crash_is_ignored_and_removed_with_the_marker(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ tmpdir = _staging_dir(models_path, "crashed-mid-write")+ _write_v1_marker(tmpdir, status="downloads_done")+ leftover = tmpdir / ".invokeai_install.json.k2j4f8.tmp"+ leftover.write_text('{"version": 1, "sta', encoding="utf-8")++ [entry] = ledger.recoverable_installs()+ assert entry.status is InstallStatus.DOWNLOADS_DONE+ entry.staging.delete_marker()++ assert not _marker_path(tmpdir).exists()+ assert not leftover.exists()++[email protected]("status", ["completed", "error", "cancelled"])+def test_terminal_staging_is_removed_at_startup_and_never_restored(+ ledger: InstallStagingLedger, models_path: Path, status: str+) -> None:+ tmpdir = _staging_dir(models_path, status)+ _write_v1_marker(tmpdir, status=status)++ assert list(ledger.recoverable_installs()) == []+ ledger.remove_dangling_staging([])++ assert not tmpdir.exists()+ assert not _claim_path(tmpdir).exists()+++def test_startup_cleanup_removes_markerless_staging_and_keeps_resumable_and_registered_dirs(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ markerless = _staging_dir(models_path, "markerless")+ resumable = _staging_dir(models_path, "resumable")+ _write_v1_marker(resumable)+ registered = _staging_dir(models_path, "registered-model")++ ledger.remove_dangling_staging([(registered / "weights.safetensors.downloading").resolve()])++ assert not markerless.exists()+ assert resumable.exists()+ assert registered.exists()+++def test_recovery_required_marker_is_neither_restored_nor_removed_nor_reused(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ staging = InstallStaging(ledger, _staging_dir(models_path, "recovery", b"recoverable source"))+ assert staging.tmpdir is not None++ _persist(staging, InstallStatus.ERROR, recovery_required=True)+ ledger.remove_dangling_staging([])++ assert _read_marker(staging.tmpdir)["recovery_required"] is True # type: ignore[index]+ assert (staging.tmpdir / "weights.safetensors.downloading").read_bytes() == b"recoverable source"+ _write_v1_marker(staging.tmpdir, status="downloading", recovery_required=True)+ assert list(ledger.recoverable_installs()) == []+ assert ledger.create_staging(SOURCE).tmpdir != staging.tmpdir+++ "marker_bytes",+ [+ b'{"version": 1, "source": "https://example.com/weights.safe',+ b"\xff\xfe not utf-8",+ b"[1, 2]",+ json.dumps({"version": 2, "source": SOURCE, "status": "downloading"}).encode(),+ ],+ ids=["torn", "not-utf-8", "not-an-object", "unknown-version"],+)+def test_staging_with_an_unusable_marker_is_kept_reported_and_left_to_orphan_cleanup(+ ledger: InstallStagingLedger, models_path: Path, caplog: pytest.LogCaptureFixture, marker_bytes: bytes+) -> None:+ tmpdir = _staging_dir(models_path, "unusable", b"only copy of a long download")+ _marker_path(tmpdir).write_bytes(marker_bytes)++ with caplog.at_level("WARNING"):+ ledger.remove_dangling_staging([])++ assert (tmpdir / "weights.safetensors.downloading").read_bytes() == b"only copy of a long download"+ assert f"Preserving install staging directory {tmpdir}" in caplog.text+ assert list(ledger.recoverable_installs()) == []+ assert ledger.create_staging(SOURCE).tmpdir != tmpdir+ assert not ledger.is_protected(tmpdir), "orphaned model cleanup must still be able to remove it"+ assert ledger.abandoned_staging([]) == [tmpdir]+++def test_reuse_picks_the_newest_resumable_staging_of_the_same_source(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ older = _staging_dir(models_path, "older")+ _write_v1_marker(older, updated_at="2026-01-01T00:00:00")+ newer = _staging_dir(models_path, "newer")+ _write_v1_marker(newer, updated_at="2026-02-01T00:00:00")+ other_source = _staging_dir(models_path, "other")+ _write_v1_marker(other_source, source="https://example.com/other.safetensors", updated_at="2026-03-01T00:00:00")+ finished = _staging_dir(models_path, "finished")+ _write_v1_marker(finished, status="completed", updated_at="2026-04-01T00:00:00")+ claimed = _staging_dir(models_path, "claimed")+ _write_v1_marker(claimed, updated_at="2026-05-01T00:00:00")++ with ledger.claim(claimed):+ assert ledger.create_staging(SOURCE).tmpdir == newer+++def test_restore_skips_claimed_and_recovery_marked_staging(ledger: InstallStagingLedger, models_path: Path) -> None:+ claimed = _staging_dir(models_path, "claimed")+ _write_v1_marker(claimed)+ marked = _staging_dir(models_path, "marked")+ _write_v1_marker(marked)+ ledger.mark_recovery_required(marked)++ with ledger.claim(claimed):+ assert list(ledger.recoverable_installs()) == []+ ledger.remove_dangling_staging([])++ assert claimed.exists()+ assert marked.exists()+++def test_staging_claimed_by_a_crashed_process_is_recovered_after_the_sweep(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ """A process that died while it held its claim never released it; the sweep proves the owner gone."""+ tmpdir = _staging_dir(models_path, "crashed-owner")+ _write_v1_marker(tmpdir)+ _claim_path(tmpdir).write_text(DEAD_OWNER, encoding="ascii")++ assert list(ledger.recoverable_installs()) == []+ ledger.sweep_stale_claims()+ [entry] = ledger.recoverable_installs()++ assert entry.staging.tmpdir == tmpdir+ entry.staging.claim()+ assert entry.staging.claimed+ assert _claim_path(tmpdir).read_text(encoding="ascii").split()[0] == str(os.getpid())+ entry.staging.release_claim()+ assert not _claim_path(tmpdir).exists()+++def test_a_crash_during_transfer_leaves_staging_protected_across_restart(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ """The recovery mark is durable before any file moves, so a crash mid-transfer never exposes the tree."""+ tmpdir = _staging_dir(models_path, "mid-transfer")+ _write_v1_marker(tmpdir, status="running")+ staging = InstallStaging(ledger, tmpdir)+ staging.begin_transfer()+ # The process dies here: its claim stays behind until the next startup sweeps it.+ _claim_path(tmpdir).write_text(DEAD_OWNER, encoding="ascii")++ ledger.sweep_stale_claims()+ ledger.remove_dangling_staging([])++ assert tmpdir.exists()+ assert _recovery_path(tmpdir).exists()+ assert list(ledger.recoverable_installs()) == []+ assert ledger.is_protected(tmpdir)+++def test_discard_without_a_claim_spares_a_tree_another_owner_holds(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ tmpdir = _staging_dir(models_path, "owned-elsewhere")++ with ledger.claim(tmpdir):+ InstallStaging(ledger, tmpdir).discard()+ assert tmpdir.exists()++ InstallStaging(ledger, tmpdir).discard()+ assert not tmpdir.exists()+ assert not _claim_path(tmpdir).exists()+++def test_discard_keeps_recovery_data_and_releases_the_claim(ledger: InstallStagingLedger, models_path: Path) -> None:+ claimed = InstallStaging(ledger, _staging_dir(models_path, "kept-claimed", b"recovery data"))+ claimed.claim()+ unclaimed = InstallStaging(ledger, _staging_dir(models_path, "kept-unclaimed", b"recovery data"))+ for staging in (claimed, unclaimed):+ assert staging.tmpdir is not None+ ledger.mark_recovery_required(staging.tmpdir)++ staging.discard()++ assert (staging.tmpdir / "weights.safetensors.downloading").read_bytes() == b"recovery data"+ assert not staging.claimed+ assert not _claim_path(staging.tmpdir).exists()++[email protected]("change", ["marker-written", "unusable-marker-written", "recovery-marked"])+def test_startup_cleanup_rechecks_a_staging_dir_once_it_holds_the_claim(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch, change: str+) -> None:+ """Another process may change the directory between cleanup's decision and its claim."""+ tmpdir = _staging_dir(models_path, "changed-before-claim")+ real_publish = install_staging_ledger._publish_claim++ def change_then_publish(root: Path) -> None:+ if root == tmpdir:+ if change == "marker-written":+ _write_v1_marker(tmpdir)+ elif change == "unusable-marker-written":+ _marker_path(tmpdir).write_text('{"version": 2}', encoding="utf-8")+ else:+ _recovery_path(tmpdir).write_text("preserve", encoding="utf-8")+ real_publish(root)++ monkeypatch.setattr(install_staging_ledger, "_publish_claim", change_then_publish)++ ledger.remove_dangling_staging([])++ assert (tmpdir / "weights.safetensors.downloading").exists()+ assert not _claim_path(tmpdir).exists()+++def test_a_claimed_tree_is_discarded_and_its_claim_released(ledger: InstallStagingLedger, models_path: Path) -> None:+ staging = InstallStaging(ledger, _staging_dir(models_path, "discarded"))+ staging.claim()+ assert staging.tmpdir is not None++ staging.discard()++ assert not staging.tmpdir.exists()+ assert not _claim_path(staging.tmpdir).exists()+ assert not staging.claimed+++def test_a_staging_tree_cannot_be_discarded_mid_transfer(ledger: InstallStagingLedger, models_path: Path) -> None:+ tmpdir = _staging_dir(models_path, "mid-transfer-discard")+ staging = InstallStaging(ledger, tmpdir)+ staging.begin_transfer()++ with pytest.raises(AssertionError, match="end the transfer"):+ staging.discard()+ assert tmpdir.exists()++ staging.end_transfer()+ staging.discard()+ assert not tmpdir.exists()+++def test_after_a_claim_conflict_the_other_owner_keeps_the_tree_and_marker(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ tmpdir = _staging_dir(models_path, "conflict-cleanup")+ _write_v1_marker(tmpdir)+ contender = InstallStaging(ledger, tmpdir)++ with ledger.claim(tmpdir):+ with pytest.raises(InstallCancellationConflictError):+ contender.claim()+ contender.delete_marker()+ contender.discard()++ assert _marker_path(tmpdir).exists()+ assert _claim_path(tmpdir).exists()+++def test_a_second_claim_on_staging_is_refused_and_recorded(ledger: InstallStagingLedger, models_path: Path) -> None:+ tmpdir = _staging_dir(models_path, "contended")+ owner = InstallStaging(ledger, tmpdir)+ owner.claim()+ contender = InstallStaging(ledger, tmpdir)++ with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):+ contender.claim()++ assert contender.claim_conflict+ assert not contender.claimed+ owner.release_claim()+ contender.claim()+ assert contender.claimed and not contender.claim_conflict+ contender.release_claim()++[email protected]("root_kind", ["staging", "source"])+def test_release_drops_claims_before_it_clears_recovery_marks(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch, root_kind: str+) -> None:+ """A crash between the two steps must leave recovery marks, which preserve the data, not claims."""+ if root_kind == "staging":+ root = _staging_dir(models_path, "release-order")+ staging = InstallStaging(ledger, root)+ else:+ root = models_path / "local-source"+ root.mkdir()+ staging = InstallStaging(ledger)+ staging.protect_source(root)+ staging.begin_transfer()+ assert _recovery_path(root).exists()+ unlinked: list[str] = []+ real_unlink = Path.unlink++ def record_unlink(path: Path, *args: Any, **kwargs: Any) -> None:+ unlinked.append(path.name)+ real_unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", record_unlink)++ staging.release(preserve_recovery=False, completed=True)++ assert unlinked == [_claim_path(root).name, _recovery_path(root).name]+++def test_release_preserving_recovery_keeps_the_marks(ledger: InstallStagingLedger, models_path: Path) -> None:+ tmpdir = _staging_dir(models_path, "preserved")+ staging = InstallStaging(ledger, tmpdir)+ staging.begin_transfer()++ staging.release(preserve_recovery=True, completed=False)++ assert not _claim_path(tmpdir).exists()+ assert _recovery_path(tmpdir).exists()+++def test_source_protection_claims_the_top_level_root_and_clears_only_resolved_recovery(+ ledger: InstallStagingLedger, models_path: Path, tmp_path: Path+) -> None:+ source_root = models_path / "local-source"+ nested = source_root / "nested"+ nested.mkdir(parents=True)+ ledger.mark_recovery_required(source_root)+ staging = InstallStaging(ledger)++ staging.protect_source(nested)++ assert _claim_path(source_root).exists()+ staging.release(preserve_recovery=False, completed=False)+ assert not _claim_path(source_root).exists()+ assert _recovery_path(source_root).exists(), "an unfinished install must keep recovery data it did not create"++ registered = InstallStaging(ledger)+ registered.protect_source(nested)+ registered.release(preserve_recovery=False, completed=True)+ assert not _recovery_path(source_root).exists(), "completing resolves the recovery data the source held"++ outside = InstallStaging(ledger)+ outside.protect_source(tmp_path)+ assert not _claim_path(tmp_path).exists()+ outside.release(preserve_recovery=False, completed=True)+++def test_an_unfinished_job_keeps_the_marks_of_a_source_that_already_held_recovery_data(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ source_root = models_path / "local-source"+ recovered = source_root / "recovered"+ recovered.mkdir(parents=True)+ ledger.mark_recovery_required(recovered)+ staging = InstallStaging(ledger)+ staging.protect_source(recovered)+ staging.begin_transfer()++ staging.finish(recovery_required=False, completed=False)++ assert not _claim_path(source_root).exists()+ assert _recovery_path(source_root).exists(), "the mark this job made stays until the job completes"+ assert _recovery_path(recovered).exists()++ completed = InstallStaging(ledger)+ completed.protect_source(recovered)+ completed.finish(recovery_required=False, completed=True)+ assert not _recovery_path(source_root).exists()+ assert not _claim_path(source_root).exists()+++def test_source_protection_refuses_a_root_held_by_another_owner(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ source_root = models_path / "local-source"+ nested = source_root / "nested"+ nested.mkdir(parents=True)++ with ledger.claim(nested):+ with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):+ InstallStaging(ledger).protect_source(nested)+ with ledger.claim(source_root):+ with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):+ InstallStaging(ledger).protect_source(nested)++ assert not _claim_path(source_root).exists()+++def test_is_protected_covers_the_path_its_ancestors_and_its_contents(+ ledger: InstallStagingLedger, models_path: Path+) -> None:+ group = models_path / "group"+ recovered = group / "recovered"+ recovered.mkdir(parents=True)+ ordinary = models_path / "ordinary"+ ordinary.mkdir()+ ledger.mark_recovery_required(recovered)++ assert ledger.is_protected(recovered)+ assert ledger.is_protected(recovered / "weights.safetensors")+ assert ledger.is_protected(group), "deleting the parent would delete the recovery root"+ assert not ledger.is_protected(ordinary)++ with ledger.claim(ordinary):+ assert ledger.is_protected(ordinary / "sub")+ assert not ledger.is_protected(ordinary)++ with ledger.claim(ordinary / "child"):+ assert ledger.is_protected(ordinary), "deleting the parent would delete the claimed child"+ assert not ledger.is_protected(ordinary)+++def test_retain_recovery_marks_an_existing_root_once_without_logging(+ ledger: InstallStagingLedger, models_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ dest_dir = models_path / "model"+ dest_dir.mkdir()+ ledger.mark_recovery_required(dest_dir)++ with caplog.at_level("ERROR"):+ ledger.retain_recovery(dest_dir)+ ledger.retain_recovery(models_path / "missing")++ assert _recovery_path(dest_dir).exists()+ assert not _recovery_path(models_path / "missing").exists()+ assert "Failed to persist destination recovery sentinel" not in caplog.text++[email protected]("error_number", [errno.EINVAL, errno.EIO])[email protected](os.name == "nt", reason="directory fsync is skipped on Windows")+def test_clearing_recovery_logs_a_directory_fsync_failure(+ ledger: InstallStagingLedger,+ models_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ error_number: int,+) -> None:+ root = models_path / "recovery-root"+ root.mkdir()+ _recovery_path(root).write_text("preserve until cleanup", encoding="utf-8")+ real_fsync = os.fsync++ def failing_directory_fsync(fd: int) -> None:+ if stat.S_ISDIR(os.fstat(fd).st_mode):+ raise OSError(error_number, "scripted directory fsync failure")+ real_fsync(fd)++ monkeypatch.setattr(install_staging_ledger.os, "fsync", failing_directory_fsync)++ ledger.clear_recovery(root)++ assert not _recovery_path(root).exists()+ assert "Failed to remove install recovery sentinel" in caplog.text+++# --------------------------------------------------------------------------------------------------------------------+# Active claims and the startup sweep+# --------------------------------------------------------------------------------------------------------------------+++def test_sweep_removes_stale_but_preserves_live_claims(ledger: InstallStagingLedger, models_path: Path) -> None:+ stale_root = models_path / "stale-claim"+ live_root = models_path / "live-claim"+ stale_root.mkdir()+ live_root.mkdir()+ _claim_path(stale_root).write_text(DEAD_OWNER, encoding="ascii")++ with ledger.claim(live_root):+ ledger.sweep_stale_claims()++ assert not _claim_path(stale_root).exists()+ assert _claim_path(live_root).exists()+ assert not _claim_path(live_root).exists()+++def test_sweep_preserves_ambiguous_legacy_claim_after_large_start_time_drift(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ claimed_root = models_path / "claim-time-drift"+ claimed_root.mkdir()+ claim = _claim_path(claimed_root)+ claim.write_text("12345 100.0\n", encoding="ascii")+ observed_start_time = [100.75]++ class Process:+ def __init__(self, _pid: int) -> None:+ pass++ def status(self) -> str:+ return install_staging_ledger.psutil.STATUS_RUNNING++ def create_time(self) -> float:+ return observed_start_time[0]++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", Process)++ ledger.sweep_stale_claims()+ assert claim.exists()++ observed_start_time[0] = 102.0+ ledger.sweep_stale_claims()+ assert claim.exists()++[email protected](platform.system() != "Linux", reason="Linux process start ticks are used for stable claim identity")+def test_sweep_reclaims_linux_claim_when_pid_has_been_reused(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "claim-pid-reuse"+ root.mkdir()+ claim = _claim_path(root)+ current_identity = install_staging_ledger._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 install_staging_ledger.psutil.STATUS_RUNNING++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", LiveProcess)+ monkeypatch.setattr(install_staging_ledger, "_linux_process_start_identity", lambda _pid: f"{boot_id}:222")++ ledger.sweep_stale_claims()++ assert not claim.exists()+++def test_sweep_preserves_claim_while_its_payload_is_being_published(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "claim-being-published"+ root.mkdir()+ claim = _claim_path(root)+ claim_created = threading.Event()+ release_publish = threading.Event()+ creator_errors: list[BaseException] = []+ real_process = install_staging_ledger.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(install_staging_ledger.psutil, "Process", BlockedProcess)++ def create_claim() -> None:+ try:+ ledger.claim(root)+ except BaseException 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()+ ledger.sweep_stale_claims()+ ledger.claim(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(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "interrupted-claim-publication"+ root.mkdir()++ def exit_before_publication() -> None:+ raise SystemExit("simulated process exit before claim publication")++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", exit_before_publication)++ with pytest.raises(SystemExit, match="simulated process exit"):+ ledger.claim(root)++ assert not _claim_path(root).exists()+ assert list(models_path.iterdir()) == [root]+++ "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_sweep_preserves_malformed_claim_before_inspecting_owner(+ ledger: InstallStagingLedger,+ models_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ payload: str,+) -> None:+ root = models_path / "malformed-claim"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text(payload, encoding="ascii")+ inspected_pids: list[int] = []++ def inspect_process(pid: int) -> Any:+ inspected_pids.append(pid)+ raise install_staging_ledger.psutil.NoSuchProcess(pid)++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", inspect_process)++ ledger.sweep_stale_claims()++ assert claim.exists()+ assert inspected_pids == []+ assert "could not verify" in caplog.text.lower()+++def test_claim_publication_survives_temporary_unlink_failure(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "claim-temp-cleanup-failure"+ root.mkdir()+ claim = _claim_path(root)+ temp_paths: list[Path] = []+ real_link = 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(install_staging_ledger.os, "link", publish)+ patch.setattr(Path, "unlink", fail_temp_unlink)+ held = ledger.claim(root)+ assert claim.exists()+ assert len(claim.read_text(encoding="ascii").split()) >= 2+ held.release()+ assert not claim.exists()+ finally:+ for temp_path in temp_paths:+ real_unlink(temp_path, missing_ok=True)+++def test_sweep_bounds_unknown_claim_diagnostics(+ ledger: InstallStagingLedger, models_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ claims = []+ for index in range(MAX_ACTIVE_CLAIM_DIAGNOSTICS + 2):+ root = models_path / f"malformed-claim-{index}"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text("unknown owner", encoding="ascii")+ claims.append(claim)++ ledger.sweep_stale_claims()++ claim_warnings = [+ record.message for record in caplog.records if "Could not verify active install claim" in record.message+ ]+ assert len(claim_warnings) == 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_sweep_does_not_delete_replacement_claim_after_process_inspection(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "replaced-claim"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text(DEAD_OWNER, 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 install_staging_ledger.psutil.NoSuchProcess(pid=_pid)++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", DeadProcess)++ ledger.sweep_stale_claims()++ assert claim.read_text(encoding="ascii") == replacement+++def test_serialized_stale_claim_sweeps_preserve_a_claim_created_after_reap(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "serialized-claim-scan"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text(DEAD_OWNER, 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+ real_claim_scan_lock = install_staging_ledger._claim_scan_lock++ 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)++ 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(Path, "unlink", blocked_unlink)+ monkeypatch.setattr(install_staging_ledger, "_claim_scan_lock", ObservedClaimScanLock)++ def run_scan() -> None:+ try:+ ledger.sweep_stale_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+ )++ if second_scan_finished.is_set():+ # An uncoordinated sweep reaps the observed claim while sweep A still holds its stale view.+ ledger.claim(root)+ release_first_unlink.set()+ assert first_claim_unlinked.wait(timeout=5)+ else:+ # A owns the sweep lock. Let it unlink, publish a new owner before releasing that lock, then let B sweep.+ release_first_unlink.set()+ assert first_claim_unlinked.wait(timeout=5)+ ledger.claim(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(os.getpid())+ ledger.sweep_stale_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_sweep_lock_is_released_after_inspection_error(+ ledger: InstallStagingLedger, models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = models_path / "claim-scan-lock-lifecycle"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text(DEAD_OWNER, encoding="ascii")+ real_process = install_staging_ledger.psutil.Process++ def fail_process_inspection(_pid: int) -> None:+ raise RuntimeError("simulated process inspection failure")++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", fail_process_inspection)+ with pytest.raises(RuntimeError, match="simulated process inspection failure"):+ ledger.sweep_stale_claims()++ lock_path = models_path / INSTALL_ACTIVE_SCAN_LOCK+ assert lock_path.name == ".invokeai_install_claims.lock"+ assert lock_path.exists()+ monkeypatch.setattr(install_staging_ledger.psutil, "Process", real_process)+ scan_thread = threading.Thread(target=ledger.sweep_stale_claims)+ scan_thread.start()+ scan_thread.join(timeout=10)++ assert not scan_thread.is_alive()+ assert not claim.exists()+ assert lock_path.exists()+++def test_windows_sweep_lock_retries_past_crt_finite_lock_attempts(+ models_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ 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(install_staging_ledger.os, "name", "nt")+ monkeypatch.setitem(sys.modules, "msvcrt", ContendedWindowsLock)+ monkeypatch.setattr(install_staging_ledger.time, "sleep", lambda _seconds: None)++ with install_staging_ledger._claim_scan_lock(models_path):+ pass++ assert calls == [*([ContendedWindowsLock.LK_NBLCK] * 13), ContendedWindowsLock.LK_UNLCK]+++def test_sweep_preserves_access_denied_claim_then_reclaims_confirmed_dead_owner(+ ledger: InstallStagingLedger,+ models_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ root = models_path / "inaccessible-claim"+ root.mkdir()+ claim = _claim_path(root)+ claim.write_text("12345 100.0\n", encoding="ascii")++ class InaccessibleProcess:+ def __init__(self, _pid: int) -> None:+ raise install_staging_ledger.psutil.AccessDenied(pid=_pid)++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", InaccessibleProcess)+ ledger.sweep_stale_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 install_staging_ledger.psutil.STATUS_RUNNING++ def create_time(self) -> float:+ return 100.0++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", LiveProcess)+ ledger.sweep_stale_claims()+ assert claim.exists()++ class DeadProcess:+ def __init__(self, _pid: int) -> None:+ raise install_staging_ledger.psutil.NoSuchProcess(pid=_pid)++ monkeypatch.setattr(install_staging_ledger.psutil, "Process", DeadProcess)+ ledger.sweep_stale_claims()+ assert not claim.exists()diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex d0d746de1d..e014c0bab4 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -5,6 +5,7 @@ Test the model installerimport errnoimport gcimport json+import osimport platformimport shutilimport sqlite3@@ -14,7 +15,7 @@ import timeimport uuidfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any, Callable, Dict+from typing import Any, Callable, Dict, Optionalfrom unittest.mock import MagicMockimport pytest@@ -39,8 +40,17 @@ from invokeai.app.services.model_install import (ModelInstallServiceBase,model_install_default,)-from invokeai.app.services.model_install.model_install_common import (+from invokeai.app.services.model_install.install_staging_ledger import (+ INSTALL_ACTIVE_SENTINEL,+ INSTALL_MARKER_FILENAME,+ INSTALL_MARKER_VERSION,INSTALL_RECOVERY_SENTINEL,+ TMPDIR_PREFIX,+ HeldClaim,+ InstallStaging,+ InstallStagingLedger,+)+from invokeai.app.services.model_install.model_install_common import (InstallCancellationConflictError,InstallDownloadConflictError,InstallRecoveryRequiredError,@@ -49,14 +59,6 @@ from invokeai.app.services.model_install.model_install_common import (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,- INSTALL_MARKER_VERSION,- TMPDIR_PREFIX,)from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL, UnknownModelExceptionfrom invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig@@ -69,12 +71,55 @@ from invokeai.backend.model_manager.taxonomy import (ModelSourceType,ModelType,)+from invokeai.backend.util.logging import InvokeAILoggerfrom tests.backend.model_manager.model_manager_fixtures import * # noqa F403from tests.test_nodes import TestEventServiceOS = platform.uname().system+def _claim_path(root: Path) -> Path:+ return root.parent / f".{root.name}{INSTALL_ACTIVE_SENTINEL}"+++def _recovery_path(root: Path) -> Path:+ return root.parent / f".{root.name}{INSTALL_RECOVERY_SENTINEL}"+++def _read_marker(tmpdir: Path) -> Optional[dict[str, Any]]:+ path = tmpdir / INSTALL_MARKER_FILENAME+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None+++def _stage(job: ModelInstallJob, tmpdir: Optional[Path], models_path: Optional[Path] = None) -> InstallStaging:+ """Give a job built by the test the staging handle the installer creates with every job."""+ root = models_path or (tmpdir.parent if tmpdir is not None else None)+ assert root is not None+ job._staging = InstallStaging(InstallStagingLedger(root, InvokeAILogger.get_logger()), tmpdir)+ return job._staging+++def _write_v1_marker(job: ModelInstallJob, status: InstallStatus) -> None:+ """Write the job's staging marker in format version 1, as any release since that format writes it."""+ assert job._staging is not None and job._staging.tmpdir is not None+ marker: dict[str, Any] = {+ "version": 1,+ "source": str(job.source),+ "access_token": getattr(job.source, "access_token", None),+ "config_in": job.config_in.model_dump(),+ "status": status.value,+ "updated_at": "2026-01-01T00:00:00",+ "files": list((job._resume_metadata or {}).values()),+ }+ if job._recovery_required:+ marker["recovery_required"] = True+ (job._staging.tmpdir / ".invokeai_install.json").write_text(json.dumps(marker), encoding="utf-8")+++def _startup_cleanup(models_path: Path) -> None:+ InstallStagingLedger(models_path, InvokeAILogger.get_logger()).remove_dangling_staging([])++def _fake_move(monkeypatch: pytest.MonkeyPatch, move: Callable[[Path, Path], object]) -> None:"""Install a move that fails on purpose. Its failures are scripted, so the retry backoff, which gives a realWindows file handle time to close, would only add sleep."""@@ -154,22 +199,6 @@ 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,@@ -206,10 +235,6 @@ 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_active_install_sentinel,- has_recovery_sentinel,- )from invokeai.app.services.orphaned_models import OrphanedModelsServiceorphan_service = OrphanedModelsService(config=mm2_app_config, store=mm2_installer.record_store)@@ -219,9 +244,9 @@ 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)+ assert _claim_path(destination_root).exists()orphan_keys = {orphan.path for orphan in orphan_service.find_orphaned_models()}- observations.append((destination_root.name, has_recovery_sentinel(destination_root), orphan_keys))+ observations.append((destination_root.name, _recovery_path(destination_root).exists(), orphan_keys))return resultmonkeypatch.setattr(model_install_default, "move", move_then_scan)@@ -232,7 +257,7 @@ def test_destination_is_hidden_from_orphan_cleanup_during_install(destination_key, has_sentinel, orphan_keys = observations[0]assert has_sentinelassert destination_key not in orphan_keys- assert not has_recovery_sentinel(mm2_app_config.models_path / destination_key)+ assert not _recovery_path(mm2_app_config.models_path / destination_key).exists()def test_managed_local_source_is_hidden_from_orphan_cleanup_during_install(@@ -241,10 +266,6 @@ def test_managed_local_source_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_active_install_sentinel,- has_recovery_sentinel,- )from invokeai.app.services.orphaned_models import OrphanedModelsServicesource_root = mm2_app_config.models_path / f"local-source-{uuid.uuid4().hex}"@@ -256,14 +277,14 @@ def test_managed_local_source_is_hidden_from_orphan_cleanup_during_install(def observe_source_during_operation(path: Path, config: ModelRecordChanges):assert path == source_root- protected = has_active_install_sentinel(source_root)+ protected = _claim_path(source_root).exists()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)+ assert _claim_path(source_root).exists()real_move_with_retries(src, dst)monkeypatch.setattr(mm2_installer, "_probe", observe_source_during_operation)@@ -280,8 +301,8 @@ def test_managed_local_source_is_hidden_from_orphan_cleanup_during_install(assert job.completeassert job.config_out is not Noneassert 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)+ assert not _claim_path(source_root).exists()+ assert not _recovery_path(source_root).exists()def test_orphan_delete_claim_prevents_a_local_install_from_starting(@@ -290,7 +311,6 @@ def test_orphan_delete_claim_prevents_a_local_install_from_starting(mm2_app_config: InvokeAIAppConfig,monkeypatch: pytest.MonkeyPatch,) -> None:- from invokeai.app.services.model_install.model_install_common import has_active_install_sentinelfrom invokeai.app.services.orphaned_models import OrphanedModelsService, orphaned_models_servicesource_root = mm2_app_config.models_path / f"local-source-{uuid.uuid4().hex}"@@ -313,7 +333,7 @@ def test_orphan_delete_claim_prevents_a_local_install_from_starting(delete_thread.start()try:assert deletion_claimed.wait(timeout=5)- assert has_active_install_sentinel(source_root)+ assert _claim_path(source_root).exists()with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):mm2_installer.install_path(source_root)assert source_root.exists()@@ -326,575 +346,12 @@ def test_orphan_delete_claim_prevents_a_local_install_from_starting(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_start_preserves_ambiguous_legacy_claim_after_large_start_time_drift(- 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)- claimed_root = mm2_app_config.models_path / "claim-time-drift"- claimed_root.mkdir()- claim = active_install_sentinel_path(claimed_root)- claim.write_text("12345 100.0\n", encoding="ascii")- observed_start_time = [100.75]-- class Process:- def __init__(self, _pid: int) -> None:- pass-- def status(self) -> str:- return model_install_default.psutil.STATUS_RUNNING-- def create_time(self) -> float:- return observed_start_time[0]-- monkeypatch.setattr(model_install_default.psutil, "Process", Process)-- mm2_installer._remove_stale_install_source_claims()-- assert claim.exists()-- observed_start_time[0] = 102.0- mm2_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()---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,mm2_app_config: InvokeAIAppConfig,monkeypatch: pytest.MonkeyPatch,) -> None:- from invokeai.app.services.model_install.model_install_common import has_recovery_sentinelfrom invokeai.app.services.orphaned_models import OrphanedModelsServiceorphan_service = OrphanedModelsService(config=mm2_app_config, store=mm2_installer.record_store)@@ -908,7 +365,7 @@ def test_unregistered_destination_remains_protected_after_registration_failure(mm2_installer.install_path(embedding_file)protected_roots = [- path for path in mm2_app_config.models_path.iterdir() if path.is_dir() and has_recovery_sentinel(path)+ path for path in mm2_app_config.models_path.iterdir() if path.is_dir() and _recovery_path(path).exists()]assert len(protected_roots) == 1recovery_root = protected_roots[0]@@ -984,7 +441,7 @@ def test_startup_cleanup_preserves_interrupted_exdev_restore_artifacts(published.write_bytes(b"published copy")artifacts.extend(((managed_copy, b"published copy"), (published, b"published copy")))- mm2_installer._remove_dangling_install_dirs()+ _startup_cleanup(mm2_app_config.models_path)assert all(path.read_bytes() == expected for path, expected in artifacts)@@ -1036,7 +493,7 @@ def test_startup_cleanup_preserves_live_exdev_restore_lookalike(assert len(staging_dirs) == 1staged_copy = staging_dirs[0] / "restored"- mm2_installer._remove_dangling_install_dirs()+ _startup_cleanup(mm2_app_config.models_path)assert staged_copy.read_bytes() == b"managed copy"assert moved.read_bytes() == b"managed copy"@@ -1194,7 +651,7 @@ def test_directory_install_preserves_collision_during_rollback(preserved_item = recovery_dest / first_item.nameassert preserved_item.exists()assert preserved_item.is_dir() == first_item_is_dir- assert mm2_installer._has_recovery_sentinel(recovery_dest)+ assert _recovery_path(recovery_dest).exists()def test_queued_local_import_rejects_cancel_after_partial_transfer_requires_recovery(@@ -1227,7 +684,7 @@ def test_queued_local_import_rejects_cancel_after_partial_transfer_requires_recorecovery_destinations = [pathfor path in set(mm2_app_config.models_path.iterdir()) - existing_model_paths- if path.is_dir() and installer._has_recovery_sentinel(path)+ if path.is_dir() and _recovery_path(path).exists()]assert len(recovery_destinations) == 1recovery_file = recovery_destinations[0] / source_path.name@@ -1240,7 +697,7 @@ def test_queued_local_import_rejects_cancel_after_partial_transfer_requires_recoassert job.status is InstallStatus.ERRORassert job.erroredassert not job.cancelled- assert installer._has_recovery_sentinel(recovery_destinations[0])+ assert _recovery_path(recovery_destinations[0]).exists()assert recovery_file.read_bytes() == partial_destination_bytesassert source_path.read_bytes() == original_source_bytes@@ -1346,7 +803,7 @@ def test_directory_install_preserves_recreated_source_when_no_replace_rename_fairecovery_dirs = [path for path in set(mm2_app_config.models_path.iterdir()) - existing_paths if path.is_dir()]assert len(recovery_dirs) == 1recovery_destination = recovery_dirs[0]- assert mm2_installer._has_recovery_sentinel(recovery_destination)+ assert _recovery_path(recovery_destination).exists()assert (recovery_destination / first_item.name).read_bytes() == original_bytes@@ -1400,7 +857,7 @@ def test_directory_install_retains_unowned_destination_artifact_after_rollback(recovery_paths = [path for path in set(mm2_app_config.models_path.iterdir()) - existing_paths if path.is_dir()]assert len(recovery_paths) == 1recovery_dest = recovery_paths[0]- assert mm2_installer._has_recovery_sentinel(recovery_dest)+ assert _recovery_path(recovery_dest).exists()assert (recovery_dest / "unowned-artifact").read_text() == "created concurrently"assert str(diffusers_dir.resolve()) in str(exc_info.value)assert str(recovery_dest.resolve()) in str(exc_info.value)@@ -1432,8 +889,8 @@ def test_remote_install_recovery_survives_cleanup_and_restart(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- job._install_tmpdir = tmpdir- mm2_installer._write_install_marker(job, status=InstallStatus.DOWNLOADS_DONE)+ _stage(job, tmpdir)+ _write_v1_marker(job, InstallStatus.DOWNLOADS_DONE)def fail_after_partial_transfer(src: Path, dst: Path):if src == failure_file:@@ -1449,21 +906,22 @@ def test_remote_install_recovery_survives_cleanup_and_restart(monkeypatch.setattr(Path, "iterdir", sorted_source_files)_fake_move(monkeypatch, fail_after_partial_transfer)- real_write_install_marker = mm2_installer._write_install_marker+ real_persist = InstallStaging.persist- def fail_recovery_marker(job_arg, *args, **kwargs):- if job_arg._recovery_required:+ def fail_recovery_marker(staging: InstallStaging, **kwargs: Any) -> None:+ if kwargs["recovery_required"]:raise OSError("simulated marker write failure")- return real_write_install_marker(job_arg, *args, **kwargs)+ real_persist(staging, **kwargs)- real_delete_install_marker = mm2_installer._delete_install_marker+ real_delete_marker = InstallStaging.delete_marker- def assert_recovery_state_before_marker_delete(tmpdir_arg: Path) -> None:- assert mm2_installer._has_recovery_sentinel(tmpdir_arg) is job._recovery_required- real_delete_install_marker(tmpdir_arg)+ def assert_recovery_state_before_marker_delete(staging: InstallStaging) -> None:+ if staging.tmpdir == tmpdir:+ assert _recovery_path(tmpdir).exists() is job._recovery_required+ real_delete_marker(staging)- monkeypatch.setattr(mm2_installer, "_write_install_marker", fail_recovery_marker)- monkeypatch.setattr(mm2_installer, "_delete_install_marker", assert_recovery_state_before_marker_delete)+ monkeypatch.setattr(InstallStaging, "persist", fail_recovery_marker)+ monkeypatch.setattr(InstallStaging, "delete_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)@@ -1471,7 +929,7 @@ def test_remote_install_recovery_survives_cleanup_and_restart(assert job.erroredassert job.errorassert job in mm2_installer.list_jobs()- assert mm2_installer._has_recovery_sentinel(tmpdir)+ assert _recovery_path(tmpdir).exists()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_filesrecovery_files = [@@ -1482,7 +940,7 @@ def test_remote_install_recovery_survives_cleanup_and_restart(assert len(recovery_files) == 1recovery_dir = recovery_files[0]assert recovery_dir.name == "tmpinstall_recovery"- assert mm2_installer._has_recovery_sentinel(recovery_dir)+ assert _recovery_path(recovery_dir).exists()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.@@ -1531,16 +989,44 @@ def test_cancel_recovery_required_install_preserves_recovery_data(local_path=downloaded_file,status=InstallStatus.ERROR,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)job._recovery_required = True- mm2_installer._write_recovery_sentinel(tmpdir)+ _recovery_path(tmpdir).write_text("preserve", encoding="utf-8")with pytest.raises(InstallRecoveryRequiredError, match="requires recovery"):mm2_installer.cancel_job(job)assert not job.cancelledassert downloaded_file.read_bytes() == b"recoverable source"- assert mm2_installer._has_recovery_sentinel(tmpdir)+ assert _recovery_path(tmpdir).exists()+++def test_cancelling_leaves_staging_another_owner_claimed_untouched(+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}claimed-elsewhere-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ partial = tmpdir / "model.safetensors.downloading"+ partial.write_bytes(b"another owner's download")+ job = ModelInstallJob(+ id=9930,+ source=URLModelSource(url=Url("https://example.com/model.safetensors")),+ config_in=ModelRecordChanges(),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ _stage(job, tmpdir)+ _write_v1_marker(job, InstallStatus.PAUSED)+ marker = (tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8")++ with HeldClaim(tmpdir):+ mm2_installer.cancel_job(job)++ assert job.cancelled+ assert (tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8") == marker+ assert partial.read_bytes() == b"another owner's download"+ shutil.rmtree(tmpdir)def test_cancel_recovery_sentinel_protects_data_before_job_flag_is_set(@@ -1558,15 +1044,15 @@ def test_cancel_recovery_sentinel_protects_data_before_job_flag_is_set(local_path=downloaded_file,status=InstallStatus.RUNNING,)- job._install_tmpdir = tmpdir- mm2_installer._write_recovery_sentinel(tmpdir)+ _stage(job, tmpdir)+ _recovery_path(tmpdir).write_text("preserve", encoding="utf-8")with pytest.raises(InstallRecoveryRequiredError, match="requires recovery"):mm2_installer.cancel_job(job)assert not job.cancelledassert downloaded_file.read_bytes() == b"recoverable source"- assert mm2_installer._has_recovery_sentinel(tmpdir)+ assert _recovery_path(tmpdir).exists()def _queue_downloaded_job(@@ -1581,7 +1067,7 @@ def _queue_downloaded_job(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)installer._install_jobs.append(job)installer._install_queue.put(job)return job@@ -1605,8 +1091,8 @@ def _write_remote_install_marker(local_path=tmpdir,status=status,)- job._install_tmpdir = tmpdir- installer._write_install_marker(job, status=status)+ _stage(job, tmpdir)+ _write_v1_marker(job, status)return download_path@@ -1629,8 +1115,8 @@ def test_restore_metadata_timeout_preserves_partial_download_for_retry(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- mm2_installer._write_install_marker(job, status=InstallStatus.DOWNLOADING)+ _stage(job, tmpdir)+ _write_v1_marker(job, InstallStatus.DOWNLOADING)def raise_metadata_timeout(*args: Any, **kwargs: Any) -> None:raise Timeout("Hugging Face metadata request timed out")@@ -1643,10 +1129,10 @@ def test_restore_metadata_timeout_preserves_partial_download_for_retry(restored_job = mm2_installer.get_job_by_source(source)[-1]assert restored_job.status == InstallStatus.PAUSEDassert partial_path.read_bytes() == b"partial model"- marker = mm2_installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.PAUSED.value- assert active_install_sentinel_path(tmpdir).exists()+ assert _claim_path(tmpdir).exists()@pytest.mark.parametrize("status_code", [429, 503])@@ -1685,9 +1171,9 @@ def test_restore_model_info_http_error_preserves_partial_download_for_retry(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)job._resume_metadata = resume_metadata- installer._write_install_marker(job, status=InstallStatus.DOWNLOADING)+ _write_v1_marker(job, 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}]}'@@ -1719,11 +1205,11 @@ def test_restore_model_info_http_error_preserves_partial_download_for_retry(restored_job = installer.get_job_by_source(source)[-1]assert restored_job.status == InstallStatus.PAUSEDassert partial_path.read_bytes() == b"partial model"- marker = installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.PAUSED.valueassert marker["files"][0]["etag"] == "retained-etag"- assert active_install_sentinel_path(tmpdir).exists()+ assert _claim_path(tmpdir).exists()queued: dict[str, Any] = {}@@ -1754,7 +1240,7 @@ def test_queue_rejection_during_shutdown_preserves_completed_download(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)mm2_installer._install_jobs.append(job)mm2_installer._stop_event.set()@@ -1762,7 +1248,7 @@ def test_queue_rejection_during_shutdown_preserves_completed_download(assert job.status == InstallStatus.DOWNLOADS_DONEassert partial_path.read_bytes() == b"downloaded model"- assert mm2_installer._read_install_marker(tmpdir) is not None+ assert _read_marker(tmpdir) is not Nonedef test_restore_leaves_unvisited_markers_untouched_when_stopping(@@ -1780,8 +1266,8 @@ def test_restore_leaves_unvisited_markers_untouched_when_stopping(assert first_partial.read_bytes() == b"partial download"assert second_partial.read_bytes() == b"partial download"- assert mm2_installer._read_install_marker(first_tmpdir) is not None- assert mm2_installer._read_install_marker(second_tmpdir) is not None+ assert _read_marker(first_tmpdir) is not None+ assert _read_marker(second_tmpdir) is not Nonedef test_stop_during_startup_restore_preserves_the_current_download(@@ -1807,11 +1293,11 @@ def test_stop_during_startup_restore_preserves_the_current_download(mm2_installer.stop()- marker = mm2_installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.PAUSED.valueassert partial_path.read_bytes() == b"partial download"- assert not active_install_sentinel_path(tmpdir).exists()+ assert not _claim_path(tmpdir).exists()assert mm2_installer._restore_completed_event.is_set()@@ -1917,8 +1403,8 @@ def test_shutdown_restore_policy_persists_current_and_resumes_unvisited_on_next_local_path=tmpdir,status=status,)- job._install_tmpdir = tmpdir- installer._write_install_marker(job, status=status)+ _stage(job, tmpdir)+ _write_v1_marker(job, status)markers[tmpdir] = (status, partial_path.read_bytes())ordered_active_markers = [@@ -1932,7 +1418,7 @@ def test_shutdown_restore_policy_persists_current_and_resumes_unvisited_on_next_original_resume = installer._resume_remote_downloaddef interrupt_first_restore(job: ModelInstallJob, *, operation_reserved: bool = False) -> None:- if job._install_tmpdir == interrupted_tmpdir:+ if job._staging is not None and job._staging.tmpdir == interrupted_tmpdir:interrupted_restore_started.set()assert installer._stop_event.wait(timeout=5)original_resume(job, operation_reserved=operation_reserved)@@ -1943,10 +1429,10 @@ def test_shutdown_restore_policy_persists_current_and_resumes_unvisited_on_next_installer.stop()for tmpdir, (original_status, expected_bytes) in markers.items():- marker = installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert (tmpdir / "weights.safetensors.downloading").read_bytes() == expected_bytes- assert not active_install_sentinel_path(tmpdir).exists()+ assert not _claim_path(tmpdir).exists()if tmpdir == interrupted_tmpdir:assert marker["status"] == InstallStatus.PAUSED.valueelse:@@ -1976,9 +1462,9 @@ def test_shutdown_restore_policy_persists_current_and_resumes_unvisited_on_next_interrupted_source = json.loads((interrupted_tmpdir / INSTALL_MARKER_FILENAME).read_text())["source"]assert restored[paused_source].status == InstallStatus.PAUSEDassert 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+ assert _read_marker(explicitly_paused_tmpdir)["status"] == InstallStatus.PAUSED.value+ assert _read_marker(interrupted_tmpdir)["status"] == InstallStatus.PAUSED.value+ assert _read_marker(unvisited_tmpdir)["status"] == InstallStatus.DOWNLOADING.valuefor tmpdir, (_, expected_bytes) in markers.items():assert (tmpdir / "weights.safetensors.downloading").read_bytes() == expected_bytesfinally:@@ -2081,14 +1567,14 @@ def test_stop_preserves_restored_downloads_without_a_multifile_job(mm2_installer.stop()- marker = mm2_installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == status.valueif status == InstallStatus.PAUSED:assert marker["files"] == resume_metadataexpected_payload = b"downloaded model" if status == InstallStatus.DOWNLOADS_DONE else b"partial download"assert partial_path.read_bytes() == expected_payload- assert not active_install_sentinel_path(tmpdir).exists()+ assert not _claim_path(tmpdir).exists()def test_service_stop_waits_for_active_install_without_cancelling_it(@@ -2114,7 +1600,7 @@ def test_service_stop_waits_for_active_install_without_cancelling_it(real_clear_pending_jobs = installer._clear_pending_jobsdef blocked_move_with_retries(src: Path, dst: Path) -> None:- sentinel_during_transfer.append(installer._has_recovery_sentinel(tmpdir))+ sentinel_during_transfer.append(_recovery_path(tmpdir).exists())transfer_started.set()assert release_transfer.wait(timeout=5)real_move_with_retries(src, dst)@@ -2199,7 +1685,7 @@ def test_service_stop_preserves_a_job_between_dequeue_and_worker_activation(assert job.downloads_doneassert tmpdir.exists()assert (tmpdir / embedding_file.name).exists()- marker = installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.DOWNLOADS_DONE.value@@ -2233,7 +1719,7 @@ def test_cancel_during_install_preflight_waits_for_probe_then_cleans_safely(installer.cancel_job(job)assert tmpdir.exists()assert (tmpdir / embedding_file.name).exists()- assert not installer._has_recovery_sentinel(tmpdir)+ assert not _recovery_path(tmpdir).exists()finally:release_probe.set()@@ -2260,8 +1746,8 @@ def test_restart_refuses_recovery_sentinel(local_path=tmpdir,status=InstallStatus.ERROR,)- job._install_tmpdir = tmpdir- mm2_installer._write_recovery_sentinel(tmpdir)+ _stage(job, tmpdir)+ _recovery_path(tmpdir).write_text("preserve", encoding="utf-8")monkeypatch.setattr(mm2_installer, "_remote_files_from_source", lambda *_args, **_kwargs: pytest.fail("restart reached source"))@@ -2274,34 +1760,7 @@ def test_restart_refuses_recovery_sentinel(assert job.status is InstallStatus.ERRORassert downloaded_file.read_bytes() == b"recoverable source"- assert mm2_installer._has_recovery_sentinel(tmpdir)---def test_recovery_required_marker_round_trips_and_preserves_staging_dir(- mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig-) -> None:- assert isinstance(mm2_installer, ModelInstallService)- tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}recovery-{uuid.uuid4().hex}"- tmpdir.mkdir()- downloaded_file = tmpdir / "model.safetensors"- downloaded_file.write_bytes(b"recoverable source")- job = ModelInstallJob(- id=995,- source=URLModelSource(url=Url("https://example.com/model.safetensors")),- config_in=ModelRecordChanges(),- local_path=tmpdir,- status=InstallStatus.ERROR,- )- job._install_tmpdir = tmpdir- job._recovery_required = True-- mm2_installer._write_install_marker(job)- marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))- mm2_installer._remove_dangling_install_dirs()-- assert marker["recovery_required"] is True- assert downloaded_file.read_bytes() == b"recoverable source"- assert tmpdir.exists()+ assert _recovery_path(tmpdir).exists()def test_registering_recovery_root_removes_its_sentinel(@@ -2311,7 +1770,7 @@ def test_registering_recovery_root_removes_its_sentinel(recovery_root = mm2_app_config.models_path / "recovered-model"recovery_root.mkdir()shutil.copy2(embedding_file, recovery_root / embedding_file.name)- sentinel = mm2_installer._recovery_sentinel_path(recovery_root)+ sentinel = _recovery_path(recovery_root)sentinel.write_text("preserve until registered", encoding="utf-8")key = mm2_installer.register_path(recovery_root)@@ -2327,7 +1786,7 @@ def test_installing_recovery_root_clears_source_sentinel_after_transfer(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 = _recovery_path(recovery_root)sentinel.write_text("preserve until transferred", encoding="utf-8")key = mm2_installer.install_path(recovery_root)@@ -2344,7 +1803,7 @@ def test_startup_scan_skips_recovery_protected_root(recovery_root = mm2_app_config.models_path / "recovered-model"recovery_root.mkdir()shutil.copy2(embedding_file, recovery_root / embedding_file.name)- sentinel = mm2_installer._recovery_sentinel_path(recovery_root)+ sentinel = _recovery_path(recovery_root)sentinel.write_text("preserve until manually registered", encoding="utf-8")mm2_installer._register_orphaned_models()@@ -2354,17 +1813,37 @@ def test_startup_scan_skips_recovery_protected_root(assert (recovery_root / embedding_file.name).exists()+def test_startup_scan_skips_a_model_directory_holding_a_claimed_root(+ mm2_installer: ModelInstallServiceBase, diffusers_dir: Path, mm2_app_config: InvokeAIAppConfig+) -> None:+ assert isinstance(mm2_installer, ModelInstallService)+ pipeline = mm2_app_config.models_path / "pipeline-being-written"+ shutil.copytree(diffusers_dir, pipeline)+ claimed_child = next(path for path in pipeline.iterdir() if path.is_dir())+ _claim_path(claimed_child).write_text("2147483647 1.0\n", encoding="ascii")++ mm2_installer._register_orphaned_models()++ assert mm2_installer.record_store.all_models() == []+ assert _claim_path(claimed_child).exists()++def test_registered_model_with_temporary_prefix_survives_startup_cleanup(mm2_installer: ModelInstallServiceBase,embedding_file: Path,mm2_app_config: InvokeAIAppConfig,+ mm2_download_queue: Any,) -> None:model_key = f"{TMPDIR_PREFIX}registered-model"installed_key = mm2_installer.install_path(embedding_file, config=ModelRecordChanges(key=model_key))installed_path = mm2_app_config.models_path / mm2_installer.record_store.get_model(installed_key).path- mm2_installer._remove_dangling_install_dirs()+ restarted_installer = ModelInstallService(+ app_config=mm2_app_config, record_store=mm2_installer.record_store, download_queue=mm2_download_queue+ )+ restarted_installer.start()+ restarted_installer.stop()assert installed_path.exists()assert mm2_installer.record_store.exists(model_key)@@ -2451,36 +1930,7 @@ def test_install_fsync_failure_preserves_source_before_transfer(assert embedding_file.read_bytes() == source_bytesassert 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+ assert not _recovery_path(destination).exists()def test_rename(@@ -2715,6 +2165,7 @@ def test_wait_for_installs_waits_for_download_completion_to_enqueue_install(source=URLModelSource(url=Url("https://www.test.foo/download/test_embedding.safetensors")),local_path=tmp_path,)+ _stage(job, None, tmp_path)with mm2_installer._lock:mm2_installer._download_cache[job.id] = jobmonkeypatch.setattr(mm2_installer, "_signal_job_downloads_done", lambda install_job: None)@@ -2784,8 +2235,8 @@ def test_import_waits_for_startup_restore(config_in=ModelRecordChanges(),local_path=tmpdir,)- interrupted_job._install_tmpdir = tmpdir- installer._write_install_marker(interrupted_job, status=InstallStatus.DOWNLOADING)+ _stage(interrupted_job, tmpdir)+ _write_v1_marker(interrupted_job, InstallStatus.DOWNLOADING)restore = installer._restore_incomplete_installswait_for_restore = installer._wait_for_restore_complete@@ -2848,8 +2299,8 @@ def test_concurrent_imports_of_same_source_return_one_job(config_in=ModelRecordChanges(),local_path=tmpdir,)- interrupted_job._install_tmpdir = tmpdir- mm2_installer._write_install_marker(interrupted_job, status=InstallStatus.DOWNLOADING)+ _stage(interrupted_job, tmpdir)+ _write_v1_marker(interrupted_job, InstallStatus.DOWNLOADING)first_import_ready = threading.Event()second_import_waiting = threading.Event()@@ -2924,12 +2375,14 @@ def test_failed_import_releases_source_reservation(import_attempts += 1if import_attempts == 1:raise RuntimeError("metadata request failed")- return ModelInstallJob(+ job = ModelInstallJob(id=99997,source=import_source,config_in=config or ModelRecordChanges(),local_path=mm2_app_config.models_path,)+ _stage(job, None, mm2_app_config.models_path)+ return jobmonkeypatch.setattr(mm2_installer, "_import_from_url", _import_from_url)@@ -2960,6 +2413,7 @@ def test_waiting_import_prefers_a_live_job_over_a_terminal_one(id=88002, source=source, config_in=ModelRecordChanges(), local_path=mm2_app_config.models_path)live_job.status = InstallStatus.DOWNLOADING+ _stage(live_job, None, mm2_app_config.models_path)# Stand in for an owner that has reserved the source but not yet registered its job.with condition:@@ -3114,6 +2568,7 @@ def test_prune_jobs_rebind_preserves_existing_iterators(local_path=mm2_app_config.models_path,status=InstallStatus.RUNNING,)+ _stage(active_job, None, mm2_app_config.models_path)mm2_installer._install_jobs.extend([*jobs, active_job])existing_iterator = iter(mm2_installer.list_jobs())assert next(existing_iterator) is jobs[0]@@ -3348,12 +2803,12 @@ def test_restore_paused_hf_install_preserves_access_token(config_in=ModelRecordChanges(),local_path=tmpdir,)- paused_job._install_tmpdir = tmpdir+ _stage(paused_job, tmpdir)paused_job.status = InstallStatus.PAUSED- mm2_installer._write_install_marker(paused_job, status=InstallStatus.PAUSED)+ _write_v1_marker(paused_job, InstallStatus.PAUSED)- marker = mm2_installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["access_token"] == access_token@@ -3371,7 +2826,7 @@ 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)+ assert _claim_path(tmpdir).exists()captured: dict[str, str | None] = {}@@ -3383,7 +2838,7 @@ 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)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3491,9 +2946,9 @@ def test_restore_claims_downloads_done_staging_before_queueing(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- staging_job._install_tmpdir = tmpdir+ _stage(staging_job, tmpdir)(tmpdir / "model.safetensors").write_bytes(b"downloaded model")- mm2_installer._write_install_marker(staging_job, status=InstallStatus.DOWNLOADS_DONE)+ _write_v1_marker(staging_job, InstallStatus.DOWNLOADS_DONE)restored_installer = ModelInstallService(app_config=mm2_app_config,@@ -3504,7 +2959,7 @@ def test_restore_claims_downloads_done_staging_before_queueing(queued_jobs: list[ModelInstallJob] = []def capture_queued_job(job: ModelInstallJob) -> None:- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()queued_jobs.append(job)monkeypatch.setattr(restored_installer, "_put_in_queue", capture_queued_job)@@ -3513,9 +2968,9 @@ def test_restore_claims_downloads_done_staging_before_queueing(restored_installer._restore_incomplete_installs()assert len(queued_jobs) == 1assert queued_jobs[0].downloads_done- assert queued_jobs[0]._install_tmpdir_active_sentinel_created+ assert queued_jobs[0]._staging.claimedfinally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3533,6 +2988,7 @@ def test_restart_failed_uses_parts_created_before_download_started()download_job = MultiFileDownloadJob(id=123, dest=tmp_path, download_parts={part})job = ModelInstallJob(id=99999, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)+ _stage(job, tmp_path)remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)monkeypatch.setattr(mm2_installer, "_multifile_download", lambda **_: download_job)@@ -3543,7 +2999,6 @@ def test_restart_failed_uses_parts_created_before_download_started(source=source,remote_files=[remote_file],metadata=None,- destdir=tmp_path,)part.resume_required = True@@ -3551,7 +3006,7 @@ def test_restart_failed_uses_parts_created_before_download_started(assert job.status == InstallStatus.PAUSEDassert job.model_dump(mode="json")["download_parts"][0]["resume_required"] is True- marker = mm2_installer._read_install_marker(tmp_path)+ marker = _read_marker(tmp_path)assert marker is not Noneassert marker["files"][0]["etag"] == '"model-etag"'assert marker["files"][0]["resume_required"] is True@@ -3577,7 +3032,7 @@ def test_download_terminal_callbacks_preserve_recovery_protected_staging(tmpdir.mkdir()payload = tmpdir / "model.safetensors"payload.write_bytes(b"recovery data")- installer._write_recovery_sentinel(tmpdir)+ _recovery_path(tmpdir).write_text("preserve", encoding="utf-8")source = URLModelSource(url=Url("https://example.com/model.safetensors"))part = DownloadJob(source=source.url, dest=payload)@@ -3589,7 +3044,7 @@ def test_download_terminal_callbacks_preserve_recovery_protected_staging(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- install_job._install_tmpdir = tmpdir+ _stage(install_job, tmpdir).claim()install_job._multifile_job = download_jobinstaller._download_cache[download_job.id] = install_jobmonkeypatch.setattr(installer._download_queue, "cancel_job", MagicMock())@@ -3599,8 +3054,10 @@ def test_download_terminal_callbacks_preserve_recovery_protected_staging(else:installer._download_cancelled_callback(download_job)- assert installer._has_recovery_sentinel(tmpdir)+ assert _recovery_path(tmpdir).exists()assert payload.read_bytes() == b"recovery data"+ # The recovery mark protects the data from here on; a leftover claim would block cleanup until restart.+ assert not _claim_path(tmpdir).exists()def test_download_completion_during_shutdown_preserves_staging_for_restore(@@ -3625,12 +3082,11 @@ def test_download_completion_during_shutdown_preserves_staging_for_restore(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- install_job._install_tmpdir = tmpdir+ _stage(install_job, tmpdir)install_job._multifile_job = download_job- install_job._install_tmpdir_active_sentinel_created = True+ install_job._staging.claim()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()@@ -3655,10 +3111,10 @@ def test_download_completion_during_shutdown_preserves_staging_for_restore(assert not callback_errorsassert install_job.downloads_doneassert tmpdir.exists()- marker = installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.DOWNLOADS_DONE.value- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()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.@@ -3688,23 +3144,22 @@ def test_stop_releases_claim_for_completed_downloads_waiting_to_install(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- install_job._install_tmpdir = tmpdir- install_job._install_tmpdir_active_sentinel_created = True+ _stage(install_job, tmpdir)+ install_job._staging.claim()install_job._multifile_job = download_jobinstaller._install_jobs.append(install_job)- create_active_install_sentinel(tmpdir)installer.stop()try:assert install_job.downloads_doneassert tmpdir.exists()- marker = installer._read_install_marker(tmpdir)+ marker = _read_marker(tmpdir)assert marker is not Noneassert marker["status"] == InstallStatus.DOWNLOADS_DONE.value- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3733,23 +3188,22 @@ def test_paused_remote_install_stays_hidden_from_orphan_cleanup(local_path=tmpdir,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobinstaller._download_cache[download_job.id] = job- create_active_install_sentinel(tmpdir)orphan_service = OrphanedModelsService(config=mm2_app_config, store=installer.record_store)try:installer._download_cancelled_callback(download_job)- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()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 resultassert payload.exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3774,12 +3228,11 @@ def test_cancel_active_remote_install_waits_for_download_queue_cleanup(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobinstaller._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)@@ -3789,7 +3242,7 @@ def test_cancel_active_remote_install_waits_for_download_queue_cleanup(assert cancel_download.call_args.args == (download_job,)assert tmpdir.exists()assert payload.exists()- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()assert installer._download_cache.get(download_job.id) is job# Cancellation may race an interrupted part being marked resumable by the queue.@@ -3798,10 +3251,10 @@ def test_cancel_active_remote_install_waits_for_download_queue_cleanup(assert job.cancelledassert not tmpdir.exists()- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()assert download_job.id not in installer._download_cachefinally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3830,13 +3283,12 @@ def test_cancel_waits_for_pending_terminal_download_callback(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobjob.download_parts = download_job.download_partsinstaller._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)@@ -3846,7 +3298,7 @@ def test_cancel_waits_for_pending_terminal_download_callback(assert job.cancelledassert tmpdir.exists()assert payload.exists()- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()cancel_download.assert_called_once_with(download_job)if terminal_callback == "complete":@@ -3858,9 +3310,9 @@ def test_cancel_waits_for_pending_terminal_download_callback(assert download_job.id not in installer._download_cacheassert installer._install_queue.qsize() == 0assert not tmpdir.exists()- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3889,13 +3341,12 @@ def test_pause_survives_pending_terminal_download_callback(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobjob.download_parts = download_job.download_partsinstaller._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:@@ -3911,12 +3362,12 @@ def test_pause_survives_pending_terminal_download_callback(assert installer._install_queue.qsize() == 0assert tmpdir.exists()assert payload.exists()- assert has_active_install_sentinel(tmpdir)- marker = installer._read_install_marker(tmpdir)+ assert _claim_path(tmpdir).exists()+ marker = _read_marker(tmpdir)assert marker is not None and marker["status"] == InstallStatus.PAUSED.valuefinally:installer.cancel_job(job)- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -3938,27 +3389,26 @@ def test_stop_preserves_staging_claim_until_download_pause_callback(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobinstaller._install_jobs.append(job)installer._download_cache[download_job.id] = job- create_active_install_sentinel(tmpdir)installer.stop()try:assert job.pausedassert installer._download_cache.get(download_job.id) is job- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()installer._download_cancelled_callback(download_job)assert download_job.id not in installer._download_cache- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()assert tmpdir.exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)def test_shutdown_releases_claim_when_pause_callback_already_ran(@@ -3980,28 +3430,27 @@ def test_shutdown_releases_claim_when_pause_callback_already_ran(local_path=tmpdir,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobinstaller._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)+ assert _claim_path(tmpdir).exists()installer.stop()- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))assert marker["status"] == InstallStatus.PAUSED.valueassert tmpdir.exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -4024,24 +3473,23 @@ def test_cancel_after_pause_callback_cleans_staging(mm2_installer: ModelInstallSlocal_path=tmpdir,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobinstaller._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)+ assert _claim_path(tmpdir).exists()installer.cancel_job(job)assert job.cancelledassert not tmpdir.exists()- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()finally:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -4071,7 +3519,7 @@ def test_remote_download_replacement_waits_for_previous_callback(local_path=tmp_path,status=InstallStatus.PAUSED if operation == "resume" else InstallStatus.ERROR,)- job._install_tmpdir = tmp_path+ _stage(job, tmp_path)job._multifile_job = old_downloadjob.download_parts = old_download.download_partsinstaller._download_cache[old_download.id] = job@@ -4105,8 +3553,8 @@ def test_concurrent_restart_requests_are_serialized(local_path=tmp_path,status=InstallStatus.ERROR,)- job._install_tmpdir = tmp_path- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmp_path)+ job._staging.claim()remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)metadata_started = threading.Event()release_metadata = threading.Event()@@ -4140,7 +3588,7 @@ def test_concurrent_restart_requests_are_serialized(assert not first_request.is_alive()assert errors == []submit_download.assert_called_once()- installer._release_install_tmpdir_claim(job)+ job._staging.release_claim()(tmp_path / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)@@ -4157,8 +3605,8 @@ def test_concurrent_resume_requests_are_serialized(local_path=tmp_path,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmp_path- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmp_path)+ job._staging.claim()remote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=64)metadata_started = threading.Event()release_metadata = threading.Event()@@ -4193,7 +3641,7 @@ def test_concurrent_resume_requests_are_serialized(assert errors == []submit_download.assert_called_once()installer._download_cache.pop(job._multifile_job.id)- installer._release_install_tmpdir_claim(job)+ job._staging.release_claim()(tmp_path / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)@@ -4225,7 +3673,7 @@ def test_remote_download_preparation_failure_preserves_retryable_state(status=initial_status,download_parts={part},)- job._install_tmpdir = tmp_path+ _stage(job, tmp_path)job._multifile_job = MultiFileDownloadJob(id=4589, dest=tmp_path, download_parts={part})monkeypatch.setattr(installer,@@ -4270,7 +3718,7 @@ def test_remote_download_retry_with_no_matching_files_preserves_retryable_state(status=initial_status,download_parts={part},)- job._install_tmpdir = tmp_path+ _stage(job, tmp_path)job._multifile_job = MultiFileDownloadJob(id=4590, dest=tmp_path, download_parts={part})monkeypatch.setattr(installer, "_remote_files_from_source", lambda _: ([], None))@@ -4310,13 +3758,12 @@ def test_pause_conflicts_after_download_install_handoff(local_path=tmpdir,status=InstallStatus.DOWNLOADING,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobjob.download_parts = download_job.download_partsinstaller._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)@@ -4335,13 +3782,13 @@ def test_pause_conflicts_after_download_install_handoff(assert job.status == expected_statusqueue_install_job.assert_called_once_with(job)assert tmpdir.exists()- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()finally:installer._active_install_job = Nonejob._install_phase = Nonejob.status = InstallStatus.DOWNLOADS_DONEinstaller.cancel_job(job)- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -4368,12 +3815,11 @@ def test_install_state_changes_conflict_during_remote_download_handoff(local_path=tmpdir,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobjob.download_parts = download_job.download_partsinstaller._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()@@ -4404,7 +3850,7 @@ def test_install_state_changes_conflict_during_remote_download_handoff(else:installer.pause_job(job)assert tmpdir.exists()- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()finally:release_metadata.set()operation_thread.join(timeout=5)@@ -4414,9 +3860,9 @@ def test_install_state_changes_conflict_during_remote_download_handoff(submit_download.assert_called_once()assert not job.cancelledinstaller._download_cache.pop(job._multifile_job.id)- installer._release_install_tmpdir_claim(job)+ job._staging.release_claim()(tmpdir / INSTALL_MARKER_FILENAME).unlink(missing_ok=True)- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)def test_shutdown_waits_for_remote_download_handoff_and_preserves_pause(@@ -4440,12 +3886,11 @@ def test_shutdown_waits_for_remote_download_handoff_and_preserves_pause(local_path=tmpdir,status=InstallStatus.PAUSED,)- job._install_tmpdir = tmpdir- job._install_tmpdir_active_sentinel_created = True+ _stage(job, tmpdir)+ job._staging.claim()job._multifile_job = download_jobjob.download_parts = download_job.download_partsinstaller._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()@@ -4488,7 +3933,7 @@ def test_shutdown_waits_for_remote_download_handoff_and_preserves_pause(submit_download.assert_not_called()assert job.pausedassert tmpdir.exists()- assert not has_active_install_sentinel(tmpdir)+ assert not _claim_path(tmpdir).exists()marker = json.loads((tmpdir / INSTALL_MARKER_FILENAME).read_text(encoding="utf-8"))assert marker["status"] == InstallStatus.PAUSED.valueshutil.rmtree(tmpdir, ignore_errors=True)@@ -4506,13 +3951,14 @@ def test_remote_staging_is_claimed_before_download_submission(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)+ _stage(job, 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+ assert _claim_path(tmpdir).exists()+ assert job._staging.claimedmonkeypatch.setattr(installer._download_queue, "submit_multifile_download", assert_claimed_before_submit)@@ -4521,14 +3967,12 @@ def test_remote_staging_is_claimed_before_download_submission(source=source,remote_files=[remote_file],metadata=None,- destdir=tmpdir,)- assert has_active_install_sentinel(tmpdir)- assert active_install_sentinel_path(tmpdir).exists()+ assert _claim_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)+ job._staging.release(preserve_recovery=False, completed=False)def test_install_worker_preserves_remote_staging_when_claim_conflicts(@@ -4540,7 +3984,7 @@ def test_install_worker_preserves_remote_staging_when_claim_conflicts(tmpdir.mkdir()payload = tmpdir / "model.safetensors"payload.write_bytes(b"owned by another install")- create_active_install_sentinel(tmpdir)+ HeldClaim(tmpdir)job = ModelInstallJob(id=458,@@ -4549,7 +3993,7 @@ def test_install_worker_preserves_remote_staging_when_claim_conflicts(local_path=tmpdir,status=InstallStatus.DOWNLOADS_DONE,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)installer._install_queue.put(job)def attempt_transfer(queued_job: ModelInstallJob) -> None:@@ -4562,10 +4006,10 @@ def test_install_worker_preserves_remote_staging_when_claim_conflicts(assert job.erroredassert payload.read_bytes() == b"owned by another install"- assert has_active_install_sentinel(tmpdir)+ assert _claim_path(tmpdir).exists()finally:# This sidecar belongs to the simulated competing operation.- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)def test_resume_reports_restart_from_scratch_on_fresh_parts(@@ -4578,7 +4022,7 @@ def test_resume_reports_restart_from_scratch_on_fresh_parts(old_part.bytes = 4old_part.download_path = tmp_path / "model.safetensors" # no .downloading file on diskjob = ModelInstallJob(id=4242, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)- job._install_tmpdir = tmp_path+ _stage(job, tmp_path)job.download_parts = {old_part}job.status = InstallStatus.PAUSEDremote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)@@ -4606,7 +4050,7 @@ def test_resume_does_not_report_restart_from_scratch_when_partial_exists(old_part.download_path = tmp_path / "model.safetensors"(tmp_path / "model.safetensors.downloading").write_bytes(b"1234")job = ModelInstallJob(id=4243, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)- job._install_tmpdir = tmp_path+ _stage(job, tmp_path)job.download_parts = {old_part}job.status = InstallStatus.PAUSEDremote_file = RemoteModelFile(url=source.url, path=Path("model.safetensors"), size=8)@@ -4742,7 +4186,7 @@ def test_restore_keeps_a_legacy_marker_whose_key_predates_key_validation() -> None:"""A marker written before install keys were checked can carry a key that is not a plain filename. It muststill be restored: dropping it strands the partial download forever, because no job is created to clean up- the tmpdir and `_remove_dangling_install_dirs` keeps any tmpdir whose marker is readable and non-terminal.+ the tmpdir and startup cleanup keeps any tmpdir whose marker is readable and non-terminal.Containment does not depend on this - `install_path()` checks the key at the join and errors the job."""assert isinstance(mm2_installer, ModelInstallService)assert mm2_installer._wait_for_restore_complete(timeout=10)@@ -4762,9 +4206,9 @@ def test_restore_keeps_a_legacy_marker_whose_key_predates_key_validation(config_in=config_in,local_path=tmpdir,)- job._install_tmpdir = tmpdir+ _stage(job, tmpdir)job.status = InstallStatus.PAUSED- mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)+ _write_v1_marker(job, InstallStatus.PAUSED)restored_installer = ModelInstallService(app_config=mm2_app_config,@@ -4778,10 +4222,46 @@ 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)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)+def test_startup_restores_staging_whose_claim_a_crashed_process_left_behind(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ mm2_download_queue: Any,+ mm2_session: Any,+) -> None:+ """A process killed mid-download never released its claim; startup must prove it stale, then resume the install."""+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}crashed-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ (tmpdir / "weights.safetensors.downloading").write_bytes(b"partial download")+ source = URLModelSource(url=Url("https://example.com/crashed.safetensors"))+ job = ModelInstallJob(id=99996, source=source, config_in=ModelRecordChanges(), local_path=tmpdir)+ _stage(job, tmpdir)+ _write_v1_marker(job, InstallStatus.PAUSED)+ _claim_path(tmpdir).write_text("2147483647 1.0\n", encoding="ascii")++ restarted_installer = ModelInstallService(+ app_config=mm2_app_config,+ record_store=mm2_installer.record_store,+ download_queue=mm2_download_queue,+ session=mm2_session,+ )+ restarted_installer.start()+ try:+ assert restarted_installer._wait_for_restore_complete(timeout=10)+ [restored] = restarted_installer.get_job_by_source(source)+ assert restored.status == InstallStatus.PAUSED+ assert _claim_path(tmpdir).read_text(encoding="ascii").split()[0] == str(os.getpid())+ finally:+ restarted_installer.stop()+ assert (tmpdir / "weights.safetensors.downloading").read_bytes() == b"partial download"+ shutil.rmtree(tmpdir)++def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(mm2_installer: ModelInstallServiceBase,mm2_app_config: InvokeAIAppConfig,@@ -4798,16 +4278,17 @@ def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(bad_tmpdir = mm2_app_config.models_path / f"tmpinstall_bad_{uuid.uuid4().hex}"bad_tmpdir.mkdir(parents=True, exist_ok=True)tmpdirs.append(bad_tmpdir)- (bad_tmpdir / INSTALL_MARKER_FILENAME).write_text(- json.dumps(- {- "version": INSTALL_MARKER_VERSION,- "source": "stabilityai/unparseable",- "config_in": {"base": "not-a-real-base"},- "status": InstallStatus.PAUSED.value,- }- )+ bad_payload = bad_tmpdir / "weights.safetensors.downloading"+ bad_payload.write_bytes(b"partial download")+ bad_marker = json.dumps(+ {+ "version": INSTALL_MARKER_VERSION,+ "source": "stabilityai/unparseable",+ "config_in": {"base": "not-a-real-base"},+ "status": InstallStatus.PAUSED.value,+ })+ (bad_tmpdir / INSTALL_MARKER_FILENAME).write_text(bad_marker)good_tmpdir = mm2_app_config.models_path / f"tmpinstall_good_{uuid.uuid4().hex}"good_tmpdir.mkdir(parents=True, exist_ok=True)@@ -4818,9 +4299,9 @@ def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(config_in=ModelRecordChanges(),local_path=good_tmpdir,)- job._install_tmpdir = good_tmpdir+ _stage(job, good_tmpdir)job.status = InstallStatus.PAUSED- mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)+ _write_v1_marker(job, InstallStatus.PAUSED)restored_installer = ModelInstallService(app_config=mm2_app_config,@@ -4831,9 +4312,12 @@ def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(restored_installer._restore_incomplete_installs()assert [str(job.source) for job in restored_installer.list_jobs()] == ["stabilityai/ordinary"]+ assert not _claim_path(bad_tmpdir).exists(), "a skipped marker must not be claimed"+ assert (bad_tmpdir / INSTALL_MARKER_FILENAME).read_text() == bad_marker+ assert bad_payload.read_bytes() == b"partial download"finally:for tmpdir in tmpdirs:- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)@@ -4870,9 +4354,9 @@ def test_restore_skips_a_marker_with_an_invalid_status_without_claiming_it_or_abconfig_in=ModelRecordChanges(),local_path=good_tmpdir,)- job._install_tmpdir = good_tmpdir+ _stage(job, good_tmpdir)job.status = InstallStatus.PAUSED- mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)+ _write_v1_marker(job, InstallStatus.PAUSED)restored_installer = ModelInstallService(app_config=mm2_app_config,@@ -4883,10 +4367,10 @@ def test_restore_skips_a_marker_with_an_invalid_status_without_claiming_it_or_abrestored_installer._restore_incomplete_installs()assert [str(job.source) for job in restored_installer.list_jobs()] == ["stabilityai/ordinary"]- assert not active_install_sentinel_path(bad_tmpdir).exists()+ assert not _claim_path(bad_tmpdir).exists()finally:for tmpdir in (bad_tmpdir, good_tmpdir):- active_install_sentinel_path(tmpdir).unlink(missing_ok=True)+ _claim_path(tmpdir).unlink(missing_ok=True)shutil.rmtree(tmpdir, ignore_errors=True)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 41dc89a99a..65c2c394fe 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,10 @@ from pathlib import Pathimport pytestfrom invokeai.app.services.config.config_default import InvokeAIAppConfig-from invokeai.app.services.model_install.model_install_common import INSTALL_ACTIVE_SENTINEL, INSTALL_RECOVERY_SENTINEL+from invokeai.app.services.model_install.install_staging_ledger import (+ INSTALL_ACTIVE_SENTINEL,+ INSTALL_RECOVERY_SENTINEL,+)from 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@@ -177,6 +180,83 @@ def test_empty_active_install_claim_protects_a_model_during_claim_publication(assert claim.exists()+def test_a_directory_with_a_claimed_root_beneath_it_is_neither_listed_nor_deleted(+ models_path: Path, store: ModelRecordServiceSQL+) -> None:+ group = models_path / "model-group"+ _write_model_file(group / "loose-weights")+ _write_model_file(group / "being-installed")+ claim = group / f".being-installed{INSTALL_ACTIVE_SENTINEL}"+ claim.write_text("2147483647 1.0\n", encoding="ascii")+ service = _service(models_path, store)++ assert service.find_orphaned_models() == []+ result = service.delete_orphaned_models(["model-group"])++ assert result["model-group"] == "error: path is reserved by an active install or install recovery"+ assert (group / "loose-weights" / "model.safetensors").exists()+ assert (group / "being-installed" / "model.safetensors").exists()++[email protected]("payload", ["model.safetensors", "model.safetensors.downloading"])+def test_staging_kept_for_an_unusable_install_marker_can_be_removed_as_an_orphan(+ models_path: Path, store: ModelRecordServiceSQL, payload: str+) -> None:+ """Startup keeps a staging directory whose marker it cannot read; orphan cleanup is how a person removes it, even+ when it holds only partial downloads."""+ staging = models_path / "tmpinstall_torn"+ _write_model_file(staging, payload)+ (staging / ".invokeai_install.json").write_text('{"version": 1, "sta', encoding="utf-8")+ service = _service(models_path, store)++ [orphan] = service.find_orphaned_models()+ assert orphan.path == "tmpinstall_torn"+ assert payload in orphan.files+ assert orphan.size_bytes >= len(b"not really a model")+ result = service.delete_orphaned_models(["tmpinstall_torn"])++ assert result == {"tmpinstall_torn": "deleted"}+ assert not staging.exists()+ assert list(models_path.iterdir()) == []+++def test_staging_with_an_unusable_marker_that_holds_a_registered_model_is_not_offered(+ models_path: Path, store: ModelRecordServiceSQL+) -> None:+ # A recovered tree registered in place, whose marker an earlier release left torn.+ staging = models_path / "tmpinstall_recovered"+ _write_model_file(staging / "my-model")+ (staging / ".invokeai_install.json").write_text('{"version": 1, "sta', encoding="utf-8")+ store.add_model(+ TI_File_SD1_Config(+ path="tmpinstall_recovered/my-model/model.safetensors",+ name="recovered",+ hash="ABC123",+ file_size=18,+ source="test/source/",+ source_type=ModelSourceType.Path,+ )+ )++ assert _service(models_path, store).find_orphaned_models() == []+++def test_staging_with_a_resumable_or_claimed_marker_is_not_offered_as_an_orphan(+ models_path: Path, store: ModelRecordServiceSQL+) -> None:+ resumable = models_path / "tmpinstall_resumable"+ _write_model_file(resumable, "model.safetensors.downloading")+ (resumable / ".invokeai_install.json").write_text(+ json.dumps({"version": 1, "source": "https://example.com/m.safetensors", "status": "paused"}), encoding="utf-8"+ )+ claimed = models_path / "tmpinstall_claimed"+ _write_model_file(claimed, "model.safetensors.downloading")+ (claimed / ".invokeai_install.json").write_text("torn", encoding="utf-8")+ (models_path / f".tmpinstall_claimed{INSTALL_ACTIVE_SENTINEL}").write_text("2147483647 1.0\n", encoding="ascii")++ assert _service(models_path, store).find_orphaned_models() == []++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")@@ -190,7 +270,7 @@ def test_parent_of_recovery_root_cannot_be_deleted(models_path: Path, store: Modassert "model-group" not in {orphan.path for orphan in service.find_orphaned_models()}result = service.delete_orphaned_models(["model-group"])- assert result["model-group"].startswith("error:")+ assert result["model-group"] == "error: path is reserved by an active install or install recovery"assert (parent / "ordinary-orphan" / "model.safetensors").exists()assert (recovery_root / "model.safetensors").exists()assert sentinel.exists()diff --git a/tests/backend/model_manager/configs/test_ip_adapter_config.py b/tests/backend/model_manager/configs/test_ip_adapter_config.pyindex 8d6d7ce1fd..c4a463c134 100644--- a/tests/backend/model_manager/configs/test_ip_adapter_config.py+++ b/tests/backend/model_manager/configs/test_ip_adapter_config.py@@ -18,7 +18,7 @@ from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI],)def test_invokeai_ip_adapter_probe_normalizes_image_encoder_metadata(tmp_path: Path, metadata: str) -> None:- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, tmp_path / "ip_adapter.bin")(tmp_path / "image_encoder.txt").write_text(metadata, encoding="utf-8")result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)@@ -28,7 +28,7 @@ def test_invokeai_ip_adapter_probe_normalizes_image_encoder_metadata(tmp_path: Pdef test_invokeai_ip_adapter_probe_rejects_empty_image_encoder_metadata(tmp_path: Path) -> None:- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, tmp_path / "ip_adapter.bin")(tmp_path / "image_encoder.txt").write_text(" \r\n\t", encoding="utf-8")result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)@@ -38,7 +38,7 @@ def test_invokeai_ip_adapter_probe_rejects_empty_image_encoder_metadata(tmp_pathdef test_invokeai_ip_adapter_probe_applies_encoder_override_without_mutating_it(tmp_path: Path) -> None:- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, tmp_path / "ip_adapter.bin")(tmp_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")overrides = {"image_encoder_model_id": "custom/image-encoder"}@@ -50,7 +50,7 @@ def test_invokeai_ip_adapter_probe_applies_encoder_override_without_mutating_it(def test_invokeai_ip_adapter_probe_rejects_empty_encoder_override(tmp_path: Path) -> None:- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, tmp_path / "ip_adapter.bin")(tmp_path / "image_encoder.txt").write_text("custom/image-encoder\n", encoding="utf-8")result = ModelConfigFactory.from_model_on_disk(@@ -62,7 +62,7 @@ def test_invokeai_ip_adapter_probe_rejects_empty_encoder_override(tmp_path: Pathdef test_invokeai_ip_adapter_probe_rejects_missing_image_encoder_metadata(tmp_path: Path) -> None:- torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.zeros(1, 768)}}, tmp_path / "ip_adapter.bin")result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)