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
feat(api): background image embedding indexer service
Lincoln Stein16f528fb007b
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 2c183f5540..8a09df5a37 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -798,6 +798,50 @@"type": "<class 'bool'>","validation": {}},+ {+ "category": "IMAGE INDEX",+ "default": false,+ "description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",+ "env_var": "INVOKEAI_IMAGE_INDEX_ENABLED",+ "literal_values": [],+ "name": "image_index_enabled",+ "required": false,+ "type": "<class 'bool'>",+ "validation": {}+ },+ {+ "category": "IMAGE INDEX",+ "default": "clip-vit-large-patch14",+ "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.",+ "env_var": "INVOKEAI_IMAGE_INDEX_MODEL",+ "literal_values": [],+ "name": "image_index_model",+ "required": false,+ "type": "<class 'str'>",+ "validation": {}+ },+ {+ "category": "IMAGE INDEX",+ "default": null,+ "description": "Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.",+ "env_var": "INVOKEAI_IMAGE_INDEX_DEVICE",+ "literal_values": [],+ "name": "image_index_device",+ "required": false,+ "type": "typing.Optional[str]",+ "validation": {}+ },+ {+ "category": "IMAGE INDEX",+ "default": 8,+ "description": "Number of images embedded per batch by the image index worker.",+ "env_var": "INVOKEAI_IMAGE_INDEX_BATCH_SIZE",+ "literal_values": [],+ "name": "image_index_batch_size",+ "required": false,+ "type": "<class 'int'>",+ "validation": {}+ },{"category": "EXTERNAL PROVIDERS","default": null,diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.pyindex 4b271ad7a6..fc3f66a30f 100644--- a/invokeai/app/api/dependencies.py+++ b/invokeai/app/api/dependencies.py@@ -27,6 +27,7 @@ from invokeai.app.services.external_generation.providers import (from invokeai.app.services.external_generation.startup import sync_configured_external_starter_modelsfrom invokeai.app.services.gallery.gallery_default import SqliteGalleryServicefrom invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage+from invokeai.app.services.image_index.image_index_default import ImageIndexService, warm_up_attentionfrom invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_moves.image_moves_default import ImageMoveServicefrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage@@ -216,6 +217,7 @@ class ApiDependencies:project_records = ProjectRecordsSqlite(db=db)users = UserService(db=db)image_index_records = ImageIndexRecordsSqlite(db=db)+ image_index = ImageIndexService()services = InvocationServices(board_image_records=board_image_records,@@ -259,8 +261,15 @@ class ApiDependencies:board_video_records=board_video_records,gallery=gallery,image_index_records=image_index_records,+ image_index=image_index,)+ # Constructing the Invoker starts every service, including the session+ # processor thread (which may immediately resume queue items that were+ # pending at shutdown). Trigger torch attention's lazy, non-thread-safe+ # kernel init while the process is still single-threaded.+ warm_up_attention(config, logger)+ApiDependencies.invoker = Invoker(services)configured_external_providers = {provider_iddiff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.pyindex ca5667d59a..5a8245b5f9 100644--- a/invokeai/app/api/sockets.py+++ b/invokeai/app/api/sockets.py@@ -22,6 +22,9 @@ from invokeai.app.services.events.events_common import (DownloadProgressEvent,DownloadStartedEvent,FastAPIEvent,+ ImageIndexEventBase,+ ImageIndexStatusEvent,+ ImageIndexUpdatedEvent,InvocationCompleteEvent,InvocationErrorEvent,InvocationProgressEvent,@@ -105,6 +108,8 @@ MODEL_EVENTS = {BULK_DOWNLOAD_EVENTS = {BulkDownloadStartedEvent, BulkDownloadCompleteEvent, BulkDownloadErrorEvent}WORKFLOW_EVENTS = {WorkflowCreatedEvent, WorkflowUpdatedEvent, WorkflowDeletedEvent}+IMAGE_INDEX_EVENTS = {ImageIndexStatusEvent, ImageIndexUpdatedEvent}+MODEL_INSTALL_EVENTS = (ModelInstallDownloadStartedEvent,ModelInstallDownloadProgressEvent,@@ -154,6 +159,7 @@ class SocketIO:register_events(BULK_DOWNLOAD_EVENTS, self._handle_bulk_image_download_event)register_events(LLM_TASK_EVENTS, self._handle_llm_task_event)register_events(WORKFLOW_EVENTS, self._handle_workflow_event)+ register_events(IMAGE_INDEX_EVENTS, self._handle_image_index_event)async def _handle_connect(self, sid: str, environ: dict, auth: dict | None) -> bool:"""Handle socket connection and authenticate the user.@@ -639,6 +645,20 @@ class SocketIO:payload = event_data.model_dump(mode="json")await self._sio.emit(event=event_name, data=payload, room=[user_room, "admin"])+ async def _handle_image_index_event(self, event: FastAPIEvent[ImageIndexEventBase]) -> None:+ event_name, event_data = event+ # The counts-free per-user poke goes to the owning user's room only —+ # admins learn the same thing from the status event below.+ if isinstance(event_data, ImageIndexUpdatedEvent):+ await self._sio.emit(+ event=event_name, data=event_data.model_dump(mode="json"), room=f"user:{event_data.user_id}"+ )+ return+ # Index counts aggregate over ALL users' images; watching them tick is+ # a side channel on other users' generation activity, so they go to+ # admins only (single-user mode's sole user is an admin).+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")+async def _handle_bulk_image_download_event(self, event: FastAPIEvent[BulkDownloadEventBase]) -> None:event_name, event_data = event# Route to user-specific + admin rooms so that other authenticateddiff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex ae1e38e0cc..a1c682afa9 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -131,6 +131,10 @@ class InvokeAIAppConfig(BaseSettings):allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.+ image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.+ image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.+ image_index_batch_size: Number of images embedded per batch by the image index worker.external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.external_gemini_api_key: API key for Gemini image generation.@@ -245,6 +249,12 @@ class InvokeAIAppConfig(BaseSettings):multiuser: bool = Field(default=False, description="Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.")strict_password_checking: bool = Field(default=False, description="Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.")+ # IMAGE INDEX+ image_index_enabled: bool = Field(default=False, description="Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.")+ image_index_model: str = Field(default="clip-vit-large-patch14", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.")+ image_index_device: Optional[str] = Field(default=None, description="Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.")+ image_index_batch_size: int = Field(default=8, gt=0, description="Number of images embedded per batch by the image index worker.")+# EXTERNAL PROVIDERSexternal_alibabacloud_api_key: Optional[str] = Field(default=None, description="API key for Alibaba Cloud DashScope image generation.")external_alibabacloud_base_url: Optional[str] = Field(diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.pyindex 5999258f6c..7bb65d6e1d 100644--- a/invokeai/app/services/events/events_base.py+++ b/invokeai/app/services/events/events_base.py@@ -15,6 +15,8 @@ from invokeai.app.services.events.events_common import (DownloadProgressEvent,DownloadStartedEvent,EventBase,+ ImageIndexStatusEvent,+ ImageIndexUpdatedEvent,InvocationCompleteEvent,InvocationErrorEvent,InvocationProgressEvent,@@ -316,3 +318,15 @@ class EventServiceBase:)# endregion++ # region Image index++ def emit_image_index_status(self, total: int, embedded: int, pending: int) -> None:+ """Emitted when the image embedding index makes progress"""+ self.dispatch(ImageIndexStatusEvent.build(total=total, embedded=embedded, pending=pending))++ def emit_image_index_updated(self, user_id: str) -> None:+ """Emitted to one user when their images were just (re)embedded"""+ self.dispatch(ImageIndexUpdatedEvent.build(user_id=user_id))++ # endregiondiff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.pyindex c831f32e60..50e80620ee 100644--- a/invokeai/app/services/events/events_common.py+++ b/invokeai/app/services/events/events_common.py@@ -869,3 +869,42 @@ class RecallParametersUpdatedEvent(QueueEventBase):@classmethoddef build(cls, queue_id: str, user_id: str, parameters: dict[str, Any]) -> "RecallParametersUpdatedEvent":return cls(queue_id=queue_id, user_id=user_id, parameters=parameters)+++class ImageIndexEventBase(EventBase):+ """Base class for image index events"""+++@payload_schema.register+class ImageIndexStatusEvent(ImageIndexEventBase):+ """Event model for image_index_status"""++ __event_name__ = "image_index_status"++ total: int = Field(description="Number of gallery images eligible for embedding")+ embedded: int = Field(description="Number of eligible images that have an embedding")+ pending: int = Field(description="Number of eligible images awaiting embedding")++ @classmethod+ def build(cls, total: int, embedded: int, pending: int) -> "ImageIndexStatusEvent":+ return cls(total=total, embedded=embedded, pending=pending)+++@payload_schema.register+class ImageIndexUpdatedEvent(ImageIndexEventBase):+ """Event model for image_index_updated.++ A counts-free poke to one user whose images were just (re)embedded, so+ their client can refresh views built on the index. Kept separate from+ ImageIndexStatusEvent because the counts aggregate every user's images+ and are therefore admin-only, while this event is safe to route to the+ owning user's room.+ """++ __event_name__ = "image_index_updated"++ user_id: str = Field(description="The user whose images were embedded")++ @classmethod+ def build(cls, user_id: str) -> "ImageIndexUpdatedEvent":+ return cls(user_id=user_id)diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pynew file mode 100644index 0000000000..453c9a2bfb--- /dev/null+++ b/invokeai/app/services/image_index/image_index_base.py@@ -0,0 +1,24 @@+from abc import ABC, abstractmethod++from invokeai.app.services.image_index.image_index_common import ImageIndexStatus+++class ImageIndexServiceBase(ABC):+ """Background service that keeps the semantic image index up to date.++ When enabled and an embedding model is available, the service embeds every+ eligible gallery image (non-intermediate, `general` category) on a worker+ thread: a backfill pass covers images that existed before the service+ started, and image-service callbacks cover images created afterwards.+ """++ @property+ @abstractmethod+ def model_id(self) -> str | None:+ """Content hash of the active embedding model, or None if the indexer is not running."""+ pass++ @abstractmethod+ def get_status(self) -> ImageIndexStatus | None:+ """Get index progress counts, or None if the indexer is not running."""+ passdiff --git a/invokeai/app/services/image_index/image_index_common.py b/invokeai/app/services/image_index/image_index_common.pyindex fc18607e70..44b6b6b6dd 100644--- a/invokeai/app/services/image_index/image_index_common.py+++ b/invokeai/app/services/image_index/image_index_common.py@@ -11,10 +11,17 @@ class ImageIndexStatus(BaseModel):total: int = Field(description="Number of gallery images eligible for indexing")embedded: int = Field(description="Number of eligible images that have an embedding")+ failed: int = Field(+ default=0,+ description="Eligible images that repeatedly failed to embed; excluded from pending so it can drain",+ )@propertydef pending(self) -> int:- return max(0, self.total - self.embedded)+ # Excluding failures matters: consumers treat pending == 0 as "the+ # index is settled", and a count that can never drain would wedge+ # them (and show an indexing spinner forever).+ return max(0, self.total - self.embedded - self.failed)class ProjectionRecord(BaseModel):diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pynew file mode 100644index 0000000000..201b8228c9--- /dev/null+++ b/invokeai/app/services/image_index/image_index_default.py@@ -0,0 +1,526 @@+import threading+from pathlib import Path+from queue import Empty, Queue+from typing import TYPE_CHECKING, Any, Callable, Optional++import numpy as np+import torch+from PIL import Image++from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase+from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, ImageIndexStatus+from invokeai.app.services.image_records.image_records_common import ImageCategory+from invokeai.app.services.images.images_common import ImageDTO+from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID+from invokeai.backend.model_manager.taxonomy import ModelType+from invokeai.backend.util.devices import TorchDevice++if TYPE_CHECKING:+ from logging import Logger++ from invokeai.app.services.config.config_default import InvokeAIAppConfig+ from invokeai.app.services.invoker import Invoker+ from invokeai.backend.model_manager.configs.factory import AnyModelConfig++# A batch of PIL images in, an (N, dim) float32 embedding matrix out.+EncodeFn = Callable[[list[Image.Image]], np.ndarray]++# How long the worker sleeps between generation-idle checks and empty-queue polls.+_POLL_SECONDS = 1.0++# An image is retried this many times (transient failures: OOM, file locks,+# model briefly unavailable) before being marked permanently failed.+_MAX_ATTEMPTS = 3+++def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:+ """Run one tiny scaled_dot_product_attention call while the process is still single-threaded.++ ROCm's AOTriton backend initializes its SDPA kernels lazily on the first+ call, and that init is not thread-safe: two threads making their first+ call concurrently can get a spurious "Accelerated SDPA only supports..."+ error or crash the process. The image index adds the first threads that+ run attention concurrently with the session processor, so its startup+ wiring calls this before any service thread exists (a warmup issued any+ later — e.g. from the service's own start() — could itself race a+ generation resumed from a queue that was non-empty at shutdown).+ """+ if not config.image_index_enabled:+ return+ try:+ device = (+ torch.device(config.image_index_device) if config.image_index_device else TorchDevice.choose_torch_device()+ )+ if device.type != "cuda":+ return+ query = torch.zeros((1, 1, 8, 8), device=device, dtype=torch.float16)+ torch.nn.functional.scaled_dot_product_attention(query, query, query)+ torch.cuda.synchronize(device)+ except Exception:+ logger.warning("Attention warm-up failed", exc_info=True)+++class ImageIndexService(ImageIndexServiceBase):+ """Embeds gallery images on a daemon worker thread.++ The image-service callbacks only enqueue work and set a status-dirty+ flag — they fire synchronously on the caller's thread and must never do+ I/O. All embedding and all status emission happens on the worker, which+ pauses while a generation is in progress unless it is configured to run+ on the CPU.+ """++ def __init__(self, encode_fn: Optional[EncodeFn] = None, model_id: Optional[str] = None) -> None:+ """Args:+ encode_fn: Test seam. When provided, it is used instead of loading the+ configured model, and `model_id` identifies the index it writes.+ model_id: Required when `encode_fn` is provided.+ """+ if (encode_fn is None) != (model_id is None):+ raise ValueError("encode_fn and model_id must be provided together")+ self._encode_fn_override = encode_fn+ self._model_id_override = model_id++ self._queue: Queue[str] = Queue()+ self._pending: set[str] = set()+ self._pending_lock = threading.Lock()+ # Per-image failure counts; after _MAX_ATTEMPTS the name moves to+ # _failed, which is excluded from backfill so a bad file cannot make+ # the backfill loop spin forever. Transient failures get retried.+ self._attempts: dict[str, int] = {}+ self._failed: set[str] = set()+ self._stop_event = threading.Event()+ self._backfill_pending = threading.Event()+ # Set by the image-service callbacks when counts changed; the worker+ # (the only emitter) turns it into one status event per sweep.+ self._status_dirty = threading.Event()+ # Owners of freshly embedded images, awaiting a per-user poke once+ # the index goes quiescent. Worker-thread only — no locking.+ self._pending_pokes: set[str] = set()+ self._worker: Optional[threading.Thread] = None++ self._invoker: Optional["Invoker"] = None+ self._model_config: Optional["AnyModelConfig"] = None+ self._model_id: Optional[str] = None+ self._encode_fn: Optional[EncodeFn] = None+ # RAM-resident model used only in CPU mode; see _encode_with_model.+ self._cpu_model: Optional[Any] = None+ self._processor: Optional[Any] = None++ @property+ def model_id(self) -> str | None:+ return self._model_id++ def get_status(self) -> ImageIndexStatus | None:+ if self._invoker is None or self._model_id is None:+ return None+ status = self._invoker.services.image_index_records.count_index_status(self._model_id)+ return status.model_copy(update={"failed": len(self._failed)})++ def start(self, invoker: "Invoker") -> None:+ self._invoker = invoker+ config = invoker.services.configuration+ if not config.image_index_enabled:+ return+ if self._worker is not None and self._worker.is_alive():+ # A second start would register duplicate image callbacks and race+ # a prior worker that outlived its stop() join.+ invoker.services.logger.warning("Image index service started twice; ignoring the second start")+ return++ if self._encode_fn_override is not None:+ self._encode_fn = self._encode_fn_override+ self._model_id = self._model_id_override+ else:+ model_config = self._resolve_model_config(config.image_index_model)+ if model_config is None:+ invoker.services.logger.warning(self._model_not_installed_message(config.image_index_model))+ return+ self._model_config = model_config+ self._model_id = model_config.hash+ self._encode_fn = self._encode_with_model++ discarded = invoker.services.image_index_records.delete_embeddings_for_other_models(self._model_id)+ if discarded:+ invoker.services.logger.info(+ f"Discarded {discarded} image embeddings computed by a previously-configured model"+ )++ invoker.services.images.on_changed(self._on_image_changed)+ invoker.services.images.on_deleted(self._on_image_deleted)++ self._backfill_pending.set()+ self._stop_event.clear()+ self._worker = threading.Thread(target=self._worker_loop, name="image_index_worker", daemon=True)+ self._worker.start()++ def stop(self, invoker: Optional["Invoker"] = None) -> None:+ self._stop_event.set()+ if self._worker is not None and self._worker.is_alive():+ self._worker.join(timeout=10)+ if self._worker.is_alive() and self._invoker is not None:+ self._invoker.services.logger.warning(+ "Image index worker did not stop within 10s (likely mid-encode); abandoning daemon thread"+ )++ # --- Image service callbacks (caller's thread — enqueue and flag only, never I/O) ---++ def _on_image_changed(self, image_dto: ImageDTO) -> None:+ if image_dto.is_intermediate or image_dto.image_category != ImageCategory.GENERAL:+ # The image may have just LEFT eligibility (e.g. adopted as a+ # canvas asset). Drop any failure bookkeeping so a name no longer+ # counted in the totals cannot skew `failed` (and thus `pending`)+ # for the rest of the process. Flag only when something was+ # actually forgotten — this branch also fires for every+ # intermediate save during generation, which must stay silent.+ if image_dto.image_name in self._failed:+ self._failed.discard(image_dto.image_name)+ self._attempts.pop(image_dto.image_name, None)+ self._status_dirty.set()+ return+ with self._pending_lock:+ if image_dto.image_name in self._pending:+ return+ self._pending.add(image_dto.image_name)+ # Flagged before the enqueue so the worker reports the image as+ # pending before it starts (and certainly before it finishes) the+ # embed. The worker does the emit: callbacks stay free of DB reads+ # (which could block the generation thread behind the worker's own+ # long transactions), and single-threaded emission means events can+ # never be dispatched with out-of-order counts.+ self._status_dirty.set()+ self._queue.put(image_dto.image_name)++ def _on_image_deleted(self, image_name: str) -> None:+ # The DB row is removed by the images FK cascade; just forget local state.+ with self._pending_lock:+ self._pending.discard(image_name)+ self._failed.discard(image_name)+ self._attempts.pop(image_name, None)+ # A deletion gives the worker nothing to embed, so this flag is the+ # only signal clients get that the index shrank; the worker notices+ # within its poll interval. Bulk deletes coalesce into one emit.+ self._status_dirty.set()++ # --- Worker ---++ def _worker_loop(self) -> None:+ assert self._invoker is not None+ logger = self._invoker.services.logger+ while not self._stop_event.is_set():+ try:+ batch = self._next_batch()+ if self._status_dirty.is_set():+ # The worker is the only emitter, so events are totally+ # ordered by one thread and can never carry out-of-order+ # counts. Checked after _next_batch so a just-enqueued+ # image is reported pending before its embed runs.+ self._status_dirty.clear()+ try:+ self._emit_status()+ except Exception:+ # For deletions this flag is the only signal clients+ # get, so a failed emit must not consume it. Cleared+ # before emitting (not after) so a set arriving+ # mid-emit is never lost either.+ self._status_dirty.set()+ raise+ if batch is None:+ if self._pending_pokes and not self._backfill_pending.is_set():+ # The index just went quiescent: poke each owner whose+ # images were embedded since the last flush. Deferred+ # to quiescence so a long backfill does not trigger a+ # refetch (and possibly a projection recompute) per+ # batch. Cleared only after all emits, so a raise+ # retries on the next pass (duplicate pokes are cheap).+ for user_id in sorted(self._pending_pokes):+ self._invoker.services.events.emit_image_index_updated(user_id=user_id)+ self._pending_pokes.clear()+ continue+ self._wait_for_idle_generation()+ if self._stop_event.is_set():+ break+ ok = self._process_batch(batch)+ self._emit_status()+ if not ok:+ # Re-sweep so queue-sourced images that failed+ # transiently are retried to _MAX_ATTEMPTS instead of+ # lingering unembedded until the next restart.+ self._backfill_pending.set()+ # Back off after a failed batch so a systemic failure+ # (broken model, OOM loop) cannot spin hot through the+ # backlog re-fetching the same names.+ self._stop_event.wait(_POLL_SECONDS)+ except Exception:+ logger.exception("Unexpected error in the image index worker")+ # Whatever was in flight may have skipped its accounting, so+ # re-sweep for anything left unembedded and re-emit counts —+ # otherwise an image dropped here lingers with pending stuck+ # above zero until the next restart.+ self._backfill_pending.set()+ self._status_dirty.set()+ self._stop_event.wait(_POLL_SECONDS)++ def _next_batch(self) -> Optional[list[str]]:+ """Get the next batch of image names, preferring backfill work.++ Returns None when there is nothing to do right now.+ """+ assert self._invoker is not None+ batch_size = self._invoker.services.configuration.image_index_batch_size++ if self._backfill_pending.is_set():+ assert self._model_id is not None+ # Over-fetch by the failed count so permanently-failing images+ # cannot occlude the rest of the backlog.+ candidates = self._invoker.services.image_index_records.list_unembedded_image_names(+ self._model_id, limit=batch_size + len(self._failed)+ )+ batch = [name for name in candidates if name not in self._failed][:batch_size]+ if batch:+ return batch+ self._backfill_pending.clear()+ self._emit_status()++ try:+ first = self._queue.get(timeout=_POLL_SECONDS)+ except Empty:+ return None+ batch = [first]+ while len(batch) < batch_size:+ try:+ batch.append(self._queue.get_nowait())+ except Empty:+ break+ return batch++ def _process_batch(self, image_names: list[str]) -> bool:+ """Embed one batch. Returns False when anything in it failed."""+ assert self._invoker is not None+ assert self._encode_fn is not None+ assert self._model_id is not None+ logger = self._invoker.services.logger++ try:+ images: list[Image.Image] = []+ loaded_names: list[str] = []+ for name in image_names:+ try:+ images.append(self._invoker.services.images.get_pil_image(name).convert("RGB"))+ loaded_names.append(name)+ except Exception as e:+ logger.warning(f"Image index: could not load '{name}' ({e})")+ self._record_failure([name])++ if not loaded_names:+ return False++ try:+ embeddings = np.asarray(self._encode_fn(images), dtype=EMBEDDING_DTYPE)+ except Exception:+ logger.exception(f"Image index: failed to embed a batch of {len(loaded_names)} images")+ self._record_failure(loaded_names)+ return False++ if embeddings.ndim != 2 or embeddings.shape[0] != len(loaded_names):+ logger.error(f"Image index: encoder returned shape {embeddings.shape} for {len(loaded_names)} images")+ self._record_failure(loaded_names)+ return False++ # L2-normalize so cosine similarity is a plain dot product downstream.+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)+ norms[norms == 0] = 1.0+ embeddings = embeddings / norms++ stored: list[str] = []+ try:+ for name, embedding in zip(loaded_names, embeddings, strict=True):+ self._invoker.services.image_index_records.upsert_embedding(name, self._model_id, embedding)+ stored.append(name)+ self._attempts.pop(name, None)+ # An image that recovers (e.g. re-embedded after an+ # update) must stop counting against the failed total.+ self._failed.discard(name)+ except Exception:+ # A raise here (e.g. "database is locked") must still route+ # the unstored names through the failure path, or they linger+ # unembedded — with pending stuck above zero — until restart.+ logger.exception(f"Image index: failed to store embeddings for a batch of {len(loaded_names)} images")+ self._record_failure([name for name in loaded_names if name not in stored])+ return False+ finally:+ self._record_owner_pokes(stored)+ return len(loaded_names) == len(image_names)+ finally:+ # Always release the batch from the dedup set — a name stuck in+ # _pending can never be re-enqueued by callbacks.+ self._forget_pending(image_names)++ def _record_failure(self, image_names: list[str]) -> None:+ """Count a failure; move an image to the permanent-failure set only after repeated attempts."""+ for name in image_names:+ attempts = self._attempts.get(name, 0) + 1+ self._attempts[name] = attempts+ if attempts >= _MAX_ATTEMPTS:+ self._failed.add(name)++ def _forget_pending(self, image_names: list[str]) -> None:+ with self._pending_lock:+ self._pending.difference_update(image_names)++ def _wait_for_idle_generation(self) -> None:+ """Block until no generation is in progress, unless embedding on CPU.++ The embedding model shares the model cache (and therefore VRAM) with+ generation; embedding on the GPU mid-generation would thrash both.+ """+ assert self._invoker is not None+ if self._device().type == "cpu":+ return+ session_queue = self._invoker.services.session_queue+ if session_queue is None:+ return+ while not self._stop_event.is_set():+ try:+ status = session_queue.get_queue_status(DEFAULT_QUEUE_ID)+ except Exception:+ return+ if status.in_progress == 0:+ return+ self._stop_event.wait(_POLL_SECONDS)++ def _emit_status(self) -> None:+ assert self._invoker is not None+ status = self.get_status()+ if status is None:+ return+ self._invoker.services.events.emit_image_index_status(+ total=status.total, embedded=status.embedded, pending=status.pending+ )++ def _record_owner_pokes(self, image_names: list[str]) -> None:+ """Queue a per-user poke for each owner of freshly stored embeddings.++ The status event is admin-only (its counts aggregate every user's+ images), so without this, non-admin clients would never hear that+ their own generations reached the index. Owner lookups are DB reads,+ which is fine here: this runs on the worker thread.+ """+ assert self._invoker is not None+ for name in image_names:+ try:+ user_id = self._invoker.services.image_records.get_user_id(name)+ except Exception:+ continue+ if user_id:+ self._pending_pokes.add(user_id)++ # --- Model handling ---++ def _model_not_installed_message(self, model_name: str) -> str:+ assert self._invoker is not None+ # The starter catalog ships same-named models of different types (the+ # 'clip-vit-large-patch14' CLIP-L text encoder vs. the CLIP Vision+ # image encoder), so name the type mismatch when that is the problem.+ # search_by_attr drops the name filter for a falsy name and would+ # return every installed model.+ same_name = (+ self._invoker.services.model_manager.store.search_by_attr(model_name=model_name) if model_name else []+ )+ if same_name:+ types = ", ".join(sorted({config.type.value for config in same_name}))+ return (+ f"Image indexing is enabled, but the installed model named '{model_name}' is of type "+ f"'{types}', not a CLIP Vision or SigLIP image encoder. Install the image-encoder model of "+ "the same name (for the default, the 'CLIP ViT-L Image Encoder' starter model from source "+ "'InvokeAI/clip-vit-large-patch14'). The image index will not be updated."+ )+ return (+ f"Image indexing is enabled but the embedding model '{model_name}' is not installed "+ "(expected a CLIP Vision or SigLIP model). The image index will not be updated."+ )++ def _resolve_model_config(self, model_name: str) -> Optional["AnyModelConfig"]:+ assert self._invoker is not None+ store = self._invoker.services.model_manager.store+ for model_type in (ModelType.CLIPVision, ModelType.SigLIP):+ configs = store.search_by_attr(model_name=model_name, model_type=model_type)+ if len(configs) > 1:+ # Names are not unique. A different pick after a reinstall+ # changes the model hash and discards the whole index.+ self._invoker.services.logger.warning(+ f"Multiple {model_type.value} models named '{model_name}' are installed; "+ f"using '{configs[0].key}' for the image index"+ )+ if configs:+ return configs[0]+ return None++ def _device(self) -> torch.device:+ override = self._invoker.services.configuration.image_index_device if self._invoker else None+ if override:+ return torch.device(override)+ return TorchDevice.choose_torch_device()++ def _model_abs_path(self) -> Path:+ assert self._invoker is not None+ assert self._model_config is not None+ model_path = Path(self._model_config.path)+ if model_path.is_absolute():+ return model_path+ return self._invoker.services.configuration.models_path / model_path++ def _get_processor(self) -> Any:+ if self._processor is None:+ from transformers import CLIPImageProcessor, SiglipImageProcessor++ assert self._model_config is not None+ processor_cls = SiglipImageProcessor if self._model_config.type is ModelType.SigLIP else CLIPImageProcessor+ try:+ self._processor = processor_cls.from_pretrained(str(self._model_abs_path()), local_files_only=True)+ except OSError:+ # InvokeAI-published CLIP Vision model dirs ship no+ # preprocessor_config.json; IP-Adapter and FLUX construct the+ # processor with defaults for the same reason.+ self._processor = processor_cls()+ return self._processor++ def _embed(self, model: Any, images: list[Image.Image], device: torch.device) -> np.ndarray:+ from transformers import CLIPVisionModelWithProjection, SiglipVisionModel++ with torch.no_grad():+ inputs = self._get_processor()(images=images, return_tensors="pt")+ # The cached model may be fp16 on GPU; inputs must match its dtype.+ pixel_values = inputs["pixel_values"].to(device=device, dtype=next(model.parameters()).dtype)+ if isinstance(model, SiglipVisionModel):+ embeddings = model(pixel_values=pixel_values).pooler_output+ elif isinstance(model, CLIPVisionModelWithProjection):+ embeddings = model(pixel_values=pixel_values).image_embeds+ else:+ raise TypeError(f"Unsupported embedding model class: {type(model).__name__}")+ return embeddings.float().cpu().numpy()++ def _encode_with_model(self, images: list[Image.Image]) -> np.ndarray:+ assert self._invoker is not None+ assert self._model_config is not None++ if self._device().type == "cpu":+ # CPU mode exists to avoid touching the model cache (and VRAM) at+ # all, so it keeps its own RAM-resident copy of the model.+ if self._cpu_model is None:+ from transformers import CLIPVisionModelWithProjection, SiglipVisionModel++ model_path = str(self._model_abs_path())+ model_cls = (+ SiglipVisionModel if self._model_config.type is ModelType.SigLIP else CLIPVisionModelWithProjection+ )+ model = model_cls.from_pretrained(model_path, local_files_only=True)+ model.eval()+ self._cpu_model = model+ return self._embed(self._cpu_model, images, torch.device("cpu"))++ loaded = self._invoker.services.model_manager.load.load_model(self._model_config)+ with loaded.model_on_device() as (_, model):+ # The cache decides where the model actually lives; follow it.+ device = next(model.parameters()).device+ return self._embed(model, images, device)diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.pyindex b18ab112b6..a32ed3f32b 100644--- a/invokeai/app/services/invocation_services.py+++ b/invokeai/app/services/invocation_services.py@@ -27,6 +27,7 @@ if TYPE_CHECKING:from invokeai.app.services.external_generation.external_generation_base import ExternalGenerationServiceBasefrom invokeai.app.services.gallery.gallery_base import GalleryServiceABCfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBase+ from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBasefrom invokeai.app.services.image_index.image_index_records_base import ImageIndexRecordsBasefrom invokeai.app.services.image_moves.image_moves_default import ImageMoveServicefrom invokeai.app.services.image_records.image_records_base import ImageRecordStorageBase@@ -98,6 +99,7 @@ class InvocationServices:board_video_records: "BoardVideoRecordStorageBase",gallery: "GalleryServiceABC",image_index_records: "ImageIndexRecordsBase",+ image_index: "ImageIndexServiceBase",image_moves: "ImageMoveService | None" = None,):self.board_images = board_images@@ -141,3 +143,4 @@ class InvocationServices:self.board_video_records = board_video_recordsself.gallery = galleryself.image_index_records = image_index_records+ self.image_index = image_indexdiff --git a/invokeai/app/services/shared/sqlite/sqlite_database.py b/invokeai/app/services/shared/sqlite/sqlite_database.pyindex e67aab0ea5..b40ef55d33 100644--- a/invokeai/app/services/shared/sqlite/sqlite_database.py+++ b/invokeai/app/services/shared/sqlite/sqlite_database.py@@ -63,7 +63,12 @@ class SqliteDatabase:if not self._db_path:returntry:- with self._conn as conn:+ # Serialize with transaction() users: services with their own+ # threads (e.g. the image index worker) may have a statement in+ # progress on this shared connection, and VACUUM refuses to run+ # concurrently with one ("cannot VACUUM - SQL statements in+ # progress").+ with self._lock, self._conn as conn:initial_db_size = Path(self._db_path).stat().st_sizeconn.execute("VACUUM;")conn.commit()diff --git a/invokeai/backend/model_manager/starter_models.py b/invokeai/backend/model_manager/starter_models.pyindex edd2a4cb14..89d82035b1 100644--- a/invokeai/backend/model_manager/starter_models.py+++ b/invokeai/backend/model_manager/starter_models.py@@ -2312,6 +2312,7 @@ STARTER_MODELS: list[StarterModel] = [t5_gguf_q3_k_s_encoder,t5_gguf_q6_k_encoder,clip_l_encoder,+ clip_vit_l_image_encoder,siglip,flux_redux,llava_onevision,diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 4eaee8c207..33aa8cb0b9 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -40870,6 +40870,52 @@"$ref": "#/components/schemas/ImageOutput"}},+ "ImageIndexStatusEvent": {+ "description": "Event model for image_index_status",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "total": {+ "description": "Number of gallery images eligible for embedding",+ "title": "Total",+ "type": "integer"+ },+ "embedded": {+ "description": "Number of eligible images that have an embedding",+ "title": "Embedded",+ "type": "integer"+ },+ "pending": {+ "description": "Number of eligible images awaiting embedding",+ "title": "Pending",+ "type": "integer"+ }+ },+ "required": ["timestamp", "total", "embedded", "pending"],+ "title": "ImageIndexStatusEvent",+ "type": "object"+ },+ "ImageIndexUpdatedEvent": {+ "description": "Event model for image_index_updated.\n\nA counts-free poke to one user whose images were just (re)embedded, so\ntheir client can refresh views built on the index. Kept separate from\nImageIndexStatusEvent because the counts aggregate every user's images\nand are therefore admin-only, while this event is safe to route to the\nowning user's room.",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "user_id": {+ "description": "The user whose images were embedded",+ "title": "User Id",+ "type": "string"+ }+ },+ "required": ["timestamp", "user_id"],+ "title": "ImageIndexUpdatedEvent",+ "type": "object"+ },"ImageInverseLerpInvocation": {"category": "image","class": "invocation",@@ -50161,6 +50207,37 @@"description": "Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.","default": false},+ "image_index_enabled": {+ "type": "boolean",+ "title": "Image Index Enabled",+ "description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",+ "default": false+ },+ "image_index_model": {+ "type": "string",+ "title": "Image Index Model",+ "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.",+ "default": "clip-vit-large-patch14"+ },+ "image_index_device": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Image Index Device",+ "description": "Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress."+ },+ "image_index_batch_size": {+ "type": "integer",+ "exclusiveMinimum": 0.0,+ "title": "Image Index Batch Size",+ "description": "Number of images embedded per batch by the image index worker.",+ "default": 8+ },"external_alibabacloud_api_key": {"anyOf": [{@@ -50261,7 +50338,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `cuda:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `cuda:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 25ccf66efd..893190d23c 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -17040,6 +17040,54 @@ export type components = {*/type: "img_hue_adjust";};+ /**+ * ImageIndexStatusEvent+ * @description Event model for image_index_status+ */+ ImageIndexStatusEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Total+ * @description Number of gallery images eligible for embedding+ */+ total: number;+ /**+ * Embedded+ * @description Number of eligible images that have an embedding+ */+ embedded: number;+ /**+ * Pending+ * @description Number of eligible images awaiting embedding+ */+ pending: number;+ };+ /**+ * ImageIndexUpdatedEvent+ * @description Event model for image_index_updated.+ *+ * A counts-free poke to one user whose images were just (re)embedded, so+ * their client can refresh views built on the index. Kept separate from+ * ImageIndexStatusEvent because the counts aggregate every user's images+ * and are therefore admin-only, while this event is safe to route to the+ * owning user's room.+ */+ ImageIndexUpdatedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * User Id+ * @description The user whose images were embedded+ */+ user_id: string;+ };/*** Inverse Lerp Image* @description Inverse linear interpolation of all pixels of an image@@ -19267,6 +19315,10 @@ export type components = {* allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.* multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.* strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.+ * image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.+ * image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ * image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.+ * image_index_batch_size: Number of images embedded per batch by the image index worker.* external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.* external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.* external_gemini_api_key: API key for Gemini image generation.@@ -19698,6 +19750,29 @@ export type components = {* @default false*/strict_password_checking?: boolean;+ /**+ * Image Index Enabled+ * @description Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.+ * @default false+ */+ image_index_enabled?: boolean;+ /**+ * Image Index Model+ * @description Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ * @default clip-vit-large-patch14+ */+ image_index_model?: string;+ /**+ * Image Index Device+ * @description Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.+ */+ image_index_device?: string | null;+ /**+ * Image Index Batch Size+ * @description Number of images embedded per batch by the image index worker.+ * @default 8+ */+ image_index_batch_size?: number;/*** External Alibabacloud Api Key* @description API key for Alibaba Cloud DashScope image generation.diff --git a/tests/app/routers/test_image_moves.py b/tests/app/routers/test_image_moves.pyindex e13566e0c7..4dbff168e2 100644--- a/tests/app/routers/test_image_moves.py+++ b/tests/app/routers/test_image_moves.py@@ -91,6 +91,7 @@ def mock_services() -> InvocationServices:board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignoreimage_moves=image_moves,system_prompt_records=None, # type: ignore)diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.pyindex a816f03984..f4fa7cc8b1 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -133,6 +133,7 @@ def mock_services() -> InvocationServices:board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignore)diff --git a/tests/app/routers/test_session_queue_workflow_call.py b/tests/app/routers/test_session_queue_workflow_call.pyindex 772add6d5e..c88cbedef9 100644--- a/tests/app/routers/test_session_queue_workflow_call.py+++ b/tests/app/routers/test_session_queue_workflow_call.py@@ -106,6 +106,7 @@ def mock_services() -> InvocationServices:board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignore)diff --git a/tests/app/routers/test_system_prompts_multiuser.py b/tests/app/routers/test_system_prompts_multiuser.pyindex e0eae6f365..18e188242f 100644--- a/tests/app/routers/test_system_prompts_multiuser.py+++ b/tests/app/routers/test_system_prompts_multiuser.py@@ -107,6 +107,7 @@ def mock_services() -> InvocationServices:board_video_records=None, # type: ignoregallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignore)diff --git a/tests/app/routers/test_system_prompts_single_user.py b/tests/app/routers/test_system_prompts_single_user.pyindex 2eb6a7d713..c90b006897 100644--- a/tests/app/routers/test_system_prompts_single_user.py+++ b/tests/app/routers/test_system_prompts_single_user.py@@ -96,6 +96,7 @@ def mock_services() -> InvocationServices:board_video_records=None, # type: ignoregallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignore)diff --git a/tests/app/routers/test_workflows_multiuser.py b/tests/app/routers/test_workflows_multiuser.pyindex 201fc02549..7f716f8510 100644--- a/tests/app/routers/test_workflows_multiuser.py+++ b/tests/app/routers/test_workflows_multiuser.py@@ -123,6 +123,7 @@ def mock_services() -> InvocationServices:board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignoreimage_index_records=None, # type: ignore+ image_index=None, # type: ignore)diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pynew file mode 100644index 0000000000..6ffa8986c0--- /dev/null+++ b/tests/app/services/image_index/test_image_index_service.py@@ -0,0 +1,462 @@+"""Tests for the image index worker service, using an injected fake encoder (no models/GPU)."""++import time+from types import SimpleNamespace+from typing import Callable++import numpy as np+import pytest+from PIL import Image++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.events.events_common import ImageIndexStatusEvent, ImageIndexUpdatedEvent+from invokeai.app.services.image_index.image_index_default import ImageIndexService+from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlite+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin+from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage+from invokeai.app.services.images.images_common import image_record_to_dto+from invokeai.app.services.images.images_default import ImageService+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.backend.util.logging import InvokeAILogger+from tests.fixtures.sqlite_database import create_mock_sqlite_database+from tests.test_nodes import TestEventService++MODEL_ID = "test-model-hash"+DIM = 8+++def _wait_until(predicate: Callable[[], bool], timeout: float = 10.0) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.02)+ raise AssertionError("Condition not met within timeout")+++def _fake_encode(images: list[Image.Image]) -> np.ndarray:+ rng = np.random.default_rng(42)+ vectors = rng.standard_normal((len(images), DIM)).astype(np.float32)+ return vectors+++def db() -> SqliteDatabase:+ config = InvokeAIAppConfig(use_memory_db=True)+ return create_mock_sqlite_database(config=config, logger=InvokeAILogger.get_logger())+++def image_records(db: SqliteDatabase) -> SqliteImageRecordStorage:+ return SqliteImageRecordStorage(db=db)+++def index_records(db: SqliteDatabase) -> ImageIndexRecordsSqlite:+ return ImageIndexRecordsSqlite(db=db)+++def images_service() -> ImageService:+ images = ImageService()+ # The worker only needs get_pil_image; bypass file storage entirely.+ images.get_pil_image = lambda image_name: Image.new("RGB", (16, 16), "purple") # type: ignore[method-assign]+ return images+++def _make_invoker(+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ enabled: bool = True,+ image_records: SqliteImageRecordStorage | None = None,+) -> SimpleNamespace:+ config = InvokeAIAppConfig(+ use_memory_db=True,+ image_index_enabled=enabled,+ image_index_device="cpu",+ image_index_batch_size=4,+ )+ services = SimpleNamespace(+ configuration=config,+ logger=InvokeAILogger.get_logger(),+ images=images_service,+ image_records=image_records,+ image_index_records=index_records,+ events=TestEventService(),+ session_queue=None,+ model_manager=None,+ )+ return SimpleNamespace(services=services)+++def service() -> ImageIndexService:+ svc = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ yield svc+ svc.stop()+++def _save_image(+ image_records: SqliteImageRecordStorage,+ image_name: str,+ is_intermediate: bool = False,+ image_category: ImageCategory = ImageCategory.GENERAL,+) -> None:+ image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=image_category,+ width=16,+ height=16,+ has_workflow=False,+ is_intermediate=is_intermediate,+ user_id="system",+ )+++def _dto_for(image_records: SqliteImageRecordStorage, image_name: str):+ record = image_records.get(image_name)+ return image_record_to_dto(record, image_url="http://x/i.png", thumbnail_url="http://x/t.png", board_id=None)+++def test_constructor_requires_matched_test_seams() -> None:+ with pytest.raises(ValueError):+ ImageIndexService(encode_fn=_fake_encode)+ with pytest.raises(ValueError):+ ImageIndexService(model_id=MODEL_ID)+++def test_disabled_service_is_inert(+ images_service: ImageService, index_records: ImageIndexRecordsSqlite, service: ImageIndexService+) -> None:+ invoker = _make_invoker(images_service, index_records, enabled=False)+ service.start(invoker)++ assert service.model_id is None+ assert service.get_status() is None+ assert images_service._on_changed_callbacks == []+ assert images_service._on_deleted_callbacks == []+++def test_backfill_indexes_preexisting_eligible_images(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ for i in range(6):+ _save_image(image_records, f"img-{i}.png")+ _save_image(image_records, "intermediate.png", is_intermediate=True)+ _save_image(image_records, "mask.png", image_category=ImageCategory.MASK)++ service.start(_make_invoker(images_service, index_records))++ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 6)+ status = index_records.count_index_status(MODEL_ID)+ assert status.total == 6+ assert status.pending == 0+ # Ineligible images have no rows.+ assert index_records.get_embeddings(["intermediate.png", "mask.png"], MODEL_ID)[0] == []+ # Stored embeddings are L2-normalized.+ _, matrix = index_records.get_embeddings([f"img-{i}.png" for i in range(6)], MODEL_ID)+ assert np.allclose(np.linalg.norm(matrix, axis=1), 1.0, atol=1e-5)+++def test_on_changed_indexes_new_eligible_image_and_skips_ineligible(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ _save_image(image_records, "new.png")+ _save_image(image_records, "new-intermediate.png", is_intermediate=True)+ # Fire the callbacks the way ImageService.create would.+ images_service._on_changed(_dto_for(image_records, "new.png"))+ images_service._on_changed(_dto_for(image_records, "new-intermediate.png"))++ _wait_until(lambda: index_records.get_embeddings(["new.png"], MODEL_ID)[0] == ["new.png"])+ assert index_records.get_embeddings(["new-intermediate.png"], MODEL_ID)[0] == []+++def test_unloadable_image_is_skipped_and_backfill_completes(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ _save_image(image_records, "good.png")+ _save_image(image_records, "bad.png")++ def get_pil_image(image_name: str) -> Image.Image:+ if image_name == "bad.png":+ raise FileNotFoundError(image_name)+ return Image.new("RGB", (16, 16), "purple")++ images_service.get_pil_image = get_pil_image # type: ignore[method-assign]+ service.start(_make_invoker(images_service, index_records))++ _wait_until(lambda: not service._backfill_pending.is_set())+ assert index_records.get_embeddings(["good.png"], MODEL_ID)[0] == ["good.png"]+ assert index_records.get_embeddings(["bad.png"], MODEL_ID)[0] == []+ assert "bad.png" in service._failed+++def test_transient_encode_failure_is_retried_to_success(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ calls = {"n": 0}++ def flaky_encode(images: list[Image.Image]) -> np.ndarray:+ calls["n"] += 1+ if calls["n"] <= 2:+ raise RuntimeError("transient failure (e.g. OOM)")+ return _fake_encode(images)++ service = ImageIndexService(encode_fn=flaky_encode, model_id=MODEL_ID)+ try:+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: index_records.get_embeddings(["a.png"], MODEL_ID)[0] == ["a.png"], timeout=15)+ assert "a.png" not in service._failed+ finally:+ service.stop()+++def test_processor_falls_back_to_defaults_when_config_missing(tmp_path) -> None:+ # InvokeAI-published CLIP Vision model dirs ship no preprocessor_config.json;+ # the processor must fall back to library defaults rather than fail every batch.+ from types import SimpleNamespace++ from transformers import CLIPImageProcessor++ from invokeai.backend.model_manager.taxonomy import ModelType++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ service._invoker = SimpleNamespace(services=SimpleNamespace(configuration=SimpleNamespace(models_path=tmp_path))) # type: ignore[assignment]+ service._model_config = SimpleNamespace(type=ModelType.CLIPVision, path=str(tmp_path)) # type: ignore[assignment]++ processor = service._get_processor()++ assert isinstance(processor, CLIPImageProcessor)+ assert service._get_processor() is processor # cached+++def test_model_not_installed_message_flags_same_name_wrong_type() -> None:+ # The starter catalog has a clip_embed text encoder under the same name as+ # the default image encoder; the warning must name the type mismatch.+ from types import SimpleNamespace++ from invokeai.backend.model_manager.taxonomy import ModelType++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)++ def search_by_attr(model_name=None, model_type=None):+ return [] if model_type is not None else [SimpleNamespace(type=ModelType.CLIPEmbed)]++ service._invoker = SimpleNamespace( # type: ignore[assignment]+ services=SimpleNamespace(model_manager=SimpleNamespace(store=SimpleNamespace(search_by_attr=search_by_attr)))+ )+ message = service._model_not_installed_message("clip-vit-large-patch14")+ assert "clip_embed" in message+ assert "InvokeAI/clip-vit-large-patch14" in message++ service._invoker.services.model_manager.store.search_by_attr = lambda model_name=None: []+ message = service._model_not_installed_message("clip-vit-large-patch14")+ assert "is not installed" in message+++def test_bad_encoder_output_marks_batch_failed(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ service = ImageIndexService(encode_fn=lambda images: np.zeros((1,), dtype=np.float32), model_id=MODEL_ID)+ try:+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())+ assert index_records.count_index_status(MODEL_ID).embedded == 0+ assert "a.png" in service._failed+ finally:+ service.stop()+++def test_status_event_emitted(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ _save_image(image_records, "a.png")+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)++ _wait_until(lambda: not service._backfill_pending.is_set())+ _wait_until(+ lambda: any(+ isinstance(e, ImageIndexStatusEvent) and e.embedded == 1 and e.total == 1+ for e in invoker.services.events.events+ )+ )+++def _status_events(invoker) -> list[ImageIndexStatusEvent]:+ return [e for e in invoker.services.events.events if isinstance(e, ImageIndexStatusEvent)]+++def test_on_changed_emits_pending_status_before_embedding(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ _save_image(image_records, "new.png")+ images_service._on_changed(_dto_for(image_records, "new.png"))++ # The callback flags status-dirty before enqueueing, and the worker+ # emits before it embeds, so a pending=1 snapshot is always observable.+ _wait_until(lambda: any(e.total == 1 and e.pending == 1 for e in _status_events(invoker)))+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)+ _wait_until(lambda: any(e.total == 1 and e.pending == 0 for e in _status_events(invoker)))+++def test_on_deleted_emits_status(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ _save_image(image_records, "a.png")+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)++ image_records.delete("a.png")+ images_service._on_deleted("a.png")++ # Deletions give the worker nothing to embed; the dirty flag set by the+ # callback is the only path to this emit, within one poll interval.+ _wait_until(lambda: any(e.total == 0 and e.embedded == 0 and e.pending == 0 for e in _status_events(invoker)))+++def test_permanently_failed_image_still_reaches_quiescence(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ """A permanently-failing image must not wedge pending above zero forever."""+ _save_image(image_records, "good.png")+ _save_image(image_records, "bad.png")++ def get_pil_image(image_name: str) -> Image.Image:+ if image_name == "bad.png":+ raise FileNotFoundError(image_name)+ return Image.new("RGB", (16, 16), "purple")++ images_service.get_pil_image = get_pil_image # type: ignore[method-assign]+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)++ _wait_until(lambda: "bad.png" in service._failed, timeout=15.0)+ # Failed images are excluded from pending, so the index settles and the+ # final emitted status reports quiescence over the embeddable remainder.+ _wait_until(lambda: any(e.total == 2 and e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))+ status = service.get_status()+ assert status is not None+ assert status.pending == 0+ assert status.failed == 1+++def test_upsert_failure_routes_through_retry_to_success(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ """A raise while storing embeddings must feed the retry path, not strand the image."""+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ real_upsert = index_records.upsert_embedding+ calls = {"count": 0}++ def flaky_upsert(name: str, model_id: str, embedding: np.ndarray) -> None:+ calls["count"] += 1+ if calls["count"] == 1:+ raise RuntimeError("database is locked")+ real_upsert(name, model_id, embedding)++ index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]++ _save_image(image_records, "flaky.png")+ images_service._on_changed(_dto_for(image_records, "flaky.png"))++ _wait_until(lambda: index_records.get_embeddings(["flaky.png"], MODEL_ID)[0] == ["flaky.png"], timeout=15.0)+ _wait_until(lambda: any(e.total == 1 and e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))+++def test_ineligible_transition_clears_failure_bookkeeping(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ """An image that leaves eligibility must stop counting against `failed`."""+ invoker = _make_invoker(images_service, index_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ service._failed.add("gone.png")+ service._attempts["gone.png"] = 3+ _save_image(image_records, "gone.png", image_category=ImageCategory.MASK)+ images_service._on_changed(_dto_for(image_records, "gone.png"))++ assert "gone.png" not in service._failed+ assert "gone.png" not in service._attempts+ status = service.get_status()+ assert status is not None+ assert status.failed == 0+++def test_owner_poke_emitted_at_quiescence(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ """Owners get a counts-free user-routed poke once their embeds settle."""+ invoker = _make_invoker(images_service, index_records, image_records=image_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ _save_image(image_records, "mine.png")+ images_service._on_changed(_dto_for(image_records, "mine.png"))++ _wait_until(+ lambda: any(+ isinstance(e, ImageIndexUpdatedEvent) and e.user_id == "system" for e in invoker.services.events.events+ )+ )+++def test_stop_joins_worker(+ images_service: ImageService, index_records: ImageIndexRecordsSqlite, service: ImageIndexService+) -> None:+ service.start(_make_invoker(images_service, index_records))+ assert service._worker is not None and service._worker.is_alive()++ service.stop()++ assert not service._worker.is_alive()diff --git a/tests/app/services/shared/sqlite/test_sqlite_database.py b/tests/app/services/shared/sqlite/test_sqlite_database.pynew file mode 100644index 0000000000..7354e4b385--- /dev/null+++ b/tests/app/services/shared/sqlite/test_sqlite_database.py@@ -0,0 +1,47 @@+"""Regression test: clean() must serialize with transaction() users.++Startup runs VACUUM after services (and their worker threads) are already+live; an unserialized VACUUM intermittently fails the whole boot with+"cannot VACUUM - SQL statements in progress".+"""++import threading++from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.backend.util.logging import InvokeAILogger+++def test_clean_waits_for_in_flight_transactions(tmp_path) -> None:+ db = SqliteDatabase(db_path=tmp_path / "test.db", logger=InvokeAILogger.get_logger())+ in_transaction = threading.Event()+ release = threading.Event()+ errors: list[Exception] = []++ def hold_transaction() -> None:+ with db.transaction() as cursor:+ cursor.execute("CREATE TABLE t (x INTEGER);")+ cursor.execute("INSERT INTO t VALUES (1);")+ in_transaction.set()+ release.wait(10)++ def run_clean() -> None:+ try:+ db.clean()+ except Exception as e:+ errors.append(e)++ holder = threading.Thread(target=hold_transaction)+ holder.start()+ assert in_transaction.wait(10)++ # clean() must block on the shared lock until the transaction finishes,+ # not fail against its open statement.+ cleaner = threading.Thread(target=run_clean)+ cleaner.start()+ release.set()+ holder.join(10)+ cleaner.join(10)++ assert not holder.is_alive()+ assert not cleaner.is_alive()+ assert errors == []diff --git a/tests/app/services/test_image_move_startup_safety.py b/tests/app/services/test_image_move_startup_safety.pyindex ca1c7ad7e4..56fe720d0d 100644--- a/tests/app/services/test_image_move_startup_safety.py+++ b/tests/app/services/test_image_move_startup_safety.py@@ -46,6 +46,7 @@ def _services(**overrides):"board_video_records": object(),"gallery": object(),"image_index_records": object(),+ "image_index": object(),"image_moves": None,"system_prompt_records": object(),}diff --git a/tests/conftest.py b/tests/conftest.pyindex 043069228c..8987001b71 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -19,6 +19,7 @@ from invokeai.app.services.client_state_persistence.client_state_persistence_sqlfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.external_generation.external_generation_default import ExternalGenerationServicefrom invokeai.app.services.gallery.gallery_default import SqliteGalleryService+from invokeai.app.services.image_index.image_index_default import ImageIndexServicefrom invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStoragefrom invokeai.app.services.images.images_default import ImageService@@ -90,6 +91,7 @@ def mock_services() -> InvocationServices:# per-date item names through it, and MagicMock cannot exercise the filter SQL.gallery=SqliteGalleryService(db=db),image_index_records=ImageIndexRecordsSqlite(db=db),+ image_index=ImageIndexService(),)