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.

perf(gallery): project media_origin onto the page, not the whole union

Lincoln Stein47546162b911
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index 20888c9c9a..7b2019b2e2 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -15,7 +15,7 @@ from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
-from invokeai.app.services.video_records.video_records_common import MEDIA_ORIGIN_JSON_EXPR, coerce_media_origin
+from invokeai.app.services.video_records.video_records_common import MEDIA_ORIGIN_SQL_EXPR, coerce_media_origin
from invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO
@@ -82,14 +82,27 @@ class SqliteGalleryService(GalleryServiceABC):
order_clause = self._build_order_clause(starred_first, order_dir)
+ # `media_origin` is joined back onto the CHOSEN page rather than selected inside the
+ # union halves. It is projected out of `videos.metadata`, a blob that lives on
+ # overflow pages, and the halves feed a sorter -- so selecting it there reads and
+ # JSON-parses every video row in the library before LIMIT, on a connection held
+ # behind a process-wide lock. Measured at 20k videos with 4 KB metadata that is
+ # ~+47ms on every gallery page; joining after LIMIT touches at most `limit` rows.
+ # (`ORDER BY` is repeated outside: a join over an ordered subquery does not preserve
+ # its order. Both clauses reference only columns the page already carries.)
union_query = f"""--sql
- SELECT * FROM (
- {image_half}
- UNION ALL
- {video_half}
- )
+ SELECT page.*, {MEDIA_ORIGIN_SQL_EXPR}
+ FROM (
+ SELECT * FROM (
+ {image_half}
+ UNION ALL
+ {video_half}
+ )
+ {order_clause}
+ LIMIT ? OFFSET ?
+ ) AS page
+ LEFT JOIN videos ON page.kind = 'video' AND videos.video_name = page.name
{order_clause}
- LIMIT ? OFFSET ?
;
"""
@@ -452,7 +465,8 @@ class SqliteGalleryService(GalleryServiceABC):
Returns `(query_with_select, params, count_query)`. Both halves emit the same columns so
UNION ALL is shape-compatible: `kind`, `name`, `width`, `height`, `category`, `starred`,
- `is_intermediate`, `board_id`, `created_at`, `duration`, `fps`, `media_origin`.
+ `is_intermediate`, `board_id`, `created_at`, `duration`, `fps`. (`media_origin` is
+ NOT one of them -- `list_items` joins it onto the chosen page instead; see there.)
`names_only=True` selects only `kind`, `name`, `starred`, `created_at` (the minimum needed
for ordering + the counts result).
@@ -465,7 +479,6 @@ class SqliteGalleryService(GalleryServiceABC):
origin_col = "image_origin"
duration_expr = "NULL"
fps_expr = "NULL"
- media_origin_expr = "NULL"
elif kind == "video":
base_table = "videos"
join_table = "board_videos"
@@ -474,7 +487,6 @@ class SqliteGalleryService(GalleryServiceABC):
origin_col = "video_origin"
duration_expr = f"{base_table}.duration"
fps_expr = f"{base_table}.fps"
- media_origin_expr = MEDIA_ORIGIN_JSON_EXPR
else:
raise ValueError(f"Unknown kind: {kind}")
@@ -515,8 +527,7 @@ class SqliteGalleryService(GalleryServiceABC):
f"{board_id_expr} AS board_id, "
f"{base_table}.created_at AS created_at, "
f"{duration_expr} AS duration, "
- f"{fps_expr} AS fps, "
- f"{media_origin_expr} AS media_origin"
+ f"{fps_expr} AS fps"
)
conditions = ""
diff --git a/invokeai/app/services/video_records/video_records_common.py b/invokeai/app/services/video_records/video_records_common.py
index 121bd3e671..29899c0f9e 100644
--- a/invokeai/app/services/video_records/video_records_common.py
+++ b/invokeai/app/services/video_records/video_records_common.py
@@ -1,4 +1,5 @@
import datetime
+import re
from typing import Any, Optional, Union
from pydantic import BaseModel, Field, StrictBool, StrictStr
@@ -52,6 +53,13 @@ MEDIA_ORIGIN_SQL_EXPR = f"{MEDIA_ORIGIN_JSON_EXPR} AS media_origin"
# gallery page that includes it.
MEDIA_ORIGIN_MAX_LENGTH = 64
+# A marker is an identifier-shaped token (`audio_upload` is the only one so far). Matching
+# the SHAPE rather than an allowlist keeps the vocabulary open, while rejecting the two
+# things `json_extract` hands back as strings without them being markers: a JSON object or
+# array arrives as its serialized text (`'{"a":"b"}'`, `'[1,2]'`), which `isinstance(str)`
+# alone would happily propagate.
+MEDIA_ORIGIN_PATTERN = re.compile(r"\A[A-Za-z0-9_-]+\Z")
+
def coerce_media_origin(value: Any) -> Optional[str]:
"""The `media_origin` marker as a string, or None for anything that is not one.
@@ -63,13 +71,13 @@ def coerce_media_origin(value: Any) -> Optional[str]:
`ValidationError` while *deserializing the row*, which does not merely mislabel the
video: it makes the record, its DTO, and every gallery listing that contains it fail to
build. One odd upload would take out the gallery. An unrecognized marker means the same
- thing as an absent one, so it is dropped here rather than propagated -- including the
- empty string, which the frontend's own mapper also treats as no marker, and one past
- :data:`MEDIA_ORIGIN_MAX_LENGTH`, which no real marker reaches.
+ thing as an absent one, so it is dropped here rather than propagated -- an empty string,
+ one past :data:`MEDIA_ORIGIN_MAX_LENGTH`, and anything not shaped like a marker per
+ :data:`MEDIA_ORIGIN_PATTERN`.
"""
- if not isinstance(value, str) or not value or len(value) > MEDIA_ORIGIN_MAX_LENGTH:
+ if not isinstance(value, str) or len(value) > MEDIA_ORIGIN_MAX_LENGTH:
return None
- return value
+ return value if MEDIA_ORIGIN_PATTERN.match(value) else None
VIDEO_DTO_COLS = ", ".join(
diff --git a/tests/app/services/video_records/test_video_records_sqlite.py b/tests/app/services/video_records/test_video_records_sqlite.py
index 8673cb6101..a7fef798f7 100644
--- a/tests/app/services/video_records/test_video_records_sqlite.py
+++ b/tests/app/services/video_records/test_video_records_sqlite.py
@@ -324,6 +324,11 @@ def test_media_origin_survives_a_listing(store: SqliteVideoRecordStorage) -> Non
pytest.param("true", id="a JSON boolean"),
pytest.param("1.5", id="a JSON float"),
pytest.param('""', id="an empty string, which the frontend also reads as no marker"),
+ # `json_extract` hands an object or array back as its SERIALIZED TEXT, so these
+ # arrive as `str` and an isinstance check alone would propagate them.
+ pytest.param('{"a": "b"}', id="a JSON object, returned as its text"),
+ pytest.param("[1, 2]", id="a JSON array, returned as its text"),
+ pytest.param('"has a space"', id="a string that is not marker-shaped"),
],
)
def test_a_non_string_marker_does_not_break_the_record(store: SqliteVideoRecordStorage, raw: str) -> None: