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
fix(api): make the retry budget agree with what /points can actually serve
Lincoln Stein11c12a5ff2cf
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 3219ee088f..858a9dd8c1 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -142,25 +142,34 @@ def _release_refresh_slot(user_id: str) -> 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]]]:+# steady state into a dict lookup; entries are int64 label arrays, bounded at+# ~400KB each by the 50k-point clustering cap (only a clustering that actually+# ran is stored, so the all-noise array returned above the cap — which is free+# to recompute and unbounded in size — never lands here).+#+# ONE entry per user, rather than a shared pool of N. A shared pool made the+# cache worse than none: with more concurrent map users than slots, strict LRU+# 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]+_cluster_cache: "OrderedDict[str, tuple[_ClusterCacheKey, np.ndarray, Optional[float]]]" = OrderedDict()+++def _cluster_cache_get(user_id: str, key: _ClusterCacheKey) -> 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+ entry = _cluster_cache.get(user_id)+ if entry is None or entry[0] != key:+ return None+ _cluster_cache.move_to_end(user_id)+ return entry[1], entry[2]-def _cluster_cache_put(key, value: tuple[np.ndarray, Optional[float]]) -> None:+def _cluster_cache_put(user_id: str, key: _ClusterCacheKey, labels: np.ndarray, resolved_eps: 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[user_id] = (key, labels, resolved_eps)+ _cluster_cache.move_to_end(user_id)+ while len(_cluster_cache) > _CLUSTER_CACHE_USERS:_cluster_cache.popitem(last=False)@@ -212,55 +221,51 @@ async def get_image_map_points(current_hash = scope_hash(model_id, current_names)stale = record.scope_hash != current_hash- # Computed once, here, because the retry decision below depends on it: a row- # can carry point_count > 0 and still contribute nothing, if every one of- # its coordinates is non-finite. Deciding on the cached count instead left- # exactly that row serving "empty, not stale" with nothing ever asking for a- # recompute — the same terminal blankness this retry exists to remove.- accessible = set(current_names)- visible_mask = np.fromiter(- (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)- )- # 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)-- retrying = Falseif stale:services.image_index.request_projection(user_id, all_images=is_admin)- elif current_names and not visible_mask.any():- # Nothing servable over a gallery that HAS embedded images: 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- # permanent failure settles into an honest "empty" instead of a- # request/event cycle driven by every poll.- retrying = services.image_index.request_projection(user_id, all_images=is_admin, failed_scope=current_hash)# 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]]:+ # image 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+ # loop time per poll on a 500k-image gallery, stalling every other request+ # 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]:+ accessible = set(current_names)+ visible_mask = np.fromiter(+ (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)+ )+ # 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_coords = record.coords[visible_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)+ # 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)+ cached_labels = _cluster_cache_get(user_id, 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+ 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,+ True,+ )try:if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:@@ -270,6 +275,11 @@ async def get_image_map_points(# 0.01 floor to a budget-shrunk eps — so the value reported# here would not be the value DBSCAN used.labels = cluster_at_eps(visible_coords, resolved_eps, min_samples)+ # Cached only here. The other branch's labels are a constant+ # -1 array sized to the full point count — free to recompute,+ # unbounded in size, and above the cap that is the only array+ # large enough to matter.+ _cluster_cache_put(user_id, cache_key, labels, resolved_eps)else:resolved_eps = Nonelabels = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)@@ -278,21 +288,32 @@ async def get_image_map_points(# data. sklearn raises on a non-finite cached row (which a build# predating the writer's isfinite guard could have left behind),# and an unhandled raise here 500s this user on EVERY request until- # their gallery changes. Serve the map unclustered instead.+ # their gallery changes. Serve the map unclustered instead. Nothing+ # is cached on this path: a one-off failure must not stick.services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving points unclustered")resolved_eps = Nonelabels = 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)- ], resolved_eps-- points, resolved_eps = await asyncio.to_thread(build_points)+ 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,+ bool(visible_mask.any()),+ )++ points, resolved_eps, any_visible = 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+ # 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+ # permanent failure settles into an honest "empty" instead of a+ # request/event cycle driven by every poll.+ retrying = services.image_index.request_projection(user_id, all_images=is_admin, failed_scope=current_hash)+state: ImageMapState = "ready" if points else ("computing" if retrying else "empty")return ImageMapPointsResponse(points=points,@@ -318,7 +339,16 @@ async def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefre# 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)+ try:+ enqueued = ApiDependencies.invoker.services.image_index.request_projection(+ user_id, all_images=is_admin, user_initiated=True+ )+ except Exception:+ # A raise between the claim and the release (the invoker is absent+ # during a startup or shutdown window, say) would otherwise leave the+ # claim held with nothing queued against it.+ _release_refresh_slot(user_id)+ raiseif not enqueued:# Nothing was actually queued (the indexer is not running), so this# request must not consume the user's interval — otherwise a clientdiff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex 5a03247c64..7c65bf5520 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -25,7 +25,13 @@ class ImageIndexServiceBase(ABC):pass@abstractmethod- def request_projection(self, user_id: str, all_images: bool = False, failed_scope: Optional[str] = None) -> bool:+ def request_projection(+ self,+ user_id: str,+ all_images: bool = False,+ failed_scope: Optional[str] = None,+ user_initiated: 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@@ -40,6 +46,10 @@ class ImageIndexServiceBase(ABC):believes to be a failed fit. The request is refused once thatscope's single retry has been used, so a caller that asks onevery poll cannot drive an endless request/event cycle.+ user_initiated: This request came from a person rather than from+ polling, so a spent retry budget is cleared and the failed+ scope gets another fit. Callers driven by a timer, an event, or+ a staleness check must leave this False.Returns:True if the request was accepted (or already pending); False ifdiff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 453a935b21..8e5a56bd02 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -149,7 +149,13 @@ 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, failed_scope: Optional[str] = None) -> bool:+ def request_projection(+ self,+ user_id: str,+ all_images: bool = False,+ failed_scope: Optional[str] = None,+ user_initiated: bool = False,+ ) -> bool:if self._model_id is None or self._worker is None or not self._worker.is_alive():return Falseif failed_scope is not None and not self._failed_scope_retry_available(user_id, failed_scope):@@ -161,6 +167,15 @@ class ImageIndexService(ImageIndexServiceBase):# the life of the process.return Falsewith self._projection_lock:+ if user_initiated:+ # A person asked for this, so give the scope a fresh budget:+ # without it /refresh answered `enqueued: true` while the worker+ # was guaranteed to short-circuit, and a user whose retry was+ # spent had no way back short of restarting the server. NOT for+ # a bare request — /points' staleness path passes none of this+ # and is driven by polling, so clearing there would hand a+ # poller the unlimited retries the budget exists to deny.+ self._failed_projection_scopes.pop(user_id, None)# Last writer wins: the scope reflects the requester's most recent# admin status, so a promotion/demotion between requests cannot# pin a stale scope.@@ -293,23 +308,12 @@ class ImageIndexService(ImageIndexServiceBase):self._status_dirty.set()raiseif batch is not None:- if self._generation_in_progress():- # Only while a generation actually holds the GPU. The- # embed below is about to park for its whole duration,- # and a projection reads stored embeddings only — no- # encoder, no GPU — so making it wait too left /points- # reporting "computing" for the length of a run.- #- # Deliberately NOT on every pass with embedding work:- # that runs a fit between every backfill batch, each one- # obsolete as soon as the next batch stores, which is- # why projections are otherwise deferred to quiescence.- # (During a generation nothing new can embed, so the- # scope hash holds still and repeat requests- # short-circuit rather than refitting.)- projection_job = self._next_projection_job()- if projection_job is not None:- self._process_projection(*projection_job)+ # Projections are serviced from INSIDE this wait (see+ # _wait_for_idle_generation), not from a gate before it. A+ # gate is only read once per pass, so a request arriving+ # after the worker had already parked waited out the whole+ # run — the exact "computing for the length of a generation"+ # symptom it was added to fix.self._wait_for_idle_generation()if self._stop_event.is_set():break@@ -585,26 +589,26 @@ class ImageIndexService(ImageIndexServiceBase):re-entered). The map stays blank until the accessible image setchanges, and the row is in SQLite, so restarting does not clear it.- Retrying once per (user, scope) per process splits the difference the- original code could not: a transient failure — a MemoryError while a- generation holds RAM, a JIT hiccup, the non-finite guard — heals on the- next request, while a permanent one costs one wasted fit per restart- instead of one per poll.-- A pure check: the budget is spent by _spend_failed_scope_retry, at the- point the fit is actually about to run. Spending it here instead meant a- "database is locked" on the embedding read — the most designed-for- transient error in this file — consumed the retry without ever- attempting a fit, leaving the map blank in a process where it would have- worked.+ Retrying a failed scope once splits the difference the original code+ could not: a transient failure — a MemoryError while a generation holds+ RAM, a JIT hiccup, the non-finite guard — heals on the next request,+ while a permanent one costs one wasted fit instead of one per poll.++ The bound is one retry per failed fit that reaches the cache, NOT one+ per (user, scope) for the life of the process: any later fit that+ produces points clears the marker, so a scope that fails, succeeds after+ a gallery change, and then fails again is retried again. That is the+ intent — the budget exists to stop a doomed fit from repeating, and a+ success in between is evidence the next failure is worth one more try.++ A pure check. The budget is spent in _process_projection, once the+ failed result is durably cached, so nothing that returns before the+ write — a "database is locked" on the embedding read, a shutdown, or a+ successful fit whose own write is lost — can burn a retry."""with self._projection_lock:return self._failed_projection_scopes.get(user_id) != current_hash- def _spend_failed_scope_retry(self, user_id: str, current_hash: str) -> None:- with self._projection_lock:- self._failed_projection_scopes[user_id] = current_hash-def _next_projection_job(self) -> Optional[tuple[str, bool]]:with self._projection_lock:if not self._projection_requests:@@ -637,7 +641,17 @@ class ImageIndexService(ImageIndexServiceBase):retrying_failed_scope = (cached is not Noneand cached.scope_hash == current_hash- and cached.point_count == 0+ # "Failed" is *nothing servable*, not point_count == 0. /points+ # drops non-finite rows before it serves them, so a row with points+ # but no FINITE points is empty to every client while looking+ # populated here. Testing the count instead left that row failing+ # this check while /points kept asking on its behalf: the request+ # was granted, the branch below short-circuited without spending the+ # budget, the emit brought the client straight back, and the retry+ # that was supposed to break the cycle could never be spent. An+ # 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 self._failed_scope_retry_available(user_id, current_hash))@@ -667,12 +681,6 @@ class ImageIndexService(ImageIndexServiceBase):self._requeue_projection(user_id, all_images)return- if retrying_failed_scope:- # Spent here, not at the check: every return above this line leaves- # the budget intact, so a transient DB error or a shutdown cannot- # burn a retry that never ran.- self._spend_failed_scope_retry(user_id, current_hash)-try:coords = compute_umap(matrix)if coords.shape[0] != len(found_names):@@ -711,12 +719,24 @@ class ImageIndexService(ImageIndexServiceBase):logger.exception(f"Image map: could not cache the projection for user '{user_id}'; re-queueing")self._requeue_projection(user_id, all_images)return- if found_names:- # A fit that produced points clears the retry marker, so a LATER- # failure over some future scope gets its own retry rather than- # inheriting this one's spent budget.- with self._projection_lock:++ # The budget moves only once the outcome is durable. Spending it before+ # the fit looked safer — nothing between the spend and compute_umap can+ # return — but it ignored the write: a fit that SUCCEEDS and then loses+ # its `set_projection` to a locked database returns above this line, and+ # the requeued job finds the old empty row with the budget already gone.+ # That threw away minutes of correct work and left the map permanently+ # blank without a single failed fit anywhere in the sequence. Spending+ # 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:+ # 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.self._failed_projection_scopes.pop(user_id, None)+ 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))except Exception:@@ -731,24 +751,20 @@ class ImageIndexService(ImageIndexServiceBase):with self._projection_lock:self._projection_requests.setdefault(user_id, all_images)- def _generation_in_progress(self) -> bool:- """Whether a generation currently holds the GPU. Cheap and non-blocking."""- assert self._invoker is not None- if self._cpu_mode():- return False- session_queue = self._invoker.services.session_queue- if session_queue is None:- return False- try:- return session_queue.get_queue_status(DEFAULT_QUEUE_ID).in_progress > 0- except Exception:- return False-def _wait_for_idle_generation(self) -> None:"""Block until no generation is in progress, unless embedding on CPU.The embedding model shares the model cache (and therefore VRAM) withgeneration; embedding on the GPU mid-generation would thrash both.++ Projection jobs are serviced while parked here. A projection reads+ stored embeddings only — no encoder, no GPU — so it is exactly the work+ that can proceed while embedding cannot, and this is the only place it+ runs alongside pending embedding work: everywhere else projections are+ deferred to quiescence, because a fit between backfill batches is+ obsolete as soon as the next batch stores. Nothing new can embed while+ we are parked, so the accessible set holds still and a repeat request+ short-circuits on its scope hash rather than refitting."""assert self._invoker is not Noneif self._cpu_mode():@@ -763,6 +779,12 @@ class ImageIndexService(ImageIndexServiceBase):returnif status.in_progress == 0:return+ projection_job = self._next_projection_job()+ if projection_job is not None:+ # No wait before looping: a request that arrived during the fit+ # is served immediately, and the generation check above is cheap.+ self._process_projection(*projection_job)+ continueself._stop_event.wait(_POLL_SECONDS)def _emit_status(self) -> None:diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 048f5009a4..07bc4adc53 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -39,7 +39,7 @@ class FakeImageIndexService(ImageIndexServiceBase):def __init__(self, model_id: str | None = MODEL_ID) -> None:self._model_id = model_idself.projection_requests: list[tuple[str, bool]] = []- self.spent_failed_scopes: set[str] = set()+ self.spent_failed_scopes: dict[str, str] = {}@propertydef model_id(self) -> str | None:@@ -50,14 +50,28 @@ class FakeImageIndexService(ImageIndexServiceBase):return Nonereturn ImageIndexStatus(total=5, embedded=3)- def request_projection(self, user_id: str, all_images: bool = False, failed_scope: str | None = None) -> bool:+ def request_projection(+ self,+ user_id: str,+ all_images: bool = False,+ failed_scope: str | None = None,+ user_initiated: bool = False,+ ) -> bool:if self._model_id is None:return False- # Mirrors the real service: a failed scope gets one retry, then refuses.- if failed_scope is not None:- if failed_scope in self.spent_failed_scopes:+ # A stand-in for the refusal, NOT a model of it: the real service decides+ # from its own view of the cached row and spends the budget on the worker+ # thread, long after this call returns. These tests pin what the ROUTER+ # does with an accept and a refusal; that the real service actually+ # refuses (and for the same rows) is pinned in+ # tests/app/services/image_index/test_image_index_service.py.+ if user_initiated:+ # A person asked, so the budget resets — as the real service does.+ self.spent_failed_scopes.pop(user_id, None)+ elif failed_scope is not None:+ if self.spent_failed_scopes.get(user_id) == failed_scope:return False- self.spent_failed_scopes.add(failed_scope)+ self.spent_failed_scopes[user_id] = failed_scopeself.projection_requests.append((user_id, all_images))return True@@ -551,32 +565,46 @@ def test_cluster_cache_is_bounded(monkeypatch, mock_invoker: Invoker, client: Tenp.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):+ # eps is caller-controlled and unthrottled. Varying it must cost the caller+ # their OWN entry and nothing else: a shared pool let one client evict every+ # other user's labels with a handful of requests.+ for i in range(image_map_router_module._CLUSTER_CACHE_USERS * 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+ assert len(image_map_router_module._cluster_cache) == 1+ assert set(image_map_router_module._cluster_cache) == {SYSTEM_USER_ID}-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"]+def test_cluster_cache_evicts_by_user_and_never_crosses_them() -> None:+ """The cache is keyed by user, so an identical key for two users is two entries.++ Asserted directly on the helpers: seeding two users whose rows collide on+ every other key component is not reachable through the API (each user's+ scope hash and updated_at differ), so a round-trip test of this would pass+ with the user dimension removed entirely.+ """+ from invokeai.app.api.routers import image_map as image_map_router_module++ key: image_map_router_module._ClusterCacheKey = ("scope", "2026-01-01 00:00:00.000", "current", 0.2, 10)+ mine = np.array([0, 1], dtype=np.int64)+ theirs = np.array([1, 0], dtype=np.int64)++ image_map_router_module._cluster_cache_put("user1", key, mine, 0.2)+ image_map_router_module._cluster_cache_put("user2", key, theirs, 0.2)++ assert image_map_router_module._cluster_cache_get("user1", key)[0] is mine+ assert image_map_router_module._cluster_cache_get("user2", key)[0] is theirs+ assert image_map_router_module._cluster_cache_get("user3", key) is None++ # A stale key for a user who has an entry is a miss, not another user's value.+ assert image_map_router_module._cluster_cache_get("user1", ("other", None, "current", 0.2, 10)) is None++ # One caller varying its own key churns only its own slot, however long it+ # goes on — this is the eviction a shared pool got wrong.+ for i in range(image_map_router_module._CLUSTER_CACHE_USERS * 3):+ image_map_router_module._cluster_cache_put("churn", ("scope", None, "current", 0.1 + i, 10), mine, 0.2)+ assert len(image_map_router_module._cluster_cache) == 3+ assert image_map_router_module._cluster_cache_get("user1", key)[0] is minedef test_a_spent_retry_stops_points_from_asking_again(diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex de19650279..2920dbf76b 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -45,6 +45,17 @@ def _wait_until(predicate: Callable[[], bool], timeout: float = 10.0) -> None:raise AssertionError("Condition not met within timeout")+def _wait_for_spent_retry(service: "ImageIndexService", user_id: str, scope: str) -> None:+ """Wait until the worker has actually charged a failed scope's retry.++ The budget is spent only once the failed result is durably cached, which is+ strictly after the fit runs and after the job leaves the request map — so+ waiting on the fit count or on an empty `_projection_requests` and then+ asserting the refusal races the worker, and loses on a slow runner.+ """+ _wait_until(lambda: service._failed_projection_scopes.get(user_id) == scope, timeout=15)++def _unit_vec() -> np.ndarray:"""A storable embedding: float32, finite, non-zero."""v = np.ones(DIM, dtype=np.float32)@@ -1107,6 +1118,162 @@ def test_a_permanently_failing_projection_is_retried_once_not_every_request(assert fits["n"] == 2, "a permanently failing scope must be retried once per process, not per request"+def test_a_cached_row_with_no_finite_points_is_a_failed_fit_not_a_result(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+ monkeypatch,+) -> None:+ """A row with point_count > 0 and every coordinate non-finite.++ /points drops non-finite rows before serving, so this row is empty to every+ client while looking populated to the service. Deciding "failed" on the+ cached count meant /points asked for a retry on this row's behalf, the+ service granted the request without ever entering the retry branch, the+ worker short-circuited and emitted projection_ready anyway, and the client —+ which refetches on that event — asked again. The budget could never be spent,+ so the refusal that is supposed to break the cycle never fired: a permanent+ request/emit loop at the worker's poll rate, and a permanent spinner.++ The router's fake service cannot show this: it decides the refusal itself,+ from the argument alone, with no view of the cached row.+ """+ from invokeai.app.services.image_index.projection import projection_params, scope_hash++ fits = {"n": 0}++ def broken_umap(embeddings, seed=42):+ fits["n"] += 1+ 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())++ names = index_records.list_accessible_embedded_images(None, MODEL_ID)+ current_hash = scope_hash(MODEL_ID, names)+ index_records.set_projection(+ "system",+ MODEL_ID,+ current_hash,+ projection_params(n_points=len(names)),+ names,+ np.full((len(names), 2), np.nan, dtype=np.float32),+ )++ # The first request on this row's behalf is granted and spends the budget.+ assert service.request_projection("system", failed_scope=current_hash) is True+ _wait_until(lambda: fits["n"] == 1, timeout=15)+ _wait_for_spent_retry(service, "system", current_hash)++ # And every one after it is refused, so /points settles into "empty".+ for _ in range(5):+ assert service.request_projection("system", failed_scope=current_hash) is False+ time.sleep(0.5)+ assert fits["n"] == 1, "a row with nothing servable must be retried once, not on every poll"+++def test_a_lost_projection_write_does_not_burn_the_retry(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+ monkeypatch,+) -> None:+ """The budget bounds failed fits, so only a failed fit that reached the cache may spend it.++ Spending it before the fit looked safe — nothing between the spend and the+ fit can return — but it ignored the write. A fit that SUCCEEDS and then loses+ its set_projection to a locked database re-queues, and the re-queued job finds+ the old empty row with the budget already gone: minutes of correct work+ discarded and the map blank for good, without a single failed fit anywhere.+ """+ from invokeai.app.services.image_index.projection import projection_params, scope_hash++ monkeypatch.setattr(image_index_default, "compute_umap", lambda matrix, seed=42: np.zeros((matrix.shape[0], 2)))+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ # 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)+ current_hash = scope_hash(MODEL_ID, names)+ index_records.set_projection(+ "system",+ MODEL_ID,+ current_hash,+ projection_params(n_points=0),+ [],+ np.empty((0, 2), dtype=np.float32),+ )++ writes = {"n": 0}+ real_set_projection = index_records.set_projection++ def failing_set_projection(*args, **kwargs):+ writes["n"] += 1+ if writes["n"] == 1:+ raise RuntimeError("database is locked")+ return real_set_projection(*args, **kwargs)++ monkeypatch.setattr(index_records, "set_projection", failing_set_projection)++ # The fit succeeds; its write is lost. The re-queued job must still be+ # allowed to run, which means the budget must not have moved.+ assert service.request_projection("system", failed_scope=current_hash) is True+ _wait_until(+ lambda: (r := index_records.get_projection("system", MODEL_ID)) is not None and r.point_count == 1,+ timeout=20,+ )+ assert writes["n"] == 2, "the lost write must be retried, not dropped"+++def test_an_explicit_refresh_restores_a_spent_retry(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+ monkeypatch,+) -> None:+ """Otherwise a spent budget is unrecoverable while the server runs.++ /refresh answered `enqueued: true` while the worker was guaranteed to+ short-circuit — the API reporting that it had accepted work it could not do,+ with no way back short of a restart.+ """+ from invokeai.app.services.image_index.projection import scope_hash++ fits = {"n": 0}++ def broken_umap(embeddings, seed=42):+ fits["n"] += 1+ 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: fits["n"] == 1, timeout=15)+ current_hash = scope_hash(MODEL_ID, index_records.list_accessible_embedded_images(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)+ assert service.request_projection("system", failed_scope=current_hash) is False, "the budget is spent"++ # A person pressing Refresh gets a real fit, not a short-circuit...+ assert service.request_projection("system", user_initiated=True) is True+ _wait_until(lambda: fits["n"] == 3, timeout=15)++ # ...while a poller still cannot, so the loop stays closed.+ _wait_for_spent_retry(service, "system", current_hash)+ assert service.request_projection("system", failed_scope=current_hash) is False++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