Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(models): install and start on drives without hard links (#10007)

Alexander Eichhorn6af20578bce6
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index a6140f762a..e671f1ce44 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -559,7 +559,7 @@ When a restore rename crosses filesystems, its temporary copy is created in a hi
Remote staging directories are claimed before downloads begin, and startup cleanup skips directories with a live claim. User-paused downloads keep their claim so orphan cleanup cannot expose or delete resumable staging; shutdown releases the claim only after the download queue has quiesced, preserving completed downloads for restart. Local sources under the managed models directory and orphan deletion also take an exclusive active claim, so probing or transfer cannot race with cleanup; startup removes claims from processes that have exited. Install jobs can be cancelled before file transfer starts. Once files are being moved, cancellation returns a conflict so the transfer can finish or preserve its recovery data. During shutdown, the installer waits for its worker to finish before cleaning queued jobs.
-Active-claim sidecars accept the legacy `PID process-start-time` payload and new Linux claims append a stable `linux:<boot-id>:<start-ticks>` process identity. A live PID with a legacy timestamp mismatch is ambiguous because wall-clock changes and PID reuse cannot be distinguished; startup preserves that claim for operator recovery. New Linux claims use the boot ID and kernel start ticks, so a reused PID can be reclaimed without comparing wall-clock time. On other platforms, new claims retain the two-field format and a reused live PID is conservatively preserved; a Linux-format sidecar encountered there is unsupported and also preserved. Claim payloads are written and flushed to a temporary file, then atomically published as a no-clobber hard link; a process killed before publication cannot leave an empty canonical claim, though it may leave an ignored temporary file. If the filesystem does not support hard links, claim creation fails rather than exposing a partial sidecar.
+Active-claim sidecars accept the legacy `PID process-start-time` payload and new Linux claims append a stable `linux:<boot-id>:<start-ticks>` process identity. A live PID with a legacy timestamp mismatch is ambiguous because wall-clock changes and PID reuse cannot be distinguished; startup preserves that claim for operator recovery. New Linux claims use the boot ID and kernel start ticks, so a reused PID can be reclaimed without comparing wall-clock time. On other platforms, new claims retain the two-field format and a reused live PID is conservatively preserved; a Linux-format sidecar encountered there is unsupported and also preserved. Claim payloads are written and flushed to a temporary file, then published under the claim name without ever replacing an existing claim (`invokeai/app/util/no_replace.py`): as a hard link; where the filesystem has no hard links (exFAT, FAT32, many network shares), by an atomic no-replace rename; where neither works (macOS exFAT, NFS, many FUSE mounts), by creating the claim exclusively and copying the payload into it. Claim creation fails only when none of these works. A process killed before publication may leave an ignored temporary file. Only the copy fallback can expose a partial claim or leave one behind: after a crash, or when a failed copy cannot confirm that the file under the claim name is still its own and so keeps it. A partial claim still counts as held, and the sweep preserves it as malformed.
Startup serializes stale-claim scans in-process and across processes with the persistent hidden `.invokeai_install_claims.lock` file in the models root; it remains in place so concurrent scanners always lock the same file. The lock covers enumeration through stale-claim removal, so a waiting scan sees claims created after the preceding scan completes. Windows uses repeated nonblocking lock attempts rather than `msvcrt.LK_LOCK`'s finite retry count, which could fail during a long scan. An empty or malformed sidecar, denied process inspection, and other inspection failures do not prove that its owner is gone, so startup preserves the claim and emits at most ten individual warnings plus one summary per scan. The next service startup retries the check. If the claim remains, an operator may remove its sidecar manually only after confirming that no install or orphan deletion is using that path; age alone is not evidence that a claim is stale.
diff --git a/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py b/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py
index aa3fcd6bbe..8cc394ea89 100644
--- a/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py
+++ b/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py
@@ -24,6 +24,7 @@ from invokeai.app.services.gallery_maintenance.gallery_maintenance_common import
GalleryMaintenanceResult,
)
from invokeai.app.services.image_moves.image_moves_default import ImageMoveJobAlreadyRunning, ImageMoveQueueActive
+from invokeai.app.util.no_replace import publish_noreplace
from invokeai.app.util.thumbnails import get_thumbnail_name
from invokeai.backend.util.logging import InvokeAILogger
@@ -863,8 +864,8 @@ class GalleryMaintenanceService:
after = os.fstat(source_file.fileno())
if GalleryMaintenanceService._signature(after)[:5] != expected[:5]:
raise OSError("Source changed while archiving")
- os.link(temporary, destination)
- temporary.unlink()
+ publish_noreplace(temporary, destination)
+ temporary.unlink(missing_ok=True)
GalleryMaintenanceService.__fsync_directory(destination.parent)
if GalleryMaintenanceService._path_signature(source) != expected:
raise OSError("Source changed before archive completion")
@@ -888,11 +889,11 @@ class GalleryMaintenanceService:
except Exception:
if source_quarantined and quarantined_source is not None:
try:
- # Link is atomic and refuses to replace a source created by another writer.
+ # Publishing is atomic and refuses to replace a source created by another writer.
# If restoration cannot safely claim the original name, leave the quarantined
# file in its hidden directory for recovery instead of deleting user data.
- os.link(quarantined_source, source)
- quarantined_source.unlink()
+ publish_noreplace(quarantined_source, source)
+ quarantined_source.unlink(missing_ok=True)
source_quarantined = False
GalleryMaintenanceService.__fsync_directory(quarantine_directory)
GalleryMaintenanceService.__fsync_directory(source.parent)
@@ -943,8 +944,8 @@ class GalleryMaintenanceService:
def _restore_quarantined_thumbnail(self, quarantined: Path, thumbnail: Path) -> None:
try:
- os.link(quarantined, thumbnail)
- quarantined.unlink()
+ publish_noreplace(quarantined, thumbnail)
+ quarantined.unlink(missing_ok=True)
self.__fsync_directory(quarantined.parent)
self.__fsync_directory(thumbnail.parent)
except OSError:
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.py
index 0d45a70767..242e5810a0 100644
--- a/invokeai/app/services/image_files/image_files_disk.py
+++ b/invokeai/app/services/image_files/image_files_disk.py
@@ -23,6 +23,7 @@ from invokeai.app.services.image_files.image_files_common import (
ImageFileSaveException,
)
from invokeai.app.services.invoker import Invoker
+from invokeai.app.util.no_replace import file_signature, publish_noreplace
from invokeai.app.util.thumbnails import get_thumbnail_name, make_thumbnail
from invokeai.backend.util.logging import InvokeAILogger
@@ -323,7 +324,6 @@ class DiskImageFileStorage(ImageFileStorageBase):
thumbnail_path.parent.mkdir(parents=True, exist_ok=True)
temporary_path: Path | None = None
thumbnail: PILImageType | None = None
- published_identity: tuple[int, int] | None = None
try:
with Image.open(image_path) as source_image:
thumbnail = make_thumbnail(source_image, thumbnail_size)
@@ -335,21 +335,19 @@ class DiskImageFileStorage(ImageFileStorageBase):
thumbnail.save(temporary_path, format="WEBP")
with open(temporary_path, "rb+") as completed_file:
os.fsync(completed_file.fileno())
- temporary_stat = temporary_path.stat()
- temporary_identity = (temporary_stat.st_dev, temporary_stat.st_ino)
try:
- # Linking publishes the fully written temporary file atomically and refuses to
- # replace a thumbnail another writer created after our first existence check.
- os.link(temporary_path, thumbnail_path)
+ # Publishes the fully written temporary file, refusing to replace a thumbnail another
+ # writer created after our first existence check. Where the drive forces a copy, the
+ # published thumbnail is a different file than the temporary one.
+ published_signature = publish_noreplace(temporary_path, thumbnail_path)
except FileExistsError:
return False
- published_identity = temporary_identity
try:
self.__fsync_directory(thumbnail_path.parent)
except Exception:
try:
- current_stat = thumbnail_path.lstat()
- if (current_stat.st_dev, current_stat.st_ino) == published_identity:
+ # Only our own thumbnail goes: not a replacement, nor one save() rewrote in place.
+ if file_signature(thumbnail_path.lstat()) == published_signature:
thumbnail_path.unlink()
self.evict_cache_paths([thumbnail_path])
try:
diff --git a/invokeai/app/services/model_install/install_staging_ledger.py b/invokeai/app/services/model_install/install_staging_ledger.py
index afe43ca30f..dd2a8adfed 100644
--- a/invokeai/app/services/model_install/install_staging_ledger.py
+++ b/invokeai/app/services/model_install/install_staging_ledger.py
@@ -52,6 +52,7 @@ from invokeai.app.services.model_install.model_install_common import (
)
from invokeai.app.services.model_records import ModelRecordChanges
from invokeai.app.util.misc import get_iso_timestamp
+from invokeai.app.util.no_replace import publish_noreplace
TMPDIR_PREFIX = "tmpinstall_"
INSTALL_MARKER_FILENAME = ".invokeai_install.json"
@@ -125,8 +126,8 @@ def _publish_claim(root: Path) -> None:
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)
+ # Publishes the complete payload atomically and fails if another owner won.
+ publish_noreplace(temp_path, path)
except BaseException:
try:
temp_path.unlink(missing_ok=True)
@@ -134,7 +135,7 @@ def _publish_claim(root: Path) -> None:
pass
raise
else:
- # Once linked, cleanup cannot make publication fail for the owner.
+ # Once published, cleanup cannot make publication fail for the owner.
try:
temp_path.unlink(missing_ok=True)
except OSError:
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index fee4083d4c..b3dff8019c 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -1,6 +1,5 @@
"""Model installation class."""
-import ctypes
import errno
import filecmp
import gc
@@ -8,7 +7,6 @@ import locale
import os
import re
import ssl
-import sys
import threading
import time
from copy import deepcopy
@@ -61,6 +59,7 @@ from invokeai.app.services.model_install.model_install_common import (
)
from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelException
from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
+from invokeai.app.util.no_replace import rename_noreplace
from invokeai.app.util.path_safety import is_plain_filename
from invokeai.app.util.ssrf import UnsafeDownloadURLException
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base
@@ -918,45 +917,12 @@ class ModelInstallService(ModelInstallServiceBase):
time.sleep(delay)
delay *= 2 # Exponential backoff
- @staticmethod
- def _rename_noreplace(src: Path, dst: Path) -> None:
- """Atomically restore a path only if its destination is still absent."""
- if sys.platform.startswith("linux"):
- libc = ctypes.CDLL(None, use_errno=True)
- renameat2 = getattr(libc, "renameat2", None)
- if renameat2 is None:
- raise OSError("atomic no-replace rename is unavailable")
- renameat2.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
- renameat2.restype = ctypes.c_int
- result = renameat2(-100, os.fsencode(src), -100, os.fsencode(dst), 1) # AT_FDCWD, RENAME_NOREPLACE
- if result != 0:
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error), str(dst))
- return
- if sys.platform == "darwin":
- libc = ctypes.CDLL(None, use_errno=True)
- renamex_np = getattr(libc, "renamex_np", None)
- if renamex_np is None:
- raise OSError("atomic no-replace rename is unavailable")
- renamex_np.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
- renamex_np.restype = ctypes.c_int
- result = renamex_np(os.fsencode(src), os.fsencode(dst), 0x00000004) # RENAME_EXCL
- if result != 0:
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error), str(dst))
- return
- if os.name == "nt":
- # Windows rename fails when the destination already exists.
- os.rename(src, dst)
- return
- raise OSError("atomic no-replace rename is unavailable on this platform")
-
@classmethod
def _restore_moved_path(cls, src: Path, dst: Path) -> None:
if dst.exists() or dst.is_symlink():
raise FileExistsError(f"Refusing to overwrite recreated source {dst}")
try:
- cls._rename_noreplace(src, dst)
+ rename_noreplace(src, dst)
except OSError as e:
if e.errno != errno.EXDEV:
raise
@@ -973,7 +939,7 @@ class ModelInstallService(ModelInstallServiceBase):
copy2(src, staged_path)
else:
raise OSError(f"Cannot restore unsupported filesystem object {src}")
- cls._rename_noreplace(staged_path, dst)
+ rename_noreplace(staged_path, dst)
if src.is_dir() and not src.is_symlink():
rmtree(src)
else:
diff --git a/invokeai/app/util/database_copy.py b/invokeai/app/util/database_copy.py
index 97540c97b5..d492b3e857 100644
--- a/invokeai/app/util/database_copy.py
+++ b/invokeai/app/util/database_copy.py
@@ -2,7 +2,6 @@
into a new SQLite file."""
import argparse
-import os
import shutil
import sys
import tempfile
@@ -28,6 +27,7 @@ from invokeai.app.services.shared.database.startup import (
open_migrated_database,
redacted_database_url,
)
+from invokeai.app.util.no_replace import publish_noreplace
from invokeai.backend.util.logging import InvokeAILogger
_START_AGAIN = (
@@ -286,17 +286,11 @@ def _copy_to_sqlite(source: Database, target_path: Path, logger: Logger) -> int:
def _move_into_place(work_path: Path, target_path: Path) -> bool:
"""Moves the copy to `target_path` unless a file is there; whether it did."""
try:
- # A link, unlike a rename, refuses a path that exists, without a moment between checking and moving.
- os.link(work_path, target_path)
+ publish_noreplace(work_path, target_path)
except FileExistsError:
return False
- except OSError:
- # A file system without hard links (FAT, some network shares): check, then move.
- if target_path.exists() or target_path.is_symlink():
- return False
- os.replace(work_path, target_path)
- return True
- # The work file's other name goes with its directory, which the caller deletes.
+ # Where the copy was linked or copied rather than renamed, the work file goes with its directory, which the caller
+ # deletes.
return True
diff --git a/invokeai/app/util/no_replace.py b/invokeai/app/util/no_replace.py
new file mode 100644
index 0000000000..73916329ba
--- /dev/null
+++ b/invokeai/app/util/no_replace.py
@@ -0,0 +1,141 @@
+"""Give a path its final name without ever replacing a path that already holds that name."""
+
+import contextlib
+import ctypes
+import os
+import shutil
+import stat
+import sys
+from pathlib import Path
+
+
+def rename_noreplace(src: Path, dst: Path) -> None:
+ """Atomically rename a file or directory; raises FileExistsError when dst exists, OSError when unsupported."""
+ if sys.platform.startswith("linux"):
+ libc = ctypes.CDLL(None, use_errno=True)
+ renameat2 = getattr(libc, "renameat2", None)
+ if renameat2 is None:
+ raise OSError("atomic no-replace rename is unavailable")
+ renameat2.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
+ renameat2.restype = ctypes.c_int
+ result = renameat2(-100, os.fsencode(src), -100, os.fsencode(dst), 1) # AT_FDCWD, RENAME_NOREPLACE
+ if result != 0:
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error), str(dst))
+ return
+ if sys.platform == "darwin":
+ libc = ctypes.CDLL(None, use_errno=True)
+ renamex_np = getattr(libc, "renamex_np", None)
+ if renamex_np is None:
+ raise OSError("atomic no-replace rename is unavailable")
+ renamex_np.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
+ renamex_np.restype = ctypes.c_int
+ result = renamex_np(os.fsencode(src), os.fsencode(dst), 0x00000004) # RENAME_EXCL
+ if result != 0:
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error), str(dst))
+ return
+ if os.name == "nt":
+ # Windows rename fails when the destination already exists.
+ os.rename(src, dst)
+ return
+ raise OSError("atomic no-replace rename is unavailable on this platform")
+
+
+FileSignature = tuple[int, int, int, int]
+
+
+def file_signature(result: os.stat_result) -> FileSignature:
+ """Device, inode, size and modification time: what tells this module's published file apart from a replacement.
+
+ The inode alone is weak evidence on FAT-family drivers (macOS msdosfs and exFAT among them), which derive file IDs
+ from where a file sits, so a replacement can carry the ID of the file it replaced.
+ """
+ return result.st_dev, result.st_ino, result.st_size, result.st_mtime_ns
+
+
+def publish_noreplace(src: Path, dst: Path) -> FileSignature:
+ """Give the regular file src the name dst; raises FileExistsError, leaving dst untouched, when dst exists.
+
+ Where hard links work, dst becomes a second name of src, src keeps its name and the caller removes it. Without hard
+ links (exFAT, FAT32, many network shares) src is renamed to dst with an atomic no-replace rename and no longer
+ exists. Where neither works (macOS exFAT, NFS, many FUSE mounts), dst is created exclusively with src's permission
+ bits and src's bytes copied into it; src keeps its name. Only in that last case can another reader briefly see a
+ partially written dst. Callers tolerate that: a claim counts by existence and a partial payload is preserved as
+ malformed; thumbnails, archives, restores and database copies are re-validated or transient. A failed copy removes
+ dst only while dst is still the file it created.
+
+ Returns the file_signature of the file published as dst, so a caller can compare file_signature(dst.lstat()) later
+ to tell whether dst still names it: taken from src before a link or rename, which change neither size nor
+ modification time, and from the copy after a copy. On Windows FAT and exFAT a rename to a longer name can change the
+ file ID, so there the signature can differ even though dst still names the published file; the thumbnail rollback,
+ which compares it, never runs on Windows, whose directory fsync is a no-op.
+ """
+ # Stat src, which the caller owns, rather than dst, which another writer could replace once it is published.
+ source = file_signature(os.lstat(src))
+ try:
+ os.link(src, dst)
+ return source
+ except FileExistsError:
+ raise
+ except OSError as link_error:
+ try:
+ rename_noreplace(src, dst)
+ return source
+ except FileExistsError:
+ raise
+ except OSError as rename_error:
+ rename_error.__cause__ = link_error
+ fallback_error = rename_error
+ try:
+ return _copy_noreplace(src, dst)
+ except FileExistsError:
+ raise
+ except OSError as copy_error:
+ raise copy_error from fallback_error
+
+
+def _copy_noreplace(src: Path, dst: Path) -> FileSignature:
+ """Create dst exclusively and copy src into it; returns the copy's file_signature."""
+ with open(src, "rb") as source:
+ # The umask can only narrow src's permission bits, so the copy is never more accessible than src.
+ mode = stat.S_IMODE(os.fstat(source.fileno()).st_mode)
+ fd = os.open(dst, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0), mode)
+ try:
+ # The writer leaves fd open: its close flushes buffered bytes, also when the copy failed, and fd then
+ # still identifies the copy as finally written.
+ with os.fdopen(fd, "wb", closefd=False) as target:
+ shutil.copyfileobj(source, target)
+ target.flush()
+ os.fsync(fd)
+ copied = file_signature(os.fstat(fd))
+ except BaseException:
+ _remove_failed_copy(fd, dst)
+ raise
+ os.close(fd)
+ return copied
+
+
+def _remove_failed_copy(fd: int, dst: Path) -> None:
+ """Unlink dst only while it still names the failed copy behind fd, and close fd; keeps dst on any doubt."""
+ # POSIX keeps fd open through the check and the unlink: no replacement can reuse the copy's inode, and times a
+ # filesystem updates on close cannot make the copy look foreign. Windows cannot unlink an open file and closes
+ # first. Left open, for writers outside InvokeAI (which never replaces dst): a replacement between the check and
+ # the unlink, which nothing prevents without hard links or no-replace rename; and, where a replacement can carry
+ # the copy's ID (FAT drivers, Windows after the close), a same-size one within one mtime step (2 s on FAT32).
+ open_fd: int | None = fd
+ try:
+ with contextlib.suppress(OSError):
+ copy = file_signature(os.fstat(fd))
+ if os.name == "nt":
+ open_fd = None
+ os.close(fd)
+ if file_signature(os.lstat(dst)) == copy:
+ if os.name == "nt":
+ # Windows refuses to unlink a read-only file, which the copy of a read-only src is.
+ os.chmod(dst, stat.S_IWRITE)
+ os.unlink(dst)
+ finally:
+ if open_fd is not None:
+ with contextlib.suppress(OSError):
+ os.close(open_fd)
diff --git a/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py b/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py
index eccd9c4432..fb6c64049e 100644
--- a/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py
+++ b/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py
@@ -1,3 +1,4 @@
+import errno
import os
import shutil
from contextlib import contextmanager
@@ -34,6 +35,7 @@ from invokeai.app.services.shared.database.schema.boards import board_images
from invokeai.app.services.shared.database.schema.image_index import image_embeddings, video_embeddings
from invokeai.app.services.shared.database.schema.image_moves import image_subfolder_move_items
from invokeai.app.services.video_records.video_records_default import VideoRecordStorage
+from invokeai.app.util import no_replace
class _ImageMutationGate:
@@ -69,6 +71,11 @@ def maintenance(
return service, db, records, files
+def _refuse_link(src: Path, dst: Path) -> None:
+ """Refuse hard links the way exFAT does on Linux."""
+ raise PermissionError(errno.EPERM, "Operation not permitted", str(dst))
+
+
def _count(database: Database, table: Table, where: ColumnElement[bool] | None = None) -> int:
statement = select(func.count()).select_from(table)
if where is not None:
@@ -594,6 +601,43 @@ def test_archive_file_tolerates_ctime_difference_between_path_and_open_file(
assert not source.exists()
+def test_archive_file_without_hard_links_publishes_and_restores_a_quarantined_source(
+ maintenance, tmp_path: Path, monkeypatch
+) -> None:
+ service, _db, _records, _files = maintenance
+ source_dir = tmp_path / "gallery"
+ source_dir.mkdir()
+ source = source_dir / "source.png"
+ destination = tmp_path / "archive" / "source.png"
+ source_bytes = b"confirmed source bytes"
+ source.write_bytes(source_bytes)
+ expected = service._signature(source.lstat())
+ real_fsync_directory = GalleryMaintenanceService._GalleryMaintenanceService__fsync_directory
+ quarantine_sync_failed = False
+
+ def fail_first_quarantine_sync(directory: Path) -> None:
+ nonlocal quarantine_sync_failed
+ if Path(directory).name.startswith(".gallery-archive-") and not quarantine_sync_failed:
+ quarantine_sync_failed = True
+ raise OSError("injected quarantine sync failure")
+ real_fsync_directory(directory)
+
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
+ monkeypatch.setattr(
+ GalleryMaintenanceService,
+ "_GalleryMaintenanceService__fsync_directory",
+ staticmethod(fail_first_quarantine_sync),
+ )
+
+ with pytest.raises(OSError, match="injected quarantine sync failure"):
+ service._archive_file(source, destination, expected)
+
+ assert destination.read_bytes() == source_bytes
+ assert list(destination.parent.iterdir()) == [destination]
+ assert source.read_bytes() == source_bytes
+ assert list(source_dir.iterdir()) == [source]
+
+
def test_preview_rejects_symlinked_record_subfolder(maintenance, tmp_path: Path) -> None:
service, _db, records, files = maintenance
_save_image_record(records, "outside.png", "linked")
@@ -667,7 +711,10 @@ def test_regeneration_removes_thumbnail_if_size_persistence_fails(maintenance, m
assert result.status == "failed"
-def test_regeneration_cleanup_preserves_replacement_thumbnail(maintenance, monkeypatch) -> None:
[email protected]("hard_links", [True, False], ids=["hard-links", "no-hard-links"])
+def test_regeneration_cleanup_preserves_replacement_thumbnail(maintenance, monkeypatch, hard_links: bool) -> None:
+ if not hard_links:
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
service, _db, records, files = maintenance
_save_image_record(records, "replacement.png", "nested")
_write_png(files, "replacement.png", "nested")
diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.py
index af5d31b322..9d06722004 100644
--- a/tests/app/services/image_files/test_image_files_disk.py
+++ b/tests/app/services/image_files/test_image_files_disk.py
@@ -19,6 +19,7 @@ from invokeai.app.services.image_files.image_files_common import (
ImageFileSaveException,
)
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage, _should_use_png_rle
+from invokeai.app.util import no_replace
from invokeai.app.util.thumbnails import get_thumbnail_name
@@ -34,6 +35,16 @@ def _restart(storage: DiskImageFileStorage, record_exists: bool) -> DiskImageFil
posix_only = pytest.mark.skipif(os.name == "nt", reason="Windows cannot open a directory for fsync")
+def _refuse_link(src: Path, dst: Path) -> None:
+ """Refuse hard links the way exFAT does on Linux."""
+ raise PermissionError(errno.EPERM, "Operation not permitted", str(dst))
+
+
+def _refuse_no_replace_rename(src: Path, dst: Path) -> None:
+ """Refuse an atomic no-replace rename the way macOS exFAT, NFS and many FUSE mounts do."""
+ raise OSError(errno.ENOTSUP, "Operation not supported", str(dst))
+
+
def _failing_directory_fsync(error_number: int):
"""An ``os.fsync`` that fails for directory descriptors only; file fsyncs still work."""
real_fsync = os.fsync
@@ -169,7 +180,12 @@ def test_iter_image_paths_streams_directory_entries_in_deterministic_order(
assert Entry.peak_active <= 2
-def test_generate_thumbnail_if_missing_preserves_source_and_never_overwrites(tmp_path: Path):
[email protected]("hard_links", [True, False], ids=["hard-links", "no-hard-links"])
+def test_generate_thumbnail_if_missing_preserves_source_and_never_overwrites(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, hard_links: bool
+):
+ if not hard_links:
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
storage = DiskImageFileStorage(tmp_path)
image_path = storage.get_path("test.png", image_subfolder="sub")
image_path.parent.mkdir(parents=True)
@@ -185,6 +201,7 @@ def test_generate_thumbnail_if_missing_preserves_source_and_never_overwrites(tmp
assert image_path.read_bytes() == original_bytes
assert storage.generate_thumbnail_if_missing("test.png", image_subfolder="sub") is False
assert thumbnail_path.read_bytes() == first_thumbnail
+ assert [path.name for path in thumbnail_path.parent.iterdir()] == [thumbnail_path.name]
def test_generate_thumbnail_if_missing_does_not_publish_partial_file(tmp_path: Path):
@@ -224,9 +241,14 @@ def test_generate_thumbnail_if_missing_fsyncs_a_writable_temporary_file(
@posix_only
[email protected]("mount", ["hard-links", "no-hard-links", "copy-only"])
def test_generate_thumbnail_if_missing_removes_thumbnail_if_directory_fsync_fails(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mount: str
):
+ if mount in ("no-hard-links", "copy-only"):
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
+ if mount == "copy-only":
+ monkeypatch.setattr(no_replace, "rename_noreplace", _refuse_no_replace_rename)
storage = DiskImageFileStorage(tmp_path)
image_path = storage.get_path("fsync-failure.png")
with Image.new("RGB", (8, 8), (20, 40, 60)) as source:
@@ -244,6 +266,7 @@ def test_generate_thumbnail_if_missing_removes_thumbnail_if_directory_fsync_fail
assert image_path.read_bytes() == original_bytes
assert not thumbnail_path.exists()
+ assert list(thumbnail_path.parent.iterdir()) == []
def test_cache_eviction_prevents_inflight_read_from_repopulating_stale_image(
diff --git a/tests/app/services/model_install/test_install_staging_ledger.py b/tests/app/services/model_install/test_install_staging_ledger.py
index 24b38e5e2e..42728514ba 100644
--- a/tests/app/services/model_install/test_install_staging_ledger.py
+++ b/tests/app/services/model_install/test_install_staging_ledger.py
@@ -30,6 +30,7 @@ from invokeai.app.services.model_install.model_install_common import (
URLModelSource,
)
from invokeai.app.services.model_records import ModelRecordChanges
+from invokeai.app.util import no_replace
from invokeai.backend.util.logging import InvokeAILogger
SOURCE = "https://example.com/weights.safetensors"
@@ -58,6 +59,16 @@ def ledger(models_path: Path) -> InstallStagingLedger:
return InstallStagingLedger(models_path, InvokeAILogger.get_logger("InstallStagingLedgerTest"))
+def without_hard_links(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Refuse hard links the way exFAT does on Linux."""
+
+ def refuse_link(src: Path, dst: Path) -> None:
+ raise PermissionError(errno.EPERM, "Operation not permitted", str(dst))
+
+ monkeypatch.setattr(no_replace.os, "link", refuse_link)
+
+
def _claim_path(root: Path) -> Path:
return root.parent / f".{root.name}.invokeai_install_active"
@@ -537,6 +548,33 @@ def test_a_second_claim_on_staging_is_refused_and_recorded(ledger: InstallStagin
contender.release_claim()
+def test_without_hard_links_a_claim_is_taken_and_a_second_claim_conflicts(
+ ledger: InstallStagingLedger, models_path: Path, without_hard_links: None
+) -> None:
+ tmpdir = _staging_dir(models_path, "no-hard-links")
+ owner = InstallStaging(ledger, tmpdir)
+ owner.claim()
+ contender = InstallStaging(ledger, tmpdir)
+
+ with pytest.raises(InstallCancellationConflictError, match="another install or orphan cleanup"):
+ contender.claim()
+
+ assert len(_claim_path(tmpdir).read_text(encoding="ascii").split()) >= 2
+ assert sorted(path.name for path in models_path.iterdir()) == sorted([tmpdir.name, _claim_path(tmpdir).name])
+ owner.release_claim()
+ assert not _claim_path(tmpdir).exists()
+
+
+def test_without_hard_links_startup_cleanup_removes_dangling_staging(
+ ledger: InstallStagingLedger, models_path: Path, without_hard_links: None
+) -> None:
+ _staging_dir(models_path, "failed-install")
+
+ ledger.remove_dangling_staging([])
+
+ assert list(models_path.iterdir()) == []
+
+
@pytest.mark.parametrize("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
@@ -899,12 +937,12 @@ def test_claim_publication_survives_temporary_unlink_failure(
root.mkdir()
claim = _claim_path(root)
temp_paths: list[Path] = []
- real_link = os.link
+ real_publish = install_staging_ledger.publish_noreplace
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)
+ real_publish(temp_path, claim_path)
def fail_temp_unlink(path: Path, *args: Any, **kwargs: Any) -> None:
if temp_paths and path == temp_paths[0]:
@@ -913,7 +951,7 @@ def test_claim_publication_survives_temporary_unlink_failure(
try:
with monkeypatch.context() as patch:
- patch.setattr(install_staging_ledger.os, "link", publish)
+ patch.setattr(install_staging_ledger, "publish_noreplace", publish)
patch.setattr(Path, "unlink", fail_temp_unlink)
held = ledger.claim(root)
assert claim.exists()
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index a2bfd00932..b5eac0f1e9 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -75,6 +75,7 @@ from invokeai.app.services.model_install.model_install_common import (
URLModelSource,
)
from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL, UnknownModelException
+from invokeai.app.util import no_replace
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
from invokeai.backend.model_manager.metadata import (
HuggingFaceMetadata,
@@ -413,14 +414,14 @@ def test_rollback_restores_source_across_filesystems_without_overwriting(
original.write_bytes(b"model weights")
moved = destination_root / "model"
shutil.move(original, moved)
- real_rename_noreplace = ModelInstallService._rename_noreplace
+ real_rename_noreplace = model_install_default.rename_noreplace
def raise_exdev_for_original(src: Path, dst: Path) -> None:
if src == moved:
raise OSError(errno.EXDEV, "cross-device link")
real_rename_noreplace(src, dst)
- monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(raise_exdev_for_original))
+ monkeypatch.setattr(model_install_default, "rename_noreplace", raise_exdev_for_original)
ModelInstallService._restore_moved_path(moved, original)
@@ -486,7 +487,7 @@ def test_startup_cleanup_preserves_live_exdev_restore_lookalike(
copy_started = threading.Event()
finish_copy = threading.Event()
real_copy2 = shutil.copy2
- real_rename_noreplace = ModelInstallService._rename_noreplace
+ real_rename_noreplace = model_install_default.rename_noreplace
def pause_copy(src: Path, dst: Path) -> Path:
real_copy2(src, dst)
@@ -500,7 +501,7 @@ def test_startup_cleanup_preserves_live_exdev_restore_lookalike(
real_rename_noreplace(src, dst)
monkeypatch.setattr(model_install_default, "copy2", pause_copy)
- monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(raise_exdev_for_managed_copy))
+ monkeypatch.setattr(model_install_default, "rename_noreplace", raise_exdev_for_managed_copy)
errors: list[Exception] = []
def restore() -> None:
@@ -747,7 +748,7 @@ def test_directory_install_rollback_race_preserves_both_source_artifacts(
locked_item = items[-1]
original_bytes = first_item.read_bytes()
real_move = shutil.move
- real_rename_noreplace = ModelInstallService._rename_noreplace
+ real_rename_noreplace = model_install_default.rename_noreplace
def fail_later_move(src: Path, dst: Path):
if src == locked_item:
@@ -760,7 +761,7 @@ def test_directory_install_rollback_race_preserves_both_source_artifacts(
real_rename_noreplace(src, dst)
_fake_move(monkeypatch, fail_later_move)
- monkeypatch.setattr(ModelInstallService, "_rename_noreplace", staticmethod(recreate_after_absence_check))
+ monkeypatch.setattr(model_install_default, "rename_noreplace", recreate_after_absence_check)
with pytest.raises(model_install_default.InstallRecoveryRequiredError, match="recovery required"):
mm2_installer.install_path(diffusers_dir)
@@ -813,11 +814,7 @@ def test_directory_install_preserves_recreated_source_when_no_replace_rename_fai
raise OSError(unsupported_errno, "atomic no-replace rename unsupported", str(dst))
_fake_move(monkeypatch, fail_later_move)
- monkeypatch.setattr(
- ModelInstallService,
- "_rename_noreplace",
- staticmethod(fail_no_replace_after_source_recreation),
- )
+ monkeypatch.setattr(model_install_default, "rename_noreplace", fail_no_replace_after_source_recreation)
with pytest.raises(InstallRecoveryRequiredError, match="recovery required") as exc_info:
mm2_installer.install_path(diffusers_dir)
@@ -1029,6 +1026,7 @@ def test_cancelling_leaves_staging_another_owner_claimed_untouched(
mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig
) -> None:
assert isinstance(mm2_installer, ModelInstallService)
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}claimed-elsewhere-{uuid.uuid4().hex}"
tmpdir.mkdir()
partial = tmpdir / "model.safetensors.downloading"
@@ -1262,6 +1260,7 @@ def test_queue_rejection_during_shutdown_preserves_completed_download(
mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig
) -> None:
assert isinstance(mm2_installer, ModelInstallService)
+ assert mm2_installer._wait_for_restore_complete(timeout=10)
tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}queue-stop-{uuid.uuid4().hex}"
partial_path = _write_remote_install_marker(mm2_installer, tmpdir, 9905, InstallStatus.DOWNLOADS_DONE)
job = ModelInstallJob(
@@ -2186,6 +2185,27 @@ def test_simple_download(mm2_installer: ModelInstallServiceBase, mm2_app_config:
assert isinstance(bus.events[4], ModelInstallCompleteEvent) # install completed
[email protected](timeout=10, method="thread")
+def test_remote_install_completes_on_a_filesystem_without_hard_links(
+ mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ def refuse_link(src: Path, dst: Path) -> None:
+ # exFAT on Linux; Windows reports WinError 1 for the same refusal.
+ raise PermissionError(errno.EPERM, "Operation not permitted", str(dst))
+
+ monkeypatch.setattr(no_replace.os, "link", refuse_link)
+ source = URLModelSource(url=Url("https://www.test.foo/download/test_embedding.safetensors"))
+
+ job = mm2_installer.import_model(source)
+ mm2_installer.wait_for_installs(timeout=10)
+
+ assert job.complete, job.error_traceback
+ assert job.config_out
+ assert (mm2_app_config.models_path / job.config_out.path).exists()
+ assert not list(mm2_app_config.models_path.glob(f".*{INSTALL_ACTIVE_SENTINEL}"))
+ assert not list(mm2_app_config.models_path.glob(f"{TMPDIR_PREFIX}*"))
+
+
@pytest.mark.timeout(timeout=10, method="thread")
def test_wait_for_installs_waits_for_download_completion_to_enqueue_install(
mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/app/util/test_no_replace.py b/tests/app/util/test_no_replace.py
new file mode 100644
index 0000000000..921a2c49fd
--- /dev/null
+++ b/tests/app/util/test_no_replace.py
@@ -0,0 +1,204 @@
+import errno
+import os
+import shutil
+import stat
+from pathlib import Path
+from typing import BinaryIO
+
+import pytest
+
+from invokeai.app.util import no_replace
+from invokeai.app.util.no_replace import file_signature, publish_noreplace, rename_noreplace
+
+
+def _refuse_link(src: Path, dst: Path) -> None:
+ """Refuse hard links the way exFAT does on Linux."""
+ raise PermissionError(errno.EPERM, "Operation not permitted", str(dst))
+
+
+def without_hard_links(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
+
+
+def _refuse_no_replace_rename(src: Path, dst: Path) -> None:
+ """Refuse an atomic no-replace rename the way macOS exFAT, NFS and many FUSE mounts do."""
+ raise OSError(errno.ENOTSUP, "Operation not supported", str(dst))
+
+
+def _limit_mount(monkeypatch: pytest.MonkeyPatch, mount: str) -> None:
+ if mount in ("no-hard-links", "copy-only"):
+ monkeypatch.setattr(no_replace.os, "link", _refuse_link)
+ if mount == "copy-only":
+ monkeypatch.setattr(no_replace, "rename_noreplace", _refuse_no_replace_rename)
+
+
+def test_publish_gives_the_file_its_final_name_and_keeps_the_source_name(tmp_path: Path) -> None:
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ dst = tmp_path / "published"
+
+ publish_noreplace(src, dst)
+
+ assert dst.read_bytes() == b"complete payload"
+ assert src.exists()
+
+
+def test_publish_without_hard_links_moves_the_file(tmp_path: Path, without_hard_links: None) -> None:
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ dst = tmp_path / "published"
+
+ publish_noreplace(src, dst)
+
+ assert dst.read_bytes() == b"complete payload"
+ assert not src.exists()
+
+
+def test_publish_without_link_or_no_replace_rename_copies_and_keeps_the_source(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _limit_mount(monkeypatch, "copy-only")
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ dst = tmp_path / "published"
+
+ publish_noreplace(src, dst)
+
+ assert dst.read_bytes() == b"complete payload"
+ assert src.read_bytes() == b"complete payload"
+
+
[email protected]("mount", ["hard-links", "no-hard-links", "copy-only"])
+def test_publish_refuses_an_existing_destination(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mount: str) -> None:
+ _limit_mount(monkeypatch, mount)
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"new payload")
+ dst = tmp_path / "published"
+ dst.write_bytes(b"other owner")
+
+ with pytest.raises(FileExistsError):
+ publish_noreplace(src, dst)
+
+ assert dst.read_bytes() == b"other owner"
+ assert src.read_bytes() == b"new payload"
+
+
[email protected]("read_only_source", [False, True], ids=["writable-source", "read-only-source"])
+def test_a_failed_copy_leaves_no_destination_and_reports_every_attempt(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, read_only_source: bool
+) -> None:
+ _limit_mount(monkeypatch, "copy-only")
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ if read_only_source:
+ # The copy inherits the read-only mode, which Windows refuses to unlink.
+ src.chmod(stat.S_IREAD)
+ dst = tmp_path / "published"
+
+ def fail_midway(source: BinaryIO, target: BinaryIO) -> None:
+ target.write(source.read(4))
+ raise OSError(errno.ENOSPC, "No space left on device")
+
+ monkeypatch.setattr(no_replace.shutil, "copyfileobj", fail_midway)
+
+ with pytest.raises(OSError) as exc_info:
+ publish_noreplace(src, dst)
+
+ assert exc_info.value.errno == errno.ENOSPC
+ assert not dst.exists()
+ assert src.read_bytes() == b"complete payload"
+ rename_error = exc_info.value.__cause__
+ assert isinstance(rename_error, OSError) and rename_error.errno == errno.ENOTSUP
+ assert isinstance(rename_error.__cause__, PermissionError)
+
+
[email protected](os.name == "nt", reason="Windows cannot replace a file that is open")
+def test_a_failed_copy_keeps_a_destination_another_writer_put_in_its_place(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _limit_mount(monkeypatch, "copy-only")
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ dst = tmp_path / "published"
+
+ def replace_destination_then_fail(source: BinaryIO, target: BinaryIO) -> None:
+ target.write(source.read(4))
+ replacement = tmp_path / "replacement"
+ replacement.write_bytes(b"other owner")
+ os.replace(replacement, dst)
+ raise OSError(errno.ENOSPC, "No space left on device")
+
+ monkeypatch.setattr(no_replace.shutil, "copyfileobj", replace_destination_then_fail)
+
+ with pytest.raises(OSError) as exc_info:
+ publish_noreplace(src, dst)
+
+ assert exc_info.value.errno == errno.ENOSPC
+ assert dst.read_bytes() == b"other owner"
+ assert src.read_bytes() == b"complete payload"
+
+
[email protected](os.name == "nt", reason="Windows has no POSIX permission bits")
+def test_a_copy_is_never_more_accessible_than_its_source(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _limit_mount(monkeypatch, "copy-only")
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"private payload")
+ src.chmod(0o600)
+ dst = tmp_path / "published"
+ real_copyfileobj = shutil.copyfileobj
+ modes_while_copying: list[int] = []
+
+ def copy_and_record_mode(source: BinaryIO, target: BinaryIO) -> None:
+ modes_while_copying.append(stat.S_IMODE(os.fstat(target.fileno()).st_mode))
+ real_copyfileobj(source, target)
+
+ monkeypatch.setattr(no_replace.shutil, "copyfileobj", copy_and_record_mode)
+ previous_umask = os.umask(0o022)
+ try:
+ publish_noreplace(src, dst)
+ finally:
+ os.umask(previous_umask)
+
+ assert modes_while_copying == [0o600]
+ assert stat.S_IMODE(dst.stat().st_mode) == 0o600
+ assert dst.read_bytes() == b"private payload"
+
+
[email protected]("mount", ["hard-links", "no-hard-links", "copy-only"])
+def test_publish_returns_the_signature_of_the_file_it_published(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mount: str
+) -> None:
+ _limit_mount(monkeypatch, mount)
+ src = tmp_path / "work.tmp"
+ src.write_bytes(b"complete payload")
+ dst = tmp_path / "published"
+
+ signature = publish_noreplace(src, dst)
+
+ assert signature == file_signature(dst.lstat())
+
+
+def test_rename_refuses_an_existing_destination(tmp_path: Path) -> None:
+ src = tmp_path / "src"
+ src.write_bytes(b"source")
+ dst = tmp_path / "dst"
+ dst.write_bytes(b"destination")
+
+ with pytest.raises(FileExistsError):
+ rename_noreplace(src, dst)
+
+ assert src.read_bytes() == b"source"
+ assert dst.read_bytes() == b"destination"
+
+
+def test_rename_moves_a_directory_with_its_contents(tmp_path: Path) -> None:
+ src = tmp_path / "src"
+ src.mkdir()
+ (src / "weights.safetensors").write_bytes(b"weights")
+ dst = tmp_path / "dst"
+
+ rename_noreplace(src, dst)
+
+ assert not src.exists()
+ assert (dst / "weights.safetensors").read_bytes() == b"weights"