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(nodes): resume image indexing on its own after an encoder replacement
Josh Corbett613fc5809f25
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 550eef80d7..c0af8f4868 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -68,7 +68,8 @@ class ImageMapPointsResponse(BaseModel):points: list[ImageMapPoint] = Field(description="The projected points")state: ImageMapState = Field(description="disabled: indexing is off; model_missing: indexing is enabled but the configured embedding "- "model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"+ "model is not installed; empty: nothing to show; computing: a projection is being built, or the index is "+ "switching to a replacement embedding model; ready: points are served")model_id: Optional[str] = Field(default=None, description="Active encoder fingerprint; clients must discard cached labels when it changes"@@ -286,6 +287,26 @@ def _active_model_id(services) -> Optional[str]:return services.image_index.model_id+def _inactive_state(services) -> ImageMapState:+ """Why there is no active model: an installed replacement still draining is not a missing model."""+ if not services.configuration.image_index_enabled:+ return "disabled"+ return "computing" if services.image_index.replacing_model else "model_missing"+++async def _search_model_id(services) -> str:+ """The active model for a search; reconciled here too, so gallery search recovers without the map open."""+ model_id = await asyncio.to_thread(_active_model_id, services)+ if model_id is None:+ detail = (+ "The image index is switching embedding models; try again shortly"+ if _inactive_state(services) == "computing"+ else "The image index is not enabled; semantic search is unavailable"+ )+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail)+ return model_id++_T = TypeVar("_T")@@ -402,15 +423,14 @@ async def get_image_map_points(# The service is also inert when indexing is enabled but the# configured model is not installed; tell the client which case# this is so it can show an actionable message.- if services.configuration.image_index_enabled:- return ImageMapPointsResponse(- points=[],- state="model_missing",- model_name=services.configuration.image_index_model,- stale=False,- point_count=0,- )- return ImageMapPointsResponse(points=[], state="disabled", stale=False, point_count=0)+ state = _inactive_state(services)+ return ImageMapPointsResponse(+ points=[],+ state=state,+ model_name=services.configuration.image_index_model if state == "model_missing" else None,+ stale=False,+ point_count=0,+ )user_id, is_admin = _scope(current_user)kinds = _served_kinds(include_videos)@@ -603,12 +623,7 @@ async def search_image_map(detail="Provide exactly one of q, image_name or video_name",)- model_id = services.image_index.model_id- if model_id is None:- raise HTTPException(- status_code=status.HTTP_409_CONFLICT,- detail="The image index is not enabled; semantic search is unavailable",- )+ model_id = await _search_model_id(services)user_id, is_admin = _scope(current_user)scope_user = None if is_admin else user_id@@ -833,12 +848,7 @@ async def search_image_map_by_image(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of image or image_url")- model_id = services.image_index.model_id- if model_id is None:- raise HTTPException(- status_code=status.HTTP_409_CONFLICT,- detail="The image index is not enabled; semantic search is unavailable",- )+ model_id = await _search_model_id(services)user_id, is_admin = _scope(current_user)scope_user = None if is_admin else user_id@@ -1247,13 +1257,11 @@ def get_image_map_status(services = ApiDependencies.invoker.servicesmodel_id = _active_model_id(services)if model_id is None:- model_missing = services.configuration.image_index_enabled+ state = _inactive_state(services)return ImageMapStatusResponse(enabled=False,- model_name=services.configuration.image_index_model if model_missing else None,- projection=ImageMapProjectionStatus(- state="model_missing" if model_missing else "disabled", stale=False, point_count=0- ),+ model_name=services.configuration.image_index_model if state == "model_missing" else None,+ projection=ImageMapProjectionStatus(state=state, stale=False, point_count=0),)user_id, is_admin = _scope(current_user)diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex a363c42c70..1d55931b14 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -38,6 +38,11 @@ class ImageIndexServiceBase(ABC):"""Content hash of the active embedding model, or None if the indexer is not running."""pass+ @property+ def replacing_model(self) -> bool:+ """True while a retired model waits to drain before its installed replacement starts."""+ return False+def try_activate(self) -> bool:"""Reconcile whether the configured embedding model is still installed.diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex b3c57f8056..1178b225ff 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -289,6 +289,10 @@ class ImageIndexService(ImageIndexServiceBase):# Retirement publishes unavailability immediately; replacement waits# for these users and the worker without blocking a polling request.self._model_users = 0+ self._users_drained = threading.Condition(self._activation_lock)+ # A retired model whose configured name now resolves to another+ # installation; cleared once the replacement starts or is missing.+ self._replacement_pending = Falseself._callbacks_registered = Falseself._last_activation_attempt: float = 0.0# Set by stop() so a request that raced shutdown cannot start a worker@@ -351,6 +355,10 @@ class ImageIndexService(ImageIndexServiceBase):def model_id(self) -> str | None:return None if self._stop_event.is_set() else self._model_id+ @property+ def replacing_model(self) -> bool:+ return self._replacement_pending and self._stop_event.is_set() and not self._stopped+@contextmanagerdef use_model(self) -> Iterator[None]:with self._activation_lock:@@ -360,6 +368,8 @@ class ImageIndexService(ImageIndexServiceBase):finally:with self._activation_lock:self._model_users -= 1+ if not self._model_users:+ self._users_drained.notify_all()def get_status(self) -> ImageIndexStatus | None:model_id = self.model_id@@ -843,11 +853,12 @@ class ImageIndexService(ImageIndexServiceBase):def try_activate(self) -> bool:"""Reconcile encoder installation, draining retired work before replacement.- Called off the event loop by map reads and by the worker. Rechecks- are throttled in both the running and missing states. No join or- encoder lock is taken here: a deleted model becomes unavailable at- once, while its in-flight users keep their stable resources until a- later poll can safely replace them.+ Called off the event loop by map and search requests and by the+ worker. Rechecks are throttled in both the running and missing states.+ No join or encoder lock is taken here: a deleted model becomes+ unavailable at once, while its in-flight users keep their stable+ resources until the exiting worker, or a later request, can safely+ replace them."""invoker = self._invokerif invoker is None or not invoker.services.configuration.image_index_enabled:@@ -886,48 +897,82 @@ class ImageIndexService(ImageIndexServiceBase):):return Trueself._stop_event.set()+ self._replacement_pending = model_config is not Noneif self._model_users or (self._worker is not None and self._worker.is_alive()):+ # A live worker finishes the swap as it exits (_finish_retirement).return False+ return self._swap_model(invoker, model_config)++ def _swap_model(self, invoker: "Invoker", model_config: Optional["AnyModelConfig"]) -> bool:+ """Retire the drained model and start `model_config`, if any. Called under _activation_lock."""+ config = invoker.services.configuration+ self._reset_model_resources()+ self._replacement_pending = False+ self._model_config = None+ self._encode_fn = None+ self._model_id = None+ if model_config is None:+ return False- self._reset_model_resources()+ invoker.services.logger.info(+ f"Image index: embedding model '{config.image_index_model}' is now installed; starting the indexer"+ )+ # `_model_id` last, and rolled back as a set: it is the flag every+ # other thread reads as "the indexer is running". Published before+ # the worker exists, a failed launch would wedge the service there+ # permanently — try_activate would treat it as running while+ # nothing consumed the queue, and no later request would retry.+ self._model_config = model_config+ self._encode_fn = self._encode_with_model+ self._model_id = model_config.hash+ try:+ self._launch_worker(invoker)+ except Exception:+ self._stop_event.set()self._model_config = Noneself._encode_fn = Noneself._model_id = None- if model_config is None:- return False-- invoker.services.logger.info(- f"Image index: embedding model '{config.image_index_model}' is now installed; starting the indexer"+ invoker.services.logger.warning(+ "Image index: could not start the indexer after the model became available; "+ "the next image map or search request will retry",+ exc_info=True,)- # `_model_id` last, and rolled back as a set: it is the flag every- # other thread reads as "the indexer is running". Published before- # the worker exists, a failed launch would wedge the service there- # permanently — the fast path above would answer True forever while- # nothing consumed the queue, and no later request would retry.- self._model_config = model_config- self._encode_fn = self._encode_with_model- self._model_id = model_config.hash+ return False+ return True++ def _finish_retirement(self) -> None:+ """Complete a retirement as the worker exits, once request users have drained.++ Replacement must not wait for an image map request: with the map closed,+ semantic search and new-image indexing would stay down indefinitely.+ """+ invoker = self._invoker+ assert invoker is not None+ with self._activation_lock:+ while self._model_users and not self._stopped:+ self._users_drained.wait()+ if self._stopped or not self._stop_event.is_set():+ return+ self._last_activation_attempt = time.monotonic()try:- self._launch_worker(invoker)+ model_config = self._resolve_model_config(invoker.services.configuration.image_index_model)except Exception:- self._stop_event.set()- self._model_config = None- self._encode_fn = None- self._model_id = None- invoker.services.logger.warning(- "Image index: could not start the indexer after the model became available; "- "the next image map request will retry",- exc_info=True,- )- return False- return True+ # Stay retired; the next request's try_activate swaps once the catalog reads again. Without a+ # resolved replacement, reads must not report one as starting.+ self._replacement_pending = False+ invoker.services.logger.warning("Image index: could not resolve the embedding model", exc_info=True)+ return+ self._swap_model(invoker, model_config)def _reset_model_resources(self) -> None:"""Retire caches only after the worker and request users have drained.Called under _activation_lock. Same-hash reinstalls must also discardlazy encoders and load failures: their path or installation may have- changed even though stored image embeddings remain valid.+ changed even though stored image embeddings remain valid. Taking+ _vocab_lock here reverses the worker's vocab-build order+ (_vocab_lock, then use_model); that is safe only because no build can+ be running once the worker has left its loop and request users drained."""self._processor = Noneself._cpu_model = None@@ -974,6 +1019,8 @@ class ImageIndexService(ImageIndexServiceBase):# worker that this stop would then never see.with self._activation_lock:self._stopped = True+ # Release a retiring worker waiting for request users in _finish_retirement.+ self._users_drained.notify_all()self._stop_event.set()if self._worker is not None and self._worker.is_alive():self._worker.join(timeout=10)@@ -1177,6 +1224,10 @@ class ImageIndexService(ImageIndexServiceBase):self._backfill_pending.set()self._status_dirty.set()self._stop_event.wait(_POLL_SECONDS)+ try:+ self._finish_retirement()+ except Exception:+ logger.exception("Image index: could not finish retiring the embedding model")def _next_batch(self) -> Optional[list[IndexedItem]]:"""Get the next batch of items, preferring backfill work.diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 6edb97dfa5..6fe218373b 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -47342,7 +47342,7 @@"type": "string","enum": ["disabled", "model_missing", "empty", "computing", "ready"],"title": "State",- "description": "disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"+ "description": "disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built, or the index is switching to a replacement embedding model; ready: points are served"},"model_id": {"anyOf": [diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 072fa91a9e..ff8b7a5bd4 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -19281,7 +19281,7 @@ export type components = {points: components["schemas"]["ImageMapPoint"][];/*** State- * @description disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served+ * @description disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built, or the index is switching to a replacement embedding model; ready: points are served* @enum {string}*/state: "disabled" | "model_missing" | "empty" | "computing" | "ready";diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 03937eaf1a..a52ed57eea 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -50,6 +50,16 @@ class MockApiDependencies(ApiDependencies):self.invoker = invoker+def _png_bytes() -> bytes:+ from io import BytesIO++ from PIL import Image++ buffer = BytesIO()+ Image.new("RGB", (8, 8), color=(200, 30, 30)).save(buffer, format="PNG")+ return buffer.getvalue()++class FakeImageIndexService(ImageIndexServiceBase):"""Records projection/search requests instead of running a worker."""@@ -67,11 +77,16 @@ class FakeImageIndexService(ImageIndexServiceBase):self.embedded_images: list = []self.vocab_invalidations = 0self.vocab_state: tuple[str, str | None] = ("idle", None)+ self.replacing = False@propertydef model_id(self) -> str | None:return self._model_id+ @property+ def replacing_model(self) -> bool:+ return self.replacing+def get_status(self) -> ImageIndexStatus | None:if self._model_id is None:return None@@ -472,6 +487,14 @@ def test_status_model_missing_when_enabled_without_model(pytest.param(lambda client: client.get("/api/v1/image_map/points"), id="points"),pytest.param(lambda client: client.get("/api/v1/image_map/status"), id="status"),pytest.param(lambda client: client.post("/api/v1/image_map/refresh"), id="refresh"),+ # Gallery search runs without the map open, so it must recover on its own.+ pytest.param(lambda client: client.get("/api/v1/image_map/search", params={"q": "a cat"}), id="search"),+ pytest.param(+ lambda client: client.post(+ "/api/v1/image_map/search_by_image", files={"image": ("ref.png", _png_bytes(), "image/png")}+ ),+ id="search_by_image",+ ),],)def test_endpoints_activate_a_model_installed_since_startup(@@ -537,6 +560,37 @@ def test_reads_revalidate_an_encoder_deleted_after_activation(assert body["index"] is None[email protected]("endpoint", ["points", "status"])+def test_reads_report_a_draining_replacement_as_computing_rather_than_missing(+ endpoint: str, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ # The replacement is installed; offering to install it again would invite a+ # duplicate install while the retired encoder's work drains.+ mock_invoker.services.configuration.image_index_enabled = True+ image_index_service._model_id = None+ image_index_service.replacing = True+ body = client.get(f"/api/v1/image_map/{endpoint}").json()+ projection = body["projection"] if endpoint == "status" else body+ assert projection["state"] == "computing"+ assert body["model_id"] is None+ assert body["model_name"] is None++ mock_invoker.services.configuration.image_index_enabled = False+ body = client.get(f"/api/v1/image_map/{endpoint}").json()+ assert (body["projection"] if endpoint == "status" else body)["state"] == "disabled"+++def test_search_during_a_replacement_says_the_model_is_switching(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ mock_invoker.services.configuration.image_index_enabled = True+ image_index_service._model_id = None+ image_index_service.replacing = True+ response = client.get("/api/v1/image_map/search", params={"q": "a cat"})+ assert response.status_code == 409+ assert "switching" in response.json()["detail"]++@pytest.mark.parametrize("endpoint", ["points", "status"])def test_encoder_fingerprint_changes_without_a_missing_model_response(endpoint: str, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient@@ -1227,18 +1281,12 @@ def test_cluster_labels_skips_the_embedding_gather_when_nothing_clustered(def test_search_by_image_upload_returns_ranked_results(image_index_service: FakeImageIndexService, client: TestClient) -> None:- from io import BytesIO-- from PIL import Image-- buffer = BytesIO()- Image.new("RGB", (8, 8), color=(200, 30, 30)).save(buffer, format="PNG")image_index_service.search_results = [(IndexedItem("image", "a.png"), 0.9), (IndexedItem("image", "b.png"), 0.4)]response = client.post("/api/v1/image_map/search_by_image",params={"limit": 5},- files={"image": ("ref.png", buffer.getvalue(), "image/png")},+ files={"image": ("ref.png", _png_bytes(), "image/png")},)assert response.status_code == 200diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex e381bb878c..6ac8c530b7 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -673,14 +673,15 @@ def test_deleted_encoder_becomes_unavailable_and_reinstall_resumes_without_dupliservice._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1assert service.try_activate() is Falseassert service.model_id is None+ assert not service.replacing_modelassert service.get_status() is Noneassert service.get_vocab_build_state() == ("unavailable", None)assert service.request_projection("system") is False+ # The exiting worker releases the deleted encoder's resources itself._wait_until(lambda: not service._worker.is_alive())- service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1- assert service.try_activate() is Falseassert service._processor is Noneassert service._cpu_model is None+ assert service._vocab_cache is None_save_image(image_records, "during.png")images_service._on_changed(_dto_for(image_records, "during.png"))@@ -763,23 +764,22 @@ def test_encoder_replacement_waits_for_inflight_embedding_and_discards_retired_bservice._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1assert service.try_activate() is Falseassert service.model_id is None- if not background_batch:- _wait_until(lambda: not service._worker.is_alive())+ assert service.replacing_model is (replacement_kind != "reinstall")installed[:] = [replacement]service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1assert service.try_activate() is False+ assert service.replacing_modelassert service._model_config is encoder_configrelease.set()if query is not None:query.join(timeout=10)assert not query.is_alive()- _wait_until(lambda: not service._worker.is_alive())- assert index_records.count_index_status(MODEL_ID).embedded == 0- service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1- assert service.try_activate() is True- assert service.model_id == replacement.hash+ # No further request: the retiring worker completes the swap once its users drain.+ _wait_until(lambda: service.model_id == replacement.hash)+ assert not service.replacing_modelif background_batch:+ # Re-encoded by the replacement: the retired encoder's batch was not stored._wait_until(lambda: index_records.count_index_status(replacement.hash).embedded == 1)else:service.embed_image(Image.new("RGB", (16, 16)))@@ -791,6 +791,71 @@ def test_encoder_replacement_waits_for_inflight_embedding_and_discards_retired_bservice.stop()+def test_worker_detected_replacement_resumes_indexing_without_requests(+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Deleting and re-adding the encoder gives it a new key. With the image map+ # closed, nothing but the worker notices, and gallery search and new-image+ # indexing must not stay down until someone opens the map.+ installed = [encoder_config]+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, name: installed[0])+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", lambda self, images: _fake_encode(images))+ service = ImageIndexService()+ try:+ _save_image(image_records, "before.png")+ service.start(_make_invoker(images_service, index_records, image_records=image_records))+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)+ retired = service._worker++ replacement = encoder_config.model_copy(update={"key": "re-added-key"})+ with service._activation_lock:+ installed[0] = replacement+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1++ _wait_until(lambda: service._model_config is replacement and service.model_id == MODEL_ID)+ assert retired is not None+ _wait_until(lambda: not retired.is_alive())+ assert service._worker is not retired and service._worker.is_alive()++ _save_image(image_records, "after.png")+ images_service._on_changed(_dto_for(image_records, "after.png"))+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 2)+ assert len(images_service._on_changed_callbacks) == 1+ finally:+ service.stop()+++def test_stop_releases_a_worker_waiting_for_request_users_to_drain(+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ installed = [encoder_config]+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, name: installed[0])+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", lambda self, images: _fake_encode(images))+ service = ImageIndexService()+ service.start(_make_invoker(images_service, index_records))+ worker = service._worker+ assert worker is not None+ with service.use_model():+ installed[0] = encoder_config.model_copy(update={"key": "replacement-key"})+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1+ assert service.try_activate() is False+ assert service.replacing_model++ # Shutdown must not wait out the request, nor start the replacement.+ service.stop()+ assert not worker.is_alive()+ assert service._worker is worker+ assert not service.replacing_model+ assert service.model_id is None++def test_projection_finishing_after_encoder_removal_does_not_publish(encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,image_records: SqliteImageRecordStorage,