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.

fix(api): stop a failed projection from blanking the map for good

Lincoln Steinc959df6fd663
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index 74d2c704a8..0f378cbe61 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -12,6 +12,7 @@ from invokeai.app.services.image_index.image_index_common import ImageIndexStatu
from invokeai.app.services.image_index.projection import (
DEFAULT_CLUSTER_MIN_SAMPLES,
MAX_CLUSTERED_POINTS,
+ cluster_at_eps,
compute_clusters,
resolve_cluster_eps,
scope_hash,
@@ -141,11 +142,24 @@ async def get_image_map_points(
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 means "a recompute is pending"; when nothing could be enqueued
+ # (the indexer is not running) nothing is pending, and a client that
+ # polls on stale would wait forever.
+ return ImageMapPointsResponse(
+ points=[], state="computing" if enqueued else "empty", stale=enqueued, point_count=0
+ )
stale = record.scope_hash != scope_hash(model_id, current_names)
+ retrying = False
if 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)
# 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
@@ -158,21 +172,40 @@ async def get_image_map_points(
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]
- 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)
+ try:
+ if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
+ resolved_eps = resolve_cluster_eps(visible_coords, eps, min_samples)
+ # cluster_at_eps, not compute_clusters: the latter re-resolves
+ # what was just resolved, and the second pass re-applies the
+ # 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)
+ else:
+ resolved_eps = None
+ labels = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
+ except Exception:
+ # Clustering is a presentation detail; the coordinates are the
+ # 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.
+ 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)
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"
+ state: ImageMapState = "ready" if points else ("computing" if retrying else "empty")
return ImageMapPointsResponse(
points=points,
state=state,
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 031ef8b71b..c7a497beef 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -126,6 +126,9 @@ class ImageIndexService(ImageIndexServiceBase):
# 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] = {}
+ # user_id -> the scope hash whose failed fit has already been retried
+ # this process; see _retry_failed_projection.
+ self._failed_projection_scopes: dict[str, str] = {}
self._projection_lock = threading.Lock()
self._invoker: Optional["Invoker"] = None
@@ -274,6 +277,17 @@ class ImageIndexService(ImageIndexServiceBase):
self._status_dirty.set()
raise
if 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)
self._wait_for_idle_generation()
if self._stop_event.is_set():
break
@@ -319,6 +333,14 @@ class ImageIndexService(ImageIndexServiceBase):
continue
# No embedding work right now — projections run when the
# index is quiescent so they cover the freshest state.
+ if self._stop_event.is_set():
+ # Neither path that arrives here re-checks the flag: the
+ # quiescent fall-through never did, and the systemic-outage
+ # backoff wait returns instantly once stop is set. Starting
+ # a multi-minute fit now outlives stop()'s 10s join, so the
+ # abandoned thread writes the database and emits an event
+ # after the app believes the service is down.
+ break
projection_job = self._next_projection_job()
if projection_job is not None:
self._process_projection(*projection_job)
@@ -436,6 +458,15 @@ 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 = 0
except 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
@@ -447,10 +478,6 @@ class ImageIndexService(ImageIndexServiceBase):
return False
finally:
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.
- self._systemic_failures = 0
return len(loaded_names) == len(image_names)
finally:
# Always release the batch from the dedup set — a name stuck in
@@ -522,6 +549,32 @@ class ImageIndexService(ImageIndexServiceBase):
# --- Projections ---
+ def _retry_failed_projection(self, user_id: str, current_hash: str, point_count: int, has_images: bool) -> 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
+ hash. Both halves are deliberate — serving "empty" is honest, and the
+ stamp stops a polling client from re-enqueueing a doomed recompute —
+ but together with the hash short-circuit they make the failure
+ terminal: /points answers `state: "empty", stale: false` (so the client
+ stops asking) and every later job returns early (so the fit is never
+ re-entered). The map stays blank until the accessible image set
+ changes, 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.
+ """
+ if point_count > 0 or not has_images:
+ return False
+ with self._projection_lock:
+ if self._failed_projection_scopes.get(user_id) == current_hash:
+ return False
+ self._failed_projection_scopes[user_id] = current_hash
+ return True
+
def _next_projection_job(self) -> Optional[tuple[str, bool]]:
with self._projection_lock:
if not self._projection_requests:
@@ -538,7 +591,8 @@ class ImageIndexService(ImageIndexServiceBase):
scope_user = None if all_images else user_id
try:
names = records.list_accessible_embedded_images(scope_user, self._model_id)
- found_names, matrix = records.get_embeddings(names, self._model_id)
+ current_hash = scope_hash(self._model_id, names)
+ cached = records.get_projection(user_id, 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
@@ -546,13 +600,15 @@ class ImageIndexService(ImageIndexServiceBase):
# 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")
+ logger.exception(f"Image map: could not read the projection scope 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:
+ if (
+ cached is not None
+ and cached.scope_hash == current_hash
+ and not self._retry_failed_projection(user_id, current_hash, cached.point_count, bool(names))
+ ):
# 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
@@ -562,6 +618,22 @@ class ImageIndexService(ImageIndexServiceBase):
)
return
+ try:
+ # Read after the short-circuit, not before: this materializes every
+ # accessible embedding (hundreds of MB on a large gallery), which is
+ # pure waste on the no-op path that /points and /refresh drive.
+ found_names, matrix = records.get_embeddings(names, self._model_id)
+ except Exception:
+ logger.exception(f"Image map: could not read embeddings for user '{user_id}'; re-queueing")
+ self._requeue_projection(user_id, all_images)
+ return
+
+ if self._stop_event.is_set():
+ # The fit is unbounded and stop() waits only 10s, so starting one
+ # now means writing the database after the app has torn down.
+ self._requeue_projection(user_id, all_images)
+ return
+
try:
coords = compute_umap(matrix)
if coords.shape[0] != len(found_names):
@@ -576,8 +648,9 @@ class ImageIndexService(ImageIndexServiceBase):
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.
+ # doomed recompute on every poll. It does NOT make the failure
+ # terminal: _retry_failed_projection 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)
@@ -599,7 +672,20 @@ 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
- self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_names))
+ 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:
+ self._failed_projection_scopes.pop(user_id, None)
+ try:
+ self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_names))
+ except Exception:
+ # The row is cached, so a polling client recovers on its own; only
+ # an event-driven client would hang. Log rather than unwind into
+ # the generic worker handler, which would re-sweep the backfill for
+ # what is purely a delivery failure.
+ logger.exception(f"Image map: could not emit projection_ready for user '{user_id}'")
def _requeue_projection(self, user_id: str, all_images: bool) -> None:
"""Put a popped job back, without clobbering a newer request for that user."""
diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.py
index 13312578ab..cba8c92de2 100644
--- a/invokeai/app/services/image_index/projection.py
+++ b/invokeai/app/services/image_index/projection.py
@@ -197,7 +197,26 @@ def compute_clusters(
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)
+ return cluster_at_eps(coords, resolve_cluster_eps(coords, eps, min_samples), min_samples)
+
+
+def cluster_at_eps(
+ coords: np.ndarray,
+ eps: float,
+ min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES,
+) -> np.ndarray:
+ """DBSCAN at an eps `resolve_cluster_eps` has ALREADY produced.
+
+ Split out so a caller that needs to report the effective eps can resolve it
+ once and cluster at exactly that value. Passing a resolved eps back into
+ compute_clusters instead would re-resolve it — and since resolution floors
+ at 0.01 before applying the neighbour-pair budget, a budget-shrunk eps comes
+ back out different, so the reported value would not be the one used.
+ """
+ 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)
from sklearn.cluster import DBSCAN
from sklearn.neighbors import KDTree
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 f13bdfcbf9..1b6cd3d1a7 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -608,6 +608,91 @@ def test_generation_wait_does_not_block_shutdown(
assert service._worker is not None and not service._worker.is_alive()
+def test_projection_does_not_wait_for_an_in_progress_generation(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ accelerator_host: None,
+) -> None:
+ """A projection reads stored embeddings only — no encoder, no GPU — so it has no
+ reason to queue behind a generation the way an embed does.
+
+ The worker parks in _wait_for_idle_generation as soon as ONE image is pending, and
+ that wait is unbounded, so ordering the projection after it made /points report
+ "computing" for the entire length of a run. Every other projection test builds its
+ invoker with device='cpu'/session_queue=None, where the wait returns immediately —
+ which is why this was invisible to the suite.
+ """
+ session_queue = SimpleNamespace(get_queue_status=lambda queue_id: SimpleNamespace(in_progress=1))
+
+ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)
+ try:
+ # One image already embedded (so the projection has input) and one that cannot
+ # be embedded while the generation holds the GPU (so the worker parks).
+ _save_image(image_records, "done.png")
+ index_records.upsert_embedding("done.png", MODEL_ID, _unit_vec())
+ _save_image(image_records, "waiting.png")
+
+ service.start(_make_invoker(images_service, index_records, device=None, session_queue=session_queue))
+ assert service.request_projection("system") is True
+
+ # The generation never ends; the projection must land anyway.
+ _wait_until(lambda: index_records.get_projection("system", MODEL_ID) is not None, timeout=20.0)
+ record = index_records.get_projection("system", MODEL_ID)
+ assert record is not None
+ assert record.image_names == ["done.png"]
+ # And the embed really is still parked behind the generation.
+ assert index_records.get_embeddings(["waiting.png"], MODEL_ID)[0] == []
+ finally:
+ service.stop()
+
+
+def test_a_partially_stored_batch_still_counts_its_systemic_failure(
+ 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.
+ """
+ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)
+ try:
+ for name in ("stored.png", "locked.png"):
+ _save_image(image_records, name)
+
+ real_upsert = index_records.upsert_embedding
+
+ def flaky_upsert(image_name, model_id, embedding):
+ if image_name == "stored.png":
+ return real_upsert(image_name, model_id, embedding)
+ 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_ID
+ service._encode_fn = _fake_encode
+
+ 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 index_records.get_embeddings(["stored.png"], MODEL_ID)[0] == ["stored.png"]
+ assert service._failed == set()
+ assert service._attempts == {}
+ finally:
+ service.stop()
+
+
def test_unparseable_device_is_ignored_rather_than_wedging_the_worker(
image_records: SqliteImageRecordStorage,
images_service: ImageService,
@@ -975,6 +1060,52 @@ def test_projection_failure_caches_empty_result_instead_of_looping(
accessible = index_records.list_accessible_embedded_images(None, MODEL_ID)
assert record.scope_hash == scope_hash(MODEL_ID, accessible)
+ # ...but "not stale" must not mean "never again". Asserting only the state
+ # above is what let the failure become terminal: the stamped hash plus the
+ # unchanged-scope short-circuit meant no later request could ever displace
+ # the empty row, so one transient fit failure blanked the map until the
+ # gallery changed — across restarts, since the row is in SQLite.
+ monkeypatch.setattr(image_index_default, "compute_umap", lambda matrix, seed=42: np.zeros((matrix.shape[0], 2)))
+ service.request_projection("system")
+
+ _wait_until(lambda: (r := index_records.get_projection("system", MODEL_ID)) is not None and r.point_count == 1)
+
+
+def test_a_permanently_failing_projection_is_retried_once_not_every_request(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ monkeypatch,
+) -> None:
+ """The other half of the bargain: recovering from a transient failure must not
+ turn a permanent one into a fit per request, which is what the empty-cache
+ stamp was protecting against in the first place."""
+ 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: index_records.get_projection("system", MODEL_ID) is not None, timeout=15)
+ assert fits["n"] == 1
+
+ # The retry is spent on the second request; every request after it must
+ # short-circuit rather than re-enter the doomed fit.
+ for _ in range(4):
+ service.request_projection("system")
+ _wait_until(lambda: not service._projection_requests, timeout=15)
+
+ _wait_until(lambda: fits["n"] == 2, timeout=15)
+ time.sleep(0.5)
+ assert fits["n"] == 2, "a permanently failing scope must be retried once per process, not per request"
+
def test_projection_request_dedup_is_last_writer_wins(service: ImageIndexService) -> None:
# Not started: requests are refused outright.
diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.py
index 415790504b..1e41e0bbff 100644
--- a/tests/app/services/image_index/test_projection.py
+++ b/tests/app/services/image_index/test_projection.py
@@ -169,3 +169,53 @@ def test_projection_params_is_stable_json() -> None:
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)
+
+
+def test_cluster_at_eps_clusters_at_exactly_the_eps_it_is_given(monkeypatch) -> None:
+ """The router resolves eps once so it can report the effective value, then clusters.
+
+ Routing that value back through compute_clusters would resolve it a SECOND time —
+ re-running the k-distance fit and the whole KD-tree budget shrink (measured at ~65%
+ of a 50k-point request), and re-applying the 0.01 floor, which re-inflates a
+ budget-shrunk eps onto a different shrink grid so the number reported to the client
+ is not the number DBSCAN used.
+ """
+ import invokeai.app.services.image_index.projection as projection
+
+ calls = {"resolve": 0}
+ real_resolve = projection.resolve_cluster_eps
+
+ def counting_resolve(*args, **kwargs):
+ calls["resolve"] += 1
+ return real_resolve(*args, **kwargs)
+
+ monkeypatch.setattr(projection, "resolve_cluster_eps", counting_resolve)
+
+ captured: dict[str, float] = {}
+ import sklearn.cluster
+
+ real_dbscan = sklearn.cluster.DBSCAN
+
+ def recording_dbscan(*args, **kwargs):
+ captured["eps"] = kwargs["eps"]
+ return real_dbscan(*args, **kwargs)
+
+ monkeypatch.setattr(sklearn.cluster, "DBSCAN", recording_dbscan)
+
+ coords = _blob_coords()
+ resolved = real_resolve(coords, None, 2)
+
+ projection.cluster_at_eps(coords, resolved, 2)
+ assert calls["resolve"] == 0, "clustering at an already-resolved eps must not resolve again"
+ assert captured["eps"] == resolved, "DBSCAN must run at exactly the eps the caller reports"
+
+ # compute_clusters keeps resolving for callers that pass a raw/None eps.
+ projection.compute_clusters(coords, eps=None, min_samples=2)
+ assert calls["resolve"] == 1
+
+
+def _blob_coords() -> np.ndarray:
+ rng = np.random.default_rng(3)
+ return np.concatenate([rng.standard_normal((20, 2)) * 0.1 + offset for offset in ([0, 0], [5, 5])]).astype(
+ np.float32
+ )