From a7e44d9fd206476f4f16848cd2bb3cf1d1fc44f1 Mon Sep 17 00:00:00 2001 From: zurdi Date: Fri, 11 Sep 2026 19:37:15 +0200 Subject: [PATCH] fix(roms): sort grouped galleries by the group aggregate With group_by_meta_id, the sibling-dedup window picks each group's representative by main-sibling/prerelease/region rank, and the outer ORDER BY only ever saw that rom's own sort key, so a group whose rank-preferred copy was never touched sorted into the NULL tail even when another sibling was played yesterday. RomUser-column sorts now aggregate the key across the group inside the existing window pass (MAX descending, MIN ascending, so a group lands in the NULL bucket only when every sibling's key is NULL), and the outer ordering reads that group value through a null-safe outer join that keeps the covering-index plan (the inner-join and CTE shapes measured 3-7x worse; this one is ~1.55x master on the one family it fixes and compiles byte-identically everywhere else). The displayed representative stays the rank-preferred one. Metadata and Rom-side grouped sorts keep representative order deliberately, since materializing a roms-side key into the window drops it off idx_roms_sibling_cover, the regression migration 0107 prevents. Fixes #4447 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L --- backend/endpoints/roms/__init__.py | 2 + backend/handler/database/roms_handler.py | 309 +++++++++++------- .../database/test_roms_group_by_index.py | 21 +- .../database/test_roms_metadata_sort.py | 13 + .../database/test_roms_rom_user_sort.py | 163 +++++++++ 5 files changed, 393 insertions(+), 115 deletions(-) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 8148bd4ba..d884fa00d 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -832,6 +832,8 @@ def get_roms( # Filter down the query query = db_rom_handler.filter_roms( query=unfiltered_query, + order_by=order_by.lower(), + order_dir=order_dir.lower(), user_id=request.user.id, hidden_platform_ids=perms.hidden_platform_ids, # type: ignore hidden_rom_ids=perms.hidden_rom_ids, # type: ignore diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index c8bf2ac12..ea3daba2f 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -11,8 +11,11 @@ from typing import Any, NamedTuple from redis.exceptions import WatchError from sqlalchemy import ( + Date, + DateTime, Enum, Integer, + Numeric, String, Text, and_, @@ -397,6 +400,37 @@ def _prerelease_rank() -> ColumnElement: ) +# Grouped galleries sort each group by the MIN/MAX over its siblings, which +# matches ORDER BY semantics on every dialect only for these types. Enum and +# lexical keys stay on the representative, so the gallery reads sorted by the +# labels it displays and the char index stays aligned with them. +_GROUP_SORT_AGGREGATE_TYPES = (Date, DateTime, Integer, Numeric) + + +class _GallerySortKey(NamedTuple): + column: Any + from_rom_user: bool + joins_rom_metadata: bool + + +def _resolve_gallery_sort_key(order_by: str, user_id: int | None) -> _GallerySortKey: + """Map a gallery `order_by` name to its sort column and source table.""" + if user_id and hasattr(RomUser, order_by) and not hasattr(Rom, order_by): + return _GallerySortKey(getattr(RomUser, order_by), True, False) + if order_by in ROM_METADATA_ORDER_COLUMNS: + return _GallerySortKey(ROM_METADATA_ORDER_COLUMNS[order_by], False, False) + if hasattr(RomMetadata, order_by) and not hasattr(Rom, order_by): + return _GallerySortKey(getattr(RomMetadata, order_by), False, True) + + column = getattr(Rom, order_by) if hasattr(Rom, order_by) else Rom.name + # Use indexed `name_sort_key` to have fast access to names without + # articles (the, a, an) and leading digits. The key is derived from + # `name` at write time, or holds a custom override when one is set. + if column is Rom.name: + column = Rom.name_sort_key + return _GallerySortKey(column, False, False) + + def with_details(func): @functools.wraps(func) def wrapper(*args, **kwargs): @@ -1255,6 +1289,10 @@ class DBRomsHandler(DBBaseHandler): def filter_roms( self, query: Query, + # The grouped dedup aggregates the active sort key over each group, so + # it needs the ordering the query was built with. + order_by: str = "", + order_dir: str = "asc", platform_ids: Sequence[int] | None = None, collection_id: int | None = None, virtual_collection_id: str | None = None, @@ -1511,6 +1549,17 @@ class DBRomsHandler(DBBaseHandler): else literal(1) ) + sort_key = _resolve_gallery_sort_key(order_by, user_id) + # A group must sort by its best sibling's key, not the + # representative's, or a group whose representative carries no + # value lands in the NULL bucket (#4447). Only rom_user keys + # aggregate: they ride the window's existing rom_user join, while + # a roms-side key would push the window off its covering index + # (see test_roms_group_by_index). + aggregates_sort_key = sort_key.from_rom_user and isinstance( + sort_key.column.type, _GROUP_SORT_AGGREGATE_TYPES + ) + # Create a subquery that identifies the primary ROM in each group. # Priority order: is_main_sibling (desc), then a full release over # a pre-release, then the configured region priority, then @@ -1538,10 +1587,87 @@ class DBRomsHandler(DBBaseHandler): ) .subquery() ) - # Only id and the row number flow downstream; the partition/order - # inputs are read straight from base_subquery, so keeping them out of - # this SELECT keeps the window's temp table narrow (carrying the wide - # fs_name_no_ext through it spilled the sort to disk). + partition_key = func.coalesce( + _create_metadata_id_case( + MetadataSource.IGDB, + base_subquery.c.igdb_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.SS, + base_subquery.c.ss_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.MOBY, + base_subquery.c.moby_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.RA, + base_subquery.c.ra_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.HASHEOUS, + base_subquery.c.hasheous_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.LAUNCHBOX, + base_subquery.c.launchbox_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.TGDB, + base_subquery.c.tgdb_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.FLASHPOINT, + base_subquery.c.flashpoint_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + MetadataSource.STEAM, + base_subquery.c.steam_id, + base_subquery.c.platform_id, + ), + _create_metadata_id_case( + "romm", + base_subquery.c.id, + base_subquery.c.platform_id, + ), + ) + + # Only id, the row number and the group sort key flow downstream; + # the partition/order inputs are read straight from base_subquery, + # so keeping them out of this SELECT keeps the window's temp table + # narrow (carrying the wide fs_name_no_ext through it spilled the + # sort to disk). + window_columns: list[ColumnElement] = [ + func.row_number() + .over( + partition_by=partition_key, + order_by=[ + is_main_sibling_order, + base_subquery.c.prerelease_rank.asc(), + base_subquery.c.region_rank.asc(), + base_subquery.c.fs_name_no_ext.asc(), + ], + ) + .label("row_num"), + ] + if aggregates_sort_key: + # MIN/MAX skip NULL siblings, so a group keeps a NULL key only + # when every sibling's key is NULL. + group_aggregate = func.max if order_dir.lower() == "desc" else func.min + window_columns.append( + group_aggregate(sort_key.column) + .over(partition_by=partition_key) + .label("group_sort_value") + ) + group_subquery = ( select(base_subquery.c.id) .select_from(base_subquery) @@ -1551,81 +1677,43 @@ class DBRomsHandler(DBBaseHandler): base_subquery.c.id == RomUser.rom_id, RomUser.user_id == user_id ), ) - .add_columns( - func.row_number() - .over( - partition_by=func.coalesce( - _create_metadata_id_case( - MetadataSource.IGDB, - base_subquery.c.igdb_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.SS, - base_subquery.c.ss_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.MOBY, - base_subquery.c.moby_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.RA, - base_subquery.c.ra_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.HASHEOUS, - base_subquery.c.hasheous_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.LAUNCHBOX, - base_subquery.c.launchbox_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.TGDB, - base_subquery.c.tgdb_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.FLASHPOINT, - base_subquery.c.flashpoint_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - MetadataSource.STEAM, - base_subquery.c.steam_id, - base_subquery.c.platform_id, - ), - _create_metadata_id_case( - "romm", - base_subquery.c.id, - base_subquery.c.platform_id, - ), - ), - order_by=[ - is_main_sibling_order, - base_subquery.c.prerelease_rank.asc(), - base_subquery.c.region_rank.asc(), - base_subquery.c.fs_name_no_ext.asc(), - ], - ) - .label("row_num"), - ) + .add_columns(*window_columns) .subquery() ) - # Add a filter to the original query to only include the primary ROM from each group - query = query.filter( - Rom.id.in_( - session.query(group_subquery.c.id).filter( - group_subquery.c.row_num == 1 + if aggregates_sort_key: + # Joining the primary rows (instead of the IN filter below) + # carries the group's key out for the ORDER BY; each id sits in + # exactly one partition, so the join cannot fan out. + dedup_subquery = ( + select(group_subquery.c.id, group_subquery.c.group_sort_value) + .where(group_subquery.c.row_num == 1) + .subquery() + ) + # The null-safe match keeps this join outer: made inner, + # MariaDB drives from the derived table and probes the wide + # roms rows per group instead of leading with a covering index. + query = query.outerjoin( + dedup_subquery, Rom.id == dedup_subquery.c.id + ).filter(dedup_subquery.c.id.is_not_distinct_from(Rom.id)) + query = query.order_by(None).order_by( + *self._gallery_order_clauses( + order_by=order_by, + order_dir=order_dir, + sort_column=dedup_subquery.c.group_sort_value, + nulls_last=sort_key.from_rom_user, + search_term=search_term, + ) + ) + else: + # Add a filter to the original query to only include the primary ROM from each group + query = query.filter( + Rom.id.in_( + session.query(group_subquery.c.id).filter( + group_subquery.c.row_num == 1 + ) ) ) - ) # The RomUser table is already joined if user_id is set if statuses and user_id: @@ -1651,46 +1739,21 @@ class DBRomsHandler(DBBaseHandler): return query - @begin_session - def get_roms_query( + def _gallery_order_clauses( self, *, - order_by: str = "", - order_dir: str = "asc", - search_term: str | None = None, - user_id: int | None = None, - session: Session = None, # type: ignore - ) -> tuple[Query[Rom], Any]: - query = self._join_rom_user(select(Rom), user_id) - - sorts_by_rom_user = False - if user_id and hasattr(RomUser, order_by) and not hasattr(Rom, order_by): - order_attr = getattr(RomUser, order_by) - sorts_by_rom_user = True - elif order_by in ROM_METADATA_ORDER_COLUMNS: - order_attr = ROM_METADATA_ORDER_COLUMNS[order_by] - elif hasattr(RomMetadata, order_by) and not hasattr(Rom, order_by): - order_attr = getattr(RomMetadata, order_by) - query = query.outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id) - elif hasattr(Rom, order_by): - order_attr = getattr(Rom, order_by) - else: - order_attr = Rom.name - - # Use indexed `name_sort_key` to have fast access to names without - # articles (the, a, an) and leading digits. The key is derived from - # `name` at write time, or holds a custom override when one is set. - if order_attr is Rom.name: - order_attr = Rom.name_sort_key - - order_attr_column = order_attr - + order_by: str, + order_dir: str, + sort_column: Any, + nulls_last: bool, + search_term: str | None, + ) -> list[Any]: # MariaDB/MySQL have no NULLS LAST, so a leading IS NULL term keeps NULL # keys (no rom_user row, or an unset field) last in both directions. - nulls_last_clause = order_attr_column.is_(None) if sorts_by_rom_user else None + nulls_last_clause = sort_column.is_(None) if nulls_last else None descending = order_dir.lower() == "desc" - order_attr = order_attr.desc() if descending else order_attr.asc() + order_attr = sort_column.desc() if descending else sort_column.asc() # Ties are common on every sort key here and the gallery pages by # offset, so without a unique final key a rom can repeat in one window @@ -1714,9 +1777,33 @@ class DBRomsHandler(DBBaseHandler): if order_by else (relevance_clause, order_attr, tiebreaker) ) - order_clauses = [clause for clause in ordering if clause is not None] + return [clause for clause in ordering if clause is not None] - return query.order_by(*order_clauses), order_attr_column # type: ignore + @begin_session + def get_roms_query( + self, + *, + order_by: str = "", + order_dir: str = "asc", + search_term: str | None = None, + user_id: int | None = None, + session: Session = None, # type: ignore + ) -> tuple[Query[Rom], Any]: + query = self._join_rom_user(select(Rom), user_id) + + sort_key = _resolve_gallery_sort_key(order_by, user_id) + if sort_key.joins_rom_metadata: + query = query.outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id) + + order_clauses = self._gallery_order_clauses( + order_by=order_by, + order_dir=order_dir, + sort_column=sort_key.column, + nulls_last=sort_key.from_rom_user, + search_term=search_term, + ) + + return query.order_by(*order_clauses), sort_key.column # type: ignore @begin_session def get_roms_scalar( @@ -1738,6 +1825,8 @@ class DBRomsHandler(DBBaseHandler): roms = self.filter_roms( query=query, + order_by=kwargs.get("order_by", ""), + order_dir=kwargs.get("order_dir", "asc"), platform_ids=kwargs.get("platform_ids", None), collection_id=kwargs.get("collection_id", None), virtual_collection_id=kwargs.get("virtual_collection_id", None), diff --git a/backend/tests/handler/database/test_roms_group_by_index.py b/backend/tests/handler/database/test_roms_group_by_index.py index 95ca6eb12..f34cdd747 100644 --- a/backend/tests/handler/database/test_roms_group_by_index.py +++ b/backend/tests/handler/database/test_roms_group_by_index.py @@ -55,10 +55,12 @@ def _subqueries(clause, found: list[Subquery] | None = None) -> list[Subquery]: return found -def _dedup_window_subquery() -> Select: +def _dedup_window_subquery(order_by: str = "", user_id: int | None = None) -> Select: """The narrow `roms` subquery the grouped query materializes for its window.""" - query, _ = db_rom_handler.get_roms_query() - grouped = db_rom_handler.filter_roms(query=query, group_by_meta_id=True) + query, _ = db_rom_handler.get_roms_query(order_by=order_by, user_id=user_id) + grouped = db_rom_handler.filter_roms( + query=query, order_by=order_by, group_by_meta_id=True, user_id=user_id + ) for subquery in _subqueries(grouped): if not isinstance(subquery.element, Select): @@ -81,7 +83,9 @@ def _dedup_window_columns() -> set[str]: } -def _dedup_window_referenced_columns() -> set[str]: +def _dedup_window_referenced_columns( + order_by: str = "", user_id: int | None = None +) -> set[str]: """Every `roms` column the window's SQL reads, expressions included. Selecting a bare column is only one way in: a CASE or a function call over @@ -89,7 +93,7 @@ def _dedup_window_referenced_columns() -> set[str]: the compiled SQL is what has to be inspected. """ sql = str( - _dedup_window_subquery().compile( + _dedup_window_subquery(order_by=order_by, user_id=user_id).compile( dialect=mysql.dialect(), compile_kwargs={"literal_binds": True} ) ) @@ -116,3 +120,10 @@ class TestGroupByMetaIdCoverage: assert not { column for column in _dedup_window_columns() if column.endswith("_metadata") } + + def test_rom_user_sorted_window_reads_only_covered_columns(self): + # The grouped sort aggregate reads its key off the window's rom_user + # join; a roms-side key would break out of the covering index here. + referenced = _dedup_window_referenced_columns(order_by="last_played", user_id=1) + + assert referenced <= set(INDEX_COLUMNS) diff --git a/backend/tests/handler/database/test_roms_metadata_sort.py b/backend/tests/handler/database/test_roms_metadata_sort.py index 8d6f8201e..b4500c3a4 100644 --- a/backend/tests/handler/database/test_roms_metadata_sort.py +++ b/backend/tests/handler/database/test_roms_metadata_sort.py @@ -86,6 +86,19 @@ class TestMetadataSortQueryShape: assert sql.count("JOIN roms_metadata") == 1 assert "JOIN rom_user" in sql + def test_grouped_metadata_sort_keeps_the_representative_key(self): + query, _ = db_rom_handler.get_roms_query(order_by="first_release_date") + grouped = db_rom_handler.filter_roms( + query=query, order_by="first_release_date", group_by_meta_id=True + ) + sql = str(grouped) + + # A roms-side group aggregate would push the sort key into the dedup + # window and off its covering index, so groups sort by the + # representative's own key (see test_roms_group_by_index). + assert "group_sort_value" not in sql + assert "ORDER BY roms.generated_first_release_date ASC" in sql + class TestMetadataSortResults: """The values sorted on are the ones the view exposes.""" diff --git a/backend/tests/handler/database/test_roms_rom_user_sort.py b/backend/tests/handler/database/test_roms_rom_user_sort.py index 0063537be..7b3c85859 100644 --- a/backend/tests/handler/database/test_roms_rom_user_sort.py +++ b/backend/tests/handler/database/test_roms_rom_user_sort.py @@ -29,6 +29,24 @@ def _make_rom(platform: Platform, name: str) -> Rom: ) +def _make_sibling(platform: Platform, name: str, region: str, igdb_id: int) -> Rom: + full_name = f"{name} ({region})" + return db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + igdb_id=igdb_id, + name=name, + slug=full_name, + fs_name=f"{full_name}.zip", + fs_name_no_tags=name, + fs_name_no_ext=full_name, + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + regions=[region], + ) + ) + + def _set_rom_user_fields(rom: Rom, user: User, fields: dict[str, object]) -> None: rom_user = db_rom_handler.add_rom_user(rom_id=rom.id, user_id=user.id) db_rom_handler.update_rom_user(rom_user.id, fields) @@ -129,3 +147,148 @@ class TestRomUserSortResults: # Offsets into a non-lexical order (a date, or an enum the database # orders by declaration) would hand the alpha strip wrong targets. assert db_rom_handler.with_char_index(query, order_column) == [] + + +def _grouped_names(user: User, platform: Platform, order_dir: str) -> list[str]: + return [ + rom.fs_name_no_ext + for rom in db_rom_handler.get_roms_scalar( + platform_ids=[platform.id], + order_by="last_played", + order_dir=order_dir, + user_id=user.id, + group_by_meta_id=True, + ) + ] + + +class TestGroupedRomUserSortResults: + """Grouped galleries sort each group by its best sibling's key (#4447).""" + + @pytest.fixture + def grouped_library(self, admin_user: User, platform: Platform) -> None: + # Sonic: the USA rom is the representative (region rank), but only the + # Japan sibling was played, most recently of all. + _make_sibling(platform, "Sonic", "USA", igdb_id=100) + _set_rom_user_fields( + _make_sibling(platform, "Sonic", "Japan", igdb_id=100), + admin_user, + {"last_played": datetime(2025, 6, 1, tzinfo=timezone.utc)}, + ) + # Tails: a played group of one. + _set_rom_user_fields( + _make_sibling(platform, "Tails", "USA", igdb_id=200), + admin_user, + {"last_played": datetime(2024, 1, 1, tzinfo=timezone.utc)}, + ) + # Knuckles: every sibling untouched. + _make_sibling(platform, "Knuckles", "USA", igdb_id=300) + _make_sibling(platform, "Knuckles", "Japan", igdb_id=300) + + @pytest.mark.parametrize( + ("order_dir", "expected"), + [ + # The Japan sibling's play surfaces Sonic first, while the USA rom + # stays the displayed representative. + ("desc", ["Sonic (USA)", "Tails (USA)", "Knuckles (USA)"]), + # Ascending takes each group's earliest non-NULL key; the fully + # unplayed group stays in the NULL tail in both directions. + ("asc", ["Tails (USA)", "Sonic (USA)", "Knuckles (USA)"]), + ], + ) + def test_group_sorts_by_its_best_sibling( + self, + admin_user: User, + platform: Platform, + grouped_library: None, + order_dir: str, + expected: list[str], + ): + assert _grouped_names(admin_user, platform, order_dir) == expected + + def test_ungrouped_sort_still_ranks_each_rom_by_its_own_key( + self, admin_user: User, platform: Platform, grouped_library: None + ): + names = [ + rom.fs_name_no_ext + for rom in db_rom_handler.get_roms_scalar( + platform_ids=[platform.id], + order_by="last_played", + order_dir="desc", + user_id=admin_user.id, + ) + ] + + assert names == [ + "Sonic (Japan)", + "Tails (USA)", + "Knuckles (Japan)", + "Knuckles (USA)", + "Sonic (USA)", + ] + + def test_grouped_count_spans_all_groups( + self, admin_user: User, platform: Platform, grouped_library: None + ): + query, _ = db_rom_handler.get_roms_query( + order_by="last_played", order_dir="desc", user_id=admin_user.id + ) + grouped = db_rom_handler.filter_roms( + query=query, + order_by="last_played", + order_dir="desc", + platform_ids=[platform.id], + group_by_meta_id=True, + user_id=admin_user.id, + ) + + assert db_rom_handler.get_rom_count(query=grouped) == 3 + + +class TestGroupedRomUserSortQueryShape: + def _grouped_sql(self, order_by: str, order_dir: str = "desc") -> str: + query, _ = db_rom_handler.get_roms_query( + order_by=order_by, order_dir=order_dir, user_id=1 + ) + return str( + db_rom_handler.filter_roms( + query=query, + order_by=order_by, + order_dir=order_dir, + group_by_meta_id=True, + user_id=1, + ) + ) + + @pytest.mark.parametrize( + ("order_dir", "aggregate"), [("desc", "max"), ("asc", "min")] + ) + def test_group_key_aggregates_with_the_sort_direction( + self, order_dir: str, aggregate: str + ): + sql = self._grouped_sql("last_played", order_dir) + direction = order_dir.upper() + + assert f"{aggregate}(rom_user.last_played) OVER" in sql + # NULLs-last emission carries over from the ungrouped rom_user sort. + assert ( + "ORDER BY anon_1.group_sort_value IS NULL, " + f"anon_1.group_sort_value {direction}, roms.id {direction}" + ) in sql + + def test_group_key_join_stays_outer(self): + sql = self._grouped_sql("last_played") + + # Made inner, MariaDB drives from the derived table and probes the + # wide roms rows once per group instead of leading with an index. + assert "LEFT OUTER JOIN (SELECT" in sql + assert "IS NOT DISTINCT FROM roms.id" in sql + + @pytest.mark.parametrize("order_by", ["name", "status"]) + def test_lexical_and_enum_sorts_keep_the_representative_key(self, order_by: str): + sql = self._grouped_sql(order_by) + + # MIN/MAX diverge from ORDER BY semantics for enums, and a lexical + # group key would disagree with the representative's displayed label. + assert "group_sort_value" not in sql + assert "IN (SELECT" in sql