Merge pull request #4054 from Spinnich/perf/gallery-dedup-cover-index

perf(roms): extend the sibling covering index to cover the ROM grouping query
This commit is contained in:
Georges-Antoine Assi
2026-08-01 17:51:37 -04:00
committed by GitHub
3 changed files with 184 additions and 1 deletions

View File

@@ -0,0 +1,87 @@
"""Extend the sibling covering index to cover the group_by_meta_id dedup
0090 added `idx_roms_sibling_cover` for the sibling_roms self-join. The
group_by_meta_id dedup window in `filter_roms` reads the same shape, but two of
its inputs are missing from that index: `flashpoint_id` (the last provider in
the partition's COALESCE chain) and `fs_name_no_ext` (the tiebreaker the window
sorts each partition by). A covering index has to carry every referenced
column, so those two omissions dropped the window to a full scan of the wide
roms row -- JSON metadata blobs and all -- once per query.
The gallery runs that window up to four times per page load (page, count,
char_index, rom_id_index), so the scan is paid repeatedly. Measured on a
92.8k-rom MariaDB copy with a 256 MB buffer pool against a 963 MB roms table:
each of those four queries went 5.4-5.6s -> 0.8-1.1s (21.9s -> 4.0s combined),
with EXPLAIN moving from `type=ALL, key=NULL` to `type=index, Using index`.
Adding `fs_name_no_ext` (varchar 450) widens the index, but real names are far
shorter than the column's maximum: on that dataset the index grew 4 MB -> 7 MB.
The wider index costs the sibling_roms join a little more to scan (~170ms ->
~209ms for a 72-rom page, measured over alternating A/B runs). Keeping the old
narrow index alongside a second dedup-only one recovers that, but the two would
share their first eight columns, and per page load the totals came out the same
(2.13s vs 2.12s), so one index wins on write amplification and on not letting
the two consumers drift apart again.
Revision ID: 0107_roms_dedup_cover_index
Revises: 0106_hash_search_indexes
Create Date: 2026-08-01 00:00:00.000000
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "0107_roms_dedup_cover_index"
down_revision = "0106_hash_search_indexes"
branch_labels = None
depends_on = None
INDEX_NAME = "idx_roms_sibling_cover"
OLD_INDEX_COLUMNS = [
"platform_id",
"igdb_id",
"moby_id",
"ss_id",
"launchbox_id",
"ra_id",
"hasheous_id",
"tgdb_id",
"id",
]
NEW_INDEX_COLUMNS = [
"platform_id",
"igdb_id",
"moby_id",
"ss_id",
"launchbox_id",
"ra_id",
"hasheous_id",
"tgdb_id",
"flashpoint_id",
"fs_name_no_ext",
"id",
]
def upgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.drop_index(INDEX_NAME, if_exists=True)
batch_op.create_index(
INDEX_NAME,
NEW_INDEX_COLUMNS,
unique=False,
if_not_exists=True,
)
def downgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.drop_index(INDEX_NAME, if_exists=True)
batch_op.create_index(
INDEX_NAME,
OLD_INDEX_COLUMNS,
unique=False,
if_not_exists=True,
)

View File

@@ -315,7 +315,11 @@ class Rom(BaseModel):
__table_args__ = (
# Enforce unique fs name per platform to avoid duplicates
Index("idx_roms_platform_id_fs_name", "platform_id", "fs_name", unique=True),
# Covers the sibling_roms view self-join
# Covers the sibling_roms view self-join and the group_by_meta_id dedup
# window. Both read only these columns, so the index has to carry every
# one of them: a single missing column (flashpoint_id or fs_name_no_ext,
# the window's partition tail and sort tiebreaker) drops the plan to a
# full scan of the wide roms row, JSON metadata blobs included.
Index(
"idx_roms_sibling_cover",
"platform_id",
@@ -326,6 +330,8 @@ class Rom(BaseModel):
"ra_id",
"hasheous_id",
"tgdb_id",
"flashpoint_id",
"fs_name_no_ext",
"id",
),
Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"),

View File

@@ -0,0 +1,90 @@
"""The "Group ROMs" dedup window and the index that has to cover it.
Grouping collapses versions of the same game into one gallery entry with a
window function. The window materializes a narrow subquery first, because
carrying the wide `roms` row (every provider's raw metadata) through the window
spills its sort to disk. That narrowing only pays off if the index carries every
column the subquery reads: a covering index is all-or-nothing, so one missing
column drops the plan to a full table scan.
`idx_roms_sibling_cover` was added in 0090 for the `sibling_roms` self-join and
did not cover `flashpoint_id` or `fs_name_no_ext`, which the window needs for
its partition tail and its sort tiebreaker. The gallery issues the grouped query
up to four times per page load (page, count, char index, id index), so the scan
was paid four times over. 0107 widened the index to close the gap.
The failure mode is silent, and adding a metadata provider is the way back into
it: a new id column joins the window's COALESCE chain, the index does not follow
it, and the gallery quietly returns to full scans.
"""
from sqlalchemy import inspect
from sqlalchemy.sql import Subquery
from sqlalchemy.sql.expression import Select
from tests.conftest import engine
from handler.database import db_rom_handler
from models.rom import Rom
INDEX_COLUMNS = [
"platform_id",
"igdb_id",
"moby_id",
"ss_id",
"launchbox_id",
"ra_id",
"hasheous_id",
"tgdb_id",
"flashpoint_id",
"fs_name_no_ext",
"id",
]
def _subqueries(clause, found: list[Subquery] | None = None) -> list[Subquery]:
found = found if found is not None else []
for child in clause.get_children():
if isinstance(child, Subquery):
found.append(child)
_subqueries(child.element, found)
elif hasattr(child, "get_children"):
_subqueries(child, found)
return found
def _dedup_window_columns() -> set[str]:
"""The `roms` columns 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)
for subquery in _subqueries(grouped):
if not isinstance(subquery.element, Select):
continue
columns = {
column.name
for column in subquery.element.selected_columns
if getattr(column, "table", None) is Rom.__table__
}
if columns:
return columns
raise AssertionError("the grouped query no longer materializes a roms subquery")
class TestSiblingCoverIndex:
def test_migrations_create_covering_index(self):
indexes = [
index["column_names"] for index in inspect(engine).get_indexes("roms")
]
assert INDEX_COLUMNS in indexes
class TestGroupByMetaIdCoverage:
def test_dedup_window_reads_only_covered_columns(self):
assert _dedup_window_columns() <= set(INDEX_COLUMNS)
def test_dedup_window_excludes_the_wide_metadata_columns(self):
assert not {
column for column in _dedup_window_columns() if column.endswith("_metadata")
}