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: lock the global torch patch, guard query vectors, and bound the URL fetch

Lincoln Stein76be5befa2db
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index c3178f5e82..9d1eacb838 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel, Field
from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api.routers._access import assert_image_read_access
+from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
from invokeai.app.services.image_index.image_index_common import ImageIndexStatus
from invokeai.app.services.image_index.projection import (
@@ -22,6 +23,7 @@ from invokeai.app.services.image_index.projection import (
resolve_cluster_eps,
scope_hash,
)
+from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException
image_map_router = APIRouter(prefix="/v1/image_map", tags=["image_map"])
@@ -387,16 +389,40 @@ async def search_image_map(
# embed the stored file on demand for this one query.
def embed_from_file() -> np.ndarray:
pil = services.images.get_pil_image(image_name)
+ # Capped exactly as the uploaded/downloaded path is: the encoder
+ # downscales to ~224px either way, and convert("RGB") on a large
+ # stored image materializes hundreds of MB on a request thread.
+ # This branch is the *normal* one for such images, since assets
+ # and intermediates are never indexed.
+ if pil.width * pil.height > MAX_SEARCH_IMAGE_PIXELS:
+ raise HTTPException(
+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
+ detail="The reference image has too many pixels",
+ )
return services.image_index.embed_image(pil)
try:
query_embedding = await asyncio.to_thread(embed_from_file)
- except Exception:
- services.logger.warning(f"Image search: failed to embed '{image_name}' on demand", exc_info=True)
+ except HTTPException:
+ raise
+ except (ImageFileNotFoundException, ImageRecordNotFoundException, OSError):
+ # The stored file is missing or undecodable — the only failure
+ # here that is really about this image. Both record and file
+ # exceptions are plain Exceptions rather than OSError, so they
+ # have to be named; PIL's decode failures are OSError subclasses.
+ services.logger.warning(f"Image search: cannot read '{image_name}' for on-demand embed", exc_info=True)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="This image could not be embedded for search (its file may be missing)",
)
+ except Exception:
+ # An encoder fault, a stopped index, an OOM. Reporting these as
+ # "file may be missing" sent anyone debugging to the wrong place.
+ services.logger.error(f"Image search: failed to embed '{image_name}' on demand", exc_info=True)
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="This image could not be embedded for search",
+ )
results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)
return ImageMapSearchResponse(
@@ -466,10 +492,31 @@ def _download_search_image(url: str) -> bytes:
import requests
deadline = time.monotonic() + _URL_TOTAL_DEADLINE_SECONDS
+
+ def _remaining() -> float:
+ """Budget left, as a positive number; raises once it is gone.
+
+ Checked before each hop and used as the per-request timeout, so the deadline bounds the
+ whole exchange rather than only the body. Without it the connect and read timeouts apply
+ afresh to every redirect, and a server that stalls each of the allowed hops before sending
+ a byte holds a thread for minutes — uninterruptibly, since this runs under
+ `asyncio.to_thread` on the executor that also serves embedding and search.
+ """
+ left = deadline - time.monotonic()
+
+ if left <= 0:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="The image download took too long",
+ )
+
+ return left
+
try:
for _ in range(_URL_MAX_REDIRECTS + 1):
_assert_url_host_allowed(url)
- with requests.get(url, stream=True, timeout=_URL_TIMEOUT_SECONDS, allow_redirects=False) as response:
+ hop_timeout = min(_URL_TIMEOUT_SECONDS, _remaining())
+ with requests.get(url, stream=True, timeout=hop_timeout, allow_redirects=False) as response:
if response.is_redirect:
location = response.headers.get("location")
if not location:
@@ -486,11 +533,7 @@ def _download_search_image(url: str) -> bytes:
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="The reference image is too large",
)
- if time.monotonic() > deadline:
- raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
- detail="The image download took too long",
- )
+ _remaining()
chunks.append(chunk)
return b"".join(chunks)
except HTTPException:
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index a90f5eab8c..0132a6e946 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -13,6 +13,7 @@ from invokeai.app.services.image_index.projection import compute_umap, projectio
from invokeai.app.services.image_records.image_records_common import ImageCategory
from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.load.optimizations import skip_torch_weight_init
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.util.devices import TorchDevice
@@ -52,6 +53,26 @@ _MAX_ATTEMPTS = 3
_MAX_BACKOFF_SECONDS = 60.0
+def _normalize_query_vector(vector: np.ndarray) -> np.ndarray:
+ """L2-normalize one query embedding, refusing anything that would poison a search.
+
+ The norm is taken in float64 for the same reason `_process_batch` does it: a float32 sum of
+ squares under/overflows well inside the range these encoders produce.
+
+ A zero or non-finite norm is raised rather than passed through. The indexer can afford to
+ drop such a row; a query cannot. Dividing by a non-finite norm gives a NaN vector, every
+ similarity it takes part in is NaN, `argpartition` then returns arbitrary rows, and FastAPI
+ serializes the NaN scores as bare `NaN` — which is not valid JSON, so the browser fails to
+ parse the response instead of showing an empty result.
+ """
+ norm = float(np.linalg.norm(vector.astype(np.float64)))
+
+ if not np.isfinite(norm) or norm == 0.0:
+ raise RuntimeError("The embedding model returned a degenerate vector for this query")
+
+ return (vector / norm).astype(EMBEDDING_DTYPE)
+
+
def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:
"""Run one tiny scaled_dot_product_attention call while the process is still single-threaded.
@@ -179,8 +200,7 @@ class ImageIndexService(ImageIndexServiceBase):
matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)
if matrix.ndim != 2 or matrix.shape[0] != 1:
raise RuntimeError(f"Encoder returned shape {matrix.shape}; expected (1, D)")
- norm = float(np.linalg.norm(matrix[0]))
- return matrix[0] / norm if norm > 0 else matrix[0]
+ return _normalize_query_vector(matrix[0])
def embed_text(self, text: str) -> np.ndarray:
if self._model_id is None:
@@ -196,8 +216,7 @@ class ImageIndexService(ImageIndexServiceBase):
outputs = model(**inputs)
embedding = outputs.pooler_output[0] if is_siglip else outputs.text_embeds[0]
vector = embedding.float().cpu().numpy()
- norm = np.linalg.norm(vector)
- return vector / norm if norm > 0 else vector
+ return _normalize_query_vector(vector)
def _get_text_encoder(self) -> tuple[Any, Any, bool]:
with self._text_encoder_lock:
@@ -212,10 +231,16 @@ class ImageIndexService(ImageIndexServiceBase):
try:
tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
text_cls = SiglipTextModel if is_siglip else CLIPTextModelWithProjection
- # skip_torch_weight_init serializes torch module construction
- # process-wide; an unserialized from_pretrained racing another
- # thread's model load leaks meta-device parameters.
- with skip_torch_weight_init():
+ # skip_torch_weight_init serializes nothing: it monkey-patches
+ # torch.nn.Linear/_ConvNd/Embedding.reset_parameters process-wide
+ # and restores whatever it saw on entry. Two threads inside it at
+ # once means the second saves the _no_op, and whoever leaves last
+ # restores _no_op for the life of the process — every layer built
+ # afterwards silently skips weight init. MODEL_LOAD_LOCK is what
+ # makes it safe, and also excludes the concurrent VRAM move whose
+ # load_state_dict(assign=True) would hijack these parameters onto
+ # the meta device. Same reasoning as ModelLoader._load_and_cache.
+ with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
model = text_cls.from_pretrained(model_path, local_files_only=True)
except Exception as e:
# Vision-only or partial installs (e.g. the IP-Adapter image
@@ -1073,9 +1098,9 @@ class ImageIndexService(ImageIndexServiceBase):
if self._model_config.type is ModelType.SigLIP
else CLIPVisionModelWithProjection
)
- # skip_torch_weight_init serializes torch module construction
- # process-wide (see _get_text_encoder).
- with skip_torch_weight_init():
+ # Process-global patch, so it needs the process-global lock —
+ # see _get_text_encoder for what goes wrong without it.
+ with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
model = model_cls.from_pretrained(model_path, local_files_only=True)
model.eval()
self._cpu_model = model
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
index 564637e48c..e799cc748a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -26,6 +26,7 @@ import {
galleryItemNamesOptions,
galleryItemsInfiniteOptions,
getGalleryItemListQueries,
+ canonicalizeGalleryItemsFilter,
type GalleryItemsFilter,
} from './queries';
import { invalidateGalleryItems } from './queryCache';
@@ -357,3 +358,64 @@ describe('Gallery item query read model', () => {
await pageRequest.catch(() => undefined);
});
});
+
+describe('canonicalizeGalleryItemsFilter under a semantic query', () => {
+ const reference = { fileId: 'external-1-abc', kind: 'file', label: 'shot.png' } as const;
+
+ it('ignores the controls a ranked result set does not answer to', () => {
+ // The semantic branch sends only the reference, so board, view, order,
+ // starred-first and the date range change nothing about the response.
+ // While they stayed in the key, clicking a board minted a fresh key and
+ // re-ran the search — re-uploading the dropped blob, or making the server
+ // re-download a remote URL, to render byte-identical results.
+ const base = canonicalizeGalleryItemsFilter({
+ boardId: 'board-a',
+ galleryView: 'images',
+ searchTerm: '',
+ semanticQuery: reference,
+ });
+
+ for (const variant of [
+ { boardId: 'board-b' },
+ { galleryView: 'assets' as const },
+ { orderDir: 'ASC' as const },
+ { starredFirst: true },
+ { createdFrom: '2026-01-01' },
+ ]) {
+ expect(
+ canonicalizeGalleryItemsFilter({
+ boardId: 'board-a',
+ galleryView: 'images',
+ searchTerm: '',
+ semanticQuery: reference,
+ ...variant,
+ })
+ ).toEqual(base);
+ }
+ });
+
+ it('still distinguishes one reference from another', () => {
+ const other = canonicalizeGalleryItemsFilter({
+ boardId: 'board-a',
+ galleryView: 'images',
+ searchTerm: '',
+ semanticQuery: { fileId: 'external-2-def', kind: 'file', label: 'shot.png' },
+ });
+
+ expect(other).not.toEqual(
+ canonicalizeGalleryItemsFilter({
+ boardId: 'board-a',
+ galleryView: 'images',
+ searchTerm: '',
+ semanticQuery: reference,
+ })
+ );
+ });
+
+ it('leaves a non-semantic filter keyed on all of its controls', () => {
+ const onBoardA = canonicalizeGalleryItemsFilter({ boardId: 'board-a', galleryView: 'images', searchTerm: '' });
+ const onBoardB = canonicalizeGalleryItemsFilter({ boardId: 'board-b', galleryView: 'images', searchTerm: '' });
+
+ expect(onBoardA).not.toEqual(onBoardB);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index e7f1816da4..77f3cb04b2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -101,16 +101,40 @@ const canonicalizeBoardsQuery = (query: GalleryBoardsQuery): CanonicalGalleryBoa
orderDir: query.orderDir ?? 'DESC',
});
-export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): CanonicalGalleryItemsFilter => ({
- boardId: filter.boardId,
- ...(filter.createdFrom ? { createdFrom: filter.createdFrom } : {}),
- ...(filter.createdTo ? { createdTo: filter.createdTo } : {}),
- galleryView: filter.galleryView,
- orderDir: filter.orderDir ?? 'DESC',
- searchTerm: filter.searchTerm.trim(),
- ...(filter.semanticQuery ? { semantic: toGallerySemanticQuery(filter.semanticQuery) } : {}),
- starredFirst: filter.starredFirst ?? false,
-});
+export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): CanonicalGalleryItemsFilter => {
+ const semantic = filter.semanticQuery ? toGallerySemanticQuery(filter.semanticQuery) : undefined;
+
+ if (semantic) {
+ // A ranked result set answers to the reference alone: the semantic branch
+ // of `galleryItemNamesOptionsForOwner` sends only the query, so board,
+ // view, order, starred-first and the date range change nothing about the
+ // response. Keeping them in the key made clicking a board — or toggling
+ // starred-first, or switching the images/assets tab — mint a fresh key and
+ // re-run the search for byte-identical results, which for a dropped file
+ // means re-uploading the blob and for a URL reference means the server
+ // re-downloads the remote image. Pinned rather than omitted so the shape
+ // stays a `CanonicalGalleryItemsFilter`; the values are never read on this
+ // path, only compared.
+ return {
+ boardId: '',
+ galleryView: 'images',
+ orderDir: 'DESC',
+ searchTerm: '',
+ semantic,
+ starredFirst: false,
+ };
+ }
+
+ return {
+ boardId: filter.boardId,
+ ...(filter.createdFrom ? { createdFrom: filter.createdFrom } : {}),
+ ...(filter.createdTo ? { createdTo: filter.createdTo } : {}),
+ galleryView: filter.galleryView,
+ orderDir: filter.orderDir ?? 'DESC',
+ searchTerm: filter.searchTerm.trim(),
+ starredFirst: filter.starredFirst ?? false,
+ };
+};
const getAccountKey = (owner: AccountScope): GalleryAccountKey => ({
accountId: owner.accountId,
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index 7d9972f32c..8ac63116cb 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -1,6 +1,7 @@
"""Tests for the /v1/image_map endpoints: serving, staleness, and user scoping."""
import logging
+from types import SimpleNamespace
import numpy as np
import pytest
@@ -760,12 +761,70 @@ def test_image_search_embeds_unindexed_reference_on_demand(
assert [r["image_name"] for r in body["results"]] == ["a.png"]
-def test_image_search_unembeddable_reference_is_404(mock_invoker: Invoker, client: TestClient) -> None:
- # No stored embedding AND the file cannot be loaded (mock file store).
+def test_image_search_unembeddable_reference_is_404(monkeypatch, mock_invoker: Invoker, client: TestClient) -> None:
+ # No stored embedding AND the file is gone. Raised explicitly rather than
+ # relying on the mock store's own AttributeError: this asserts the mapping
+ # for the exception a real missing file produces, which is a plain
+ # Exception subclass and not an OSError.
+ from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
+
_save_unembedded_image(mock_invoker, "not-indexed.png")
+
+ def _missing(name):
+ raise ImageFileNotFoundException()
+
+ monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", _missing)
+
assert client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).status_code == 404
+def test_image_search_rejects_an_oversized_stored_reference(
+ monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ # Assets and intermediates are never indexed, so this on-demand branch is the
+ # normal path for exactly the images that can be huge. Without a cap the
+ # convert("RGB") inside embed_image materializes hundreds of MB on a request
+ # thread; the uploaded/downloaded path has always capped, this one had not.
+ from PIL import Image
+
+ from invokeai.app.api.routers.image_map import MAX_SEARCH_IMAGE_PIXELS
+
+ _save_unembedded_image(mock_invoker, "huge.png")
+
+ side = int(MAX_SEARCH_IMAGE_PIXELS**0.5) + 64
+ oversized = SimpleNamespace(width=side, height=side)
+ monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", lambda name: oversized)
+
+ response = client.get("/api/v1/image_map/search", params={"image_name": "huge.png"})
+
+ assert response.status_code == 415
+ # Refused before anything tried to decode it.
+ assert image_index_service.embedded_images == []
+
+ # A reference inside the cap still embeds.
+ monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", lambda name: Image.new("RGB", (4, 4)))
+ assert client.get("/api/v1/image_map/search", params={"image_name": "huge.png"}).status_code == 200
+
+
+def test_image_search_reports_an_encoder_fault_as_a_server_error(
+ monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ # A missing file is a 404, but an encoder fault, a stopped index or an OOM is
+ # ours — reporting those as "its file may be missing" sends whoever is
+ # debugging to the wrong place entirely.
+ from PIL import Image
+
+ _save_unembedded_image(mock_invoker, "not-indexed.png")
+ monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", lambda name: Image.new("RGB", (4, 4)))
+
+ def _boom(pil):
+ raise RuntimeError("The image index is not running")
+
+ monkeypatch.setattr(image_index_service, "embed_image", _boom)
+
+ assert client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).status_code == 500
+
+
def test_search_by_image_upload_returns_ranked_results(
image_index_service: FakeImageIndexService, client: TestClient
) -> None:
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 efb9bedeb8..942d0feb8b 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -1618,3 +1618,59 @@ def test_search_similar_scopes_to_the_requesting_user(
# Admin scope (None) sees both.
admin_names = {name for name, _ in service.search_similar(None, unit(0), limit=10)}
assert admin_names == {"mine.png", "theirs.png"}
+
+
+def test_query_vectors_reject_a_non_finite_embedding(service: ImageIndexService) -> None:
+ # The indexer drops rows whose norm is non-finite because they poison every
+ # similarity they take part in. A query has nothing to drop: dividing anyway
+ # gives an all-NaN vector, then all-NaN scores, arbitrary argpartition
+ # results, and a response body containing bare `NaN` — which is not valid
+ # JSON, so the browser fails to parse it rather than showing no matches.
+ from invokeai.app.services.image_index.image_index_default import _normalize_query_vector
+
+ for bad in (np.inf, np.nan):
+ vector = np.ones(DIM, dtype=np.float32)
+ vector[0] = bad
+
+ with pytest.raises(RuntimeError, match="degenerate"):
+ _normalize_query_vector(vector)
+
+ with pytest.raises(RuntimeError, match="degenerate"):
+ _normalize_query_vector(np.zeros(DIM, dtype=np.float32))
+
+
+def test_query_vectors_normalize_in_float64(service: ImageIndexService) -> None:
+ from invokeai.app.services.image_index.image_index_default import _normalize_query_vector
+
+ # A float32 sum of squares overflows to inf well inside the range these
+ # encoders produce; float64 carries it, so this must normalize rather than
+ # trip the guard above.
+ vector = np.full(DIM, 3.0e19, dtype=np.float32)
+ normalized = _normalize_query_vector(vector)
+
+ assert np.isfinite(normalized).all()
+ assert float(np.linalg.norm(normalized.astype(np.float64))) == pytest.approx(1.0, rel=1e-3)
+
+
+def test_lazy_model_construction_takes_the_process_global_load_lock() -> None:
+ # skip_torch_weight_init monkey-patches torch.nn.*.reset_parameters process-wide
+ # and restores whatever it saw on entry. Two threads inside it at once means the
+ # second saves the no-op, and whoever leaves last restores the no-op forever —
+ # every layer built afterwards silently skips weight init. MODEL_LOAD_LOCK is
+ # what makes it safe, so both lazy loaders must hold it.
+ import inspect
+
+ from invokeai.app.services.image_index import image_index_default
+
+ loaders = (
+ image_index_default.ImageIndexService._get_text_encoder,
+ image_index_default.ImageIndexService._encode_with_model,
+ )
+
+ for fn in loaders:
+ source = inspect.getsource(fn)
+
+ if "skip_torch_weight_init" in source:
+ assert "MODEL_LOAD_LOCK.write_lock()" in source, (
+ f"{fn.__qualname__} patches torch globally without the process-global load lock"
+ )