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): repair image_subfolder_move_items cascade; harden image index records
Lincoln Steinb59d34b5b2d6
diff --git a/invokeai/app/services/image_index/image_index_common.py b/invokeai/app/services/image_index/image_index_common.pyindex 67370f8c2f..fc18607e70 100644--- a/invokeai/app/services/image_index/image_index_common.py+++ b/invokeai/app/services/image_index/image_index_common.py@@ -34,10 +34,39 @@ class ProjectionRecord(BaseModel):def embedding_to_blob(embedding: np.ndarray) -> bytes:- """Serialize a 1-D embedding vector to bytes for BLOB storage."""+ """Serialize a 1-D embedding vector to bytes for BLOB storage.++ The vector is stored as float32; a float64 input is narrowed. Callers are responsible for+ L2-normalizing — this only rejects vectors that could not have been normalized, because a+ non-finite value silently poisons every similarity and projection computation that later+ touches the same batch, with no way to attribute it after the fact.+ """if embedding.ndim != 1:raise ValueError(f"Expected a 1-D embedding, got shape {embedding.shape}")- return np.ascontiguousarray(embedding, dtype=EMBEDDING_DTYPE).tobytes()+ if embedding.shape[0] == 0:+ # A zero-dim row would be stored with dim=0 and then fail every batch it appears in,+ # because `get_embeddings` requires one consistent dim across the result set.+ raise ValueError("Refusing to store a zero-length embedding")+ if not np.issubdtype(embedding.dtype, np.floating):+ # Checked before the cast, which would otherwise raise TypeError (not the documented+ # ValueError) on a structured dtype, and would silently discard the imaginary part of a+ # complex one.+ raise ValueError(f"Expected a floating-point embedding, got dtype {embedding.dtype}")+ with np.errstate(all="ignore"):+ # Narrowing can overflow to inf or underflow to zero; both are reported below as+ # ValueError. Suppressing every flag here keeps that true even if some caller has set+ # `np.seterr(all="raise")` process-wide, which would otherwise surface as+ # FloatingPointError and break this function's documented contract.+ narrowed = np.ascontiguousarray(embedding, dtype=EMBEDDING_DTYPE)+ if not np.isfinite(narrowed).all():+ # Also catches a float64 magnitude that overflows to inf when narrowed to float32.+ raise ValueError("Embedding contains NaN or infinite values")+ if not narrowed.any():+ # All-zero cannot be an L2-normalized vector. It arrives either from an encoder failure+ # or from float64 components that underflowed to zero when narrowed, and it produces+ # NaN in every cosine similarity it takes part in.+ raise ValueError("Refusing to store an all-zero embedding; it cannot be L2-normalized")+ return narrowed.tobytes()def blob_to_embedding(blob: bytes, dim: int) -> np.ndarray:diff --git a/invokeai/app/services/image_index/image_index_records_base.py b/invokeai/app/services/image_index/image_index_records_base.pyindex df074dbcbe..9e55493c89 100644--- a/invokeai/app/services/image_index/image_index_records_base.py+++ b/invokeai/app/services/image_index/image_index_records_base.py@@ -14,6 +14,12 @@ class ImageIndexRecordsBase(ABC):Only "gallery" images are indexed: non-intermediate images in the`general` category.++ Every method here is its own unit of work and must not be called from inside another+ service's open transaction. `SqliteDatabase.transaction()` commits and rolls back the whole+ shared connection rather than using savepoints, so a nested call either commits the outer+ transaction's work early (on success) or discards it (on failure). No caller in the tree+ nests these today; keep it that way."""@abstractmethod@@ -25,6 +31,10 @@ class ImageIndexRecordsBase(ABC):All embeddings stored under one model_id must share the same dim;`get_embeddings` fails on a result set with inconsistent dims.++ Raises ValueError on a vector that could not be a normalized embedding — empty, all+ zero, non-floating dtype, or containing NaN/inf — since any of those poisons every+ batch it later appears in."""pass@@ -38,6 +48,10 @@ class ImageIndexRecordsBase(ABC):A tuple of (found_names, matrix) where matrix has shape(len(found_names), dim) and rows align with found_names. Imageswithout a stored embedding are silently omitted.++ When nothing matches, the matrix is empty with shape (0, 0): no row was read, so+ there is no dim to report. Callers that need the dim must get it elsewhere rather+ than from `matrix.shape[1]`."""pass@@ -72,9 +86,13 @@ class ImageIndexRecordsBase(ABC):def list_accessible_embedded_images(self, user_id: str | None, model_id: str) -> list[str]:"""List embedded images the user can access, sorted by image name.- A user can access their own images, images on shared or public boards,- and images on boards individually shared with them (shared_boards).- Pass user_id=None for the admin scope (every embedded image).+ A user can access their own unboarded images, images on boards they own, images on+ shared or public boards, and images on boards individually shared with them+ (shared_boards). Pass user_id=None for the admin scope.++ Images on an archived board are excluded from every scope, including the admin one,+ matching the gallery's "all" listing. So the admin scope is every embedded image that+ is not archived, not literally every embedded image.The sorted result is the input to the projection scope hash, so theordering here must stay stable.diff --git a/invokeai/app/services/image_index/image_index_records_sqlite.py b/invokeai/app/services/image_index/image_index_records_sqlite.pyindex b4d7da2937..f30316aa07 100644--- a/invokeai/app/services/image_index/image_index_records_sqlite.py+++ b/invokeai/app/services/image_index/image_index_records_sqlite.py@@ -1,5 +1,4 @@import json-import sqlite3import numpy as np@@ -17,6 +16,7 @@ from invokeai.app.services.image_index.image_index_records_base import ImageIndefrom invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.backend.util.logging import InvokeAILogger# SQLite's default variable limit is 999; stay well under it when chunking IN clauses._IN_CLAUSE_CHUNK = 500@@ -35,36 +35,44 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):def __init__(self, db: SqliteDatabase) -> None:super().__init__()self._db = db+ self._logger = InvokeAILogger.get_logger(self.__class__.__name__)def start(self, invoker: Invoker) -> None:self._invoker = invokerdef upsert_embedding(self, image_name: str, model_id: str, embedding: np.ndarray) -> None:blob = embedding_to_blob(embedding)- try:- with self._db.transaction() as cursor:- cursor.execute(- """--sql- INSERT INTO image_embeddings (image_name, model_id, dim, embedding)- VALUES (?, ?, ?, ?)- ON CONFLICT (image_name, model_id)- DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding;- """,- (image_name, model_id, embedding.shape[0], blob),- )- except sqlite3.IntegrityError:- # The image was deleted between being scheduled and embedded (the- # FK parent is gone). Its embedding is pointless; drop it silently.- pass+ with self._db.transaction() as cursor:+ # The image may be deleted between being scheduled and embedded, in which case the+ # embedding is pointless and this is a no-op. `WHERE EXISTS` rather than catching the+ # foreign-key IntegrityError: the guard and the insert are one atomic statement, and+ # no exception is raised on the expected race, so nothing can leave the transaction+ # in a state the caller did not ask for. An IntegrityError from here now means a+ # genuine bug and is allowed to propagate.+ cursor.execute(+ """--sql+ INSERT INTO image_embeddings (image_name, model_id, dim, embedding)+ SELECT ?, ?, ?, ?+ WHERE EXISTS (SELECT 1 FROM images WHERE images.image_name = ?)+ ON CONFLICT (image_name, model_id)+ DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding;+ """,+ (image_name, model_id, embedding.shape[0], blob, image_name),+ )+ if cursor.rowcount == 0:+ self._logger.debug(f"Skipped embedding for missing image {image_name}")def get_embeddings(self, image_names: list[str], model_id: str) -> tuple[list[str], np.ndarray]:# Dedupe while preserving order so repeated input names cannot# double-count rows in downstream projection/similarity math.image_names = list(dict.fromkeys(image_names))found_names: list[str] = []- vectors: list[np.ndarray] = []- dim: int | None = None+ raw: list[tuple[int, bytes]] = []+ # Only the reads happen under the transaction. Deserialization and validation are done+ # afterwards so a malformed row raises outside it: `transaction()` rolls the shared+ # connection back on any exception, which would be an unpleasant side effect of what the+ # caller asked to be a read.with self._db.transaction() as cursor:for start in range(0, len(image_names), _IN_CLAUSE_CHUNK):chunk = image_names[start : start + _IN_CLAUSE_CHUNK]@@ -80,15 +88,18 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):rows = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}# Preserve the caller's ordering within each chunk.for name in chunk:- if name not in rows:- continue- row_dim, blob = rows[name]- if dim is None:- dim = row_dim- elif row_dim != dim:- raise ValueError(f"Inconsistent embedding dims for model {model_id}: found {row_dim} and {dim}")- found_names.append(name)- vectors.append(blob_to_embedding(blob, row_dim))+ if name in rows:+ found_names.append(name)+ raw.append(rows[name])++ dim: int | None = None+ vectors: list[np.ndarray] = []+ for row_dim, blob in raw:+ if dim is None:+ dim = row_dim+ elif row_dim != dim:+ raise ValueError(f"Inconsistent embedding dims for model {model_id}: found {row_dim} and {dim}")+ vectors.append(blob_to_embedding(blob, row_dim))if not vectors:return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)@@ -114,6 +125,10 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):return cursor.rowcountdef list_unembedded_image_names(self, model_id: str, limit: int) -> list[str]:+ if limit < 0:+ # SQLite reads a negative LIMIT as unbounded, which would turn a backfill batch into+ # a full-table load. Fail on a miscomputed limit instead of silently doing that.+ raise ValueError(f"limit must be non-negative, got {limit}")with self._db.transaction() as cursor:cursor.execute(f"""--sql@@ -243,26 +258,27 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):if len(image_names) != coords.shape[0]:raise ValueError(f"Got {len(image_names)} image names but {coords.shape[0]} coordinate rows")blob = coords_to_blob(coords)- try:- with self._db.transaction() as cursor:- cursor.execute(- """--sql- INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)- VALUES (?, ?, ?, ?, ?, ?, ?)- ON CONFLICT (user_id, model_id)- DO UPDATE SET- scope_hash = excluded.scope_hash,- params = excluded.params,- point_count = excluded.point_count,- image_names = excluded.image_names,- coords = excluded.coords;- """,- (user_id, model_id, scope_hash, params, len(image_names), json.dumps(image_names), blob),- )- except sqlite3.IntegrityError:- # The user was deleted while their projection was being computed;- # there is nobody left to serve it to.- pass+ with self._db.transaction() as cursor:+ # No-op if the user was deleted while their projection was being computed; there is+ # nobody left to serve it to. Guarded by `WHERE EXISTS` for the same reason as in+ # `upsert_embedding`.+ cursor.execute(+ """--sql+ INSERT INTO image_projections (user_id, model_id, scope_hash, params, point_count, image_names, coords)+ SELECT ?, ?, ?, ?, ?, ?, ?+ WHERE EXISTS (SELECT 1 FROM users WHERE users.user_id = ?)+ ON CONFLICT (user_id, model_id)+ DO UPDATE SET+ scope_hash = excluded.scope_hash,+ params = excluded.params,+ point_count = excluded.point_count,+ image_names = excluded.image_names,+ coords = excluded.coords;+ """,+ (user_id, model_id, scope_hash, params, len(image_names), json.dumps(image_names), blob, user_id),+ )+ if cursor.rowcount == 0:+ self._logger.debug(f"Skipped projection for missing user {user_id}")def delete_projection(self, user_id: str, model_id: str) -> None:with self._db.transaction() as cursor:diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.pyindex 8861baff90..db353d7c63 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_03_add_image_index_tables.py@@ -11,8 +11,17 @@ each gallery image plus a cached 2D UMAP projection per user:so staleness is detected by re-deriving it, never by bookkeeping.The DDL uses IF NOT EXISTS so databases that acquired these tables from a-pre-rename build of this feature (which shipped them as a numeric migration)-no-op cleanly.+pre-rename build of this feature (commit `b3f46181d`, which shipped them as+`migration_34`) re-run it harmlessly.++That build burned the `migration_34` id, though, and this migration cannot+undo that on its own: the affected database records `migration_34` as applied,+so the migrator skips this fork's real `migration_34` and never creates the+image-subfolder move tables. Repairing that is+`migration_2026_08_08_repair_image_subfolder_move_tables`, which has to be a+separate migration because it recreates tables this one has no business+owning. Do not weaken that migration on the assumption that this one covers+the case — it does not."""import sqlite3diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_08_repair_image_subfolder_move_tables.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_08_repair_image_subfolder_move_tables.pynew file mode 100644index 0000000000..37b1f140d9--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_08_repair_image_subfolder_move_tables.py@@ -0,0 +1,183 @@+"""Repair `image_subfolder_move_items` on databases that need it, for two independent reasons.++**1. The missing `ON DELETE CASCADE`.**++`migration_34` originally declared `image_name TEXT NOT NULL REFERENCES images(image_name)` with+no `ON DELETE` action, i.e. `NO ACTION`. Move items are an audit trail: they are inserted when a+subfolder move runs and updated to `committed`, but nothing ever deletes them. Foreign keys are+enforced on the app connection (`SqliteDatabase.__init__`), so a `NO ACTION` FK pointing at a row+that is never cleaned up permanently blocks `DELETE FROM images` for every image that has ever+been through a move. Any install running a non-`flat` `image_subfolder_strategy` could not delete+those images, and `invokeai-db-maintenance --operation clean` could not clean them either.++`migration_34`'s DDL now carries the cascade, which fixes freshly-created databases. This+migration rebuilds the table on databases that already have the cascade-less version. SQLite+cannot `ALTER` a foreign key, so the table must be recreated and the rows copied across.++One case does get worse, and it is the lesser evil rather than a clean win. Deleting an image+while a move job is mid-flight — file already relocated, `images.image_subfolder` not yet+updated — used to fail with the same IntegrityError; now it succeeds, the cascade drops the+item row, and the relocated file is left on disk with nothing referencing it. Image deletion is+not gated on an active job (`_has_active_job_for_image` is consulted only when planning). That+narrow leak is preferable to images that can never be deleted at all, but it is the reason not+to describe move items as a pure audit trail: the cascade does delete them.++**2. The burned `migration_34` slot.**++A pre-rename build of the image-map feature (commit `b3f46181d`) shipped the image index tables+as a numeric `migration_34`, colliding with this fork's `migration_34`. A database opened by that+build records `migration_34` as applied, so the migrator skips the real one forever and the move+tables are never created — the app then fails at startup in `ImageMoveService.startup_recovery()`+with `no such table: image_subfolder_move_jobs`.++This is the same failure mode, and the same remedy, as+`migration_2026_07_30_repair_projects_table`: a dated id cannot collide, so this migration runs+exactly once on every database and creates whatever is missing. The `CREATE TABLE` statements+below are copies of `migration_34`'s with the cascade added — keep the two in sync.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration++_CREATE_JOBS_TABLE = """--sql+CREATE TABLE IF NOT EXISTS image_subfolder_move_jobs (+ id INTEGER PRIMARY KEY,+ state TEXT NOT NULL CHECK (+ state IN ('planned', 'moving', 'moved', 'committed', 'error')+ ),+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ error_message TEXT+);+"""++# Column list in table order, used to build both the CREATE and the copying INSERT/SELECT.+_ITEMS_COLUMNS = [+ "job_id",+ "image_name",+ "old_subfolder",+ "new_subfolder",+ "is_intermediate",+ "old_path",+ "new_path",+ "old_thumbnail_path",+ "new_thumbnail_path",+ "state",+ "error_message",+]++# Identical to migration_34's definition, except `image_name` carries ON DELETE CASCADE.+_ITEMS_TABLE_BODY = """+ job_id INTEGER NOT NULL REFERENCES image_subfolder_move_jobs(id),+ image_name TEXT NOT NULL REFERENCES images(image_name) ON DELETE CASCADE,+ old_subfolder TEXT NOT NULL,+ new_subfolder TEXT NOT NULL,+ is_intermediate BOOLEAN NOT NULL DEFAULT FALSE,+ old_path TEXT,+ new_path TEXT,+ old_thumbnail_path TEXT,+ new_thumbnail_path TEXT,+ state TEXT NOT NULL CHECK (+ state IN ('planned', 'moved', 'committed', 'error')+ ),+ error_message TEXT,+ PRIMARY KEY (job_id, image_name)+"""+++class RepairImageSubfolderMoveTablesCallback:+ def __call__(self, cursor: sqlite3.Cursor) -> None:+ self._create_missing_tables(cursor)+ if self._items_fk_is_missing_cascade(cursor):+ self._rebuild_items_table(cursor)++ def _create_missing_tables(self, cursor: sqlite3.Cursor) -> None:+ """Create the move tables if the burned `migration_34` slot meant they never were."""+ cursor.execute(_CREATE_JOBS_TABLE)+ cursor.execute(f"CREATE TABLE IF NOT EXISTS image_subfolder_move_items ({_ITEMS_TABLE_BODY});")+ self._create_items_indexes(cursor)+ cursor.execute(+ """--sql+ CREATE TRIGGER IF NOT EXISTS tg_image_subfolder_move_jobs_updated_at+ AFTER UPDATE+ ON image_subfolder_move_jobs FOR EACH ROW+ BEGIN+ UPDATE image_subfolder_move_jobs+ SET updated_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')+ WHERE id = old.id;+ END;+ """+ )++ def _create_items_indexes(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_image_subfolder_move_items_job_state+ ON image_subfolder_move_items(job_id, state);+ """+ )+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_image_subfolder_move_items_image_name+ ON image_subfolder_move_items(image_name);+ """+ )++ def _items_fk_is_missing_cascade(self, cursor: sqlite3.Cursor) -> bool:+ """True if the `images` foreign key exists but does not cascade deletes."""+ cursor.execute("PRAGMA foreign_key_list(image_subfolder_move_items);")+ # Row shape: (id, seq, table, from, to, on_update, on_delete, match)+ return any(row[2] == "images" and row[6] != "CASCADE" for row in cursor.fetchall())++ def _rebuild_items_table(self, cursor: sqlite3.Cursor) -> None:+ """Recreate the table with the cascading FK and copy the rows across.++ SQLite cannot alter a foreign key in place. Foreign keys are enabled on this connection,+ which constrains the copy in two ways:++ - Both joins are required, not merely tidy. The new table declares foreign keys to+ `images` *and* `image_subfolder_move_jobs`, and both are checked on the copying+ INSERT. Deleting a parent used to be possible with foreign keys off —+ `gallery_maintenance.py` did exactly that before it started enabling the pragma — so+ orphaned item rows can exist. An orphan that reached the INSERT would abort the+ migration inside the migrator's transaction, and since nothing would then be+ recorded, every subsequent startup would fail the same way with no path to recovery.+ Dropping the rows is safe: `commit_database_updates` already treats an item whose+ image is gone as a hard failure, so these rows only block a job that can never+ commit. (`migration_2026_08_06_add_project_boards` quarantines instead of dropping,+ because there the rows are user-authored documents rather than an audit trail.)+ - `DROP TABLE` is safe: nothing references `image_subfolder_move_items` as a parent, so+ the implicit row removal cannot violate another table's constraint.+ """+ columns = ", ".join(_ITEMS_COLUMNS)+ qualified = ", ".join(f"items.{column}" for column in _ITEMS_COLUMNS)+ cursor.execute("DROP TABLE IF EXISTS image_subfolder_move_items_new;")+ cursor.execute(f"CREATE TABLE image_subfolder_move_items_new ({_ITEMS_TABLE_BODY});")+ cursor.execute(+ f"""--sql+ INSERT INTO image_subfolder_move_items_new ({columns})+ SELECT {qualified}+ FROM image_subfolder_move_items AS items+ JOIN images ON images.image_name = items.image_name+ JOIN image_subfolder_move_jobs AS jobs ON jobs.id = items.job_id;+ """+ )+ cursor.execute("DROP TABLE image_subfolder_move_items;")+ cursor.execute("ALTER TABLE image_subfolder_move_items_new RENAME TO image_subfolder_move_items;")+ # The old table's indexes were dropped along with it; recreate them on the new one.+ self._create_items_indexes(cursor)+++def build_migration() -> Migration:+ """Build the migration that repairs `image_subfolder_move_items`:+ - Adds the missing `ON DELETE CASCADE` on `image_name`.+ - Creates the move tables on databases where the burned `migration_34` slot skipped them.+ """+ return Migration(+ id="2026_08_08_repair_image_subfolder_move_tables",+ # migration_34 created these tables; this repairs its output. The dated id means this+ # migration runs even on databases that wrongly recorded migration_34 as applied.+ depends_on="migration_34",+ callback=RepairImageSubfolderMoveTablesCallback(),+ )diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_34.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_34.pyindex 82d428ad24..929cc988e1 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_34.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_34.py@@ -22,7 +22,13 @@ class Migration34Callback:"""--sqlCREATE TABLE IF NOT EXISTS image_subfolder_move_items (job_id INTEGER NOT NULL REFERENCES image_subfolder_move_jobs(id),- image_name TEXT NOT NULL REFERENCES images(image_name),+ -- ON DELETE CASCADE: move items are an audit trail of a completed+ -- move, never deleted on their own. Without the cascade the FK is+ -- NO ACTION, which blocks deletion of any image that was ever moved+ -- (foreign keys are enforced on the app connection). Databases that+ -- predate this clause are repaired by+ -- migration_2026_08_08_repair_image_subfolder_move_tables.+ image_name TEXT NOT NULL REFERENCES images(image_name) ON DELETE CASCADE,old_subfolder TEXT NOT NULL,new_subfolder TEXT NOT NULL,is_intermediate BOOLEAN NOT NULL DEFAULT FALSE,diff --git a/tests/app/services/image_index/test_image_index_records.py b/tests/app/services/image_index/test_image_index_records.pyindex 6b0556a324..bd9b2d6204 100644--- a/tests/app/services/image_index/test_image_index_records.py+++ b/tests/app/services/image_index/test_image_index_records.py@@ -1,5 +1,7 @@"""Tests for the image index records service: embedding storage, eligibility, access scoping, projections."""+import sqlite3+import numpy as npimport pytest@@ -13,7 +15,10 @@ from invokeai.app.services.image_index.image_index_common import (coords_to_blob,embedding_to_blob,)-from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlite+from invokeai.app.services.image_index.image_index_records_sqlite import (+ _IN_CLAUSE_CHUNK,+ ImageIndexRecordsSqlite,+)from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStoragefrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase@@ -103,6 +108,68 @@ def test_embedding_blob_rejects_bad_shapes() -> None:blob_to_embedding(embedding_to_blob(_vec(1)), DIM + 1)+def test_embedding_blob_rejects_non_finite_values() -> None:+ # A NaN/inf row poisons every similarity and projection computation it later lands in, and+ # cannot be attributed after the fact — so it must be refused at the boundary.+ for bad in (np.nan, np.inf, -np.inf):+ v = _vec(1)+ v[0] = bad+ with pytest.raises(ValueError, match="NaN or infinite"):+ embedding_to_blob(v)++ # A float64 magnitude that overflows when narrowed to float32 is the same defect, arriving+ # via dtype conversion rather than as a literal inf.+ with pytest.raises(ValueError, match="NaN or infinite"):+ embedding_to_blob(np.array([1e40] * DIM, dtype=np.float64))+++def test_embedding_blob_rejects_zero_length() -> None:+ # dim=0 stores cleanly but then fails every batch it appears in, because get_embeddings+ # requires one consistent dim across the result set.+ with pytest.raises(ValueError, match="zero-length"):+ embedding_to_blob(np.zeros(0, dtype=np.float32))+++def test_embedding_blob_rejects_all_zero_vector() -> None:+ # Not L2-normalizable, and it yields NaN in every cosine similarity it takes part in.+ with pytest.raises(ValueError, match="all-zero"):+ embedding_to_blob(np.zeros(DIM, dtype=np.float32))++ # Same defect arriving by underflow: float64 components too small to survive the narrowing.+ with pytest.raises(ValueError, match="all-zero"):+ embedding_to_blob(np.full(DIM, 1e-320, dtype=np.float64))+++def test_embedding_blob_rejects_non_floating_dtypes() -> None:+ # These must raise the documented ValueError, not TypeError from the cast or a silent+ # coercion that stores meaningless numbers.+ for bad in (+ np.zeros(2, dtype=[("a", "f4"), ("b", "f4")]),+ np.array([1 + 1j, 2 + 0j], dtype=np.complex128),+ np.arange(DIM, dtype=np.int64),+ np.ones(DIM, dtype=bool),+ ):+ with pytest.raises(ValueError, match="floating-point"):+ embedding_to_blob(bad)+++def test_embedding_blob_survives_global_numpy_error_state() -> None:+ # A process-wide np.seterr must not turn the documented ValueError into FloatingPointError.+ old = np.seterr(all="raise")+ try:+ with pytest.raises(ValueError, match="NaN or infinite"):+ embedding_to_blob(np.array([1e40] * DIM, dtype=np.float64))+ with pytest.raises(ValueError, match="all-zero"):+ embedding_to_blob(np.full(DIM, 1e-320, dtype=np.float64))+ finally:+ np.seterr(**old)+++def test_embedding_blob_narrows_float64_input() -> None:+ v64 = (np.arange(DIM, dtype=np.float64) + 1.0) / 10.0+ assert np.array_equal(blob_to_embedding(embedding_to_blob(v64), DIM), v64.astype(np.float32))++def test_coords_blob_roundtrip_and_validation() -> None:coords = np.arange(10, dtype=np.float32).reshape(5, 2)assert np.array_equal(blob_to_coords(coords_to_blob(coords), 5), coords)@@ -168,16 +235,42 @@ def test_get_embeddings_empty_input_and_no_matches(def test_get_embeddings_chunks_large_requests(image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:- # More names than one IN-clause chunk (500) to exercise the chunked path.- count = 501+ # Straddle the IN-clause chunk boundary so the multi-chunk path really runs. Derived from+ # the constant rather than hardcoded, so raising the chunk size cannot silently reduce this+ # to a single-chunk test.+ count = _IN_CLAUSE_CHUNK + 1for i in range(count):_save_image(image_records, f"img-{i:04d}.png")index_records.upsert_embedding(f"img-{i:04d}.png", MODEL_ID, _vec(i))- requested = [f"img-{i:04d}.png" for i in range(count)]+ # Reverse order: SQLite would return each chunk in its own order, so this fails unless the+ # implementation reorders results back to the caller's sequence within every chunk.+ requested = [f"img-{i:04d}.png" for i in reversed(range(count))]names, matrix = index_records.get_embeddings(requested, MODEL_ID)assert names == requestedassert matrix.shape == (count, DIM)+ # Rows must still align with the names after chunking and reordering.+ assert np.array_equal(matrix[0], _vec(count - 1))+ assert np.array_equal(matrix[-1], _vec(0))+++def test_get_embeddings_rejects_inconsistent_dims(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite, db: SqliteDatabase+) -> None:+ # The ABC promises a failure on mixed dims under one model_id. Write a short vector behind+ # the service's back, since upsert_embedding alone cannot produce the inconsistency.+ _save_image(image_records, "a.png")+ _save_image(image_records, "b.png")+ index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))+ short = np.ones(DIM // 2, dtype=np.float32)+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, ?, ?, ?);",+ ("b.png", MODEL_ID, DIM // 2, embedding_to_blob(short)),+ )++ with pytest.raises(ValueError, match="Inconsistent embedding dims"):+ index_records.get_embeddings(["a.png", "b.png"], MODEL_ID)def test_get_embeddings_deduplicates_input_names(@@ -206,6 +299,34 @@ def test_set_projection_for_deleted_user_is_noop(index_records: ImageIndexRecordassert index_records.get_projection("no-such-user", MODEL_ID) is None+def test_skipped_write_raises_nothing_and_leaves_the_connection_usable(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite, db: SqliteDatabase+) -> None:+ # The missing-parent case is handled by `WHERE EXISTS`, not by provoking and swallowing an+ # IntegrityError. That matters because `db.transaction()` commits/rolls back the whole+ # shared connection: a swallowed error would leave the connection mid-statement-failure, and+ # an escaping one would roll back. Neither may happen, and the next write must still work.+ index_records.upsert_embedding("gone.png", MODEL_ID, _vec(1))+ index_records.set_projection(+ "no-such-user", MODEL_ID, "hash-1", "{}", ["a.png"], np.zeros((1, 2), dtype=np.float32)+ )++ assert db._conn.in_transaction is False++ _save_image(image_records, "real.png")+ index_records.upsert_embedding("real.png", MODEL_ID, _vec(2))+ assert index_records.get_embeddings(["real.png"], MODEL_ID)[0] == ["real.png"]+++def test_skipped_write_does_not_raise_integrity_error(index_records: ImageIndexRecordsSqlite) -> None:+ # Pin the mechanism, not just the outcome: if the guard regressed to relying on the foreign+ # key, this would raise instead of no-opping.+ try:+ index_records.upsert_embedding("gone.png", MODEL_ID, _vec(1))+ except sqlite3.IntegrityError as exc: # pragma: no cover - the assertion is the point+ pytest.fail(f"missing-parent write must be a no-op, not an IntegrityError: {exc}")++def test_delete_embedding_removes_all_models(image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:@@ -261,13 +382,41 @@ def test_list_unembedded_skips_ineligible_and_embedded(assert unembedded == ["eligible.png"]-def test_list_unembedded_respects_limit(- image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+def test_list_unembedded_respects_limit_and_returns_oldest_first(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite, db: SqliteDatabase) -> None:+ # `created_at` has millisecond resolution, so five back-to-back saves almost always tie and+ # the `image_name ASC` tie-break alone decides the result — which would let a reversed+ # `created_at` ordering pass unnoticed. Stamp distinct timestamps in the *reverse* of+ # alphabetical order so the two orderings disagree and only `created_at` can satisfy this.for i in range(5):_save_image(image_records, f"img-{i}.png")+ with db.transaction() as cursor:+ for i in range(5):+ cursor.execute(+ "UPDATE images SET created_at = ? WHERE image_name = ?;",+ (f"2026-01-0{5 - i} 00:00:00.000", f"img-{i}.png"),+ )++ batch = index_records.list_unembedded_image_names(MODEL_ID, limit=3)- assert len(index_records.list_unembedded_image_names(MODEL_ID, limit=3)) == 3+ # Which three matters, not just how many: backfill walks oldest-first, and a reversed order+ # would silently re-scan the newest images forever while the oldest never got embedded.+ assert batch == ["img-4.png", "img-3.png", "img-2.png"]+++def test_list_unembedded_rejects_negative_limit(index_records: ImageIndexRecordsSqlite) -> None:+ # SQLite reads a negative LIMIT as unbounded, which would turn a bounded backfill batch into+ # a full-table load.+ with pytest.raises(ValueError, match="non-negative"):+ index_records.list_unembedded_image_names(MODEL_ID, limit=-1)+++def test_list_unembedded_zero_limit_returns_nothing(+ image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+) -> None:+ _save_image(image_records, "a.png")+ assert index_records.list_unembedded_image_names(MODEL_ID, limit=0) == []def test_count_index_status(image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:@@ -418,12 +567,16 @@ def test_accessible_images_excludes_archived_boards(assert index_records.list_accessible_embedded_images(None, MODEL_ID) == ["own-unboarded.png"]-def test_accessible_images_deduplicates_multi_board_images(+def test_accessible_images_returns_boarded_images_once(image_records: SqliteImageRecordStorage,board_records: SqliteBoardRecordStorage,board_image_records: SqliteBoardImageRecordStorage,index_records: ImageIndexRecordsSqlite,) -> None:+ # `board_images` has PRIMARY KEY (image_name), so an image is on at most one board and the+ # board join cannot multiply rows. This pins that the join stays single-valued: if+ # board_images ever became many-to-many, the result would duplicate and the scope hash+ # (derived from this list) would change without the accessible set changing._save_image(image_records, "a.png")index_records.upsert_embedding("a.png", MODEL_ID, _vec(1))board_a = board_records.save("A", SYSTEM_USER_ID).board_id@@ -432,6 +585,60 @@ def test_accessible_images_deduplicates_multi_board_images(assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["a.png"]+def test_accessible_images_are_filtered_by_model_id(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ other_user_id: str,+) -> None:+ # The scope hash is derived from this listing while the embedding matrix is fetched by+ # model_id. If the listing ignored model_id, a model switch would put images into the scope+ # whose embeddings get_embeddings cannot return, desynchronizing names from coordinates.+ _save_image(image_records, "current.png")+ _save_image(image_records, "stale.png")+ index_records.upsert_embedding("current.png", MODEL_ID, _vec(1))+ index_records.upsert_embedding("stale.png", OTHER_MODEL_ID, _vec(2))++ shared = board_records.save("Shared", SYSTEM_USER_ID).board_id+ board_records.update(shared, BoardChanges(board_visibility=BoardVisibility.Shared))+ board_image_records.add_image_to_board(shared, "current.png")+ board_image_records.add_image_to_board(shared, "stale.png")++ # Every scope must apply the filter, not just the owner's.+ assert index_records.list_accessible_embedded_images(SYSTEM_USER_ID, MODEL_ID) == ["current.png"]+ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["current.png"]+ assert index_records.list_accessible_embedded_images(None, MODEL_ID) == ["current.png"]+ assert index_records.list_accessible_embedded_images(None, OTHER_MODEL_ID) == ["stale.png"]+++def test_accessible_images_exclude_individually_shared_archived_board(+ image_records: SqliteImageRecordStorage,+ board_records: SqliteBoardRecordStorage,+ board_image_records: SqliteBoardImageRecordStorage,+ index_records: ImageIndexRecordsSqlite,+ db: SqliteDatabase,+ other_user_id: str,+) -> None:+ # Archiving is tested for visibility-shared boards; the shared_boards grant is a separate+ # branch of the access clause and must be archived-gated too.+ _save_image(image_records, "granted.png")+ index_records.upsert_embedding("granted.png", MODEL_ID, _vec(1))+ board_id = board_records.save("Private", SYSTEM_USER_ID).board_id+ board_image_records.add_image_to_board(board_id, "granted.png")+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO shared_boards (board_id, user_id) VALUES (?, ?);",+ (board_id, other_user_id),+ )++ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == ["granted.png"]++ board_records.update(board_id, BoardChanges(archived=True))++ assert index_records.list_accessible_embedded_images(other_user_id, MODEL_ID) == []++# --- Projections ---diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_08_repair_image_subfolder_move_tables.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_08_repair_image_subfolder_move_tables.pynew file mode 100644index 0000000000..96bd808bee--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_08_repair_image_subfolder_move_tables.py@@ -0,0 +1,211 @@+import sqlite3++import pytest++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_08_08_repair_image_subfolder_move_tables import (+ RepairImageSubfolderMoveTablesCallback,+ build_migration,+)++# migration_34's original definition, with the NO ACTION foreign key this migration repairs.+_LEGACY_ITEMS_TABLE = """+CREATE TABLE image_subfolder_move_items (+ job_id INTEGER NOT NULL REFERENCES image_subfolder_move_jobs(id),+ image_name TEXT NOT NULL REFERENCES images(image_name),+ old_subfolder TEXT NOT NULL,+ new_subfolder TEXT NOT NULL,+ is_intermediate BOOLEAN NOT NULL DEFAULT FALSE,+ old_path TEXT,+ new_path TEXT,+ old_thumbnail_path TEXT,+ new_thumbnail_path TEXT,+ state TEXT NOT NULL CHECK (+ state IN ('planned', 'moved', 'committed', 'error')+ ),+ error_message TEXT,+ PRIMARY KEY (job_id, image_name)+);+"""++_LEGACY_JOBS_TABLE = """+CREATE TABLE image_subfolder_move_jobs (+ id INTEGER PRIMARY KEY,+ state TEXT NOT NULL CHECK (+ state IN ('planned', 'moving', 'moved', 'committed', 'error')+ ),+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ error_message TEXT+);+"""+++def _make_db() -> sqlite3.Connection:+ db = sqlite3.connect(":memory:")+ db.execute("PRAGMA foreign_keys = ON;")+ db.execute("CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY);")+ return db+++def _make_legacy_db() -> sqlite3.Connection:+ """A database as migration_34 originally left it: move tables present, no cascade."""+ db = _make_db()+ db.execute(_LEGACY_JOBS_TABLE)+ db.execute(_LEGACY_ITEMS_TABLE)+ db.execute("CREATE INDEX idx_image_subfolder_move_items_job_state ON image_subfolder_move_items(job_id, state);")+ db.execute("CREATE INDEX idx_image_subfolder_move_items_image_name ON image_subfolder_move_items(image_name);")+ return db+++def _add_move_item(db: sqlite3.Connection, image_name: str, job_id: int = 1) -> None:+ db.execute("INSERT OR IGNORE INTO image_subfolder_move_jobs (id, state) VALUES (?, 'committed');", (job_id,))+ db.execute(+ "INSERT INTO image_subfolder_move_items (job_id, image_name, old_subfolder, new_subfolder, state)"+ " VALUES (?, ?, '', 'a1', 'committed');",+ (job_id, image_name),+ )+++def _on_delete_action(db: sqlite3.Connection) -> str:+ for row in db.execute("PRAGMA foreign_key_list(image_subfolder_move_items);").fetchall():+ if row[2] == "images":+ return str(row[6])+ raise AssertionError("no foreign key to images")+++def test_legacy_schema_blocks_image_deletion() -> None:+ """The defect this migration exists to fix, pinned so the repair cannot be declared unnecessary."""+ db = _make_legacy_db()+ db.execute("INSERT INTO images VALUES ('moved.png');")+ _add_move_item(db, "moved.png")++ with pytest.raises(sqlite3.IntegrityError):+ db.execute("DELETE FROM images WHERE image_name = 'moved.png';")+++def test_repairs_missing_cascade_and_preserves_rows() -> None:+ db = _make_legacy_db()+ db.execute("INSERT INTO images VALUES ('moved.png');")+ _add_move_item(db, "moved.png")++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ assert _on_delete_action(db) == "CASCADE"+ assert db.execute(+ "SELECT job_id, image_name, new_subfolder, state FROM image_subfolder_move_items;"+ ).fetchall() == [(1, "moved.png", "a1", "committed")]++ # The deletion that used to fail now succeeds and takes the audit row with it.+ db.execute("DELETE FROM images WHERE image_name = 'moved.png';")+ assert db.execute("SELECT COUNT(*) FROM image_subfolder_move_items;").fetchone() == (0,)+++def test_rebuild_drops_rows_orphaned_while_foreign_keys_were_off() -> None:+ """gallery_maintenance.py used to delete images with FKs off, which could orphan move items.++ Those rows cannot be carried into a table that declares a cascading FK.+ """+ db = _make_legacy_db()+ db.execute("INSERT INTO images VALUES ('kept.png');")+ _add_move_item(db, "kept.png")+ db.execute("INSERT INTO images VALUES ('vanished.png');")+ _add_move_item(db, "vanished.png")+ # `PRAGMA foreign_keys` is a no-op inside a transaction, and the inserts above opened one+ # implicitly, so commit before toggling it off.+ db.commit()+ db.execute("PRAGMA foreign_keys = OFF;")+ db.execute("DELETE FROM images WHERE image_name = 'vanished.png';")+ db.commit()+ db.execute("PRAGMA foreign_keys = ON;")++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ assert db.execute("SELECT image_name FROM image_subfolder_move_items;").fetchall() == [("kept.png",)]+++def test_rebuild_drops_rows_orphaned_against_the_jobs_table() -> None:+ """The copy must guard BOTH foreign keys, not just the one to images.++ An item row whose job is missing would fail the new table's FK on insert, aborting the+ migration inside the migrator's transaction. Nothing would be recorded, so every later+ startup would fail identically with no route to recovery.+ """+ db = _make_legacy_db()+ db.execute("INSERT INTO images VALUES ('kept.png'), ('orphan.png');")+ _add_move_item(db, "kept.png", job_id=1)+ _add_move_item(db, "orphan.png", job_id=2)+ db.commit()+ db.execute("PRAGMA foreign_keys = OFF;")+ db.execute("DELETE FROM image_subfolder_move_jobs WHERE id = 2;")+ db.commit()+ db.execute("PRAGMA foreign_keys = ON;")++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ assert db.execute("SELECT image_name FROM image_subfolder_move_items;").fetchall() == [("kept.png",)]+++def test_recreates_indexes_after_rebuild() -> None:+ db = _make_legacy_db()++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ names = {+ row[0]+ for row in db.execute(+ "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='image_subfolder_move_items';"+ ).fetchall()+ }+ assert "idx_image_subfolder_move_items_job_state" in names+ assert "idx_image_subfolder_move_items_image_name" in names+ # The scratch table must not survive the rebuild.+ assert db.execute("SELECT name FROM sqlite_master WHERE name='image_subfolder_move_items_new';").fetchone() is None+++def test_creates_tables_when_the_burned_migration_34_slot_skipped_them() -> None:+ """A database from the pre-rename image-index build recorded migration_34 but has no move tables."""+ db = _make_db()++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ db.execute("INSERT INTO images VALUES ('i1.png');")+ _add_move_item(db, "i1.png")+ assert _on_delete_action(db) == "CASCADE"+ assert db.execute("SELECT name FROM sqlite_master WHERE type='trigger';").fetchone() is not None+++def test_is_idempotent() -> None:+ db = _make_legacy_db()+ db.execute("INSERT INTO images VALUES ('moved.png');")+ _add_move_item(db, "moved.png")++ RepairImageSubfolderMoveTablesCallback()(db.cursor())+ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ assert _on_delete_action(db) == "CASCADE"+ assert db.execute("SELECT COUNT(*) FROM image_subfolder_move_items;").fetchone() == (1,)+++def test_already_repaired_database_is_not_rebuilt() -> None:+ db = _make_db()+ RepairImageSubfolderMoveTablesCallback()(db.cursor())+ assert RepairImageSubfolderMoveTablesCallback()._items_fk_is_missing_cascade(db.cursor()) is False++ # Leave a rowid gap: two rows inserted, the first deleted, so the survivor sits at rowid 2.+ # A rebuild would copy it into a fresh table and renumber it to 1, so this discriminates+ # between short-circuiting and rebuilding — which a single-row table would not.+ db.execute("INSERT INTO images VALUES ('gone.png'), ('kept.png');")+ _add_move_item(db, "gone.png")+ _add_move_item(db, "kept.png")+ db.execute("DELETE FROM images WHERE image_name = 'gone.png';")+ assert db.execute("SELECT rowid FROM image_subfolder_move_items;").fetchall() == [(2,)]++ RepairImageSubfolderMoveTablesCallback()(db.cursor())++ assert db.execute("SELECT rowid FROM image_subfolder_move_items;").fetchall() == [(2,)]+++def test_migration_metadata() -> None:+ migration = build_migration()+ assert migration.id == "2026_08_08_repair_image_subfolder_move_tables"+ assert migration.depends_on == "migration_34"