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): admin-editable supplementary vocabulary for image map cluster labels
Lincoln Stein85d42e035a2c
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 94d8fa556b..d6834d07bf 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -9,11 +9,16 @@ from fastapi import File, HTTPException, Query, UploadFile, statusfrom fastapi.routing import APIRouterfrom pydantic import BaseModel, Field-from invokeai.app.api.auth_dependencies import CurrentUserOrDefault+from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers._access import assert_image_read_accessfrom invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException-from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError+from invokeai.app.services.image_index.cluster_labels import (+ MAX_CUSTOM_VOCAB_TERM_LENGTH,+ MAX_CUSTOM_VOCAB_TERMS,+ normalize_custom_vocab_terms,+)+from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError, VocabBuildStatefrom invokeai.app.services.image_index.image_index_common import ImageIndexStatusfrom invokeai.app.services.image_index.projection import (DEFAULT_CLUSTER_MIN_SAMPLES,@@ -806,6 +811,73 @@ def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefreshRespreturn ImageMapRefreshResponse(enqueued=enqueued)+class ImageMapVocabResponse(BaseModel):+ """The supplementary cluster-labeling vocabulary and its embedding build state."""++ terms: list[str] = Field(description="The stored supplementary terms, normalized, sorted alphabetically")+ state: VocabBuildState = Field(+ description="unavailable: the index is not running; idle: embeddings will build when labels are next "+ "requested; building: an embedding (re)build is queued or running; ready: embeddings are serving; "+ "error: the last build failed (see error)"+ )+ error: Optional[str] = Field(default=None, description="Why the last embedding build failed; only set on error")+ max_terms: int = Field(description="Maximum number of supplementary terms the server accepts")+ max_term_length: int = Field(description="Maximum length of one term, in characters")+++class ImageMapVocabUpdate(BaseModel):+ """Replacement supplementary vocabulary."""++ terms: list[str] = Field(+ max_length=MAX_CUSTOM_VOCAB_TERMS,+ description="The full supplementary term list; replaces what is stored. Terms are normalized "+ "(lowercased, whitespace collapsed) and deduplicated server-side.",+ )+++def _vocab_response(services) -> ImageMapVocabResponse:+ terms = services.image_index_records.get_custom_vocab_terms()+ state, error = services.image_index.get_vocab_build_state()+ return ImageMapVocabResponse(+ terms=terms,+ state=state,+ error=error,+ max_terms=MAX_CUSTOM_VOCAB_TERMS,+ max_term_length=MAX_CUSTOM_VOCAB_TERM_LENGTH,+ )+++@image_map_router.get("/vocab", operation_id="get_image_map_vocab", response_model=ImageMapVocabResponse)+def get_image_map_vocab(current_user: CurrentUserOrDefault) -> ImageMapVocabResponse:+ """Gets the supplementary cluster-labeling vocabulary.++ The list is server-wide: cluster labels are computed against one shared+ vocabulary. Readable by any user; only admins may change it.+ """+ return _vocab_response(ApiDependencies.invoker.services)+++@image_map_router.put("/vocab", operation_id="update_image_map_vocab", response_model=ImageMapVocabResponse)+def update_image_map_vocab(update: ImageMapVocabUpdate, current_user: AdminUserOrDefault) -> ImageMapVocabResponse:+ """Replaces the supplementary cluster-labeling vocabulary. Admin-only.++ The stored embeddings are invalidated and rebuilt in the background (the+ response's `state` reflects this); labels served in the meantime still use+ the previous vocabulary. Works while the index is disabled too — terms+ persist and take effect when indexing next runs.+ """+ try:+ terms = normalize_custom_vocab_terms(update.terms)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e))++ services = ApiDependencies.invoker.services+ services.image_index_records.set_custom_vocab_terms(terms)+ # After the commit, so the rebuild can only ever read the new rows.+ services.image_index.invalidate_vocab()+ return _vocab_response(services)++@image_map_router.get("/status", operation_id="get_image_map_status", response_model=ImageMapStatusResponse)def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:"""Gets embedding index progress and the user's projection cache status."""diff --git a/invokeai/app/services/image_index/cluster_labels.py b/invokeai/app/services/image_index/cluster_labels.pyindex 090f37d5c9..74cf6acfab 100644--- a/invokeai/app/services/image_index/cluster_labels.py+++ b/invokeai/app/services/image_index/cluster_labels.py@@ -28,6 +28,41 @@ PROMPT_TEMPLATES: tuple[str, ...] = (_VOCAB_PATH = Path(__file__).parent / "cluster_vocab.txt"+# Bounds on the admin-maintained supplementary vocabulary. The term cap keeps a+# rebuild after an edit to seconds (each term costs len(PROMPT_TEMPLATES)+# encoder strings); the length cap keeps every templated phrase well inside+# CLIP's 77-token context so no term is silently truncated by the tokenizer.+MAX_CUSTOM_VOCAB_TERMS = 500+MAX_CUSTOM_VOCAB_TERM_LENGTH = 64+++def normalize_custom_vocab_terms(raw: list[str]) -> list[str]:+ """Normalize user-supplied vocabulary terms for storage and embedding.++ Whitespace is collapsed, terms are lowercased to match the bundled+ vocabulary's convention, empties are dropped, and duplicates are removed+ (first occurrence wins, order preserved).++ Raises:+ ValueError: A term exceeds MAX_CUSTOM_VOCAB_TERM_LENGTH after+ normalization. Raised (naming the term) rather than truncated:+ a silently shortened phrase would embed as something the user+ never wrote.+ """+ terms: list[str] = []+ seen: set[str] = set()+ for entry in raw:+ term = " ".join(entry.split()).lower()+ if not term:+ continue+ if len(term) > MAX_CUSTOM_VOCAB_TERM_LENGTH:+ raise ValueError(f"Vocabulary term is longer than {MAX_CUSTOM_VOCAB_TERM_LENGTH} characters: '{term[:80]}'")+ if term in seen:+ continue+ seen.add(term)+ terms.append(term)+ return terms+def load_vocabulary() -> list[str]:"""Load the bundled labeling vocabulary (deduplicated, order-preserving)."""diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex ba43450c0a..c912ccf3af 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from typing import Optional+from typing import Literal, Optionalimport numpy as npfrom PIL import Image@@ -11,6 +11,14 @@ class TextSearchUnavailableError(Exception):"""The configured embedding model has no usable text tower installed."""+# unavailable: the indexer is not running (disabled, or its model is missing).+# idle: nothing has asked for cluster labels yet; the build runs on demand.+# building: a build is queued or in progress (including after an invalidation).+# ready: the vocabulary embeddings are cached and serving.+# error: the last build failed; invalidate_vocab() clears the failure and retries.+VocabBuildState = Literal["unavailable", "idle", "building", "ready", "error"]++class ImageIndexServiceBase(ABC):"""Background service that keeps the semantic image index up to date.@@ -82,6 +90,29 @@ class ImageIndexServiceBase(ABC):"""pass+ @abstractmethod+ def invalidate_vocab(self) -> None:+ """Discard the cached vocabulary embeddings and queue a rebuild.++ Called after the supplementary vocabulary changes. Must never block:+ it may be called from a request thread while the worker holds the+ vocabulary lock for a minutes-long build, so implementations signal+ the worker rather than clearing caches inline. Also clears a memoized+ build failure, so it doubles as the retry path for a failed build.++ Safe to call when the indexer is not running: the vocabulary lives in+ the database and the next start builds from current state anyway.+ """+ pass++ @abstractmethod+ def get_vocab_build_state(self) -> tuple[VocabBuildState, Optional[str]]:+ """The vocabulary embedding build's state, plus an error message when failed.++ Never blocks and never triggers a build; safe on request threads.+ """+ pass+@abstractmethoddef search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:"""Rank the user's accessible embedded images by cosine similarity.diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex ee5c53fa32..f11b362a48 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -8,7 +8,11 @@ import numpy as npimport torchfrom PIL import Image-from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase, TextSearchUnavailableError+from invokeai.app.services.image_index.image_index_base import (+ ImageIndexServiceBase,+ TextSearchUnavailableError,+ VocabBuildState,+)from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, ImageIndexStatusfrom invokeai.app.services.image_index.projection import compute_umap, projection_params, scope_hashfrom invokeai.app.services.image_records.image_records_common import ImageCategory@@ -274,6 +278,12 @@ class ImageIndexService(ImageIndexServiceBase):# Set by a labels request, serviced on the worker: the build is minutes# of encoder work and must never run on a request thread.self._vocab_build_requested = threading.Event()+ # Set by invalidate_vocab (the supplementary vocabulary changed, or a+ # failed build should be retried). The worker clears the RAM cache and+ # the memoized failure before rebuilding. A flag rather than clearing+ # them inline: invalidation runs on request threads, and _vocab_lock+ # is held by the worker for the whole of a minutes-long build.+ self._vocab_invalidate_requested = threading.Event()# Guards the lazy _processor/_cpu_model init: embed_image runs on# request threads concurrently with the indexer worker.self._vision_init_lock = threading.Lock()@@ -363,13 +373,45 @@ class ImageIndexService(ImageIndexServiceBase):raise TextSearchUnavailableError("Cluster labels are still being prepared; try again shortly")+ def invalidate_vocab(self) -> None:+ # Flags only — never _vocab_lock, which the worker holds for the whole+ # of a build; taking it here would park a request thread for minutes.+ #+ # The invalidation flag is set BEFORE the build-request flag. The+ # worker reads them in the opposite order (clears the build request,+ # then checks for invalidation), so whichever flag the worker's pass+ # misses is still set for its next pass; set the other way around, an+ # invalidation could slip between the worker's two reads and leave a+ # stale cache standing with no rebuild queued.+ self._vocab_invalidate_requested.set()+ self._vocab_build_requested.set()++ def get_vocab_build_state(self) -> tuple[VocabBuildState, Optional[str]]:+ if self._invoker is None or self._model_id is None:+ return "unavailable", None+ # Flags first: a pending invalidation means the current cache (or+ # failure) is about to be discarded, so reporting it would be a lie.+ if self._vocab_invalidate_requested.is_set() or self._vocab_build_requested.is_set():+ return "building", None+ # The worker holds _vocab_lock for the whole of a build; a failed+ # non-blocking acquire IS the "in progress" signal. The only other+ # holders (get_vocab_embeddings, and this method on another request+ # thread) hold it for microseconds, so a false "building" is a+ # transient a client's next poll corrects.+ if not self._vocab_lock.acquire(blocking=False):+ return "building", None+ try:+ if self._vocab_failure is not None:+ return "error", str(self._vocab_failure)+ if self._vocab_cache is not None:+ return "ready", None+ return "idle", None+ finally:+ self._vocab_lock.release()+def _build_vocab_embeddings(self) -> None:"""Build and cache the phrase embeddings. Index-worker thread only."""- from invokeai.app.services.image_index.cluster_labels import (- ensemble_phrase_embeddings,- load_vocabulary,- vocab_fingerprint,- )+ from invokeai.app.services.image_index.cluster_labels import load_vocabularywith self._vocab_lock:if self._vocab_cache is not None or self._vocab_failure is not None:@@ -377,31 +419,35 @@ class ImageIndexService(ImageIndexServiceBase):if self._invoker is None or self._model_id is None:return- vocabulary = load_vocabulary()- fingerprint = vocab_fingerprint(vocabulary)+ bundled = load_vocabulary()+ # Read inside the lock, and only after the worker cleared the+ # invalidation flags: a replacement committed after this read sets+ # the flags again, which forces another pass over the new rows.+ custom = self._invoker.services.image_index_records.get_custom_vocab_terms()+ # The bundled phrase wins a collision: it keeps the bundled cache+ # file's fingerprint independent of the custom list, and the label+ # the user would get is the same phrase either way.+ 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_path = self._invoker.services.configuration.db_path.parent / f"cluster_vocab_{model_tag}.npz"+ cache_dir = self._invoker.services.configuration.db_path.parent- if cache_path.exists():- try:- # Closed explicitly: np.load returns a lazily-read NpzFile- # holding the zip handle open, and the rewrite below- # truncates this very file on a fingerprint mismatch.- with np.load(cache_path, allow_pickle=False) as cached:- if str(cached["fingerprint"]) == fingerprint:- self._vocab_cache = (vocabulary, cached["embeddings"].astype(EMBEDDING_DTYPE))-- if self._vocab_cache is not None:- return- except Exception:- self._invoker.services.logger.warning("Discarding unreadable cluster vocabulary cache")-- # First run for this model: embedding ~1700 phrases x 7 templates- # takes minutes — hence the disk cache.+ # 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:- embeddings = ensemble_phrase_embeddings(self._embed_texts, vocabulary)+ bundled_matrix = self._load_or_embed_phrases(bundled, cache_dir / f"cluster_vocab_{model_tag}.npz")+ if custom:+ custom_matrix = self._load_or_embed_phrases(+ custom, cache_dir / f"cluster_vocab_custom_{model_tag}.npz"+ )+ self._vocab_cache = (bundled + custom, np.concatenate([bundled_matrix, custom_matrix]))+ else:+ self._vocab_cache = (bundled, bundled_matrix)except Exception as e:self._invoker.services.logger.warning("Could not build the cluster vocabulary", exc_info=True)# Remembered, so a vision-only install answers the next request@@ -421,37 +467,61 @@ class ImageIndexService(ImageIndexServiceBase):e.__context__ = Noneself._vocab_failure = e.with_traceback(None)- return+ def _load_or_embed_phrases(self, phrases: list[str], cache_path: Path) -> np.ndarray:+ """One vocabulary tier's embedding matrix, from its disk cache or the encoder.+ Index-worker thread only, under `_vocab_lock`. Raises on encoder+ failure (the caller memoizes it); a cache-write failure only warns.+ """+ from invokeai.app.services.image_index.cluster_labels import ensemble_phrase_embeddings, vocab_fingerprint++ assert self._invoker is not None+ fingerprint = vocab_fingerprint(phrases)++ if cache_path.exists():try:- cache_path.parent.mkdir(parents=True, exist_ok=True)- # Written aside and renamed: two processes sharing a db_dir can- # first-run at once, and a kill mid-write would otherwise leave- # a truncated archive that costs another full re-embed.- #- # The staging name has to end in `.npz` because np.savez appends- # that extension to any path that lacks it: written as `.tmp`,- # the archive landed at `.tmp.npz` and the rename below then- # failed on the `.tmp` that was never created. The failure was- # swallowed by the handler, so the cache never reached disk and- # every restart re-embedded the whole vocabulary (minutes,- # during which cluster labels are unavailable) while leaking one- # orphaned staging file per run.- staging_path = cache_path.with_name(f"{cache_path.name}.{os.getpid()}.tmp.npz")- np.savez(staging_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))- os.replace(staging_path, cache_path)+ # Closed explicitly: np.load returns a lazily-read NpzFile+ # holding the zip handle open, and the rewrite below+ # truncates this very file on a fingerprint mismatch.+ with np.load(cache_path, allow_pickle=False) as cached:+ if str(cached["fingerprint"]) == fingerprint:+ return cached["embeddings"].astype(EMBEDDING_DTYPE)except Exception:- # With the exception, not just the path. The in-memory cache- # below is assigned either way, so a write failure costs- # nothing until the next restart and is invisible until someone- # goes looking at startup times. The `.tmp` bug above survived- # because this line said only that something had gone wrong,- # never what — the FileNotFoundError it swallowed names the- # missing staging file outright.- self._invoker.services.logger.warning(- f"Could not write cluster vocabulary cache to {cache_path}", exc_info=True- )- self._vocab_cache = (vocabulary, embeddings)+ self._invoker.services.logger.warning("Discarding unreadable cluster vocabulary cache")++ # First run for this tier: embedding ~1700 phrases x 7 templates+ # takes minutes for the bundled vocabulary — hence the disk cache.+ embeddings = ensemble_phrase_embeddings(self._embed_texts, phrases)++ try:+ cache_path.parent.mkdir(parents=True, exist_ok=True)+ # Written aside and renamed: two processes sharing a db_dir can+ # first-run at once, and a kill mid-write would otherwise leave+ # a truncated archive that costs another full re-embed.+ #+ # The staging name has to end in `.npz` because np.savez appends+ # that extension to any path that lacks it: written as `.tmp`,+ # the archive landed at `.tmp.npz` and the rename below then+ # failed on the `.tmp` that was never created. The failure was+ # swallowed by the handler, so the cache never reached disk and+ # every restart re-embedded the whole vocabulary (minutes,+ # during which cluster labels are unavailable) while leaking one+ # orphaned staging file per run.+ staging_path = cache_path.with_name(f"{cache_path.name}.{os.getpid()}.tmp.npz")+ np.savez(staging_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))+ os.replace(staging_path, cache_path)+ except Exception:+ # With the exception, not just the path. The caller caches the+ # matrix in RAM either way, so a write failure costs+ # nothing until the next restart and is invisible until someone+ # goes looking at startup times. The `.tmp` bug above survived+ # because this line said only that something had gone wrong,+ # never what — the FileNotFoundError it swallowed names the+ # missing staging file outright.+ self._invoker.services.logger.warning(+ f"Could not write cluster vocabulary cache to {cache_path}", exc_info=True+ )+ return embeddingsdef _get_text_encoder(self) -> tuple[Any, Any, bool]:with self._text_encoder_lock:@@ -772,6 +842,17 @@ class ImageIndexService(ImageIndexServiceBase):# result of a build that is already covering it, and# _build_vocab_embeddings is a no-op once one has landed.self._vocab_build_requested.clear()+ if self._vocab_invalidate_requested.is_set():+ # Cleared before the caches are dropped: an+ # invalidation arriving after this clear re-sets both+ # flags (in that order — see invalidate_vocab), so it+ # is picked up on the next pass rather than lost.+ # Dropping the memoized failure here makes+ # invalidate_vocab the retry path for a failed build.+ self._vocab_invalidate_requested.clear()+ with self._vocab_lock:+ self._vocab_cache = None+ self._vocab_failure = Noneself._build_vocab_embeddings()continueprojection_job = self._next_projection_job()diff --git a/invokeai/app/services/image_index/image_index_records_base.py b/invokeai/app/services/image_index/image_index_records_base.pyindex 9e55493c89..0d6bbdae06 100644--- a/invokeai/app/services/image_index/image_index_records_base.py+++ b/invokeai/app/services/image_index/image_index_records_base.py@@ -99,6 +99,27 @@ class ImageIndexRecordsBase(ABC):"""pass+ @abstractmethod+ def get_custom_vocab_terms(self) -> list[str]:+ """List the supplementary cluster-labeling vocabulary terms, sorted by term.++ The list is server-wide (see the vocabulary table's migration) and is+ merged with the bundled vocabulary at embedding-build time. The sorted+ order feeds the vocabulary fingerprint, so it must stay stable.+ """+ pass++ @abstractmethod+ def set_custom_vocab_terms(self, terms: list[str]) -> None:+ """Replace the supplementary vocabulary with the given terms, atomically.++ Callers pass normalized terms (`normalize_custom_vocab_terms`); this+ stores what it is given. Replacement rather than per-term mutation:+ the vocabulary is a single small list edited as a whole, and replace+ semantics make the API idempotent.+ """+ pass+@abstractmethoddef get_projection(self, user_id: str, model_id: str) -> ProjectionRecord | None:"""Get the user's cached projection, or None if one was never computed."""diff --git a/invokeai/app/services/image_index/image_index_records_sqlite.py b/invokeai/app/services/image_index/image_index_records_sqlite.pyindex f30316aa07..a44937e72a 100644--- a/invokeai/app/services/image_index/image_index_records_sqlite.py+++ b/invokeai/app/services/image_index/image_index_records_sqlite.py@@ -219,6 +219,32 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):)return [row[0] for row in cursor.fetchall()]+ def get_custom_vocab_terms(self) -> list[str]:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT term FROM image_index_vocab_terms ORDER BY term ASC;+ """+ )+ return [row[0] for row in cursor.fetchall()]++ def set_custom_vocab_terms(self, terms: list[str]) -> None:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ DELETE FROM image_index_vocab_terms;+ """+ )+ # OR IGNORE: callers normalize away duplicates, but the NOCASE+ # primary key would otherwise turn a case-variant pair that slipped+ # through into an IntegrityError that rolls back the whole replace.+ cursor.executemany(+ """--sql+ INSERT OR IGNORE INTO image_index_vocab_terms (term) VALUES (?);+ """,+ [(term,) for term in terms],+ )+def get_projection(self, user_id: str, model_id: str) -> ProjectionRecord | None:with self._db.transaction() as cursor:cursor.execute(diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_23_add_image_index_vocab_terms.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_23_add_image_index_vocab_terms.pynew file mode 100644index 0000000000..ed3b39bfcd--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_23_add_image_index_vocab_terms.py@@ -0,0 +1,44 @@+"""Add the supplementary cluster-labeling vocabulary table.++The semantic image map labels clusters by zero-shot similarity against a+bundled vocabulary (`cluster_vocab.txt`). `image_index_vocab_terms` holds the+admin-maintained supplementary terms that are merged with the bundled list at+embedding-build time.++The table is server-wide rather than per-user: phrase embeddings are built+once per embedding model and shared by every user's cluster labels, so a+per-user vocabulary would need a per-user embedding build.++Terms are stored normalized (lowercased, whitespace-collapsed) by the API+layer; COLLATE NOCASE on the primary key is a backstop against case-variant+duplicates reaching the table by any other route.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddImageIndexVocabTermsCallback:+ """Migration to add the image_index_vocab_terms table."""++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS image_index_vocab_terms (+ term TEXT NOT NULL COLLATE NOCASE,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (term)+ );+ """+ )+++def build_migration() -> Migration:+ """Build the migration that adds the supplementary vocabulary table for+ semantic image map cluster labeling."""+ return Migration(+ id="2026_08_23_add_image_index_vocab_terms",+ depends_on="2026_08_18_add_workflow_last_run_at",+ callback=AddImageIndexVocabTermsCallback(),+ )diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 094a50b473..00c135c7c0 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -47,6 +47,8 @@ class FakeImageIndexService(ImageIndexServiceBase):self.text_unavailable = Falseself.embedded_texts: list[str] = []self.embedded_images: list = []+ self.vocab_invalidations = 0+ self.vocab_state: tuple[str, str | None] = ("idle", None)@propertydef model_id(self) -> str | None:@@ -95,6 +97,15 @@ class FakeImageIndexService(ImageIndexServiceBase):vocabulary = ["alpha", "beta", "gamma", "delta"]return vocabulary, np.eye(DIM, dtype=np.float32)+ def invalidate_vocab(self) -> None:+ self.vocab_invalidations += 1+ self.vocab_state = ("building", None)++ def get_vocab_build_state(self) -> tuple[str, str | None]:+ if self._model_id is None:+ return "unavailable", None+ return self.vocab_state+def request_projection(self,user_id: str,@@ -1104,3 +1115,95 @@ def test_cluster_labels_empty_without_projection(client: TestClient) -> None:"updated_at": None,"visible_hash": None,}+++# --- Supplementary vocabulary ---+++def test_vocab_get_returns_terms_and_state(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ _records(mock_invoker).set_custom_vocab_terms(["zebra", "aardvark"])++ body = client.get("/api/v1/image_map/vocab").json()++ assert body["terms"] == ["aardvark", "zebra"]+ assert body["state"] == "idle"+ assert body["error"] is None+ # The client sizes its input constraints from these.+ assert body["max_terms"] > 0+ assert body["max_term_length"] > 0+++def test_vocab_get_reports_unavailable_when_indexer_not_running(+ image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ image_index_service._model_id = None+ body = client.get("/api/v1/image_map/vocab").json()+ # Terms are still served: they persist and apply when indexing next runs.+ assert body["state"] == "unavailable"+++def test_vocab_put_normalizes_dedupes_stores_and_invalidates(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ response = client.put(+ "/api/v1/image_map/vocab",+ json={"terms": [" Golden Retriever ", "golden retriever", "", "Zebra"]},+ )++ assert response.status_code == 200+ body = response.json()+ assert body["terms"] == ["golden retriever", "zebra"]+ assert body["state"] == "building"+ # Stored, and the embedding cache was invalidated after the commit.+ assert _records(mock_invoker).get_custom_vocab_terms() == ["golden retriever", "zebra"]+ assert image_index_service.vocab_invalidations == 1+++def test_vocab_put_replaces_rather_than_merges(mock_invoker: Invoker, client: TestClient) -> None:+ client.put("/api/v1/image_map/vocab", json={"terms": ["zebra"]})+ client.put("/api/v1/image_map/vocab", json={"terms": ["okapi"]})+ assert _records(mock_invoker).get_custom_vocab_terms() == ["okapi"]++ client.put("/api/v1/image_map/vocab", json={"terms": []})+ assert _records(mock_invoker).get_custom_vocab_terms() == []+++def test_vocab_put_rejects_an_overlong_term_and_stores_nothing(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ _records(mock_invoker).set_custom_vocab_terms(["zebra"])++ response = client.put("/api/v1/image_map/vocab", json={"terms": ["ok", "x" * 65]})++ assert response.status_code == 422+ assert "64" in response.json()["detail"]+ # The stored list is untouched and nothing was invalidated.+ assert _records(mock_invoker).get_custom_vocab_terms() == ["zebra"]+ assert image_index_service.vocab_invalidations == 0+++def test_vocab_put_rejects_too_many_terms(mock_invoker: Invoker, client: TestClient) -> None:+ response = client.put("/api/v1/image_map/vocab", json={"terms": [f"term {i}" for i in range(501)]})+ assert response.status_code == 422+ assert _records(mock_invoker).get_custom_vocab_terms() == []+++def test_vocab_writes_are_admin_only(multiuser, mock_invoker: Invoker, client: TestClient) -> None:+ _create_user(mock_invoker, "[email protected]", is_admin=True)+ _create_user(mock_invoker, "[email protected]")+ admin_headers = _login(client, "[email protected]")+ user_headers = _login(client, "[email protected]")++ denied = client.put("/api/v1/image_map/vocab", json={"terms": ["zebra"]}, headers=user_headers)+ assert denied.status_code == 403+ assert _records(mock_invoker).get_custom_vocab_terms() == []++ allowed = client.put("/api/v1/image_map/vocab", json={"terms": ["zebra"]}, headers=admin_headers)+ assert allowed.status_code == 200++ # The list itself is readable by any user.+ read = client.get("/api/v1/image_map/vocab", headers=user_headers)+ assert read.status_code == 200+ assert read.json()["terms"] == ["zebra"]diff --git a/tests/app/services/image_index/test_cluster_labels.py b/tests/app/services/image_index/test_cluster_labels.pyindex 5f094d3959..a740b32e77 100644--- a/tests/app/services/image_index/test_cluster_labels.py+++ b/tests/app/services/image_index/test_cluster_labels.py@@ -1,12 +1,15 @@"""Tests for the vocabulary-based cluster labeling math."""import numpy as np+import pytestfrom invokeai.app.services.image_index.cluster_labels import (+ MAX_CUSTOM_VOCAB_TERM_LENGTH,PROMPT_TEMPLATES,ensemble_phrase_embeddings,label_clusters,load_vocabulary,+ normalize_custom_vocab_terms,vocab_fingerprint,)@@ -18,6 +21,24 @@ def test_load_vocabulary_is_nonempty_and_deduplicated() -> None:assert len({phrase.casefold() for phrase in vocabulary}) == len(vocabulary)+def test_normalize_custom_vocab_terms_lowercases_collapses_and_dedupes() -> None:+ normalized = normalize_custom_vocab_terms([" Golden Retriever ", "golden retriever", "", " ", "Zebra"])+ # First occurrence wins and input order is preserved (storage sorts later).+ assert normalized == ["golden retriever", "zebra"]+++def test_normalize_custom_vocab_terms_rejects_an_overlong_term() -> None:+ # Rejected rather than truncated: a silently shortened phrase would embed+ # as something the user never wrote.+ term = "x" * (MAX_CUSTOM_VOCAB_TERM_LENGTH + 1)+ with pytest.raises(ValueError, match=str(MAX_CUSTOM_VOCAB_TERM_LENGTH)):+ normalize_custom_vocab_terms([term])+ # Whitespace collapse happens first, so a term only *padded* past the+ # limit is fine.+ padded = "y" * MAX_CUSTOM_VOCAB_TERM_LENGTH + " "+ assert normalize_custom_vocab_terms([padded]) == ["y" * MAX_CUSTOM_VOCAB_TERM_LENGTH]++def test_vocab_fingerprint_changes_with_content() -> None:assert vocab_fingerprint(["a", "b"]) != vocab_fingerprint(["a", "c"])assert vocab_fingerprint(["a", "b"]) == vocab_fingerprint(["a", "b"])diff --git a/tests/app/services/image_index/test_image_index_records.py b/tests/app/services/image_index/test_image_index_records.pyindex bd9b2d6204..952be88bd3 100644--- a/tests/app/services/image_index/test_image_index_records.py+++ b/tests/app/services/image_index/test_image_index_records.py@@ -687,3 +687,24 @@ def test_projection_rejects_mismatched_lengths(index_records: ImageIndexRecordsSindex_records.set_projection(SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((2, 2), dtype=np.float32))+++def test_custom_vocab_terms_roundtrip_sorted_with_replace_semantics(index_records: ImageIndexRecordsSqlite) -> None:+ assert index_records.get_custom_vocab_terms() == []++ index_records.set_custom_vocab_terms(["zebra", "aardvark"])+ assert index_records.get_custom_vocab_terms() == ["aardvark", "zebra"]++ # Replacement, not merge: what is passed is what is stored.+ index_records.set_custom_vocab_terms(["okapi"])+ assert index_records.get_custom_vocab_terms() == ["okapi"]++ index_records.set_custom_vocab_terms([])+ assert index_records.get_custom_vocab_terms() == []+++def test_custom_vocab_case_variant_duplicates_cannot_fail_the_replace(index_records: ImageIndexRecordsSqlite) -> None:+ # Callers normalize, but the NOCASE primary key is a backstop: a+ # case-variant pair must collapse to one row, not roll back the replace.+ index_records.set_custom_vocab_terms(["Zebra", "zebra"])+ assert len(index_records.get_custom_vocab_terms()) == 1diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex e384ba3e05..20ccddc664 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1755,6 +1755,7 @@ def test_a_failed_vocabulary_build_does_not_pin_the_rejected_text_encoder(service._invoker = SimpleNamespace( # type: ignore[assignment]services=SimpleNamespace(configuration=SimpleNamespace(models_path=tmp_path, db_path=tmp_path / "db.sqlite"),+ image_index_records=SimpleNamespace(get_custom_vocab_terms=lambda: []),# Not a real Logger: pytest's logging plugin retains every LogRecord# for the test, and a record carrying exc_info holds the very# traceback whose release is being asserted.@@ -1950,6 +1951,7 @@ def _vocab_build_service(tmp_path, monkeypatch: pytest.MonkeyPatch, matrix: np.nservices=SimpleNamespace(configuration=SimpleNamespace(db_path=tmp_path / "invokeai.db"),logger=InvokeAILogger.get_logger(),+ image_index_records=SimpleNamespace(get_custom_vocab_terms=lambda: []),))svc._model_id = MODEL_ID@@ -2042,3 +2044,218 @@ def test_batch_normalization_zeroes_a_degenerate_row_instead_of_failing(service:assert float(np.linalg.norm(normalized[0])) == pytest.approx(1.0, rel=1e-5)assert not normalized[1].any()assert not normalized[2].any()+++# --- Custom (supplementary) vocabulary ---+++def _phrase_matrix(phrases: list[str]) -> np.ndarray:+ """Deterministic, phrase-distinguishable rows: every value is the phrase's length."""+ return np.stack([np.full(DIM, float(len(phrase)), dtype=EMBEDDING_DTYPE) for phrase in phrases])+++def _vocab_service_with_custom_terms(tmp_path, monkeypatch: pytest.MonkeyPatch, custom: list[str]) -> ImageIndexService:+ """A service wired for `_build_vocab_embeddings` over a three-phrase bundled vocabulary."""+ from invokeai.app.services.image_index import cluster_labels++ monkeypatch.setattr(cluster_labels, "load_vocabulary", lambda: ["a cat", "a dog", "a car"])+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", lambda embed_fn, phrases: _phrase_matrix(phrases))++ svc = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ svc._invoker = SimpleNamespace( # type: ignore[assignment]+ services=SimpleNamespace(+ configuration=SimpleNamespace(db_path=tmp_path / "invokeai.db"),+ logger=InvokeAILogger.get_logger(),+ image_index_records=SimpleNamespace(get_custom_vocab_terms=lambda: list(custom)),+ )+ )+ svc._model_id = MODEL_ID++ return svc+++def test_custom_terms_are_appended_and_bundled_phrases_win_collisions(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # "a dog" collides with the bundled vocabulary and is dropped (the label a+ # user would get is the same phrase either way); "zebra crossing" extends it.+ service = _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["zebra crossing", "a dog"])++ service._build_vocab_embeddings()++ assert service._vocab_cache is not None+ vocabulary, matrix = service._vocab_cache+ assert vocabulary == ["a cat", "a dog", "a car", "zebra crossing"]+ assert matrix.shape == (4, DIM)+ # Rows stay aligned with the merged phrase list across the concatenation.+ assert np.array_equal(matrix[3], np.full(DIM, float(len("zebra crossing")), dtype=EMBEDDING_DTYPE))+ # Both tiers persisted, separately.+ tag = MODEL_ID.replace(":", "_")[:24]+ assert (tmp_path / f"cluster_vocab_{tag}.npz").exists()+ assert (tmp_path / f"cluster_vocab_custom_{tag}.npz").exists()+++def test_editing_custom_terms_re_embeds_only_the_custom_tier(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ # The bundled tier is ~1700 phrases and minutes of encoder work; an edit to+ # the custom list must be answered from the bundled tier's disk cache.+ from invokeai.app.services.image_index import cluster_labels++ _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["zebra"])._build_vocab_embeddings()++ embedded: list[list[str]] = []++ def _record(embed_fn: Callable[[list[str]], np.ndarray], phrases: list[str]) -> np.ndarray:+ embedded.append(list(phrases))+ return _phrase_matrix(phrases)++ second = _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["zebra", "okapi"])+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", _record)++ second._build_vocab_embeddings()++ assert embedded == [["zebra", "okapi"]]+ assert second._vocab_cache is not None+ assert second._vocab_cache[0] == ["a cat", "a dog", "a car", "zebra", "okapi"]+ assert second._vocab_cache[1].shape == (5, DIM)+++def test_an_unchanged_custom_tier_is_loaded_from_disk(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ from invokeai.app.services.image_index import cluster_labels++ _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["zebra"])._build_vocab_embeddings()++ def _refuse(embed_fn: Callable[[list[str]], np.ndarray], phrases: list[str]) -> np.ndarray:+ raise AssertionError("re-embedded a tier that was already cached")++ second = _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["zebra"])+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", _refuse)++ second._build_vocab_embeddings()++ assert second._vocab_cache is not None+ assert second._vocab_cache[0] == ["a cat", "a dog", "a car", "zebra"]+++def test_vocab_build_state_reports_each_phase(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ fresh = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ assert fresh.get_vocab_build_state() == ("unavailable", None)++ service = _vocab_service_with_custom_terms(tmp_path, monkeypatch, [])+ assert service.get_vocab_build_state() == ("idle", None)++ service.invalidate_vocab()+ assert service.get_vocab_build_state() == ("building", None)++ # The worker's pass: clear the flags, then build.+ service._vocab_build_requested.clear()+ service._vocab_invalidate_requested.clear()+ service._build_vocab_embeddings()+ assert service.get_vocab_build_state() == ("ready", None)+++def test_vocab_build_state_reports_error_with_the_failure_message(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ from invokeai.app.services.image_index import cluster_labels++ service = _vocab_service_with_custom_terms(tmp_path, monkeypatch, [])++ def _raise(embed_fn: Callable[[list[str]], np.ndarray], phrases: list[str]) -> np.ndarray:+ raise RuntimeError("simulated: no text tower")++ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", _raise)+ service._build_vocab_embeddings()++ state, message = service.get_vocab_build_state()+ assert state == "error"+ assert message is not None and "no text tower" in message+++def test_invalidate_vocab_never_blocks_on_an_in_flight_build(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ # The worker holds _vocab_lock for the whole of a minutes-long build;+ # invalidation runs on request threads and must return without it.+ service = _vocab_service_with_custom_terms(tmp_path, monkeypatch, [])+ assert service._vocab_lock.acquire(blocking=False)+ try:+ done = threading.Event()++ def _invalidate() -> None:+ service.invalidate_vocab()+ done.set()++ thread = threading.Thread(target=_invalidate)+ thread.start()+ thread.join(timeout=2)+ assert done.is_set(), "invalidate_vocab blocked behind the vocabulary lock"+ # And an in-flight build reads as building.+ assert service.get_vocab_build_state() == ("building", None)+ finally:+ service._vocab_lock.release()+++def test_invalidate_vocab_rebuilds_with_the_new_terms_on_the_worker(+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from invokeai.app.services.image_index import cluster_labels+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ monkeypatch.setattr(cluster_labels, "load_vocabulary", lambda: ["a cat"])+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", lambda embed_fn, phrases: _phrase_matrix(phrases))+ monkeypatch.setattr(InvokeAIAppConfig, "db_path", property(lambda self: tmp_path / "invokeai.db"))+ index_records.set_custom_vocab_terms(["dog"])++ service.start(_make_invoker(images_service, index_records))+ with pytest.raises(TextSearchUnavailableError, match="still being prepared"):+ service.get_vocab_embeddings()+ _wait_until(lambda: service.get_vocab_build_state() == ("ready", None))+ assert service.get_vocab_embeddings()[0] == ["a cat", "dog"]++ index_records.set_custom_vocab_terms(["dog", "zebra"])+ service.invalidate_vocab()++ _wait_until(+ lambda: service.get_vocab_build_state() == ("ready", None)+ and service._vocab_cache is not None+ and "zebra" in service._vocab_cache[0]+ )+ vocabulary, matrix = service.get_vocab_embeddings()+ assert vocabulary == ["a cat", "dog", "zebra"]+ assert matrix.shape == (3, DIM)+++def test_invalidate_vocab_retries_a_failed_build(+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A memoized build failure is deliberately never retried on its own (see+ # test_a_failed_vocabulary_build_is_not_retried_on_every_request);+ # invalidation is the one path that clears it.+ from invokeai.app.services.image_index import cluster_labels+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ flaky = {"fail": True}++ def _ensemble(embed_fn: Callable[[list[str]], np.ndarray], phrases: list[str]) -> np.ndarray:+ if flaky["fail"]:+ raise RuntimeError("simulated: no text tower")+ return _phrase_matrix(phrases)++ monkeypatch.setattr(cluster_labels, "load_vocabulary", lambda: ["a cat"])+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", _ensemble)+ monkeypatch.setattr(InvokeAIAppConfig, "db_path", property(lambda self: tmp_path / "invokeai.db"))++ service.start(_make_invoker(images_service, index_records))+ with pytest.raises(TextSearchUnavailableError, match="still being prepared"):+ service.get_vocab_embeddings()+ _wait_until(lambda: service.get_vocab_build_state()[0] == "error")++ flaky["fail"] = False+ service.invalidate_vocab()++ _wait_until(lambda: service.get_vocab_build_state() == ("ready", None))+ assert service.get_vocab_embeddings()[0] == ["a cat"]