diff --git a/backend/alembic/versions/0127_rom_identity_keys.py b/backend/alembic/versions/0127_rom_identity_keys.py new file mode 100644 index 000000000..8690c1157 --- /dev/null +++ b/backend/alembic/versions/0127_rom_identity_keys.py @@ -0,0 +1,365 @@ +"""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. +- 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 +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. +revision = "0127_rom_identity_keys" +down_revision = "0126_unique_rom_full_path" +branch_labels = None +depends_on = None + + +TABLE = "rom_identity_keys" + +# (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"), + (2, "ss_id"), + (3, "launchbox_id"), + (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] + + +# --------------------------------------------------------------------------- +# Backfill and triggers +# --------------------------------------------------------------------------- + + +def _backfill(pg: bool) -> list[str]: + """One statement per provider, skipping the ROMs it never matched. + + 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: + select = ( + f"SELECT {code}, platform_id, {_as_provider_id(pg, 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, " + f"{_as_provider_id(False, f'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, " + 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 + ) + 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 + + +# --------------------------------------------------------------------------- +# 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 +# --------------------------------------------------------------------------- + +# 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 +) + +_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.String(length=IDENTITY_PROVIDER_ID_LENGTH), + 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 + ) + + # 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") + 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) + + 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) + + _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)) + + 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/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index b4db10de1..ad1385598 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -1326,6 +1326,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/recommendations_handler.py b/backend/handler/database/recommendations_handler.py index 30c81760b..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. Read off the list `sibling_roms` matches on, but 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 76c801cf4..da867909c 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, @@ -76,6 +77,7 @@ from utils.database import ( LIKE_ESCAPE_CHAR, epoch_ms_in_ranges, escape_like, + is_postgresql, json_array_contains_all, json_array_contains_any, json_array_contains_value, @@ -1507,6 +1509,7 @@ class DBRomsHandler(DBBaseHandler): Rom.launchbox_id, Rom.tgdb_id, Rom.flashpoint_id, + Rom.steam_id, ) .subquery() ) @@ -1567,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, @@ -3450,6 +3458,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 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" + 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/models/rom.py b/backend/models/rom.py index f6fa4e10f..130c88d6f 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -175,9 +175,13 @@ class DocSource(enum.StrEnum): # 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. +# 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", @@ -187,14 +191,54 @@ IDENTITY_ID_FIELDS: Final[tuple[str, ...]] = ( "hasheous_id", "tgdb_id", "steam_id", + "flashpoint_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): + """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 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. + """ + + __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[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 + ) + + 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" @@ -202,10 +246,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 @@ -582,11 +622,11 @@ class Rom(BaseModel): # The digest is opaque to a range scan, so the scan loop's # (platform_id, fs_name) batch lookup needs an index of its own. Index("idx_roms_platform_id_fs_name", "platform_id", "fs_name"), - # 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", @@ -598,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/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/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 8a341c54b..cacf6954b 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1964,6 +1964,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 new file mode 100644 index 000000000..ac1ab70d4 --- /dev/null +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -0,0 +1,281 @@ +"""Checks for the `rom_identity_keys` mirror that backs the `sibling_roms` view. + +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 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 ( + 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 _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, + 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, 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) + 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) == { + (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( + 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", 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 `IDENTITY_ID_FIELDS` without a migration that backfills + and matches on the new provider fails here. + """ + 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] + + 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) == { + (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) == { + (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 = (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): + 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) + ] + + +class TestIdentityKeyStatistics: + """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. + """ + + 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) == { + (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() 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 ]