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): throttle image map refreshes and reuse repeat clusterings

Lincoln Stein55af35ebc6ae
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index 0f378cbe61..9933ec79be 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -1,4 +1,7 @@
import asyncio
+import threading
+import time
+from collections import OrderedDict
from typing import Literal, Optional
import numpy as np
@@ -104,6 +107,63 @@ def _scope(current_user) -> tuple[str, bool]:
return current_user.user_id, current_user.is_admin
+# A recompute takes minutes on any gallery large enough for this to matter, so
+# refusing a second request inside this window costs a caller nothing — while a
+# loop of them would otherwise pin the single index worker for every user and
+# fan an event into every connected admin's socket per iteration.
+MIN_REFRESH_INTERVAL_SECONDS = 10.0
+
+_refresh_claims: dict[str, float] = {}
+# Guards both module-level caches below. Held only for dict work, never across
+# clustering or a DB call.
+_state_lock = threading.Lock()
+
+
+def _claim_refresh_slot(user_id: str) -> bool:
+ """Whether this user may enqueue a refresh now, claiming their interval if so."""
+ now = time.monotonic()
+ with _state_lock:
+ # Prune on write: entries older than the window can never throttle
+ # anyone, so this keeps the map to users who refreshed recently rather
+ # than one entry per user who ever has.
+ for uid, claimed_at in list(_refresh_claims.items()):
+ if now - claimed_at >= MIN_REFRESH_INTERVAL_SECONDS:
+ del _refresh_claims[uid]
+ if user_id in _refresh_claims:
+ return False
+ _refresh_claims[user_id] = now
+ return True
+
+
+def _release_refresh_slot(user_id: str) -> None:
+ with _state_lock:
+ _refresh_claims.pop(user_id, None)
+
+
+# /points is polled, and between polls its inputs almost never change, so the
+# clustering it repeats is usually identical work. Caching the labels turns the
+# steady state into a dict lookup; the entries are int64 label arrays (~400KB at
+# the 50k-point clustering cap), so a handful of them costs a few MB.
+_CLUSTER_CACHE_ENTRIES = 8
+_cluster_cache: "OrderedDict[tuple[str, str, Optional[str], Optional[float], int], tuple[np.ndarray, Optional[float]]]" = OrderedDict()
+
+
+def _cluster_cache_get(key) -> Optional[tuple[np.ndarray, Optional[float]]]:
+ with _state_lock:
+ hit = _cluster_cache.get(key)
+ if hit is not None:
+ _cluster_cache.move_to_end(key)
+ return hit
+
+
+def _cluster_cache_put(key, value: tuple[np.ndarray, Optional[float]]) -> None:
+ with _state_lock:
+ _cluster_cache[key] = value
+ _cluster_cache.move_to_end(key)
+ while len(_cluster_cache) > _CLUSTER_CACHE_ENTRIES:
+ _cluster_cache.popitem(last=False)
+
+
@image_map_router.get("/points", operation_id="get_image_map_points", response_model=ImageMapPointsResponse)
async def get_image_map_points(
current_user: CurrentUserOrDefault,
@@ -149,7 +209,8 @@ async def get_image_map_points(
points=[], state="computing" if enqueued else "empty", stale=enqueued, point_count=0
)
- stale = record.scope_hash != scope_hash(model_id, current_names)
+ current_hash = scope_hash(model_id, current_names)
+ stale = record.scope_hash != current_hash
retrying = False
if stale:
services.image_index.request_projection(user_id, all_images=is_admin)
@@ -179,6 +240,21 @@ async def get_image_map_points(
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_coords = record.coords[mask]
+
+ # Every input to the clustering is pinned by this key: which projection
+ # row (its own scope hash plus updated_at, which moves on every rewrite),
+ # which subset of it this user can currently see (current_hash), and the
+ # two DBSCAN parameters. user_id is in the key too, so one user's labels
+ # can never be served to another even if the rest collides.
+ cache_key = (user_id, record.scope_hash, record.updated_at, current_hash, eps, min_samples)
+ cached_labels = _cluster_cache_get(cache_key)
+ if cached_labels is not None:
+ labels, resolved_eps = cached_labels
+ 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
+
try:
if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
resolved_eps = resolve_cluster_eps(visible_coords, eps, min_samples)
@@ -199,6 +275,11 @@ async def get_image_map_points(
services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving points unclustered")
resolved_eps = None
labels = np.full((visible_coords.shape[0],), -1, dtype=np.int64)
+ else:
+ # Only a real result is cached: caching the degraded all-noise
+ # fallback would make a one-off failure stick for as long as the
+ # entry survives.
+ _cluster_cache_put(cache_key, (labels, resolved_eps))
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)
@@ -225,7 +306,17 @@ async def get_image_map_points(
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)
+ if not _claim_refresh_slot(user_id):
+ # Throttled, not failed: `enqueued` already means "was this accepted",
+ # so a client needs no new status code or field to understand it.
+ return ImageMapRefreshResponse(enqueued=False)
+
enqueued = ApiDependencies.invoker.services.image_index.request_projection(user_id, all_images=is_admin)
+ if not enqueued:
+ # Nothing was actually queued (the indexer is not running), so this
+ # request must not consume the user's interval — otherwise a client
+ # polling through a restart is locked out of the first real refresh.
+ _release_refresh_slot(user_id)
return ImageMapRefreshResponse(enqueued=enqueued)
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index f8e930bef6..612d7f2b81 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -425,3 +425,149 @@ def test_cluster_labels_computed_only_over_accessible_points(
assert [p["image_name"] for p in body["points"]] == ["p1.png", "p2.png", "far.png"]
assert {p["cluster"] for p in body["points"]} == {-1}
+
+
+# --- Refresh throttling and clustering reuse ---
+
+
[email protected](autouse=True)
+def _reset_image_map_router_state():
+ """The throttle and cluster cache are module state, so they outlive a test."""
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ image_map_router_module._refresh_claims.clear()
+ image_map_router_module._cluster_cache.clear()
+ yield
+ image_map_router_module._refresh_claims.clear()
+ image_map_router_module._cluster_cache.clear()
+
+
+def test_refresh_is_throttled_per_user(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is True
+ # A recompute takes minutes; a second request inside the window is refused
+ # without reaching the single shared index worker at all.
+ for _ in range(5):
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is False
+ assert len(image_index_service.projection_requests) == 1
+
+ # Once the interval has passed the next request is accepted again.
+ image_map_router_module._refresh_claims[SYSTEM_USER_ID] -= image_map_router_module.MIN_REFRESH_INTERVAL_SECONDS + 1
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is True
+ assert len(image_index_service.projection_requests) == 2
+
+
+def test_refresh_throttle_is_not_consumed_when_nothing_was_enqueued(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ """A refused enqueue (indexer down) must not lock the user out of the next real one."""
+ image_index_service._model_id = None
+
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is False
+
+ image_index_service._model_id = MODEL_ID
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is True
+
+
+def test_refresh_throttle_does_not_gate_the_points_recovery_path(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ """/points enqueues the one-shot retry of a failed projection.
+
+ Throttling inside request_projection instead of the route would suppress that
+ recovery, so a failed fit would go back to being permanent.
+ """
+ _seed_embedded_image(mock_invoker, "a.png")
+ # An empty projection over a non-empty gallery: the shape a failed fit leaves.
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, [], np.empty((0, 2), dtype=np.float32))
+
+ assert client.post("/api/v1/image_map/refresh").json()["enqueued"] is True
+ before = len(image_index_service.projection_requests)
+ body = client.get("/api/v1/image_map/points").json()
+
+ assert len(image_index_service.projection_requests) == before + 1
+ assert body["state"] == "computing"
+
+
+def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker: Invoker, client: TestClient) -> None:
+ """/points is polled, and between polls nothing it clusters has changed."""
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ calls = {"n": 0}
+ real_cluster = image_map_router_module.cluster_at_eps
+
+ def counting_cluster(coords, eps, min_samples):
+ calls["n"] += 1
+ return real_cluster(coords, eps, min_samples)
+
+ monkeypatch.setattr(image_map_router_module, "cluster_at_eps", counting_cluster)
+
+ names = ["a.png", "b.png", "c.png", "d.png"]
+ 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)
+
+ first = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()
+ for _ in range(4):
+ repeat = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()
+ assert repeat["points"] == first["points"]
+ assert repeat["cluster_eps"] == first["cluster_eps"]
+ assert calls["n"] == 1, "identical repeat polls must not recluster"
+
+ # Every clustering input is part of the key.
+ client.get("/api/v1/image_map/points", params={"eps": 0.05, "min_samples": 2}).json()
+ assert calls["n"] == 2, "a different eps must recluster"
+ client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 3}).json()
+ assert calls["n"] == 3, "a different min_samples must recluster"
+
+ # 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())
+ 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"]
+
+
+def test_cluster_cache_is_bounded(monkeypatch, mock_invoker: Invoker, client: TestClient) -> None:
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ names = ["a.png", "b.png", "c.png", "d.png"]
+ for name in names:
+ _seed_embedded_image(mock_invoker, name)
+ _seed_projection(
+ mock_invoker,
+ SYSTEM_USER_ID,
+ names,
+ np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32),
+ )
+
+ # Distinct eps values are distinct keys; the cache must not grow per request.
+ for i in range(image_map_router_module._CLUSTER_CACHE_ENTRIES * 3):
+ client.get("/api/v1/image_map/points", params={"eps": 0.1 + i * 0.01, "min_samples": 2})
+
+ assert len(image_map_router_module._cluster_cache) == image_map_router_module._CLUSTER_CACHE_ENTRIES
+
+
+def test_cluster_cache_never_serves_one_users_labels_to_another(
+ multiuser, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """user_id is in the cache key, so a collision on every other component still cannot cross users."""
+ 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]")
+
+ _seed_embedded_image(mock_invoker, "mine.png", user_id=user1_id)
+ _seed_embedded_image(mock_invoker, "theirs.png", user_id=user2_id)
+ _seed_projection(mock_invoker, user1_id, ["mine.png"], np.array([[0.0, 0.0]], dtype=np.float32))
+ _seed_projection(mock_invoker, user2_id, ["theirs.png"], np.array([[0.0, 0.0]], dtype=np.float32))
+
+ first = client.get("/api/v1/image_map/points", headers=user1_headers).json()
+ second = client.get("/api/v1/image_map/points", headers=user2_headers).json()
+
+ assert [p["image_name"] for p in first["points"]] == ["mine.png"]
+ assert [p["image_name"] for p in second["points"]] == ["theirs.png"]