Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(api): image map endpoints with cached UMAP projection and DBSCAN clusters

Lincoln Stein18a1766acdc8
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
new file mode 100644
index 0000000000..74d2c704a8
--- /dev/null
+++ b/invokeai/app/api/routers/image_map.py
@@ -0,0 +1,233 @@
+import asyncio
+from typing import Literal, Optional
+
+import numpy as np
+from fastapi import Query, status
+from fastapi.routing import APIRouter
+from pydantic import BaseModel, Field
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.image_index.image_index_common import ImageIndexStatus
+from invokeai.app.services.image_index.projection import (
+ DEFAULT_CLUSTER_MIN_SAMPLES,
+ MAX_CLUSTERED_POINTS,
+ compute_clusters,
+ resolve_cluster_eps,
+ scope_hash,
+)
+
+image_map_router = APIRouter(prefix="/v1/image_map", tags=["image_map"])
+
+ImageMapState = Literal["disabled", "model_missing", "empty", "computing", "ready"]
+
+
+class ImageMapPoint(BaseModel):
+ """One image'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")
+ cluster: int = Field(description="DBSCAN cluster label; -1 means unclustered")
+
+
+class ImageMapPointsResponse(BaseModel):
+ """The current user's semantic map."""
+
+ points: list[ImageMapPoint] = Field(description="The projected points")
+ state: ImageMapState = Field(
+ description="disabled: indexing is off; model_missing: indexing is enabled but the configured embedding "
+ "model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"
+ )
+ model_name: Optional[str] = Field(
+ default=None,
+ description="The configured embedding model's name; only set when state is model_missing, so the client "
+ "can tell the user which model to install",
+ )
+ stale: bool = Field(
+ description="True when the accessible image set has changed since this projection was computed; a refresh has been requested"
+ )
+ point_count: int = Field(description="Number of points returned")
+ cluster_eps: Optional[float] = Field(
+ default=None,
+ description="The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). "
+ "Pass it back explicitly to get an identical clustering from a later request.",
+ )
+ updated_at: Optional[str] = Field(default=None, description="When the served projection was computed")
+
+
+class ImageMapProjectionStatus(BaseModel):
+ """Status of the current user's cached projection."""
+
+ state: ImageMapState = Field(description="Projection cache state")
+ stale: bool = Field(description="Whether the cached projection lags the accessible image set")
+ point_count: int = Field(description="Points in the cached projection")
+ updated_at: Optional[str] = Field(default=None, description="When the cached projection was computed")
+
+
+class ImageMapStatusResponse(BaseModel):
+ """Combined index + projection status for the current user."""
+
+ enabled: bool = Field(description="Whether the embedding index is running")
+ model_name: Optional[str] = Field(
+ default=None,
+ description="The configured embedding model's name; only set when the projection state is model_missing",
+ )
+ index: Optional[ImageIndexStatus] = Field(
+ default=None,
+ description="Embedding index progress counts. Admin-only: the counts aggregate over all users' images, so they are omitted for regular users.",
+ )
+ projection: ImageMapProjectionStatus = Field(description="The user's projection cache status")
+
+
+class ImageMapRefreshResponse(BaseModel):
+ """Result of a projection refresh request."""
+
+ enqueued: bool = Field(description="True if the recompute was accepted (or already pending)")
+
+
+ClusterEpsQuery = Query(
+ default=None,
+ ge=0.01,
+ le=2.0,
+ description="DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's "
+ "k-distance distribution. Clamped server-side relative to the projection's coordinate span.",
+)
+ClusterMinSamplesQuery = Query(
+ default=DEFAULT_CLUSTER_MIN_SAMPLES, ge=2, le=100, description="DBSCAN min_samples for clustering"
+)
+
+
+def _scope(current_user) -> tuple[str, bool]:
+ """(projection cache key, admin-wide scope flag) for the requesting user."""
+ return current_user.user_id, current_user.is_admin
+
+
+@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,
+) -> ImageMapPointsResponse:
+ """Gets the current user's semantic image map.
+
+ Serves the cached UMAP projection (never blocks on a UMAP fit) and runs
+ DBSCAN per request, so `eps` is live-adjustable. If the cache is missing
+ or stale, a recompute is enqueued and reflected in `state`/`stale`.
+ """
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ # The service is also inert when indexing is enabled but the
+ # configured model is not installed; tell the client which case
+ # this is so it can show an actionable message.
+ if services.configuration.image_index_enabled:
+ return ImageMapPointsResponse(
+ points=[],
+ state="model_missing",
+ model_name=services.configuration.image_index_model,
+ stale=False,
+ point_count=0,
+ )
+ 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
+ )
+ record = services.image_index_records.get_projection(user_id, model_id)
+
+ if record is None:
+ if not current_names:
+ return ImageMapPointsResponse(points=[], state="empty", stale=False, point_count=0)
+ enqueued = services.image_index.request_projection(user_id, all_images=is_admin)
+ return ImageMapPointsResponse(points=[], state="computing" if enqueued else "empty", stale=True, point_count=0)
+
+ stale = record.scope_hash != scope_hash(model_id, current_names)
+ if 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
+ # 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). The clustering and
+ # response assembly are CPU-bound, so they run off the event loop.
+ def build_points() -> tuple[list[ImageMapPoint], Optional[float]]:
+ accessible = set(current_names)
+ mask = np.fromiter(
+ (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)
+ )
+ visible_names = [name for name, keep in zip(record.image_names, mask, strict=True) if keep]
+ visible_coords = record.coords[mask]
+ resolved_eps = (
+ resolve_cluster_eps(visible_coords, eps, min_samples)
+ if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS
+ else None
+ )
+ labels = compute_clusters(visible_coords, eps=resolved_eps, min_samples=min_samples)
+ 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)
+ ], resolved_eps
+
+ points, resolved_eps = await asyncio.to_thread(build_points)
+ state: ImageMapState = "ready" if points else "empty"
+ return ImageMapPointsResponse(
+ points=points,
+ state=state,
+ stale=stale,
+ point_count=len(points),
+ cluster_eps=resolved_eps,
+ updated_at=record.updated_at,
+ )
+
+
+@image_map_router.post(
+ "/refresh",
+ operation_id="refresh_image_map",
+ response_model=ImageMapRefreshResponse,
+ status_code=status.HTTP_202_ACCEPTED,
+)
+async def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefreshResponse:
+ """Requests a recompute of the current user's image map projection."""
+ user_id, is_admin = _scope(current_user)
+ enqueued = ApiDependencies.invoker.services.image_index.request_projection(user_id, all_images=is_admin)
+ return ImageMapRefreshResponse(enqueued=enqueued)
+
+
+@image_map_router.get("/status", operation_id="get_image_map_status", response_model=ImageMapStatusResponse)
+async def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:
+ """Gets embedding index progress and the user's projection cache status."""
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ model_missing = services.configuration.image_index_enabled
+ return ImageMapStatusResponse(
+ enabled=False,
+ model_name=services.configuration.image_index_model if model_missing else None,
+ projection=ImageMapProjectionStatus(
+ state="model_missing" if model_missing else "disabled", stale=False, point_count=0
+ ),
+ )
+
+ user_id, is_admin = _scope(current_user)
+ record = services.image_index_records.get_projection(user_id, model_id)
+ if record is None:
+ projection = ImageMapProjectionStatus(state="empty", stale=False, point_count=0)
+ else:
+ current_names = services.image_index_records.list_accessible_embedded_images(
+ 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))
+ projection = ImageMapProjectionStatus(
+ state="ready" if visible_count else "empty",
+ stale=record.scope_hash != scope_hash(model_id, current_names),
+ point_count=visible_count,
+ updated_at=record.updated_at,
+ )
+ # Index counts aggregate over all users' images; expose them to admins only.
+ index = services.image_index.get_status() if is_admin else None
+ return ImageMapStatusResponse(enabled=True, index=index, projection=projection)
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py
index 5a8245b5f9..d4249bcb65 100644
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@ -25,6 +25,7 @@ from invokeai.app.services.events.events_common import (
ImageIndexEventBase,
ImageIndexStatusEvent,
ImageIndexUpdatedEvent,
+ ImageMapProjectionReadyEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
@@ -108,7 +109,7 @@ MODEL_EVENTS = {
BULK_DOWNLOAD_EVENTS = {BulkDownloadStartedEvent, BulkDownloadCompleteEvent, BulkDownloadErrorEvent}
WORKFLOW_EVENTS = {WorkflowCreatedEvent, WorkflowUpdatedEvent, WorkflowDeletedEvent}
-IMAGE_INDEX_EVENTS = {ImageIndexStatusEvent, ImageIndexUpdatedEvent}
+IMAGE_INDEX_EVENTS = {ImageIndexStatusEvent, ImageIndexUpdatedEvent, ImageMapProjectionReadyEvent}
MODEL_INSTALL_EVENTS = (
ModelInstallDownloadStartedEvent,
@@ -654,6 +655,13 @@ class SocketIO:
event=event_name, data=event_data.model_dump(mode="json"), room=f"user:{event_data.user_id}"
)
return
+ # Projection-ready events go to the owning user's room plus admins.
+ if isinstance(event_data, ImageMapProjectionReadyEvent):
+ # Single emit with a room list: python-socketio dedupes, so an
+ # admin viewing their own map gets exactly one event.
+ rooms = [f"user:{event_data.user_id}", "admin"]
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=rooms)
+ return
# Index counts aggregate over ALL users' images; watching them tick is
# a side channel on other users' generation activity, so they go to
# admins only (single-user mode's sole user is an admin).
diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py
index 96373df31e..495ab10e99 100644
--- a/invokeai/app/api_app.py
+++ b/invokeai/app/api_app.py
@@ -30,6 +30,7 @@ from invokeai.app.api.routers import (
custom_nodes,
download_queue,
gallery,
+ image_map,
image_moves,
images,
model_manager,
@@ -413,6 +414,7 @@ app.include_router(model_manager.model_manager_router, prefix="/api")
app.include_router(download_queue.download_queue_router, prefix="/api")
app.include_router(image_moves.image_moves_router, prefix="/api")
app.include_router(images.images_router, prefix="/api")
+app.include_router(image_map.image_map_router, prefix="/api")
app.include_router(videos.videos_router, prefix="/api")
app.include_router(gallery.gallery_router, prefix="/api")
app.include_router(boards.boards_router, prefix="/api")
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index 2ded5a7a94..87626eba60 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -17,6 +17,7 @@ from invokeai.app.services.events.events_common import (
EventBase,
ImageIndexStatusEvent,
ImageIndexUpdatedEvent,
+ ImageMapProjectionReadyEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
@@ -329,4 +330,8 @@ class EventServiceBase:
"""Emitted to one user when their images were just (re)embedded"""
self.dispatch(ImageIndexUpdatedEvent.build(user_id=user_id))
+ def emit_image_map_projection_ready(self, user_id: str, point_count: int) -> None:
+ """Emitted when a user's image map projection has been recomputed"""
+ self.dispatch(ImageMapProjectionReadyEvent.build(user_id=user_id, point_count=point_count))
+
# endregion
diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.py
index 386157af8c..e10c1c5196 100644
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@ -915,3 +915,17 @@ class ImageIndexUpdatedEvent(ImageIndexEventBase):
@classmethod
def build(cls, user_id: str) -> "ImageIndexUpdatedEvent":
return cls(user_id=user_id)
+
+
+@payload_schema.register
+class ImageMapProjectionReadyEvent(ImageIndexEventBase):
+ """Event model for image_map_projection_ready"""
+
+ __event_name__ = "image_map_projection_ready"
+
+ user_id: str = Field(description="The user whose image map projection was recomputed")
+ point_count: int = Field(description="Number of points in the recomputed projection")
+
+ @classmethod
+ def build(cls, user_id: str, point_count: int) -> "ImageMapProjectionReadyEvent":
+ return cls(user_id=user_id, point_count=point_count)
diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.py
index 453c9a2bfb..606e70c675 100644
--- a/invokeai/app/services/image_index/image_index_base.py
+++ b/invokeai/app/services/image_index/image_index_base.py
@@ -22,3 +22,22 @@ class ImageIndexServiceBase(ABC):
def get_status(self) -> ImageIndexStatus | None:
"""Get index progress counts, or None if the indexer is not running."""
pass
+
+ @abstractmethod
+ def request_projection(self, user_id: str, all_images: bool = False) -> bool:
+ """Ask the worker to (re)compute a user's image map projection.
+
+ Requests are deduplicated per user; the projection runs after any
+ pending embedding work, and an `image_map_projection_ready` event is
+ emitted when the cache is updated.
+
+ Args:
+ user_id: The user whose projection cache to update.
+ all_images: Compute over every embedded image (admin scope)
+ rather than the user's accessible set.
+
+ Returns:
+ True if the request was accepted (or already pending); False if
+ the indexer is not running.
+ """
+ pass
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 53a0f4c477..9129f4a351 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -9,6 +9,7 @@ from PIL import Image
from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase
from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, ImageIndexStatus
+from invokeai.app.services.image_index.projection import compute_umap, projection_params, scope_hash
from invokeai.app.services.image_records.image_records_common import ImageCategory
from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID
@@ -121,6 +122,11 @@ class ImageIndexService(ImageIndexServiceBase):
# the index goes quiescent. Worker-thread only — no locking.
self._pending_pokes: set[str] = set()
self._worker: Optional[threading.Thread] = None
+ # user_id -> all_images. Deduplicates projection requests per user;
+ # a request arriving while that user's projection is being computed
+ # lands here again and is honored on the next pass.
+ self._projection_requests: dict[str, bool] = {}
+ self._projection_lock = threading.Lock()
self._invoker: Optional["Invoker"] = None
self._model_config: Optional["AnyModelConfig"] = None
@@ -140,6 +146,16 @@ class ImageIndexService(ImageIndexServiceBase):
status = self._invoker.services.image_index_records.count_index_status(self._model_id)
return status.model_copy(update={"failed": len(self._failed)})
+ def request_projection(self, user_id: str, all_images: bool = False) -> bool:
+ if self._model_id is None or self._worker is None or not self._worker.is_alive():
+ return False
+ with self._projection_lock:
+ # Last writer wins: the scope reflects the requester's most recent
+ # admin status, so a promotion/demotion between requests cannot
+ # pin a stale scope.
+ self._projection_requests[user_id] = all_images
+ return True
+
def start(self, invoker: "Invoker") -> None:
self._invoker = invoker
config = invoker.services.configuration
@@ -257,35 +273,42 @@ class ImageIndexService(ImageIndexServiceBase):
# mid-emit is never lost either.
self._status_dirty.set()
raise
- if batch is None:
- if self._pending_pokes and not self._backfill_pending.is_set():
- # The index just went quiescent: poke each owner whose
- # images were embedded since the last flush. Deferred
- # to quiescence so a long backfill does not trigger a
- # refetch (and possibly a projection recompute) per
- # batch. Cleared only after all emits, so a raise
- # retries on the next pass (duplicate pokes are cheap).
- for user_id in sorted(self._pending_pokes):
- self._invoker.services.events.emit_image_index_updated(user_id=user_id)
- self._pending_pokes.clear()
+ if batch is not None:
+ self._wait_for_idle_generation()
+ if self._stop_event.is_set():
+ break
+ ok = self._process_batch(batch)
+ self._emit_status()
+ if not ok:
+ # Re-sweep so queue-sourced images that failed
+ # transiently are retried to _MAX_ATTEMPTS instead of
+ # lingering unembedded until the next restart.
+ self._backfill_pending.set()
+ # Back off after a failed batch so a systemic failure
+ # (broken model, OOM loop) cannot spin hot through the
+ # backlog re-fetching the same names. The delay grows
+ # with consecutive systemic failures: images are no
+ # longer retired by an outage, so without this an
+ # outage would retry the same batch at 1 Hz for as
+ # long as it lasts.
+ self._stop_event.wait(self._backoff_seconds())
continue
- self._wait_for_idle_generation()
- if self._stop_event.is_set():
- break
- ok = self._process_batch(batch)
- self._emit_status()
- if not ok:
- # Re-sweep so queue-sourced images that failed
- # transiently are retried to _MAX_ATTEMPTS instead of
- # lingering unembedded until the next restart.
- self._backfill_pending.set()
- # Back off after a failed batch so a systemic failure
- # (broken model, OOM loop) cannot spin hot through the
- # backlog re-fetching the same names. The delay grows with
- # consecutive systemic failures: images are no longer
- # retired by an outage, so without this an outage would
- # retry the same batch at 1 Hz for as long as it lasts.
- self._stop_event.wait(self._backoff_seconds())
+ if self._pending_pokes and not self._backfill_pending.is_set():
+ # The index just went quiescent: poke each owner whose
+ # images were embedded since the last flush. Deferred to
+ # quiescence so a long backfill does not trigger a
+ # refetch (and possibly a projection recompute) per
+ # batch. Cleared only after all emits, so a raise here
+ # retries on the next pass (duplicate pokes are cheap).
+ for user_id in sorted(self._pending_pokes):
+ self._invoker.services.events.emit_image_index_updated(user_id=user_id)
+ self._pending_pokes.clear()
+ continue
+ # No embedding work right now — projections run when the
+ # index is quiescent so they cover the freshest state.
+ projection_job = self._next_projection_job()
+ if projection_job is not None:
+ self._process_projection(*projection_job)
except Exception:
logger.exception("Unexpected error in the image index worker")
# Whatever was in flight may have skipped its accounting, so
@@ -484,6 +507,50 @@ class ImageIndexService(ImageIndexServiceBase):
with self._pending_lock:
self._pending.difference_update(image_names)
+ # --- Projections ---
+
+ def _next_projection_job(self) -> Optional[tuple[str, bool]]:
+ with self._projection_lock:
+ if not self._projection_requests:
+ return None
+ user_id = next(iter(self._projection_requests))
+ return user_id, self._projection_requests.pop(user_id)
+
+ def _process_projection(self, user_id: str, all_images: bool) -> None:
+ assert self._invoker is not None
+ assert self._model_id is not None
+ logger = self._invoker.services.logger
+ records = self._invoker.services.image_index_records
+
+ scope_user = None if all_images else user_id
+ names = records.list_accessible_embedded_images(scope_user, self._model_id)
+ found_names, matrix = records.get_embeddings(names, self._model_id)
+ 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")
+ except Exception:
+ logger.exception(f"Image map: UMAP projection failed for user '{user_id}' ({len(found_names)} 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; the next gallery change flips
+ # the hash and retries naturally.
+ found_names = []
+ coords = np.empty((0, 2), dtype=EMBEDDING_DTYPE)
+
+ # Hash the scope the projection was computed against (on failure the
+ # empty cache still claims the current scope, so staleness detection —
+ # not client polling — decides when to retry).
+ records.set_projection(
+ user_id,
+ self._model_id,
+ scope_hash(self._model_id, names),
+ projection_params(n_points=len(found_names)),
+ found_names,
+ coords,
+ )
+ self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_names))
+
def _wait_for_idle_generation(self) -> None:
"""Block until no generation is in progress, unless embedding on CPU.
diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.py
new file mode 100644
index 0000000000..cf5674be5e
--- /dev/null
+++ b/invokeai/app/services/image_index/projection.py
@@ -0,0 +1,206 @@
+"""Pure projection/clustering math for the image map.
+
+umap-learn (and its numba JIT) and scikit-learn are imported lazily inside
+the functions: importing numba costs seconds and these modules must not slow
+app startup or break the app if the dependency stack is unhealthy.
+
+Parameters follow PhotoMapAI's tuning: UMAP(n_neighbors=min(15, N-1),
+n_components=2, min_dist=0.05, metric="cosine") and DBSCAN(min_samples=10)
+over the 2D coordinates. Unlike PhotoMapAI (fixed eps=0.2 plus a user-facing
+slider), eps defaults to an adaptive value: UMAP's output scale grows as the
+point count shrinks, so any fixed eps that works for a dense thousand-image
+map labels a small gallery as all noise.
+"""
+
+import hashlib
+import json
+import warnings
+from typing import Optional
+
+import numpy as np
+
+from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE
+
+DEFAULT_CLUSTER_EPS = 0.2
+DEFAULT_CLUSTER_MIN_SAMPLES = 10
+DEFAULT_UMAP_SEED = 42
+
+
+def projection_params(seed: int = DEFAULT_UMAP_SEED, n_points: int = 0) -> str:
+ """JSON description of the projection parameters, stored with the cache."""
+ return json.dumps(
+ {
+ "metric": "cosine",
+ "min_dist": 0.05,
+ "n_components": 2,
+ "n_neighbors": min(15, n_points - 1) if n_points > 1 else 1,
+ "seed": seed,
+ },
+ sort_keys=True,
+ )
+
+
+def compute_umap(embeddings: np.ndarray, seed: int = DEFAULT_UMAP_SEED) -> np.ndarray:
+ """Project an (N, D) embedding matrix to (N, 2) with UMAP.
+
+ Returns an empty (0, 2) array for empty input. A single point maps to the
+ origin; 2-3 points fall back to a PCA projection because umap-learn
+ cannot fit them (n_neighbors must exceed 1, and spectral initialization
+ needs fewer components than points). Raises on UMAP failure — the caller
+ decides what a failed fit means for its cache.
+ """
+ if embeddings.shape[0] == 0:
+ return np.empty((0, 2), dtype=EMBEDDING_DTYPE)
+ if embeddings.shape[0] == 1:
+ return np.zeros((1, 2), dtype=EMBEDDING_DTYPE)
+ if embeddings.shape[0] <= 3:
+ centered = embeddings.astype(np.float64) - embeddings.mean(axis=0)
+ _, _, vt = np.linalg.svd(centered, full_matrices=False)
+ coords = centered @ vt[:2].T
+ if coords.shape[1] < 2:
+ coords = np.pad(coords, ((0, 0), (0, 2 - coords.shape[1])))
+ return coords.astype(EMBEDDING_DTYPE)
+
+ from umap import UMAP
+
+ with warnings.catch_warnings():
+ # UMAP warns about TBB versions and small-N spectral fallbacks; both
+ # are noise at this call site.
+ warnings.filterwarnings("ignore")
+ n_neighbors = min(15, embeddings.shape[0] - 1)
+ umap_model = UMAP(
+ n_neighbors=n_neighbors,
+ n_components=2,
+ min_dist=0.05,
+ metric="cosine",
+ random_state=seed,
+ )
+ coords = umap_model.fit_transform(embeddings)
+ return np.asarray(coords, dtype=EMBEDDING_DTYPE)
+
+
+# Above this many points, per-request DBSCAN is skipped (everything is served
+# as unclustered) — sklearn DBSCAN materializes all radius neighborhoods, and
+# the memory cost grows with the pair count.
+MAX_CLUSTERED_POINTS = 50_000
+
+# eps is clamped to this fraction of the projection's coordinate span. UMAP's
+# output scale is data-dependent, so an absolute eps close to the span makes
+# every point a neighbor of every other (O(N^2) memory in sklearn's DBSCAN).
+MAX_EPS_SPAN_FRACTION = 0.05
+
+
+def adaptive_cluster_eps(coords: np.ndarray, min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES) -> float:
+ """Median k-distance of the coordinates: each point's distance to its
+ min_samples-th nearest neighbor, aggregated with the median.
+
+ This is the standard DBSCAN eps heuristic: a point whose min_samples-th
+ neighbor is within eps is a core point, so the median k-distance makes
+ roughly half the points core points — clusters form wherever density is
+ above the map's typical density, at any gallery size or UMAP scale.
+ """
+ n_points = coords.shape[0]
+ k = min(min_samples, n_points - 1)
+ if k < 1:
+ return DEFAULT_CLUSTER_EPS
+
+ from sklearn.neighbors import NearestNeighbors
+
+ # k + 1 neighbors because each point's nearest neighbor is itself.
+ distances, _ = NearestNeighbors(n_neighbors=k + 1).fit(coords).kneighbors(coords)
+ eps = float(np.median(distances[:, -1]))
+ # Coincident points give a zero k-distance; zero eps clusters nothing.
+ return eps if eps > 0 else DEFAULT_CLUSTER_EPS
+
+
+# sklearn's DBSCAN materializes every point's radius neighborhood as int64
+# index arrays, so its memory is proportional to the neighbor-pair count.
+# 50M pairs is ~400MB — comparable to the worst case the old fixed eps=0.2
+# default could produce, and far below OOM territory.
+MAX_NEIGHBOR_PAIRS = 50_000_000
+
+
+def _shrink_eps_to_pair_budget(coords: np.ndarray, eps: float) -> float:
+ """Shrink eps until DBSCAN's neighbor-pair count fits MAX_NEIGHBOR_PAIRS.
+
+ The span clamp alone cannot bound memory: a dense blob concentrates most
+ pairs in a small region, so a modest eps on a wide map can still
+ materialize billions of pairs. Counting pairs with a KD-tree is cheap.
+ """
+ if coords.shape[0] < 2:
+ return eps
+
+ from sklearn.neighbors import KDTree
+
+ tree = KDTree(coords)
+ for _ in range(12):
+ pairs = int(tree.query_radius(coords, r=eps, count_only=True).sum())
+ if pairs <= MAX_NEIGHBOR_PAIRS:
+ break
+ eps *= 0.7
+ return eps
+
+
+def resolve_cluster_eps(
+ coords: np.ndarray,
+ eps: Optional[float] = None,
+ min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES,
+) -> float:
+ """The eps compute_clusters will actually use for these coordinates.
+
+ Resolution order: adaptive default when eps is None, then the span clamp,
+ then the neighbor-pair budget. Exposed so callers (the /points endpoint)
+ can report the effective eps and other callers can reuse it verbatim.
+ """
+ if eps is None:
+ # Cap at the API's own upper bound (le=2.0) so a reported adaptive
+ # eps can always be passed back explicitly. Values that large only
+ # arise on sparse structureless maps, where a smaller eps just means
+ # more (correct) noise.
+ eps = min(adaptive_cluster_eps(coords, min_samples), 2.0)
+ span = float(np.ptp(coords, axis=0).max()) if coords.shape[0] > 1 else 0.0
+ if span > 0:
+ eps = min(eps, span * MAX_EPS_SPAN_FRACTION)
+ # Floor at the API's lower bound (ge=0.01), again for pass-back validity.
+ # Only degenerate near-coincident maps clamp below it.
+ return max(_shrink_eps_to_pair_budget(coords, eps), 0.01)
+
+
+def compute_clusters(
+ coords: np.ndarray,
+ eps: Optional[float] = None,
+ min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES,
+) -> np.ndarray:
+ """DBSCAN-cluster 2D coordinates. Label -1 is noise ("unclustered").
+
+ Cheap enough to run per request, which is what makes the eps parameter
+ live-adjustable without recomputing the UMAP. When eps is None it is
+ derived from the data with adaptive_cluster_eps; see resolve_cluster_eps
+ for the clamps applied either way. Clustering is skipped entirely above
+ MAX_CLUSTERED_POINTS.
+ """
+ if coords.shape[0] == 0:
+ return np.empty((0,), dtype=np.int64)
+ if coords.shape[0] > MAX_CLUSTERED_POINTS:
+ return np.full((coords.shape[0],), -1, dtype=np.int64)
+
+ eps = resolve_cluster_eps(coords, eps, min_samples)
+
+ from sklearn.cluster import DBSCAN
+
+ 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.
+
+ Order-insensitive: the caller may pass names in any order. Comparing the
+ stored hash against a freshly derived one detects staleness from any
+ cause — new/deleted images, board visibility changes, shares.
+ """
+ digest = hashlib.sha256()
+ digest.update(model_id.encode("utf-8"))
+ for name in sorted(image_names):
+ digest.update(b"\x00")
+ digest.update(name.encode("utf-8"))
+ return digest.hexdigest()
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index d4107d488a..56308a9144 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -6288,6 +6288,127 @@
]
}
},
+ "/api/v1/image_map/points": {
+ "get": {
+ "tags": ["image_map"],
+ "summary": "Get Image Map Points",
+ "description": "Gets the current user's semantic image map.\n\nServes the cached UMAP projection (never blocks on a UMAP fit) and runs\nDBSCAN per request, so `eps` is live-adjustable. If the cache is missing\nor stale, a recompute is enqueued and reflected in `state`/`stale`.",
+ "operationId": "get_image_map_points",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "eps",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "number",
+ "maximum": 2.0,
+ "minimum": 0.01
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span.",
+ "title": "Eps"
+ },
+ "description": "DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span."
+ },
+ {
+ "name": "min_samples",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "minimum": 2,
+ "description": "DBSCAN min_samples for clustering",
+ "default": 10,
+ "title": "Min Samples"
+ },
+ "description": "DBSCAN min_samples for clustering"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImageMapPointsResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/image_map/refresh": {
+ "post": {
+ "tags": ["image_map"],
+ "summary": "Refresh Image Map",
+ "description": "Requests a recompute of the current user's image map projection.",
+ "operationId": "refresh_image_map",
+ "responses": {
+ "202": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImageMapRefreshResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/image_map/status": {
+ "get": {
+ "tags": ["image_map"],
+ "summary": "Get Image Map Status",
+ "description": "Gets embedding index progress and the user's projection cache status.",
+ "operationId": "get_image_map_status",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImageMapStatusResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/videos/upload": {
"post": {
"tags": ["videos"],
@@ -40870,6 +40991,30 @@
"$ref": "#/components/schemas/ImageOutput"
}
},
+ "ImageIndexStatus": {
+ "properties": {
+ "total": {
+ "type": "integer",
+ "title": "Total",
+ "description": "Number of gallery images eligible for indexing"
+ },
+ "embedded": {
+ "type": "integer",
+ "title": "Embedded",
+ "description": "Number of eligible images that have an embedding"
+ },
+ "failed": {
+ "type": "integer",
+ "title": "Failed",
+ "description": "Eligible images 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."
+ },
"ImageIndexStatusEvent": {
"description": "Event model for image_index_status",
"properties": {
@@ -41223,6 +41368,214 @@
"$ref": "#/components/schemas/ImageOutput"
}
},
+ "ImageMapPoint": {
+ "properties": {
+ "x": {
+ "type": "number",
+ "title": "X",
+ "description": "UMAP x coordinate"
+ },
+ "y": {
+ "type": "number",
+ "title": "Y",
+ "description": "UMAP y coordinate"
+ },
+ "image_name": {
+ "type": "string",
+ "title": "Image Name",
+ "description": "The image this point represents"
+ },
+ "cluster": {
+ "type": "integer",
+ "title": "Cluster",
+ "description": "DBSCAN cluster label; -1 means unclustered"
+ }
+ },
+ "type": "object",
+ "required": ["x", "y", "image_name", "cluster"],
+ "title": "ImageMapPoint",
+ "description": "One image's position on the 2D semantic map."
+ },
+ "ImageMapPointsResponse": {
+ "properties": {
+ "points": {
+ "items": {
+ "$ref": "#/components/schemas/ImageMapPoint"
+ },
+ "type": "array",
+ "title": "Points",
+ "description": "The projected points"
+ },
+ "state": {
+ "type": "string",
+ "enum": ["disabled", "model_missing", "empty", "computing", "ready"],
+ "title": "State",
+ "description": "disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"
+ },
+ "model_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model Name",
+ "description": "The configured embedding model's name; only set when state is model_missing, so the client can tell the user which model to install"
+ },
+ "stale": {
+ "type": "boolean",
+ "title": "Stale",
+ "description": "True when the accessible image set has changed since this projection was computed; a refresh has been requested"
+ },
+ "point_count": {
+ "type": "integer",
+ "title": "Point Count",
+ "description": "Number of points returned"
+ },
+ "cluster_eps": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cluster Eps",
+ "description": "The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). Pass it back explicitly to get an identical clustering from a later request."
+ },
+ "updated_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Updated At",
+ "description": "When the served projection was computed"
+ }
+ },
+ "type": "object",
+ "required": ["points", "state", "stale", "point_count"],
+ "title": "ImageMapPointsResponse",
+ "description": "The current user's semantic map."
+ },
+ "ImageMapProjectionReadyEvent": {
+ "description": "Event model for image_map_projection_ready",
+ "properties": {
+ "timestamp": {
+ "description": "The timestamp of the event",
+ "title": "Timestamp",
+ "type": "integer"
+ },
+ "user_id": {
+ "description": "The user whose image map projection was recomputed",
+ "title": "User Id",
+ "type": "string"
+ },
+ "point_count": {
+ "description": "Number of points in the recomputed projection",
+ "title": "Point Count",
+ "type": "integer"
+ }
+ },
+ "required": ["timestamp", "user_id", "point_count"],
+ "title": "ImageMapProjectionReadyEvent",
+ "type": "object"
+ },
+ "ImageMapProjectionStatus": {
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["disabled", "model_missing", "empty", "computing", "ready"],
+ "title": "State",
+ "description": "Projection cache state"
+ },
+ "stale": {
+ "type": "boolean",
+ "title": "Stale",
+ "description": "Whether the cached projection lags the accessible image set"
+ },
+ "point_count": {
+ "type": "integer",
+ "title": "Point Count",
+ "description": "Points in the cached projection"
+ },
+ "updated_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Updated At",
+ "description": "When the cached projection was computed"
+ }
+ },
+ "type": "object",
+ "required": ["state", "stale", "point_count"],
+ "title": "ImageMapProjectionStatus",
+ "description": "Status of the current user's cached projection."
+ },
+ "ImageMapRefreshResponse": {
+ "properties": {
+ "enqueued": {
+ "type": "boolean",
+ "title": "Enqueued",
+ "description": "True if the recompute was accepted (or already pending)"
+ }
+ },
+ "type": "object",
+ "required": ["enqueued"],
+ "title": "ImageMapRefreshResponse",
+ "description": "Result of a projection refresh request."
+ },
+ "ImageMapStatusResponse": {
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "title": "Enabled",
+ "description": "Whether the embedding index is running"
+ },
+ "model_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model Name",
+ "description": "The configured embedding model's name; only set when the projection state is model_missing"
+ },
+ "index": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ImageIndexStatus"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Embedding index progress counts. Admin-only: the counts aggregate over all users' images, so they are omitted for regular users."
+ },
+ "projection": {
+ "$ref": "#/components/schemas/ImageMapProjectionStatus",
+ "description": "The user's projection cache status"
+ }
+ },
+ "type": "object",
+ "required": ["enabled", "projection"],
+ "title": "ImageMapStatusResponse",
+ "description": "Combined index + projection status for the current user."
+ },
"ImageMaskToTensorInvocation": {
"category": "mask",
"class": "invocation",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 7ab59961f2..869c6a6e3c 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1517,6 +1517,70 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/image_map/points": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Image Map Points
+ * @description Gets the current user's semantic image map.
+ *
+ * Serves the cached UMAP projection (never blocks on a UMAP fit) and runs
+ * DBSCAN per request, so `eps` is live-adjustable. If the cache is missing
+ * or stale, a recompute is enqueued and reflected in `state`/`stale`.
+ */
+ get: operations["get_image_map_points"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/image_map/refresh": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Refresh Image Map
+ * @description Requests a recompute of the current user's image map projection.
+ */
+ post: operations["refresh_image_map"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/image_map/status": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Image Map Status
+ * @description Gets embedding index progress and the user's projection cache status.
+ */
+ get: operations["get_image_map_status"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/videos/upload": {
parameters: {
query?: never;
@@ -17040,6 +17104,28 @@ export type components = {
*/
type: "img_hue_adjust";
};
+ /**
+ * ImageIndexStatus
+ * @description Progress of the embedding index for one embedding model.
+ */
+ ImageIndexStatus: {
+ /**
+ * Total
+ * @description Number of gallery images eligible for indexing
+ */
+ total: number;
+ /**
+ * Embedded
+ * @description Number of eligible images that have an embedding
+ */
+ embedded: number;
+ /**
+ * Failed
+ * @description Eligible images that repeatedly failed to embed; excluded from pending so it can drain
+ * @default 0
+ */
+ failed?: number;
+ };
/**
* ImageIndexStatusEvent
* @description Event model for image_index_status
@@ -17240,6 +17326,153 @@ export type components = {
*/
type: "img_lerp";
};
+ /**
+ * ImageMapPoint
+ * @description One image's position on the 2D semantic map.
+ */
+ ImageMapPoint: {
+ /**
+ * X
+ * @description UMAP x coordinate
+ */
+ x: number;
+ /**
+ * Y
+ * @description UMAP y coordinate
+ */
+ y: number;
+ /**
+ * Image Name
+ * @description The image this point represents
+ */
+ image_name: string;
+ /**
+ * Cluster
+ * @description DBSCAN cluster label; -1 means unclustered
+ */
+ cluster: number;
+ };
+ /**
+ * ImageMapPointsResponse
+ * @description The current user's semantic map.
+ */
+ ImageMapPointsResponse: {
+ /**
+ * Points
+ * @description The projected points
+ */
+ points: components["schemas"]["ImageMapPoint"][];
+ /**
+ * State
+ * @description disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served
+ * @enum {string}
+ */
+ state: "disabled" | "model_missing" | "empty" | "computing" | "ready";
+ /**
+ * Model Name
+ * @description The configured embedding model's name; only set when state is model_missing, so the client can tell the user which model to install
+ */
+ model_name?: string | null;
+ /**
+ * Stale
+ * @description True when the accessible image set has changed since this projection was computed; a refresh has been requested
+ */
+ stale: boolean;
+ /**
+ * Point Count
+ * @description Number of points returned
+ */
+ point_count: number;
+ /**
+ * Cluster Eps
+ * @description The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). Pass it back explicitly to get an identical clustering from a later request.
+ */
+ cluster_eps?: number | null;
+ /**
+ * Updated At
+ * @description When the served projection was computed
+ */
+ updated_at?: string | null;
+ };
+ /**
+ * ImageMapProjectionReadyEvent
+ * @description Event model for image_map_projection_ready
+ */
+ ImageMapProjectionReadyEvent: {
+ /**
+ * Timestamp
+ * @description The timestamp of the event
+ */
+ timestamp: number;
+ /**
+ * User Id
+ * @description The user whose image map projection was recomputed
+ */
+ user_id: string;
+ /**
+ * Point Count
+ * @description Number of points in the recomputed projection
+ */
+ point_count: number;
+ };
+ /**
+ * ImageMapProjectionStatus
+ * @description Status of the current user's cached projection.
+ */
+ ImageMapProjectionStatus: {
+ /**
+ * State
+ * @description Projection cache state
+ * @enum {string}
+ */
+ state: "disabled" | "model_missing" | "empty" | "computing" | "ready";
+ /**
+ * Stale
+ * @description Whether the cached projection lags the accessible image set
+ */
+ stale: boolean;
+ /**
+ * Point Count
+ * @description Points in the cached projection
+ */
+ point_count: number;
+ /**
+ * Updated At
+ * @description When the cached projection was computed
+ */
+ updated_at?: string | null;
+ };
+ /**
+ * ImageMapRefreshResponse
+ * @description Result of a projection refresh request.
+ */
+ ImageMapRefreshResponse: {
+ /**
+ * Enqueued
+ * @description True if the recompute was accepted (or already pending)
+ */
+ enqueued: boolean;
+ };
+ /**
+ * ImageMapStatusResponse
+ * @description Combined index + projection status for the current user.
+ */
+ ImageMapStatusResponse: {
+ /**
+ * Enabled
+ * @description Whether the embedding index is running
+ */
+ enabled: boolean;
+ /**
+ * Model Name
+ * @description The configured embedding model's name; only set when the projection state is model_missing
+ */
+ model_name?: string | null;
+ /** @description Embedding index progress counts. Admin-only: the counts aggregate over all users' images, so they are omitted for regular users. */
+ index?: components["schemas"]["ImageIndexStatus"] | null;
+ /** @description The user's projection cache status */
+ projection: components["schemas"]["ImageMapProjectionStatus"];
+ };
/**
* Image Mask to Tensor
* @description Convert a mask image to a tensor. Converts the image to grayscale and uses thresholding at the specified value.
@@ -44882,6 +45115,80 @@ export interface operations {
};
};
};
+ get_image_map_points: {
+ parameters: {
+ query?: {
+ /** @description DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span. */
+ eps?: number | null;
+ /** @description DBSCAN min_samples for clustering */
+ min_samples?: number;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ImageMapPointsResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ refresh_image_map: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 202: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ImageMapRefreshResponse"];
+ };
+ };
+ };
+ };
+ get_image_map_status: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ImageMapStatusResponse"];
+ };
+ };
+ };
+ };
upload_video: {
parameters: {
query: {
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
new file mode 100644
index 0000000000..f8e930bef6
--- /dev/null
+++ b/tests/app/routers/test_image_map.py
@@ -0,0 +1,427 @@
+"""Tests for the /v1/image_map endpoints: serving, staleness, and user scoping."""
+
+import logging
+
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api_app import app
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from 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_records_sqlite import ImageIndexRecordsSqlite
+from invokeai.app.services.image_index.projection import scope_hash
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
+from invokeai.app.services.invocation_services import InvocationServices
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.users.users_common import UserCreateRequest
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+MODEL_ID = "test-model-hash"
+DIM = 4
+SYSTEM_USER_ID = "system"
+
+
+class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker: Invoker) -> None:
+ self.invoker = invoker
+
+
+class FakeImageIndexService(ImageIndexServiceBase):
+ """Records projection requests instead of running a worker."""
+
+ def __init__(self, model_id: str | None = MODEL_ID) -> None:
+ self._model_id = model_id
+ self.projection_requests: list[tuple[str, bool]] = []
+
+ @property
+ def model_id(self) -> str | None:
+ return self._model_id
+
+ def get_status(self) -> ImageIndexStatus | None:
+ if self._model_id is None:
+ return None
+ return ImageIndexStatus(total=5, embedded=3)
+
+ def request_projection(self, user_id: str, all_images: bool = False) -> bool:
+ if self._model_id is None:
+ return False
+ self.projection_requests.append((user_id, all_images))
+ return True
+
+
+def image_index_service() -> FakeImageIndexService:
+ return FakeImageIndexService()
+
+
+def mock_services(image_index_service: FakeImageIndexService) -> InvocationServices:
+ from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
+ from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
+ from invokeai.app.services.boards.boards_default import BoardService
+ from invokeai.app.services.bulk_download.bulk_download_default import BulkDownloadService
+ from invokeai.app.services.client_state_persistence.client_state_persistence_sqlite import (
+ ClientStatePersistenceSqlite,
+ )
+ from invokeai.app.services.images.images_default import ImageService
+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
+ from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
+ from invokeai.app.services.project_records.project_records_sqlite import ProjectRecordsSqlite
+ from invokeai.app.services.users.users_default import UserService
+ from tests.test_nodes import TestEventService
+
+ configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
+ logger = InvokeAILogger.get_logger()
+ db = create_mock_sqlite_database(configuration, logger)
+
+ return InvocationServices(
+ board_image_records=SqliteBoardImageRecordStorage(db=db),
+ board_images=None, # type: ignore
+ board_records=SqliteBoardRecordStorage(db=db),
+ boards=BoardService(),
+ bulk_download=BulkDownloadService(),
+ configuration=configuration,
+ events=TestEventService(),
+ image_files=None, # type: ignore
+ image_records=SqliteImageRecordStorage(db=db),
+ images=ImageService(),
+ invocation_cache=MemoryInvocationCache(max_cache_size=0),
+ logger=logging, # type: ignore
+ model_images=None, # type: ignore
+ model_manager=None, # type: ignore
+ download_queue=None, # type: ignore
+ names=None, # type: ignore
+ performance_statistics=InvocationStatsService(),
+ session_processor=None, # type: ignore
+ session_queue=None, # type: ignore
+ urls=None, # type: ignore
+ workflow_records=None, # type: ignore
+ tensors=None, # type: ignore
+ conditioning=None, # type: ignore
+ style_preset_records=None, # type: ignore
+ style_preset_image_files=None, # type: ignore
+ workflow_thumbnails=None, # type: ignore
+ model_relationship_records=None, # type: ignore
+ model_relationships=None, # type: ignore
+ client_state_persistence=ClientStatePersistenceSqlite(db=db),
+ project_records=ProjectRecordsSqlite(db=db),
+ users=UserService(db),
+ wildcard_records=None, # type: ignore
+ system_prompt_records=None, # type: ignore
+ videos=None, # type: ignore
+ video_files=None, # type: ignore
+ video_records=None, # type: ignore
+ board_video_records=None, # type: ignore
+ gallery=None, # type: ignore
+ image_index_records=ImageIndexRecordsSqlite(db=db),
+ image_index=image_index_service,
+ external_generation=None, # type: ignore
+ )
+
+
+def mock_invoker(mock_services: InvocationServices) -> Invoker:
+ return Invoker(services=mock_services)
+
+
+def client(monkeypatch, mock_invoker: Invoker) -> TestClient:
+ mock_deps = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.image_map.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", mock_deps)
+ return TestClient(app)
+
+
+def _records(mock_invoker: Invoker) -> ImageIndexRecordsSqlite:
+ return mock_invoker.services.image_index_records
+
+
+def _seed_embedded_image(mock_invoker: Invoker, image_name: str, user_id: str = SYSTEM_USER_ID) -> None:
+ mock_invoker.services.image_records.save(
+ image_name=image_name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=16,
+ height=16,
+ has_workflow=False,
+ user_id=user_id,
+ )
+ 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))
+
+
+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(
+ 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
+ )
+
+
+# --- Single-user mode (system admin) ---
+
+
+def test_points_disabled_when_indexer_not_running(
+ monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ image_index_service._model_id = None
+ response = client.get("/api/v1/image_map/points")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["state"] == "disabled"
+ assert body["points"] == []
+
+
+def test_points_model_missing_when_enabled_without_model(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ # Indexing enabled in config, but the service found no installed model at
+ # start: the client must be able to tell this apart from "disabled".
+ image_index_service._model_id = None
+ mock_invoker.services.configuration.image_index_enabled = True
+ body = client.get("/api/v1/image_map/points").json()
+ assert body["state"] == "model_missing"
+ assert body["model_name"] == mock_invoker.services.configuration.image_index_model
+ assert body["points"] == []
+
+
+def test_points_empty_when_nothing_embedded(client: TestClient) -> None:
+ response = client.get("/api/v1/image_map/points")
+ assert response.status_code == 200
+ assert response.json()["state"] == "empty"
+
+
+def test_points_computing_and_enqueues_when_cache_missing(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _seed_embedded_image(mock_invoker, "a.png")
+
+ response = client.get("/api/v1/image_map/points")
+
+ body = response.json()
+ assert body["state"] == "computing"
+ assert body["stale"] is True
+ # System user is admin in single-user mode -> all_images scope.
+ assert image_index_service.projection_requests == [(SYSTEM_USER_ID, True)]
+
+
+def test_points_served_with_live_eps_clustering(mock_invoker: Invoker, client: TestClient) -> None:
+ names = ["a.png", "b.png", "c.png", "d.png"]
+ for name in names:
+ _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)
+
+ clustered = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()
+ assert clustered["state"] == "ready"
+ assert clustered["stale"] is False
+ assert clustered["point_count"] == 4
+ labels = {p["image_name"]: p["cluster"] for p in clustered["points"]}
+ assert labels["a.png"] == labels["b.png"] != labels["c.png"] == labels["d.png"]
+ assert labels["a.png"] != -1
+ assert clustered["cluster_eps"] == 0.5
+
+ # A much smaller eps dissolves the pairs into noise — recluster without recompute.
+ noisy = client.get("/api/v1/image_map/points", params={"eps": 0.05, "min_samples": 2}).json()
+ assert {p["cluster"] for p in noisy["points"]} == {-1}
+
+ # No eps: the adaptive default resolves to a concrete value, reported so a
+ # later request can reproduce the exact clustering.
+ adaptive = client.get("/api/v1/image_map/points", params={"min_samples": 2}).json()
+ assert adaptive["cluster_eps"] is not None
+ pinned = client.get("/api/v1/image_map/points", params={"eps": adaptive["cluster_eps"], "min_samples": 2}).json()
+ assert [p["cluster"] for p in pinned["points"]] == [p["cluster"] for p in adaptive["points"]]
+
+
+def test_stale_projection_filters_now_inaccessible_names_and_requests_refresh(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _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)
+ # The image disappears after the projection was cached.
+ mock_invoker.services.image_records.delete("gone.png")
+
+ body = client.get("/api/v1/image_map/points").json()
+
+ assert body["stale"] is True
+ assert [p["image_name"] for p in body["points"]] == ["keep.png"]
+ assert image_index_service.projection_requests == [(SYSTEM_USER_ID, True)]
+
+
+def test_refresh_endpoint_enqueues(image_index_service: FakeImageIndexService, client: TestClient) -> None:
+ response = client.post("/api/v1/image_map/refresh")
+ assert response.status_code == 202
+ assert response.json()["enqueued"] is True
+ assert image_index_service.projection_requests == [(SYSTEM_USER_ID, True)]
+
+
+def test_status_endpoint(mock_invoker: Invoker, client: TestClient) -> None:
+ body = client.get("/api/v1/image_map/status").json()
+ assert body["enabled"] is True
+ assert body["index"] == {"total": 5, "embedded": 3, "failed": 0}
+ 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))
+ body = client.get("/api/v1/image_map/status").json()
+ assert body["projection"]["state"] == "ready"
+ assert body["projection"]["stale"] is False
+ assert body["projection"]["point_count"] == 1
+
+
+def test_status_model_missing_when_enabled_without_model(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ image_index_service._model_id = None
+ mock_invoker.services.configuration.image_index_enabled = True
+ body = client.get("/api/v1/image_map/status").json()
+ assert body["enabled"] is False
+ assert body["model_name"] == mock_invoker.services.configuration.image_index_model
+ assert body["projection"]["state"] == "model_missing"
+
+
+def test_status_disabled(image_index_service: FakeImageIndexService, client: TestClient) -> None:
+ image_index_service._model_id = None
+ body = client.get("/api/v1/image_map/status").json()
+ assert body["enabled"] is False
+ assert body["model_name"] is None
+ assert body["projection"]["state"] == "disabled"
+
+
+def test_eps_validation(client: TestClient) -> None:
+ assert client.get("/api/v1/image_map/points", params={"eps": 0}).status_code == 422
+ assert client.get("/api/v1/image_map/points", params={"eps": 99}).status_code == 422
+
+
+# --- Multiuser mode: per-user scoping ---
+
+
+def multiuser(monkeypatch, mock_invoker: Invoker):
+ from invokeai.app.services.auth.token_service import set_jwt_secret
+
+ set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")
+ mock_invoker.services.configuration.multiuser = True
+
+
+def _create_user(mock_invoker: Invoker, email: str, is_admin: bool = False) -> str:
+ user = mock_invoker.services.users.create(
+ UserCreateRequest(email=email, display_name=email, password="TestPass123", is_admin=is_admin)
+ )
+ return user.user_id
+
+
+def _login(client: TestClient, email: str) -> dict[str, str]:
+ response = client.post("/api/v1/auth/login", json={"email": email, "password": "TestPass123", "remember_me": False})
+ assert response.status_code == 200
+ return {"Authorization": f"Bearer {response.json()['token']}"}
+
+
+def test_multiuser_projection_and_scope_are_per_user(
+ multiuser, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _create_user(mock_invoker, "[email protected]", is_admin=True)
+ user1_id = _create_user(mock_invoker, "[email protected]")
+ user2_id = _create_user(mock_invoker, "[email protected]")
+ user1_headers = _login(client, "[email protected]")
+ user2_headers = _login(client, "[email protected]")
+
+ # 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)
+ _records(mock_invoker).set_projection(
+ user1_id, MODEL_ID, scope_hash(MODEL_ID, accessible1), "{}", accessible1, np.zeros((1, 2), dtype=np.float32)
+ )
+
+ # user1 sees their own point.
+ body1 = client.get("/api/v1/image_map/points", headers=user1_headers).json()
+ assert [p["image_name"] for p in body1["points"]] == ["private1.png"]
+ assert body1["stale"] is False
+
+ # user2 has no cache and nothing accessible: empty, nothing enqueued, and
+ # user1's private image name never appears.
+ body2 = client.get("/api/v1/image_map/points", headers=user2_headers).json()
+ assert body2["state"] == "empty"
+ assert body2["points"] == []
+ assert (user2_id, False) not in image_index_service.projection_requests
+
+ # A non-admin refresh is scoped to their own images, not all_images.
+ client.post("/api/v1/image_map/refresh", headers=user2_headers)
+ assert (user2_id, False) in image_index_service.projection_requests
+
+ # Global index counts are admin-only in the status endpoint.
+ assert client.get("/api/v1/image_map/status", headers=user1_headers).json()["index"] is None
+
+
+def test_multiuser_stale_cache_never_leaks_revoked_names(multiuser, mock_invoker: Invoker, client: TestClient) -> None:
+ _create_user(mock_invoker, "[email protected]", is_admin=True)
+ user1_id = _create_user(mock_invoker, "[email protected]")
+ user2_id = _create_user(mock_invoker, "[email protected]")
+ user2_headers = _login(client, "[email protected]")
+
+ # user2's cached projection contains user1's image (e.g. from a share
+ # that has since been revoked). It must be filtered out when served.
+ _seed_embedded_image(mock_invoker, "was-shared.png", user_id=user1_id)
+ _seed_embedded_image(mock_invoker, "own2.png", user_id=user2_id)
+ _records(mock_invoker).set_projection(
+ user2_id,
+ MODEL_ID,
+ "stale-hash",
+ "{}",
+ ["was-shared.png", "own2.png"],
+ np.zeros((2, 2), dtype=np.float32),
+ )
+
+ body = client.get("/api/v1/image_map/points", headers=user2_headers).json()
+
+ assert body["stale"] is True
+ assert [p["image_name"] for p in body["points"]] == ["own2.png"]
+
+ # The status endpoint's point_count is also filtered to the current scope.
+ status_body = client.get("/api/v1/image_map/status", headers=user2_headers).json()
+ assert status_body["projection"]["point_count"] == 1
+
+
+def test_cluster_labels_computed_only_over_accessible_points(
+ multiuser, mock_invoker: Invoker, client: TestClient
+) -> None:
+ # Density-chaining through a hidden (inaccessible) point must not fuse the
+ # visible points into a cluster — that both mislabels them and leaks the
+ # hidden point's existence between them.
+ _create_user(mock_invoker, "[email protected]", is_admin=True)
+ user1_id = _create_user(mock_invoker, "[email protected]")
+ user2_id = _create_user(mock_invoker, "[email protected]")
+ user2_headers = _login(client, "[email protected]")
+
+ for name in ["p1.png", "p2.png", "far.png"]:
+ _seed_embedded_image(mock_invoker, name, user_id=user2_id)
+ _seed_embedded_image(mock_invoker, "hidden.png", user_id=user1_id)
+ # p1 and p2 are 3.0 apart (beyond eps 2.0); hidden sits between them, 1.5
+ # from each — close enough to chain them if it were clustered too. far.png
+ # widens the span so the eps clamp does not bind.
+ _records(mock_invoker).set_projection(
+ user2_id,
+ MODEL_ID,
+ "stale-hash",
+ "{}",
+ ["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),
+ )
+
+ body = client.get("/api/v1/image_map/points", params={"eps": 2.0, "min_samples": 2}, headers=user2_headers).json()
+
+ assert [p["image_name"] for p in body["points"]] == ["p1.png", "p2.png", "far.png"]
+ assert {p["cluster"] for p in body["points"]} == {-1}
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index d30df992e2..9cb7bc8ff8 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -1,5 +1,6 @@
"""Tests for the image index worker service, using an injected fake encoder (no models/GPU)."""
+import threading
import time
from types import SimpleNamespace
from typing import Callable
@@ -906,3 +907,82 @@ def test_stop_joins_worker(
service.stop()
assert not service._worker.is_alive()
+
+
+# --- Projection jobs ---
+
+
+def test_projection_job_computes_and_caches(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+) -> None:
+ from invokeai.app.services.events.events_common import ImageMapProjectionReadyEvent
+
+ # Three images stay on compute_umap's deterministic PCA fallback: the
+ # first real UMAP fit JIT-compiles numba, which blows CI timeouts on slow
+ # (Windows/macOS) runners. The worker pipeline under test is identical.
+ for i in range(3):
+ _save_image(image_records, f"img-{i}.png")
+ invoker = _make_invoker(images_service, index_records)
+ service.start(invoker)
+ _wait_until(lambda: not service._backfill_pending.is_set())
+
+ assert service.request_projection("system") is True
+
+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=30)
+ record = index_records.get_projection("system", MODEL_ID)
+ assert record is not None
+ assert record.point_count == 3
+ assert sorted(record.image_names) == [f"img-{i}.png" for i in range(3)]
+ assert record.coords.shape == (3, 2)
+ _wait_until(
+ lambda: any(
+ isinstance(e, ImageMapProjectionReadyEvent) and e.point_count == 3 for e in invoker.services.events.events
+ )
+ )
+
+
+def test_projection_failure_caches_empty_result_instead_of_looping(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ monkeypatch,
+) -> None:
+ from invokeai.app.services.image_index import image_index_default
+ from invokeai.app.services.image_index.projection import scope_hash
+
+ def broken_umap(embeddings, seed=42):
+ raise RuntimeError("synthetic UMAP failure")
+
+ monkeypatch.setattr(image_index_default, "compute_umap", broken_umap)
+ _save_image(image_records, "a.png")
+ service.start(_make_invoker(images_service, index_records))
+ _wait_until(lambda: not service._backfill_pending.is_set())
+
+ service.request_projection("system")
+
+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=15)
+ record = index_records.get_projection("system", MODEL_ID)
+ assert record is not None
+ 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)
+ assert record.scope_hash == scope_hash(MODEL_ID, accessible)
+
+
+def test_projection_request_dedup_is_last_writer_wins(service: ImageIndexService) -> None:
+ # Not started: requests are refused outright.
+ assert service.request_projection("system") is False
+
+ # Simulate a running worker to exercise the dedup map directly.
+ service._model_id = MODEL_ID
+ service._worker = threading.Thread(target=lambda: time.sleep(0.2), daemon=True)
+ service._worker.start()
+
+ assert service.request_projection("system", all_images=True) is True
+ assert service.request_projection("system", all_images=False) is True
+ assert service._projection_requests == {"system": False}
diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.py
new file mode 100644
index 0000000000..415790504b
--- /dev/null
+++ b/tests/app/services/image_index/test_projection.py
@@ -0,0 +1,171 @@
+"""Tests for the pure projection/clustering functions (UMAP, DBSCAN, scope hashing)."""
+
+import json
+
+import numpy as np
+
+from invokeai.app.services.image_index.projection import (
+ DEFAULT_CLUSTER_EPS,
+ adaptive_cluster_eps,
+ compute_clusters,
+ compute_umap,
+ projection_params,
+ resolve_cluster_eps,
+ scope_hash,
+)
+
+
+def _blobs(n_per_blob: int = 30, dim: int = 64, n_blobs: int = 3) -> np.ndarray:
+ """Well-separated gaussian blobs in embedding space, L2-normalized."""
+ rng = np.random.default_rng(7)
+ centers = rng.standard_normal((n_blobs, dim)) * 10
+ vectors = np.concatenate([center + rng.standard_normal((n_per_blob, dim)) * 0.1 for center in centers]).astype(
+ np.float32
+ )
+ return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
+
+
+def test_umap_shapes_and_finiteness() -> None:
+ embeddings = _blobs()
+ coords = compute_umap(embeddings)
+ assert coords.shape == (embeddings.shape[0], 2)
+ assert coords.dtype == np.float32
+ assert np.isfinite(coords).all()
+
+
+def test_umap_recovers_separated_blobs_as_clusters() -> None:
+ coords = compute_umap(_blobs())
+ # Normalize coordinate scale so a fixed eps is meaningful.
+ span = np.ptp(coords, axis=0).max()
+ labels = compute_clusters(coords, eps=span * 0.05, min_samples=10)
+ non_noise = {label for label in labels if label != -1}
+ assert len(non_noise) >= 2
+
+
+def test_umap_is_deterministic_with_seed() -> None:
+ embeddings = _blobs(n_per_blob=15)
+ assert np.array_equal(compute_umap(embeddings, seed=42), compute_umap(embeddings, seed=42))
+
+
+def test_umap_degenerate_inputs() -> None:
+ assert compute_umap(np.empty((0, 8), dtype=np.float32)).shape == (0, 2)
+ single = compute_umap(np.ones((1, 8), dtype=np.float32))
+ assert single.shape == (1, 2)
+ assert np.isfinite(single).all()
+
+
+def test_umap_tiny_galleries_fall_back_to_pca() -> None:
+ # umap-learn cannot fit 2 or 3 points; these must still produce a map
+ # rather than an exception (which would loop the projection worker).
+ rng = np.random.default_rng(3)
+ for n in (2, 3):
+ coords = compute_umap(rng.standard_normal((n, 16)).astype(np.float32))
+ assert coords.shape == (n, 2)
+ assert np.isfinite(coords).all()
+ # Distinct points must land at distinct coordinates.
+ two = compute_umap(np.array([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=np.float32))
+ assert not np.allclose(two[0], two[1])
+
+
+def test_compute_clusters_empty_and_noise() -> None:
+ assert compute_clusters(np.empty((0, 2), dtype=np.float32)).shape == (0,)
+ # Points far apart with min_samples > 1 are all noise.
+ scattered = np.array([[0, 0], [100, 100], [-100, 50]], dtype=np.float32)
+ assert set(compute_clusters(scattered, eps=0.5, min_samples=2)) == {-1}
+
+
+def test_compute_clusters_adaptive_default_scales_to_small_galleries() -> None:
+ # Small-N UMAP output is widely spread (span ~30 for a few dozen points),
+ # so a fixed eps=0.2 labels everything noise; the adaptive default must
+ # recover three well-separated 12-point blobs without an explicit eps.
+ rng = np.random.default_rng(7)
+ centers = np.array([[0.0, 0.0], [30.0, 0.0], [0.0, 30.0]])
+ coords = np.vstack([center + rng.normal(scale=0.4, size=(12, 2)) for center in centers]).astype(np.float32)
+
+ labels = compute_clusters(coords)
+
+ assert set(labels) == {0, 1, 2}
+ for blob in range(3):
+ assert len(set(labels[blob * 12 : (blob + 1) * 12])) == 1
+
+
+def test_compute_clusters_adaptive_default_leaves_structureless_maps_unclustered() -> None:
+ # A uniform grid has no density structure; the span clamp keeps the
+ # adaptive eps below the grid spacing so nothing chains into a cluster.
+ xs, ys = np.meshgrid(np.arange(8.0), np.arange(8.0))
+ coords = np.stack([xs.ravel(), ys.ravel()], axis=1).astype(np.float32)
+
+ assert set(compute_clusters(coords)) == {-1}
+
+
+def test_adaptive_cluster_eps_degenerate_inputs() -> None:
+ assert adaptive_cluster_eps(np.zeros((1, 2), dtype=np.float32)) == DEFAULT_CLUSTER_EPS
+ coincident = np.zeros((20, 2), dtype=np.float32)
+ assert adaptive_cluster_eps(coincident) == DEFAULT_CLUSTER_EPS
+ # Coincident points still cluster under the fallback eps.
+ assert set(compute_clusters(coincident)) == {0}
+
+
+def test_eps_shrinks_to_fit_neighbor_pair_budget(monkeypatch) -> None:
+ # A dense blob on a wide map: the adaptive eps (set by the sparse
+ # background) would materialize a quadratic number of neighbor pairs
+ # inside the blob. The budget must shrink eps rather than let DBSCAN
+ # allocate them.
+ import invokeai.app.services.image_index.projection as projection
+
+ rng = np.random.default_rng(3)
+ dense = rng.normal(scale=0.05, size=(120, 2))
+ sparse = rng.uniform(-50.0, 50.0, size=(120, 2))
+ coords = np.vstack([dense, sparse]).astype(np.float32)
+
+ unbudgeted = resolve_cluster_eps(coords)
+ monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 5_000)
+ budgeted = resolve_cluster_eps(coords)
+
+ assert budgeted < unbudgeted
+ # And the budgeted eps is what the default clustering path actually uses:
+ # identical labels when passed back explicitly.
+ np.testing.assert_array_equal(compute_clusters(coords), compute_clusters(coords, eps=budgeted))
+
+
+def test_resolve_cluster_eps_is_idempotent() -> None:
+ # /points reports the resolved eps so a later request can reproduce the
+ # clustering; resolving an already-resolved eps must not change it.
+ rng = np.random.default_rng(5)
+ coords = rng.normal(size=(200, 2)).astype(np.float32) * 10
+ resolved = resolve_cluster_eps(coords)
+ assert resolve_cluster_eps(coords, eps=resolved) == resolved
+
+
+def test_compute_clusters_clamps_eps_to_span_fraction() -> None:
+ # Span ~1: an eps near the span would make every point a neighbor of
+ # every other (the sklearn DBSCAN memory blowup); the clamp keeps distant
+ # pairs from ever merging.
+ coords = np.array([[0, 0], [0.01, 0], [1, 1], [1.01, 1]], dtype=np.float32)
+ labels = compute_clusters(coords, eps=2.0, min_samples=2)
+ assert labels[0] == labels[1] != labels[2] == labels[3]
+
+
+def test_compute_clusters_skips_huge_point_sets() -> None:
+ from invokeai.app.services.image_index.projection import MAX_CLUSTERED_POINTS
+
+ coords = np.zeros((MAX_CLUSTERED_POINTS + 1, 2), dtype=np.float32)
+ labels = compute_clusters(coords, eps=0.2, min_samples=2)
+ assert set(labels) == {-1}
+
+
+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"])
+ 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"])
+
+
+def test_projection_params_is_stable_json() -> None:
+ params = json.loads(projection_params(n_points=100))
+ assert params["n_neighbors"] == 15
+ assert json.loads(projection_params(n_points=5))["n_neighbors"] == 4
+ assert json.loads(projection_params(n_points=1))["n_neighbors"] == 1
+ assert projection_params(n_points=100) == projection_params(n_points=100)