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(image-index): retire obsolete vocabulary caches (#10013)

Nianze Wu708890242cd9
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index a9614b1aa3..aa87ae5b15 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -542,21 +542,16 @@ class ImageIndexService(ImageIndexServiceBase):
bundled_keys = {phrase.casefold() for phrase in bundled}
custom = [term for term in custom if term.casefold() not in bundled_keys]
- # The model hash contains ':' (e.g. 'blake3:...'), illegal in
- # Windows filenames.
- model_tag = self._model_id.replace(":", "_")[:24]
- cache_dir = self._invoker.services.configuration.db_path.parent
+ bundled_path, custom_path = self._vocab_cache_paths()
# Two cache tiers: the bundled vocabulary (~1700 phrases, minutes
# to embed, effectively immutable) and the custom terms (a few
# hundred at most, seconds). Caching them separately means an edit
# to the custom list never pays the bundled tier's build again.
try:
- bundled_matrix = self._load_or_embed_phrases(bundled, cache_dir / f"cluster_vocab_{model_tag}.npz")
+ bundled_matrix = self._load_or_embed_phrases(bundled, bundled_path)
if custom:
- custom_matrix = self._load_or_embed_phrases(
- custom, cache_dir / f"cluster_vocab_custom_{model_tag}.npz"
- )
+ custom_matrix = self._load_or_embed_phrases(custom, custom_path)
self._vocab_cache = (bundled + custom, np.concatenate([bundled_matrix, custom_matrix]))
else:
self._vocab_cache = (bundled, bundled_matrix)
@@ -1037,6 +1032,7 @@ class ImageIndexService(ImageIndexServiceBase):
discarded = invoker.services.image_index_records.delete_embeddings_for_other_models(self._model_id)
if discarded:
invoker.services.logger.info(f"Discarded {discarded} embeddings computed by a previously-configured model")
+ self._prune_vocab_caches()
if not self._callbacks_registered:
invoker.services.images.on_changed(self._on_image_changed)
@@ -1052,6 +1048,37 @@ class ImageIndexService(ImageIndexServiceBase):
self._worker = threading.Thread(target=self._worker_loop, name="image_index_worker", daemon=True)
self._worker.start()
+ def _vocab_cache_paths(self) -> tuple[Path, Path]:
+ """The current model's bundled and custom vocabulary archives, as written and as kept by pruning."""
+ assert self._invoker is not None and self._model_id is not None
+ cache_dir = self._invoker.services.configuration.db_path.parent
+ # The model hash contains ':' (e.g. 'blake3:...'), illegal in Windows filenames.
+ model_tag = self._model_id.replace(":", "_")[:24]
+ return cache_dir / f"cluster_vocab_{model_tag}.npz", cache_dir / f"cluster_vocab_custom_{model_tag}.npz"
+
+ def _prune_vocab_caches(self) -> None:
+ """Retire obsolete vocabulary archives under the index's one-current-model policy."""
+ assert self._invoker is not None
+ current = set(self._vocab_cache_paths())
+ cache_dir = self._invoker.services.configuration.db_path.parent
+ try:
+ for cache_path in cache_dir.glob("cluster_vocab_*.npz"):
+ # Both writer generations use .tmp.npz; these may still be open
+ # in another instance and are not obsolete published archives.
+ if cache_path in current or cache_path.name.lower().endswith(".tmp.npz"):
+ continue
+ try:
+ if cache_path.is_symlink() or not cache_path.is_file():
+ continue
+ cache_path.unlink(missing_ok=True)
+ except OSError:
+ self._invoker.services.logger.warning(
+ f"Could not remove stale cluster vocabulary cache at {cache_path}", exc_info=True
+ )
+ except OSError:
+ # Cache maintenance must not prevent startup or a late encoder swap.
+ self._invoker.services.logger.warning("Could not prune obsolete cluster vocabulary caches", exc_info=True)
+
def stop(self, invoker: Optional["Invoker"] = None) -> None:
# Under the lock so a map request cannot be midway through starting a
# worker that this stop would then never see.
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index aa0a90023e..c85641b113 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -99,6 +99,13 @@ def db() -> Database:
return create_mock_sqlite_database(config=config, logger=InvokeAILogger.get_logger())
[email protected](autouse=True)
+def isolate_index_storage(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Migrations and cache retirement touch files even when the records database is in-memory.
+ monkeypatch.setattr(InvokeAIAppConfig, "root_path", property(lambda self: tmp_path))
+ monkeypatch.setattr(InvokeAIAppConfig, "db_path", property(lambda self: tmp_path / "invokeai.db"))
+
+
@pytest.fixture
def image_records(db: Database) -> ImageRecordStorage:
return ImageRecordStorage(db)
@@ -1284,6 +1291,163 @@ def test_disabled_service_does_not_discard_embeddings(
service.stop()
[email protected]("late_activation", [False, True], ids=["startup", "late-activation"])
+def test_activation_prunes_only_obsolete_vocabulary_archives(
+ tmp_path: Path,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ late_activation: bool,
+) -> None:
+ model_id = "blake3:613228c1fd904fb8e0123456789abcdef"
+ # Literal expected writer names catch using the full hash instead of its truncated tag.
+ kept_names = ["cluster_vocab_blake3_613228c1fd904fb8e.npz", "cluster_vocab_custom_blake3_613228c1fd904fb8e.npz"]
+ stale_names = ["cluster_vocab_old.npz", "cluster_vocab_custom_old.npz"]
+ other_names = [
+ "cluster_vocab_old.npz123.tmp.npz",
+ "cluster_vocab_old.npz.random.tmp.npz",
+ "cluster_vocab_custom_old.npz.random.tmp.npz",
+ "cluster_vocab_old.npz.uppercase.TMP.NPZ",
+ "cluster_vocab_old.npz.bak",
+ "other-cache.npz",
+ "invokeai.db",
+ ]
+ preserved = {}
+ for name in kept_names + stale_names + other_names:
+ path = tmp_path / name
+ path.write_bytes(name.encode())
+ if name not in stale_names:
+ preserved[path] = path.read_bytes()
+ directory = tmp_path / "cluster_vocab_directory.npz"
+ directory.mkdir()
+ nested_cache = directory / "cluster_vocab_old.npz"
+ nested_cache.write_bytes(b"not owned by this database directory")
+
+ if late_activation:
+ service = ImageIndexService()
+ resolved = SimpleNamespace(key="encoder-key", hash=model_id)
+ model_manager = SimpleNamespace(
+ store=SimpleNamespace(search_by_attr=lambda **kwargs: []), load=_NO_MODEL_CACHES
+ )
+ with patch.object(service, "_resolve_model_config", side_effect=[None, resolved]):
+ try:
+ service.start(_make_invoker(images_service, index_records, model_manager=model_manager))
+ assert all((tmp_path / name).exists() for name in stale_names)
+ service._last_activation_attempt = 0
+ assert service.try_activate()
+ assert service._worker is not None and service._worker.is_alive()
+ assert all(not (tmp_path / name).exists() for name in stale_names)
+ finally:
+ service.stop()
+ else:
+ service = ImageIndexService(encode_fn=_fake_encode, model_id=model_id)
+ try:
+ service.start(_make_invoker(images_service, index_records))
+ assert service._worker is not None and service._worker.is_alive()
+ assert all(not (tmp_path / name).exists() for name in stale_names)
+ finally:
+ service.stop()
+
+ assert all(path.read_bytes() == contents for path, contents in preserved.items())
+ assert nested_cache.read_bytes() == b"not owned by this database directory"
+
+
+def test_vocabulary_pruning_continues_after_one_file_cannot_be_deleted(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+) -> None:
+ caches = {tmp_path / "cluster_vocab_old.npz", tmp_path / "cluster_vocab_custom_old.npz"}
+ for cache in caches:
+ cache.write_bytes(b"obsolete archive")
+ attempted: list[Path] = []
+ original_unlink = Path.unlink
+
+ def unlink(path: Path, *args, **kwargs) -> None:
+ if path in caches:
+ attempted.append(path)
+ if len(attempted) == 1:
+ raise PermissionError("simulated cache sharing violation")
+ original_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", unlink)
+ _save_image(image_records, "new.png")
+ service.start(_make_invoker(images_service, index_records))
+ _wait_until(lambda: index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"))
+
+ assert len(attempted) == 2
+ assert attempted[0].read_bytes() == b"obsolete archive"
+ assert not attempted[1].exists()
+ assert "Could not remove stale cluster vocabulary cache" in caplog.text
+
+
+def test_vocabulary_pruning_scan_failure_does_not_prevent_indexing(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+) -> None:
+ original_glob = Path.glob
+
+ def glob(path: Path, pattern: str, *args, **kwargs):
+ if path == tmp_path and pattern == "cluster_vocab_*.npz":
+ raise PermissionError("simulated unreadable cache directory")
+ return original_glob(path, pattern, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "glob", glob)
+ _save_image(image_records, "new.png")
+ service.start(_make_invoker(images_service, index_records))
+ _wait_until(lambda: index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"))
+
+ assert "Could not prune obsolete cluster vocabulary caches" in caplog.text
+
+
[email protected]("enabled", [False, True], ids=["disabled", "missing-model"])
+def test_inactive_service_preserves_vocabulary_archives(
+ tmp_path: Path,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ enabled: bool,
+) -> None:
+ path = tmp_path / "cluster_vocab_old.npz"
+ path.write_bytes(b"preserved until a replacement model is active")
+ service = ImageIndexService()
+ model_manager = SimpleNamespace(store=SimpleNamespace(search_by_attr=lambda **kwargs: []), load=_NO_MODEL_CACHES)
+ with patch.object(service, "_resolve_model_config", return_value=None):
+ try:
+ service.start(_make_invoker(images_service, index_records, enabled=enabled, model_manager=model_manager))
+ assert path.read_bytes() == b"preserved until a replacement model is active"
+ assert service._worker is None
+ finally:
+ service.stop()
+
+
+def test_vocabulary_pruning_preserves_symlinks_and_their_targets(
+ tmp_path: Path,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+) -> None:
+ target = tmp_path / "unrelated.npz"
+ target.write_bytes(b"not a service-owned archive")
+ link = tmp_path / "cluster_vocab_link.npz"
+ try:
+ link.symlink_to(target)
+ except OSError as error:
+ pytest.skip(f"Host cannot create symlinks: {error}")
+
+ service.start(_make_invoker(images_service, index_records))
+
+ assert link.is_symlink()
+ assert target.read_bytes() == b"not a service-owned archive"
+
+
def test_worker_waits_for_generation_to_finish_when_not_on_cpu(
image_records: ImageRecordStorage,
images_service: ImageService,