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 ]