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): separate systemic from per-image failures; harden device and model resolution
Lincoln Steine6ad3282b89e
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 8d50254512..e36a79dc73 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -25,13 +25,30 @@ if TYPE_CHECKING:# A batch of PIL images in, an (N, dim) float32 embedding matrix out.EncodeFn = Callable[[list[Image.Image]], np.ndarray]++def _is_cpu_override(override: Optional[str]) -> bool:+ """True if `image_index_device` asks for CPU mode.++ `cpu` is the only meaningful value; the config documents every other value as ignored.+ Compared as a normalized string rather than via `torch.device`, which raises on anything+ that is not a valid device spec — including near-misses like `CPU`.+ """+ return override is not None and override.strip().lower() == "cpu"++# How long the worker sleeps between generation-idle checks and empty-queue polls._POLL_SECONDS = 1.0-# An image is retried this many times (transient failures: OOM, file locks,-# model briefly unavailable) before being marked permanently failed.+# An image is retried this many times before being marked permanently failed. This bounds+# per-image badness only — a corrupt file, an unreadable image, an embedding that cannot be+# normalized. Failures of the machinery (the encoder, the database) never consume this budget;+# see _record_systemic_failure._MAX_ATTEMPTS = 3+# Consecutive systemic failures back off exponentially from _POLL_SECONDS up to this ceiling,+# so an outage that lasts hours does not retry at 1 Hz while still recovering promptly.+_MAX_BACKOFF_SECONDS = 60.0+def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:"""Run one tiny scaled_dot_product_attention call while the process is still single-threaded.@@ -48,9 +65,12 @@ def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:if not config.image_index_enabled:returntry:- device = (- torch.device(config.image_index_device) if config.image_index_device else TorchDevice.choose_torch_device()- )+ # Mirrors ImageIndexService._cpu_mode: `cpu` selects CPU mode, anything else is+ # ignored rather than parsed as a device, so a bad value cannot decide where — or+ # whether — the warm-up runs.+ if _is_cpu_override(config.image_index_device):+ return+ device = TorchDevice.choose_torch_device()if device.type != "cuda":returnquery = torch.zeros((1, 1, 8, 8), device=device, dtype=torch.float16)@@ -89,6 +109,9 @@ class ImageIndexService(ImageIndexServiceBase):# the backfill loop spin forever. Transient failures get retried.self._attempts: dict[str, int] = {}self._failed: set[str] = set()+ # Consecutive failures of the machinery rather than of any image. Drives the retry+ # backoff and is reset by the first batch that stores anything. Worker-thread only.+ self._systemic_failures = 0self._stop_event = threading.Event()self._backfill_pending = threading.Event()# Set by the image-service callbacks when counts changed; the worker@@ -128,6 +151,15 @@ class ImageIndexService(ImageIndexServiceBase):invoker.services.logger.warning("Image index service started twice; ignoring the second start")return+ device_override = config.image_index_device+ if device_override and not _is_cpu_override(device_override):+ # Ignored, as documented — but silently ignoring a near-miss like `CPU` leaves the+ # operator believing indexing runs on the CPU when it is following the model cache.+ invoker.services.logger.warning(+ f"image_index_device={device_override!r} is not understood and is being ignored; "+ "only 'cpu' selects CPU mode"+ )+if self._encode_fn_override is not None:self._encode_fn = self._encode_fn_overrideself._model_id = self._model_id_override@@ -249,8 +281,11 @@ class ImageIndexService(ImageIndexServiceBase):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.- self._stop_event.wait(_POLL_SECONDS)+ # 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())except Exception:logger.exception("Unexpected error in the image index worker")# Whatever was in flight may have skipped its accounting, so@@ -319,12 +354,12 @@ class ImageIndexService(ImageIndexServiceBase):embeddings = np.asarray(self._encode_fn(images), dtype=EMBEDDING_DTYPE)except Exception:logger.exception(f"Image index: failed to embed a batch of {len(loaded_names)} images")- self._record_failure(loaded_names)+ self._attribute_batch_failure("the encoder raised", loaded_names)return Falseif embeddings.ndim != 2 or embeddings.shape[0] != len(loaded_names):logger.error(f"Image index: encoder returned shape {embeddings.shape} for {len(loaded_names)} images")- self._record_failure(loaded_names)+ self._attribute_batch_failure("the encoder returned an unusable result", loaded_names)return False# L2-normalize so cosine similarity is a plain dot product downstream. The norm is@@ -366,20 +401,77 @@ class ImageIndexService(ImageIndexServiceBase):# update) must stop counting against the failed total.self._failed.discard(name)except Exception:- # A raise here (e.g. "database is locked") must still route- # the unstored names through the failure path, or they linger- # unembedded — with pending stuck above zero — until restart.+ # 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+ # rather than being charged an attempt each.logger.exception(f"Image index: failed to store embeddings for a batch of {len(loaded_names)} images")- self._record_failure([name for name in loaded_names if name not in stored])+ self._record_systemic_failure(+ "storing embeddings failed", [name for name in loaded_names if name not in stored]+ )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.+ self._systemic_failures = 0return len(loaded_names) == len(image_names)finally:# Always release the batch from the dedup set — a name stuck in# _pending can never be re-enqueued by callbacks.self._forget_pending(image_names)+ def _attribute_batch_failure(self, reason: str, image_names: list[str]) -> None:+ """Charge a whole-batch embedding failure to the images or to the machinery."""+ if self._encoder_is_healthy():+ # The encoder works on a trivial image, so something about these images is what+ # broke it. Charge them, so a poisonous one is quarantined after _MAX_ATTEMPTS and+ # stops blocking the rest of the backlog.+ self._record_failure(image_names)+ else:+ self._record_systemic_failure(reason, image_names)++ def _encoder_is_healthy(self) -> bool:+ """Probe the encoder with a trivial image to tell a broken encoder from bad input.++ This is the discriminator the whole failure-attribution scheme rests on. A batch that+ fails to embed says nothing on its own about *why*: the model may be uninstalled, or one+ image in the batch may be corrupt. Repetition cannot separate the two — a real outage+ and a poisonous image both fail every time — so the encoder is asked directly.++ A healthy encoder means the batch failed because of its contents, and the images are+ charged an attempt so a bad one is eventually quarantined and the backfill can move past+ it. An unhealthy one means the machinery is down, and the images must not be charged.+ """+ assert self._encode_fn is not None+ try:+ probe = np.asarray(self._encode_fn([Image.new("RGB", (16, 16))]), dtype=EMBEDDING_DTYPE)+ except Exception:+ return False+ return probe.ndim == 2 and probe.shape[0] == 1 and probe.shape[1] > 0++ def _record_systemic_failure(self, reason: str, image_names: list[str]) -> None:+ """Record a failure of the machinery: back off, but charge no image for it.++ `_MAX_ATTEMPTS` exists so one bad file cannot spin the backfill forever. Charging an+ outage against that budget instead retires every image the outage touched, and because+ nothing clears `_failed` but a successful embed, restoring the model would not bring+ them back — only a restart would. The images stay pending here, so the sweep retries+ them once the machinery recovers, and `pending` keeps telling the truth meanwhile.+ """+ assert self._invoker is not None+ self._systemic_failures += 1+ self._invoker.services.logger.warning(+ f"Image index: {reason}; leaving {len(image_names)} image(s) pending for retry "+ f"(consecutive failures: {self._systemic_failures})"+ )++ def _backoff_seconds(self) -> float:+ if self._systemic_failures <= 0:+ return _POLL_SECONDS+ # Cap the exponent before the shift so a long outage cannot overflow it.+ return min(_POLL_SECONDS * (2 ** min(self._systemic_failures - 1, 16)), _MAX_BACKOFF_SECONDS)+def _record_failure(self, image_names: list[str]) -> None:"""Count a failure; move an image to the permanent-failure set only after repeated attempts."""for name in image_names:@@ -399,7 +491,7 @@ class ImageIndexService(ImageIndexServiceBase):generation; embedding on the GPU mid-generation would thrash both."""assert self._invoker is not None- if self._device().type == "cpu":+ if self._cpu_mode():returnsession_queue = self._invoker.services.session_queueif session_queue is None:@@ -466,25 +558,47 @@ class ImageIndexService(ImageIndexServiceBase):def _resolve_model_config(self, model_name: str) -> Optional["AnyModelConfig"]:assert self._invoker is not None+ if not model_name:+ # `search_by_attr` drops the name predicate for a falsy name and would return every+ # installed model of the type, so an empty config value would silently adopt an+ # arbitrary one — and then `start()` discards every embedding computed by the model+ # the user actually meant. `_model_not_installed_message` guards this too.+ return Nonestore = self._invoker.services.model_manager.storefor model_type in (ModelType.CLIPVision, ModelType.SigLIP):configs = store.search_by_attr(model_name=model_name, model_type=model_type)+ if not configs:+ continue+ # Names are not unique (the UNIQUE(name, base, type) constraint is gone), and+ # `search_by_attr` orders by type/base/name/format — so for two otherwise identical+ # rows the tiebreak is insertion order, and reinstalling one moves the winner. That+ # changes the model hash, and `start()` then discards every embedding computed under+ # the old one. Order by key instead: stable across reinstalls of the same set.+ chosen = min(configs, key=lambda config: config.key)if len(configs) > 1:- # Names are not unique. A different pick after a reinstall- # changes the model hash and discards the whole index.self._invoker.services.logger.warning(f"Multiple {model_type.value} models named '{model_name}' are installed; "- f"using '{configs[0].key}' for the image index"+ f"using '{chosen.key}' for the image index")- if configs:- return configs[0]+ return chosenreturn None- def _device(self) -> torch.device:+ def _cpu_mode(self) -> bool:+ """True when embeddings should be computed on a service-local CPU copy of the model.++ Both callers only ever ask whether this is CPU mode — the GPU path follows whatever+ device the model cache picked. So the override is never turned into a `torch.device`:+ `image_index_device` is a free-form config string with no validator, and+ `torch.device("CPU")` raises. Building one here put the worker in a permanent+ exception loop on a typo, bypassing the `_MAX_ATTEMPTS` bound because it raised before+ any batch was attempted.+ """override = self._invoker.services.configuration.image_index_device if self._invoker else None- if override:- return torch.device(override)- return TorchDevice.choose_torch_device()+ if _is_cpu_override(override):+ return True+ # Any other value is ignored, as the config documents. Fall back to the auto-chosen+ # device so a CPU-only host still gets CPU mode.+ return TorchDevice.choose_torch_device().type == "cpu"def _model_abs_path(self) -> Path:assert self._invoker is not None@@ -528,7 +642,7 @@ class ImageIndexService(ImageIndexServiceBase):assert self._invoker is not Noneassert self._model_config is not None- if self._device().type == "cpu":+ if self._cpu_mode():# CPU mode exists to avoid touching the model cache (and VRAM) at# all, so it keeps its own RAM-resident copy of the model.if self._cpu_model is None:diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 22021efc9a..4c21310985 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -10,7 +10,12 @@ 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.image_index_default import ImageIndexService+from invokeai.app.services.image_index.image_index_default import (+ _MAX_ATTEMPTS,+ _MAX_BACKOFF_SECONDS,+ _POLL_SECONDS,+ ImageIndexService,+)from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlitefrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage@@ -34,6 +39,12 @@ def _wait_until(predicate: Callable[[], bool], timeout: float = 10.0) -> None:raise AssertionError("Condition not met within timeout")+def _unit_vec() -> np.ndarray:+ """A storable embedding: float32, finite, non-zero."""+ v = np.ones(DIM, dtype=np.float32)+ return v / np.linalg.norm(v)++def _fake_encode(images: list[Image.Image]) -> np.ndarray:rng = np.random.default_rng(42)vectors = rng.standard_normal((len(images), DIM)).astype(np.float32)@@ -69,11 +80,14 @@ def _make_invoker(index_records: ImageIndexRecordsSqlite,enabled: bool = True,image_records: SqliteImageRecordStorage | None = None,+ device: str | None = "cpu",+ session_queue: object | None = None,+ model_manager: object | None = None,) -> SimpleNamespace:config = InvokeAIAppConfig(use_memory_db=True,image_index_enabled=enabled,- image_index_device="cpu",+ image_index_device=device,image_index_batch_size=4,)services = SimpleNamespace(@@ -83,8 +97,8 @@ def _make_invoker(image_records=image_records,image_index_records=index_records,events=TestEventService(),- session_queue=None,- model_manager=None,+ session_queue=session_queue,+ model_manager=model_manager,)return SimpleNamespace(services=services)@@ -271,7 +285,7 @@ def test_model_not_installed_message_flags_same_name_wrong_type() -> None:assert "is not installed" in message-def test_bad_encoder_output_marks_batch_failed(+def test_broken_encoder_leaves_images_pending_rather_than_quarantined(image_records: SqliteImageRecordStorage,images_service: ImageService,index_records: ImageIndexRecordsSqlite,@@ -280,13 +294,143 @@ def test_bad_encoder_output_marks_batch_failed(try:_save_image(image_records, "a.png")service.start(_make_invoker(images_service, index_records))- _wait_until(lambda: not service._backfill_pending.is_set())+ _wait_until(lambda: service._systemic_failures > 0)++ assert index_records.count_index_status(MODEL_ID).embedded == 0+ # NOT quarantined. A broken encoder is a fault of the machinery, and `_MAX_ATTEMPTS`+ # bounds per-image badness only. Retiring the image here would be a lie about the image+ # and — since nothing but a successful embed clears `_failed` — would survive the+ # encoder being fixed, leaving the index short until a restart.+ assert "a.png" not in service._failed+ assert service.get_status().pending == 1+ finally:+ service.stop()+++def test_index_recovers_from_an_encoder_outage_without_a_restart(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The point of separating systemic from per-image failure.++ An outage lasting more than `_MAX_ATTEMPTS` sweeps used to retire every image it touched.+ Nothing but a successful embed clears `_failed`, so the images stayed dead after the model+ came back and only a process restart recovered them. They must now come back on their own.+ """+ outage = {"active": True}++ def encode(images: list[Image.Image]) -> np.ndarray:+ if outage["active"]:+ raise RuntimeError("model is not installed")+ return _fake_encode(images)++ service = ImageIndexService(encode_fn=encode, model_id=MODEL_ID)+ try:+ for i in range(6):+ _save_image(image_records, f"img-{i}.png")+ service.start(_make_invoker(images_service, index_records))++ # Outlast _MAX_ATTEMPTS sweeps, which is what used to retire the images.+ _wait_until(lambda: service._systemic_failures > _MAX_ATTEMPTS, timeout=15.0)+ assert service._failed == set()+ assert service._attempts == {}assert index_records.count_index_status(MODEL_ID).embedded == 0- assert "a.png" in service._failed++ outage["active"] = False++ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 6, timeout=30.0)+ assert service._failed == set()+ assert service.get_status().pending == 0+ # The backoff must unwind too, or the next transient blip would start at the ceiling.+ assert service._systemic_failures == 0finally:service.stop()+def test_sustained_storage_failure_does_not_quarantine_images(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """A database that is down is no more the images' fault than a missing model is.++ "database is locked" outlasting `_MAX_ATTEMPTS` sweeps must not retire the images, for the+ same reason an encoder outage must not: `_failed` would survive the database recovering.+ """+ outage = {"active": True}+ real_upsert = index_records.upsert_embedding++ def flaky_upsert(name: str, model_id: str, embedding: np.ndarray) -> None:+ if outage["active"]:+ raise RuntimeError("database is locked")+ real_upsert(name, model_id, embedding)++ index_records.upsert_embedding = flaky_upsert # 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: service._systemic_failures > _MAX_ATTEMPTS, timeout=15.0)+ assert service._failed == set()+ assert service._attempts == {}++ outage["active"] = False++ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 3, timeout=30.0)+ assert service._failed == set()+ finally:+ service.stop()+++def test_batch_failure_is_charged_to_the_images_when_the_encoder_is_healthy(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The other half: a poisonous image must still be quarantined so the backlog can advance.++ Not charging the images would be just as wrong in the other direction — one image the+ encoder chokes on would block the sweep forever, since backfill always returns it first.+ The encoder is probed with a trivial image to tell the two situations apart.+ """++ def encode(images: list[Image.Image]) -> np.ndarray:+ # Healthy for the one-image probe, broken for any real batch.+ if len(images) == 1 and images[0].size == (16, 16):+ return _fake_encode(images)+ raise RuntimeError("cannot encode these images")++ service = ImageIndexService(encode_fn=encode, model_id=MODEL_ID)+ try:+ for i in range(2):+ _save_image(image_records, f"img-{i}.png")+ service.start(_make_invoker(images_service, index_records))++ _wait_until(lambda: len(service._failed) == 2, timeout=20.0)+ # Charged to the images, not to the machinery.+ assert service._systemic_failures == 0+ # And the index settles rather than retrying them forever.+ _wait_until(lambda: service.get_status().pending == 0, timeout=15.0)+ finally:+ service.stop()+++def test_systemic_backoff_grows_and_is_capped(service: ImageIndexService) -> None:+ service._systemic_failures = 0+ assert service._backoff_seconds() == _POLL_SECONDS+ service._systemic_failures = 1+ assert service._backoff_seconds() == _POLL_SECONDS+ service._systemic_failures = 3+ assert service._backoff_seconds() == _POLL_SECONDS * 4+ # Capped, and no overflow for an outage that lasts a very long time.+ service._systemic_failures = 10_000+ assert service._backoff_seconds() == _MAX_BACKOFF_SECONDS++def test_zero_norm_embedding_fails_only_its_own_image(image_records: SqliteImageRecordStorage,images_service: ImageService,@@ -319,6 +463,163 @@ def test_zero_norm_embedding_fails_only_its_own_image(service.stop()+def test_start_discards_only_other_models_embeddings(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The one destructive operation in the service: prove what it does and does not delete.++ `start()` prunes embeddings computed by a previously-configured model. If it ever pruned+ the current model's rows the whole index would be silently rebuilt from scratch on every+ boot, and if it pruned nothing the index would accumulate dead rows forever.+ """+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _unit_vec())+ index_records.upsert_embedding("a.png", "stale-model-hash", _unit_vec())+ assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == ["a.png"]++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == []+ assert index_records.get_embeddings(["a.png"], MODEL_ID)[0] == ["a.png"]+ finally:+ service.stop()+++def test_disabled_service_does_not_discard_embeddings(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """Turning the feature off must not destroy an index built while it was on."""+ _save_image(image_records, "a.png")+ index_records.upsert_embedding("a.png", "stale-model-hash", _unit_vec())++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ service.start(_make_invoker(images_service, index_records, enabled=False))+ assert index_records.get_embeddings(["a.png"], "stale-model-hash")[0] == ["a.png"]+ finally:+ service.stop()+++def test_worker_waits_for_generation_to_finish_when_not_on_cpu(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """The VRAM contract: off the CPU path, embedding must pause while a generation runs.++ Every other test sets device='cpu' and session_queue=None, so `_wait_for_idle_generation`+ returns at its first statement and this contract is never exercised.+ """+ queue_status = SimpleNamespace(in_progress=1)+ session_queue = SimpleNamespace(get_queue_status=lambda queue_id: queue_status)++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records, device=None, session_queue=session_queue))++ # Generation in progress: the worker must hold off rather than embed.+ time.sleep(0.5)+ assert index_records.count_index_status(MODEL_ID).embedded == 0++ queue_status.in_progress = 0+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1, timeout=15.0)+ finally:+ service.stop()+++def test_generation_wait_does_not_block_shutdown(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """A generation that never ends must not stop the worker from honouring stop()."""+ session_queue = SimpleNamespace(get_queue_status=lambda queue_id: SimpleNamespace(in_progress=1))++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records, device=None, session_queue=session_queue))+ time.sleep(0.2)++ started = time.monotonic()+ service.stop()+ assert time.monotonic() - started < 5.0+ assert service._worker is not None and not service._worker.is_alive()+++def test_unparseable_device_is_ignored_rather_than_wedging_the_worker(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """`image_index_device` is free-form config with no validator.++ A near-miss like 'CPU' used to be handed to torch.device(), which raises — inside the+ worker loop, before any batch was attempted, so the _MAX_ATTEMPTS bound never applied and+ the worker spun on the same exception forever with pending stuck above zero.+ """+ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ try:+ _save_image(image_records, "a.png")+ service.start(_make_invoker(images_service, index_records, device="CPU"))+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1, timeout=15.0)+ assert service.get_status().pending == 0+ finally:+ service.stop()+++def test_empty_model_name_does_not_resolve_to_an_arbitrary_model(+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """`search_by_attr` drops its name predicate for a falsy name.++ Without a guard an empty `image_index_model` adopts whichever model happens to sort first+ and then discards every embedding computed by the model the user actually configured.+ """+ installed = SimpleNamespace(key="some-key", name="clip-vit-large-patch14", hash="some-hash")+ store = SimpleNamespace(search_by_attr=lambda model_name, model_type: [installed])+ model_manager = SimpleNamespace(store=store)++ service = ImageIndexService()+ service._invoker = _make_invoker(images_service, index_records, model_manager=model_manager)++ assert service._resolve_model_config("") is None+ # Sanity: the same store does resolve a real name, so the None above is the guard talking+ # and not simply an empty store.+ assert service._resolve_model_config("clip-vit-large-patch14") is installed+++def test_duplicate_model_names_resolve_deterministically(+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ """Two models can share a name, and the pick must not move when one is reinstalled.++ `search_by_attr` breaks ties by insertion order, so reinstalling a duplicate flips which+ config wins. That changes the model hash, and `start()` then discards every embedding+ computed under the previous one — the whole index, silently.+ """+ a = SimpleNamespace(key="key-a", name="clip-vit-large-patch14", hash="hash-a")+ b = SimpleNamespace(key="key-b", name="clip-vit-large-patch14", hash="hash-b")++ def resolve(order: list[SimpleNamespace]) -> SimpleNamespace:+ store = SimpleNamespace(search_by_attr=lambda model_name, model_type: list(order))+ service = ImageIndexService()+ service._invoker = _make_invoker(images_service, index_records, model_manager=SimpleNamespace(store=store))+ return service._resolve_model_config("clip-vit-large-patch14")++ # Same set, either insertion order — the winner must not move.+ assert resolve([a, b]).key == resolve([b, a]).key == "key-a"++def test_status_event_emitted(image_records: SqliteImageRecordStorage,images_service: ImageService,