From 850d7e5f2a5f7f697bd27b30353f4653a826d590 Mon Sep 17 00:00:00 2001 From: Spinnich Date: Tue, 8 Sep 2026 10:10:48 +0000 Subject: [PATCH 1/5] perf(gallery): materialize the ids sibling_roms matches on `sibling_roms` was a view that self-joined `roms` on an OR of seven equalities across seven columns. The compared values come from the joined row, so no index can drive that OR: MariaDB answers it by block-nested-loop scanning every ROM on the platform. Every gallery page paid that for its version badges, and the gallery's "Versions" filter asked the same view for an EXISTS over the whole library. Migration 0126 moves the ids into `rom_identity_keys`, one narrow row per ROM per provider it matched, and redefines `sibling_roms` as a self-join of that table. Triggers on `roms` keep it in sync, guarded by `NEW.x <=> OLD.x` so the writes that touch no identity id skip the resync; deletes ride the foreign key's cascade. This is the move 0101 made for `virtual_collections`. Matching is unchanged: the same seven providers, still scoped to a platform. No application code changes and no API shape changes. Measured on a clone of a real 96k-ROM, 123-platform library: GET /api/roms?duplicate=true 977,571 ms -> 22,149 ms (45x) PlayStation gallery (9,196) 1,039.0 ms -> 382.2 ms (2.7x) Arcade gallery (7,719) 844.5 ms -> 296.2 ms (2.9x) all-games gallery 3,023.9 ms -> 2,690.5 ms (1.1x) The all-games page barely moves because its rows are drawn from 123 mostly small platforms, so the per-platform scan was cheap per row. Its residual is almost entirely the group_by_meta_id dedup window (2,535 ms of 2,676 ms measured on the same clone), a separate problem. The view deliberately has no DISTINCT: a pair matched by two providers emits two rows, and DISTINCT would stop the view merging into the caller's query at 11x the cost. Both readers already collapse duplicates. The ANALYZE after the backfill is load-bearing. Without sampled statistics the optimizer estimates thousands of rows per lookup and picks a worse join order for the rest of the list query, leaving the gallery slower than before this ran. Fixes #4391 Related to #4382 Co-Authored-By: Claude Opus 5 --- .../versions/0126_rom_identity_keys.py | 306 ++++++++++++++++++ backend/models/rom.py | 56 +++- backend/tests/endpoints/roms/test_rom.py | 80 +++++ .../database/test_rom_identity_keys.py | 246 ++++++++++++++ 4 files changed, 676 insertions(+), 12 deletions(-) create mode 100644 backend/alembic/versions/0126_rom_identity_keys.py create mode 100644 backend/tests/handler/database/test_rom_identity_keys.py diff --git a/backend/alembic/versions/0126_rom_identity_keys.py b/backend/alembic/versions/0126_rom_identity_keys.py new file mode 100644 index 000000000..13c63ecb8 --- /dev/null +++ b/backend/alembic/versions/0126_rom_identity_keys.py @@ -0,0 +1,306 @@ +"""Materialize the ids `sibling_roms` matches on into an indexed table + +``sibling_roms`` was a view that self-joined ``roms`` on an OR of seven +equalities across seven columns. The compared values come from the joined row, +so no index can drive that OR: MariaDB answers it by block-nested-loop scanning +every ROM on the page's platform. That made every gallery page pay for the +sibling badges (~54% of a 1s request on an 18.5k-ROM library), and the gallery's +"Versions" filter, which asks the same view for an EXISTS over the whole +library, a four-minute request. + +The ids now live in ``rom_identity_keys``, one narrow row per (ROM, provider it +matched), and the view is a self-join of that table on (provider, platform, +provider id). The table is kept in sync by triggers on ``roms`` (no application +hook, no background job), with rom deletions handled by the foreign key's +cascade. + +Notes: +- Storing the ids rather than the pairs keeps this linear in the library. A + materialized pair table reads marginally faster but grows as the square of a + sibling group, and its trigger has to read other ROMs, so a single mis-scrape + pointing 800 ROMs at one game would write 642k rows. +- The view emits one row per matching provider, so a pair matched by both IGDB + and ScreenScraper appears twice. `DISTINCT` would collapse that at 11x the + cost, because it stops the view merging into the caller's query; the two + readers dedupe instead. +- Matching is unchanged: the same seven providers, still scoped to a platform, + so responses are identical. `steam_id` (in `IDENTITY_ID_FIELDS`) and + `flashpoint_id` (in the `group_by_meta_id` window) are still not part of it. + +Revision ID: 0126_rom_identity_keys +Revises: 0125_drop_redundant_indexes +Create Date: 2026-09-07 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op # type: ignore[attr-defined] + +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0126_rom_identity_keys" +down_revision = "0125_drop_redundant_indexes" +branch_labels = None +depends_on = None + + +TABLE = "rom_identity_keys" + +# (provider code, roms column). Frozen here rather than read off +# `SIBLING_IDENTITY_ID_FIELDS`, which a later migration is free to extend. +IDENTITY_PROVIDERS = ( + (0, "igdb_id"), + (1, "moby_id"), + (2, "ss_id"), + (3, "launchbox_id"), + (4, "ra_id"), + (5, "hasheous_id"), + (6, "tgdb_id"), +) + +_COLUMNS = "provider, platform_id, provider_id, rom_id" + +# A change to any of these invalidates the ROM's key rows. +_TRACKED_COLUMNS = ["platform_id"] + [column for _, column in IDENTITY_PROVIDERS] + + +# --------------------------------------------------------------------------- +# Backfill and triggers +# --------------------------------------------------------------------------- + + +def _backfill(pg: bool) -> list[str]: + """One statement per provider, skipping the ROMs it never matched. + + The upsert semantics keep it idempotent, so a re-run after a partial + failure only fills the rows still missing. + """ + statements = [] + for code, column in IDENTITY_PROVIDERS: + select = ( + f"SELECT {code}, platform_id, {column}, id " # nosec B608 + f"FROM roms WHERE {column} IS NOT NULL" + ) + if pg: + statements.append( + f"INSERT INTO {TABLE} ({_COLUMNS})\n{select}\nON CONFLICT DO NOTHING" # nosec B608 + ) + else: + statements.append( + f"INSERT IGNORE INTO {TABLE} ({_COLUMNS})\n{select}" + ) # nosec B608 + return statements + + +def _mysql_inserts() -> str: + """A ROM's key rows, one guarded statement per provider. + + MySQL/MariaDB do not expose ``NEW.*`` inside a derived table in a trigger + body, so the NULLs cannot be filtered out by a single INSERT ... SELECT. + """ + return "\n".join( + f"IF NEW.{column} IS NOT NULL THEN\n" # nosec B608 + f"INSERT IGNORE INTO {TABLE} ({_COLUMNS}) " + f"VALUES ({code}, NEW.platform_id, NEW.{column}, NEW.id);\n" + "END IF;" + for code, column in IDENTITY_PROVIDERS + ) + + +def _mysql_triggers() -> list[str]: + unchanged = " AND ".join(f"NEW.{c} <=> OLD.{c}" for c in _TRACKED_COLUMNS) + inserts = _mysql_inserts() + return [ + f"CREATE TRIGGER {TABLE}_ai AFTER INSERT ON roms\n" + f"FOR EACH ROW\nBEGIN\n{inserts}\nEND", + f"CREATE TRIGGER {TABLE}_au AFTER UPDATE ON roms\n" # nosec B608 + f"FOR EACH ROW\nBEGIN\n" + f"IF NOT ({unchanged}) THEN\n" + f"DELETE FROM {TABLE} WHERE rom_id = NEW.id;\n" + f"{inserts}\n" + f"END IF;\n" + f"END", + ] + + +def _postgres_trigger_function() -> str: + unchanged = " AND ".join( + f"NEW.{c} IS NOT DISTINCT FROM OLD.{c}" for c in _TRACKED_COLUMNS + ) + inserts = "\n".join( + f" IF NEW.{column} IS NOT NULL THEN\n" # nosec B608 + f" INSERT INTO {TABLE} ({_COLUMNS})\n" + f" VALUES ({code}, NEW.platform_id, NEW.{column}, NEW.id)\n" + f" ON CONFLICT DO NOTHING;\n" + f" END IF;" + for code, column in IDENTITY_PROVIDERS + ) + return f""" +CREATE OR REPLACE FUNCTION romm_sync_rom_identity_keys() RETURNS trigger + LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF {unchanged} THEN + RETURN NULL; + END IF; + DELETE FROM {TABLE} WHERE rom_id = NEW.id; + END IF; + +{inserts} + + RETURN NULL; +END $$ +""" # nosec B608 + + +# --------------------------------------------------------------------------- +# View +# --------------------------------------------------------------------------- + +# Carried over from the definition this replaces, so the view's shape is +# unchanged; a merged view never evaluates a column nobody selects. +_PROVIDER_COLUMNS = ",\n ".join( + f"CASE WHEN k1.provider = {code} THEN k1.provider_id END AS {column}" + for code, column in IDENTITY_PROVIDERS +) + +_VIEW = f""" +CREATE VIEW sibling_roms AS +SELECT + k1.rom_id AS rom_id, + k2.rom_id AS sibling_rom_id, + k1.platform_id AS platform_id, + NOW() AS created_at, + NOW() AS updated_at, + {_PROVIDER_COLUMNS} +FROM {TABLE} k1 +JOIN {TABLE} k2 + ON k1.provider = k2.provider + AND k1.platform_id = k2.platform_id + AND k1.provider_id = k2.provider_id + AND k1.rom_id <> k2.rom_id +""" # nosec B608 + + +def upgrade() -> None: + connection = op.get_bind() + pg = is_postgresql(connection) + + # Every step is guarded so a re-run after a partial failure recovers + # cleanly. MySQL/MariaDB auto-commit each DDL statement, so a crash + # mid-migration leaves objects behind without advancing the alembic version. + op.create_table( + TABLE, + sa.Column("provider", sa.SmallInteger(), nullable=False), + sa.Column("platform_id", sa.Integer(), nullable=False), + sa.Column("provider_id", sa.Integer(), nullable=False), + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column( + "created_at", + sa.TIMESTAMP(timezone=True), + server_default=sa.func.now(), + nullable=False, + ), + sa.Column( + "updated_at", + sa.TIMESTAMP(timezone=True), + server_default=sa.func.now(), + nullable=False, + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("provider", "platform_id", "provider_id", "rom_id"), + if_not_exists=True, + ) + op.create_index( + f"idx_{TABLE}_rom_id", TABLE, ["rom_id"], unique=False, if_not_exists=True + ) + + for statement in _backfill(pg): + op.execute(statement) + + # Without sampled statistics the optimizer estimates thousands of rows per + # (provider, platform, provider id) and picks a worse join order for the + # rest of the list query, leaving the gallery slower than before this ran. + op.execute(f"ANALYZE {'' if pg else 'TABLE '}{TABLE}") + + if pg: + op.execute(_postgres_trigger_function()) + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_aiu ON roms") + op.execute( + f"CREATE TRIGGER {TABLE}_aiu AFTER INSERT OR UPDATE ON roms\n" + "FOR EACH ROW EXECUTE FUNCTION romm_sync_rom_identity_keys()" + ) + else: + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_ai") + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_au") + for trigger in _mysql_triggers(): + op.execute(trigger) + + op.execute("DROP VIEW IF EXISTS sibling_roms") + op.execute(_VIEW) + + +def downgrade() -> None: + connection = op.get_bind() + pg = is_postgresql(connection) + + op.execute("DROP VIEW IF EXISTS sibling_roms") + op.execute(_legacy_view(pg)) + + if pg: + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_aiu ON roms") + op.execute("DROP FUNCTION IF EXISTS romm_sync_rom_identity_keys()") + else: + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_ai") + op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_au") + + # The rom_id index backs the foreign key, so it goes with the table. + op.drop_table(TABLE) + + +# --------------------------------------------------------------------------- +# Derive-on-read view definition (verbatim from 0073), used only by downgrade() +# --------------------------------------------------------------------------- + + +def _legacy_view(pg: bool) -> str: + null_safe_equal_operator = "IS NOT DISTINCT FROM" if pg else "<=>" + return f""" +CREATE VIEW sibling_roms AS +SELECT + r1.id AS rom_id, + r2.id AS sibling_rom_id, + r1.platform_id AS platform_id, + NOW() AS created_at, + NOW() AS updated_at, + CASE WHEN r1.igdb_id {null_safe_equal_operator} r2.igdb_id THEN r1.igdb_id END AS igdb_id, + CASE WHEN r1.moby_id {null_safe_equal_operator} r2.moby_id THEN r1.moby_id END AS moby_id, + CASE WHEN r1.ss_id {null_safe_equal_operator} r2.ss_id THEN r1.ss_id END AS ss_id, + CASE WHEN r1.launchbox_id {null_safe_equal_operator} r2.launchbox_id THEN r1.launchbox_id END AS launchbox_id, + CASE WHEN r1.ra_id {null_safe_equal_operator} r2.ra_id THEN r1.ra_id END AS ra_id, + CASE WHEN r1.hasheous_id {null_safe_equal_operator} r2.hasheous_id THEN r1.hasheous_id END AS hasheous_id, + CASE WHEN r1.tgdb_id {null_safe_equal_operator} r2.tgdb_id THEN r1.tgdb_id END AS tgdb_id +FROM + roms r1 +JOIN + roms r2 +ON + r1.platform_id = r2.platform_id + AND r1.id != r2.id + AND ( + (r1.igdb_id = r2.igdb_id AND r1.igdb_id IS NOT NULL) + OR + (r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL) + OR + (r1.ss_id = r2.ss_id AND r1.ss_id IS NOT NULL) + OR + (r1.launchbox_id = r2.launchbox_id AND r1.launchbox_id IS NOT NULL) + OR + (r1.ra_id = r2.ra_id AND r1.ra_id IS NOT NULL) + OR + (r1.hasheous_id = r2.hasheous_id AND r1.hasheous_id IS NOT NULL) + OR + (r1.tgdb_id = r2.tgdb_id AND r1.tgdb_id IS NOT NULL) + ) +""" # nosec B608 diff --git a/backend/models/rom.py b/backend/models/rom.py index 809d8d4ed..60e1017ea 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -164,11 +164,10 @@ class DocSource(enum.StrEnum): SCRAPER = "scraper" # Downloaded by a metadata provider -# Provider ids that name a game rather than a file, so two ROMs sharing any of -# them are one title (regions, revisions, storefront copies). Add a provider -# here and to the `sibling_roms` view together, or the two notions of "the same -# game" drift apart. -IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( +# Provider ids `sibling_roms` matches on. A field's position is the `provider` +# code stored in `rom_identity_keys`, so this tuple is append-only, and a new +# provider needs a migration that backfills its rows. +SIBLING_IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( "igdb_id", "moby_id", "ss_id", @@ -176,15 +175,52 @@ IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( "ra_id", "hasheous_id", "tgdb_id", - "steam_id", ) +# Provider ids that name a game rather than a file, so two ROMs sharing any of +# them are one title (regions, revisions, storefront copies). Wider than the +# sibling list by `steam_id`; the `group_by_meta_id` window is wider again by +# `flashpoint_id`. +IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = SIBLING_IDENTITY_ID_FIELDS + ("steam_id",) + + +class RomIdentityKey(BaseModel): + """One row per (ROM, provider it has a match id for), scoped to a platform. + + Two ROMs are the same game when they share a row's (provider, platform, + provider id), so `sibling_roms` is an indexed lookup over this table rather + than an OR of seven equalities across the whole of `roms`. + + Maintained by database triggers on `roms` (migration 0126), so no write path + has to update it; deletes ride the foreign key's cascade. + """ + + __tablename__ = "rom_identity_keys" + + __table_args__ = (Index("idx_rom_identity_keys_rom_id", "rom_id"),) + + provider: Mapped[int] = mapped_column(SmallInteger, primary_key=True) + platform_id: Mapped[int] = mapped_column(Integer, primary_key=True) + provider_id: Mapped[int] = mapped_column(Integer, primary_key=True) + rom_id: Mapped[int] = mapped_column( + ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True + ) + + created_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), server_default=func.now() + ) + class SiblingRom(BaseModel): """Other files of the same game on the same platform. - A database view, not a table, matching over `IDENTITY_ID_FIELDS` minus - `steam_id`, which postdates it. + A database view, not a table, over `RomIdentityKey` self-joined on its + (provider, platform, provider id). A pair matched by several providers + appears once per provider, which `get_siblings_for_roms` and the relationship + loaders both collapse. """ __tablename__ = "sibling_roms" @@ -192,10 +228,6 @@ class SiblingRom(BaseModel): rom_id: Mapped[int] = mapped_column(Integer, primary_key=True) sibling_rom_id: Mapped[int] = mapped_column(Integer, primary_key=True) - __table_args__ = ( - UniqueConstraint("rom_id", "sibling_rom_id", name="unique_sibling_roms"), - ) - class RomArchiveMember(TypedDict): name: str diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index ac063bfd0..87f67e7c1 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -446,6 +446,86 @@ def test_get_roms_filter_by_metadata_providers( assert {item["id"] for item in body["items"]} == {rom.id} +def test_get_roms_filter_by_duplicate( + client: TestClient, access_token: str, rom: Rom, platform: Platform +): + """The gallery's "Versions" filter, which reads `sibling_roms`.""" + siblings = [ + db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name=name, + slug=name, + fs_name=f"{name}.zip", + fs_name_no_tags=name, + fs_name_no_ext=name, + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + igdb_id=MOCK_IGDB_ID, + ) + ) + for name in ("rom_usa", "rom_japan") + ] + + response = client.get( + "/api/roms", + headers={"Authorization": f"Bearer {access_token}"}, + params={"platform_id": platform.id, "duplicate": True}, + ) + assert response.status_code == status.HTTP_200_OK + assert {item["id"] for item in response.json()["items"]} == { + sibling.id for sibling in siblings + } + + response = client.get( + "/api/roms", + headers={"Authorization": f"Bearer {access_token}"}, + params={"platform_id": platform.id, "duplicate": False}, + ) + assert response.status_code == status.HTTP_200_OK + assert {item["id"] for item in response.json()["items"]} == {rom.id} + + +def test_get_rom_sibling_matched_by_two_providers_appears_once( + client: TestClient, access_token: str, platform: Platform +): + """`sibling_roms` has a row per matching provider; the response has one.""" + roms = [ + db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name=name, + slug=name, + fs_name=f"{name}.zip", + fs_name_no_tags=name, + fs_name_no_ext=name, + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + igdb_id=MOCK_IGDB_ID, + ss_id=MOCK_SS_ID, + ) + ) + for name in ("twin_usa", "twin_japan") + ] + + response = client.get( + f"/api/roms/{roms[0].id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_200_OK + assert [s["id"] for s in response.json()["sibling_roms"]] == [roms[1].id] + + response = client.get( + "/api/roms", + headers={"Authorization": f"Bearer {access_token}"}, + params={"platform_id": platform.id}, + ) + assert response.status_code == status.HTTP_200_OK + items = {item["id"]: item for item in response.json()["items"]} + assert [s["id"] for s in items[roms[0].id]["sibling_roms"]] == [roms[1].id] + assert [s["id"] for s in items[roms[1].id]["sibling_roms"]] == [roms[0].id] + + def test_get_roms_filter_by_tags( client: TestClient, access_token: str, rom: Rom, platform: Platform ): diff --git a/backend/tests/handler/database/test_rom_identity_keys.py b/backend/tests/handler/database/test_rom_identity_keys.py new file mode 100644 index 000000000..fa342e50e --- /dev/null +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -0,0 +1,246 @@ +"""Checks for the `rom_identity_keys` mirror that backs the `sibling_roms` view. + +Migration 0126 moved sibling matching off an OR-of-seven-equalities self-join +over `roms` and onto one row per (ROM, provider it has an id for), maintained by +triggers on `roms` rather than by application code. These tests write through +the normal handlers and assert both the key rows and the view follow. +""" + +import pytest +from sqlalchemy import select + +from handler.database import db_rom_handler +from handler.database.base_handler import sync_session +from models.platform import Platform +from models.rom import ( + SIBLING_IDENTITY_ID_FIELDS, + Rom, + RomIdentityKey, + SiblingRom, +) +from models.user import User + + +def _add_rom(platform: Platform, name: str, **identity_ids: int) -> Rom: + return db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name=name, + slug=name, + fs_name=f"{name}.zip", + fs_name_no_tags=name, + fs_name_no_ext=name, + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + **identity_ids, + ) + ) + + +def _keys(rom_id: int) -> set[tuple[int, int, int]]: + """The (provider code, platform_id, provider_id) rows the triggers wrote.""" + with sync_session.begin() as session: + return { + tuple(row) + for row in session.execute( + select( + RomIdentityKey.provider, + RomIdentityKey.platform_id, + RomIdentityKey.provider_id, + ).where(RomIdentityKey.rom_id == rom_id) + ).all() + } + + +def _view_rows(rom_id: int) -> list[int]: + """Raw `sibling_roms` rows, undeduped: the view emits one per match.""" + with sync_session.begin() as session: + return sorted( + session.scalars( + select(SiblingRom.sibling_rom_id).where(SiblingRom.rom_id == rom_id) + ).all() + ) + + +def _siblings(rom_id: int, user_id: int) -> list[int]: + with sync_session.begin() as session: + buckets = db_rom_handler.get_siblings_for_roms( + [rom_id], user_id=user_id, session=session + ) + return sorted(sibling.id for sibling, _ in buckets[rom_id]) + + +class TestRomIdentityKeys: + def test_insert_writes_one_key_per_matched_provider(self, platform: Platform): + rom = _add_rom(platform, "scraped", igdb_id=11, ss_id=22) + + assert _keys(rom.id) == { + (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 11), + (SIBLING_IDENTITY_ID_FIELDS.index("ss_id"), platform.id, 22), + } + + def test_unscraped_rom_has_no_keys_and_no_siblings( + self, admin_user: User, platform: Platform + ): + first = _add_rom(platform, "unscraped_a") + second = _add_rom(platform, "unscraped_b") + + assert _keys(first.id) == set() + assert _siblings(first.id, admin_user.id) == [] + assert _siblings(second.id, admin_user.id) == [] + + @pytest.mark.parametrize("field", SIBLING_IDENTITY_ID_FIELDS) + def test_each_provider_matches_on_its_own( + self, admin_user: User, platform: Platform, field: str + ): + """Guards the trigger's provider list against the view's. + + Appending to `SIBLING_IDENTITY_ID_FIELDS` without a migration that + backfills and matches on the new provider fails here. + """ + first = _add_rom(platform, f"{field}_a", **{field: 4242}) + second = _add_rom(platform, f"{field}_b", **{field: 4242}) + + assert _siblings(first.id, admin_user.id) == [second.id] + assert _siblings(second.id, admin_user.id) == [first.id] + + def test_ids_from_different_providers_do_not_collide( + self, admin_user: User, platform: Platform + ): + """The provider is part of the key, so `igdb_id = 5` is not `ss_id = 5`.""" + igdb = _add_rom(platform, "igdb_five", igdb_id=5) + ss = _add_rom(platform, "ss_five", ss_id=5) + + assert _siblings(igdb.id, admin_user.id) == [] + assert _siblings(ss.id, admin_user.id) == [] + + def test_same_id_on_another_platform_is_not_a_sibling( + self, admin_user: User, platform: Platform, other_platform: Platform + ): + here = _add_rom(platform, "here", igdb_id=77) + there = _add_rom(other_platform, "there", igdb_id=77) + + assert _siblings(here.id, admin_user.id) == [] + assert _siblings(there.id, admin_user.id) == [] + + def test_pair_matching_two_providers_surfaces_once( + self, admin_user: User, platform: Platform + ): + """The view emits a row per matching provider; the API must not.""" + first = _add_rom(platform, "twice_a", igdb_id=9, ss_id=9) + second = _add_rom(platform, "twice_b", igdb_id=9, ss_id=9) + + assert _view_rows(first.id) == [second.id, second.id] + assert _siblings(first.id, admin_user.id) == [second.id] + + loaded = db_rom_handler.get_rom(first.id) + assert loaded is not None + assert [sibling.id for sibling in loaded.sibling_roms] == [second.id] + + def test_metadata_refresh_moves_the_keys( + self, admin_user: User, platform: Platform + ): + """`update_rom` is a Core-level UPDATE, so only the trigger covers it.""" + rom = _add_rom(platform, "refreshed", igdb_id=100) + old_match = _add_rom(platform, "old_match", igdb_id=100) + new_match = _add_rom(platform, "new_match", igdb_id=200) + + db_rom_handler.update_rom(rom.id, {"igdb_id": 200}) + + assert _keys(rom.id) == { + (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 200) + } + assert _siblings(rom.id, admin_user.id) == [new_match.id] + assert _siblings(old_match.id, admin_user.id) == [] + + def test_clearing_an_id_drops_the_key(self, admin_user: User, platform: Platform): + rom = _add_rom(platform, "cleared", igdb_id=300) + other = _add_rom(platform, "still_matched", igdb_id=300) + + db_rom_handler.update_rom(rom.id, {"igdb_id": None}) + + assert _keys(rom.id) == set() + assert _siblings(rom.id, admin_user.id) == [] + assert _siblings(other.id, admin_user.id) == [] + + def test_moving_a_rom_moves_its_keys( + self, admin_user: User, platform: Platform, other_platform: Platform + ): + rom = _add_rom(platform, "moved", igdb_id=400) + left_behind = _add_rom(platform, "left_behind", igdb_id=400) + + db_rom_handler.update_rom(rom.id, {"platform_id": other_platform.id}) + + assert _keys(rom.id) == { + (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), other_platform.id, 400) + } + assert _siblings(rom.id, admin_user.id) == [] + assert _siblings(left_behind.id, admin_user.id) == [] + + def test_delete_cascades(self, platform: Platform): + rom = _add_rom(platform, "deleted", igdb_id=500) + rom_id = rom.id + + db_rom_handler.delete_rom(rom_id) + + assert _keys(rom_id) == set() + + def test_update_touching_no_identity_id_skips_the_resync(self, platform: Platform): + """The `<=>` guard: without it every rom write pays a full resync.""" + rom = _add_rom(platform, "guarded", igdb_id=600) + marker = (SIBLING_IDENTITY_ID_FIELDS.index("tgdb_id"), platform.id, 999999) + with sync_session.begin() as session: + session.add( + RomIdentityKey( + provider=marker[0], + platform_id=marker[1], + provider_id=marker[2], + rom_id=rom.id, + ) + ) + + db_rom_handler.update_rom(rom.id, {"fs_size_bytes": 1234}) + assert marker in _keys(rom.id) + + db_rom_handler.update_rom(rom.id, {"igdb_id": 601}) + assert marker not in _keys(rom.id) + + def test_hidden_siblings_are_excluded( + self, admin_user: User, platform: Platform, other_platform: Platform + ): + rom = _add_rom(platform, "visible", igdb_id=700) + hidden_rom = _add_rom(platform, "hidden_rom", igdb_id=700) + + with sync_session.begin() as session: + buckets = db_rom_handler.get_siblings_for_roms( + [rom.id], + user_id=admin_user.id, + session=session, + hidden_rom_ids=[hidden_rom.id], + ) + assert buckets[rom.id] == [] + + with sync_session.begin() as session: + buckets = db_rom_handler.get_siblings_for_roms( + [rom.id], + user_id=admin_user.id, + session=session, + hidden_platform_ids=[platform.id], + ) + assert buckets[rom.id] == [] + + def test_is_main_sibling_resolves_per_user( + self, admin_user: User, platform: Platform + ): + rom = _add_rom(platform, "main_a", igdb_id=800) + sibling = _add_rom(platform, "main_b", igdb_id=800) + rom_user = db_rom_handler.add_rom_user(rom_id=sibling.id, user_id=admin_user.id) + db_rom_handler.update_rom_user(rom_user.id, {"is_main_sibling": True}) + + with sync_session.begin() as session: + buckets = db_rom_handler.get_siblings_for_roms( + [rom.id], user_id=admin_user.id, session=session + ) + assert [(s.id, is_main) for s, is_main in buckets[rom.id]] == [ + (sibling.id, True) + ] From e60007d37c03a6059bdf59f92e0a433b6c15fc9b Mon Sep 17 00:00:00 2001 From: Spinnich Date: Tue, 8 Sep 2026 10:17:20 +0000 Subject: [PATCH 2/5] docs(gallery): correct the comments the materialized keys invalidated `idx_roms_sibling_cover` no longer backs a self-join over `roms`, only the `group_by_meta_id` dedup window, so the index comment named a reader that does not exist and would mislead anyone weighing whether the index can be narrowed. The view's per-provider columns keep their names but a row now fills only its own provider's, so "the view's shape is unchanged" read as a promise about the values too. `recommendations_handler` matches on a list that is wider than the sibling list by `steam_id`; its comment pointed at the sibling list instead. Co-Authored-By: Claude Opus 5 --- backend/alembic/versions/0126_rom_identity_keys.py | 4 ++-- backend/handler/database/recommendations_handler.py | 2 +- backend/models/rom.py | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/alembic/versions/0126_rom_identity_keys.py b/backend/alembic/versions/0126_rom_identity_keys.py index 13c63ecb8..042f97b70 100644 --- a/backend/alembic/versions/0126_rom_identity_keys.py +++ b/backend/alembic/versions/0126_rom_identity_keys.py @@ -158,8 +158,8 @@ END $$ # View # --------------------------------------------------------------------------- -# Carried over from the definition this replaces, so the view's shape is -# unchanged; a merged view never evaluates a column nobody selects. +# Same column names as the definition this replaces, though a row now fills +# only its own provider's; nothing selects them, and a merged view skips them. _PROVIDER_COLUMNS = ",\n ".join( f"CASE WHEN k1.provider = {code} THEN k1.provider_id END AS {column}" for code, column in IDENTITY_PROVIDERS diff --git a/backend/handler/database/recommendations_handler.py b/backend/handler/database/recommendations_handler.py index 30c81760b..c32ea7569 100644 --- a/backend/handler/database/recommendations_handler.py +++ b/backend/handler/database/recommendations_handler.py @@ -27,7 +27,7 @@ EDGE_INSERT_CHUNK_SIZE = 1_000 MAX_CO_OCCURRENCE_SET_SIZE = 250 # Two ROMs sharing any of these are one title and are never recommended for -# each other. Read off the list `sibling_roms` matches on, but not scoped to a +# each other. Wider than the sibling list by `steam_id`, and not scoped to a # platform: a game reissued on other hardware is no more a suggestion either. IDENTITY_ID_COLUMNS = tuple(getattr(RomFacets, field) for field in IDENTITY_ID_FIELDS) diff --git a/backend/models/rom.py b/backend/models/rom.py index 60e1017ea..19ceaecf7 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -594,11 +594,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 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. + # Covers the group_by_meta_id dedup window, which reads 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", From 6a3d207ece7797696d66413addd599451595e8cd Mon Sep 17 00:00:00 2001 From: Spinnich Date: Tue, 8 Sep 2026 11:06:41 +0000 Subject: [PATCH 3/5] perf(gallery): resample the identity keys after a scan fills them Migration 0126 samples `rom_identity_keys` right after its backfill, which on a fresh install runs while the table is still empty. The first scan then fills it through the triggers, and MariaDB keeps planning `sibling_roms` against the empty sample: measured on 37k key rows, one gallery page's sibling statement takes 891.7 ms in that state against 2.1 ms once resampled, which is worse than the 550.7 ms the view it replaces cost. InnoDB's auto-recalc does not cover it. It fires and updates the stored row count, but the plan does not change until the table is reopened or analyzed: 90 s after a trigger-paced fill, `mysql.innodb_table_stats` was correct and the plan was still the block-nested-loop one. Addresses the "Fresh Installs Keep Stale Statistics" review comment on #4394. Co-Authored-By: Claude Opus 5 --- .../versions/0126_rom_identity_keys.py | 2 ++ backend/endpoints/sockets/scan.py | 7 ++++++ backend/handler/database/roms_handler.py | 16 ++++++++++++ backend/tests/endpoints/sockets/test_scan.py | 25 +++++++++++++++++++ .../database/test_rom_identity_keys.py | 21 ++++++++++++++++ 5 files changed, 71 insertions(+) diff --git a/backend/alembic/versions/0126_rom_identity_keys.py b/backend/alembic/versions/0126_rom_identity_keys.py index 042f97b70..ab17e01cc 100644 --- a/backend/alembic/versions/0126_rom_identity_keys.py +++ b/backend/alembic/versions/0126_rom_identity_keys.py @@ -222,6 +222,8 @@ def upgrade() -> None: # Without sampled statistics the optimizer estimates thousands of rows per # (provider, platform, provider id) and picks a worse join order for the # rest of the list query, leaving the gallery slower than before this ran. + # A fresh install samples an empty table here, so a scan resamples after it + # fills one (`db_rom_handler.refresh_identity_key_statistics`). op.execute(f"ANALYZE {'' if pg else 'TABLE '}{TABLE}") if pg: diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index cdd811d95..5d4da33ab 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -1307,6 +1307,13 @@ async def scan_platforms( except Exception as e: log.error(f"Couldn't refresh smart collections after the scan: {e}") + # A fresh install sampled `rom_identity_keys` while it was empty, and + # this scan is what filled it. Failing here only costs a query plan. + try: + db_rom_handler.refresh_identity_key_statistics() + except Exception as e: + log.error(f"Couldn't resample the sibling identity keys: {e}") + # Otherwise the games scanned today have an empty "Similar games" # section until the nightly build. Threaded: the scoring is CPU-bound. try: diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 724848a5e..a1feacc80 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -63,6 +63,7 @@ from models.rom import ( RomFileCategory, RomFileDocMeta, RomFileUser, + RomIdentityKey, RomMetadata, RomNote, RomUser, @@ -74,6 +75,7 @@ from utils import get_version from utils.database import ( LIKE_ESCAPE_CHAR, escape_like, + is_postgresql, json_array_contains_all, json_array_contains_any, json_array_contains_value, @@ -3409,6 +3411,20 @@ class DBRomsHandler(DBBaseHandler): "platforms": sorted(platforms), } + @begin_session + def refresh_identity_key_statistics( + self, + *, + session: Session = None, # type: ignore + ) -> None: + """Resample `rom_identity_keys` so the sibling join keeps its indexed plan. + + Migration 0126's sample lands on an empty table on a fresh install, and + InnoDB's auto-recalc refreshes the stored row count without replanning. + """ + keyword = "ANALYZE" if is_postgresql(session.connection()) else "ANALYZE TABLE" + session.execute(text(f"{keyword} {RomIdentityKey.__tablename__}")) + def invalidate_filter_values_cache(self) -> None: old_version = str(int(sync_cache.incr(ROM_FILTERS_CACHE_VERSION_KEY)) - 1) old_keys_set = _filter_values_cache_keys_key(old_version) diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 0a84b6a94..40d43610c 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1945,6 +1945,31 @@ class TestPostScanRecommendations: assert patched.emit.await_args.args[0] == "scan:done" +class TestPostScanIdentityKeyStatistics: + """A fresh install samples `rom_identity_keys` while it is still empty, so + the scan that fills it has to hand the optimizer a fresh sample.""" + + async def test_a_completed_scan_resamples_the_identity_keys(self, patched, mocker): + refresh = mocker.patch.object( + scan_module.db_rom_handler, "refresh_identity_key_statistics" + ) + + await scan_platforms(platform_ids=[], metadata_sources=[]) + + refresh.assert_called_once_with() + + async def test_a_failure_to_resample_does_not_fail_the_scan(self, patched, mocker): + mocker.patch.object( + scan_module.db_rom_handler, + "refresh_identity_key_statistics", + side_effect=RuntimeError("boom"), + ) + + await scan_platforms(platform_ids=[], metadata_sources=[]) + + assert patched.emit.await_args.args[0] == "scan:done" + + class TestGetPico8CoverUrl: """Tests for the PICO-8 cover art URL helper on FSRomsHandler.""" diff --git a/backend/tests/handler/database/test_rom_identity_keys.py b/backend/tests/handler/database/test_rom_identity_keys.py index fa342e50e..419e02b58 100644 --- a/backend/tests/handler/database/test_rom_identity_keys.py +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -244,3 +244,24 @@ class TestRomIdentityKeys: assert [(s.id, is_main) for s, is_main in buckets[rom.id]] == [ (sibling.id, True) ] + + +class TestIdentityKeyStatistics: + """Migration 0126 samples this table right after its backfill, which a fresh + install runs while the table is still empty. The scan that fills it has to + resample, or the optimizer keeps the plan it chose for an empty table. + """ + + def test_resampling_leaves_the_keys_readable(self, platform: Platform): + """Runs the real statement, so each engine's CI leg proves its own syntax.""" + rom = _add_rom(platform, "sampled", igdb_id=99) + + db_rom_handler.refresh_identity_key_statistics() + + assert _keys(rom.id) == { + (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 99) + } + + def test_resampling_an_empty_table_is_not_an_error(self) -> None: + """A fresh install resamples after a scan that found nothing.""" + db_rom_handler.refresh_identity_key_statistics() From dc27acd28496a4d90c24dac092aaf835a3c8f0c6 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Sep 2026 14:09:49 -0400 Subject: [PATCH 4/5] fix(gallery): create the identity triggers before the backfill A rom written between the backfill and the trigger creation got no key rows, and nothing short of a later edit to one of its identity columns would have noticed. Both writes skip a row that is already there, so the two steps can overlap. Also correct the revision the docstrings point at and the claim that IDENTITY_ID_FIELDS contains the group_by_meta_id window's columns. Co-Authored-By: Claude Opus 5 (1M context) --- .../versions/0127_rom_identity_keys.py | 27 ++++++++++--------- backend/handler/database/roms_handler.py | 2 +- backend/models/rom.py | 6 ++--- .../database/test_rom_identity_keys.py | 8 +++--- 4 files changed, 22 insertions(+), 21 deletions(-) diff --git a/backend/alembic/versions/0127_rom_identity_keys.py b/backend/alembic/versions/0127_rom_identity_keys.py index d77bb10fd..5122eda96 100644 --- a/backend/alembic/versions/0127_rom_identity_keys.py +++ b/backend/alembic/versions/0127_rom_identity_keys.py @@ -73,8 +73,8 @@ _TRACKED_COLUMNS = ["platform_id"] + [column for _, column in IDENTITY_PROVIDERS def _backfill(pg: bool) -> list[str]: """One statement per provider, skipping the ROMs it never matched. - The upsert semantics keep it idempotent, so a re-run after a partial - failure only fills the rows still missing. + Insert-or-skip, so a re-run after a partial failure only fills the rows + still missing, and the rows the triggers already wrote are left alone. """ statements = [] for code, column in IDENTITY_PROVIDERS: @@ -216,16 +216,9 @@ def upgrade() -> None: f"idx_{TABLE}_rom_id", TABLE, ["rom_id"], unique=False, if_not_exists=True ) - for statement in _backfill(pg): - op.execute(statement) - - # Without sampled statistics the optimizer estimates thousands of rows per - # (provider, platform, provider id) and picks a worse join order for the - # rest of the list query, leaving the gallery slower than before this ran. - # A fresh install samples an empty table here, so a scan resamples after it - # fills one (`db_rom_handler.refresh_identity_key_statistics`). - op.execute(f"ANALYZE {'' if pg else 'TABLE '}{TABLE}") - + # Before the backfill: a rom written between the two steps would otherwise + # never get its key rows, and nothing but a later edit of that rom would + # notice. Both writes skip a row that is already there. if pg: op.execute(_postgres_trigger_function()) op.execute(f"DROP TRIGGER IF EXISTS {TABLE}_aiu ON roms") @@ -239,6 +232,16 @@ def upgrade() -> None: for trigger in _mysql_triggers(): op.execute(trigger) + for statement in _backfill(pg): + op.execute(statement) + + # Without sampled statistics the optimizer estimates thousands of rows per + # (provider, platform, provider id) and picks a worse join order for the + # rest of the list query, leaving the gallery slower than before this ran. + # A fresh install samples an empty table here, so a scan resamples after it + # fills one (`db_rom_handler.refresh_identity_key_statistics`). + op.execute(f"ANALYZE {'' if pg else 'TABLE '}{TABLE}") + op.execute("DROP VIEW IF EXISTS sibling_roms") op.execute(_VIEW) diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 2cdf2816b..09bdc92d6 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -3460,7 +3460,7 @@ class DBRomsHandler(DBBaseHandler): ) -> None: """Resample `rom_identity_keys` so the sibling join keeps its indexed plan. - Migration 0126's sample lands on an empty table on a fresh install, and + Migration 0127's sample lands on an empty table on a fresh install, and InnoDB's auto-recalc refreshes the stored row count without replanning. """ keyword = "ANALYZE" if is_postgresql(session.connection()) else "ANALYZE TABLE" diff --git a/backend/models/rom.py b/backend/models/rom.py index 1edd7e79d..9843dc8a8 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -188,9 +188,9 @@ SIBLING_IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( ) # Provider ids that name a game rather than a file, so two ROMs sharing any of -# them are one title (regions, revisions, storefront copies). Wider than the -# sibling list by `steam_id`; the `group_by_meta_id` window is wider again by -# `flashpoint_id`. +# them are one title (regions, revisions, storefront copies). The sibling list +# plus `steam_id`; the `group_by_meta_id` window is the sibling list plus +# `flashpoint_id` instead, so neither list contains the other. IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = SIBLING_IDENTITY_ID_FIELDS + ("steam_id",) diff --git a/backend/tests/handler/database/test_rom_identity_keys.py b/backend/tests/handler/database/test_rom_identity_keys.py index 419e02b58..9b4a7b032 100644 --- a/backend/tests/handler/database/test_rom_identity_keys.py +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -1,6 +1,6 @@ """Checks for the `rom_identity_keys` mirror that backs the `sibling_roms` view. -Migration 0126 moved sibling matching off an OR-of-seven-equalities self-join +Migration 0127 moved sibling matching off an OR-of-seven-equalities self-join over `roms` and onto one row per (ROM, provider it has an id for), maintained by triggers on `roms` rather than by application code. These tests write through the normal handlers and assert both the key rows and the view follow. @@ -205,9 +205,7 @@ class TestRomIdentityKeys: db_rom_handler.update_rom(rom.id, {"igdb_id": 601}) assert marker not in _keys(rom.id) - def test_hidden_siblings_are_excluded( - self, admin_user: User, platform: Platform, other_platform: Platform - ): + def test_hidden_siblings_are_excluded(self, admin_user: User, platform: Platform): rom = _add_rom(platform, "visible", igdb_id=700) hidden_rom = _add_rom(platform, "hidden_rom", igdb_id=700) @@ -247,7 +245,7 @@ class TestRomIdentityKeys: class TestIdentityKeyStatistics: - """Migration 0126 samples this table right after its backfill, which a fresh + """Migration 0127 samples this table right after its backfill, which a fresh install runs while the table is still empty. The scan that fills it has to resample, or the optimizer keeps the plan it chose for an empty table. """ From 083ea5f9531a72ac6046763df97a741ff150cf0d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Sep 2026 15:42:56 -0400 Subject: [PATCH 5/5] perf(gallery): match siblings on every identity id `sibling_roms` matched on seven providers, the gallery's dedup window on those plus `flashpoint_id`, and the recommendation feed on those plus `steam_id`. Three lists, so a pair sharing only a Steam or Flashpoint id was the same game to one reader and two games to another. They are one list now. `rom_identity_keys` carries all nine providers, which makes `provider_id` a varchar since `flashpoint_id` is a string, and the dedup window's cover index grows by `steam_id` so the window keeps its indexed plan. Co-Authored-By: Claude Opus 5 (1M context) --- .../versions/0127_rom_identity_keys.py | 72 ++++++++++++++++--- .../database/recommendations_handler.py | 4 +- backend/handler/database/roms_handler.py | 6 ++ backend/models/rom.py | 31 +++++--- .../database/test_rom_identity_keys.py | 52 +++++++++----- .../database/test_roms_group_by_index.py | 20 +++--- 6 files changed, 133 insertions(+), 52 deletions(-) diff --git a/backend/alembic/versions/0127_rom_identity_keys.py b/backend/alembic/versions/0127_rom_identity_keys.py index 5122eda96..8690c1157 100644 --- a/backend/alembic/versions/0127_rom_identity_keys.py +++ b/backend/alembic/versions/0127_rom_identity_keys.py @@ -23,9 +23,12 @@ Notes: and ScreenScraper appears twice. `DISTINCT` would collapse that at 11x the cost, because it stops the view merging into the caller's query; the two readers dedupe instead. -- Matching is unchanged: the same seven providers, still scoped to a platform, - so responses are identical. `steam_id` (in `IDENTITY_ID_FIELDS`) and - `flashpoint_id` (in the `group_by_meta_id` window) are still not part of it. +- Every id in `IDENTITY_ID_FIELDS` matches, still scoped to a platform. The + view's own list used to stop short of `steam_id` and `flashpoint_id`, so a + pair sharing only one of those was a sibling to the gallery's dedup window + but not to the sibling badge; one list now answers both. +- The ids share one `provider_id` column, so it is a varchar: `flashpoint_id` + is a string, the rest are integers cast on the way in. Revision ID: 0127_rom_identity_keys Revises: 0126_unique_rom_full_path @@ -36,6 +39,7 @@ Create Date: 2026-09-07 00:00:00.000000 import sqlalchemy as sa from alembic import op # type: ignore[attr-defined] +from models.rom import IDENTITY_PROVIDER_ID_LENGTH from utils.database import is_postgresql # revision identifiers, used by Alembic. @@ -47,8 +51,10 @@ depends_on = None TABLE = "rom_identity_keys" -# (provider code, roms column). Frozen here rather than read off -# `SIBLING_IDENTITY_ID_FIELDS`, which a later migration is free to extend. +# (provider code, roms column), a frozen snapshot of `IDENTITY_ID_FIELDS` and +# its positions. Read off the model this would rewrite itself under a fresh +# install the day that list grows, leaving two installs on the same revision +# with different triggers. IDENTITY_PROVIDERS = ( (0, "igdb_id"), (1, "moby_id"), @@ -57,10 +63,18 @@ IDENTITY_PROVIDERS = ( (4, "ra_id"), (5, "hasheous_id"), (6, "tgdb_id"), + (7, "steam_id"), + (8, "flashpoint_id"), ) _COLUMNS = "provider, platform_id, provider_id, rom_id" + +def _as_provider_id(pg: bool, expression: str) -> str: + """Every provider's id, integer or string, in the one varchar column.""" + return f"CAST({expression} AS {'VARCHAR' if pg else 'CHAR'})" + + # A change to any of these invalidates the ROM's key rows. _TRACKED_COLUMNS = ["platform_id"] + [column for _, column in IDENTITY_PROVIDERS] @@ -79,7 +93,7 @@ def _backfill(pg: bool) -> list[str]: statements = [] for code, column in IDENTITY_PROVIDERS: select = ( - f"SELECT {code}, platform_id, {column}, id " # nosec B608 + f"SELECT {code}, platform_id, {_as_provider_id(pg, column)}, id " # nosec B608 f"FROM roms WHERE {column} IS NOT NULL" ) if pg: @@ -102,7 +116,8 @@ def _mysql_inserts() -> str: return "\n".join( f"IF NEW.{column} IS NOT NULL THEN\n" # nosec B608 f"INSERT IGNORE INTO {TABLE} ({_COLUMNS}) " - f"VALUES ({code}, NEW.platform_id, NEW.{column}, NEW.id);\n" + f"VALUES ({code}, NEW.platform_id, " + f"{_as_provider_id(False, f'NEW.{column}')}, NEW.id);\n" "END IF;" for code, column in IDENTITY_PROVIDERS ) @@ -131,7 +146,8 @@ def _postgres_trigger_function() -> str: inserts = "\n".join( f" IF NEW.{column} IS NOT NULL THEN\n" # nosec B608 f" INSERT INTO {TABLE} ({_COLUMNS})\n" - f" VALUES ({code}, NEW.platform_id, NEW.{column}, NEW.id)\n" + f" VALUES ({code}, NEW.platform_id, " + f"{_as_provider_id(True, f'NEW.{column}')}, NEW.id)\n" f" ON CONFLICT DO NOTHING;\n" f" END IF;" for code, column in IDENTITY_PROVIDERS @@ -154,6 +170,36 @@ END $$ """ # nosec B608 +# --------------------------------------------------------------------------- +# Dedup window cover +# --------------------------------------------------------------------------- + +# `group_by_meta_id` now reads `steam_id` too, and the index has to carry every +# column that window touches or its plan drops to a full scan of the wide roms +# row (0107 measured it). +COVER_INDEX = "idx_roms_sibling_cover" +_COVER_HEAD = [ + "platform_id", + "igdb_id", + "moby_id", + "ss_id", + "launchbox_id", + "ra_id", + "hasheous_id", + "tgdb_id", + "flashpoint_id", +] +_COVER_TAIL = ["fs_name_no_ext", "generated_primary_region", "id"] +OLD_COVER_COLUMNS = [*_COVER_HEAD, *_COVER_TAIL] +NEW_COVER_COLUMNS = [*_COVER_HEAD, "steam_id", *_COVER_TAIL] + + +def _rebuild_cover_index(columns: list[str]) -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_index(COVER_INDEX, if_exists=True) + batch_op.create_index(COVER_INDEX, columns, unique=False, if_not_exists=True) + + # --------------------------------------------------------------------------- # View # --------------------------------------------------------------------------- @@ -194,7 +240,11 @@ def upgrade() -> None: TABLE, sa.Column("provider", sa.SmallInteger(), nullable=False), sa.Column("platform_id", sa.Integer(), nullable=False), - sa.Column("provider_id", sa.Integer(), nullable=False), + sa.Column( + "provider_id", + sa.String(length=IDENTITY_PROVIDER_ID_LENGTH), + nullable=False, + ), sa.Column("rom_id", sa.Integer(), nullable=False), sa.Column( "created_at", @@ -245,11 +295,15 @@ def upgrade() -> None: op.execute("DROP VIEW IF EXISTS sibling_roms") op.execute(_VIEW) + _rebuild_cover_index(NEW_COVER_COLUMNS) + def downgrade() -> None: connection = op.get_bind() pg = is_postgresql(connection) + _rebuild_cover_index(OLD_COVER_COLUMNS) + op.execute("DROP VIEW IF EXISTS sibling_roms") op.execute(_legacy_view(pg)) diff --git a/backend/handler/database/recommendations_handler.py b/backend/handler/database/recommendations_handler.py index c32ea7569..a13659fdb 100644 --- a/backend/handler/database/recommendations_handler.py +++ b/backend/handler/database/recommendations_handler.py @@ -27,8 +27,8 @@ EDGE_INSERT_CHUNK_SIZE = 1_000 MAX_CO_OCCURRENCE_SET_SIZE = 250 # Two ROMs sharing any of these are one title and are never recommended for -# each other. Wider than the sibling list by `steam_id`, and not scoped to a -# platform: a game reissued on other hardware is no more a suggestion either. +# each other. Unlike `sibling_roms` this is not scoped to a platform: a game +# reissued on other hardware is no more a suggestion either. IDENTITY_ID_COLUMNS = tuple(getattr(RomFacets, field) for field in IDENTITY_ID_FIELDS) # Votes a rating needs before it is trusted on its own in the cold-start feed; diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 09bdc92d6..da867909c 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1509,6 +1509,7 @@ class DBRomsHandler(DBBaseHandler): Rom.launchbox_id, Rom.tgdb_id, Rom.flashpoint_id, + Rom.steam_id, ) .subquery() ) @@ -1569,6 +1570,11 @@ class DBRomsHandler(DBBaseHandler): 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, diff --git a/backend/models/rom.py b/backend/models/rom.py index 9843dc8a8..130c88d6f 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -174,10 +174,15 @@ class DocSource(enum.StrEnum): SCRAPER = "scraper" # Downloaded by a metadata provider -# Provider ids `sibling_roms` matches on. A field's position is the `provider` -# code stored in `rom_identity_keys`, so this tuple is append-only, and a new -# provider needs a migration that backfills its rows. -SIBLING_IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( +# Provider ids that name a game rather than a file, so two ROMs sharing any of +# them are one title (regions, revisions, storefront copies). Every reader of +# "the same game" matches on this one list: `sibling_roms`, the +# `group_by_meta_id` gallery window, and the recommendation feed's exclusions. +# +# A field's position is the `provider` code stored in `rom_identity_keys`, so +# the tuple is append-only, and a new provider needs a migration that backfills +# its rows. +IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( "igdb_id", "moby_id", "ss_id", @@ -185,13 +190,13 @@ SIBLING_IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( "ra_id", "hasheous_id", "tgdb_id", + "steam_id", + "flashpoint_id", ) -# Provider ids that name a game rather than a file, so two ROMs sharing any of -# them are one title (regions, revisions, storefront copies). The sibling list -# plus `steam_id`; the `group_by_meta_id` window is the sibling list plus -# `flashpoint_id` instead, so neither list contains the other. -IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = SIBLING_IDENTITY_ID_FIELDS + ("steam_id",) +# Wide enough for the longest of those columns (`flashpoint_id`), since +# `rom_identity_keys` holds every provider's id in one column. +IDENTITY_PROVIDER_ID_LENGTH: Final = 100 class RomIdentityKey(BaseModel): @@ -199,7 +204,8 @@ class RomIdentityKey(BaseModel): Two ROMs are the same game when they share a row's (provider, platform, provider id), so `sibling_roms` is an indexed lookup over this table rather - than an OR of seven equalities across the whole of `roms`. + than an OR of one equality per `IDENTITY_ID_FIELDS` entry across the whole + of `roms`. Maintained by database triggers on `roms` (migration 0127), so no write path has to update it; deletes ride the foreign key's cascade. @@ -211,7 +217,9 @@ class RomIdentityKey(BaseModel): provider: Mapped[int] = mapped_column(SmallInteger, primary_key=True) platform_id: Mapped[int] = mapped_column(Integer, primary_key=True) - provider_id: Mapped[int] = mapped_column(Integer, primary_key=True) + provider_id: Mapped[str] = mapped_column( + String(length=IDENTITY_PROVIDER_ID_LENGTH), primary_key=True + ) rom_id: Mapped[int] = mapped_column( ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True ) @@ -630,6 +638,7 @@ class Rom(BaseModel): "hasheous_id", "tgdb_id", "flashpoint_id", + "steam_id", "fs_name_no_ext", "generated_primary_region", "id", diff --git a/backend/tests/handler/database/test_rom_identity_keys.py b/backend/tests/handler/database/test_rom_identity_keys.py index 9b4a7b032..ac1ab70d4 100644 --- a/backend/tests/handler/database/test_rom_identity_keys.py +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -1,27 +1,39 @@ """Checks for the `rom_identity_keys` mirror that backs the `sibling_roms` view. -Migration 0127 moved sibling matching off an OR-of-seven-equalities self-join -over `roms` and onto one row per (ROM, provider it has an id for), maintained by +Migration 0127 moved sibling matching off an OR-of-equalities self-join over +`roms` and onto one row per (ROM, provider it has an id for), maintained by triggers on `roms` rather than by application code. These tests write through the normal handlers and assert both the key rows and the view follow. """ import pytest -from sqlalchemy import select +from sqlalchemy import String, select from handler.database import db_rom_handler from handler.database.base_handler import sync_session from models.platform import Platform from models.rom import ( - SIBLING_IDENTITY_ID_FIELDS, + IDENTITY_ID_FIELDS, Rom, RomIdentityKey, SiblingRom, ) from models.user import User +# `flashpoint_id` is a varchar column, the other ids are integers, so a +# parametrized test has to hand each one a value its column accepts. +_STRING_ID_FIELDS = frozenset( + field + for field in IDENTITY_ID_FIELDS + if isinstance(Rom.__table__.c[field].type, String) +) -def _add_rom(platform: Platform, name: str, **identity_ids: int) -> Rom: + +def _sample_id(field: str, value: int) -> int | str: + return str(value) if field in _STRING_ID_FIELDS else value + + +def _add_rom(platform: Platform, name: str, **identity_ids: int | str) -> Rom: return db_rom_handler.add_rom( Rom( platform_id=platform.id, @@ -37,8 +49,11 @@ def _add_rom(platform: Platform, name: str, **identity_ids: int) -> Rom: ) -def _keys(rom_id: int) -> set[tuple[int, int, int]]: - """The (provider code, platform_id, provider_id) rows the triggers wrote.""" +def _keys(rom_id: int) -> set[tuple[int, int, str]]: + """The (provider code, platform_id, provider_id) rows the triggers wrote. + + `provider_id` is the varchar every provider's id is cast into. + """ with sync_session.begin() as session: return { tuple(row) @@ -75,8 +90,8 @@ class TestRomIdentityKeys: rom = _add_rom(platform, "scraped", igdb_id=11, ss_id=22) assert _keys(rom.id) == { - (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 11), - (SIBLING_IDENTITY_ID_FIELDS.index("ss_id"), platform.id, 22), + (IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, "11"), + (IDENTITY_ID_FIELDS.index("ss_id"), platform.id, "22"), } def test_unscraped_rom_has_no_keys_and_no_siblings( @@ -89,17 +104,18 @@ class TestRomIdentityKeys: assert _siblings(first.id, admin_user.id) == [] assert _siblings(second.id, admin_user.id) == [] - @pytest.mark.parametrize("field", SIBLING_IDENTITY_ID_FIELDS) + @pytest.mark.parametrize("field", IDENTITY_ID_FIELDS) def test_each_provider_matches_on_its_own( self, admin_user: User, platform: Platform, field: str ): """Guards the trigger's provider list against the view's. - Appending to `SIBLING_IDENTITY_ID_FIELDS` without a migration that - backfills and matches on the new provider fails here. + Appending to `IDENTITY_ID_FIELDS` without a migration that backfills + and matches on the new provider fails here. """ - first = _add_rom(platform, f"{field}_a", **{field: 4242}) - second = _add_rom(platform, f"{field}_b", **{field: 4242}) + value = _sample_id(field, 4242) + first = _add_rom(platform, f"{field}_a", **{field: value}) + second = _add_rom(platform, f"{field}_b", **{field: value}) assert _siblings(first.id, admin_user.id) == [second.id] assert _siblings(second.id, admin_user.id) == [first.id] @@ -148,7 +164,7 @@ class TestRomIdentityKeys: db_rom_handler.update_rom(rom.id, {"igdb_id": 200}) assert _keys(rom.id) == { - (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 200) + (IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, "200") } assert _siblings(rom.id, admin_user.id) == [new_match.id] assert _siblings(old_match.id, admin_user.id) == [] @@ -172,7 +188,7 @@ class TestRomIdentityKeys: db_rom_handler.update_rom(rom.id, {"platform_id": other_platform.id}) assert _keys(rom.id) == { - (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), other_platform.id, 400) + (IDENTITY_ID_FIELDS.index("igdb_id"), other_platform.id, "400") } assert _siblings(rom.id, admin_user.id) == [] assert _siblings(left_behind.id, admin_user.id) == [] @@ -188,7 +204,7 @@ class TestRomIdentityKeys: def test_update_touching_no_identity_id_skips_the_resync(self, platform: Platform): """The `<=>` guard: without it every rom write pays a full resync.""" rom = _add_rom(platform, "guarded", igdb_id=600) - marker = (SIBLING_IDENTITY_ID_FIELDS.index("tgdb_id"), platform.id, 999999) + marker = (IDENTITY_ID_FIELDS.index("tgdb_id"), platform.id, "999999") with sync_session.begin() as session: session.add( RomIdentityKey( @@ -257,7 +273,7 @@ class TestIdentityKeyStatistics: db_rom_handler.refresh_identity_key_statistics() assert _keys(rom.id) == { - (SIBLING_IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, 99) + (IDENTITY_ID_FIELDS.index("igdb_id"), platform.id, "99") } def test_resampling_an_empty_table_is_not_an_error(self) -> 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 57c2f6ca8..95ca6eb12 100644 --- a/backend/tests/handler/database/test_roms_group_by_index.py +++ b/backend/tests/handler/database/test_roms_group_by_index.py @@ -32,19 +32,15 @@ from tests.conftest import engine from handler.database import db_rom_handler from models.rom import Rom +# Taken off the model rather than repeated, so these checks read as "the +# migrations and the window agree with the declared index". INDEX_COLUMNS = [ - "platform_id", - "igdb_id", - "moby_id", - "ss_id", - "launchbox_id", - "ra_id", - "hasheous_id", - "tgdb_id", - "flashpoint_id", - "fs_name_no_ext", - "generated_primary_region", - "id", + column.name + for column in next( + index + for index in Rom.__table__.indexes + if index.name == "idx_roms_sibling_cover" + ).columns ]