Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(image-index): isolate vocabulary cache staging (#10033)
Nianze Wub2d443b78307
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex aa87ae5b15..b74dbb6816 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -5,6 +5,7 @@ from contextlib import contextmanagerfrom pathlib import Pathfrom queue import Empty, Queuefrom typing import TYPE_CHECKING, AbstractSet, Any, Callable, Iterable, Iterator, Optional+from uuid import uuid4import numpy as npimport torch@@ -615,29 +616,26 @@ class ImageIndexService(ImageIndexServiceBase):try:cache_path.parent.mkdir(parents=True, exist_ok=True)- # Written aside and renamed: two processes sharing a db_dir can- # first-run at once, and a kill mid-write would otherwise leave- # a truncated archive that costs another full re-embed.- #- # The staging name has to end in `.npz` because np.savez appends- # that extension to any path that lacks it: written as `.tmp`,- # the archive landed at `.tmp.npz` and the rename below then- # failed on the `.tmp` that was never created. The failure was- # swallowed by the handler, so the cache never reached disk and- # every restart re-embedded the whole vocabulary (minutes,- # during which cluster labels are unavailable) while leaking one- # orphaned staging file per run.- staging_path = cache_path.with_name(f"{cache_path.name}.{os.getpid()}.tmp.npz")- np.savez(staging_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))- os.replace(staging_path, cache_path)+ # Each writer owns a separate file in the cache directory. Normal+ # file creation preserves the umask and directory's default ACLs.+ staging_path = cache_path.with_name(f"{cache_path.name}.{uuid4().hex}.tmp.npz")+ staging_file = staging_path.open("xb")+ # Only clean up after exclusive creation succeeds: a collision+ # must never remove another writer's staging file.+ try:+ with staging_file:+ np.savez(staging_file, embeddings=embeddings, fingerprint=np.str_(fingerprint))+ # Windows requires the staging handle to be closed first.+ os.replace(staging_path, cache_path)+ finally:+ staging_path.unlink(missing_ok=True)except Exception:# With the exception, not just the path. The caller caches the# matrix in RAM either way, so a write failure costs# nothing until the next restart and is invisible until someone- # goes looking at startup times. The `.tmp` bug above survived- # because this line said only that something had gone wrong,- # never what — the FileNotFoundError it swallowed names the- # missing staging file outright.+ # goes looking at startup times. A past bug left the cache never+ # reaching disk, unnoticed because this warning said only that+ # something had failed, never what.self._invoker.services.logger.warning(f"Could not write cluster vocabulary cache to {cache_path}", exc_info=True)diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex c85641b113..d698ee152d 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1,9 +1,12 @@"""Tests for the image index worker service, using an injected fake encoder (no models/GPU)."""import inspect+import os+import statimport threadingimport timeimport weakref+from contextlib import nullcontextfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Callable@@ -3228,6 +3231,146 @@ def test_a_failed_cache_write_says_what_went_wrong(tmp_path, monkeypatch: pytestassert service._vocab_cache is not None+def test_overlapping_vocabulary_writers_cannot_modify_a_published_cache(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # Separate services model processes sharing a directory. Their PID-based+ # staging names collide even though their in-process locks are independent.+ first_matrix = np.arange(3 * DIM, dtype=EMBEDDING_DTYPE).reshape(3, DIM)+ second_matrix = -first_matrix+ first = _vocab_build_service(tmp_path, monkeypatch, first_matrix)+ cache_path = tmp_path / f"cluster_vocab_{MODEL_ID.replace(':', '_')[:24]}.npz"+ opened = threading.Event()+ second_published = threading.Event()+ first_written = threading.Event()+ finish_first = threading.Event()+ errors: list[BaseException] = []+ save = np.savez++ def _save(file, **arrays) -> None:+ if threading.current_thread() is not writer:+ save(file, **arrays)+ return+ # Keep the actual handle open across the other writer's publication.+ # Accept either np.savez's path or file interface, without pinning the+ # staging-name implementation. Windows refuses to rename a shared open+ # path; POSIX publishes an inode that the first writer can still alter.+ context = open(file, "wb") if isinstance(file, (str, Path)) else nullcontext(file)+ with context as handle:+ opened.set()+ # Production swallows exceptions raised here, so record them.+ try:+ assert second_published.wait(10), "The second writer did not finish"+ save(handle, **arrays)+ handle.flush()+ first_written.set()+ assert finish_first.wait(10), "The first writer was not released"+ except AssertionError as error:+ errors.append(error)+ raise++ def _build_first() -> None:+ try:+ first._build_vocab_embeddings()+ except BaseException as error:+ errors.append(error)++ monkeypatch.setattr(image_index_default.np, "savez", _save)+ writer = threading.Thread(target=_build_first)+ writer.start()+ try:+ assert opened.wait(10), "The first writer did not open its staging file"+ second = _vocab_build_service(tmp_path, monkeypatch, second_matrix)+ second._build_vocab_embeddings()+ assert cache_path.exists(), "A concurrent writer could not publish its cache"+ with np.load(cache_path, allow_pickle=False) as cached:+ assert np.array_equal(cached["embeddings"], second_matrix)+ published = cache_path.read_bytes()+ second_published.set()+ assert first_written.wait(10), "The first writer did not finish serialization"+ assert cache_path.read_bytes() == published, "An unpublished writer altered the live cache"+ finally:+ second_published.set()+ finish_first.set()+ writer.join(timeout=10)++ assert not writer.is_alive()+ assert not errors+ with np.load(cache_path, allow_pickle=False) as cached:+ assert np.array_equal(cached["embeddings"], first_matrix)+ assert sorted(tmp_path.iterdir()) == [cache_path]++[email protected]("existing_cache", [False, True], ids=["first-build", "replacement"])[email protected]("failure", ["serialization", "publication"])+def test_failed_vocabulary_publication_cleans_only_its_staging_file(+ tmp_path, monkeypatch: pytest.MonkeyPatch, existing_cache: bool, failure: str+) -> None:+ matrix = np.arange(3 * DIM, dtype=EMBEDDING_DTYPE).reshape(3, DIM)+ service = _vocab_build_service(tmp_path, monkeypatch, matrix)+ cache_path = tmp_path / f"cluster_vocab_{MODEL_ID.replace(':', '_')[:24]}.npz"+ previous: bytes | None = None+ if existing_cache:+ np.savez(cache_path, embeddings=-matrix, fingerprint=np.str_("older vocabulary"))+ previous = cache_path.read_bytes()+ # Another writer's staging file must not be swept on failure.+ other_staging = tmp_path / f"{cache_path.name}.other.tmp.npz"+ other_staging.write_bytes(b"another writer's incomplete cache")+ recorded: list[tuple[str, object]] = []+ service._invoker.services.logger = SimpleNamespace( # type: ignore[union-attr]+ warning=lambda message, exc_info=False: recorded.append((str(message), exc_info))+ )++ def _fail_save(file, **arrays) -> None:+ if isinstance(file, (str, Path)):+ Path(file).write_bytes(b"partial archive")+ else:+ file.write(b"partial archive")+ raise OSError("simulated serialization failure")++ def _fail_replace(src: object, dst: object) -> None:+ raise PermissionError("simulated publication failure")++ if failure == "serialization":+ monkeypatch.setattr(image_index_default.np, "savez", _fail_save)+ else:+ monkeypatch.setattr(image_index_default.os, "replace", _fail_replace)+ service._build_vocab_embeddings()++ assert service._vocab_cache is not None+ assert service._vocab_failure is None+ vocabulary, cached_matrix = service._vocab_cache+ assert vocabulary == ["a cat", "a dog", "a car"]+ assert np.array_equal(cached_matrix, matrix)+ assert len(recorded) == 1+ assert "Could not write cluster vocabulary cache" in recorded[0][0]+ assert recorded[0][1] is True+ assert other_staging.read_bytes() == b"another writer's incomplete cache"+ if previous is not None:+ assert cache_path.read_bytes() == previous+ else:+ assert not cache_path.exists()+ expected_files = {other_staging}+ if existing_cache:+ expected_files.add(cache_path)+ assert set(tmp_path.iterdir()) == expected_files++[email protected](os.name != "posix", reason="POSIX file modes are not supported on this platform")+def test_vocabulary_cache_uses_normal_file_mode(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ matrix = np.arange(3 * DIM, dtype=EMBEDDING_DTYPE).reshape(3, DIM)+ service = _vocab_build_service(tmp_path, monkeypatch, matrix)+ reference_path = tmp_path / "reference.npz"+ np.savez(reference_path, embeddings=matrix, fingerprint=np.str_("reference vocabulary"))++ service._build_vocab_embeddings()++ cache_path = tmp_path / f"cluster_vocab_{MODEL_ID.replace(':', '_')[:24]}.npz"+ assert stat.S_IMODE(cache_path.stat().st_mode) == stat.S_IMODE(reference_path.stat().st_mode)+ with np.load(cache_path, allow_pickle=False) as cached:+ assert np.array_equal(cached["embeddings"], matrix)++def test_batch_normalization_zeroes_a_degenerate_row_instead_of_failing(service: ImageIndexService) -> None:# One bad row out of ~11,700 must not discard the whole vocabulary build:# that raises past the endpoint's handling as a 500 and, nothing having been