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(image-index): retry a memoized vocabulary-build failure after a window

Lincoln Steina36f00bb37c3
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 4715f52e11..969a3468b0 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -58,6 +58,12 @@ _MAX_ATTEMPTS = 3
# so an outage that lasts hours does not retry at 1 Hz while still recovering promptly.
_MAX_BACKOFF_SECONDS = 60.0
+# A memoized vocabulary-build failure is retried at most this often. Transient causes (an OOM
+# while the GPU was busy generating, a text-tower load that lost a race) recover on the next
+# labels request after the window; a permanently broken install still answers from memory for
+# everything in between, at one rebuild attempt per window rather than one per points refresh.
+_VOCAB_FAILURE_RETRY_SECONDS = 600.0
+
def _normalize_query_vector(vector: np.ndarray) -> np.ndarray:
"""L2-normalize one query embedding, refusing anything that would poison a search.
@@ -290,6 +296,13 @@ class ImageIndexService(ImageIndexServiceBase):
# MODEL_LOAD_LOCK, contending with generation's model loads — once per
# points refresh, forever.
self._vocab_failure: Optional[Exception] = None
+ # When _vocab_failure was memoized (time.monotonic). A failure is not
+ # forever: an OOM while the GPU was busy generating, or a text-tower
+ # load that lost a race, recovers — so a request arriving after
+ # _VOCAB_FAILURE_RETRY_SECONDS drops the memo and queues a rebuild.
+ # The window keeps the vision-only case above at one from_pretrained
+ # attempt per window instead of one per points refresh.
+ self._vocab_failed_at: Optional[float] = None
# Set by a labels request, serviced on the worker: the build is minutes
# of encoder work and must never run on a request thread.
self._vocab_build_requested = threading.Event()
@@ -373,14 +386,29 @@ class ImageIndexService(ImageIndexServiceBase):
if self._vocab_cache is not None:
return self._vocab_cache
if self._vocab_failure is not None:
- # Cleared again on the way out, not just when it was stored:
- # re-raising a persistent exception re-attaches a fresh traceback
- # to it, so without this the frames grow by one propagation per
- # labels request, forever, each set holding that request's caller
- # frame — whose `record` is the whole projection, coordinates
- # included. Clearing here bounds it to the one propagation in
- # flight instead, which the next request replaces.
- raise self._vocab_failure.with_traceback(None)
+ # Aged past the retry window: drop the memo and fall through to
+ # queue a rebuild. The failure may have been transient (an OOM
+ # while the GPU was busy generating); answering from memory
+ # forever would pin one bad minute as a permanent outage.
+ # A stopped worker is exempt — it would never consume the
+ # build request, so the request would 409 "still being
+ # prepared" for the rest of the process's life; the memoized
+ # failure (the real cause) is the better answer there.
+ if (
+ self._vocab_failed_at is None
+ or self._stop_event.is_set()
+ or time.monotonic() - self._vocab_failed_at < _VOCAB_FAILURE_RETRY_SECONDS
+ ):
+ # Cleared again on the way out, not just when it was stored:
+ # re-raising a persistent exception re-attaches a fresh traceback
+ # to it, so without this the frames grow by one propagation per
+ # labels request, forever, each set holding that request's caller
+ # frame — whose `record` is the whole projection, coordinates
+ # included. Clearing here bounds it to the one propagation in
+ # flight instead, which the next request replaces.
+ raise self._vocab_failure.with_traceback(None)
+ self._vocab_failure = None
+ self._vocab_failed_at = None
if self._invoker is None or self._model_id is None:
raise TextSearchUnavailableError("The image index is not running")
@@ -481,6 +509,7 @@ class ImageIndexService(ImageIndexServiceBase):
e.__cause__ = None
e.__context__ = None
self._vocab_failure = e.with_traceback(None)
+ self._vocab_failed_at = time.monotonic()
def _load_or_embed_phrases(self, phrases: list[str], cache_path: Path) -> np.ndarray:
"""One vocabulary tier's embedding matrix, from its disk cache or the encoder.
@@ -982,6 +1011,7 @@ class ImageIndexService(ImageIndexServiceBase):
with self._vocab_lock:
self._vocab_cache = None
self._vocab_failure = None
+ self._vocab_failed_at = None
try:
self._build_vocab_embeddings()
except Exception:
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 0b7811ed71..47bd39bfb2 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -2057,6 +2057,9 @@ def test_a_failed_vocabulary_build_is_not_retried_on_every_request(service: Imag
from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
service._vocab_failure = TextSearchUnavailableError("no text encoder") # type: ignore[assignment]
+ # As the worker's except branch always does — a fresh failure, inside the
+ # retry window.
+ service._vocab_failed_at = time.monotonic()
with pytest.raises(TextSearchUnavailableError, match="no text encoder"):
service.get_vocab_embeddings()
@@ -2065,6 +2068,87 @@ def test_a_failed_vocabulary_build_is_not_retried_on_every_request(service: Imag
assert not service._vocab_build_requested.is_set()
+def test_an_aged_vocabulary_failure_requeues_the_build(service: ImageIndexService) -> None:
+ # The memo protects a vision-only install from per-refresh text-tower
+ # retries, but the failure itself can be transient — an OOM while the GPU
+ # was busy generating, a load that lost a race. Answering from memory
+ # forever pins one bad minute as a permanent labels outage; after the
+ # retry window, the next request must drop the memo and ask the worker
+ # to build again.
+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
+
+ service._invoker = SimpleNamespace() # type: ignore[assignment]
+ service._model_id = MODEL_ID
+ service._vocab_failure = TextSearchUnavailableError("encoder OOM") # type: ignore[assignment]
+ service._vocab_failed_at = time.monotonic() - image_index_default._VOCAB_FAILURE_RETRY_SECONDS - 1
+
+ with pytest.raises(TextSearchUnavailableError, match="still being prepared"):
+ service.get_vocab_embeddings()
+
+ assert service._vocab_build_requested.is_set()
+ assert service._vocab_failure is None
+ assert service._vocab_failed_at is None
+
+
+def test_a_failed_build_records_when_it_failed(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The retry window is measured from the build's failure, so the stamp must
+ # land with the memo.
+ from invokeai.app.services.image_index import cluster_labels
+
+ def _oom(embed_fn, vocabulary):
+ raise RuntimeError("encoder OOM")
+
+ matrix = np.arange(3 * DIM, dtype=EMBEDDING_DTYPE).reshape(3, DIM)
+ service = _vocab_build_service(tmp_path, monkeypatch, matrix)
+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", _oom)
+
+ service._build_vocab_embeddings()
+
+ assert service._vocab_failure is not None
+ assert service._vocab_failed_at is not None
+ # Two-sided: a stamp written with the wrong clock (time.time against a
+ # monotonic read) is a huge negative difference that a one-sided bound
+ # passes vacuously — and the memo would then never age out.
+ assert abs(time.monotonic() - service._vocab_failed_at) < 5
+
+
+def test_an_aged_vocabulary_failure_does_not_requeue_against_a_stopped_worker(
+ service: ImageIndexService,
+) -> None:
+ # The decay assumes the index worker will consume the build request. After
+ # stop() nothing will, so a request arriving in the shutdown window must
+ # answer with the memoized failure — the real cause — rather than queue a
+ # rebuild that 409s "still being prepared" for the rest of the process's
+ # life.
+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
+
+ service._vocab_failure = TextSearchUnavailableError("encoder OOM") # type: ignore[assignment]
+ service._vocab_failed_at = time.monotonic() - image_index_default._VOCAB_FAILURE_RETRY_SECONDS - 1
+ service._stop_event.set()
+
+ with pytest.raises(TextSearchUnavailableError, match="encoder OOM"):
+ service.get_vocab_embeddings()
+
+ assert not service._vocab_build_requested.is_set()
+ assert service._vocab_failure is not None
+
+
+def test_the_worker_clears_the_failure_stamp_with_the_memo(service: ImageIndexService) -> None:
+ """Pin the CALL SITE, not just the fields.
+
+ The worker's invalidation block drops the memo and its stamp together; the
+ stamp is only ever read under `if self._vocab_failure is not None`, so
+ leaving it behind is invisible today — but any future read outside that
+ guard turns the stale value live. Like the backoff call-site test above,
+ this is the plausible hand-resolved-rebase loss the suite must see.
+ """
+ source = inspect.getsource(ImageIndexService._worker_loop)
+ invalidate_block = source.split("_vocab_invalidate_requested.clear()")[1].split("try:")[0]
+
+ assert "self._vocab_failure = None" in invalidate_block
+ assert "self._vocab_failed_at = None" in invalidate_block
+
+
def _vocab_build_service(tmp_path, monkeypatch: pytest.MonkeyPatch, matrix: np.ndarray) -> ImageIndexService:
"""A service wired for `_build_vocab_embeddings` over a three-phrase vocabulary."""
from invokeai.app.services.image_index import cluster_labels