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): let projections run during an embedding outage; bound the DBSCAN eps budget
Lincoln Stein1c41c26a7362
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 9129f4a351..031ef8b71b 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -279,20 +279,33 @@ class ImageIndexService(ImageIndexServiceBase):breakok = 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+ if ok:+ continue+ # 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 not self._systemic_failures:+ # Per-image failures retire after _MAX_ATTEMPTS, so the+ # backlog drains and quiescence arrives on its own.+ continue+ # A systemic failure charges no image, by design — which+ # means this same batch reappears on every pass and+ # quiescence never comes. Fall through to the projection+ # work below rather than skipping it for the duration of+ # the outage: a projection reads only already-stored+ # embeddings, so it needs no encoder and is still correct+ # while embedding is stalled. Without this the image map+ # reports "computing" forever over a gallery that is in+ # fact embedded.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@@ -523,12 +536,42 @@ class ImageIndexService(ImageIndexServiceBase):records = self._invoker.services.image_index_recordsscope_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:+ names = records.list_accessible_embedded_images(scope_user, self._model_id)+ found_names, matrix = records.get_embeddings(names, self._model_id)+ except Exception:+ # The DB reads are as failure-prone as the fit ("database is+ # locked" is a designed-for condition here), and the job was+ # already popped from the dedup map. Re-queue it rather than let+ # the generic worker handler swallow it: /refresh has already+ # answered `enqueued: true`, and a client waiting on+ # image_map_projection_ready would otherwise wait forever.+ logger.exception(f"Image map: could not read embeddings for user '{user_id}'; re-queueing")+ self._requeue_projection(user_id, all_images)+ return++ current_hash = scope_hash(self._model_id, names)+ cached = records.get_projection(user_id, self._model_id)+ if cached is not None and cached.scope_hash == current_hash:+ # 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+ # asked for a refresh hears that its request was honoured.+ self._invoker.services.events.emit_image_map_projection_ready(+ user_id=user_id, point_count=cached.point_count+ )+ return+try:coords = compute_umap(matrix)if coords.shape[0] != len(found_names):raise RuntimeError(f"projection produced {coords.shape[0]} points for {len(found_names)} images")+ if not np.isfinite(coords).all():+ # A NaN reaching the cache makes /points raise inside sklearn+ # on every request, and the cache is only replaced when the+ # scope hash changes — so it would 500 that user indefinitely.+ # Treat it as a failed fit and take the empty-cache path.+ raise RuntimeError("projection produced non-finite coordinates")except Exception:logger.exception(f"Image map: UMAP projection failed for user '{user_id}' ({len(found_names)} points)")# Cache an empty projection under the CURRENT scope hash. Serving@@ -541,16 +584,28 @@ class ImageIndexService(ImageIndexServiceBase):# 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,- )+ try:+ records.set_projection(+ user_id,+ self._model_id,+ current_hash,+ projection_params(n_points=len(found_names)),+ found_names,+ coords,+ )+ except Exception:+ # Same reasoning as the read above: the fit is done but unsaved, so+ # re-queue rather than drop it and leave /refresh's promise unmet.+ logger.exception(f"Image map: could not cache the projection for user '{user_id}'; re-queueing")+ self._requeue_projection(user_id, all_images)+ returnself._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_names))+ def _requeue_projection(self, user_id: str, all_images: bool) -> None:+ """Put a popped job back, without clobbering a newer request for that user."""+ with self._projection_lock:+ self._projection_requests.setdefault(user_id, all_images)+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.pyindex cf5674be5e..13312578ab 100644--- a/invokeai/app/services/image_index/projection.py+++ b/invokeai/app/services/image_index/projection.py@@ -119,6 +119,12 @@ def adaptive_cluster_eps(coords: np.ndarray, min_samples: int = DEFAULT_CLUSTER_# default could produce, and far below OOM territory.MAX_NEIGHBOR_PAIRS = 50_000_000+# Hard lower bound for the budget shrink. A fully coincident map can never fit+# the pair budget at any positive eps, so the shrink needs a floor to+# terminate; compute_clusters skips clustering when the budget is still+# unmet here rather than letting DBSCAN allocate.+MIN_BUDGETED_EPS = 1e-6+def _shrink_eps_to_pair_budget(coords: np.ndarray, eps: float) -> float:"""Shrink eps until DBSCAN's neighbor-pair count fits MAX_NEIGHBOR_PAIRS.@@ -133,10 +139,13 @@ def _shrink_eps_to_pair_budget(coords: np.ndarray, eps: float) -> float:from sklearn.neighbors import KDTreetree = KDTree(coords)- for _ in range(12):+ # Iterate until the budget is met rather than a fixed count: 12 rounds of+ # 0.7 only covers a 71x reduction, and a tight blob can need far more.+ # Bounded below by MIN_BUDGETED_EPS so a fully coincident map terminates.+ while eps > MIN_BUDGETED_EPS:pairs = int(tree.query_radius(coords, r=eps, count_only=True).sum())if pairs <= MAX_NEIGHBOR_PAIRS:- break+ return epseps *= 0.7return eps@@ -161,9 +170,13 @@ def resolve_cluster_eps(span = float(np.ptp(coords, axis=0).max()) if coords.shape[0] > 1 else 0.0if 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)+ # Floor at the API's lower bound (ge=0.01) for pass-back validity, but do+ # it BEFORE the budget shrink, never after: applied afterwards it silently+ # re-inflated eps past the neighbor-pair budget the shrink had just+ # computed, which is how a near-coincident map reached 400M pairs against+ # a 50M budget (~4GB). The budget bounds memory and therefore wins; an eps+ # below the API's floor is a cosmetic pass-back wart, an OOM is not.+ return _shrink_eps_to_pair_budget(coords, max(eps, 0.01))def compute_clusters(@@ -187,6 +200,16 @@ def compute_clusters(eps = resolve_cluster_eps(coords, eps, min_samples)from sklearn.cluster import DBSCAN+ from sklearn.neighbors import KDTree++ if coords.shape[0] > 1:+ # The shrink bottoms out at MIN_BUDGETED_EPS, which a fully coincident+ # map cannot satisfy at any positive radius. Skip clustering rather+ # than hand DBSCAN a neighborhood it would materialize into GBs — same+ # response shape as the MAX_CLUSTERED_POINTS skip above.+ pairs = int(KDTree(coords).query_radius(coords, r=eps, count_only=True).sum())+ if pairs > MAX_NEIGHBOR_PAIRS:+ return np.full((coords.shape[0],), -1, dtype=np.int64)return DBSCAN(eps=eps, min_samples=min_samples).fit(coords).labels_diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 9cb7bc8ff8..859de33d51 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1,9 +1,11 @@"""Tests for the image index worker service, using an injected fake encoder (no models/GPU)."""+import inspectimport threadingimport timefrom types import SimpleNamespacefrom typing import Callable+from unittest.mock import patchimport numpy as npimport pytest@@ -12,6 +14,7 @@ from PIL import Imagefrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.events.events_common import ImageIndexStatusEvent, ImageIndexUpdatedEvent+from invokeai.app.services.image_index import image_index_defaultfrom invokeai.app.services.image_index.image_index_default import (_MAX_ATTEMPTS,_MAX_BACKOFF_SECONDS,@@ -951,7 +954,6 @@ def test_projection_failure_caches_empty_result_instead_of_looping(service: ImageIndexService,monkeypatch,) -> None:- from invokeai.app.services.image_index import image_index_defaultfrom invokeai.app.services.image_index.projection import scope_hashdef broken_umap(embeddings, seed=42):@@ -986,3 +988,161 @@ def test_projection_request_dedup_is_last_writer_wins(service: ImageIndexServiceassert service.request_projection("system", all_images=True) is Trueassert service.request_projection("system", all_images=False) is Trueassert service._projection_requests == {"system": False}+++def test_systemic_embedding_outage_does_not_starve_projections(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The emergent interaction between "never retire on a systemic failure" and+ "projections only at quiescence".++ A systemic failure charges no image, by design, so the same batch is returned on every+ pass and quiescence never arrives. If projections only ran in the quiescent branch, an+ outage would make the image map report "computing" forever over images that ARE embedded —+ and the projection needs no encoder, so there is no reason for it to wait.+ """+ embedded_ok = _unit_vec()++ def broken_encode(images: list[Image.Image]) -> np.ndarray:+ raise RuntimeError("model is gone")++ service = ImageIndexService(encode_fn=broken_encode, model_id=MODEL_ID)+ try:+ # One image already embedded (the projection has something to work with) and one that+ # can never embed while the encoder is down.+ _save_image(image_records, "done.png")+ _save_image(image_records, "stuck.png")+ index_records.upsert_embedding("done.png", MODEL_ID, embedded_ok)++ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: service._systemic_failures >= 1, timeout=20.0)++ assert service.request_projection("system") is True++ # The projection must land despite embedding being permanently stalled.+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=30.0)+ record = index_records.get_projection("system", MODEL_ID)+ assert record is not None+ assert record.image_names == ["done.png"]+ # And the outage is still an outage: no image was retired to make this happen.+ assert service._failed == set()+ assert service._systemic_failures >= 1+ finally:+ service.stop()+++def test_projection_request_is_requeued_when_the_database_read_fails(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The job is popped from the dedup map before the work runs.++ A raise outside the fit's own try unwinds to the generic worker handler, which knows+ nothing about projections — so the request would be dropped after /refresh had already+ answered `enqueued: true`, and an event-driven client would wait forever.+ """+ calls = {"n": 0}+ real_list = index_records.list_accessible_embedded_images++ def flaky_list(user_id, model_id):+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("database is locked")+ return real_list(user_id, model_id)++ index_records.list_accessible_embedded_images = flaky_list # type: ignore[method-assign]++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ for i in range(3):+ _save_image(image_records, f"img-{i}.png")+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ service.request_projection("system")++ # Retried rather than dropped: the projection still lands.+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=30.0)+ assert calls["n"] >= 2+ finally:+ service.stop()+++def test_unchanged_scope_does_not_recompute_the_projection(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """Repeat requests over an unchanged gallery must not re-run the fit.++ The fit is seeded, so recomputing burns minutes of single-threaded worker CPU to produce+ identical coordinates — and a client that refetches on `projection_ready` would drive it+ in a loop.+ """+ fits = {"n": 0}+ real_umap = image_index_default.compute_umap++ def counting_umap(matrix: np.ndarray) -> np.ndarray:+ fits["n"] += 1+ return real_umap(matrix)++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ for i in range(3):+ _save_image(image_records, f"img-{i}.png")+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ with patch.object(image_index_default, "compute_umap", counting_umap):+ service.request_projection("system")+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=30.0)+ assert fits["n"] == 1++ for _ in range(3):+ service.request_projection("system")+ _wait_until(lambda: not service._projection_requests, timeout=30.0)++ assert fits["n"] == 1, "unchanged scope must reuse the cached projection"++ # A real scope change still recomputes. The callback is what enqueues work — writing+ # the row alone leaves the backfill unarmed, so the worker would never see it.+ _save_image(image_records, "new.png")+ images_service._on_changed(_dto_for(image_records, "new.png"))+ _wait_until(lambda: index_records.get_embeddings(["new.png"], MODEL_ID)[0] == ["new.png"], timeout=30.0)+ with patch.object(image_index_default, "compute_umap", counting_umap):+ service.request_projection("system")+ _wait_until(lambda: fits["n"] == 2, timeout=30.0)+ finally:+ service.stop()+++def test_failed_batch_uses_the_escalating_backoff(service: ImageIndexService) -> None:+ """Pin the CALL SITE, not just the helper.++ `_backoff_seconds()` is unit-tested on its own, but reverting the worker's failed-batch+ wait to a fixed `_POLL_SECONDS` — the single most plausible way to lose this in a+ hand-resolved rebase conflict — was previously invisible to the suite.+ """+ source = inspect.getsource(ImageIndexService._worker_loop)+ assert "self._stop_event.wait(self._backoff_seconds())" in source+ assert "self._stop_event.wait(_POLL_SECONDS)" not in source.split("except Exception")[0]+++def test_projection_job_is_popped_before_running(service: ImageIndexService) -> None:+ """A job left in the dedup map turns the worker into an infinite recompute loop.++ Nothing else stops it: with the scope-hash short-circuit the fit is skipped, but the+ `projection_ready` emit would still fire on every pass.+ """+ service._model_id = MODEL_ID+ with service._projection_lock:+ service._projection_requests["u1"] = False++ job = service._next_projection_job()++ assert job == ("u1", False)+ assert service._projection_requests == {}, "the job must be removed when it is taken"+ assert service._next_projection_job() is None