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): stop the failed-projection retry from becoming a request loop
Lincoln Steinf59efa835589
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 9933ec79be..3219ee088f 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -211,16 +211,32 @@ 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 record.point_count == 0 and current_names:- # An empty projection over a gallery that HAS embedded images is a- # failed fit, not a result — and it is stamped with the current scope,- # so staleness will never ask for it again. Request the recompute; the- # service grants one retry per scope per process, so a transient- # failure heals here while a permanent one cannot spin.- retrying = 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@@ -229,17 +245,8 @@ async def get_image_map_points(# 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)- )- # Drop non-finite rows as well. A NaN cannot be serialized as valid- # JSON, so one corrupt coordinate would fail the whole response — and- # rows written before the projection writer grew its isfinite guard are- # still out there in existing databases.- 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]+ 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),diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex 606e70c675..5a03247c64 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -1,4 +1,5 @@from abc import ABC, abstractmethod+from typing import Optionalfrom invokeai.app.services.image_index.image_index_common import ImageIndexStatus@@ -24,7 +25,7 @@ class ImageIndexServiceBase(ABC):pass@abstractmethod- def request_projection(self, user_id: str, all_images: bool = False) -> bool:+ def request_projection(self, user_id: str, all_images: bool = False, failed_scope: Optional[str] = None) -> bool:"""Ask the worker to (re)compute a user's image map projection.Requests are deduplicated per user; the projection runs after any@@ -35,6 +36,10 @@ class ImageIndexServiceBase(ABC):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.+ failed_scope: The scope hash of a cached projection the caller+ believes to be a failed fit. The request is refused once that+ scope's single retry has been used, so a caller that asks on+ every poll cannot drive an endless request/event cycle.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 c7a497beef..453a935b21 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -127,7 +127,7 @@ class ImageIndexService(ImageIndexServiceBase):# lands here again and is honored on the next pass.self._projection_requests: dict[str, bool] = {}# user_id -> the scope hash whose failed fit has already been retried- # this process; see _retry_failed_projection.+ # this process; see _failed_scope_retry_available.self._failed_projection_scopes: dict[str, str] = {}self._projection_lock = threading.Lock()@@ -149,9 +149,17 @@ 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:+ def request_projection(self, user_id: str, all_images: bool = False, failed_scope: Optional[str] = None) -> bool:if self._model_id is None or self._worker is None or not self._worker.is_alive():return False+ if failed_scope is not None and not self._failed_scope_retry_available(user_id, failed_scope):+ # The caller is asking on behalf of a cached failure whose one retry+ # is already spent. Refusing here is what stops the loop: the worker+ # would otherwise pop the job, short-circuit, and still emit+ # projection_ready — which the client listens for and answers with+ # another /points, which asks again, at the worker's poll rate for+ # the life of the process.+ return Falsewith self._projection_lock:# Last writer wins: the scope reflects the requester's most recent# admin status, so a promotion/demotion between requests cannot@@ -170,6 +178,14 @@ class ImageIndexService(ImageIndexServiceBase):invoker.services.logger.warning("Image index service started twice; ignoring the second start")return+ # Projection state is per-run: a spent retry marker left over from the+ # previous run would deny a scope the retry this run's docstring+ # promises it, and a job requeued at the last shutdown would resurrect+ # here carrying an admin scope the user may no longer have.+ with self._projection_lock:+ self._failed_projection_scopes.clear()+ self._projection_requests.clear()+device_override = config.image_index_deviceif device_override and not _is_cpu_override(device_override):# Ignored, as documented — but silently ignoring a near-miss like `CPU` leaves the@@ -277,17 +293,23 @@ class ImageIndexService(ImageIndexServiceBase):self._status_dirty.set()raiseif batch is not None:- # Before the generation wait, not after: a projection reads- # only already-stored embeddings, so unlike an embed it- # needs neither the encoder nor the GPU and has no reason to- # queue behind a generation. Waiting first is what made- # /points report "computing" for the whole length of a- # multi-image run — the same starvation the systemic-outage- # fall-through below was added to prevent, reached by the- # far more common trigger.- projection_job = self._next_projection_job()- if projection_job is not None:- self._process_projection(*projection_job)+ 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)self._wait_for_idle_generation()if self._stop_event.is_set():break@@ -458,15 +480,6 @@ class ImageIndexService(ImageIndexServiceBase):# An image that recovers (e.g. re-embedded after an# update) must stop counting against the failed total.self._failed.discard(name)- if stored:- # Anything stored proves the encoder and the database are both working, so- # the outage (if there was one) is over and the backoff resets. Only on the- # success path: in a `finally` this ran AFTER the handler below had counted- # the failure, so a batch that stored its first image and then hit the lock- # erased the very outage it had just recorded — which flattened the backoff- # to 1 Hz and, since the fall-through below keys on the counter, also skipped- # the projection work for the duration of the contention.- self._systemic_failures = 0except Exception:# A raise here (e.g. "database is locked") is a property of the database, not of# any image, so it is systemic: the unstored names stay pending and are retried@@ -478,6 +491,17 @@ class ImageIndexService(ImageIndexServiceBase):return Falsefinally:self._record_owner_pokes(stored)+ if stored:+ # Anything stored proves the encoder and the database are both working, so+ # the outage (if there was one) is over and the backoff resets. In the+ # `finally` deliberately, i.e. reached even when the handler above has just+ # counted a failure: a batch that stores ANY image is making progress, so+ # the backlog drains and quiescence arrives on its own. Moving this to the+ # success path instead left the counter with no reset while every batch+ # partially failed, which escalated the wait to its 60s ceiling — a far+ # worse outcome under mild write contention than the flat 1Hz retry it was+ # meant to fix.+ self._systemic_failures = 0return len(loaded_names) == len(image_names)finally:# Always release the batch from the dedup set — a name stuck in@@ -549,7 +573,7 @@ class ImageIndexService(ImageIndexServiceBase):# --- Projections ---- def _retry_failed_projection(self, user_id: str, current_hash: str, point_count: int, has_images: bool) -> bool:+ def _failed_scope_retry_available(self, user_id: str, current_hash: str) -> bool:"""Whether a cached projection that is empty over a non-empty gallery gets another fit.A fit that raised caches an EMPTY result stamped with the CURRENT scope@@ -566,14 +590,20 @@ class ImageIndexService(ImageIndexServiceBase):generation holds RAM, a JIT hiccup, the non-finite guard — heals on thenext request, while a permanent one costs one wasted fit per restartinstead 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."""- if point_count > 0 or not has_images:- return Falsewith self._projection_lock:- if self._failed_projection_scopes.get(user_id) == current_hash:- return False+ 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- return Truedef _next_projection_job(self) -> Optional[tuple[str, bool]]:with self._projection_lock:@@ -604,11 +634,14 @@ class ImageIndexService(ImageIndexServiceBase):self._requeue_projection(user_id, all_images)return- if (+ retrying_failed_scope = (cached is not Noneand cached.scope_hash == current_hash- and not self._retry_failed_projection(user_id, current_hash, cached.point_count, bool(names))- ):+ and cached.point_count == 0+ and bool(names)+ and self._failed_scope_retry_available(user_id, current_hash)+ )+ if cached is not None and cached.scope_hash == current_hash and not retrying_failed_scope:# Nothing the projection depends on has changed, and the fit is# seeded, so recomputing would burn minutes of single-threaded CPU# to arrive at identical coordinates. Still emit, so a client that@@ -634,6 +667,12 @@ 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):@@ -649,7 +688,7 @@ class ImageIndexService(ImageIndexServiceBase):# Cache an empty projection under the CURRENT scope hash. Serving# "empty" is honest, and it stops the client from re-enqueueing a# doomed recompute on every poll. It does NOT make the failure- # terminal: _retry_failed_projection grants this scope one more fit+ # terminal: _failed_scope_retry_available grants this scope one more fit# per process, and the next gallery change flips the hash anyway.found_names = []coords = np.empty((0, 2), dtype=EMBEDDING_DTYPE)@@ -692,6 +731,19 @@ 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.diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 612d7f2b81..048f5009a4 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -39,6 +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()@propertydef model_id(self) -> str | None:@@ -49,9 +50,14 @@ class FakeImageIndexService(ImageIndexServiceBase):return Nonereturn ImageIndexStatus(total=5, embedded=3)- def request_projection(self, user_id: str, all_images: bool = False) -> bool:+ def request_projection(self, user_id: str, all_images: bool = False, failed_scope: str | None = None) -> 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:+ return False+ self.spent_failed_scopes.add(failed_scope)self.projection_requests.append((user_id, all_images))return True@@ -571,3 +577,48 @@ def test_cluster_cache_never_serves_one_users_labels_to_another(assert [p["image_name"] for p in first["points"]] == ["mine.png"]assert [p["image_name"] for p in second["points"]] == ["theirs.png"]+++def test_a_spent_retry_stops_points_from_asking_again(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ """The client listens for projection_ready and refetches on it.++ So a /points that requests a recompute on every poll closes a cycle with the+ worker's unconditional emit: request -> short-circuit -> emit -> refetch ->+ request, at the worker's poll rate for the life of the process. Passing the+ failed scope lets the service refuse once the retry is spent, which breaks it.+ """+ _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))++ first = client.get("/api/v1/image_map/points").json()+ assert first["state"] == "computing", "the one retry is requested"+ assert len(image_index_service.projection_requests) == 1++ for _ in range(5):+ later = client.get("/api/v1/image_map/points").json()+ assert later["state"] == "empty", "a spent retry must settle into an honest empty"+ assert len(image_index_service.projection_requests) == 1, "no further recomputes may be requested"+++def test_an_all_non_finite_projection_is_not_permanently_blank(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ """point_count > 0 while every coordinate is NaN — what a database written before+ the writer's isfinite guard can still hold.++ Deciding the retry on the cached count rather than on what is actually servable+ left this row serving "empty, not stale" with nothing ever asking for a recompute.+ """+ names = ["a.png", "b.png"]+ for name in names:+ _seed_embedded_image(mock_invoker, name)+ _seed_projection(mock_invoker, SYSTEM_USER_ID, names, np.full((2, 2), np.nan, dtype=np.float32))++ body = client.get("/api/v1/image_map/points").json()++ assert body["points"] == []+ assert body["state"] == "computing", "a row with nothing servable must ask for a recompute"+ assert [user for user, _ in image_index_service.projection_requests] == [SYSTEM_USER_ID]diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 1b6cd3d1a7..de19650279 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -647,20 +647,20 @@ def test_projection_does_not_wait_for_an_in_progress_generation(service.stop()-def test_a_partially_stored_batch_still_counts_its_systemic_failure(+def test_a_partially_stored_batch_does_not_escalate_the_backoff(image_records: SqliteImageRecordStorage,images_service: ImageService,index_records: ImageIndexRecordsSqlite,) -> None:- """`if stored: self._systemic_failures = 0` ran in a `finally`, i.e. AFTER the- handler that had just counted the failure.-- So a batch whose first write succeeded and whose second hit "database is locked" —- the exact contention this code designs for — erased the outage it had just recorded.- That flattened the escalating backoff to a 1 Hz retry loop and, because the- projection fall-through keys on the same counter, skipped projections for the whole- contention window. Both existing systemic-failure tests fail EVERY write, so- `stored` is always empty and this branch was never reached.+ """A batch that stores ANYTHING resets the systemic-failure counter, even though the+ batch also failed.++ The counter exists to stop a hot retry loop when NO progress is possible. A batch that+ stored an image is making progress: the backlog drains and quiescence arrives on its+ own, so escalating is wrong. Counting these instead — reachable by moving the reset off+ the `finally` — leaves no reset path at all while every batch partially fails, which+ walks the wait up to its 60s ceiling while the index is still working. That is worse+ under mild write contention than the flat 1Hz retry it would be correcting."""service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)try:@@ -675,17 +675,17 @@ def test_a_partially_stored_batch_still_counts_its_systemic_failure(raise RuntimeError("database is locked")index_records.upsert_embedding = flaky_upsert # type: ignore[method-assign]- # Drive one batch directly, with no worker running: through the worker the- # counter also climbs on later all-failing batches, so the assertion below- # would hold with or without the fix.service._invoker = _make_invoker(images_service, index_records)service._model_id = MODEL_IDservice._encode_fn = _fake_encode- assert service._process_batch(["stored.png", "locked.png"]) is False+ # Several rounds: the escalation this guards against is cumulative.+ for _ in range(8):+ assert service._process_batch(["stored.png", "locked.png"]) is False- assert service._systemic_failures == 1, "a partial store must not erase the outage it just recorded"- # The half that stored is still stored, and no image was charged an attempt.+ assert service._systemic_failures == 0, "progress must clear the outage counter"+ assert service._backoff_seconds() == _POLL_SECONDS, "a draining index must not back off"+ # The half that stored is stored, and no image was charged an attempt.assert index_records.get_embeddings(["stored.png"], MODEL_ID)[0] == ["stored.png"]assert service._failed == set()assert service._attempts == {}