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): budget scoped search matrices by bytes (#10069)

Nianze Wu9687689934e3
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index f83fa29722..2bbe4379dd 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -64,6 +64,11 @@ def _is_cpu_override(override: Optional[str]) -> bool:
# How long the worker sleeps between generation-idle checks and empty-queue polls.
_POLL_SECONDS = 1.0
+# Soft budget for retained decoded matrices, not metadata, in-flight builds or caller-held arrays.
+# The two most recent scopes always stay, even over budget, so two alternating scopes never evict each other.
+# Roughly the previous two-entry envelope at 100k x 768 float32 values per entry.
+_SEARCH_CACHE_MAX_BYTES = 600 * 1024**2
+
# 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;
@@ -364,9 +369,10 @@ class ImageIndexService(ImageIndexServiceBase):
# Guards the lazy _processor/_cpu_model init: embed_image runs on
# request threads concurrently with the indexer worker.
self._vision_init_lock = threading.Lock()
- # scope_hash -> (items, matrix): the accessible embedding matrix for
- # similarity search, so repeated queries skip re-reading BLOBs.
- self._search_cache: dict[str, tuple[list[IndexedItem], np.ndarray]] = {}
+ # (user_id, model_id) -> (scope_hash, items, matrix): one version per owner,
+ # so gallery growth retires old matrices while small scopes can share the budget.
+ self._search_cache: dict[tuple[str | None, str], tuple[str, list[IndexedItem], np.ndarray]] = {}
+ self._search_cache_bytes = 0
self._search_cache_lock = threading.Lock()
# (vocabulary, embeddings) for cluster labeling; RAM + disk cached.
self._vocab_cache: Optional[tuple[list[str], np.ndarray]] = None
@@ -724,31 +730,39 @@ class ImageIndexService(ImageIndexServiceBase):
records = self._invoker.services.image_index_records
items = records.list_accessible_embedded_items(user_id, self._model_id)
+ cache_key = (user_id, self._model_id)
+ fingerprint = scope_hash(self._model_id, items)
+ with self._search_cache_lock:
+ cached = self._search_cache.pop(cache_key, None)
+ if cached is not None:
+ if cached[0] == fingerprint:
+ self._search_cache[cache_key] = cached # LRU touch.
+ return cached[1], cached[2]
+ self._search_cache_bytes -= cached[2].nbytes
if not items:
return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)
- # Memory math: one entry is N x dim float32 (~300 MB at 100k x 768),
- # so the LRU holds two entries and evicts oldest-first rather than
- # clearing wholesale. Keys self-invalidate: any change to the
- # accessible set changes the scope hash.
- cache_key = scope_hash(self._model_id, items)
+ # Build outside the lock: duplicate misses beat serializing searches behind BLOB reads.
+ found_items, matrix = records.get_embeddings(items, self._model_id)
+ matrix_bytes = matrix.nbytes
with self._search_cache_lock:
- cached = self._search_cache.get(cache_key)
- if cached is not None:
- # LRU touch.
- del self._search_cache[cache_key]
- self._search_cache[cache_key] = cached
- if cached is None:
- # Built outside the lock: a concurrent miss for the same scope
- # transiently builds a duplicate, which beats serializing every
- # search behind a multi-second BLOB read.
- cached = records.get_embeddings(items, self._model_id)
- with self._search_cache_lock:
- while len(self._search_cache) >= 2:
- self._search_cache.pop(next(iter(self._search_cache)))
- self._search_cache[cache_key] = cached
-
- return cached
+ # Last completion wins, possibly an older gallery snapshot. Keep its own fingerprint
+ # so a later request rechecks visibility and misses rather than serving stale rows.
+ previous = self._search_cache.pop(cache_key, None)
+ if previous is not None:
+ self._search_cache_bytes -= previous[2].nbytes
+ # Empty results must not accumulate owners that cost nothing against the budget.
+ if matrix_bytes:
+ while (
+ len(self._search_cache) >= 2
+ and self._search_cache_bytes + matrix_bytes > _SEARCH_CACHE_MAX_BYTES
+ ):
+ _, _, evicted_matrix = self._search_cache.pop(next(iter(self._search_cache)))
+ self._search_cache_bytes -= evicted_matrix.nbytes
+ self._search_cache[cache_key] = (fingerprint, found_items, matrix)
+ self._search_cache_bytes += matrix_bytes
+
+ return found_items, matrix
def search_similar(
self,
@@ -1034,6 +1048,7 @@ class ImageIndexService(ImageIndexServiceBase):
self._vocab_invalidate_requested.clear()
with self._search_cache_lock:
self._search_cache.clear()
+ self._search_cache_bytes = 0
with self._projection_lock:
self._projection_requests.clear()
self._failed_projection_scopes.clear()
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 3870361406..b09bb428d1 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -9,13 +9,14 @@ import weakref
from contextlib import nullcontext
from pathlib import Path
from types import SimpleNamespace
-from typing import Callable
+from typing import Callable, Iterator
from unittest.mock import patch
import numpy as np
import pytest
import torch
from PIL import Image
+from sqlalchemy import event
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.events.events_common import ImageIndexStatusEvent, ImageIndexUpdatedEvent
@@ -689,6 +690,8 @@ def test_deleted_encoder_becomes_unavailable_and_reinstall_resumes_without_dupli
service._cpu_model = object()
service._text_encoder_failure = "previous installation was incomplete"
service._vocab_cache = (["old"], np.ones((1, DIM), dtype=np.float32))
+ assert service.get_accessible_embeddings("system")[0] == imgs("before.png")
+ assert service._search_cache_bytes == 32
installed.clear()
service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
@@ -703,6 +706,8 @@ def test_deleted_encoder_becomes_unavailable_and_reinstall_resumes_without_dupli
assert service._processor is None
assert service._cpu_model is None
assert service._vocab_cache is None
+ assert service._search_cache == {}
+ assert service._search_cache_bytes == 0
_save_image(image_records, "during.png")
images_service._on_changed(_dto_for(image_records, "during.png"))
@@ -719,6 +724,8 @@ def test_deleted_encoder_becomes_unavailable_and_reinstall_resumes_without_dupli
assert service._cpu_model is None
assert service._text_encoder_failure is None
assert service._vocab_cache is None
+ assert service.get_accessible_embeddings("system")[0] == imgs("before.png", "during.png")
+ assert service._search_cache_bytes == 64
finally:
service.stop()
@@ -2967,6 +2974,464 @@ def test_search_similar_returns_empty_when_not_running(service: ImageIndexServic
assert service.search_similar(None, np.ones(DIM, dtype=np.float32), limit=5) == []
+def search_scope_users(
+ db: Database,
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+) -> tuple[str, str]:
+ """Two non-admin owners and admin ALL, with 32, 96 and 128 decoded bytes respectively."""
+ from invokeai.app.services.users.users_common import UserCreateRequest
+ from invokeai.app.services.users.users_default import UserService
+
+ users = UserService(db)
+ owner = users.create(
+ UserCreateRequest(email="[email protected]", display_name="Owner", password="TestPass123", is_admin=False)
+ )
+ other = users.create(
+ UserCreateRequest(email="[email protected]", display_name="Cache", password="TestPass123", is_admin=False)
+ )
+ assert owner.is_admin is False
+ assert other.is_admin is False
+ # Seed every embedding before the worker starts, so backfill cannot overwrite the one-hot vectors.
+ for axis, name in enumerate(("a.png", "b.png", "c.png", "d.png")):
+ image_records.save(
+ image_name=name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=16,
+ height=16,
+ has_workflow=False,
+ user_id=owner.user_id if axis == 0 else other.user_id,
+ )
+ vector = np.zeros(DIM, dtype=np.float32)
+ vector[axis] = 1
+ index_records.upsert_embedding(IndexedItem("image", name), MODEL_ID, vector)
+ backfill_done = threading.Event()
+ list_unembedded_items = index_records.list_unembedded_items
+
+ def empty_backfill(model_id: str, limit: int) -> list[IndexedItem]:
+ rows = list_unembedded_items(model_id, limit)
+ assert rows == []
+ backfill_done.set()
+ return rows
+
+ with patch.object(index_records, "list_unembedded_items", side_effect=empty_backfill):
+ service.start(_make_invoker(images_service, index_records))
+ assert backfill_done.wait(timeout=10)
+ return owner.user_id, other.user_id
+
+
+def embedding_blob_selects(db: Database) -> Iterator[list[str]]:
+ selects: list[str] = []
+
+ def record_select(conn, cursor, statement, parameters, context, executemany):
+ if statement.lstrip().upper().startswith("SELECT") and "image_embeddings.embedding" in statement:
+ selects.append(statement)
+
+ event.listen(db.engine, "before_cursor_execute", record_select)
+ try:
+ yield selects
+ finally:
+ event.remove(db.engine, "before_cursor_execute", record_select)
+
+
[email protected]("all_images", [False, True], ids=["owner", "all"])
+def test_search_cache_retires_previous_gallery_versions_during_growth(
+ all_images: bool,
+ search_scope_users: tuple[str, str],
+ image_records: ImageRecordStorage,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ embedding_blob_selects: list[str],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 4096)
+ service.get_accessible_embeddings(other)
+ user_id = None if all_images else owner
+ names = ["a.png", "b.png", "c.png", "d.png"] if all_images else ["a.png"]
+ axes = [0, 1, 2, 3] if all_images else [0]
+ query = np.arange(DIM, 0, -1, dtype=np.float32)
+ for refresh in range(4):
+ if refresh:
+ # Grow the real gallery AFTER startup and each preceding refresh, as new embeddings land.
+ name = f"new-{refresh}.png"
+ axis = refresh + 3
+ image_records.save(
+ image_name=name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=16,
+ height=16,
+ has_workflow=False,
+ user_id=owner,
+ )
+ index_records.upsert_embedding(IndexedItem("image", name), MODEL_ID, np.eye(DIM, dtype=np.float32)[axis])
+ names.append(name)
+ axes.append(axis)
+ items, matrix = service.get_accessible_embeddings(user_id)
+ assert items == imgs(*names)
+ np.testing.assert_array_equal(matrix, np.eye(DIM, dtype=np.float32)[axes])
+ assert service.search_similar(user_id, query, 10) == [
+ (IndexedItem("image", name), float(DIM - axis)) for name, axis in zip(names, axes, strict=True)
+ ]
+ assert service.get_accessible_embeddings(other)[0] == imgs("b.png", "c.png", "d.png")
+ assert len(embedding_blob_selects) == refresh + 2
+ assert service._search_cache_bytes == 96 + len(names) * 32
+ assert sum(entry[-1].nbytes for entry in service._search_cache.values()) == service._search_cache_bytes
+ assert len(service._search_cache) == 2
+
+
[email protected]("all_images", [False, True], ids=["owner", "all"])
+def test_search_cache_empty_gallery_retires_its_previous_matrix(
+ all_images: bool,
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ embedding_blob_selects: list[str],
+) -> None:
+ owner, other = search_scope_users
+ service.get_accessible_embeddings(other)
+ user_id = None if all_images else owner
+ previous_items, _ = service.get_accessible_embeddings(user_id)
+ for item in previous_items:
+ index_records.delete_embedding(item)
+ for _ in range(2):
+ items, matrix = service.get_accessible_embeddings(user_id)
+ assert items == []
+ assert matrix.shape == (0, 0)
+ assert service.search_similar(user_id, _unit_vec(), 10) == []
+ assert len(embedding_blob_selects) == 2
+ assert len(service._search_cache) == 1
+ assert service._search_cache_bytes == 96
+ assert sum(entry[-1].nbytes for entry in service._search_cache.values()) == 96
+
+
+def test_search_cache_reuses_three_scopes_within_byte_budget(
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ # All three differently sized matrices fit exactly; entry count must not evict them.
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 256)
+ query = np.array([1, 0.5, -0.5, -1, 0, 0, 0, 0], dtype=np.float32)
+ cases = [
+ (owner, imgs("a.png"), [[1, 0, 0, 0, 0, 0, 0, 0]], [1]),
+ (
+ other,
+ imgs("b.png", "c.png", "d.png"),
+ [[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0]],
+ [0.5, -0.5, -1],
+ ),
+ (
+ None,
+ imgs("a.png", "b.png", "c.png", "d.png"),
+ [
+ [1, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0],
+ ],
+ [1, 0.5, -0.5, -1],
+ ),
+ ]
+ with patch.object(index_records, "get_embeddings", wraps=index_records.get_embeddings) as reads:
+ for cycle in range(4):
+ for user_id, expected_items, expected_matrix, expected_scores in cases:
+ items, matrix = service.get_accessible_embeddings(user_id)
+ assert items == expected_items
+ np.testing.assert_array_equal(matrix, np.array(expected_matrix, dtype=np.float32))
+ results = service.search_similar(user_id, query, limit=10)
+ assert [item for item, _ in results] == expected_items
+ assert [score for _, score in results] == pytest.approx(expected_scores)
+ if cycle == 0:
+ assert reads.call_count == 3
+ assert reads.call_count == 3, "warmed scopes within the byte budget must not re-read embedding BLOBs"
+
+
[email protected]("budget", [128, 160])
+def test_search_cache_evicts_lru_by_matrix_bytes(
+ budget: int,
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", budget)
+ with patch.object(index_records, "get_embeddings", wraps=index_records.get_embeddings) as reads:
+ service.get_accessible_embeddings(owner) # 32 bytes
+ service.get_accessible_embeddings(other) # 96 bytes
+ assert service._search_cache_bytes == 128
+ service.get_accessible_embeddings(owner) # Touch: the other owner is now LRU.
+ assert reads.call_count == 2
+ service.get_accessible_embeddings(None) # 128 bytes: evicts the other owner, keeps the touched one.
+ assert reads.call_count == 3
+ assert service._search_cache_bytes == 160
+ assert sum(entry[-1].nbytes for entry in service._search_cache.values()) == 160
+ service.get_accessible_embeddings(owner)
+ assert reads.call_count == 3
+ service.get_accessible_embeddings(other) # Admin ALL is now LRU.
+ assert reads.call_count == 4
+ assert service._search_cache_bytes == 128
+ assert sum(entry[-1].nbytes for entry in service._search_cache.values()) == 128
+
+
+def test_search_cache_alternating_scopes_over_budget_do_not_evict_each_other(
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ embedding_blob_selects: list[str],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 96)
+ with patch.object(index_records, "get_embeddings", wraps=index_records.get_embeddings) as reads:
+ for _ in range(3):
+ assert service.get_accessible_embeddings(owner)[0] == imgs("a.png")
+ items, matrix = service.get_accessible_embeddings(None) # 128 bytes: over budget on its own.
+ assert items == imgs("a.png", "b.png", "c.png", "d.png")
+ np.testing.assert_array_equal(matrix, np.eye(DIM, dtype=np.float32)[:4])
+ assert service.search_similar(None, np.arange(DIM, 0, -1, dtype=np.float32), 10) == list(
+ zip(imgs("a.png", "b.png", "c.png", "d.png"), [8, 7, 6, 5], strict=True)
+ )
+ assert service._search_cache_bytes == 160
+ assert reads.call_count == len(embedding_blob_selects) == 2
+ # A third scope replaces the LRU one, so at most two stay over budget.
+ assert service.get_accessible_embeddings(other)[0] == imgs("b.png", "c.png", "d.png")
+ assert reads.call_count == 3
+ assert service._search_cache_bytes == 224
+ assert len(service._search_cache) == 2
+
+
+def test_search_cache_evicts_several_scopes_down_to_the_two_most_recent(
+ db: Database,
+ search_scope_users: tuple[str, str],
+ image_records: ImageRecordStorage,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from invokeai.app.services.users.users_common import UserCreateRequest
+ from invokeai.app.services.users.users_default import UserService
+
+ owner, other = search_scope_users
+ third = UserService(db).create(
+ UserCreateRequest(email="[email protected]", display_name="Third", password="TestPass123", is_admin=False)
+ )
+ image_records.save(
+ image_name="e.png",
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=16,
+ height=16,
+ has_workflow=False,
+ user_id=third.user_id,
+ )
+ index_records.upsert_embedding(imgs("e.png")[0], MODEL_ID, np.eye(DIM, dtype=np.float32)[4])
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 160)
+ with patch.object(index_records, "get_embeddings", wraps=index_records.get_embeddings) as reads:
+ for user_id in (owner, third.user_id, other): # 32 + 32 + 96 bytes fit exactly.
+ service.get_accessible_embeddings(user_id)
+ assert service._search_cache_bytes == 160
+ assert len(service._search_cache) == 3
+ service.get_accessible_embeddings(None) # 160 bytes: both older small scopes go.
+ assert reads.call_count == 4
+ assert service._search_cache_bytes == 256
+ service.get_accessible_embeddings(other)
+ service.get_accessible_embeddings(None)
+ assert reads.call_count == 4
+ service.get_accessible_embeddings(third.user_id)
+ assert reads.call_count == 5
+
+
+def test_search_cache_does_not_retain_empty_matrices_after_embeddings_disappear(
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ get_embeddings = index_records.get_embeddings
+
+ def delete_before_read(items, model_id):
+ # The visibility query succeeded, but its rows disappear before the BLOB read.
+ for item in items:
+ index_records.delete_embedding(item)
+ return get_embeddings(items, model_id)
+
+ monkeypatch.setattr(index_records, "get_embeddings", delete_before_read)
+ for user_id in (owner, other, None):
+ items, matrix = service.get_accessible_embeddings(user_id)
+ assert items == []
+ assert matrix.shape == (0, 0)
+ assert service._search_cache == {}
+ assert service._search_cache_bytes == 0
+
+
[email protected]("newer_finishes_first", [False, True])
+def test_search_cache_out_of_order_gallery_fills_keep_one_version_per_owner(
+ newer_finishes_first: bool,
+ search_scope_users: tuple[str, str],
+ image_records: ImageRecordStorage,
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ embedding_blob_selects: list[str],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from concurrent.futures import ThreadPoolExecutor
+
+ owner, other = search_scope_users
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 256)
+ service.get_accessible_embeddings(other)
+ entered = [threading.Event(), threading.Event()]
+ release = [threading.Event(), threading.Event()]
+ get_embeddings = index_records.get_embeddings
+ calls = 0
+
+ def read_then_wait(items, model_id):
+ nonlocal calls
+ # Submissions are gated by entered, so the first two reads have a deterministic order.
+ index = calls
+ calls += 1
+ result = get_embeddings(items, model_id)
+ if index < 2:
+ entered[index].set()
+ assert release[index].wait(timeout=10)
+ return result
+
+ with patch.object(index_records, "get_embeddings", side_effect=read_then_wait):
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ try:
+ older = pool.submit(service.get_accessible_embeddings, owner)
+ assert entered[0].wait(timeout=10)
+ image_records.save(
+ image_name="new.png",
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=16,
+ height=16,
+ has_workflow=False,
+ user_id=owner,
+ )
+ index_records.upsert_embedding(imgs("new.png")[0], MODEL_ID, np.eye(DIM, dtype=np.float32)[4])
+ newer = pool.submit(service.get_accessible_embeddings, owner)
+ assert entered[1].wait(timeout=10)
+ futures = [older, newer]
+ for index in [1, 0] if newer_finishes_first else [0, 1]:
+ release[index].set()
+ items, matrix = futures[index].result(timeout=10)
+ assert items == (imgs("a.png", "new.png") if index else imgs("a.png"))
+ np.testing.assert_array_equal(matrix, np.eye(DIM, dtype=np.float32)[[0, 4] if index else [0]])
+ assert len(service._search_cache) == 2
+ assert service._search_cache_bytes == 96 + (64 if index else 32)
+ assert (
+ sum(entry[-1].nbytes for entry in service._search_cache.values()) == service._search_cache_bytes
+ )
+ finally:
+ for pending in release:
+ pending.set()
+ # A late old fill may replace the newer matrix, but must keep its OLD fingerprint:
+ # the next current-gallery request must never hit the old rows as if they were current.
+ for _ in range(2):
+ items, matrix = service.get_accessible_embeddings(owner)
+ assert items == imgs("a.png", "new.png")
+ np.testing.assert_array_equal(matrix, np.eye(DIM, dtype=np.float32)[[0, 4]])
+ assert service._search_cache_bytes == 160
+ assert service.get_accessible_embeddings(other)[0] == imgs("b.png", "c.png", "d.png")
+ assert len(embedding_blob_selects) == (4 if newer_finishes_first else 3)
+
+
+def test_search_cache_concurrent_same_scope_fills_are_charged_once(
+ search_scope_users: tuple[str, str],
+ index_records: ImageIndexRecords,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ from concurrent.futures import ThreadPoolExecutor
+
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 128)
+ service.get_accessible_embeddings(owner)
+ entered = [threading.Event(), threading.Event()]
+ release = [threading.Event(), threading.Event()]
+ calls_lock = threading.Lock()
+ calls = 0
+ get_embeddings = index_records.get_embeddings
+
+ def read_then_wait(items, model_id):
+ nonlocal calls
+ with calls_lock:
+ index = calls
+ calls += 1
+ result = get_embeddings(items, model_id)
+ entered[index].set()
+ assert release[index].wait(timeout=10)
+ return result
+
+ with patch.object(index_records, "get_embeddings", side_effect=read_then_wait) as reads:
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ try:
+ first = pool.submit(service.get_accessible_embeddings, other)
+ assert entered[0].wait(timeout=10)
+ second = pool.submit(service.get_accessible_embeddings, other)
+ assert entered[1].wait(timeout=10)
+ release[0].set()
+ first_result = first.result(timeout=10)
+ release[1].set()
+ second_result = second.result(timeout=10)
+ finally:
+ for event in release:
+ event.set()
+ assert first_result[0] == second_result[0] == imgs("b.png", "c.png", "d.png")
+ np.testing.assert_array_equal(first_result[1], second_result[1])
+ assert first_result[1].nbytes == second_result[1].nbytes == 96
+ assert len(service._search_cache) == 2
+ assert service._search_cache_bytes == 128
+ assert sum(entry[-1].nbytes for entry in service._search_cache.values()) == 128
+ service.get_accessible_embeddings(owner)
+ service.get_accessible_embeddings(other)
+ assert reads.call_count == 2
+
+
+def test_search_cache_rechecks_board_visibility_with_multiple_cached_scopes(
+ search_scope_users: tuple[str, str],
+ db: Database,
+ service: ImageIndexService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owner, other = search_scope_users
+ from invokeai.app.services.board_access.board_access_common import GeneralAccess
+ from invokeai.app.services.board_image_records.board_image_records_default import BoardImageRecordStorage
+ from invokeai.app.services.board_records.board_records_common import BoardChanges
+ from invokeai.app.services.board_records.board_records_default import BoardRecordStorage
+
+ monkeypatch.setattr(image_index_default, "_SEARCH_CACHE_MAX_BYTES", 1024)
+ boards = BoardRecordStorage(db)
+ board = boards.save("Private", user_id=other)
+ BoardImageRecordStorage(db).add_image_to_board(board.board_id, "b.png")
+ query = np.array([1, 0.5, -0.5, -1, 0, 0, 0, 0], dtype=np.float32)
+ a, b, c, d = imgs("a.png", "b.png", "c.png", "d.png")
+ assert service.search_similar(owner, query, 10) == [(a, 1)]
+ assert service.search_similar(other, query, 10) == [(b, 0.5), (c, -0.5), (d, -1)]
+ assert service.search_similar(None, query, 10) == [(a, 1), (b, 0.5), (c, -0.5), (d, -1)]
+ boards.update(board.board_id, BoardChanges(general_access=GeneralAccess.Viewer))
+ assert service.search_similar(owner, query, 10) == [(a, 1), (b, 0.5)]
+ boards.update(board.board_id, BoardChanges(general_access=GeneralAccess.Restricted))
+ assert service.search_similar(owner, query, 10) == [(a, 1)]
+ boards.update(board.board_id, BoardChanges(archived=True))
+ assert service.search_similar(other, query, 10) == [(c, -0.5), (d, -1)]
+ assert service.search_similar(None, query, 10) == [(a, 1), (c, -0.5), (d, -1)]
+ boards.update(board.board_id, BoardChanges(archived=False))
+ assert service.search_similar(None, query, 10) == [(a, 1), (b, 0.5), (c, -0.5), (d, -1)]
+
+
def test_search_similar_scopes_to_the_requesting_user(
db: Database,
image_records: ImageRecordStorage,