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): image embedding and projection cache tables + records service
Lincoln Stein4a4c9dd00aae
diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.pyindex a87e328a47..4b271ad7a6 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_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_moves.image_moves_default import ImageMoveServicefrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStoragefrom invokeai.app.services.images.images_default import ImageService@@ -214,6 +215,7 @@ class ApiDependencies:client_state_persistence = ClientStatePersistenceSqlite(db=db)project_records = ProjectRecordsSqlite(db=db)users = UserService(db=db)+ image_index_records = ImageIndexRecordsSqlite(db=db)services = InvocationServices(board_image_records=board_image_records,@@ -256,6 +258,7 @@ class ApiDependencies:video_records=video_records,board_video_records=board_video_records,gallery=gallery,+ image_index_records=image_index_records,)ApiDependencies.invoker = Invoker(services)diff --git a/invokeai/app/services/image_index/image_index_common.py b/invokeai/app/services/image_index/image_index_common.pynew file mode 100644index 0000000000..67370f8c2f--- /dev/null+++ b/invokeai/app/services/image_index/image_index_common.py@@ -0,0 +1,68 @@+"""Common types and helpers for the semantic image index services."""++import numpy as np+from pydantic import BaseModel, ConfigDict, Field++EMBEDDING_DTYPE = np.float32+++class ImageIndexStatus(BaseModel):+ """Progress of the embedding index for one embedding model."""++ total: int = Field(description="Number of gallery images eligible for indexing")+ embedded: int = Field(description="Number of eligible images that have an embedding")++ @property+ def pending(self) -> int:+ return max(0, self.total - self.embedded)+++class ProjectionRecord(BaseModel):+ """A cached 2D projection of a user's accessible images."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ user_id: str = Field(description="The user the projection was computed for")+ model_id: str = Field(description="Content hash of the embedding model")+ scope_hash: str = Field(description="Fingerprint of the image set the projection covers")+ params: str = Field(description="JSON of the projection parameters")+ point_count: int = Field(description="Number of projected points")+ image_names: list[str] = Field(description="Image names, row-aligned with coords")+ coords: np.ndarray = Field(description="float32 array of shape (point_count, 2)")+ created_at: str = Field(description="When the projection was first computed")+ updated_at: str = Field(description="When the projection was last recomputed")+++def embedding_to_blob(embedding: np.ndarray) -> bytes:+ """Serialize a 1-D embedding vector to bytes for BLOB storage."""+ if embedding.ndim != 1:+ raise ValueError(f"Expected a 1-D embedding, got shape {embedding.shape}")+ return np.ascontiguousarray(embedding, dtype=EMBEDDING_DTYPE).tobytes()+++def blob_to_embedding(blob: bytes, dim: int) -> np.ndarray:+ """Deserialize an embedding BLOB, validating its length against the stored dim.++ Returns a read-only view over the blob; copy before mutating.+ """+ if len(blob) != dim * EMBEDDING_DTYPE().itemsize:+ raise ValueError(+ f"Embedding blob is {len(blob)} bytes; expected {dim * EMBEDDING_DTYPE().itemsize} for dim {dim}"+ )+ return np.frombuffer(blob, dtype=EMBEDDING_DTYPE)+++def coords_to_blob(coords: np.ndarray) -> bytes:+ """Serialize an (N, 2) coordinate array to bytes for BLOB storage."""+ if coords.ndim != 2 or coords.shape[1] != 2:+ raise ValueError(f"Expected coords of shape (N, 2), got {coords.shape}")+ return np.ascontiguousarray(coords, dtype=EMBEDDING_DTYPE).tobytes()+++def blob_to_coords(blob: bytes, point_count: int) -> np.ndarray:+ """Deserialize a coordinate BLOB, validating its length against the stored point count."""+ expected = point_count * 2 * EMBEDDING_DTYPE().itemsize+ if len(blob) != expected:+ raise ValueError(f"Coords blob is {len(blob)} bytes; expected {expected} for {point_count} points")+ # Copy so callers get a writable array rather than a read-only buffer view.+ return np.frombuffer(blob, dtype=EMBEDDING_DTYPE).reshape(point_count, 2).copy()diff --git a/invokeai/app/services/image_index/image_index_records_base.py b/invokeai/app/services/image_index/image_index_records_base.pynew file mode 100644index 0000000000..df074dbcbe--- /dev/null+++ b/invokeai/app/services/image_index/image_index_records_base.py@@ -0,0 +1,116 @@+from abc import ABC, abstractmethod++import numpy as np++from invokeai.app.services.image_index.image_index_common import ImageIndexStatus, ProjectionRecord+++class ImageIndexRecordsBase(ABC):+ """Storage for the semantic image index.++ Embeddings are global: one row per (image_name, model_id), shared by every+ user who can access the image. Projections are per-user caches over the+ set of images that user can access.++ Only "gallery" images are indexed: non-intermediate images in the+ `general` category.+ """++ @abstractmethod+ def upsert_embedding(self, image_name: str, model_id: str, embedding: np.ndarray) -> None:+ """Insert or replace the embedding for an image under the given model.++ A no-op if the image no longer exists (it may be deleted between being+ scheduled for embedding and the write landing).++ All embeddings stored under one model_id must share the same dim;+ `get_embeddings` fails on a result set with inconsistent dims.+ """+ pass++ @abstractmethod+ def get_embeddings(self, image_names: list[str], model_id: str) -> tuple[list[str], np.ndarray]:+ """Fetch embeddings for the given images.++ Duplicate input names are deduplicated, preserving first-seen order.++ Returns:+ A tuple of (found_names, matrix) where matrix has shape+ (len(found_names), dim) and rows align with found_names. Images+ without a stored embedding are silently omitted.+ """+ pass++ @abstractmethod+ def delete_embedding(self, image_name: str) -> None:+ """Delete all stored embeddings for an image (across all models)."""+ pass++ @abstractmethod+ def delete_embeddings_for_other_models(self, model_id: str) -> int:+ """Delete embeddings computed by any model other than the given one.++ Used when the configured embedding model changes: rows from the+ previous model are dead weight.++ Returns:+ The number of rows deleted.+ """+ pass++ @abstractmethod+ def list_unembedded_image_names(self, model_id: str, limit: int) -> list[str]:+ """List eligible images that have no embedding under the given model, oldest first."""+ pass++ @abstractmethod+ def count_index_status(self, model_id: str) -> ImageIndexStatus:+ """Count eligible images and how many of them are embedded under the given model."""+ pass++ @abstractmethod+ def list_accessible_embedded_images(self, user_id: str | None, model_id: str) -> list[str]:+ """List embedded images the user can access, sorted by image name.++ A user can access their own images, images on shared or public boards,+ and images on boards individually shared with them (shared_boards).+ Pass user_id=None for the admin scope (every embedded image).++ The sorted result is the input to the projection scope hash, so the+ ordering here must stay stable.+ """+ pass++ @abstractmethod+ def get_projection(self, user_id: str, model_id: str) -> ProjectionRecord | None:+ """Get the user's cached projection, or None if one was never computed."""+ pass++ @abstractmethod+ def set_projection(+ self,+ user_id: str,+ model_id: str,+ scope_hash: str,+ params: str,+ image_names: list[str],+ coords: np.ndarray,+ ) -> None:+ """Insert or replace the user's cached projection.++ A no-op if the user no longer exists.++ Args:+ user_id: The user the projection was computed for.+ model_id: Content hash of the embedding model.+ scope_hash: Fingerprint of the image set the projection covers.+ params: JSON of the projection parameters.+ image_names: Image names, row-aligned with coords.+ coords: float32 array of shape (len(image_names), 2).+ """+ pass++ @abstractmethod+ def delete_projection(self, user_id: str, model_id: str) -> None:+ """Delete the user's cached projection. Idempotent."""+ passdiff --git a/invokeai/app/services/image_index/image_index_records_sqlite.py b/invokeai/app/services/image_index/image_index_records_sqlite.pynew file mode 100644index 0000000000..b4d7da2937--- /dev/null+++ b/invokeai/app/services/image_index/image_index_records_sqlite.py@@ -0,0 +1,274 @@+import json+import sqlite3++import numpy as np++from invokeai.app.services.board_records.board_records_common import BoardVisibility+from invokeai.app.services.image_index.image_index_common import (+ EMBEDDING_DTYPE,+ ImageIndexStatus,+ ProjectionRecord,+ blob_to_coords,+ blob_to_embedding,+ coords_to_blob,+ embedding_to_blob,+)+from invokeai.app.services.image_index.image_index_records_base import ImageIndexRecordsBase+from invokeai.app.services.image_records.image_records_common import ImageCategory+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase++# SQLite's default variable limit is 999; stay well under it when chunking IN clauses.+_IN_CLAUSE_CHUNK = 500++# Conditions defining a "gallery" image, i.e. one worth indexing.+_ELIGIBLE_IMAGE_CONDITIONS = "images.is_intermediate = ? AND images.image_category = ?"+++def _eligible_params() -> tuple[bool, str]:+ return (False, ImageCategory.GENERAL.value)+++class ImageIndexRecordsSqlite(ImageIndexRecordsBase):+ """SQLite implementation of semantic image index storage."""++ def __init__(self, db: SqliteDatabase) -> None:+ super().__init__()+ self._db = db++ def start(self, invoker: Invoker) -> None:+ self._invoker = invoker++ def upsert_embedding(self, image_name: str, model_id: str, embedding: np.ndarray) -> None:+ blob = embedding_to_blob(embedding)+ try:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO image_embeddings (image_name, model_id, dim, embedding)+ VALUES (?, ?, ?, ?)+ ON CONFLICT (image_name, model_id)+ DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding;+ """,+ (image_name, model_id, embedding.shape[0], blob),+ )+ except sqlite3.IntegrityError:+ # The image was deleted between being scheduled and embedded (the+ # FK parent is gone). Its embedding is pointless; drop it silently.+ pass++ def get_embeddings(self, image_names: list[str], model_id: str) -> tuple[list[str], np.ndarray]:+ # Dedupe while preserving order so repeated input names cannot+ # double-count rows in downstream projection/similarity math.+ image_names = list(dict.fromkeys(image_names))+ found_names: list[str] = []+ vectors: list[np.ndarray] = []+ dim: int | None = None++ with self._db.transaction() as cursor:+ for start in range(0, len(image_names), _IN_CLAUSE_CHUNK):+ chunk = image_names[start : start + _IN_CLAUSE_CHUNK]+ placeholders = ",".join("?" * len(chunk))+ cursor.execute(+ f"""--sql+ SELECT image_name, dim, embedding+ FROM image_embeddings+ WHERE model_id = ? AND image_name IN ({placeholders});+ """,+ (model_id, *chunk),+ )+ rows = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}+ # Preserve the caller's ordering within each chunk.+ for name in chunk:+ if name not in rows:+ continue+ row_dim, blob = rows[name]+ if dim is None:+ dim = row_dim+ elif row_dim != dim:+ raise ValueError(f"Inconsistent embedding dims for model {model_id}: found {row_dim} and {dim}")+ found_names.append(name)+ vectors.append(blob_to_embedding(blob, row_dim))++ if not vectors:+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)+ return found_names, np.stack(vectors)++ def delete_embedding(self, image_name: str) -> None:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ DELETE FROM image_embeddings WHERE image_name = ?;+ """,+ (image_name,),+ )++ def delete_embeddings_for_other_models(self, model_id: str) -> int:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ DELETE FROM image_embeddings WHERE model_id != ?;+ """,+ (model_id,),+ )+ return cursor.rowcount++ def list_unembedded_image_names(self, model_id: str, limit: int) -> list[str]:+ with self._db.transaction() as cursor:+ cursor.execute(+ f"""--sql+ SELECT images.image_name+ FROM images+ LEFT JOIN image_embeddings+ ON image_embeddings.image_name = images.image_name+ AND image_embeddings.model_id = ?+ WHERE {_ELIGIBLE_IMAGE_CONDITIONS}+ AND image_embeddings.image_name IS NULL+ ORDER BY images.created_at ASC, images.image_name ASC+ LIMIT ?;+ """,+ (model_id, *_eligible_params(), limit),+ )+ return [row[0] for row in cursor.fetchall()]++ def count_index_status(self, model_id: str) -> ImageIndexStatus:+ with self._db.transaction() as cursor:+ cursor.execute(+ f"""--sql+ SELECT+ COUNT(*),+ COUNT(image_embeddings.image_name)+ FROM images+ LEFT JOIN image_embeddings+ ON image_embeddings.image_name = images.image_name+ AND image_embeddings.model_id = ?+ WHERE {_ELIGIBLE_IMAGE_CONDITIONS};+ """,+ (model_id, *_eligible_params()),+ )+ total, embedded = cursor.fetchone()+ return ImageIndexStatus(total=total, embedded=embedded)++ def list_accessible_embedded_images(self, user_id: str | None, model_id: str) -> list[str]:+ # Both clauses mirror the gallery "all" listing semantics+ # (image_records_sqlite): images on archived boards are hidden from+ # every scope, and a scoped user sees their own unboarded images plus+ # images on active boards they own, that are shared/public, or that+ # were individually shared with them via shared_boards. The projection+ # scope_hash and semantic search both derive from this listing, so any+ # change here must keep matching the gallery's access model.+ params: list[object] = [model_id, *_eligible_params()]+ if user_id is None:+ # Administrative scope: everything except archived-board images.+ access_clause = """AND (+ board_images.board_id IS NULL+ OR EXISTS (+ SELECT 1 FROM boards+ WHERE boards.board_id = board_images.board_id+ AND boards.archived = 0+ )+ )"""+ else:+ access_clause = """AND (+ (board_images.board_id IS NULL AND images.user_id = ?)+ OR EXISTS (+ SELECT 1 FROM boards+ WHERE boards.board_id = board_images.board_id+ AND boards.archived = 0+ AND (+ boards.user_id = ?+ OR boards.board_visibility IN (?, ?)+ OR EXISTS (+ SELECT 1 FROM shared_boards+ WHERE shared_boards.board_id = boards.board_id+ AND shared_boards.user_id = ?+ )+ )+ )+ )"""+ params.extend([user_id, user_id, BoardVisibility.Shared.value, BoardVisibility.Public.value, user_id])++ with self._db.transaction() as cursor:+ cursor.execute(+ f"""--sql+ SELECT DISTINCT image_embeddings.image_name+ FROM image_embeddings+ JOIN images ON images.image_name = image_embeddings.image_name+ LEFT JOIN board_images ON board_images.image_name = images.image_name+ WHERE image_embeddings.model_id = ?+ AND {_ELIGIBLE_IMAGE_CONDITIONS}+ {access_clause}+ ORDER BY image_embeddings.image_name ASC;+ """,+ params,+ )+ return [row[0] for row in cursor.fetchall()]++ def get_projection(self, user_id: str, model_id: str) -> ProjectionRecord | None:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT scope_hash, params, point_count, image_names, coords, created_at, updated_at+ FROM image_projections+ WHERE user_id = ? AND model_id = ?;+ """,+ (user_id, model_id),+ )+ row = cursor.fetchone()++ if row is None:+ return None++ return ProjectionRecord(+ user_id=user_id,+ model_id=model_id,+ scope_hash=row[0],+ params=row[1],+ point_count=row[2],+ image_names=json.loads(row[3]),+ coords=blob_to_coords(row[4], row[2]),+ created_at=row[5],+ updated_at=row[6],+ )++ def set_projection(+ self,+ user_id: str,+ model_id: str,+ scope_hash: str,+ params: str,+ image_names: list[str],+ coords: np.ndarray,+ ) -> None:+ if len(image_names) != coords.shape[0]:+ raise ValueError(f"Got {len(image_names)} image names but {coords.shape[0]} coordinate rows")+ blob = coords_to_blob(coords)+ try:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (user_id, model_id)+ DO UPDATE SET+ scope_hash = excluded.scope_hash,+ params = excluded.params,+ point_count = excluded.point_count,+ image_names = excluded.image_names,+ coords = excluded.coords;+ """,+ (user_id, model_id, scope_hash, params, len(image_names), json.dumps(image_names), blob),+ )+ except sqlite3.IntegrityError:+ # The user was deleted while their projection was being computed;+ # there is nobody left to serve it to.+ pass++ def delete_projection(self, user_id: str, model_id: str) -> None:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ DELETE FROM image_projections WHERE user_id = ? AND model_id = ?;+ """,+ (user_id, model_id),+ )diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.pyindex cc5182f761..b18ab112b6 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_records_base import ImageIndexRecordsBasefrom invokeai.app.services.image_moves.image_moves_default import ImageMoveServicefrom invokeai.app.services.image_records.image_records_base import ImageRecordStorageBasefrom invokeai.app.services.images.images_base import ImageServiceABC@@ -96,6 +97,7 @@ class InvocationServices:video_records: "VideoRecordStorageBase",board_video_records: "BoardVideoRecordStorageBase",gallery: "GalleryServiceABC",+ image_index_records: "ImageIndexRecordsBase",image_moves: "ImageMoveService | None" = None,):self.board_images = board_images@@ -138,3 +140,4 @@ class InvocationServices:self.video_records = video_recordsself.board_video_records = board_video_recordsself.gallery = gallery+ self.image_index_records = image_index_recordsdiff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.pynew file mode 100644index 0000000000..8861baff90--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.py@@ -0,0 +1,102 @@+"""Add tables for the semantic image index.++The image map / semantic search feature keeps a vision-model embedding for+each gallery image plus a cached 2D UMAP projection per user:++- `image_embeddings` is global (embeddings are user-independent): one row per+ (image_name, model_id), where model_id is the embedding model's content+ hash so re-installs of the same weights keep the index valid.+- `image_projections` caches one UMAP projection per (user_id, model_id) over+ the set of images that user can access. `scope_hash` fingerprints that set+ so staleness is detected by re-deriving it, never by bookkeeping.++The DDL uses IF NOT EXISTS so databases that acquired these tables from a+pre-rename build of this feature (which shipped them as a numeric migration)+no-op cleanly.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddImageIndexTablesCallback:+ """Migration to add the image_embeddings and image_projections tables."""++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ self._create_image_embeddings_table(cursor)+ self._create_image_projections_table(cursor)++ def _create_image_embeddings_table(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS image_embeddings (+ image_name TEXT NOT NULL,+ -- Content hash of the embedding model, not its install key.+ model_id TEXT NOT NULL,+ dim INTEGER NOT NULL,+ -- float32, L2-normalized, dim * 4 bytes.+ embedding BLOB NOT NULL,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (image_name, model_id),+ FOREIGN KEY (image_name) REFERENCES images(image_name) ON DELETE CASCADE+ );+ """+ )+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_image_embeddings_model_id ON image_embeddings(model_id);+ """+ )++ def _create_image_projections_table(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS image_projections (+ user_id TEXT NOT NULL,+ model_id TEXT NOT NULL,+ -- Fingerprint of the accessible image set the projection was+ -- computed over; a mismatch against the current set marks the+ -- cached projection stale.+ scope_hash TEXT NOT NULL,+ -- JSON of the projection parameters (n_neighbors, min_dist, ...).+ params TEXT NOT NULL,+ point_count INTEGER NOT NULL,+ -- JSON array of image names, row-aligned with coords.+ image_names TEXT NOT NULL,+ -- float32, shape (point_count, 2).+ coords BLOB NOT NULL,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (user_id, model_id),+ FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE+ );+ """+ )+ cursor.execute(+ """--sql+ CREATE TRIGGER IF NOT EXISTS tg_image_projections_updated_at+ AFTER UPDATE ON image_projections+ FOR EACH ROW+ BEGIN+ UPDATE image_projections+ SET updated_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')+ WHERE user_id = OLD.user_id AND model_id = OLD.model_id;+ END;+ """+ )+++def build_migration() -> Migration:+ """Build the migration that adds the image index tables:+ - `image_embeddings` (global per-image embedding index).+ - `image_projections` (per-user cached UMAP projections).+ """+ return Migration(+ id="2026_08_03_add_image_index_tables",+ # images(image_name) predates migration_33; migration_33 also transitively+ # guarantees migration_27's `users` table, which image_projections' FK+ # references. Same dependency reasoning as 2026_07_30_repair_projects_table.+ depends_on="migration_33",+ callback=AddImageIndexTablesCallback(),+ )diff --git a/invokeai/backend/util/gallery_maintenance.py b/invokeai/backend/util/gallery_maintenance.pyindex 973f633e95..43780c35db 100644--- a/invokeai/backend/util/gallery_maintenance.py+++ b/invokeai/backend/util/gallery_maintenance.py@@ -167,6 +167,10 @@ class DatabaseMapper:def connect(self):"""Open connection to the database."""self.connection = sqlite3.connect(self.database_path)+ # FK enforcement is per-connection and off by default. Without it, the+ # image deletions below leave orphaned rows in tables that declare+ # ON DELETE CASCADE against images (board_images, image_embeddings).+ self.connection.execute("PRAGMA foreign_keys = ON;")self.cursor = self.connection.cursor()def get_all_image_files(self):diff --git a/tests/app/routers/test_image_moves.py b/tests/app/routers/test_image_moves.pyindex b7e1cee311..e13566e0c7 100644--- a/tests/app/routers/test_image_moves.py+++ b/tests/app/routers/test_image_moves.py@@ -90,6 +90,7 @@ def mock_services() -> InvocationServices:video_records=SqliteVideoRecordStorage(db=db),board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignore+ image_index_records=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 9a22db11f8..a816f03984 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -132,6 +132,7 @@ def mock_services() -> InvocationServices:video_records=SqliteVideoRecordStorage(db=db),board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignore+ image_index_records=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 64c7f7a984..772add6d5e 100644--- a/tests/app/routers/test_session_queue_workflow_call.py+++ b/tests/app/routers/test_session_queue_workflow_call.py@@ -105,6 +105,7 @@ def mock_services() -> InvocationServices:video_records=SqliteVideoRecordStorage(db=db),board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignore+ image_index_records=None, # type: ignore)diff --git a/tests/app/routers/test_system_prompts_multiuser.py b/tests/app/routers/test_system_prompts_multiuser.pyindex f4c16699ba..e0eae6f365 100644--- a/tests/app/routers/test_system_prompts_multiuser.py+++ b/tests/app/routers/test_system_prompts_multiuser.py@@ -106,6 +106,7 @@ def mock_services() -> InvocationServices:video_records=None, # type: ignoreboard_video_records=None, # type: ignoregallery=None, # type: ignore+ image_index_records=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 1d9df114ea..2eb6a7d713 100644--- a/tests/app/routers/test_system_prompts_single_user.py+++ b/tests/app/routers/test_system_prompts_single_user.py@@ -95,6 +95,7 @@ def mock_services() -> InvocationServices:video_records=None, # type: ignoreboard_video_records=None, # type: ignoregallery=None, # type: ignore+ image_index_records=None, # type: ignore)diff --git a/tests/app/routers/test_workflows_multiuser.py b/tests/app/routers/test_workflows_multiuser.pyindex 6c34b02c00..201fc02549 100644--- a/tests/app/routers/test_workflows_multiuser.py+++ b/tests/app/routers/test_workflows_multiuser.py@@ -122,6 +122,7 @@ def mock_services() -> InvocationServices:video_records=SqliteVideoRecordStorage(db=db),board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignore+ image_index_records=None, # type: ignore)diff --git a/tests/app/services/image_index/test_image_index_records.py b/tests/app/services/image_index/test_image_index_records.pynew file mode 100644index 0000000000..6b0556a324--- /dev/null+++ b/tests/app/services/image_index/test_image_index_records.py@@ -0,0 +1,482 @@+"""Tests for the image index records service: embedding storage, eligibility, access scoping, projections."""++import numpy as np+import pytest++from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage+from invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibility+from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage+from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.image_index.image_index_common import (+ blob_to_coords,+ blob_to_embedding,+ coords_to_blob,+ embedding_to_blob,+)+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.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.services.users.users_common import UserCreateRequest+from invokeai.app.services.users.users_default import UserService+from invokeai.backend.util.logging import InvokeAILogger+from tests.fixtures.sqlite_database import create_mock_sqlite_database++SYSTEM_USER_ID = "system"+MODEL_ID = "model-hash-1"+OTHER_MODEL_ID = "model-hash-2"+DIM = 8+++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 board_records(db: SqliteDatabase) -> SqliteBoardRecordStorage:+ return SqliteBoardRecordStorage(db=db)+++def board_image_records(db: SqliteDatabase) -> SqliteBoardImageRecordStorage:+ return SqliteBoardImageRecordStorage(db=db)+++def index_records(db: SqliteDatabase) -> ImageIndexRecordsSqlite:+ return ImageIndexRecordsSqlite(db=db)+++def other_user_id(db: SqliteDatabase) -> str:+ users = UserService(db=db)+ user = users.create(+ UserCreateRequest(email="[email protected]", display_name="Other", password="TestPass123", is_admin=False)+ )+ return user.user_id+++def _save_image(+ image_records: SqliteImageRecordStorage,+ image_name: str,+ user_id: str = SYSTEM_USER_ID,+ 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=64,+ height=64,+ has_workflow=False,+ is_intermediate=is_intermediate,+ user_id=user_id,+ )+++def _vec(seed: int) -> np.ndarray:+ rng = np.random.default_rng(seed)+ v = rng.standard_normal(DIM).astype(np.float32)+ return v / np.linalg.norm(v)+++# --- Blob helpers ---+++def test_embedding_blob_roundtrip_is_bit_exact() -> None:+ v = _vec(1)+ assert np.array_equal(blob_to_embedding(embedding_to_blob(v), DIM), v)+++def test_embedding_blob_rejects_bad_shapes() -> None:+ with pytest.raises(ValueError):+ embedding_to_blob(np.zeros((2, 2), dtype=np.float32))+ with pytest.raises(ValueError):+ blob_to_embedding(embedding_to_blob(_vec(1)), DIM + 1)+++def test_coords_blob_roundtrip_and_validation() -> None:+ coords = np.arange(10, dtype=np.float32).reshape(5, 2)+ assert np.array_equal(blob_to_coords(coords_to_blob(coords), 5), coords)+ with pytest.raises(ValueError):+ coords_to_blob(np.zeros((5, 3), dtype=np.float32))+ with pytest.raises(ValueError):+ blob_to_coords(coords_to_blob(coords), 4)+++def test_coords_from_blob_are_writable() -> None:+ coords = blob_to_coords(coords_to_blob(np.zeros((2, 2), dtype=np.float32)), 2)+ coords[0, 0] = 5.0 # must not raise+ assert coords[0, 0] == 5.0+++# --- Embedding CRUD ---+++def test_upsert_and_get_roundtrip(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ _save_image(image_records, "b.png")+ va, vb = _vec(1), _vec(2)+ index_records.upsert_embedding("a.png", MODEL_ID, va)+ index_records.upsert_embedding("b.png", MODEL_ID, vb)++ names, matrix = index_records.get_embeddings(["b.png", "a.png", "missing.png"], MODEL_ID)++ assert names == ["b.png", "a.png"]+ assert matrix.dtype == np.float32+ assert np.array_equal(matrix[0], vb)+ assert np.array_equal(matrix[1], va)+++def test_upsert_replaces_existing_embedding(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ replacement = _vec(99)+ index_records.upsert_embedding("a.png", MODEL_ID, replacement)++ names, matrix = index_records.get_embeddings(["a.png"], MODEL_ID)+ assert names == ["a.png"]+ assert np.array_equal(matrix[0], replacement)+++def test_get_embeddings_empty_input_and_no_matches(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ names, matrix = index_records.get_embeddings([], MODEL_ID)+ assert names == []+ assert matrix.shape == (0, 0)++ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ names, matrix = index_records.get_embeddings(["a.png"], OTHER_MODEL_ID)+ assert names == []+ assert matrix.shape == (0, 0)+++def test_get_embeddings_chunks_large_requests(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ # More names than one IN-clause chunk (500) to exercise the chunked path.+ count = 501+ for i in range(count):+ _save_image(image_records, f"img-{i:04d}.png")+ index_records.upsert_embedding(f"img-{i:04d}.png", MODEL_ID, _vec(i))++ requested = [f"img-{i:04d}.png" for i in range(count)]+ names, matrix = index_records.get_embeddings(requested, MODEL_ID)+ assert names == requested+ assert matrix.shape == (count, DIM)+++def test_get_embeddings_deduplicates_input_names(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))++ names, matrix = index_records.get_embeddings(["a.png", "a.png"], MODEL_ID)++ assert names == ["a.png"]+ assert matrix.shape == (1, DIM)+++def test_upsert_embedding_for_deleted_image_is_noop(index_records: ImageIndexRecordsSqlite) -> None:+ # The image was deleted (or never existed) by the time the write lands;+ # the FK violation must not escape as a raw sqlite3 error.+ index_records.upsert_embedding("gone.png", MODEL_ID, _vec(1))+ assert index_records.get_embeddings(["gone.png"], MODEL_ID)[0] == []+++def test_set_projection_for_deleted_user_is_noop(index_records: ImageIndexRecordsSqlite) -> None:+ index_records.set_projection(+ "no-such-user", MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ )+ assert index_records.get_projection("no-such-user", MODEL_ID) is None+++def test_delete_embedding_removes_all_models(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding("a.png", OTHER_MODEL_ID, _vec(2))++ index_records.delete_embedding("a.png")++ assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == []+ assert index_records.get_embeddings(["a.png"], OTHER_MODEL_ID)[0] == []+++def test_image_delete_cascades_to_embeddings(+ db: SqliteDatabase, image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))++ image_records.delete("a.png")++ assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == []+++def test_delete_embeddings_for_other_models(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding("a.png", OTHER_MODEL_ID, _vec(2))++ deleted = index_records.delete_embeddings_for_other_models(MODEL_ID)++ assert deleted == 1+ assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == ["a.png"]+ assert index_records.get_embeddings(["a.png"], OTHER_MODEL_ID)[0] == []+++# --- Eligibility: backfill listing and status counts ---+++def test_list_unembedded_skips_ineligible_and_embedded(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "eligible.png")+ _save_image(image_records, "embedded.png")+ _save_image(image_records, "intermediate.png", is_intermediate=True)+ _save_image(image_records, "mask.png", image_category=ImageCategory.MASK)+ index_records.upsert_embedding("embedded.png", MODEL_ID, _vec(1))++ unembedded = index_records.list_unembedded_image_names(MODEL_ID, limit=10)++ assert unembedded == ["eligible.png"]+++def test_list_unembedded_respects_limit(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ for i in range(5):+ _save_image(image_records, f"img-{i}.png")++ assert len(index_records.list_unembedded_image_names(MODEL_ID, limit=3)) == 3+++def test_count_index_status(image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:+ _save_image(image_records, "a.png")+ _save_image(image_records, "b.png")+ _save_image(image_records, "intermediate.png", is_intermediate=True)+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))++ status = index_records.count_index_status(MODEL_ID)++ assert status.total == 2+ assert status.embedded == 1+ assert status.pending == 1+++# --- Access scoping ---+++def test_accessible_images_scoping(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ # System user's images: one unboarded, one on a private board, one shared, one public.+ for seed, name in enumerate(["own-unboarded.png", "own-private.png", "own-shared.png", "own-public.png"]):+ _save_image(image_records, name, user_id=SYSTEM_USER_ID)+ index_records.upsert_embedding(name, MODEL_ID, _vec(seed))+ # Other user's unboarded image.+ _save_image(image_records, "theirs-unboarded.png", user_id=other_user_id)+ index_records.upsert_embedding("theirs-unboarded.png", MODEL_ID, _vec(5))+ # An intermediate image never shows up even for its owner.+ _save_image(image_records, "own-intermediate.png", user_id=SYSTEM_USER_ID, is_intermediate=True)++ private_board = board_records.save("Private", SYSTEM_USER_ID).board_id+ shared_board = board_records.save("Shared", SYSTEM_USER_ID).board_id+ public_board = board_records.save("Public", SYSTEM_USER_ID).board_id+ board_records.update(shared_board, BoardChanges(board_visibility=BoardVisibility.Shared))+ board_records.update(public_board, BoardChanges(board_visibility=BoardVisibility.Public))+ board_image_records.add_image_to_board(private_board, "own-private.png")+ board_image_records.add_image_to_board(shared_board, "own-shared.png")+ board_image_records.add_image_to_board(public_board, "own-public.png")++ # Owner sees their unboarded image and everything on active boards they own.+ assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == sorted(+ ["own-unboarded.png", "own-private.png", "own-shared.png", "own-public.png"]+ )++ # The other user sees their own image plus shared/public board images — never the+ # system user's private-board or unboarded images.+ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == sorted(+ ["theirs-unboarded.png", "own-shared.png", "own-public.png"]+ )++ # Admin scope (None) sees everything embedded.+ assert index_records.list_accessible_embedded_images(None, MODEL_ID) == sorted(+ [+ "own-unboarded.png",+ "own-private.png",+ "own-shared.png",+ "own-public.png",+ "theirs-unboarded.png",+ ]+ )+++def test_accessible_images_includes_individually_shared_boards(+ db: SqliteDatabase,+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ # A private board individually shared with other_user via shared_boards+ # must expose its images to them — mirroring the board-listing access+ # model. No service writes shared_boards yet, so insert the row directly.+ _save_image(image_records, "own-individually-shared.png", user_id=SYSTEM_USER_ID)+ index_records.upsert_embedding("own-individually-shared.png", MODEL_ID, _vec(1))+ board_id = board_records.save("Individually shared", SYSTEM_USER_ID).board_id+ board_image_records.add_image_to_board(board_id, "own-individually-shared.png")+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO shared_boards (board_id, user_id, can_edit) VALUES (?, ?, ?);",+ (board_id, other_user_id, False),+ )++ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["own-individually-shared.png"]+ # A third party without the share still cannot see it.+ users = UserService(db=db)+ third_user = users.create(+ UserCreateRequest(email="[email protected]", display_name="Third", password="TestPass123", is_admin=False)+ )+ assert index_records.list_accessible_embedded_images(third_user.user_id, MODEL_ID) == []+++def test_accessible_images_includes_boards_owned_by_user(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ # An image uploaded by another user onto a board the system user OWNS is+ # accessible to the board owner — matching the gallery "all" listing+ # (image_records_sqlite), which grants access via boards.user_id even+ # without shared/public visibility or a shared_boards row.+ _save_image(image_records, "theirs-on-my-board.png", user_id=other_user_id)+ index_records.upsert_embedding("theirs-on-my-board.png", MODEL_ID, _vec(1))+ my_board = board_records.save("Mine", SYSTEM_USER_ID).board_id+ board_image_records.add_image_to_board(my_board, "theirs-on-my-board.png")++ assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["theirs-on-my-board.png"]+ # The uploader placed it on a private board they neither own nor were+ # granted; like the gallery "all" listing, they no longer see it.+ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == []+++def test_accessible_images_excludes_archived_boards(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ # Archived boards hide their images from every scope, mirroring the+ # gallery "all" listing: even the owner and the administrative scope.+ _save_image(image_records, "own-archived.png", user_id=SYSTEM_USER_ID)+ _save_image(image_records, "own-unboarded.png", user_id=SYSTEM_USER_ID)+ _save_image(image_records, "shared-archived.png", user_id=SYSTEM_USER_ID)+ for seed, name in enumerate(["own-archived.png", "own-unboarded.png", "shared-archived.png"]):+ index_records.upsert_embedding(name, MODEL_ID, _vec(seed))++ archived_board = board_records.save("Archived", SYSTEM_USER_ID).board_id+ archived_shared_board = board_records.save("Archived shared", SYSTEM_USER_ID).board_id+ board_records.update(archived_shared_board, BoardChanges(board_visibility=BoardVisibility.Shared))+ board_image_records.add_image_to_board(archived_board, "own-archived.png")+ board_image_records.add_image_to_board(archived_shared_board, "shared-archived.png")+ board_records.update(archived_board, BoardChanges(archived=True))+ board_records.update(archived_shared_board, BoardChanges(archived=True))++ # Owner: archived-board images are hidden; unboarded images are unaffected.+ assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["own-unboarded.png"]+ # An archived shared board grants nothing to other users either.+ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == []+ # The administrative scope also hides archived-board images.+ assert index_records.list_accessible_embedded_images(None, MODEL_ID) == ["own-unboarded.png"]+++def test_accessible_images_deduplicates_multi_board_images(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ board_a = board_records.save("A", SYSTEM_USER_ID).board_id+ board_image_records.add_image_to_board(board_a, "a.png")++ assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["a.png"]+++# --- Projections ---+++def test_projection_roundtrip(index_records: ImageIndexRecordsSqlite) -> None:+ coords = np.array([[0.5, -1.5], [2.0, 3.0]], dtype=np.float32)+ index_records.set_projection(SYSTEM_USER_ID, MODEL_ID, "hash-1", '{"n_neighbors": 15}', ["a.png", "b.png"], coords)++ record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)++ assert record is not None+ assert record.scope_hash == "hash-1"+ assert record.params == '{"n_neighbors": 15}'+ assert record.point_count == 2+ assert record.image_names == ["a.png", "b.png"]+ assert np.array_equal(record.coords, coords)+++def test_projection_upsert_replaces(index_records: ImageIndexRecordsSqlite) -> None:+ index_records.set_projection(+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ )+ index_records.set_projection(+ SYSTEM_USER_ID, MODEL_ID, "hash-2", "{}", ["a.png", "b.png"], np.ones((2, 2), dtype=np.float32)+ )++ record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)++ assert record is not None+ assert record.scope_hash == "hash-2"+ assert record.point_count == 2+++def test_projection_missing_and_delete_idempotent(index_records: ImageIndexRecordsSqlite) -> None:+ assert index_records.get_projection(SYSTEM_USER_ID, MODEL_ID) is None+ index_records.delete_projection(SYSTEM_USER_ID, MODEL_ID) # no-op++ index_records.set_projection(+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ )+ index_records.delete_projection(SYSTEM_USER_ID, MODEL_ID)+ assert index_records.get_projection(SYSTEM_USER_ID, MODEL_ID) is None+++def test_projection_rejects_mismatched_lengths(index_records: ImageIndexRecordsSqlite) -> None:+ with pytest.raises(ValueError):+ index_records.set_projection(+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((2, 2), dtype=np.float32)+ )diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_03_add_image_index_tables.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_03_add_image_index_tables.pynew file mode 100644index 0000000000..8f3ef9fa10--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_03_add_image_index_tables.py@@ -0,0 +1,65 @@+import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_08_03_add_image_index_tables import (+ AddImageIndexTablesCallback,+ build_migration,+)+++def _make_db() -> sqlite3.Connection:+ db = sqlite3.connect(":memory:")+ db.execute("PRAGMA foreign_keys = ON;")+ # Referenced by the new tables' FKs: images (migration_1) and users (migration_27).+ db.execute("CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY);")+ db.execute("CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);")+ return db+++def test_creates_the_image_index_tables() -> None:+ db = _make_db()++ AddImageIndexTablesCallback()(db.cursor())++ db.execute("INSERT INTO images VALUES ('i1');")+ db.execute("INSERT INTO users VALUES ('u1');")+ db.execute("INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES ('i1', 'm1', 2, x'00');")+ db.execute(+ "INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)"+ " VALUES ('u1', 'm1', 'h', '{}', 1, '[]', x'00');"+ )++ cursor = db.cursor()+ cursor.execute("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_image_embeddings_model_id';")+ assert cursor.fetchone() is not None+ cursor.execute("SELECT name FROM sqlite_master WHERE type='trigger' AND name='tg_image_projections_updated_at';")+ assert cursor.fetchone() is not None++ # FK cascade: deleting an image removes its embeddings.+ db.execute("DELETE FROM images WHERE image_name = 'i1';")+ cursor.execute("SELECT COUNT(*) FROM image_embeddings;")+ assert cursor.fetchone() == (0,)+ db.close()+++def test_is_idempotent_on_a_database_that_already_has_the_tables() -> None:+ """Databases that acquired these tables from a pre-rename numeric build of this feature must+ no-op rather than fail, and existing rows must survive."""+ db = _make_db()+ AddImageIndexTablesCallback()(db.cursor())+ db.execute("INSERT INTO images VALUES ('i1');")+ db.execute("INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES ('i1', 'm1', 2, x'00');")++ AddImageIndexTablesCallback()(db.cursor())++ cursor = db.cursor()+ cursor.execute("SELECT image_name FROM image_embeddings;")+ assert cursor.fetchall() == [("i1",)]+ db.close()+++def test_migration_has_a_dated_id_so_it_cannot_collide_with_an_upstream_number() -> None:+ migration = build_migration()+ assert migration.id == "2026_08_03_add_image_index_tables"+ assert migration.depends_on == "migration_33"+ assert migration.from_version is None+ assert migration.to_version is Nonediff --git a/tests/app/services/test_image_move_startup_safety.py b/tests/app/services/test_image_move_startup_safety.pyindex a03a98045a..ca1c7ad7e4 100644--- a/tests/app/services/test_image_move_startup_safety.py+++ b/tests/app/services/test_image_move_startup_safety.py@@ -45,6 +45,7 @@ def _services(**overrides):"video_records": object(),"board_video_records": object(),"gallery": object(),+ "image_index_records": object(),"image_moves": None,"system_prompt_records": object(),}diff --git a/tests/conftest.py b/tests/conftest.pyindex a22de7483b..043069228c 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_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStoragefrom invokeai.app.services.images.images_default import ImageServicefrom invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache@@ -88,6 +89,7 @@ def mock_services() -> InvocationServices:# Real SQLite-backed gallery service: the virtual-boards router reads dates and# per-date item names through it, and MagicMock cannot exercise the filter SQL.gallery=SqliteGalleryService(db=db),+ image_index_records=ImageIndexRecordsSqlite(db=db),)