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(app): index gallery videos into the semantic image map
Lincoln Stein75e32bd0ac73
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 96b70d9061..f23aaf9fc2 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -936,7 +936,7 @@{"category": "IMAGE INDEX","default": true,- "description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",+ "description": "Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.","env_var": "INVOKEAI_IMAGE_INDEX_ENABLED","literal_values": [],"name": "image_index_enabled",@@ -947,7 +947,7 @@{"category": "IMAGE INDEX","default": "DFN2B-CLIP-ViT-L-14-39B",- "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.",+ "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.","env_var": "INVOKEAI_IMAGE_INDEX_MODEL","literal_values": [],"name": "image_index_model",@@ -969,7 +969,7 @@{"category": "IMAGE INDEX","default": 8,- "description": "Number of images embedded per batch by the image index worker.",+ "description": "Number of gallery items embedded per batch by the image index worker.","env_var": "INVOKEAI_IMAGE_INDEX_BATCH_SIZE","literal_values": [],"name": "image_index_batch_size",diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 9811fe848f..f8cf9760c1 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -7,11 +7,12 @@ from typing import Literal, Optionalimport numpy as npfrom fastapi import File, HTTPException, Query, UploadFile, statusfrom fastapi.routing import APIRouter+from PIL import Imagefrom pydantic import BaseModel, Fieldfrom invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies-from invokeai.app.api.routers._access import assert_image_read_access+from invokeai.app.api.routers._access import assert_image_read_access, assert_video_read_accessfrom invokeai.app.services.image_files.image_files_common import ImageFileNotFoundExceptionfrom invokeai.app.services.image_index.cluster_labels import (MAX_CUSTOM_VOCAB_TERM_LENGTH,@@ -19,7 +20,11 @@ from invokeai.app.services.image_index.cluster_labels import (normalize_custom_vocab_terms,)from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError, VocabBuildState-from invokeai.app.services.image_index.image_index_common import ImageIndexStatus+from invokeai.app.services.image_index.image_index_common import (+ ImageIndexStatus,+ IndexedItem,+ MediaKind,+)from invokeai.app.services.image_index.projection import (DEFAULT_CLUSTER_MIN_SAMPLES,MAX_CLUSTERED_POINTS,@@ -30,6 +35,7 @@ from invokeai.app.services.image_index.projection import (scope_hash,)from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException+from invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundExceptionimage_map_router = APIRouter(prefix="/v1/image_map", tags=["image_map"])@@ -37,11 +43,14 @@ ImageMapState = Literal["disabled", "model_missing", "empty", "computing", "readclass ImageMapPoint(BaseModel):- """One image's position on the 2D semantic map."""+ """One gallery item's position on the 2D semantic map."""x: float = Field(description="UMAP x coordinate")y: float = Field(description="UMAP y coordinate")- image_name: str = Field(description="The image this point represents")+ image_name: str = Field(+ description="The image or video this point represents; `kind` says which namespace the name belongs to"+ )+ kind: MediaKind = Field(description="Whether this point is an image or a video")cluster: int = Field(description="DBSCAN cluster label; -1 means unclustered")@@ -173,7 +182,7 @@ def _release_refresh_slot(user_id: str) -> None:# over a round-robin access pattern misses every time, and any single caller# could evict everyone else by varying `eps` across a handful of requests._CLUSTER_CACHE_USERS = 32-_ClusterCacheKey = tuple[str, Optional[str], str, Optional[float], int]+_ClusterCacheKey = tuple[str, Optional[str], str, Optional[float], int, tuple[MediaKind, ...]]_cluster_cache: "OrderedDict[str, tuple[_ClusterCacheKey, np.ndarray, Optional[float]]]" = OrderedDict()@@ -210,11 +219,59 @@ def _active_model_id(services) -> Optional[str]:return model_id+# Videos are indexed whether or not a client can render them, so serving them is opt-in: a+# client that resolves every name through the images endpoints (as the shipped gallery does)+# would turn a video into a broken tile and a selectable item that does not exist.+IncludeVideosQuery = Query(+ default=False,+ description="Include indexed videos among the returned items. Leave off unless the client "+ "resolves each item through the endpoint its `kind` names.",+)+++def _served_kinds(include_videos: bool) -> tuple[MediaKind, ...]:+ return ("image", "video") if include_videos else ("image",)+++def _search_reference(image_name: Optional[str], video_name: Optional[str]) -> Optional[IndexedItem]:+ """The reference item for a similarity search, or None when none was given.++ Naming both is refused rather than resolved by precedence: it is a caller mistake, and the+ endpoint's "exactly one of" contract is what tells the caller so.+ """+ if image_name is not None and video_name is not None:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="Provide exactly one of q, image_name or video_name",+ )+ if image_name is not None:+ return IndexedItem("image", image_name)+ if video_name is not None:+ return IndexedItem("video", video_name)+ return None+++def _reference_image(services, item: IndexedItem) -> Image.Image:+ """The pixels a reference item is embedded from.++ A video is represented by its thumbnail — the frame the index itself embeds — so an+ unindexed video answers the same query an indexed one would, and no decoder runs on a+ request thread.+ """+ if item.kind == "video":+ # Copied out of the context manager so the thumbnail's file handle is closed here+ # rather than whenever the returned image is collected.+ with Image.open(services.videos.get_path(item.name, thumbnail=True)) as thumbnail:+ return thumbnail.copy()+ return services.images.get_pil_image(item.name)++@image_map_router.get("/points", operation_id="get_image_map_points", response_model=ImageMapPointsResponse)async def get_image_map_points(current_user: CurrentUserOrDefault,eps: Optional[float] = ClusterEpsQuery,min_samples: int = ClusterMinSamplesQuery,+ include_videos: bool = IncludeVideosQuery,) -> ImageMapPointsResponse:"""Gets the current user's semantic image map.@@ -240,13 +297,19 @@ async def get_image_map_points(return ImageMapPointsResponse(points=[], state="disabled", stale=False, point_count=0)user_id, is_admin = _scope(current_user)- current_names = services.image_index_records.list_accessible_embedded_images(- None if is_admin else user_id, model_id+ kinds = _served_kinds(include_videos)+ # Both reads are SQLite work under the process-wide database lock, and on a large gallery+ # the accessible listing is the expensive one — so they run off the event loop, like the+ # clustering below.+ current_items, record = await asyncio.to_thread(+ lambda: (+ services.image_index_records.list_accessible_embedded_items(None if is_admin else user_id, model_id),+ services.image_index_records.get_projection(user_id, model_id),+ ))- record = services.image_index_records.get_projection(user_id, model_id)if record is None:- if not current_names:+ if not current_items:return ImageMapPointsResponse(points=[], state="empty", stale=False, point_count=0)enqueued = services.image_index.request_projection(user_id, all_images=is_admin)# stale means "a recompute is pending"; when nothing could be enqueued@@ -256,17 +319,17 @@ async def get_image_map_points(points=[], state="computing" if enqueued else "empty", stale=enqueued, point_count=0)- current_hash = scope_hash(model_id, current_names)+ current_hash = scope_hash(model_id, current_items)stale = record.scope_hash != current_hashif stale:services.image_index.request_projection(user_id, all_images=is_admin)- # Serve only points still in the user's current accessible set, so images+ # Serve only points still in the user's current accessible set, so items# un-shared (or deleted) since the projection was computed never leak out# of a stale cache. Filtering happens BEFORE clustering: labels computed# over hidden points would let density-chaining through an inaccessible- # image leak its existence (and be wrong besides). All of this is CPU-bound+ # item leak its existence (and be wrong besides). All of this is CPU-bound# and O(point count) — including the accessibility mask, which is a Python# membership test per cached point — so it runs off the event loop. Hoisting# the mask into the coroutine to decide the retry first cost 54ms of event@@ -274,16 +337,21 @@ async def get_image_map_points(# in the process; the retry decision is made below instead, from the one# fact it actually needs.def build_points() -> tuple[list[ImageMapPoint], Optional[float], bool, str]:- accessible = set(current_names)+ accessible = set(current_items)+ # The kind filter narrows what is SERVED, never what the scope hash covers: the+ # projection is fitted over every accessible item, so hashing a filtered set would+ # make every cached projection look permanently stale to an images-only client.visible_mask = np.fromiter(- (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)+ (item in accessible and item.kind in kinds for item in record.items),+ dtype=bool,+ count=len(record.items),)# A NaN cannot be serialized as valid JSON, so one corrupt coordinate# would fail the whole response; rows written before the projection# writer grew its isfinite guard are still out there in existing# databases.visible_mask &= np.isfinite(record.coords).all(axis=1)- visible_names = [name for name, keep in zip(record.image_names, visible_mask, strict=True) if keep]+ visible_items = [item for item, keep in zip(record.items, visible_mask, strict=True) if keep]visible_coords = record.coords[visible_mask]# Every input to the clustering is pinned by this key: which projection@@ -292,18 +360,21 @@ async def get_image_map_points(# two DBSCAN parameters. The cache is keyed by user on top of this, so# one user's labels can never be served to another even if all of these# collide.- cache_key: _ClusterCacheKey = (record.scope_hash, record.updated_at, current_hash, eps, min_samples)+ # The served kinds are part of the key: labels are computed over the visible points,+ # and an entry built for one kind filter is a different-length array for another —+ # which the zip below would refuse, 500ing whichever request read it second.+ cache_key: _ClusterCacheKey = (record.scope_hash, record.updated_at, current_hash, eps, min_samples, kinds)cached_labels = _cluster_cache_get(user_id, cache_key)if cached_labels is not None:labels, resolved_eps = cached_labelsreturn ([- ImageMapPoint(x=float(x), y=float(y), image_name=name, cluster=int(label))- for name, (x, y), label in zip(visible_names, visible_coords, labels, strict=True)+ ImageMapPoint(x=float(x), y=float(y), image_name=item.name, kind=item.kind, cluster=int(label))+ for item, (x, y), label in zip(visible_items, visible_coords, labels, strict=True)],resolved_eps,True,- scope_hash(model_id, visible_names),+ scope_hash(model_id, visible_items),)try:@@ -334,19 +405,25 @@ async def get_image_map_points(labels = np.full((visible_coords.shape[0],), -1, dtype=np.int64)return ([- ImageMapPoint(x=float(x), y=float(y), image_name=name, cluster=int(label))- for name, (x, y), label in zip(visible_names, visible_coords, labels, strict=True)+ ImageMapPoint(x=float(x), y=float(y), image_name=item.name, kind=item.kind, cluster=int(label))+ for item, (x, y), label in zip(visible_items, visible_coords, labels, strict=True)],resolved_eps,bool(visible_mask.any()),- scope_hash(model_id, visible_names),+ scope_hash(model_id, visible_items),)points, resolved_eps, any_visible, visible_hash = await asyncio.to_thread(build_points)retrying = False- if not stale and current_names and not any_visible:- # Nothing servable over a gallery that HAS embedded images: a failed+ # Only items of a kind this caller is served can evidence a failed fit. An accessible set+ # that is all videos, read by a client that asked for images, is empty for a reason the+ # projection cannot fix — and asking anyway starts the exact cycle `failed_scope` exists to+ # stop: the worker short-circuits on the matching scope hash without ever marking the scope+ # failed, emits projection_ready, and the client comes straight back with another /points.+ servable_exists = any(item.kind in kinds for item in current_items)+ if not stale and servable_exists and not any_visible:+ # Nothing servable over a gallery that HAS embedded items of this kind: a failed# fit, not a result — and it is stamped with the current scope, so# staleness will never ask for it again. `failed_scope` makes the# service refuse this once the scope's single retry is spent, so a@@ -369,12 +446,13 @@ async def get_image_map_points(class ImageMapSearchResult(BaseModel):"""One semantic search hit."""- image_name: str = Field(description="The matching image")+ image_name: str = Field(description="The matching image or video; `kind` says which namespace the name belongs to")+ kind: MediaKind = Field(description="Whether this hit is an image or a video")score: float = Field(description="Cosine similarity to the query; higher is more similar")class ImageMapSearchResponse(BaseModel):- """Semantic search results over the user's embedded images."""+ """Semantic search results over the user's embedded gallery items."""results: list[ImageMapSearchResult] = Field(description="Ranked results, most similar first")@@ -384,20 +462,25 @@ async def search_image_map(current_user: CurrentUserOrDefault,q: Optional[str] = Query(default=None, max_length=500, description="Text query to embed and search with"),image_name: Optional[str] = Query(default=None, description="Reference image for similarity search"),+ video_name: Optional[str] = Query(default=None, description="Reference video for similarity search"),limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),+ include_videos: bool = IncludeVideosQuery,) -> ImageMapSearchResponse:- """Ranks the user's accessible images by semantic similarity.+ """Ranks the user's accessible images and videos by semantic similarity.Provide exactly one of `q` (text search — requires the embedding model's- text encoder to be installed) or `image_name` (visual similarity — uses- the reference image's stored embedding when it exists, and otherwise- embeds the image file on demand, so unindexed images such as assets can- be reference images too).+ text encoder to be installed), `image_name`, or `video_name` (visual+ similarity — uses the reference item's stored embedding when it exists,+ and otherwise embeds its file on demand, so unindexed items such as assets+ can be reference items too). A video is represented by its thumbnail, the+ same frame the index embedded."""services = ApiDependencies.invoker.services- if (q is None) == (image_name is None):+ reference = _search_reference(image_name, video_name)+ if (q is None) == (reference is None):raise HTTPException(- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of q or image_name"+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="Provide exactly one of q, image_name or video_name",)model_id = services.image_index.model_id@@ -416,16 +499,19 @@ async def search_image_map(except TextSearchUnavailableError as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))else:- assert image_name is not None- assert_image_read_access(image_name, current_user)- found, matrix = services.image_index_records.get_embeddings([image_name], model_id)+ assert reference is not None+ if reference.kind == "video":+ assert_video_read_access(reference.name, current_user)+ else:+ assert_image_read_access(reference.name, current_user)+ found, matrix = services.image_index_records.get_embeddings([reference], model_id)if found:query_embedding = matrix[0]else:# Not in the index (assets and intermediates are never indexed) —# embed the stored file on demand for this one query.def embed_from_file() -> np.ndarray:- pil = services.images.get_pil_image(image_name)+ pil = _reference_image(services, reference)# Capped exactly as the uploaded/downloaded path is: the encoder# downscales to ~224px either way, and convert("RGB") on a large# stored image materializes hundreds of MB on a request thread.@@ -442,28 +528,34 @@ async def search_image_map(query_embedding = await asyncio.to_thread(embed_from_file)except HTTPException:raise- except (ImageFileNotFoundException, ImageRecordNotFoundException, OSError):+ except (ImageFileNotFoundException, ImageRecordNotFoundException, VideoRecordNotFoundException, OSError):# The stored file is missing or undecodable — the only failure- # here that is really about this image. Both record and file+ # here that is really about this item. Both record and file# exceptions are plain Exceptions rather than OSError, so they# have to be named; PIL's decode failures are OSError subclasses.- services.logger.warning(f"Image search: cannot read '{image_name}' for on-demand embed", exc_info=True)+ services.logger.warning(+ f"Image search: cannot read {reference.kind} '{reference.name}' for on-demand embed", exc_info=True+ )raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,- detail="This image could not be embedded for search (its file may be missing)",+ detail="This item could not be embedded for search (its file may be missing)",)except Exception:# An encoder fault, a stopped index, an OOM. Reporting these as# "file may be missing" sent anyone debugging to the wrong place.- services.logger.error(f"Image search: failed to embed '{image_name}' on demand", exc_info=True)+ services.logger.error(+ f"Image search: failed to embed {reference.kind} '{reference.name}' on demand", exc_info=True+ )raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail="This image could not be embedded for search",+ detail="This item could not be embedded for search",)- results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)+ results = await asyncio.to_thread(+ services.image_index.search_similar, scope_user, query_embedding, limit, _served_kinds(include_videos)+ )return ImageMapSearchResponse(- results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]+ results=[ImageMapSearchResult(image_name=item.name, kind=item.kind, score=score) for item, score in results])@@ -591,6 +683,7 @@ async def search_image_map_by_image(image: Optional[UploadFile] = File(default=None, description="Reference image file"),image_url: Optional[str] = Query(default=None, max_length=2000, description="URL of a reference image"),limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),+ include_videos: bool = IncludeVideosQuery,) -> ImageMapSearchResponse:"""Ranks the user's accessible images by similarity to an arbitrary reference image.@@ -650,9 +743,11 @@ async def search_image_map_by_image(detail="The reference could not be decoded as an image",)- results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)+ results = await asyncio.to_thread(+ services.image_index.search_similar, scope_user, query_embedding, limit, _served_kinds(include_videos)+ )return ImageMapSearchResponse(- results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]+ results=[ImageMapSearchResult(image_name=item.name, kind=item.kind, score=score) for item, score in results])@@ -687,6 +782,7 @@ async def get_image_map_cluster_labels(eps: Optional[float] = ClusterEpsQuery,min_samples: int = ClusterMinSamplesQuery,top_k: int = Query(default=3, ge=1, le=10, description="Candidate labels per cluster"),+ include_videos: bool = IncludeVideosQuery,) -> ImageMapClusterLabelsResponse:"""Labels the user's visible clusters with the most similar vocabulary phrases.@@ -716,25 +812,28 @@ async def get_image_map_cluster_labels(except TextSearchUnavailableError as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))- current_names = services.image_index_records.list_accessible_embedded_images(- None if is_admin else user_id, model_id- )+ current_items = services.image_index_records.list_accessible_embedded_items(None if is_admin else user_id, model_id)def build() -> tuple[dict[int, dict], str]:- accessible = set(current_names)+ accessible = set(current_items)+ # Exactly the mask /points applies, kind filter included: the two responses' visible+ # hashes are compared by the client, so they must cover the same set.+ kinds = _served_kinds(include_videos)mask = np.fromiter(- (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)+ (item in accessible and item.kind in kinds for item in record.items),+ dtype=bool,+ count=len(record.items),)# Exactly the mask /points applies, non-finite filter included. Without# it this endpoint's visible_hash is computed over a different set of- # names than the one /points reports, so every response the client+ # items than the one /points reports, so every response the client# receives fails the hash comparison it is told to make and all labels# are discarded — and the clustering below is handed a NaN, which# sklearn raises on, 500ing this user until their gallery changes.mask &= np.isfinite(record.coords).all(axis=1)- visible_names = [name for name, keep in zip(record.image_names, mask, strict=True) if keep]- visible_hash = scope_hash(model_id, visible_names)- if not visible_names:+ visible_items = [item for item, keep in zip(record.items, mask, strict=True) if keep]+ visible_hash = scope_hash(model_id, visible_items)+ if not visible_items:return {}, visible_hashvisible_coords = record.coords[mask]try:@@ -762,25 +861,25 @@ async def get_image_map_cluster_labels(if not clustered.any():return {}, visible_hash- cluster_by_name = dict(zip(visible_names, cluster_ids, strict=True))+ cluster_by_item = dict(zip(visible_items, cluster_ids, strict=True))# The accessible matrix comes from the same LRU the search endpoint# uses — this endpoint fires after every points refresh, and a full# BLOB read per request would not scale to large galleries.- accessible_names, accessible_matrix = services.image_index.get_accessible_embeddings(+ accessible_items, accessible_matrix = services.image_index.get_accessible_embeddings(None if is_admin else user_id)- row_by_name = {name: index for index, name in enumerate(accessible_names)}+ row_by_item = {item: index for index, item in enumerate(accessible_items)}# Noise rows are excluded here rather than inside label_clusters: they# contribute to no centroid, so gathering them only widens the copy.- found_names = [- name- for name, is_clustered in zip(visible_names, clustered, strict=True)- if is_clustered and name in row_by_name+ found_items = [+ item+ for item, is_clustered in zip(visible_items, clustered, strict=True)+ if is_clustered and item in row_by_item]- if not found_names:+ if not found_items:return {}, visible_hash- embeddings = accessible_matrix[[row_by_name[name] for name in found_names]]- aligned = np.fromiter((cluster_by_name[name] for name in found_names), dtype=np.int64, count=len(found_names))+ embeddings = accessible_matrix[[row_by_item[item] for item in found_items]]+ aligned = np.fromiter((cluster_by_item[item] for item in found_items), dtype=np.int64, count=len(found_items))return label_clusters(aligned, embeddings, vocabulary, vocab_embeddings, top_k=top_k), visible_hashlabels, visible_hash = await asyncio.to_thread(build)@@ -797,11 +896,11 @@ async def get_image_map_cluster_labels(class ImageMapImageLabelsResponse(BaseModel):- """The best vocabulary labels for one image."""+ """The best vocabulary labels for one gallery item."""label: str = Field(description="Best-matching vocabulary phrase")alternates: list[str] = Field(description="Runner-up phrases")- score: float = Field(description="Cosine similarity of the best phrase to the image's embedding")+ score: float = Field(description="Cosine similarity of the best phrase to the item's embedding")@image_map_router.get(@@ -809,13 +908,14 @@ class ImageMapImageLabelsResponse(BaseModel):)async def get_image_map_image_labels(current_user: CurrentUserOrDefault,- image_name: str = Query(description="The image to label"),+ image_name: str = Query(description="The image or video to label"),+ kind: MediaKind = Query(default="image", description="Which namespace image_name belongs to"),top_k: int = Query(default=3, ge=1, le=10, description="Number of candidate labels"),) -> ImageMapImageLabelsResponse:- """Labels one image with the vocabulary phrases most similar to its stored embedding.+ """Labels one gallery item with the vocabulary phrases most similar to its stored embedding.- Serves map hover cards, so it only covers images the index has embedded;- an unindexed image (assets, intermediates, not-yet-indexed) is a 404+ Serves map hover cards, so it only covers items the index has embedded;+ an unindexed item (assets, intermediates, not-yet-indexed) is a 404rather than an on-demand embed — a hover must never queue encoder work.Requires the embedding model's text encoder, like /cluster_labels."""@@ -824,7 +924,11 @@ async def get_image_map_image_labels(if model_id is None:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="The image index is not enabled")- assert_image_read_access(image_name, current_user)+ item = IndexedItem(kind, image_name)+ if item.kind == "video":+ assert_video_read_access(item.name, current_user)+ else:+ assert_image_read_access(item.name, current_user)try:vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)@@ -838,22 +942,22 @@ async def get_image_map_image_labels(## A stored row whose blob length disagrees with its `dim` column raises out# of `blob_to_embedding`, and a row whose dim disagrees with the vocabulary- # matrix raises out of the matmul below. Both are this one image's data+ # matrix raises out of the matmul below. Both are this one item's data# being unusable, so both answer 404 like the degenerate-vector case — an# unhandled 500 here would refire on every hover of that point, which is# once per pointer sweep rather than once per user action.try:- found, matrix = await asyncio.to_thread(services.image_index_records.get_embeddings, [image_name], model_id)+ found, matrix = await asyncio.to_thread(services.image_index_records.get_embeddings, [item], model_id)if not found:raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND, detail="This image has no stored embedding to label"+ status_code=status.HTTP_404_NOT_FOUND, detail="This item has no stored embedding to label")# float64 for the norm, and a degenerate row is refused rather than# passed through — exactly as `_normalize_query_vector` does for search# queries. Dividing by a zero or non-finite norm makes every score NaN,# and `argpartition` then returns arbitrary rows: the card would present- # three unrelated vocabulary phrases as this image's tags, with a+ # three unrelated vocabulary phrases as this item's tags, with a# `score` that serializes as JSON null against a schema that declares it# a float. The writer rejects such rows now, but ones predating that# guard are still out there — the same assumption this file already@@ -867,9 +971,11 @@ async def get_image_map_image_labels(except HTTPException:raiseexcept ValueError:- services.logger.warning(f"Image map: cannot label '{image_name}' from its stored embedding", exc_info=True)+ services.logger.warning(+ f"Image map: cannot label {item.kind} '{item.name}' from its stored embedding", exc_info=True+ )raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND, detail="This image's stored embedding cannot be labeled"+ status_code=status.HTTP_404_NOT_FOUND, detail="This item's stored embedding cannot be labeled")# Bounded by the score vector too, not just the phrase list: a cached vocab@@ -988,7 +1094,9 @@ def update_image_map_vocab(update: ImageMapVocabUpdate, current_user: AdminUserO@image_map_router.get("/status", operation_id="get_image_map_status", response_model=ImageMapStatusResponse)-def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:+def get_image_map_status(+ current_user: CurrentUserOrDefault, include_videos: bool = IncludeVideosQuery+) -> ImageMapStatusResponse:"""Gets embedding index progress and the user's projection cache status."""services = ApiDependencies.invoker.servicesmodel_id = _active_model_id(services)@@ -1007,15 +1115,17 @@ def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusReif record is None:projection = ImageMapProjectionStatus(state="empty", stale=False, point_count=0)else:- current_names = services.image_index_records.list_accessible_embedded_images(+ current_items = services.image_index_records.list_accessible_embedded_items(None if is_admin else user_id, model_id)# Count only currently-accessible points; a stale record's raw count- # would reveal the size of a since-revoked scope.- visible_count = len(set(record.image_names) & set(current_names))+ # would reveal the size of a since-revoked scope. Kinds the caller did not ask for are+ # excluded too, so this count matches the points /points would serve it.+ kinds = _served_kinds(include_videos)+ visible_count = len({item for item in set(record.items) & set(current_items) if item.kind in kinds})projection = ImageMapProjectionStatus(state="ready" if visible_count else "empty",- stale=record.scope_hash != scope_hash(model_id, current_names),+ stale=record.scope_hash != scope_hash(model_id, current_items),point_count=visible_count,updated_at=record.updated_at,)diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 154c55141c..f4640c3653 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -142,10 +142,10 @@ class InvokeAIAppConfig(BaseSettings):allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.- image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.- image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.+ image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.- image_index_batch_size: Number of images embedded per batch by the image index worker.+ image_index_batch_size: Number of gallery items embedded per batch by the image index worker.external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.external_gemini_api_key: API key for Gemini image generation.@@ -274,10 +274,10 @@ class InvokeAIAppConfig(BaseSettings):strict_password_checking: bool = Field(default=False, description="Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.")# IMAGE INDEX- image_index_enabled: bool = Field(default=True, description="Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.")- image_index_model: str = Field(default="DFN2B-CLIP-ViT-L-14-39B", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.")+ image_index_enabled: bool = Field(default=True, description="Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.")+ image_index_model: str = Field(default="DFN2B-CLIP-ViT-L-14-39B", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.")image_index_device: Optional[str] = Field(default=None, description="Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.")- image_index_batch_size: int = Field(default=8, gt=0, description="Number of images embedded per batch by the image index worker.")+ image_index_batch_size: int = Field(default=8, gt=0, description="Number of gallery items embedded per batch by the image index worker.")# EXTERNAL PROVIDERSexternal_alibabacloud_api_key: Optional[str] = Field(default=None, description="API key for Alibaba Cloud DashScope image generation.")diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex 41ce558a00..9dea4217d9 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -4,7 +4,7 @@ from typing import Literal, Optionalimport numpy as npfrom PIL import Image-from invokeai.app.services.image_index.image_index_common import ImageIndexStatus+from invokeai.app.services.image_index.image_index_common import ImageIndexStatus, IndexedItem, MediaKindclass TextSearchUnavailableError(Exception):@@ -20,12 +20,15 @@ VocabBuildState = Literal["unavailable", "idle", "building", "ready", "error"]class ImageIndexServiceBase(ABC):- """Background service that keeps the semantic image index up to date.+ """Background service that keeps the semantic index up to date.When enabled and an embedding model is available, the service embeds every- eligible gallery image (non-intermediate, `general` category) on a worker- thread: a backfill pass covers images that existed before the service- started, and image-service callbacks cover images created afterwards.+ eligible gallery item (non-intermediate, `general` category) on a worker+ thread: a backfill pass covers items that existed before the service+ started, and image- and video-service callbacks cover items created+ afterwards. A video is embedded through its thumbnail — the representative+ frame extracted when the video was created — so it takes part in the map+ and in search exactly as an image does."""@property@@ -80,11 +83,11 @@ class ImageIndexServiceBase(ABC):pass@abstractmethod- def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:- """Names + L2-normalized embedding matrix of the user's accessible images.+ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[IndexedItem], np.ndarray]:+ """Items + L2-normalized embedding matrix of the user's accessible gallery.Served from a small LRU keyed by the accessible-set scope hash (which- self-invalidates on any set change). Rows align with names. Pass+ self-invalidates on any set change). Rows align with items. Passuser_id=None for the admin scope. Call off the event loop."""pass@@ -126,13 +129,20 @@ class ImageIndexServiceBase(ABC):pass@abstractmethod- def 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.+ def search_similar(+ self,+ user_id: str | None,+ query_embedding: np.ndarray,+ limit: int,+ kinds: Optional[tuple[MediaKind, ...]] = None,+ ) -> list[tuple[IndexedItem, float]]:+ """Rank the user's accessible embedded items by cosine similarity.Embeddings are L2-normalized, so similarity is a dot product. Pass- user_id=None for the admin scope. Returns (image_name, score) pairs,- best first. Call off the event loop — the accessible embedding matrix- may be read from the database on a cache miss.+ user_id=None for the admin scope, and `kinds` to restrict results to+ those media kinds (None means every kind). Returns (item, score)+ pairs, best first. Call off the event loop — the accessible embedding+ matrix may be read from the database on a cache miss."""pass@@ -152,7 +162,7 @@ class ImageIndexServiceBase(ABC):Args:user_id: The user whose projection cache to update.- all_images: Compute over every embedded image (admin scope)+ all_images: Compute over every embedded item (admin scope)rather than the user's accessible set.failed_scope: The scope hash of a cached projection the callerbelieves to be a failed fit. The request is refused once thatdiff --git a/invokeai/app/services/image_index/image_index_common.py b/invokeai/app/services/image_index/image_index_common.pyindex 44b6b6b6dd..19057ec2b0 100644--- a/invokeai/app/services/image_index/image_index_common.py+++ b/invokeai/app/services/image_index/image_index_common.py@@ -1,19 +1,42 @@"""Common types and helpers for the semantic image index services."""+from typing import Literal, NamedTuple+import numpy as npfrom pydantic import BaseModel, ConfigDict, FieldEMBEDDING_DTYPE = np.float32+MediaKind = Literal["image", "video"]+++class IndexedItem(NamedTuple):+ """One indexable gallery item.++ Images and videos are separate namespaces — separate tables, separate access joins,+ separate URLs — so an indexed item is addressed by both. Names are server-assigned and+ unique across both namespaces in practice, but the kind is what tells a client which+ endpoint resolves the name, and the index never has to guess it from an extension.++ A NamedTuple so it can key the worker's pending/failure bookkeeping and be compared and+ sorted without ceremony.+ """++ kind: MediaKind+ name: str+class ImageIndexStatus(BaseModel):- """Progress of the embedding index for one embedding model."""+ """Progress of the embedding index for one embedding model.++ Counts cover both media kinds: an indexed gallery is its images plus its videos.+ """- total: int = Field(description="Number of gallery images eligible for indexing")- embedded: int = Field(description="Number of eligible images that have an embedding")+ total: int = Field(description="Number of gallery items (images and videos) eligible for indexing")+ embedded: int = Field(description="Number of eligible items that have an embedding")failed: int = Field(default=0,- description="Eligible images that repeatedly failed to embed; excluded from pending so it can drain",+ description="Eligible items that repeatedly failed to embed; excluded from pending so it can drain",)@property@@ -25,16 +48,16 @@ class ImageIndexStatus(BaseModel):class ProjectionRecord(BaseModel):- """A cached 2D projection of a user's accessible images."""+ """A cached 2D projection of a user's accessible gallery items."""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")+ scope_hash: str = Field(description="Fingerprint of the item 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")+ items: list[IndexedItem] = Field(description="Indexed items, 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")diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 969a3468b0..6c2e00056d 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -14,11 +14,17 @@ from invokeai.app.services.image_index.image_index_base import (TextSearchUnavailableError,VocabBuildState,)-from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, ImageIndexStatus+from invokeai.app.services.image_index.image_index_common import (+ EMBEDDING_DTYPE,+ ImageIndexStatus,+ IndexedItem,+ MediaKind,+)from invokeai.app.services.image_index.projection import compute_umap, projection_params, scope_hashfrom invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.images.images_common import ImageDTOfrom invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID+from invokeai.app.services.videos.videos_common import VideoDTOfrom invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCKfrom invokeai.backend.model_manager.load.optimizations import skip_torch_weight_initfrom invokeai.backend.model_manager.taxonomy import ModelType@@ -210,13 +216,17 @@ _ACTIVATION_RETRY_INTERVAL_S = 5.0class ImageIndexService(ImageIndexServiceBase):- """Embeds gallery images on a daemon worker thread.+ """Embeds gallery images and videos on a daemon worker thread.++ A video is embedded through the thumbnail the video file store extracted+ when it was created, so indexing one costs exactly what indexing an image+ costs and needs no decoder here.- The image-service callbacks only enqueue work and set a status-dirty- flag — they fire synchronously on the caller's thread and must never do- I/O. All embedding and all status emission happens on the worker, which- pauses while a generation is in progress unless it is configured to run- on the CPU.+ The image- and video-service callbacks only enqueue work and set a+ status-dirty flag — they fire synchronously on the caller's thread and+ must never do I/O. All embedding and all status emission happens on the+ worker, which pauses while a generation is in progress unless it is+ configured to run on the CPU."""def __init__(self, encode_fn: Optional[EncodeFn] = None, model_id: Optional[str] = None) -> None:@@ -230,15 +240,15 @@ class ImageIndexService(ImageIndexServiceBase):self._encode_fn_override = encode_fnself._model_id_override = model_id- self._queue: Queue[str] = Queue()- self._pending: set[str] = set()+ self._queue: Queue[IndexedItem] = Queue()+ self._pending: set[IndexedItem] = set()self._pending_lock = threading.Lock()- # Per-image failure counts; after _MAX_ATTEMPTS the name moves to+ # Per-item failure counts; after _MAX_ATTEMPTS the item moves to# _failed, which is excluded from backfill so a bad file cannot make# the backfill loop spin forever. Transient failures get retried.- self._attempts: dict[str, int] = {}- self._failed: set[str] = set()- # Consecutive failures of the machinery rather than of any image. Drives the retry+ self._attempts: dict[IndexedItem, int] = {}+ self._failed: set[IndexedItem] = set()+ # Consecutive failures of the machinery rather than of any item. Drives the retry# backoff and is reset by the first batch that stores anything. Worker-thread only.self._systemic_failures = 0self._stop_event = threading.Event()@@ -315,9 +325,9 @@ class ImageIndexService(ImageIndexServiceBase):# Guards the lazy _processor/_cpu_model init: embed_image runs on# request threads concurrently with the indexer worker.self._vision_init_lock = threading.Lock()- # scope_hash -> (names, matrix): the accessible embedding matrix for+ # scope_hash -> (items, matrix): the accessible embedding matrix for# similarity search, so repeated queries skip re-reading BLOBs.- self._search_cache: dict[str, tuple[list[str], np.ndarray]] = {}+ self._search_cache: dict[str, tuple[list[IndexedItem], np.ndarray]] = {}self._search_cache_lock = threading.Lock()# (vocabulary, embeddings) for cluster labeling; RAM + disk cached.self._vocab_cache: Optional[tuple[list[str], np.ndarray]] = None@@ -639,20 +649,20 @@ class ImageIndexService(ImageIndexServiceBase):self._text_encoder = (tokenizer, model, is_siglip)return self._text_encoder- def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:+ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[IndexedItem], np.ndarray]:if self._invoker is None or self._model_id is None:return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)records = self._invoker.services.image_index_records- names = records.list_accessible_embedded_images(user_id, self._model_id)- if not names:+ items = records.list_accessible_embedded_items(user_id, self._model_id)+ if not items:return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)# Memory math: one entry is N x dim float32 (~300 MB at 100k x 768),# so the LRU holds two entries and evicts oldest-first rather than# clearing wholesale. Keys self-invalidate: any change to the# accessible set changes the scope hash.- cache_key = scope_hash(self._model_id, names)+ cache_key = scope_hash(self._model_id, items)with self._search_cache_lock:cached = self._search_cache.get(cache_key)if cached is not None:@@ -663,7 +673,7 @@ class ImageIndexService(ImageIndexServiceBase):# Built outside the lock: a concurrent miss for the same scope# transiently builds a duplicate, which beats serializing every# search behind a multi-second BLOB read.- cached = records.get_embeddings(names, self._model_id)+ cached = records.get_embeddings(items, self._model_id)with self._search_cache_lock:while len(self._search_cache) >= 2:self._search_cache.pop(next(iter(self._search_cache)))@@ -671,16 +681,32 @@ class ImageIndexService(ImageIndexServiceBase):return cached- def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:- found_names, matrix = self.get_accessible_embeddings(user_id)+ def search_similar(+ self,+ user_id: str | None,+ query_embedding: np.ndarray,+ limit: int,+ kinds: Optional[tuple[MediaKind, ...]] = None,+ ) -> list[tuple[IndexedItem, float]]:+ found_items, matrix = self.get_accessible_embeddings(user_id)if matrix.size == 0:return []scores = matrix @ query_embedding.astype(matrix.dtype)- top = min(limit, len(found_names))+ # Restricting by kind selects among the SCORES, not among the rows: masking the matrix+ # would copy it, and it is the largest array in the process (~300 MB at 100k x 768).+ # The dot product over rows nobody asked for is a rounding error beside that.+ candidates = np.arange(len(found_items))+ if kinds is not None:+ candidates = candidates[[found_items[index].kind in kinds for index in candidates]]+ if candidates.size == 0:+ return []+ scores = scores[candidates]++ top = min(limit, candidates.size)order = np.argpartition(-scores, top - 1)[:top]order = order[np.argsort(-scores[order])]- return [(found_names[index], float(scores[index])) for index in order]+ return [(found_items[candidates[index]], float(scores[index])) for index in order]def request_projection(self,@@ -848,12 +874,12 @@ class ImageIndexService(ImageIndexServiceBase):"""Wire the image callbacks and start the worker thread. Runs once per active model."""discarded = invoker.services.image_index_records.delete_embeddings_for_other_models(self._model_id)if discarded:- invoker.services.logger.info(- f"Discarded {discarded} image embeddings computed by a previously-configured model"- )+ invoker.services.logger.info(f"Discarded {discarded} embeddings computed by a previously-configured model")invoker.services.images.on_changed(self._on_image_changed)invoker.services.images.on_deleted(self._on_image_deleted)+ invoker.services.videos.on_changed(self._on_video_changed)+ invoker.services.videos.on_deleted(self._on_video_deleted)self._backfill_pending.set()self._stop_event.clear()@@ -873,40 +899,61 @@ class ImageIndexService(ImageIndexServiceBase):"Image index worker did not stop within 10s (likely mid-encode); abandoning daemon thread")- # --- Image service callbacks (caller's thread — enqueue and flag only, never I/O) ---+ # --- Media service callbacks (caller's thread — enqueue and flag only, never I/O) ---def _on_image_changed(self, image_dto: ImageDTO) -> None:- if image_dto.is_intermediate or image_dto.image_category != ImageCategory.GENERAL:- # The image may have just LEFT eligibility (e.g. adopted as a- # canvas asset). Drop any failure bookkeeping so a name no longer+ self._on_item_changed(+ IndexedItem("image", image_dto.image_name),+ eligible=not image_dto.is_intermediate and image_dto.image_category is ImageCategory.GENERAL,+ )++ def _on_image_deleted(self, image_name: str) -> None:+ self._on_item_deleted(IndexedItem("image", image_name))++ def _on_video_changed(self, video_dto: VideoDTO) -> None:+ self._on_item_changed(+ IndexedItem("video", video_dto.video_name),+ # Videos carry the image category enum; `general` is the gallery's, exactly as for+ # images. A video is enqueued from here rather than from its own creation path+ # because this fires after the file store has written the thumbnail the embed reads.+ eligible=not video_dto.is_intermediate and video_dto.video_category is ImageCategory.GENERAL,+ )++ def _on_video_deleted(self, video_name: str) -> None:+ self._on_item_deleted(IndexedItem("video", video_name))++ def _on_item_changed(self, item: IndexedItem, eligible: bool) -> None:+ if not eligible:+ # The item may have just LEFT eligibility (e.g. an image adopted as+ # a canvas asset). Drop any failure bookkeeping so an item no longer# counted in the totals cannot skew `failed` (and thus `pending`)# for the rest of the process. Flag only when something was# actually forgotten — this branch also fires for every# intermediate save during generation, which must stay silent.- if image_dto.image_name in self._failed:- self._failed.discard(image_dto.image_name)- self._attempts.pop(image_dto.image_name, None)+ if item in self._failed:+ self._failed.discard(item)+ self._attempts.pop(item, None)self._status_dirty.set()returnwith self._pending_lock:- if image_dto.image_name in self._pending:+ if item in self._pending:return- self._pending.add(image_dto.image_name)- # Flagged before the enqueue so the worker reports the image as+ self._pending.add(item)+ # Flagged before the enqueue so the worker reports the item as# pending before it starts (and certainly before it finishes) the# embed. The worker does the emit: callbacks stay free of DB reads# (which could block the generation thread behind the worker's own# long transactions), and single-threaded emission means events can# never be dispatched with out-of-order counts.self._status_dirty.set()- self._queue.put(image_dto.image_name)+ self._queue.put(item)- def _on_image_deleted(self, image_name: str) -> None:- # The DB row is removed by the images FK cascade; just forget local state.+ def _on_item_deleted(self, item: IndexedItem) -> None:+ # The DB row is removed by the images/videos FK cascade; just forget local state.with self._pending_lock:- self._pending.discard(image_name)- self._failed.discard(image_name)- self._attempts.pop(image_name, None)+ self._pending.discard(item)+ self._failed.discard(item)+ self._attempts.pop(item, None)# A deletion gives the worker nothing to embed, so this flag is the# only signal clients get that the index shrank; the worker notices# within its poll interval. Bulk deletes coalesce into one emit.@@ -1039,8 +1086,8 @@ class ImageIndexService(ImageIndexServiceBase):self._status_dirty.set()self._stop_event.wait(_POLL_SECONDS)- def _next_batch(self) -> Optional[list[str]]:- """Get the next batch of image names, preferring backfill work.+ def _next_batch(self) -> Optional[list[IndexedItem]]:+ """Get the next batch of items, preferring backfill work.Returns None when there is nothing to do right now."""@@ -1049,12 +1096,12 @@ class ImageIndexService(ImageIndexServiceBase):if self._backfill_pending.is_set():assert self._model_id is not None- # Over-fetch by the failed count so permanently-failing images+ # Over-fetch by the failed count so permanently-failing items# cannot occlude the rest of the backlog.- candidates = self._invoker.services.image_index_records.list_unembedded_image_names(+ candidates = self._invoker.services.image_index_records.list_unembedded_items(self._model_id, limit=batch_size + len(self._failed))- batch = [name for name in candidates if name not in self._failed][:batch_size]+ batch = [item for item in candidates if item not in self._failed][:batch_size]if batch:return batchself._backfill_pending.clear()@@ -1072,7 +1119,7 @@ class ImageIndexService(ImageIndexServiceBase):breakreturn batch- def _process_batch(self, image_names: list[str]) -> bool:+ def _process_batch(self, items: list[IndexedItem]) -> bool:"""Embed one batch. Returns False when anything in it failed."""assert self._invoker is not Noneassert self._encode_fn is not None@@ -1081,28 +1128,28 @@ class ImageIndexService(ImageIndexServiceBase):try:images: list[Image.Image] = []- loaded_names: list[str] = []- for name in image_names:+ loaded: list[IndexedItem] = []+ for item in items:try:- images.append(self._invoker.services.images.get_pil_image(name).convert("RGB"))- loaded_names.append(name)+ images.append(self._load_item_image(item))+ loaded.append(item)except Exception as e:- logger.warning(f"Image index: could not load '{name}' ({e})")- self._record_failure([name])+ logger.warning(f"Image index: could not load {item.kind} '{item.name}' ({e})")+ self._record_failure([item])- if not loaded_names:+ if not loaded:return Falsetry:embeddings = np.asarray(self._encode_fn(images), dtype=EMBEDDING_DTYPE)except Exception:- logger.exception(f"Image index: failed to embed a batch of {len(loaded_names)} images")- self._attribute_batch_failure("the encoder raised", loaded_names)+ logger.exception(f"Image index: failed to embed a batch of {len(loaded)} items")+ self._attribute_batch_failure("the encoder raised", loaded)return False- if embeddings.ndim != 2 or embeddings.shape[0] != len(loaded_names):- logger.error(f"Image index: encoder returned shape {embeddings.shape} for {len(loaded_names)} images")- self._attribute_batch_failure("the encoder returned an unusable result", loaded_names)+ if embeddings.ndim != 2 or embeddings.shape[0] != len(loaded):+ logger.error(f"Image index: encoder returned shape {embeddings.shape} for {len(loaded)} items")+ self._attribute_batch_failure("the encoder returned an unusable result", loaded)return False# L2-normalize so cosine similarity is a plain dot product downstream. The norm is@@ -1113,43 +1160,43 @@ class ImageIndexService(ImageIndexServiceBase):# A row whose norm is zero or non-finite cannot be normalized: it stays all-zero or# becomes non-finite, either of which the storage layer rejects because it yields NaN# in every similarity it takes part in. Drop those rows and fail only their own- # names — the old `norms[norms == 0] = 1.0` handed an all-zero vector straight to+ # items — the old `norms[norms == 0] = 1.0` handed an all-zero vector straight to# upsert_embedding, whose ValueError then failed the whole batch.degenerate = ~np.isfinite(norms).all(axis=1) | (norms[:, 0] == 0)if degenerate.any():- dropped = [name for name, bad in zip(loaded_names, degenerate, strict=True) if bad]+ dropped = [item for item, bad in zip(loaded, degenerate, strict=True) if bad]logger.warning(f"Image index: encoder returned unusable embeddings for {dropped}")self._record_failure(dropped)keep = ~degenerate- # Reassigned before `stored` and the handler below, so dropped names are already+ # Reassigned before `stored` and the handler below, so dropped items are already# accounted for and cannot be failed a second time. Shrinking it also makes the- # `len(loaded_names) == len(image_names)` return False, which re-arms the- # backfill so these images are retried rather than stranded.- loaded_names = [name for name, ok in zip(loaded_names, keep, strict=True) if ok]+ # `len(loaded) == len(items)` return False, which re-arms the backfill so these+ # items are retried rather than stranded.+ loaded = [item for item, ok in zip(loaded, keep, strict=True) if ok]embeddings = embeddings[keep]norms = norms[keep]embeddings = (embeddings / norms).astype(np.float32)- stored: list[str] = []+ stored: list[IndexedItem] = []try:- for name, embedding in zip(loaded_names, embeddings, strict=True):- # Deliberately not caught per-image: any exception from here must reach the- # handler below, which fails every unstored name and returns False to re-arm- # the backfill. Swallowing one image's error here would leave it unembedded+ for item, embedding in zip(loaded, embeddings, strict=True):+ # Deliberately not caught per-item: any exception from here must reach the+ # handler below, which fails every unstored item and returns False to re-arm+ # the backfill. Swallowing one item's error here would leave it unembedded# with no retry ever scheduled, wedging `pending` above zero.- self._invoker.services.image_index_records.upsert_embedding(name, self._model_id, embedding)- stored.append(name)- self._attempts.pop(name, None)- # An image that recovers (e.g. re-embedded after an+ self._invoker.services.image_index_records.upsert_embedding(item, self._model_id, embedding)+ stored.append(item)+ self._attempts.pop(item, None)+ # An item that recovers (e.g. re-embedded after an# update) must stop counting against the failed total.- self._failed.discard(name)+ self._failed.discard(item)except Exception:# A raise here (e.g. "database is locked") is a property of the database, not of- # any image, so it is systemic: the unstored names stay pending and are retried+ # any item, so it is systemic: the unstored items stay pending and are retried# rather than being charged an attempt each.- logger.exception(f"Image index: failed to store embeddings for a batch of {len(loaded_names)} images")+ logger.exception(f"Image index: failed to store embeddings for a batch of {len(loaded)} items")self._record_systemic_failure(- "storing embeddings failed", [name for name in loaded_names if name not in stored]+ "storing embeddings failed", [item for item in loaded if item not in stored])return Falsefinally:@@ -1158,28 +1205,43 @@ class ImageIndexService(ImageIndexServiceBase):# Anything stored proves the encoder and the database are both working, so# the outage (if there was one) is over and the backoff resets. In the# `finally` deliberately, i.e. reached even when the handler above has just- # counted a failure: a batch that stores ANY image is making progress, so+ # counted a failure: a batch that stores ANY item is making progress, so# the backlog drains and quiescence arrives on its own. Moving this to the# success path instead left the counter with no reset while every batch# partially failed, which escalated the wait to its 60s ceiling — a far# worse outcome under mild write contention than the flat 1Hz retry it was# meant to fix.self._systemic_failures = 0- return len(loaded_names) == len(image_names)+ return len(loaded) == len(items)finally:- # Always release the batch from the dedup set — a name stuck in+ # Always release the batch from the dedup set — an item stuck in# _pending can never be re-enqueued by callbacks.- self._forget_pending(image_names)+ self._forget_pending(items)- def _attribute_batch_failure(self, reason: str, image_names: list[str]) -> None:- """Charge a whole-batch embedding failure to the images or to the machinery."""+ def _load_item_image(self, item: IndexedItem) -> Image.Image:+ """The pixels an item is embedded from, as RGB.++ An image is embedded from the image itself; a video from the thumbnail the video file+ store extracted when it was created. The thumbnail is a real frame of the video, and at+ 256px it is already larger than the 224px the vision towers resize to — so embedding it+ costs nothing extra and needs no decoder on this path.+ """+ assert self._invoker is not None+ if item.kind == "video":+ path = self._invoker.services.videos.get_path(item.name, thumbnail=True)+ with Image.open(path) as thumbnail:+ return thumbnail.convert("RGB")+ return self._invoker.services.images.get_pil_image(item.name).convert("RGB")++ def _attribute_batch_failure(self, reason: str, items: list[IndexedItem]) -> None:+ """Charge a whole-batch embedding failure to the items or to the machinery."""if self._encoder_is_healthy():- # The encoder works on a trivial image, so something about these images is what+ # The encoder works on a trivial image, so something about these items is what# broke it. Charge them, so a poisonous one is quarantined after _MAX_ATTEMPTS and# stops blocking the rest of the backlog.- self._record_failure(image_names)+ self._record_failure(items)else:- self._record_systemic_failure(reason, image_names)+ self._record_systemic_failure(reason, items)def _encoder_is_healthy(self) -> bool:"""Probe the encoder with a trivial image to tell a broken encoder from bad input.@@ -1189,9 +1251,9 @@ class ImageIndexService(ImageIndexServiceBase):image in the batch may be corrupt. Repetition cannot separate the two — a real outageand a poisonous image both fail every time — so the encoder is asked directly.- A healthy encoder means the batch failed because of its contents, and the images are+ A healthy encoder means the batch failed because of its contents, and the items arecharged an attempt so a bad one is eventually quarantined and the backfill can move past- it. An unhealthy one means the machinery is down, and the images must not be charged.+ it. An unhealthy one means the machinery is down, and the items must not be charged."""assert self._encode_fn is not Nonetry:@@ -1200,19 +1262,19 @@ class ImageIndexService(ImageIndexServiceBase):return Falsereturn probe.ndim == 2 and probe.shape[0] == 1 and probe.shape[1] > 0- def _record_systemic_failure(self, reason: str, image_names: list[str]) -> None:- """Record a failure of the machinery: back off, but charge no image for it.+ def _record_systemic_failure(self, reason: str, items: list[IndexedItem]) -> None:+ """Record a failure of the machinery: back off, but charge no item for it.`_MAX_ATTEMPTS` exists so one bad file cannot spin the backfill forever. Charging an- outage against that budget instead retires every image the outage touched, and because+ outage against that budget instead retires every item the outage touched, and becausenothing clears `_failed` but a successful embed, restoring the model would not bring- them back — only a restart would. The images stay pending here, so the sweep retries+ them back — only a restart would. The items stay pending here, so the sweep retriesthem once the machinery recovers, and `pending` keeps telling the truth meanwhile."""assert self._invoker is not Noneself._systemic_failures += 1self._invoker.services.logger.warning(- f"Image index: {reason}; leaving {len(image_names)} image(s) pending for retry "+ f"Image index: {reason}; leaving {len(items)} item(s) pending for retry "f"(consecutive failures: {self._systemic_failures})")@@ -1222,17 +1284,17 @@ class ImageIndexService(ImageIndexServiceBase):# Cap the exponent before the shift so a long outage cannot overflow it.return min(_POLL_SECONDS * (2 ** min(self._systemic_failures - 1, 16)), _MAX_BACKOFF_SECONDS)- def _record_failure(self, image_names: list[str]) -> None:- """Count a failure; move an image to the permanent-failure set only after repeated attempts."""- for name in image_names:- attempts = self._attempts.get(name, 0) + 1- self._attempts[name] = attempts+ def _record_failure(self, items: list[IndexedItem]) -> None:+ """Count a failure; move an item to the permanent-failure set only after repeated attempts."""+ for item in items:+ attempts = self._attempts.get(item, 0) + 1+ self._attempts[item] = attemptsif attempts >= _MAX_ATTEMPTS:- self._failed.add(name)+ self._failed.add(item)- def _forget_pending(self, image_names: list[str]) -> None:+ def _forget_pending(self, items: list[IndexedItem]) -> None:with self._pending_lock:- self._pending.difference_update(image_names)+ self._pending.difference_update(items)# --- Projections ---@@ -1283,8 +1345,8 @@ class ImageIndexService(ImageIndexServiceBase):scope_user = None if all_images else user_idtry:- names = records.list_accessible_embedded_images(scope_user, self._model_id)- current_hash = scope_hash(self._model_id, names)+ items = records.list_accessible_embedded_items(scope_user, self._model_id)+ current_hash = scope_hash(self._model_id, items)cached = records.get_projection(user_id, self._model_id)except Exception:# The DB reads are as failure-prone as the fit ("database is@@ -1311,7 +1373,7 @@ class ImageIndexService(ImageIndexServiceBase):# empty coords array reduces to False here too, so this subsumes the# count test rather than replacing it.and not np.isfinite(cached.coords).all(axis=1).any()- and bool(names)+ and bool(items)and self._failed_scope_retry_available(user_id, current_hash))if cached is not None and cached.scope_hash == current_hash and not retrying_failed_scope:@@ -1328,7 +1390,7 @@ class ImageIndexService(ImageIndexServiceBase):# Read after the short-circuit, not before: this materializes every# accessible embedding (hundreds of MB on a large gallery), which is# pure waste on the no-op path that /points and /refresh drive.- found_names, matrix = records.get_embeddings(names, self._model_id)+ found_items, matrix = records.get_embeddings(items, self._model_id)except Exception:logger.exception(f"Image map: could not read embeddings for user '{user_id}'; re-queueing")self._requeue_projection(user_id, all_images)@@ -1342,8 +1404,8 @@ class ImageIndexService(ImageIndexServiceBase):try:coords = compute_umap(matrix)- if coords.shape[0] != len(found_names):- raise RuntimeError(f"projection produced {coords.shape[0]} points for {len(found_names)} images")+ if coords.shape[0] != len(found_items):+ raise RuntimeError(f"projection produced {coords.shape[0]} points for {len(found_items)} items")if not np.isfinite(coords).all():# A NaN reaching the cache makes /points raise inside sklearn# on every request, and the cache is only replaced when the@@ -1351,13 +1413,13 @@ class ImageIndexService(ImageIndexServiceBase):# Treat it as a failed fit and take the empty-cache path.raise RuntimeError("projection produced non-finite coordinates")except Exception:- logger.exception(f"Image map: UMAP projection failed for user '{user_id}' ({len(found_names)} points)")+ logger.exception(f"Image map: UMAP projection failed for user '{user_id}' ({len(found_items)} points)")# Cache an empty projection under the CURRENT scope hash. Serving# "empty" is honest, and it stops the client from re-enqueueing a# doomed recompute on every poll. It does NOT make the failure# terminal: _failed_scope_retry_available grants this scope one more fit# per process, and the next gallery change flips the hash anyway.- found_names = []+ found_items = []coords = np.empty((0, 2), dtype=EMBEDDING_DTYPE)# Hash the scope the projection was computed against (on failure the@@ -1368,8 +1430,8 @@ class ImageIndexService(ImageIndexServiceBase):user_id,self._model_id,current_hash,- projection_params(n_points=len(found_names)),- found_names,+ projection_params(n_points=len(found_items)),+ found_items,coords,)except Exception:@@ -1389,7 +1451,7 @@ class ImageIndexService(ImageIndexServiceBase):# here means the budget is charged for exactly what it is meant to# bound: a failed fit that reached the cache.with self._projection_lock:- if found_names:+ if found_items:# A fit that produced points clears the marker, so a LATER# failure over some future scope gets its own retry rather than# inheriting this one's spent budget.@@ -1397,7 +1459,7 @@ class ImageIndexService(ImageIndexServiceBase):elif retrying_failed_scope:self._failed_projection_scopes[user_id] = current_hashtry:- self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_names))+ self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_items))except Exception:# The row is cached, so a polling client recovers on its own; only# an event-driven client would hang. Log rather than unwind into@@ -1459,18 +1521,21 @@ class ImageIndexService(ImageIndexServiceBase):total=status.total, embedded=status.embedded, pending=status.pending, failed=status.failed)- def _record_owner_pokes(self, image_names: list[str]) -> None:+ def _record_owner_pokes(self, items: list[IndexedItem]) -> None:"""Queue a per-user poke for each owner of freshly stored embeddings.The status event is admin-only (its counts aggregate every user's- images), so without this, non-admin clients would never hear that+ items), so without this, non-admin clients would never hear thattheir own generations reached the index. Owner lookups are DB reads,which is fine here: this runs on the worker thread."""assert self._invoker is not None- for name in image_names:+ for item in items:try:- user_id = self._invoker.services.image_records.get_user_id(name)+ if item.kind == "video":+ user_id = self._invoker.services.video_records.get_user_id(item.name)+ else:+ user_id = self._invoker.services.image_records.get_user_id(item.name)except Exception:continueif user_id:diff --git a/invokeai/app/services/image_index/image_index_records_base.py b/invokeai/app/services/image_index/image_index_records_base.pyindex 0d6bbdae06..c285e4e035 100644--- a/invokeai/app/services/image_index/image_index_records_base.py+++ b/invokeai/app/services/image_index/image_index_records_base.py@@ -2,18 +2,20 @@ from abc import ABC, abstractmethodimport numpy as np-from invokeai.app.services.image_index.image_index_common import ImageIndexStatus, ProjectionRecord+from invokeai.app.services.image_index.image_index_common import ImageIndexStatus, IndexedItem, ProjectionRecordclass ImageIndexRecordsBase(ABC):- """Storage for the semantic image index.+ """Storage for the semantic index over gallery images and videos.- 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.+ Embeddings are global: one row per (item, model_id), shared by every user+ who can access the item. Projections are per-user caches over the set of+ items that user can access.- Only "gallery" images are indexed: non-intermediate images in the- `general` category.+ Only "gallery" items are indexed: non-intermediate images and videos in+ the `general` category. Each media kind has its own embedding table, so an+ embedding is deleted with its media by foreign key and eligibility and+ board access are answered from that kind's own tables.Every method here is its own unit of work and must not be called from inside anotherservice's open transaction. `SqliteDatabase.transaction()` commits and rolls back the whole@@ -23,10 +25,10 @@ class ImageIndexRecordsBase(ABC):"""@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.+ def upsert_embedding(self, item: IndexedItem, model_id: str, embedding: np.ndarray) -> None:+ """Insert or replace the embedding for an item under the given model.- A no-op if the image no longer exists (it may be deleted between being+ A no-op if the item no longer exists (it may be deleted between beingscheduled for embedding and the write landing).All embeddings stored under one model_id must share the same dim;@@ -39,14 +41,14 @@ class ImageIndexRecordsBase(ABC):pass@abstractmethod- def get_embeddings(self, image_names: list[str], model_id: str) -> tuple[list[str], np.ndarray]:- """Fetch embeddings for the given images.+ def get_embeddings(self, items: list[IndexedItem], model_id: str) -> tuple[list[IndexedItem], np.ndarray]:+ """Fetch embeddings for the given items.- Duplicate input names are deduplicated, preserving first-seen order.+ Duplicate input items 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+ A tuple of (found_items, matrix) where matrix has shape+ (len(found_items), dim) and rows align with found_items. Itemswithout a stored embedding are silently omitted.When nothing matches, the matrix is empty with shape (0, 0): no row was read, so@@ -56,8 +58,8 @@ class ImageIndexRecordsBase(ABC):pass@abstractmethod- def delete_embedding(self, image_name: str) -> None:- """Delete all stored embeddings for an image (across all models)."""+ def delete_embedding(self, item: IndexedItem) -> None:+ """Delete all stored embeddings for an item (across all models)."""pass@abstractmethod@@ -73,29 +75,35 @@ class ImageIndexRecordsBase(ABC):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."""+ def list_unembedded_items(self, model_id: str, limit: int) -> list[IndexedItem]:+ """List eligible items that have no embedding under the given model, oldest first.++ Both media kinds are merged into one sequence by creation time, so the batch is the+ oldest work in the gallery rather than every image before any video. It is strict+ FIFO, not a per-kind quota: a large backlog of old images is indexed before newer+ videos, exactly as an all-image backlog is indexed in order.+ """pass@abstractmethoddef count_index_status(self, model_id: str) -> ImageIndexStatus:- """Count eligible images and how many of them are embedded under the given model."""+ """Count eligible items of both kinds and how many 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.+ def list_accessible_embedded_items(self, user_id: str | None, model_id: str) -> list[IndexedItem]:+ """List embedded items the user can access: images sorted by name, then videos.- A user can access their own unboarded images, images on boards they own, images on- shared or public boards, and images on boards individually shared with them+ A user can access their own unboarded items, items on boards they own, items on+ shared or public boards, and items on boards individually shared with them(shared_boards). Pass user_id=None for the admin scope.- Images on an archived board are excluded from every scope, including the admin one,- matching the gallery's "all" listing. So the admin scope is every embedded image that- is not archived, not literally every embedded image.+ Items on an archived board are excluded from every scope, including the admin one,+ matching the gallery's "all" listing. So the admin scope is every embedded item that+ is not archived, not literally every embedded item.- The sorted result is the input to the projection scope hash, so the- ordering here must stay stable.+ The result is the input to the projection scope hash, so the ordering+ here must stay stable."""pass@@ -132,7 +140,7 @@ class ImageIndexRecordsBase(ABC):model_id: str,scope_hash: str,params: str,- image_names: list[str],+ items: list[IndexedItem],coords: np.ndarray,) -> None:"""Insert or replace the user's cached projection.@@ -142,10 +150,10 @@ class ImageIndexRecordsBase(ABC):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.+ scope_hash: Fingerprint of the item 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).+ items: Indexed items, row-aligned with coords.+ coords: float32 array of shape (len(items), 2)."""passdiff --git a/invokeai/app/services/image_index/image_index_records_sqlite.py b/invokeai/app/services/image_index/image_index_records_sqlite.pyindex a44937e72a..1185381ae7 100644--- a/invokeai/app/services/image_index/image_index_records_sqlite.py+++ b/invokeai/app/services/image_index/image_index_records_sqlite.py@@ -1,4 +1,5 @@import json+from dataclasses import dataclassimport numpy as np@@ -6,6 +7,8 @@ from invokeai.app.services.board_records.board_records_common import BoardVisibifrom invokeai.app.services.image_index.image_index_common import (EMBEDDING_DTYPE,ImageIndexStatus,+ IndexedItem,+ MediaKind,ProjectionRecord,blob_to_coords,blob_to_embedding,@@ -21,8 +24,48 @@ from invokeai.backend.util.logging import InvokeAILogger# 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 = ?"++@dataclass(frozen=True)+class _Namespace:+ """The tables and columns one media kind is indexed through.++ Images and videos are indexed by the same rules over different tables, so the rules are+ written once and the SQL is built per namespace. Every field is a constant of this module;+ nothing here is ever derived from a request.+ """++ kind: MediaKind+ table: str+ name_column: str+ category_column: str+ embeddings_table: str+ board_table: str++ @property+ def eligible_conditions(self) -> str:+ """Conditions defining a "gallery" item, i.e. one worth indexing."""+ return f"{self.table}.is_intermediate = ? AND {self.table}.{self.category_column} = ?"+++_IMAGES = _Namespace(+ kind="image",+ table="images",+ name_column="image_name",+ category_column="image_category",+ embeddings_table="image_embeddings",+ board_table="board_images",+)+_VIDEOS = _Namespace(+ kind="video",+ table="videos",+ name_column="video_name",+ category_column="video_category",+ embeddings_table="video_embeddings",+ board_table="board_videos",+)+# Images first, so every listing that concatenates namespaces has one stable order.+_NAMESPACES: tuple[_Namespace, ...] = (_IMAGES, _VIDEOS)+_NAMESPACE_BY_KIND: dict[MediaKind, _Namespace] = {namespace.kind: namespace for namespace in _NAMESPACES}def _eligible_params() -> tuple[bool, str]:@@ -40,61 +83,65 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):def start(self, invoker: Invoker) -> None:self._invoker = invoker- def upsert_embedding(self, image_name: str, model_id: str, embedding: np.ndarray) -> None:+ def upsert_embedding(self, item: IndexedItem, model_id: str, embedding: np.ndarray) -> None:+ namespace = _NAMESPACE_BY_KIND[item.kind]blob = embedding_to_blob(embedding)with self._db.transaction() as cursor:- # The image may be deleted between being scheduled and embedded, in which case the+ # The item may be deleted between being scheduled and embedded, in which case the# embedding is pointless and this is a no-op. `WHERE EXISTS` rather than catching the# foreign-key IntegrityError: the guard and the insert are one atomic statement, and# no exception is raised on the expected race, so nothing can leave the transaction# in a state the caller did not ask for. An IntegrityError from here now means a# genuine bug and is allowed to propagate.cursor.execute(- """--sql- INSERT INTO image_embeddings (image_name, model_id, dim, embedding)+ f"""--sql+ INSERT INTO {namespace.embeddings_table} ({namespace.name_column}, model_id, dim, embedding)SELECT ?, ?, ?, ?- WHERE EXISTS (SELECT 1 FROM images WHERE images.image_name = ?)- ON CONFLICT (image_name, model_id)+ WHERE EXISTS (+ SELECT 1 FROM {namespace.table} WHERE {namespace.table}.{namespace.name_column} = ?+ )+ ON CONFLICT ({namespace.name_column}, model_id)DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding;""",- (image_name, model_id, embedding.shape[0], blob, image_name),+ (item.name, model_id, embedding.shape[0], blob, item.name),)if cursor.rowcount == 0:- self._logger.debug(f"Skipped embedding for missing image {image_name}")+ self._logger.debug(f"Skipped embedding for missing {item.kind} {item.name}")- 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+ def get_embeddings(self, items: list[IndexedItem], model_id: str) -> tuple[list[IndexedItem], np.ndarray]:+ # Dedupe while preserving order so repeated input items cannot# double-count rows in downstream projection/similarity math.- image_names = list(dict.fromkeys(image_names))- found_names: list[str] = []- raw: list[tuple[int, bytes]] = []+ items = list(dict.fromkeys(items))+ rows: dict[IndexedItem, tuple[int, bytes]] = {}# Only the reads happen under the transaction. Deserialization and validation are done# afterwards so a malformed row raises outside it: `transaction()` rolls the shared# connection back on any exception, which would be an unpleasant side effect of what the# caller asked to be a read.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 in rows:- found_names.append(name)- raw.append(rows[name])+ for namespace in _NAMESPACES:+ names = [item.name for item in items if item.kind == namespace.kind]+ for start in range(0, len(names), _IN_CLAUSE_CHUNK):+ chunk = names[start : start + _IN_CLAUSE_CHUNK]+ placeholders = ",".join("?" * len(chunk))+ cursor.execute(+ f"""--sql+ SELECT {namespace.name_column}, dim, embedding+ FROM {namespace.embeddings_table}+ WHERE model_id = ? AND {namespace.name_column} IN ({placeholders});+ """,+ (model_id, *chunk),+ )+ for name, dim, blob in cursor.fetchall():+ rows[IndexedItem(namespace.kind, name)] = (dim, blob)++ # Read back in the caller's order: the returned matrix's rows align with it.+ found_items = [item for item in items if item in rows]dim: int | None = Nonevectors: list[np.ndarray] = []- for row_dim, blob in raw:+ for item in found_items:+ row_dim, blob = rows[item]if dim is None:dim = row_dimelif row_dim != dim:@@ -103,121 +150,153 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):if not vectors:return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)- return found_names, np.stack(vectors)+ return found_items, np.stack(vectors)- def delete_embedding(self, image_name: str) -> None:+ def delete_embedding(self, item: IndexedItem) -> None:+ namespace = _NAMESPACE_BY_KIND[item.kind]with self._db.transaction() as cursor:cursor.execute(- """--sql- DELETE FROM image_embeddings WHERE image_name = ?;+ f"""--sql+ DELETE FROM {namespace.embeddings_table} WHERE {namespace.name_column} = ?;""",- (image_name,),+ (item.name,),)def delete_embeddings_for_other_models(self, model_id: str) -> int:+ deleted = 0with self._db.transaction() as cursor:- cursor.execute(- """--sql- DELETE FROM image_embeddings WHERE model_id != ?;- """,- (model_id,),- )- return cursor.rowcount+ for namespace in _NAMESPACES:+ cursor.execute(+ f"""--sql+ DELETE FROM {namespace.embeddings_table} WHERE model_id != ?;+ """,+ (model_id,),+ )+ deleted += cursor.rowcount+ return deleted- def list_unembedded_image_names(self, model_id: str, limit: int) -> list[str]:+ def list_unembedded_items(self, model_id: str, limit: int) -> list[IndexedItem]:if limit < 0:# SQLite reads a negative LIMIT as unbounded, which would turn a backfill batch into# a full-table load. Fail on a miscomputed limit instead of silently doing that.raise ValueError(f"limit must be non-negative, got {limit}")++ # Each namespace contributes its own oldest `limit` rows, merged here so a batch is the+ # globally oldest work rather than every image before any video. Taking `limit` from each+ # is what makes the merge correct: whatever the merged prefix should contain is present+ # in one of the two lists.+ candidates: list[tuple[str, str, IndexedItem]] = []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()]+ for namespace in _NAMESPACES:+ cursor.execute(+ f"""--sql+ SELECT {namespace.table}.{namespace.name_column}, {namespace.table}.created_at+ FROM {namespace.table}+ LEFT JOIN {namespace.embeddings_table}+ ON {namespace.embeddings_table}.{namespace.name_column}+ = {namespace.table}.{namespace.name_column}+ AND {namespace.embeddings_table}.model_id = ?+ WHERE {namespace.eligible_conditions}+ AND {namespace.embeddings_table}.{namespace.name_column} IS NULL+ ORDER BY {namespace.table}.created_at ASC, {namespace.table}.{namespace.name_column} ASC+ LIMIT ?;+ """,+ (model_id, *_eligible_params(), limit),+ )+ candidates.extend(+ (created_at, name, IndexedItem(namespace.kind, name)) for name, created_at in cursor.fetchall()+ )++ candidates.sort(key=lambda candidate: (candidate[0], candidate[1]))+ return [item for _, _, item in candidates[:limit]]def count_index_status(self, model_id: str) -> ImageIndexStatus:+ total = 0+ embedded = 0with 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()+ for namespace in _NAMESPACES:+ cursor.execute(+ f"""--sql+ SELECT+ COUNT(*),+ COUNT({namespace.embeddings_table}.{namespace.name_column})+ FROM {namespace.table}+ LEFT JOIN {namespace.embeddings_table}+ ON {namespace.embeddings_table}.{namespace.name_column}+ = {namespace.table}.{namespace.name_column}+ AND {namespace.embeddings_table}.model_id = ?+ WHERE {namespace.eligible_conditions};+ """,+ (model_id, *_eligible_params()),+ )+ namespace_total, namespace_embedded = cursor.fetchone()+ total += namespace_total+ embedded += namespace_embeddedreturn ImageIndexStatus(total=total, embedded=embedded)- def list_accessible_embedded_images(self, user_id: str | None, model_id: str) -> list[str]:+ def list_accessible_embedded_items(self, user_id: str | None, model_id: str) -> list[IndexedItem]:# 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 = ?- )- )+ # (image_records_sqlite / video_records_sqlite): items on archived+ # boards are hidden from every scope, and a scoped user sees their own+ # unboarded items plus items 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.+ items: list[IndexedItem] = []+ with self._db.transaction() as cursor:+ for namespace in _NAMESPACES:+ params: list[object] = [model_id, *_eligible_params()]+ if user_id is None:+ # Administrative scope: everything except items on archived boards.+ access_clause = f"""AND (+ {namespace.board_table}.board_id IS NULL+ OR EXISTS (+ SELECT 1 FROM boards+ WHERE boards.board_id = {namespace.board_table}.board_id+ AND boards.archived = 0+ )+ )"""+ else:+ access_clause = f"""AND (+ ({namespace.board_table}.board_id IS NULL AND {namespace.table}.user_id = ?)+ OR EXISTS (+ SELECT 1 FROM boards+ WHERE boards.board_id = {namespace.board_table}.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])- )"""- 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()]+ cursor.execute(+ f"""--sql+ SELECT DISTINCT {namespace.embeddings_table}.{namespace.name_column}+ FROM {namespace.embeddings_table}+ JOIN {namespace.table}+ ON {namespace.table}.{namespace.name_column}+ = {namespace.embeddings_table}.{namespace.name_column}+ LEFT JOIN {namespace.board_table}+ ON {namespace.board_table}.{namespace.name_column} = {namespace.table}.{namespace.name_column}+ WHERE {namespace.embeddings_table}.model_id = ?+ AND {namespace.eligible_conditions}+ {access_clause}+ ORDER BY {namespace.embeddings_table}.{namespace.name_column} ASC;+ """,+ params,+ )+ items.extend(IndexedItem(namespace.kind, row[0]) for row in cursor.fetchall())+ return itemsdef get_custom_vocab_terms(self) -> list[str]:with self._db.transaction() as cursor:@@ -249,7 +328,7 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):with self._db.transaction() as cursor:cursor.execute("""--sql- SELECT scope_hash, params, point_count, image_names, coords, created_at, updated_at+ SELECT scope_hash, params, point_count, image_names, item_kinds, coords, created_at, updated_atFROM image_projectionsWHERE user_id = ? AND model_id = ?;""",@@ -260,16 +339,33 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):if row is None:return None+ names: list[str] = json.loads(row[3])+ # A projection cached before videos were indexable has no kinds: every name in it is an+ # image, which is what a NULL column means. Same reading for a row written by this code,+ # where the column is always present.+ kinds: list[MediaKind] = json.loads(row[4]) if row[4] is not None else ["image"] * len(names)+ if len(kinds) != len(names):+ # Unreachable from this code — both arrays are written by one statement from one+ # list — but reachable by downgrading to a build that rewrites `image_names` and+ # leaves `item_kinds` behind. Reported as "no cached projection" rather than+ # raised: every reader is a request handler or the worker's own fit, so raising+ # would 500 the map and spin the worker on a row that only `set_projection`+ # repairs — which is never reached while the read keeps failing.+ self._logger.warning(+ f"Discarding the cached projection for user {user_id}: {len(names)} names but {len(kinds)} kinds"+ )+ 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],+ items=[IndexedItem(kind, name) for kind, name in zip(kinds, names, strict=True)],+ coords=blob_to_coords(row[5], row[2]),+ created_at=row[6],+ updated_at=row[7],)def set_projection(@@ -278,20 +374,23 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):model_id: str,scope_hash: str,params: str,- image_names: list[str],+ items: list[IndexedItem],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")+ if len(items) != coords.shape[0]:+ raise ValueError(f"Got {len(items)} items but {coords.shape[0]} coordinate rows")blob = coords_to_blob(coords)+ names = json.dumps([item.name for item in items])+ kinds = json.dumps([item.kind for item in items])with self._db.transaction() as cursor:# No-op if the user was deleted while their projection was being computed; there is# nobody left to serve it to. Guarded by `WHERE EXISTS` for the same reason as in# `upsert_embedding`.cursor.execute("""--sql- INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)- SELECT ?, ?, ?, ?, ?, ?, ?+ INSERT INTO image_projections+ (user_id, model_id, scope_hash, params, point_count, image_names, item_kinds, coords)+ SELECT ?, ?, ?, ?, ?, ?, ?, ?WHERE EXISTS (SELECT 1 FROM users WHERE users.user_id = ?)ON CONFLICT (user_id, model_id)DO UPDATE SET@@ -299,9 +398,10 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):params = excluded.params,point_count = excluded.point_count,image_names = excluded.image_names,+ item_kinds = excluded.item_kinds,coords = excluded.coords;""",- (user_id, model_id, scope_hash, params, len(image_names), json.dumps(image_names), blob, user_id),+ (user_id, model_id, scope_hash, params, len(items), names, kinds, blob, user_id),)if cursor.rowcount == 0:self._logger.debug(f"Skipped projection for missing user {user_id}")diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.pyindex cba8c92de2..ecadd0963a 100644--- a/invokeai/app/services/image_index/projection.py+++ b/invokeai/app/services/image_index/projection.py@@ -19,7 +19,7 @@ from typing import Optionalimport numpy as np-from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE+from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, IndexedItemDEFAULT_CLUSTER_EPS = 0.2DEFAULT_CLUSTER_MIN_SAMPLES = 10@@ -233,16 +233,22 @@ def cluster_at_eps(return DBSCAN(eps=eps, min_samples=min_samples).fit(coords).labels_-def scope_hash(model_id: str, image_names: list[str]) -> str:- """Fingerprint of an accessible-image set under one model.+def scope_hash(model_id: str, items: list[IndexedItem]) -> str:+ """Fingerprint of an accessible-item set under one model.- Order-insensitive: the caller may pass names in any order. Comparing the+ Order-insensitive: the caller may pass items in any order. Comparing thestored hash against a freshly derived one detects staleness from any- cause — new/deleted images, board visibility changes, shares.+ cause — new/deleted items, board visibility changes, shares.++ Names alone identify the set: image and video names are both a UUID plus a+ kind-specific extension, so one name cannot name two items. Leaving the+ kind out of the digest also means a gallery with no videos keeps the+ projection it had before videos were indexable, rather than every user+ paying for a recomputed fit on the first load after an upgrade."""digest = hashlib.sha256()digest.update(model_id.encode("utf-8"))- for name in sorted(image_names):+ for name in sorted(item.name for item in items):digest.update(b"\x00")digest.update(name.encode("utf-8"))return digest.hexdigest()diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_12_add_video_embeddings.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_12_add_video_embeddings.pynew file mode 100644index 0000000000..e3a1e6f904--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_12_add_video_embeddings.py@@ -0,0 +1,94 @@+"""Extend the semantic index to gallery videos.++A video is indexed by its thumbnail — the representative frame the video file+store already extracts when the video is created — so a video takes part in the+image map and in semantic search exactly as an image does.++Videos keep their own embedding table rather than sharing `image_embeddings`:+the FK that deletes an embedding with its media can only reference one table,+and eligibility and board access are answered from `videos`/`board_videos` with+their own columns. One table per namespace keeps both honest.++`image_projections` gains `item_kinds`, a JSON array row-aligned with+`image_names` naming the namespace each name belongs to. It is nullable, and a+NULL means what every projection cached before this migration was: all images.+So existing caches stay valid instead of every user paying for a recomputed+projection on first load after an upgrade.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddVideoEmbeddingsCallback:+ """Migration to add the video_embeddings table and the projection item_kinds column."""++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ self._assert_videos_table_exists(cursor)+ self._create_video_embeddings_table(cursor)+ self._add_projection_item_kinds(cursor)++ def _assert_videos_table_exists(self, cursor: sqlite3.Cursor) -> None:+ """Fail here rather than at the first insert if `videos` has not been created yet.++ A migration declares one `depends_on`, and this one names the migration whose column it+ alters. Its other prerequisite — `videos`, which the new foreign key references — is+ satisfied by run order (dated migrations run in date order, and the videos tables are+ two months older). SQLite resolves foreign-key targets lazily, so getting that wrong+ would create the table here and fail obscurely on the first embedding written months+ later; this turns it into a migration failure naming the cause.+ """+ cursor.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'videos';")+ if cursor.fetchone() is None:+ raise RuntimeError(+ "Cannot add video_embeddings: the videos table does not exist. "+ "2026_07_01_add_videos_tables must run first."+ )++ def _create_video_embeddings_table(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS video_embeddings (+ video_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 (video_name, model_id),+ FOREIGN KEY (video_name) REFERENCES videos(video_name) ON DELETE CASCADE+ );+ """+ )+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_video_embeddings_model_id ON video_embeddings(model_id);+ """+ )++ def _add_projection_item_kinds(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute("PRAGMA table_info(image_projections);")+ if any(row[1] == "item_kinds" for row in cursor.fetchall()):+ return+ cursor.execute(+ """--sql+ ALTER TABLE image_projections ADD COLUMN item_kinds TEXT;+ """+ )+++def build_migration() -> Migration:+ """Build the migration that extends the semantic index to videos:+ - `video_embeddings` (global per-video embedding index).+ - `image_projections.item_kinds` (which namespace each projected name belongs to).+ """+ return Migration(+ id="2026_09_12_add_video_embeddings",+ # Adds the sibling of `image_embeddings` and a column to `image_projections`,+ # both created by this migration. `videos`, which the new FK references, is+ # older still (2026_07_01_add_videos_tables).+ depends_on="2026_08_03_add_image_index_tables",+ callback=AddVideoEmbeddingsCallback(),+ )diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex a64c8b9408..0bfa298aa2 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -6782,6 +6782,18 @@"title": "Min Samples"},"description": "DBSCAN min_samples for clustering"+ },+ {+ "name": "include_videos",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names.",+ "default": false,+ "title": "Include Videos"+ },+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."}],"responses": {@@ -6812,7 +6824,7 @@"get": {"tags": ["image_map"],"summary": "Search Image Map",- "description": "Ranks the user's accessible images by semantic similarity.\n\nProvide exactly one of `q` (text search \u2014 requires the embedding model's\ntext encoder to be installed) or `image_name` (visual similarity \u2014 uses\nthe reference image's stored embedding when it exists, and otherwise\nembeds the image file on demand, so unindexed images such as assets can\nbe reference images too).",+ "description": "Ranks the user's accessible images and videos by semantic similarity.\n\nProvide exactly one of `q` (text search \u2014 requires the embedding model's\ntext encoder to be installed), `image_name`, or `video_name` (visual\nsimilarity \u2014 uses the reference item's stored embedding when it exists,\nand otherwise embeds its file on demand, so unindexed items such as assets\ncan be reference items too). A video is represented by its thumbnail, the\nsame frame the index embedded.","operationId": "search_image_map","security": [{@@ -6857,6 +6869,24 @@},"description": "Reference image for similarity search"},+ {+ "name": "video_name",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Reference video for similarity search",+ "title": "Video Name"+ },+ "description": "Reference video for similarity search"+ },{"name": "limit","in": "query",@@ -6870,6 +6900,18 @@"title": "Limit"},"description": "Maximum number of results"+ },+ {+ "name": "include_videos",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names.",+ "default": false,+ "title": "Include Videos"+ },+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."}],"responses": {@@ -6940,6 +6982,18 @@"title": "Limit"},"description": "Maximum number of results"+ },+ {+ "name": "include_videos",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names.",+ "default": false,+ "title": "Include Videos"+ },+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."}],"requestBody": {@@ -7034,6 +7088,18 @@"title": "Top K"},"description": "Candidate labels per cluster"+ },+ {+ "name": "include_videos",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names.",+ "default": false,+ "title": "Include Videos"+ },+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."}],"responses": {@@ -7064,7 +7130,7 @@"get": {"tags": ["image_map"],"summary": "Get Image Map Image Labels",- "description": "Labels one image with the vocabulary phrases most similar to its stored embedding.\n\nServes map hover cards, so it only covers images the index has embedded;\nan unindexed image (assets, intermediates, not-yet-indexed) is a 404\nrather than an on-demand embed \u2014 a hover must never queue encoder work.\nRequires the embedding model's text encoder, like /cluster_labels.",+ "description": "Labels one gallery item with the vocabulary phrases most similar to its stored embedding.\n\nServes map hover cards, so it only covers items the index has embedded;\nan unindexed item (assets, intermediates, not-yet-indexed) is a 404\nrather than an on-demand embed \u2014 a hover must never queue encoder work.\nRequires the embedding model's text encoder, like /cluster_labels.","operationId": "get_image_map_image_labels","security": [{@@ -7078,10 +7144,23 @@"required": true,"schema": {"type": "string",- "description": "The image to label",+ "description": "The image or video to label","title": "Image Name"},- "description": "The image to label"+ "description": "The image or video to label"+ },+ {+ "name": "kind",+ "in": "query",+ "required": false,+ "schema": {+ "enum": ["image", "video"],+ "type": "string",+ "description": "Which namespace image_name belongs to",+ "default": "image",+ "title": "Kind"+ },+ "description": "Which namespace image_name belongs to"},{"name": "top_k",@@ -7221,6 +7300,25 @@"summary": "Get Image Map Status","description": "Gets embedding index progress and the user's projection cache status.","operationId": "get_image_map_status",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "include_videos",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names.",+ "default": false,+ "title": "Include Videos"+ },+ "description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."+ }+ ],"responses": {"200": {"description": "Successful Response",@@ -7231,13 +7329,18 @@}}}+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }}- },- "security": [- {- "HTTPBearer": []- }- ]+ }}},"/api/v1/videos/upload": {@@ -44196,24 +44299,24 @@"total": {"type": "integer","title": "Total",- "description": "Number of gallery images eligible for indexing"+ "description": "Number of gallery items (images and videos) eligible for indexing"},"embedded": {"type": "integer","title": "Embedded",- "description": "Number of eligible images that have an embedding"+ "description": "Number of eligible items that have an embedding"},"failed": {"type": "integer","title": "Failed",- "description": "Eligible images that repeatedly failed to embed; excluded from pending so it can drain",+ "description": "Eligible items that repeatedly failed to embed; excluded from pending so it can drain","default": 0}},"type": "object","required": ["total", "embedded"],"title": "ImageIndexStatus",- "description": "Progress of the embedding index for one embedding model."+ "description": "Progress of the embedding index for one embedding model.\n\nCounts cover both media kinds: an indexed gallery is its images plus its videos."},"ImageIndexStatusEvent": {"description": "Event model for image_index_status",@@ -44652,13 +44755,13 @@"score": {"type": "number","title": "Score",- "description": "Cosine similarity of the best phrase to the image's embedding"+ "description": "Cosine similarity of the best phrase to the item's embedding"}},"type": "object","required": ["label", "alternates", "score"],"title": "ImageMapImageLabelsResponse",- "description": "The best vocabulary labels for one image."+ "description": "The best vocabulary labels for one gallery item."},"ImageMapPoint": {"properties": {@@ -44675,7 +44778,13 @@"image_name": {"type": "string","title": "Image Name",- "description": "The image this point represents"+ "description": "The image or video this point represents; `kind` says which namespace the name belongs to"+ },+ "kind": {+ "type": "string",+ "enum": ["image", "video"],+ "title": "Kind",+ "description": "Whether this point is an image or a video"},"cluster": {"type": "integer",@@ -44684,9 +44793,9 @@}},"type": "object",- "required": ["x", "y", "image_name", "cluster"],+ "required": ["x", "y", "image_name", "kind", "cluster"],"title": "ImageMapPoint",- "description": "One image's position on the 2D semantic map."+ "description": "One gallery item's position on the 2D semantic map."},"ImageMapPointsResponse": {"properties": {@@ -44854,14 +44963,20 @@"type": "object","required": ["results"],"title": "ImageMapSearchResponse",- "description": "Semantic search results over the user's embedded images."+ "description": "Semantic search results over the user's embedded gallery items."},"ImageMapSearchResult": {"properties": {"image_name": {"type": "string","title": "Image Name",- "description": "The matching image"+ "description": "The matching image or video; `kind` says which namespace the name belongs to"+ },+ "kind": {+ "type": "string",+ "enum": ["image", "video"],+ "title": "Kind",+ "description": "Whether this hit is an image or a video"},"score": {"type": "number",@@ -44870,7 +44985,7 @@}},"type": "object",- "required": ["image_name", "score"],+ "required": ["image_name", "kind", "score"],"title": "ImageMapSearchResult","description": "One semantic search hit."},@@ -54466,13 +54581,13 @@"image_index_enabled": {"type": "boolean","title": "Image Index Enabled",- "description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",+ "description": "Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.","default": true},"image_index_model": {"type": "string","title": "Image Index Model",- "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.",+ "description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.","default": "DFN2B-CLIP-ViT-L-14-39B"},"image_index_device": {@@ -54491,7 +54606,7 @@"type": "integer","exclusiveMinimum": 0.0,"title": "Image Index Batch Size",- "description": "Number of images embedded per batch by the image index worker.",+ "description": "Number of gallery items embedded per batch by the image index worker.","default": 8},"external_alibabacloud_api_key": {@@ -54594,7 +54709,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 8708d9b0d7..526835da62 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1616,13 +1616,14 @@ export type paths = {};/*** Search Image Map- * @description Ranks the user's accessible images by semantic similarity.+ * @description Ranks the user's accessible images and videos by semantic similarity.** Provide exactly one of `q` (text search — requires the embedding model's- * text encoder to be installed) or `image_name` (visual similarity — uses- * the reference image's stored embedding when it exists, and otherwise- * embeds the image file on demand, so unindexed images such as assets can- * be reference images too).+ * text encoder to be installed), `image_name`, or `video_name` (visual+ * similarity — uses the reference item's stored embedding when it exists,+ * and otherwise embeds its file on demand, so unindexed items such as assets+ * can be reference items too). A video is represented by its thumbnail, the+ * same frame the index embedded.*/get: operations["search_image_map"];put?: never;@@ -1695,10 +1696,10 @@ export type paths = {};/*** Get Image Map Image Labels- * @description Labels one image with the vocabulary phrases most similar to its stored embedding.+ * @description Labels one gallery item with the vocabulary phrases most similar to its stored embedding.*- * Serves map hover cards, so it only covers images the index has embedded;- * an unindexed image (assets, intermediates, not-yet-indexed) is a 404+ * Serves map hover cards, so it only covers items the index has embedded;+ * an unindexed item (assets, intermediates, not-yet-indexed) is a 404* rather than an on-demand embed — a hover must never queue encoder work.* Requires the embedding model's text encoder, like /cluster_labels.*/@@ -18206,21 +18207,23 @@ export type components = {/*** ImageIndexStatus* @description Progress of the embedding index for one embedding model.+ *+ * Counts cover both media kinds: an indexed gallery is its images plus its videos.*/ImageIndexStatus: {/*** Total- * @description Number of gallery images eligible for indexing+ * @description Number of gallery items (images and videos) eligible for indexing*/total: number;/*** Embedded- * @description Number of eligible images that have an embedding+ * @description Number of eligible items that have an embedding*/embedded: number;/*** Failed- * @description Eligible images that repeatedly failed to embed; excluded from pending so it can drain+ * @description Eligible items that repeatedly failed to embed; excluded from pending so it can drain* @default 0*/failed?: number;@@ -18471,7 +18474,7 @@ export type components = {};/*** ImageMapImageLabelsResponse- * @description The best vocabulary labels for one image.+ * @description The best vocabulary labels for one gallery item.*/ImageMapImageLabelsResponse: {/**@@ -18486,13 +18489,13 @@ export type components = {alternates: string[];/*** Score- * @description Cosine similarity of the best phrase to the image's embedding+ * @description Cosine similarity of the best phrase to the item's embedding*/score: number;};/*** ImageMapPoint- * @description One image's position on the 2D semantic map.+ * @description One gallery item's position on the 2D semantic map.*/ImageMapPoint: {/**@@ -18507,9 +18510,15 @@ export type components = {y: number;/*** Image Name- * @description The image this point represents+ * @description The image or video this point represents; `kind` says which namespace the name belongs to*/image_name: string;+ /**+ * Kind+ * @description Whether this point is an image or a video+ * @enum {string}+ */+ kind: "image" | "video";/*** Cluster* @description DBSCAN cluster label; -1 means unclustered@@ -18624,7 +18633,7 @@ export type components = {};/*** ImageMapSearchResponse- * @description Semantic search results over the user's embedded images.+ * @description Semantic search results over the user's embedded gallery items.*/ImageMapSearchResponse: {/**@@ -18640,9 +18649,15 @@ export type components = {ImageMapSearchResult: {/*** Image Name- * @description The matching image+ * @description The matching image or video; `kind` says which namespace the name belongs to*/image_name: string;+ /**+ * Kind+ * @description Whether this hit is an image or a video+ * @enum {string}+ */+ kind: "image" | "video";/*** Score* @description Cosine similarity to the query; higher is more similar@@ -20828,10 +20843,10 @@ export type components = {* allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.* multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.* strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.- * image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.- * image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ * image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.+ * image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.* image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.- * image_index_batch_size: Number of images embedded per batch by the image index worker.+ * image_index_batch_size: Number of gallery items embedded per batch by the image index worker.* external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.* external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.* external_gemini_api_key: API key for Gemini image generation.@@ -21340,13 +21355,13 @@ export type components = {strict_password_checking?: boolean;/*** Image Index Enabled- * @description Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.+ * @description Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.* @default true*/image_index_enabled?: boolean;/*** Image Index Model- * @description Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.+ * @description Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.* @default DFN2B-CLIP-ViT-L-14-39B*/image_index_model?: string;@@ -21357,7 +21372,7 @@ export type components = {image_index_device?: string | null;/*** Image Index Batch Size- * @description Number of images embedded per batch by the image index worker.+ * @description Number of gallery items embedded per batch by the image index worker.* @default 8*/image_index_batch_size?: number;@@ -49603,6 +49618,8 @@ export interface operations {eps?: number | null;/** @description DBSCAN min_samples for clustering */min_samples?: number;+ /** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */+ include_videos?: boolean;};header?: never;path?: never;@@ -49637,8 +49654,12 @@ export interface operations {q?: string | null;/** @description Reference image for similarity search */image_name?: string | null;+ /** @description Reference video for similarity search */+ video_name?: string | null;/** @description Maximum number of results */limit?: number;+ /** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */+ include_videos?: boolean;};header?: never;path?: never;@@ -49673,6 +49694,8 @@ export interface operations {image_url?: string | null;/** @description Maximum number of results */limit?: number;+ /** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */+ include_videos?: boolean;};header?: never;path?: never;@@ -49713,6 +49736,8 @@ export interface operations {min_samples?: number;/** @description Candidate labels per cluster */top_k?: number;+ /** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */+ include_videos?: boolean;};header?: never;path?: never;@@ -49743,8 +49768,10 @@ export interface operations {get_image_map_image_labels: {parameters: {query: {- /** @description The image to label */+ /** @description The image or video to label */image_name: string;+ /** @description Which namespace image_name belongs to */+ kind?: "image" | "video";/** @description Number of candidate labels */top_k?: number;};@@ -49849,7 +49876,10 @@ export interface operations {};get_image_map_status: {parameters: {- query?: never;+ query?: {+ /** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */+ include_videos?: boolean;+ };header?: never;path?: never;cookie?: never;@@ -49865,6 +49895,15 @@ export interface operations {"application/json": components["schemas"]["ImageMapStatusResponse"];};};+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };};};upload_video: {diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex a267d117b5..fb96d97585 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -1,17 +1,23 @@"""Tests for the /v1/image_map endpoints: serving, staleness, and user scoping."""import logging+from pathlib import Pathfrom types import SimpleNamespaceimport numpy as npimport pytestfrom fastapi.testclient import TestClient+from PIL import Imagefrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api_app import app+from invokeai.app.services.board_video_records.board_video_records_sqlite import SqliteBoardVideoRecordStoragefrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase-from invokeai.app.services.image_index.image_index_common import ImageIndexStatus+from invokeai.app.services.image_index.image_index_common import (+ ImageIndexStatus,+ IndexedItem,+)from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_index.projection import scope_hashfrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin@@ -19,6 +25,8 @@ from invokeai.app.services.image_records.image_records_sqlite import SqliteImagefrom invokeai.app.services.invocation_services import InvocationServicesfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.users.users_common import UserCreateRequest+from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStorage+from invokeai.app.services.videos.videos_default import VideoServicefrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.fixtures.sqlite_database import create_mock_sqlite_database@@ -43,6 +51,7 @@ class FakeImageIndexService(ImageIndexServiceBase):self.projection_requests: list[tuple[str, bool]] = []self.spent_failed_scopes: dict[str, str] = {}self.search_calls: list[tuple[str | None, int]] = []+ self.search_kinds: list[tuple[str, ...] | None] = []self.search_results: list[tuple[str, float]] = []self.text_unavailable = Falseself.embedded_texts: list[str] = []@@ -75,17 +84,25 @@ class FakeImageIndexService(ImageIndexServiceBase):vector[0] = 1.0return vector- def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:+ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[IndexedItem], np.ndarray]:# Wired to the real records store by the mock_services fixture so# endpoints exercising the accessible matrix see seeded embeddings.if self.index_records is None:return [], np.empty((0, 0), dtype=np.float32)- names = self.index_records.list_accessible_embedded_images(user_id, MODEL_ID)- return self.index_records.get_embeddings(names, MODEL_ID)+ items = self.index_records.list_accessible_embedded_items(user_id, MODEL_ID)+ return self.index_records.get_embeddings(items, MODEL_ID)- def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:+ def search_similar(+ self,+ user_id: str | None,+ query_embedding: np.ndarray,+ limit: int,+ kinds: tuple[str, ...] | None = None,+ ) -> list[tuple[IndexedItem, float]]:self.search_calls.append((user_id, limit))- return self.search_results[:limit]+ self.search_kinds.append(kinds)+ results = [(item, score) for item, score in self.search_results if kinds is None or item.kind in kinds]+ return results[:limit]def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError@@ -137,8 +154,28 @@ def image_index_service() -> FakeImageIndexService:return FakeImageIndexService()+def _video_service(thumbnails: Path, video_records: SqliteVideoRecordStorage) -> VideoService:+ """A video service that resolves thumbnails to real files, which is all these endpoints read.++ It goes through the record store first, like the real one: a name with no video raises+ rather than resolving to a fabricated file, which is what makes the not-found paths real.+ """+ videos = VideoService()++ def get_path(video_name: str, thumbnail: bool = False) -> str:+ assert thumbnail, "these endpoints only ever read a video's thumbnail"+ video_records.get(video_name)+ path = thumbnails / f"{video_name}.webp"+ if not path.exists():+ Image.new("RGB", (16, 16), "teal").save(path, "WEBP")+ return str(path)++ videos.get_path = get_path # type: ignore[method-assign]+ return videos++@pytest.fixture-def mock_services(image_index_service: FakeImageIndexService) -> InvocationServices:+def mock_services(image_index_service: FakeImageIndexService, tmp_path: Path) -> InvocationServices:from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStoragefrom invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStoragefrom invokeai.app.services.boards.boards_default import BoardService@@ -191,10 +228,10 @@ def mock_services(image_index_service: FakeImageIndexService) -> InvocationServiusers=UserService(db),wildcard_records=None, # type: ignoresystem_prompt_records=None, # type: ignore- videos=None, # type: ignore+ videos=_video_service(tmp_path, video_records := SqliteVideoRecordStorage(db=db)),video_files=None, # type: ignore- video_records=None, # type: ignore- board_video_records=None, # type: ignore+ video_records=video_records,+ board_video_records=SqliteBoardVideoRecordStorage(db=db),gallery=None, # type: ignoreimage_index_records=(index_records := ImageIndexRecordsSqlite(db=db)),image_index=image_index_service,@@ -236,7 +273,24 @@ def _seed_embedded_image(mock_invoker: Invoker, image_name: str, user_id: str =)rng = np.random.default_rng(abs(hash(image_name)) % (2**32))vec = rng.standard_normal(DIM).astype(np.float32)- _records(mock_invoker).upsert_embedding(image_name, MODEL_ID, vec / np.linalg.norm(vec))+ _records(mock_invoker).upsert_embedding(IndexedItem("image", image_name), MODEL_ID, vec / np.linalg.norm(vec))+++def _seed_embedded_video(mock_invoker: Invoker, video_name: str, user_id: str = SYSTEM_USER_ID) -> None:+ mock_invoker.services.video_records.save(+ video_name=video_name,+ video_origin=ResourceOrigin.INTERNAL,+ video_category=ImageCategory.GENERAL,+ width=16,+ height=16,+ duration=2.0,+ fps=24.0,+ has_workflow=False,+ user_id=user_id,+ )+ rng = np.random.default_rng(abs(hash(video_name)) % (2**32))+ vec = rng.standard_normal(DIM).astype(np.float32)+ _records(mock_invoker).upsert_embedding(IndexedItem("video", video_name), MODEL_ID, vec / np.linalg.norm(vec))def _save_unembedded_image(mock_invoker: Invoker, image_name: str, user_id: str = SYSTEM_USER_ID) -> None:@@ -251,13 +305,21 @@ def _save_unembedded_image(mock_invoker: Invoker, image_name: str, user_id: str)-def _seed_projection(mock_invoker: Invoker, user_id: str, image_names: list[str], coords: np.ndarray) -> None:- accessible = _records(mock_invoker).list_accessible_embedded_images(+def imgs(*names: str) -> list[IndexedItem]:+ """The image-namespace items for these names."""+ return [IndexedItem("image", name) for name in names]+++def vids(*names: str) -> list[IndexedItem]:+ """The video-namespace items for these names."""+ return [IndexedItem("video", name) for name in names]+++def _seed_projection(mock_invoker: Invoker, user_id: str, items: list[IndexedItem], coords: np.ndarray) -> None:+ accessible = _records(mock_invoker).list_accessible_embedded_items(None if user_id == SYSTEM_USER_ID else user_id, MODEL_ID)- _records(mock_invoker).set_projection(- user_id, MODEL_ID, scope_hash(MODEL_ID, accessible), "{}", image_names, coords- )+ _records(mock_invoker).set_projection(user_id, MODEL_ID, scope_hash(MODEL_ID, accessible), "{}", items, coords)# --- Single-user mode (system admin) ---@@ -315,7 +377,7 @@ def test_points_served_with_live_eps_clustering(mock_invoker: Invoker, client: T_seed_embedded_image(mock_invoker, name)# Two tight pairs far apart (span 30 -> the server-side eps clamp is ~1.5).coords = np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32)- _seed_projection(mock_invoker, SYSTEM_USER_ID, names, coords)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), coords)clustered = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()assert clustered["state"] == "ready"@@ -344,7 +406,7 @@ def test_stale_projection_filters_now_inaccessible_names_and_requests_refresh(_seed_embedded_image(mock_invoker, "keep.png")_seed_embedded_image(mock_invoker, "gone.png")coords = np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32)- _seed_projection(mock_invoker, SYSTEM_USER_ID, ["keep.png", "gone.png"], coords)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("keep.png", "gone.png"), coords)# The image disappears after the projection was cached.mock_invoker.services.image_records.delete("gone.png")@@ -369,7 +431,7 @@ def test_status_endpoint(mock_invoker: Invoker, client: TestClient) -> None:assert body["projection"]["state"] == "empty"_seed_embedded_image(mock_invoker, "a.png")- _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a.png"], np.zeros((1, 2), dtype=np.float32))+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))body = client.get("/api/v1/image_map/status").json()assert body["projection"]["state"] == "ready"assert body["projection"]["stale"] is False@@ -486,7 +548,7 @@ def test_multiuser_projection_and_scope_are_per_user(# user1 has a private (unboarded) embedded image and a cached projection._seed_embedded_image(mock_invoker, "private1.png", user_id=user1_id)- accessible1 = _records(mock_invoker).list_accessible_embedded_images(user1_id, MODEL_ID)+ accessible1 = _records(mock_invoker).list_accessible_embedded_items(user1_id, MODEL_ID)_records(mock_invoker).set_projection(user1_id, MODEL_ID, scope_hash(MODEL_ID, accessible1), "{}", accessible1, np.zeros((1, 2), dtype=np.float32))@@ -526,7 +588,7 @@ def test_multiuser_stale_cache_never_leaks_revoked_names(multiuser, mock_invokerMODEL_ID,"stale-hash","{}",- ["was-shared.png", "own2.png"],+ imgs("was-shared.png", "own2.png"),np.zeros((2, 2), dtype=np.float32),)@@ -562,7 +624,7 @@ def test_cluster_labels_computed_only_over_accessible_points(MODEL_ID,"stale-hash","{}",- ["p1.png", "hidden.png", "p2.png", "far.png"],+ imgs("p1.png", "hidden.png", "p2.png", "far.png"),np.array([[0.0, 0.0], [1.5, 0.0], [3.0, 0.0], [0.0, 60.0]], dtype=np.float32),)@@ -654,7 +716,7 @@ def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker:for name in names:_seed_embedded_image(mock_invoker, name)coords = np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32)- _seed_projection(mock_invoker, SYSTEM_USER_ID, names, coords)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), coords)first = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()for _ in range(4):@@ -671,7 +733,7 @@ def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker:# A recomputed projection (same scope, new coordinates) must not be served# from the entry the previous one left behind.- _seed_projection(mock_invoker, SYSTEM_USER_ID, names, coords[::-1].copy())+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), coords[::-1].copy())reprojected = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()assert calls["n"] == 4, "a rewritten projection must recluster"assert reprojected["points"] != first["points"]@@ -686,7 +748,7 @@ def test_cluster_cache_is_bounded(monkeypatch, mock_invoker: Invoker, client: Te_seed_projection(mock_invoker,SYSTEM_USER_ID,- names,+ imgs(*names),np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32),)@@ -768,7 +830,7 @@ def test_an_all_non_finite_projection_is_not_permanently_blank(names = ["a.png", "b.png"]for name in names:_seed_embedded_image(mock_invoker, name)- _seed_projection(mock_invoker, SYSTEM_USER_ID, names, np.full((2, 2), np.nan, dtype=np.float32))+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), np.full((2, 2), np.nan, dtype=np.float32))body = client.get("/api/v1/image_map/points").json()@@ -791,7 +853,7 @@ def test_search_disabled_index_conflicts(image_index_service: FakeImageIndexServdef test_text_search_returns_ranked_results(image_index_service: FakeImageIndexService, client: TestClient) -> None:- image_index_service.search_results = [("a.png", 0.9), ("b.png", 0.5)]+ image_index_service.search_results = [(IndexedItem("image", "a.png"), 0.9), (IndexedItem("image", "b.png"), 0.5)]body = client.get("/api/v1/image_map/search", params={"limit": 10, "q": "a red barn"}).json()@@ -799,8 +861,8 @@ def test_text_search_returns_ranked_results(image_index_service: FakeImageIndexS# System user is admin in single-user mode -> global (None) scope.assert image_index_service.search_calls == [(None, 10)]assert body["results"] == [- {"image_name": "a.png", "score": 0.9},- {"image_name": "b.png", "score": 0.5},+ {"image_name": "a.png", "kind": "image", "score": 0.9},+ {"image_name": "b.png", "kind": "image", "score": 0.5},]@@ -819,7 +881,10 @@ def test_image_search_uses_stored_embedding(mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient) -> None:_seed_embedded_image(mock_invoker, "ref.png")- image_index_service.search_results = [("ref.png", 1.0), ("close.png", 0.8)]+ image_index_service.search_results = [+ (IndexedItem("image", "ref.png"), 1.0),+ (IndexedItem("image", "close.png"), 0.8),+ ]body = client.get("/api/v1/image_map/search", params={"image_name": "ref.png"}).json()@@ -835,7 +900,7 @@ def test_image_search_embeds_unindexed_reference_on_demand(_save_unembedded_image(mock_invoker, "not-indexed.png")monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", lambda name: Image.new("RGB", (4, 4)))- image_index_service.search_results = [("a.png", 0.7)]+ image_index_service.search_results = [(IndexedItem("image", "a.png"), 0.7)]body = client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).json()@@ -916,7 +981,7 @@ def test_cluster_labels_skips_the_embedding_gather_when_nothing_clustered(# len(visible) x D float32 for nothing — gigabytes on the large galleries# /points is written for, once per points refresh._seed_embedded_image(mock_invoker, "a.png")- _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a.png"], np.zeros((1, 2), dtype=np.float32))+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))monkeypatch.setattr("invokeai.app.api.routers.image_map.compute_clusters",@@ -949,7 +1014,7 @@ def test_search_by_image_upload_returns_ranked_results(buffer = BytesIO()Image.new("RGB", (8, 8), color=(200, 30, 30)).save(buffer, format="PNG")- image_index_service.search_results = [("a.png", 0.9), ("b.png", 0.4)]+ image_index_service.search_results = [(IndexedItem("image", "a.png"), 0.9), (IndexedItem("image", "b.png"), 0.4)]response = client.post("/api/v1/image_map/search_by_image",@@ -1086,9 +1151,9 @@ def test_cluster_labels_align_with_served_clusters(mock_invoker: Invoker, client("b2.png", axis_vec(1)),]:_save_unembedded_image(mock_invoker, name)- _records(mock_invoker).upsert_embedding(name, MODEL_ID, vec)+ _records(mock_invoker).upsert_embedding(IndexedItem("image", name), MODEL_ID, vec)coords = np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32)- _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a1.png", "a2.png", "b1.png", "b2.png"], coords)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a1.png", "a2.png", "b1.png", "b2.png"), coords)points = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()labels = client.get("/api/v1/image_map/cluster_labels", params={"eps": 0.5, "min_samples": 2, "top_k": 2}).json()[@@ -1138,9 +1203,9 @@ def test_cluster_labels_survive_a_non_finite_row_the_way_points_does(mock_invokevector = np.zeros(DIM, dtype=np.float32)vector[index % 2] = 1.0_save_unembedded_image(mock_invoker, name)- _records(mock_invoker).upsert_embedding(name, MODEL_ID, vector)+ _records(mock_invoker).upsert_embedding(IndexedItem("image", name), MODEL_ID, vector)coords = np.array([[0.0, 0.0], [0.2, 0.0], [np.nan, np.nan]], dtype=np.float32)- _seed_projection(mock_invoker, SYSTEM_USER_ID, names, coords)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), coords)points = client.get("/api/v1/image_map/points", params={"min_samples": 2}).json()labels_response = client.get("/api/v1/image_map/cluster_labels", params={"min_samples": 2})@@ -1156,7 +1221,7 @@ def test_cluster_labels_unavailable_text_encoder_conflicts(mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient) -> None:_seed_embedded_image(mock_invoker, "a.png")- _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a.png"], np.zeros((1, 2), dtype=np.float32))+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))image_index_service.text_unavailable = Trueassert client.get("/api/v1/image_map/cluster_labels").status_code == 409@@ -1272,7 +1337,9 @@ def test_image_labels_rank_the_vocabulary_for_one_image(mock_invoker: Invoker, c# unstable — happen to break a tie.vector = np.array([0.6, 0.8, 0.3, 0.1], dtype=np.float32)_save_unembedded_image(mock_invoker, "leaning.png")- _records(mock_invoker).upsert_embedding("leaning.png", MODEL_ID, vector / np.linalg.norm(vector))+ _records(mock_invoker).upsert_embedding(+ IndexedItem("image", "leaning.png"), MODEL_ID, vector / np.linalg.norm(vector)+ )body = client.get("/api/v1/image_map/image_labels", params={"image_name": "leaning.png"}).json()@@ -1365,7 +1432,7 @@ def test_image_labels_refuse_a_degenerate_stored_embedding(assert "label" not in response.json(), "a refusal must not carry an arbitrary vocabulary phrase"# The row IS present: this must be the degenerate-vector refusal, not the# not-indexed 404, or the test would pass without exercising the guard.- assert response.json()["detail"] == "This image's stored embedding cannot be labeled"+ assert response.json()["detail"] == "This item's stored embedding cannot be labeled"def test_image_labels_corrupt_blob_is_404_not_500(mock_invoker: Invoker, client: TestClient) -> None:@@ -1404,3 +1471,256 @@ def test_image_labels_dim_mismatch_with_the_vocabulary_is_404_not_500(response = client.get("/api/v1/image_map/image_labels", params={"image_name": "wide.png"})assert response.status_code == 404+++# --- Videos on the map ---+++def test_points_carry_the_kind_of_each_item(mock_invoker: Invoker, client: TestClient) -> None:+ # A client resolves a point's thumbnail from a kind-specific endpoint, so a video point+ # that claimed to be an image would render as a broken image.+ _seed_embedded_image(mock_invoker, "a.png")+ _seed_embedded_video(mock_invoker, "clip.mp4")+ _seed_projection(+ mock_invoker,+ SYSTEM_USER_ID,+ [IndexedItem("image", "a.png"), IndexedItem("video", "clip.mp4")],+ np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32),+ )++ body = client.get("/api/v1/image_map/points", params={"include_videos": True}).json()++ assert body["state"] == "ready"+ assert {(p["image_name"], p["kind"]) for p in body["points"]} == {("a.png", "image"), ("clip.mp4", "video")}+++def test_a_new_video_makes_the_projection_stale(mock_invoker: Invoker, client: TestClient) -> None:+ # Staleness is about the projection, not about what this client renders: the fit has to+ # cover the video before any client can be shown it, and the scope hash is taken over the+ # whole accessible set for exactly that reason. One refit per new item, the same as for a+ # new image — not a poll loop, since the refit clears it.+ _seed_embedded_image(mock_invoker, "a.png")+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))+ assert client.get("/api/v1/image_map/points").json()["stale"] is False++ _seed_embedded_video(mock_invoker, "clip.mp4")++ assert client.get("/api/v1/image_map/points").json()["stale"] is True+++def test_search_by_video_reference_uses_its_stored_embedding(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ _seed_embedded_video(mock_invoker, "ref.mp4")+ image_index_service.search_results = [+ (IndexedItem("video", "ref.mp4"), 1.0),+ (IndexedItem("image", "close.png"), 0.8),+ ]++ response = client.get("/api/v1/image_map/search", params={"video_name": "ref.mp4", "include_videos": True})++ assert response.status_code == 200+ assert response.json()["results"] == [+ {"image_name": "ref.mp4", "kind": "video", "score": 1.0},+ {"image_name": "close.png", "kind": "image", "score": 0.8},+ ]+ # The stored embedding was used; nothing was embedded on demand.+ assert image_index_service.embedded_images == []+++def test_search_refuses_both_an_image_and_a_video_reference(client: TestClient) -> None:+ response = client.get("/api/v1/image_map/search", params={"image_name": "a.png", "video_name": "clip.mp4"})++ assert response.status_code == 422+++def test_image_labels_accept_a_video(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ _seed_embedded_video(mock_invoker, "clip.mp4")++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "clip.mp4", "kind": "video"})++ assert response.status_code == 200+ assert response.json()["label"] in {"alpha", "beta", "gamma", "delta"}+++def test_image_labels_do_not_read_a_video_through_the_image_namespace(+ mock_invoker: Invoker, client: TestClient+) -> None:+ # Without the kind, a video name would be looked up among images: a 404 at best, and at+ # worst another item's embedding if the namespaces ever shared names.+ _seed_embedded_video(mock_invoker, "clip.mp4")++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "clip.mp4"})++ assert response.status_code == 404+++def test_points_hide_videos_unless_the_client_asks_for_them(mock_invoker: Invoker, client: TestClient) -> None:+ # A client that resolves every point through the images endpoints — which the shipped+ # gallery does — would render a video point as a broken tile, so serving them is opt-in.+ _seed_embedded_image(mock_invoker, "a.png")+ _seed_embedded_video(mock_invoker, "clip.mp4")+ _seed_projection(+ mock_invoker,+ SYSTEM_USER_ID,+ [IndexedItem("image", "a.png"), IndexedItem("video", "clip.mp4")],+ np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32),+ )++ body = client.get("/api/v1/image_map/points").json()++ assert [p["image_name"] for p in body["points"]] == ["a.png"]+ # The projection covers both items, so hiding one must not make the cache look stale —+ # that would have the client asking for a recompute on every poll, forever.+ assert body["stale"] is False+ assert body["state"] == "ready"+++def test_hidden_videos_are_left_out_of_the_status_count(mock_invoker: Invoker, client: TestClient) -> None:+ _seed_embedded_image(mock_invoker, "a.png")+ _seed_embedded_video(mock_invoker, "clip.mp4")+ _seed_projection(+ mock_invoker,+ SYSTEM_USER_ID,+ [IndexedItem("image", "a.png"), IndexedItem("video", "clip.mp4")],+ np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32),+ )++ default_body = client.get("/api/v1/image_map/status").json()+ opted_in_body = client.get("/api/v1/image_map/status", params={"include_videos": True}).json()++ assert default_body["projection"]["point_count"] == 1+ assert opted_in_body["projection"]["point_count"] == 2+++def test_cluster_labels_cover_the_same_items_as_points(mock_invoker: Invoker, client: TestClient) -> None:+ # The client compares the two responses' visible_hash and discards labels computed over a+ # different set, so both endpoints must apply the same kind filter.+ _seed_embedded_image(mock_invoker, "a.png")+ _seed_embedded_video(mock_invoker, "clip.mp4")+ _seed_projection(+ mock_invoker,+ SYSTEM_USER_ID,+ [IndexedItem("image", "a.png"), IndexedItem("video", "clip.mp4")],+ np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32),+ )++ for params in ({}, {"include_videos": True}):+ points = client.get("/api/v1/image_map/points", params=params).json()+ labels = client.get("/api/v1/image_map/cluster_labels", params=params).json()+ assert points["visible_hash"] == labels["visible_hash"], params+++def test_search_hides_videos_unless_the_client_asks_for_them(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ image_index_service.search_results = [(IndexedItem("video", "clip.mp4"), 0.9), (IndexedItem("image", "a.png"), 0.5)]++ default_body = client.get("/api/v1/image_map/search", params={"q": "cat"}).json()+ opted_in_body = client.get("/api/v1/image_map/search", params={"q": "cat", "include_videos": True}).json()++ assert [result["image_name"] for result in default_body["results"]] == ["a.png"]+ assert [result["image_name"] for result in opted_in_body["results"]] == ["clip.mp4", "a.png"]+ # The service is told which kinds to rank, rather than the endpoint trimming the ranking+ # afterwards — which would return fewer hits than the caller's limit.+ assert image_index_service.search_kinds == [("image",), ("image", "video")]+++def test_video_search_reference_embeds_the_thumbnail_on_demand(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ # A video that is not in the index — an intermediate, or one generated seconds ago — is+ # still usable as a reference: its thumbnail is embedded for this one query. Asking the+ # images store for it would 404 instead.+ mock_invoker.services.video_records.save(+ video_name="fresh.mp4",+ video_origin=ResourceOrigin.INTERNAL,+ video_category=ImageCategory.GENERAL,+ width=16,+ height=16,+ duration=2.0,+ fps=24.0,+ has_workflow=False,+ user_id=SYSTEM_USER_ID,+ )+ image_index_service.search_results = [(IndexedItem("image", "a.png"), 0.6)]++ response = client.get("/api/v1/image_map/search", params={"video_name": "fresh.mp4"})++ assert response.status_code == 200+ assert len(image_index_service.embedded_images) == 1+ # The thumbnail, not the video file: 16x16 is what the fixture writes.+ assert image_index_service.embedded_images[0].size == (16, 16)+++def test_video_search_reference_reports_a_missing_video_as_not_found(mock_invoker: Invoker, client: TestClient) -> None:+ response = client.get("/api/v1/image_map/search", params={"video_name": "no-such.mp4"})++ assert response.status_code == 404+++def test_multiuser_video_reference_enforces_read_access(multiuser, mock_invoker: Invoker, client: TestClient) -> None:+ # The video access clause is a different join against different tables than the image one,+ # so it needs its own end-to-end check: a wrong join leaks another user's private video.+ _create_user(mock_invoker, "[email protected]", is_admin=True)+ user1_id = _create_user(mock_invoker, "[email protected]")+ _create_user(mock_invoker, "[email protected]")+ user2_headers = _login(client, "[email protected]")++ _seed_embedded_video(mock_invoker, "private1.mp4", user_id=user1_id)++ refused = client.get("/api/v1/image_map/search", params={"video_name": "private1.mp4"}, headers=user2_headers)+ labels_refused = client.get(+ "/api/v1/image_map/image_labels",+ params={"image_name": "private1.mp4", "kind": "video"},+ headers=user2_headers,+ )++ assert refused.status_code == 403+ assert labels_refused.status_code == 403+++def test_multiuser_video_on_a_shared_board_is_readable(multiuser, mock_invoker: Invoker, client: TestClient) -> None:+ from invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibility++ _create_user(mock_invoker, "[email protected]", is_admin=True)+ user1_id = _create_user(mock_invoker, "[email protected]")+ _create_user(mock_invoker, "[email protected]")+ user2_headers = _login(client, "[email protected]")++ _seed_embedded_video(mock_invoker, "shared1.mp4", user_id=user1_id)+ board = mock_invoker.services.board_records.save("Shared", user1_id).board_id+ mock_invoker.services.board_records.update(board, BoardChanges(board_visibility=BoardVisibility.Shared))+ mock_invoker.services.board_video_records.add_video_to_board(board, "shared1.mp4")++ response = client.get("/api/v1/image_map/search", params={"video_name": "shared1.mp4"}, headers=user2_headers)++ assert response.status_code == 200+++def test_a_video_only_gallery_answers_empty_instead_of_asking_forever(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ # Nothing servable here is the kind filter's doing, not a failed fit: the projection covers+ # the video and its coordinates are fine. Diagnosing it as a failure asks the worker for a+ # recompute, which short-circuits on the matching scope hash and emits projection_ready —+ # which the client answers with another /points, for the life of the process.+ _seed_embedded_video(mock_invoker, "clip.mp4")+ _seed_projection(+ mock_invoker, SYSTEM_USER_ID, [IndexedItem("video", "clip.mp4")], np.zeros((1, 2), dtype=np.float32)+ )++ first = client.get("/api/v1/image_map/points").json()+ second = client.get("/api/v1/image_map/points").json()++ assert first["state"] == "empty"+ assert first["stale"] is False+ assert first["points"] == []+ # A settled answer, not one that changes every time the client asks again.+ assert second == first+ # The mechanism, not just the symptom: the endpoint must not ask for a recompute at all.+ # Each request is answered with a projection_ready event, which is what brings the client+ # back for another /points.+ assert image_index_service.projection_requests == []diff --git a/tests/app/services/image_index/test_image_index_records.py b/tests/app/services/image_index/test_image_index_records.pyindex 952be88bd3..1b61583171 100644--- a/tests/app/services/image_index/test_image_index_records.py+++ b/tests/app/services/image_index/test_image_index_records.py@@ -8,8 +8,10 @@ import pytestfrom invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStoragefrom invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibilityfrom invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage+from invokeai.app.services.board_video_records.board_video_records_sqlite import SqliteBoardVideoRecordStoragefrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.image_index.image_index_common import (+ IndexedItem,blob_to_coords,blob_to_embedding,coords_to_blob,@@ -24,6 +26,7 @@ from invokeai.app.services.image_records.image_records_sqlite import SqliteImagefrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabasefrom invokeai.app.services.users.users_common import UserCreateRequestfrom invokeai.app.services.users.users_default import UserService+from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStoragefrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.fixtures.sqlite_database import create_mock_sqlite_database@@ -54,6 +57,16 @@ def board_image_records(db: SqliteDatabase) -> SqliteBoardImageRecordStorage:return SqliteBoardImageRecordStorage(db=db)+def video_records(db: SqliteDatabase) -> SqliteVideoRecordStorage:+ return SqliteVideoRecordStorage(db=db)+++def board_video_records(db: SqliteDatabase) -> SqliteBoardVideoRecordStorage:+ return SqliteBoardVideoRecordStorage(db=db)++@pytest.fixturedef index_records(db: SqliteDatabase) -> ImageIndexRecordsSqlite:return ImageIndexRecordsSqlite(db=db)@@ -87,6 +100,37 @@ def _save_image()+def _save_video(+ video_records: SqliteVideoRecordStorage,+ video_name: str,+ user_id: str = SYSTEM_USER_ID,+ is_intermediate: bool = False,+ video_category: ImageCategory = ImageCategory.GENERAL,+) -> None:+ video_records.save(+ video_name=video_name,+ video_origin=ResourceOrigin.INTERNAL,+ video_category=video_category,+ width=64,+ height=64,+ duration=2.0,+ fps=24.0,+ has_workflow=False,+ is_intermediate=is_intermediate,+ user_id=user_id,+ )+++def imgs(*names: str) -> list[IndexedItem]:+ """The image-namespace items for these names."""+ return [IndexedItem("image", name) for name in names]+++def vids(*names: str) -> list[IndexedItem]:+ """The video-namespace items for these names."""+ return [IndexedItem("video", name) for name in names]++def _vec(seed: int) -> np.ndarray:rng = np.random.default_rng(seed)v = rng.standard_normal(DIM).astype(np.float32)@@ -194,12 +238,12 @@ def test_upsert_and_get_roundtrip(_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)+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, va)+ index_records.upsert_embedding(IndexedItem("image", "b.png"), MODEL_ID, vb)- names, matrix = index_records.get_embeddings(["b.png", "a.png", "missing.png"], MODEL_ID)+ names, matrix = index_records.get_embeddings(imgs("b.png", "a.png", "missing.png"), MODEL_ID)- assert names == ["b.png", "a.png"]+ assert names == imgs("b.png", "a.png")assert matrix.dtype == np.float32assert np.array_equal(matrix[0], vb)assert np.array_equal(matrix[1], va)@@ -209,12 +253,12 @@ 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))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))replacement = _vec(99)- index_records.upsert_embedding("a.png", MODEL_ID, replacement)+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, replacement)- names, matrix = index_records.get_embeddings(["a.png"], MODEL_ID)- assert names == ["a.png"]+ names, matrix = index_records.get_embeddings(imgs("a.png"), MODEL_ID)+ assert names == imgs("a.png")assert np.array_equal(matrix[0], replacement)@@ -226,8 +270,8 @@ def test_get_embeddings_empty_input_and_no_matches(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)+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))+ names, matrix = index_records.get_embeddings(imgs("a.png"), OTHER_MODEL_ID)assert names == []assert matrix.shape == (0, 0)@@ -241,11 +285,11 @@ def test_get_embeddings_chunks_large_requests(count = _IN_CLAUSE_CHUNK + 1for 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))+ index_records.upsert_embedding(IndexedItem("image", f"img-{i:04d}.png"), MODEL_ID, _vec(i))# Reverse order: SQLite would return each chunk in its own order, so this fails unless the# implementation reorders results back to the caller's sequence within every chunk.- requested = [f"img-{i:04d}.png" for i in reversed(range(count))]+ requested = [IndexedItem("image", f"img-{i:04d}.png") for i in reversed(range(count))]names, matrix = index_records.get_embeddings(requested, MODEL_ID)assert names == requestedassert matrix.shape == (count, DIM)@@ -261,7 +305,7 @@ def test_get_embeddings_rejects_inconsistent_dims(# the service's back, since upsert_embedding alone cannot produce the inconsistency._save_image(image_records, "a.png")_save_image(image_records, "b.png")- index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))short = np.ones(DIM // 2, dtype=np.float32)with db.transaction() as cursor:cursor.execute(@@ -270,31 +314,31 @@ def test_get_embeddings_rejects_inconsistent_dims()with pytest.raises(ValueError, match="Inconsistent embedding dims"):- index_records.get_embeddings(["a.png", "b.png"], MODEL_ID)+ index_records.get_embeddings(imgs("a.png", "b.png"), MODEL_ID)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))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))- names, matrix = index_records.get_embeddings(["a.png", "a.png"], MODEL_ID)+ names, matrix = index_records.get_embeddings(imgs("a.png", "a.png"), MODEL_ID)- assert names == ["a.png"]+ assert names == imgs("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] == []+ index_records.upsert_embedding(IndexedItem("image", "gone.png"), MODEL_ID, _vec(1))+ assert index_records.get_embeddings(imgs("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)+ "no-such-user", MODEL_ID, "hash-1", "{}", imgs("a.png"), np.zeros((1, 2), dtype=np.float32))assert index_records.get_projection("no-such-user", MODEL_ID) is None@@ -306,23 +350,23 @@ def test_skipped_write_raises_nothing_and_leaves_the_connection_usable(# IntegrityError. That matters because `db.transaction()` commits/rolls back the whole# shared connection: a swallowed error would leave the connection mid-statement-failure, and# an escaping one would roll back. Neither may happen, and the next write must still work.- index_records.upsert_embedding("gone.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "gone.png"), MODEL_ID, _vec(1))index_records.set_projection(- "no-such-user", MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ "no-such-user", MODEL_ID, "hash-1", "{}", imgs("a.png"), np.zeros((1, 2), dtype=np.float32))assert db._conn.in_transaction is False_save_image(image_records, "real.png")- index_records.upsert_embedding("real.png", MODEL_ID, _vec(2))- assert index_records.get_embeddings(["real.png"], MODEL_ID)[0] == ["real.png"]+ index_records.upsert_embedding(IndexedItem("image", "real.png"), MODEL_ID, _vec(2))+ assert index_records.get_embeddings(imgs("real.png"), MODEL_ID)[0] == imgs("real.png")def test_skipped_write_does_not_raise_integrity_error(index_records: ImageIndexRecordsSqlite) -> None:# Pin the mechanism, not just the outcome: if the guard regressed to relying on the foreign# key, this would raise instead of no-opping.try:- index_records.upsert_embedding("gone.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "gone.png"), MODEL_ID, _vec(1))except sqlite3.IntegrityError as exc: # pragma: no cover - the assertion is the pointpytest.fail(f"missing-parent write must be a no-op, not an IntegrityError: {exc}")@@ -331,38 +375,38 @@ 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.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), OTHER_MODEL_ID, _vec(2))- index_records.delete_embedding("a.png")+ index_records.delete_embedding(IndexedItem("image", "a.png"))- assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == []- assert index_records.get_embeddings(["a.png"], OTHER_MODEL_ID)[0] == []+ assert index_records.get_embeddings(imgs("a.png"), MODEL_ID)[0] == []+ assert index_records.get_embeddings(imgs("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))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))image_records.delete("a.png")- assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == []+ assert index_records.get_embeddings(imgs("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))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "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] == []+ assert index_records.get_embeddings(imgs("a.png"), MODEL_ID)[0] == imgs("a.png")+ assert index_records.get_embeddings(imgs("a.png"), OTHER_MODEL_ID)[0] == []# --- Eligibility: backfill listing and status counts ---@@ -375,11 +419,11 @@ def test_list_unembedded_skips_ineligible_and_embedded(_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))+ index_records.upsert_embedding(IndexedItem("image", "embedded.png"), MODEL_ID, _vec(1))- unembedded = index_records.list_unembedded_image_names(MODEL_ID, limit=10)+ unembedded = index_records.list_unembedded_items(MODEL_ID, limit=10)- assert unembedded == ["eligible.png"]+ assert unembedded == imgs("eligible.png")def test_list_unembedded_respects_limit_and_returns_oldest_first(@@ -398,32 +442,32 @@ def test_list_unembedded_respects_limit_and_returns_oldest_first((f"2026-01-0{5 - i} 00:00:00.000", f"img-{i}.png"),)- batch = index_records.list_unembedded_image_names(MODEL_ID, limit=3)+ batch = index_records.list_unembedded_items(MODEL_ID, limit=3)# Which three matters, not just how many: backfill walks oldest-first, and a reversed order# would silently re-scan the newest images forever while the oldest never got embedded.- assert batch == ["img-4.png", "img-3.png", "img-2.png"]+ assert batch == imgs("img-4.png", "img-3.png", "img-2.png")def test_list_unembedded_rejects_negative_limit(index_records: ImageIndexRecordsSqlite) -> None:# SQLite reads a negative LIMIT as unbounded, which would turn a bounded backfill batch into# a full-table load.with pytest.raises(ValueError, match="non-negative"):- index_records.list_unembedded_image_names(MODEL_ID, limit=-1)+ index_records.list_unembedded_items(MODEL_ID, limit=-1)def test_list_unembedded_zero_limit_returns_nothing(image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:_save_image(image_records, "a.png")- assert index_records.list_unembedded_image_names(MODEL_ID, limit=0) == []+ assert index_records.list_unembedded_items(MODEL_ID, limit=0) == []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))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))status = index_records.count_index_status(MODEL_ID)@@ -445,10 +489,10 @@ def test_accessible_images_scoping(# 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))+ index_records.upsert_embedding(IndexedItem("image", 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))+ index_records.upsert_embedding(IndexedItem("image", "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)@@ -462,25 +506,25 @@ def test_accessible_images_scoping(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"]+ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == sorted(+ imgs("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"]+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == sorted(+ imgs("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(- [+ assert index_records.list_accessible_embedded_items(None, MODEL_ID) == sorted(+ imgs("own-unboarded.png","own-private.png","own-shared.png","own-public.png","theirs-unboarded.png",- ]+ ))@@ -496,7 +540,7 @@ def test_accessible_images_includes_individually_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))+ index_records.upsert_embedding(IndexedItem("image", "own-individually-shared.png"), MODEL_ID, _vec(1))board_id = board_records.save("Individually shared", SYSTEM_USER_ID).board_idboard_image_records.add_image_to_board(board_id, "own-individually-shared.png")with db.transaction() as cursor:@@ -505,13 +549,13 @@ def test_accessible_images_includes_individually_shared_boards((board_id, other_user_id, False),)- assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["own-individually-shared.png"]+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == imgs("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) == []+ assert index_records.list_accessible_embedded_items(third_user.user_id, MODEL_ID) == []def test_accessible_images_includes_boards_owned_by_user(@@ -526,14 +570,14 @@ def test_accessible_images_includes_boards_owned_by_user(# (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))+ index_records.upsert_embedding(IndexedItem("image", "theirs-on-my-board.png"), MODEL_ID, _vec(1))my_board = board_records.save("Mine", SYSTEM_USER_ID).board_idboard_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"]+ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == imgs("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) == []+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == []def test_accessible_images_excludes_archived_boards(@@ -549,7 +593,7 @@ def test_accessible_images_excludes_archived_boards(_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))+ index_records.upsert_embedding(IndexedItem("image", name), MODEL_ID, _vec(seed))archived_board = board_records.save("Archived", SYSTEM_USER_ID).board_idarchived_shared_board = board_records.save("Archived shared", SYSTEM_USER_ID).board_id@@ -560,11 +604,11 @@ def test_accessible_images_excludes_archived_boards(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"]+ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == imgs("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) == []+ assert index_records.list_accessible_embedded_items(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"]+ assert index_records.list_accessible_embedded_items(None, MODEL_ID) == imgs("own-unboarded.png")def test_accessible_images_returns_boarded_images_once(@@ -578,11 +622,11 @@ def test_accessible_images_returns_boarded_images_once(# board_images ever became many-to-many, the result would duplicate and the scope hash# (derived from this list) would change without the accessible set changing._save_image(image_records, "a.png")- index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))board_a = board_records.save("A", SYSTEM_USER_ID).board_idboard_image_records.add_image_to_board(board_a, "a.png")- assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["a.png"]+ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == imgs("a.png")def test_accessible_images_are_filtered_by_model_id(@@ -597,8 +641,8 @@ def test_accessible_images_are_filtered_by_model_id(# whose embeddings get_embeddings cannot return, desynchronizing names from coordinates._save_image(image_records, "current.png")_save_image(image_records, "stale.png")- index_records.upsert_embedding("current.png", MODEL_ID, _vec(1))- index_records.upsert_embedding("stale.png", OTHER_MODEL_ID, _vec(2))+ index_records.upsert_embedding(IndexedItem("image", "current.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "stale.png"), OTHER_MODEL_ID, _vec(2))shared = board_records.save("Shared", SYSTEM_USER_ID).board_idboard_records.update(shared, BoardChanges(board_visibility=BoardVisibility.Shared))@@ -606,10 +650,10 @@ def test_accessible_images_are_filtered_by_model_id(board_image_records.add_image_to_board(shared, "stale.png")# Every scope must apply the filter, not just the owner's.- assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["current.png"]- assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["current.png"]- assert index_records.list_accessible_embedded_images(None, MODEL_ID) == ["current.png"]- assert index_records.list_accessible_embedded_images(None, OTHER_MODEL_ID) == ["stale.png"]+ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == imgs("current.png")+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == imgs("current.png")+ assert index_records.list_accessible_embedded_items(None, MODEL_ID) == imgs("current.png")+ assert index_records.list_accessible_embedded_items(None, OTHER_MODEL_ID) == imgs("stale.png")def test_accessible_images_exclude_individually_shared_archived_board(@@ -623,7 +667,7 @@ def test_accessible_images_exclude_individually_shared_archived_board(# Archiving is tested for visibility-shared boards; the shared_boards grant is a separate# branch of the access clause and must be archived-gated too._save_image(image_records, "granted.png")- index_records.upsert_embedding("granted.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "granted.png"), MODEL_ID, _vec(1))board_id = board_records.save("Private", SYSTEM_USER_ID).board_idboard_image_records.add_image_to_board(board_id, "granted.png")with db.transaction() as cursor:@@ -632,11 +676,11 @@ def test_accessible_images_exclude_individually_shared_archived_board((board_id, other_user_id),)- assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["granted.png"]+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == imgs("granted.png")board_records.update(board_id, BoardChanges(archived=True))- assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == []+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == []# --- Projections ---@@ -644,7 +688,9 @@ def test_accessible_images_exclude_individually_shared_archived_board(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)+ index_records.set_projection(+ SYSTEM_USER_ID, MODEL_ID, "hash-1", '{"n_neighbors": 15}', imgs("a.png", "b.png"), coords+ )record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)@@ -652,16 +698,16 @@ def test_projection_roundtrip(index_records: ImageIndexRecordsSqlite) -> 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 record.items == imgs("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)+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", imgs("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)+ SYSTEM_USER_ID, MODEL_ID, "hash-2", "{}", imgs("a.png", "b.png"), np.ones((2, 2), dtype=np.float32))record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)@@ -676,7 +722,7 @@ def test_projection_missing_and_delete_idempotent(index_records: ImageIndexRecorindex_records.delete_projection(SYSTEM_USER_ID, MODEL_ID) # no-opindex_records.set_projection(- SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", imgs("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@@ -685,7 +731,7 @@ def test_projection_missing_and_delete_idempotent(index_records: ImageIndexRecordef 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)+ SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", imgs("a.png"), np.zeros((2, 2), dtype=np.float32))@@ -708,3 +754,219 @@ def test_custom_vocab_case_variant_duplicates_cannot_fail_the_replace(index_reco# 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()) == 1+++# --- Videos ---+++def test_videos_are_stored_counted_and_listed_alongside_images(+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_image(image_records, "a.png")+ _save_video(video_records, "clip.mp4")+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("video", "clip.mp4"), MODEL_ID, _vec(2))++ status = index_records.count_index_status(MODEL_ID)+ assert (status.total, status.embedded) == (2, 2)++ items, matrix = index_records.get_embeddings(+ [IndexedItem("video", "clip.mp4"), IndexedItem("image", "a.png")], MODEL_ID+ )+ # Rows follow the caller's order across both namespaces, not one namespace after the other.+ assert items == [IndexedItem("video", "clip.mp4"), IndexedItem("image", "a.png")]+ assert np.array_equal(matrix[0], _vec(2))+ assert np.array_equal(matrix[1], _vec(1))+++def test_an_image_and_a_video_are_different_items(+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ # Names are generated with kind-specific extensions, so this cannot happen by accident —+ # but the namespaces must not be able to read or overwrite each other's rows.+ _save_image(image_records, "same.png")+ _save_video(video_records, "same.png")+ index_records.upsert_embedding(IndexedItem("image", "same.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("video", "same.png"), MODEL_ID, _vec(2))++ assert np.array_equal(index_records.get_embeddings(imgs("same.png"), MODEL_ID)[1][0], _vec(1))+ assert np.array_equal(index_records.get_embeddings(vids("same.png"), MODEL_ID)[1][0], _vec(2))++ index_records.delete_embedding(IndexedItem("image", "same.png"))+ assert index_records.get_embeddings(imgs("same.png"), MODEL_ID)[0] == []+ assert index_records.get_embeddings(vids("same.png"), MODEL_ID)[0] == vids("same.png")+++def test_ineligible_videos_are_not_indexable(+ video_records: SqliteVideoRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_video(video_records, "eligible.mp4")+ _save_video(video_records, "intermediate.mp4", is_intermediate=True)+ _save_video(video_records, "mask.mp4", video_category=ImageCategory.MASK)++ assert index_records.list_unembedded_items(MODEL_ID, limit=10) == vids("eligible.mp4")+ assert index_records.count_index_status(MODEL_ID).total == 1+++def test_unembedded_listing_merges_both_kinds_oldest_first(+ db: SqliteDatabase,+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ # Interleaved creation times: listing one namespace and then the other would put every+ # image before any video, so a video generated hours ago would wait behind newer images.+ # Timestamps are set explicitly because four rows saved in a row land in the same+ # millisecond, and then only the name tiebreak would be under test.+ _save_image(image_records, "first.png")+ _save_video(video_records, "second.mp4")+ _save_image(image_records, "third.png")+ _save_video(video_records, "fourth.mp4")+ with db.transaction() as cursor:+ for table, column, name, created_at in (+ ("images", "image_name", "first.png", "2026-01-01 00:00:01.000"),+ ("videos", "video_name", "second.mp4", "2026-01-01 00:00:02.000"),+ ("images", "image_name", "third.png", "2026-01-01 00:00:03.000"),+ ("videos", "video_name", "fourth.mp4", "2026-01-01 00:00:04.000"),+ ):+ cursor.execute(f"UPDATE {table} SET created_at = ? WHERE {column} = ?;", (created_at, name))++ batch = index_records.list_unembedded_items(MODEL_ID, limit=3)++ assert batch == [+ IndexedItem("image", "first.png"),+ IndexedItem("video", "second.mp4"),+ IndexedItem("image", "third.png"),+ ]+++def test_deleting_a_video_deletes_its_embedding(+ video_records: SqliteVideoRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_video(video_records, "clip.mp4")+ index_records.upsert_embedding(IndexedItem("video", "clip.mp4"), MODEL_ID, _vec(1))++ video_records.delete("clip.mp4")++ assert index_records.get_embeddings(vids("clip.mp4"), MODEL_ID)[0] == []+++def test_embedding_a_missing_video_is_a_noop(index_records: ImageIndexRecordsSqlite) -> None:+ # The video may be deleted between being scheduled and embedded; the write is dropped+ # rather than raising a foreign-key error at the worker.+ index_records.upsert_embedding(IndexedItem("video", "gone.mp4"), MODEL_ID, _vec(1))+ assert index_records.get_embeddings(vids("gone.mp4"), MODEL_ID)[0] == []+++def test_video_access_scoping_follows_board_membership(+ video_records: SqliteVideoRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_video_records: SqliteBoardVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ _save_video(video_records, "own-unboarded.mp4")+ _save_video(video_records, "own-shared.mp4")+ _save_video(video_records, "own-private.mp4")+ for seed, name in enumerate(["own-unboarded.mp4", "own-shared.mp4", "own-private.mp4"]):+ index_records.upsert_embedding(IndexedItem("video", name), MODEL_ID, _vec(seed))++ shared_board = board_records.save("Shared", SYSTEM_USER_ID).board_id+ private_board = board_records.save("Private", SYSTEM_USER_ID).board_id+ board_records.update(shared_board, BoardChanges(board_visibility=BoardVisibility.Shared))+ board_video_records.add_video_to_board(shared_board, "own-shared.mp4")+ board_video_records.add_video_to_board(private_board, "own-private.mp4")++ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == sorted(+ vids("own-unboarded.mp4", "own-shared.mp4", "own-private.mp4")+ )+ # The other user sees the shared board's video and nothing else of ours.+ assert index_records.list_accessible_embedded_items(other_user_id, MODEL_ID) == vids("own-shared.mp4")+++def test_videos_on_archived_boards_are_hidden_from_every_scope(+ video_records: SqliteVideoRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_video_records: SqliteBoardVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_video(video_records, "archived.mp4")+ index_records.upsert_embedding(IndexedItem("video", "archived.mp4"), MODEL_ID, _vec(1))+ board = board_records.save("Archived", SYSTEM_USER_ID).board_id+ board_video_records.add_video_to_board(board, "archived.mp4")+ board_records.update(board, BoardChanges(archived=True))++ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == []+ assert index_records.list_accessible_embedded_items(None, MODEL_ID) == []+++def test_accessible_listing_orders_images_before_videos(+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ # The listing feeds the projection scope hash and the search matrix, both of which need a+ # stable order across calls.+ _save_video(video_records, "a.mp4")+ _save_image(image_records, "z.png")+ index_records.upsert_embedding(IndexedItem("video", "a.mp4"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("image", "z.png"), MODEL_ID, _vec(2))++ assert index_records.list_accessible_embedded_items(SYSTEM_USER_ID, MODEL_ID) == [+ IndexedItem("image", "z.png"),+ IndexedItem("video", "a.mp4"),+ ]+++def test_projection_roundtrips_mixed_items(index_records: ImageIndexRecordsSqlite) -> None:+ coords = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)+ items = [IndexedItem("image", "a.png"), IndexedItem("video", "clip.mp4")]++ index_records.set_projection(SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", items, coords)++ record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)+ assert record is not None+ assert record.items == items+++def test_projection_without_stored_kinds_reads_as_images(+ db: SqliteDatabase, index_records: ImageIndexRecordsSqlite+) -> None:+ # Rows written before videos were indexable have no kinds column. They are all-image+ # projections, and must keep serving rather than being discarded on upgrade.+ coords = coords_to_blob(np.array([[1.0, 2.0]], dtype=np.float32))+ with db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)+ VALUES (?, ?, ?, ?, ?, ?, ?);+ """,+ (SYSTEM_USER_ID, MODEL_ID, "hash-1", "{}", 1, '["legacy.png"]', coords),+ )++ record = index_records.get_projection(SYSTEM_USER_ID, MODEL_ID)++ assert record is not None+ assert record.items == imgs("legacy.png")+++def test_delete_embeddings_for_other_models_covers_both_kinds(+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_image(image_records, "a.png")+ _save_video(video_records, "clip.mp4")+ index_records.upsert_embedding(IndexedItem("image", "a.png"), OTHER_MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("video", "clip.mp4"), OTHER_MODEL_ID, _vec(2))+ index_records.upsert_embedding(IndexedItem("video", "clip.mp4"), MODEL_ID, _vec(3))++ # A video indexed by a since-replaced model is as dead as an image indexed by one.+ assert index_records.delete_embeddings_for_other_models(MODEL_ID) == 2+ assert index_records.get_embeddings(imgs("a.png"), OTHER_MODEL_ID)[0] == []+ assert index_records.get_embeddings(vids("clip.mp4"), OTHER_MODEL_ID)[0] == []+ assert index_records.get_embeddings(vids("clip.mp4"), MODEL_ID)[0] == vids("clip.mp4")diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 47bd39bfb2..8fb1a9a7be 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -4,6 +4,7 @@ import inspectimport threadingimport timeimport weakref+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Callablefrom unittest.mock import patch@@ -16,7 +17,7 @@ from PIL import Imagefrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.events.events_common import ImageIndexStatusEvent, ImageIndexUpdatedEventfrom invokeai.app.services.image_index import image_index_default-from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE+from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, IndexedItemfrom invokeai.app.services.image_index.image_index_default import (_ACTIVATION_RETRY_INTERVAL_S,_MAX_ATTEMPTS,@@ -30,6 +31,9 @@ from invokeai.app.services.image_records.image_records_sqlite import SqliteImagefrom invokeai.app.services.images.images_common import image_record_to_dtofrom invokeai.app.services.images.images_default import ImageServicefrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStorage+from invokeai.app.services.videos.videos_common import VideoDTO, video_record_to_dto+from invokeai.app.services.videos.videos_default import VideoServicefrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.fixtures.sqlite_database import create_mock_sqlite_database@@ -59,6 +63,16 @@ def _wait_for_spent_retry(service: "ImageIndexService", user_id: str, scope: str_wait_until(lambda: service._failed_projection_scopes.get(user_id) == scope, timeout=15)+def imgs(*names: str) -> list[IndexedItem]:+ """The image-namespace items for these names."""+ return [IndexedItem("image", name) for name in names]+++def vids(*names: str) -> list[IndexedItem]:+ """The video-namespace items for these names."""+ return [IndexedItem("video", name) for name in names]++def _unit_vec() -> np.ndarray:"""A storable embedding: float32, finite, non-zero."""v = np.ones(DIM, dtype=np.float32)@@ -95,6 +109,29 @@ def images_service() -> ImageService:return images+def video_records(db: SqliteDatabase) -> SqliteVideoRecordStorage:+ return SqliteVideoRecordStorage(db=db)+++def videos_service(tmp_path: Path) -> VideoService:+ """A video service whose thumbnails are real files, as the worker reads them from disk."""+ videos = VideoService()+ thumbnails = tmp_path / "video-thumbnails"+ thumbnails.mkdir()++ def get_path(video_name: str, thumbnail: bool = False) -> str:+ assert thumbnail, "the index only ever reads a video's thumbnail"+ path = thumbnails / f"{video_name}.webp"+ if not path.exists():+ Image.new("RGB", (16, 16), "teal").save(path, "WEBP")+ return str(path)++ videos.get_path = get_path # type: ignore[method-assign]+ return videos++def _make_invoker(images_service: ImageService,index_records: ImageIndexRecordsSqlite,@@ -103,6 +140,8 @@ def _make_invoker(device: str | None = "cpu",session_queue: object | None = None,model_manager: object | None = None,+ videos_service: VideoService | None = None,+ video_records: SqliteVideoRecordStorage | None = None,) -> SimpleNamespace:config = InvokeAIAppConfig(use_memory_db=True,@@ -115,6 +154,8 @@ def _make_invoker(logger=InvokeAILogger.get_logger(),images=images_service,image_records=image_records,+ videos=videos_service if videos_service is not None else VideoService(),+ video_records=video_records,image_index_records=index_records,events=TestEventService(),session_queue=session_queue,@@ -160,6 +201,31 @@ def _save_image()+def _save_video(+ video_records: SqliteVideoRecordStorage,+ video_name: str,+ is_intermediate: bool = False,+ video_category: ImageCategory = ImageCategory.GENERAL,+) -> None:+ video_records.save(+ video_name=video_name,+ video_origin=ResourceOrigin.INTERNAL,+ video_category=video_category,+ width=16,+ height=16,+ duration=2.0,+ fps=24.0,+ has_workflow=False,+ is_intermediate=is_intermediate,+ user_id="system",+ )+++def _video_dto_for(video_records: SqliteVideoRecordStorage, video_name: str) -> VideoDTO:+ record = video_records.get(video_name)+ return video_record_to_dto(record, video_url="http://x/v.mp4", thumbnail_url="http://x/v.webp", board_id=None)++def _dto_for(image_records: SqliteImageRecordStorage, image_name: str):record = image_records.get(image_name)return image_record_to_dto(record, image_url="http://x/i.png", thumbnail_url="http://x/t.png", board_id=None)@@ -202,9 +268,9 @@ def test_backfill_indexes_preexisting_eligible_images(assert status.total == 6assert status.pending == 0# Ineligible images have no rows.- assert index_records.get_embeddings(["intermediate.png", "mask.png"], MODEL_ID)[0] == []+ assert index_records.get_embeddings(imgs("intermediate.png", "mask.png"), MODEL_ID)[0] == []# Stored embeddings are L2-normalized.- _, matrix = index_records.get_embeddings([f"img-{i}.png" for i in range(6)], MODEL_ID)+ _, matrix = index_records.get_embeddings([IndexedItem("image", f"img-{i}.png") for i in range(6)], MODEL_ID)assert np.allclose(np.linalg.norm(matrix, axis=1), 1.0, atol=1e-5)@@ -224,8 +290,8 @@ def test_on_changed_indexes_new_eligible_image_and_skips_ineligible(images_service._on_changed(_dto_for(image_records, "new.png"))images_service._on_changed(_dto_for(image_records, "new-intermediate.png"))- _wait_until(lambda: index_records.get_embeddings(["new.png"], MODEL_ID)[0] == ["new.png"])- assert index_records.get_embeddings(["new-intermediate.png"], MODEL_ID)[0] == []+ _wait_until(lambda: index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"))+ assert index_records.get_embeddings(imgs("new-intermediate.png"), MODEL_ID)[0] == []def test_unloadable_image_is_skipped_and_backfill_completes(@@ -246,9 +312,9 @@ def test_unloadable_image_is_skipped_and_backfill_completes(service.start(_make_invoker(images_service, index_records))_wait_until(lambda: not service._backfill_pending.is_set())- assert index_records.get_embeddings(["good.png"], MODEL_ID)[0] == ["good.png"]- assert index_records.get_embeddings(["bad.png"], MODEL_ID)[0] == []- assert "bad.png" in service._failed+ assert index_records.get_embeddings(imgs("good.png"), MODEL_ID)[0] == imgs("good.png")+ assert index_records.get_embeddings(imgs("bad.png"), MODEL_ID)[0] == []+ assert IndexedItem("image", "bad.png") in service._faileddef test_transient_encode_failure_is_retried_to_success(@@ -268,8 +334,8 @@ def test_transient_encode_failure_is_retried_to_success(try:_save_image(image_records, "a.png")service.start(_make_invoker(images_service, index_records))- _wait_until(lambda: index_records.get_embeddings(["a.png"], MODEL_ID)[0] == ["a.png"], timeout=15)- assert "a.png" not in service._failed+ _wait_until(lambda: index_records.get_embeddings(imgs("a.png"), MODEL_ID)[0] == imgs("a.png"), timeout=15)+ assert IndexedItem("image", "a.png") not in service._failedfinally:service.stop()@@ -458,7 +524,7 @@ def test_broken_encoder_leaves_images_pending_rather_than_quarantined(# bounds per-image badness only. Retiring the image here would be a lie about the image# and — since nothing but a successful embed clears `_failed` — would survive the# encoder being fixed, leaving the index short until a restart.- assert "a.png" not in service._failed+ assert IndexedItem("image", "a.png") not in service._failedassert service.get_status().pending == 1finally:service.stop()@@ -552,10 +618,10 @@ def test_sustained_storage_failure_does_not_quarantine_images(outage = {"active": True}real_upsert = index_records.upsert_embedding- def flaky_upsert(name: str, model_id: str, embedding: np.ndarray) -> None:+ def flaky_upsert(item: IndexedItem, model_id: str, embedding: np.ndarray) -> None:if outage["active"]:raise RuntimeError("database is locked")- real_upsert(name, model_id, embedding)+ real_upsert(item, model_id, embedding)index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]@@ -646,10 +712,10 @@ def test_zero_norm_embedding_fails_only_its_own_image(_wait_until(lambda: not service._backfill_pending.is_set())# The healthy image is embedded despite sharing a batch with the degenerate one.- assert index_records.get_embeddings(["b-good.png"], MODEL_ID)[0] == ["b-good.png"]- assert index_records.get_embeddings(["a-bad.png"], MODEL_ID)[0] == []- _wait_until(lambda: "a-bad.png" in service._failed)- assert "b-good.png" not in service._failed+ assert index_records.get_embeddings(imgs("b-good.png"), MODEL_ID)[0] == imgs("b-good.png")+ assert index_records.get_embeddings(imgs("a-bad.png"), MODEL_ID)[0] == []+ _wait_until(lambda: IndexedItem("image", "a-bad.png") in service._failed)+ assert IndexedItem("image", "b-good.png") not in service._failedfinally:service.stop()@@ -666,17 +732,17 @@ def test_start_discards_only_other_models_embeddings(boot, and if it pruned nothing the index would accumulate dead rows forever."""_save_image(image_records, "a.png")- index_records.upsert_embedding("a.png", MODEL_ID, _unit_vec())- index_records.upsert_embedding("a.png", "stale-model-hash", _unit_vec())- assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == ["a.png"]+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _unit_vec())+ index_records.upsert_embedding(IndexedItem("image", "a.png"), "stale-model-hash", _unit_vec())+ assert index_records.get_embeddings(imgs("a.png"), "stale-model-hash")[0] == imgs("a.png")service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)try:service.start(_make_invoker(images_service, index_records))_wait_until(lambda: not service._backfill_pending.is_set())- assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == []- assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == ["a.png"]+ assert index_records.get_embeddings(imgs("a.png"), "stale-model-hash")[0] == []+ assert index_records.get_embeddings(imgs("a.png"), MODEL_ID)[0] == imgs("a.png")finally:service.stop()@@ -688,12 +754,12 @@ def test_disabled_service_does_not_discard_embeddings() -> None:"""Turning the feature off must not destroy an index built while it was on."""_save_image(image_records, "a.png")- index_records.upsert_embedding("a.png", "stale-model-hash", _unit_vec())+ index_records.upsert_embedding(IndexedItem("image", "a.png"), "stale-model-hash", _unit_vec())service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)try:service.start(_make_invoker(images_service, index_records, enabled=False))- assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == ["a.png"]+ assert index_records.get_embeddings(imgs("a.png"), "stale-model-hash")[0] == imgs("a.png")finally:service.stop()@@ -769,7 +835,7 @@ def test_projection_does_not_wait_for_an_in_progress_generation(# One image already embedded (so the projection has input) and one that cannot# be embedded while the generation holds the GPU (so the worker parks)._save_image(image_records, "done.png")- index_records.upsert_embedding("done.png", MODEL_ID, _unit_vec())+ index_records.upsert_embedding(IndexedItem("image", "done.png"), MODEL_ID, _unit_vec())_save_image(image_records, "waiting.png")service.start(_make_invoker(images_service, index_records, device=None, session_queue=session_queue))@@ -779,9 +845,9 @@ def test_projection_does_not_wait_for_an_in_progress_generation(_wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=20.0)record = index_records.get_projection("system", MODEL_ID)assert record is not None- assert record.image_names == ["done.png"]+ assert record.items == imgs("done.png")# And the embed really is still parked behind the generation.- assert index_records.get_embeddings(["waiting.png"], MODEL_ID)[0] == []+ assert index_records.get_embeddings(imgs("waiting.png"), MODEL_ID)[0] == []finally:service.stop()@@ -808,9 +874,9 @@ def test_a_partially_stored_batch_does_not_escalate_the_backoff(real_upsert = index_records.upsert_embedding- def flaky_upsert(image_name, model_id, embedding):- if image_name == "stored.png":- return real_upsert(image_name, model_id, embedding)+ def flaky_upsert(item, model_id, embedding):+ if item.name == "stored.png":+ return real_upsert(item, model_id, embedding)raise RuntimeError("database is locked")index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]@@ -820,12 +886,12 @@ def test_a_partially_stored_batch_does_not_escalate_the_backoff(# Several rounds: the escalation this guards against is cumulative.for _ in range(8):- assert service._process_batch(["stored.png", "locked.png"]) is False+ assert service._process_batch(imgs("stored.png", "locked.png")) is Falseassert service._systemic_failures == 0, "progress must clear the outage counter"assert service._backoff_seconds() == _POLL_SECONDS, "a draining index must not back off"# The half that stored is stored, and no image was charged an attempt.- assert index_records.get_embeddings(["stored.png"], MODEL_ID)[0] == ["stored.png"]+ assert index_records.get_embeddings(imgs("stored.png"), MODEL_ID)[0] == imgs("stored.png")assert service._failed == set()assert service._attempts == {}finally:@@ -979,7 +1045,7 @@ def test_permanently_failed_image_still_reaches_quiescence(invoker = _make_invoker(images_service, index_records)service.start(invoker)- _wait_until(lambda: "bad.png" in service._failed, timeout=15.0)+ _wait_until(lambda: IndexedItem("image", "bad.png") in service._failed, timeout=15.0)# Failed images are excluded from pending, so the index settles and the# final emitted status reports quiescence over the embeddable remainder._wait_until(lambda: any(e.total == 2 and e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))@@ -1003,18 +1069,18 @@ def test_upsert_failure_routes_through_retry_to_success(real_upsert = index_records.upsert_embeddingcalls = {"count": 0}- def flaky_upsert(name: str, model_id: str, embedding: np.ndarray) -> None:+ def flaky_upsert(item: IndexedItem, model_id: str, embedding: np.ndarray) -> None:calls["count"] += 1if calls["count"] == 1:raise RuntimeError("database is locked")- real_upsert(name, model_id, embedding)+ real_upsert(item, model_id, embedding)index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]_save_image(image_records, "flaky.png")images_service._on_changed(_dto_for(image_records, "flaky.png"))- _wait_until(lambda: index_records.get_embeddings(["flaky.png"], MODEL_ID)[0] == ["flaky.png"], timeout=15.0)+ _wait_until(lambda: index_records.get_embeddings(imgs("flaky.png"), MODEL_ID)[0] == imgs("flaky.png"), timeout=15.0)_wait_until(lambda: any(e.total == 1 and e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))@@ -1038,18 +1104,18 @@ def test_upsert_value_error_also_routes_through_retry(real_upsert = index_records.upsert_embeddingcalls = {"count": 0}- def flaky_upsert(name: str, model_id: str, embedding: np.ndarray) -> None:+ def flaky_upsert(item: IndexedItem, model_id: str, embedding: np.ndarray) -> None:calls["count"] += 1if calls["count"] == 1:raise ValueError("rejected by a future storage-layer validation")- real_upsert(name, model_id, embedding)+ real_upsert(item, model_id, embedding)index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]_save_image(image_records, "flaky.png")images_service._on_changed(_dto_for(image_records, "flaky.png"))- _wait_until(lambda: index_records.get_embeddings(["flaky.png"], MODEL_ID)[0] == ["flaky.png"], timeout=15.0)+ _wait_until(lambda: index_records.get_embeddings(imgs("flaky.png"), MODEL_ID)[0] == imgs("flaky.png"), timeout=15.0)_wait_until(lambda: any(e.total == 1 and e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))@@ -1073,10 +1139,10 @@ def test_normalizable_extreme_magnitudes_are_not_dropped(service.start(_make_invoker(images_service, index_records))_wait_until(lambda: not service._backfill_pending.is_set())- names, matrix = index_records.get_embeddings(["tiny.png"], MODEL_ID)- assert names == ["tiny.png"]+ names, matrix = index_records.get_embeddings(imgs("tiny.png"), MODEL_ID)+ assert names == imgs("tiny.png")assert np.isclose(np.linalg.norm(matrix[0]), 1.0)- assert "tiny.png" not in service._failed+ assert IndexedItem("image", "tiny.png") not in service._failedfinally:service.stop()@@ -1092,13 +1158,13 @@ def test_ineligible_transition_clears_failure_bookkeeping(service.start(invoker)_wait_until(lambda: not service._backfill_pending.is_set())- service._failed.add("gone.png")- service._attempts["gone.png"] = 3+ service._failed.add(IndexedItem("image", "gone.png"))+ service._attempts[IndexedItem("image", "gone.png")] = 3_save_image(image_records, "gone.png", image_category=ImageCategory.MASK)images_service._on_changed(_dto_for(image_records, "gone.png"))- assert "gone.png" not in service._failed- assert "gone.png" not in service._attempts+ assert IndexedItem("image", "gone.png") not in service._failed+ assert IndexedItem("image", "gone.png") not in service._attemptsstatus = service.get_status()assert status is not Noneassert status.failed == 0@@ -1162,7 +1228,7 @@ def test_projection_job_computes_and_caches(record = index_records.get_projection("system", MODEL_ID)assert record is not Noneassert record.point_count == 3- assert sorted(record.image_names) == [f"img-{i}.png" for i in range(3)]+ assert sorted(record.items) == [IndexedItem("image", f"img-{i}.png") for i in range(3)]assert record.coords.shape == (3, 2)_wait_until(lambda: any(@@ -1196,7 +1262,7 @@ def test_projection_failure_caches_empty_result_instead_of_looping(assert record.point_count == 0# The empty cache claims the scope it failed against, so it is NOT stale —# clients see "empty" rather than re-enqueueing a doomed recompute forever.- accessible = index_records.list_accessible_embedded_images(None, MODEL_ID)+ accessible = index_records.list_accessible_embedded_items(None, MODEL_ID)assert record.scope_hash == scope_hash(MODEL_ID, accessible)# ...but "not stale" must not mean "never again". Asserting only the state@@ -1280,7 +1346,7 @@ def test_a_cached_row_with_no_finite_points_is_a_failed_fit_not_a_result(service.start(_make_invoker(images_service, index_records))_wait_until(lambda: not service._backfill_pending.is_set())- names = index_records.list_accessible_embedded_images(None, MODEL_ID)+ names = index_records.list_accessible_embedded_items(None, MODEL_ID)current_hash = scope_hash(MODEL_ID, names)index_records.set_projection("system",@@ -1327,7 +1393,7 @@ def test_a_lost_projection_write_does_not_burn_the_retry(# The empty row a failed fit leaves behind, stamped with the current scope:# what the retry is granted against.- names = index_records.list_accessible_embedded_images(None, MODEL_ID)+ names = index_records.list_accessible_embedded_items(None, MODEL_ID)current_hash = scope_hash(MODEL_ID, names)index_records.set_projection("system",@@ -1387,7 +1453,7 @@ def test_an_explicit_refresh_restores_a_spent_retry(service.request_projection("system")_wait_until(lambda: fits["n"] == 1, timeout=15)- current_hash = scope_hash(MODEL_ID, index_records.list_accessible_embedded_images(None, MODEL_ID))+ current_hash = scope_hash(MODEL_ID, index_records.list_accessible_embedded_items(None, MODEL_ID))assert service.request_projection("system", failed_scope=current_hash) is True_wait_until(lambda: fits["n"] == 2, timeout=15)_wait_for_spent_retry(service, "system", current_hash)@@ -1440,7 +1506,7 @@ def test_systemic_embedding_outage_does_not_starve_projections(# can never embed while the encoder is down._save_image(image_records, "done.png")_save_image(image_records, "stuck.png")- index_records.upsert_embedding("done.png", MODEL_ID, embedded_ok)+ index_records.upsert_embedding(IndexedItem("image", "done.png"), MODEL_ID, embedded_ok)service.start(_make_invoker(images_service, index_records))_wait_until(lambda: service._systemic_failures >= 1, timeout=20.0)@@ -1451,7 +1517,7 @@ def test_systemic_embedding_outage_does_not_starve_projections(_wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=30.0)record = index_records.get_projection("system", MODEL_ID)assert record is not None- assert record.image_names == ["done.png"]+ assert record.items == imgs("done.png")# And the outage is still an outage: no image was retired to make this happen.assert service._failed == set()assert service._systemic_failures >= 1@@ -1480,11 +1546,11 @@ def test_search_similar_ranks_by_cosine_and_respects_scope(for name, vec in [("a.png", unit(0)), ("close.png", unit(1, mix=0.9)), ("far.png", unit(2))]:_save_image(image_records, name)- index_records.upsert_embedding(name, MODEL_ID, vec)+ index_records.upsert_embedding(IndexedItem("image", name), MODEL_ID, vec)results = service.search_similar(None, unit(0), limit=2)- assert [name for name, _ in results] == ["a.png", "close.png"]+ assert [item for item, _ in results] == imgs("a.png", "close.png")assert results[0][1] > results[1][1] > 0.0# limit caps the result count; scores are descending.@@ -1551,7 +1617,7 @@ def test_projection_request_is_requeued_when_the_database_read_fails(answered `enqueued: true`, and an event-driven client would wait forever."""calls = {"n": 0}- real_list = index_records.list_accessible_embedded_images+ real_list = index_records.list_accessible_embedded_itemsdef flaky_list(user_id, model_id):calls["n"] += 1@@ -1559,7 +1625,7 @@ def test_projection_request_is_requeued_when_the_database_read_fails(raise RuntimeError("database is locked")return real_list(user_id, model_id)- index_records.list_accessible_embedded_images = flaky_list # type: ignore[method-assign]+ index_records.list_accessible_embedded_items = flaky_list # type: ignore[method-assign]service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)try:@@ -1622,7 +1688,7 @@ def test_unchanged_scope_does_not_recompute_the_projection(# the row alone leaves the backfill unarmed, so the worker would never see it._save_image(image_records, "new.png")images_service._on_changed(_dto_for(image_records, "new.png"))- _wait_until(lambda: index_records.get_embeddings(["new.png"], MODEL_ID)[0] == ["new.png"], timeout=30.0)+ _wait_until(lambda: index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"), timeout=30.0)with patch.object(image_index_default, "compute_umap", counting_umap):service.request_projection("system")_wait_until(lambda: fits["n"] == 2, timeout=30.0)@@ -1956,7 +2022,7 @@ def test_search_similar_scopes_to_the_requesting_user(# system owns mine.png; the other user owns theirs.png (both unboarded)._save_image(image_records, "mine.png")- index_records.upsert_embedding("mine.png", MODEL_ID, unit(0))+ index_records.upsert_embedding(IndexedItem("image", "mine.png"), MODEL_ID, unit(0))image_records.save(image_name="theirs.png",image_origin=ResourceOrigin.INTERNAL,@@ -1966,16 +2032,16 @@ def test_search_similar_scopes_to_the_requesting_user(has_workflow=False,user_id=other_user.user_id,)- index_records.upsert_embedding("theirs.png", MODEL_ID, unit(0))+ index_records.upsert_embedding(IndexedItem("image", "theirs.png"), MODEL_ID, unit(0))# The other user's scope must exclude the system user's private image# even though it scores identically.names = [name for name, _ in service.search_similar(other_user.user_id, unit(0), limit=10)]- assert names == ["theirs.png"]+ assert names == imgs("theirs.png")# Admin scope (None) sees both.- admin_names = {name for name, _ in service.search_similar(None, unit(0), limit=10)}- assert admin_names == {"mine.png", "theirs.png"}+ admin_items = {item for item, _ in service.search_similar(None, unit(0), limit=10)}+ assert admin_items == set(imgs("mine.png", "theirs.png"))def test_query_vectors_reject_a_non_finite_embedding(service: ImageIndexService) -> None:@@ -2532,3 +2598,193 @@ def test_a_transient_custom_terms_read_failure_keeps_the_rebuild_queued(_wait_until(lambda: service.get_vocab_build_state() == ("ready", None), timeout=15)assert calls["count"] >= 2assert service.get_vocab_embeddings()[0] == ["a cat", "dog"]+++# --- Videos ---+++def test_backfill_indexes_preexisting_videos(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ _save_image(image_records, "img.png")+ _save_video(video_records, "clip.mp4")+ _save_video(video_records, "intermediate.mp4", is_intermediate=True)+ _save_video(video_records, "mask.mp4", video_category=ImageCategory.MASK)++ service.start(+ _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ )++ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 2)+ assert index_records.get_embeddings(vids("clip.mp4"), MODEL_ID)[0] == vids("clip.mp4")+ assert index_records.get_embeddings(vids("intermediate.mp4", "mask.mp4"), MODEL_ID)[0] == []+++def test_new_video_is_indexed_from_its_thumbnail(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ invoker = _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ _save_video(video_records, "new.mp4")+ _save_video(video_records, "new-intermediate.mp4", is_intermediate=True)+ # Fire the callbacks the way VideoService.create would, i.e. after the thumbnail is written.+ videos_service._on_changed(_video_dto_for(video_records, "new.mp4"))+ videos_service._on_changed(_video_dto_for(video_records, "new-intermediate.mp4"))++ _wait_until(lambda: index_records.get_embeddings(vids("new.mp4"), MODEL_ID)[0] == vids("new.mp4"))+ assert index_records.get_embeddings(vids("new-intermediate.mp4"), MODEL_ID)[0] == []+++def test_video_thumbnail_is_what_gets_embedded(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ # The embedding must come from the video's own thumbnail, not from the image service (which+ # here returns a different colour) — a wrong source would still produce a plausible vector.+ embedded: list[Image.Image] = []++ def capture(images: list[Image.Image]) -> np.ndarray:+ embedded.extend(images)+ return np.stack([_unit_vec() for _ in images])++ service = ImageIndexService(encode_fn=capture, model_id=MODEL_ID)+ _save_video(video_records, "clip.mp4")+ try:+ service.start(+ _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ )+ _wait_until(lambda: index_records.get_embeddings(vids("clip.mp4"), MODEL_ID)[0] == vids("clip.mp4"))+ finally:+ service.stop()++ assert embedded, "the encoder was never called"+ assert embedded[0].size == (16, 16)+ # Nearest-colour rather than equality: the thumbnail is a lossy WEBP, so its pixels are+ # near the colour it was written with, not identical to it.+ pixel = embedded[0].getpixel((0, 0))+ thumbnail_colour = Image.new("RGB", (1, 1), "teal").getpixel((0, 0))+ image_service_colour = Image.new("RGB", (1, 1), "purple").getpixel((0, 0))++ def distance(a: tuple[int, ...], b: tuple[int, ...]) -> int:+ return sum(abs(x - y) for x, y in zip(a, b, strict=True))++ assert distance(pixel, thumbnail_colour) < distance(pixel, image_service_colour)+++def test_unreadable_video_thumbnail_is_charged_to_the_video(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ # A video whose thumbnail never got written must not stall the backfill; it retires after+ # _MAX_ATTEMPTS exactly as an unreadable image does.+ _save_video(video_records, "no-thumbnail.mp4")+ videos_service.get_path = lambda video_name, thumbnail=False: "/nonexistent/thumb.webp" # type: ignore[method-assign]++ service.start(+ _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ )++ _wait_until(lambda: IndexedItem("video", "no-thumbnail.mp4") in service._failed)+ assert index_records.get_embeddings(vids("no-thumbnail.mp4"), MODEL_ID)[0] == []+++def test_deleted_video_is_forgotten(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ invoker = _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ service.start(invoker)+ _save_video(video_records, "clip.mp4")+ videos_service._on_changed(_video_dto_for(video_records, "clip.mp4"))+ _wait_until(lambda: index_records.get_embeddings(vids("clip.mp4"), MODEL_ID)[0] == vids("clip.mp4"))++ # Seeded so the assertions below depend on the delete callback rather than on the FK+ # cascade: bookkeeping a deleted video leaves behind inflates `failed` for the life of the+ # process, and `pending` can then never drain to zero.+ service._failed.add(IndexedItem("video", "clip.mp4"))+ service._attempts[IndexedItem("video", "clip.mp4")] = 3++ video_records.delete("clip.mp4")+ videos_service._on_deleted("clip.mp4")++ _wait_until(lambda: index_records.count_index_status(MODEL_ID).total == 0)+ assert IndexedItem("video", "clip.mp4") not in service._pending+ assert IndexedItem("video", "clip.mp4") not in service._failed+ assert IndexedItem("video", "clip.mp4") not in service._attempts+++def test_video_owner_is_poked_when_its_embedding_lands(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ image_records: SqliteImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ # The status event is admin-only, so this per-user poke is the only signal a non-admin+ # gets that their generation reached the index. The owner has to be looked up in the+ # videos table: asking the images table for a video name finds nothing, and the lookup is+ # deliberately swallowed, so the map would simply never refresh for them.+ invoker = _make_invoker(+ images_service,+ index_records,+ image_records=image_records,+ videos_service=videos_service,+ video_records=video_records,+ )+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ _save_video(video_records, "mine.mp4")+ videos_service._on_changed(_video_dto_for(video_records, "mine.mp4"))++ _wait_until(+ lambda: any(+ isinstance(e, ImageIndexUpdatedEvent) and e.user_id == "system" for e in invoker.services.events.events+ )+ )+++def test_video_leaving_eligibility_clears_its_failure_bookkeeping(+ images_service: ImageService,+ videos_service: VideoService,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ # A video that stops being a gallery item must stop counting against `failed`, or it skews+ # `pending` for the rest of the process. The category half of the predicate is the part+ # that is genuinely video-specific — a different field on a different DTO.+ invoker = _make_invoker(images_service, index_records, videos_service=videos_service, video_records=video_records)+ service.start(invoker)+ _wait_until(lambda: not service._backfill_pending.is_set())++ service._failed.add(IndexedItem("video", "gone.mp4"))+ service._attempts[IndexedItem("video", "gone.mp4")] = 3+ _save_video(video_records, "gone.mp4", video_category=ImageCategory.MASK)+ videos_service._on_changed(_video_dto_for(video_records, "gone.mp4"))++ assert IndexedItem("video", "gone.mp4") not in service._failed+ assert IndexedItem("video", "gone.mp4") not in service._attempts+ status = service.get_status()+ assert status is not None+ assert status.failed == 0diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.pyindex 1e41e0bbff..6233ef6fb3 100644--- a/tests/app/services/image_index/test_projection.py+++ b/tests/app/services/image_index/test_projection.py@@ -4,6 +4,7 @@ import jsonimport numpy as np+from invokeai.app.services.image_index.image_index_common import IndexedItemfrom invokeai.app.services.image_index.projection import (DEFAULT_CLUSTER_EPS,adaptive_cluster_eps,@@ -155,12 +156,20 @@ def test_compute_clusters_skips_huge_point_sets() -> None:def test_scope_hash_is_order_insensitive_and_discriminating() -> None:- assert scope_hash("m", ["a", "b"]) == scope_hash("m", ["b", "a"])- assert scope_hash("m", ["a", "b"]) != scope_hash("m", ["a", "c"])- assert scope_hash("m", ["a", "b"]) != scope_hash("m2", ["a", "b"])+ a, b, c = IndexedItem("image", "a"), IndexedItem("image", "b"), IndexedItem("image", "c")+ assert scope_hash("m", [a, b]) == scope_hash("m", [b, a])+ assert scope_hash("m", [a, b]) != scope_hash("m", [a, c])+ assert scope_hash("m", [a, b]) != scope_hash("m2", [a, b])+ # A video joining the set changes it, so a cached projection computed before it existed+ # is detected as stale.+ assert scope_hash("m", [a, b]) != scope_hash("m", [a, b, IndexedItem("video", "clip.mp4")])+ # The kind itself is NOT hashed: names identify items on their own, and hashing the kind+ # would give every pre-video projection a new hash, costing every user a recomputed fit on+ # the first load after the upgrade.+ assert scope_hash("m", [IndexedItem("image", "x")]) == scope_hash("m", [IndexedItem("video", "x")])assert scope_hash("m", []) != scope_hash("m2", [])# Concatenation ambiguity: ["ab"] must differ from ["a", "b"].- assert scope_hash("m", ["ab"]) != scope_hash("m", ["a", "b"])+ assert scope_hash("m", [IndexedItem("image", "ab")]) != scope_hash("m", [a, b])def test_projection_params_is_stable_json() -> None:diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_12_add_video_embeddings.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_12_add_video_embeddings.pynew file mode 100644index 0000000000..b51a23629e--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_12_add_video_embeddings.py@@ -0,0 +1,102 @@+import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_08_03_add_image_index_tables import (+ AddImageIndexTablesCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_12_add_video_embeddings import (+ AddVideoEmbeddingsCallback,+)+++def _make_db() -> sqlite3.Connection:+ db = sqlite3.connect(":memory:")+ db.execute("PRAGMA foreign_keys = ON;")+ # Referenced by FKs: images/users (older migrations) and videos (2026_07_01_add_videos_tables).+ db.execute("CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY);")+ db.execute("CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);")+ db.execute("CREATE TABLE videos (video_name TEXT NOT NULL PRIMARY KEY);")+ AddImageIndexTablesCallback()(db.cursor())+ return db+++def test_creates_the_video_embeddings_table_with_its_cascade() -> None:+ db = _make_db()++ AddVideoEmbeddingsCallback()(db.cursor())++ db.execute("INSERT INTO videos VALUES ('v1');")+ db.execute("INSERT INTO video_embeddings (video_name, model_id, dim, embedding) VALUES ('v1', 'm1', 2, x'00');")++ cursor = db.cursor()+ cursor.execute("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_video_embeddings_model_id';")+ assert cursor.fetchone() is not None++ # An embedding must not outlive the video it describes.+ db.execute("DELETE FROM videos WHERE video_name = 'v1';")+ cursor.execute("SELECT COUNT(*) FROM video_embeddings;")+ assert cursor.fetchone() == (0,)+ db.close()+++def test_an_embedding_for_a_missing_video_is_refused() -> None:+ db = _make_db()+ AddVideoEmbeddingsCallback()(db.cursor())++ try:+ db.execute(+ "INSERT INTO video_embeddings (video_name, model_id, dim, embedding) VALUES ('gone.mp4', 'm1', 2, x'00');"+ )+ raise AssertionError("the foreign key should have refused this row")+ except sqlite3.IntegrityError:+ pass+ db.close()+++def test_existing_projections_survive_and_read_as_all_images() -> None:+ # The upgrade must not invalidate cached projections: a NULL item_kinds means what every+ # projection meant before videos were indexable.+ db = _make_db()+ db.execute("INSERT INTO users VALUES ('u1');")+ db.execute(+ "INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)"+ " VALUES ('u1', 'm1', 'h', '{}', 1, '[\"a.png\"]', x'00');"+ )++ AddVideoEmbeddingsCallback()(db.cursor())++ cursor = db.cursor()+ cursor.execute("SELECT image_names, item_kinds FROM image_projections WHERE user_id = 'u1';")+ assert cursor.fetchone() == ('["a.png"]', None)+ db.close()+++def test_is_idempotent_on_a_database_that_already_migrated() -> None:+ db = _make_db()+ AddVideoEmbeddingsCallback()(db.cursor())+ db.execute("INSERT INTO videos VALUES ('v1');")+ db.execute("INSERT INTO video_embeddings (video_name, model_id, dim, embedding) VALUES ('v1', 'm1', 2, x'00');")++ # The ALTER TABLE would raise "duplicate column name" without the guard, which would fail+ # the whole startup migration run.+ AddVideoEmbeddingsCallback()(db.cursor())++ cursor = db.cursor()+ cursor.execute("SELECT video_name FROM video_embeddings;")+ assert cursor.fetchall() == [("v1",)]+ db.close()+++def test_migration_refuses_to_run_before_the_videos_table_exists() -> None:+ """The foreign key's target is created by an older migration, and SQLite resolves targets+ lazily — so a reordering would fail obscurely at the first embedding rather than here."""+ db = sqlite3.connect(":memory:")+ db.execute("CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);")+ db.execute("CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY);")+ AddImageIndexTablesCallback()(db.cursor())++ try:+ AddVideoEmbeddingsCallback()(db.cursor())+ raise AssertionError("the migration should have refused to run")+ except RuntimeError as error:+ assert "videos table does not exist" in str(error)+ db.close()