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.

Merge branch 'main' into fix/image-index-load-report-noise

Lincoln Stein2b498f3809ab
diff --cc invokeai/app/services/image_index/image_index_default.py
index 60cd11bd18,6c2e00056d..8cdf42f65d
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@@ -863,10 -878,10 +887,12 @@@ class ImageIndexService(ImageIndexServi
invoker.services.images.on_changed(self._on_image_changed)
invoker.services.images.on_deleted(self._on_image_deleted)
+ invoker.services.videos.on_changed(self._on_video_changed)
+ invoker.services.videos.on_deleted(self._on_video_deleted)
self._backfill_pending.set()
+ # A previous run stopped mid-pass leaves this set; this run's pass announces itself.
+ self._backfill_announced = False
self._stop_event.clear()
self._worker = threading.Thread(target=self._worker_loop, name="image_index_worker", daemon=True)
self._worker.start()
@@@ -1060,23 -1096,15 +1107,23 @@@
if self._backfill_pending.is_set():
assert self._model_id is not None
- # Over-fetch by the failed count so permanently-failing images
+ # Over-fetch by the failed count so permanently-failing items
# cannot occlude the rest of the backlog.
- candidates = self._invoker.services.image_index_records.list_unembedded_image_names(
+ candidates = self._invoker.services.image_index_records.list_unembedded_items(
self._model_id, limit=batch_size + len(self._failed)
)
- batch = [name for name in candidates if name not in self._failed][:batch_size]
+ batch = [item for item in candidates if item not in self._failed][:batch_size]
if batch:
+ if not self._backfill_announced and self._announce_backfill_start():
+ self._backfill_announced = True
+ # `_failed` is cumulative over the process, so the outcome line can only
+ # speak for this pass by diffing against where it started.
+ self._backfill_failed_at_start = len(self._failed)
return batch
self._backfill_pending.clear()
+ if self._backfill_announced:
+ self._backfill_announced = False
+ self._report_backfill_outcome()
self._emit_status()
try:
@@@ -1091,59 -1119,7 +1138,59 @@@
break
return batch
+ def _announce_backfill_start(self) -> bool:
- """Log that images without an embedding are being indexed. False if it could not.
++ """Log that items without an embedding are being indexed. False if it could not.
+
+ This and `_report_backfill_outcome` bracket one backfill pass — work the log
+ previously showed only as a transformers load report for the encoder, with no
+ indication of what was being done or whether it worked. The pair is best-effort: a
+ pass that is stopped, or that never drains because the encoder is down, leaves the
+ start line unanswered (the outage warns on its own).
+
+ Returns whether the line was logged, so a count that could not be read leaves the
+ announcement to a later batch instead of costing this one — this runs on the path
+ that returns work, where a raise would discard the batch and reach the worker's
+ handler as an unexpected error.
+ """
+ assert self._invoker is not None
+ try:
+ status = self.get_status()
+ except Exception:
+ return False
+ if status is None:
+ return False
+ # The running encoder, not the configured name, which can be edited mid-run. The
+ # injected-encoder seam runs without a model config, and then has no name to give.
+ named = f" with embedding model '{self._model_config.name}'" if self._model_config is not None else ""
- self._invoker.services.logger.info(f"Image index: indexing {status.pending} image(s){named}")
++ self._invoker.services.logger.info(f"Image index: indexing {status.pending} item(s){named}")
+ return True
+
+ def _report_backfill_outcome(self) -> None:
+ """Log the result of the backfill pass that just drained.
+
+ Reached with nothing left to embed, so the pass is over one way or the other: either
- every eligible image has an embedding, or the rest exhausted their attempts and are
++ every eligible item has an embedding, or the rest exhausted their attempts and are
+ excluded from `pending` (which is why the pass ends rather than retrying forever).
+
+ Only failures charged during this pass are reported as its outcome. `_failed` is
- cumulative, so reporting it whole would warn about images that retired hours ago on
++ cumulative, so reporting it whole would warn about items that retired hours ago on
+ every later pass, for the life of the process.
+ """
+ assert self._invoker is not None
+ status = self.get_status()
+ if status is None:
+ return
+ logger = self._invoker.services.logger
+ retired = len(self._failed) - self._backfill_failed_at_start
+ if retired > 0:
+ logger.warning(
- f"Image index: indexing finished with {retired} image(s) that could not be embedded "
++ f"Image index: indexing finished with {retired} item(s) that could not be embedded "
+ f"({status.embedded} of {status.total} indexed)"
+ )
+ else:
- logger.info(f"Image index: indexing complete ({status.embedded} of {status.total} images indexed)")
++ logger.info(f"Image index: indexing complete ({status.embedded} of {status.total} items indexed)")
+
- def _process_batch(self, image_names: list[str]) -> bool:
+ def _process_batch(self, items: list[IndexedItem]) -> bool:
"""Embed one batch. Returns False when anything in it failed."""
assert self._invoker is not None
assert self._encode_fn is not None
diff --cc tests/app/services/image_index/test_image_index_service.py
index 15ca3ccbd6,8fb1a9a7be..f7a7f56518
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@@ -246,91 -312,11 +312,91 @@@ def test_unloadable_image_is_skipped_an
service.start(_make_invoker(images_service, index_records))
_wait_until(lambda: not service._backfill_pending.is_set())
- assert index_records.get_embeddings(["good.png"], MODEL_ID)[0] == ["good.png"]
- assert index_records.get_embeddings(["bad.png"], MODEL_ID)[0] == []
- assert "bad.png" in service._failed
+ assert index_records.get_embeddings(imgs("good.png"), MODEL_ID)[0] == imgs("good.png")
+ assert index_records.get_embeddings(imgs("bad.png"), MODEL_ID)[0] == []
+ assert IndexedItem("image", "bad.png") in service._failed
+def test_backfill_logs_what_it_indexed_and_that_it_finished(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ for i in range(3):
+ _save_image(image_records, f"img-{i}.png")
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(_make_invoker(images_service, index_records))
+ # Waited on the log line itself: the pass reports its outcome after clearing the flag
+ # that says it is running, so waiting on the flag races the message.
- _wait_until(lambda: "Image index: indexing complete (3 of 3 images indexed)" in caplog.text)
- assert "Image index: indexing 3 image(s)" in caplog.text
++ _wait_until(lambda: "Image index: indexing complete (3 of 3 items indexed)" in caplog.text)
++ assert "Image index: indexing 3 item(s)" in caplog.text
+
+ # An image arriving afterwards is embedded from the queue, not by a backfill pass,
+ # so it does not re-announce one.
+ caplog.clear()
+ _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"])
++ _wait_until(lambda: index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"))
+ assert "Image index: indexing" not in caplog.text
+
+
+def test_restart_over_an_indexed_gallery_logs_nothing(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # The common case on every restart: a pass with nothing to do must not announce itself,
+ # or the log gains a line per server start that says nothing happened.
+ _save_image(image_records, "already.png")
- index_records.upsert_embedding("already.png", MODEL_ID, _unit_vec())
++ index_records.upsert_embedding(IndexedItem("image", "already.png"), MODEL_ID, _unit_vec())
+ invoker = _make_invoker(images_service, index_records)
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(invoker)
+ # The sweep that found nothing emits the status event, so this is the observable that
+ # the pass has been and gone.
+ _wait_until(lambda: any(e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))
+ assert "Image index: indexing" not in caplog.text
+
+
+def test_backfill_reports_images_it_could_not_embed(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ _save_image(image_records, "good.png")
+ _save_image(image_records, "bad.png")
+
+ def get_pil_image(image_name: str) -> Image.Image:
+ if image_name == "bad.png":
+ raise FileNotFoundError(image_name)
+ return Image.new("RGB", (16, 16), "purple")
+
+ images_service.get_pil_image = get_pil_image # type: ignore[method-assign]
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(_make_invoker(images_service, index_records))
+ # The pass ends because the failure retired, so the outcome has to say so rather than
+ # claiming a complete index.
- _wait_until(lambda: "Image index: indexing finished with 1 image(s) that could not be embedded" in caplog.text)
++ _wait_until(lambda: "Image index: indexing finished with 1 item(s) that could not be embedded" in caplog.text)
+ assert "indexing complete" not in caplog.text
+
+ # A later pass speaks for itself: the image that retired earlier is still in the
+ # cumulative failure set, but nothing failed this time.
+ caplog.clear()
+ _save_image(image_records, "later.png")
+ service._backfill_pending.set()
- _wait_until(lambda: "Image index: indexing complete (2 of 3 images indexed)" in caplog.text)
++ _wait_until(lambda: "Image index: indexing complete (2 of 3 items indexed)" in caplog.text)
+ assert "could not be embedded" not in caplog.text
+
+
def test_transient_encode_failure_is_retried_to_success(
image_records: SqliteImageRecordStorage,
images_service: ImageService,