From cf18cc9799177eaaae1049d0120992944a33cf7f Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 24 Nov 2026 09:46:38 -0500 Subject: [PATCH] pr-ready: code-review Co-Authored-By: Claude Opus 5.5 --- backend/endpoints/sockets/scan.py | 14 ++-- backend/handler/database/roms_handler.py | 22 ++----- backend/handler/database/sibling_groups.py | 56 ++++++++++------ backend/handler/recommendation/feed.py | 27 ++++---- backend/handler/recommendation/serving.py | 20 +++--- .../tests/endpoints/test_recommendations.py | 19 ++++++ .../database/test_rom_identity_keys.py | 4 +- .../database/test_rom_sibling_groups.py | 64 +++++++++++++++++-- .../database/test_roms_group_by_index.py | 5 +- .../tests/handler/recommendation/test_feed.py | 14 ++++ backend/tests/test_migrations.py | 2 +- 11 files changed, 169 insertions(+), 78 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 98f070333..636cfe76a 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -1420,6 +1420,13 @@ async def scan_platforms( log.info(f"{emoji.EMOJI_CHECK_MARK} Scan completed") + # Repairs a group two scan workers rewrote at once, before the cache drop + # and the smart collection refresh read the groups. + try: + db_rom_handler.rebuild_sibling_groups() + except Exception as e: + log.error(f"Couldn't rebuild the sibling groups: {e}") + # The library changed; drop cached filter values. db_rom_handler.invalidate_filter_values_cache() @@ -1442,13 +1449,6 @@ async def scan_platforms( except Exception as e: log.error(f"Couldn't resample the sibling identity keys: {e}") - # Each ROM write regroups its own versions; this repairs a group two - # scan workers rewrote at once. - try: - db_rom_handler.rebuild_sibling_groups() - except Exception as e: - log.error(f"Couldn't rebuild the sibling groups: {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 64185e701..3cc37120f 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1122,10 +1122,11 @@ class DBRomsHandler(DBBaseHandler): self, rom_ids: Sequence[int], *, + present_only: bool = False, session: Session = INJECTED_SESSION, ) -> dict[int, int]: """Each ROM's `sibling_group_key`, equal for every version of one game.""" - return sibling_groups.group_keys(session, rom_ids) + return sibling_groups.group_keys(session, rom_ids, present_only=present_only) @begin_session def get_sibling_group_members( @@ -1143,17 +1144,15 @@ class DBRomsHandler(DBBaseHandler): rom_ids: Sequence[int], *, user_id: int | None, - visibility: RomVisibilityFilter = UNRESTRICTED, + visibility: RomVisibilityFilter, session: Session = INJECTED_SESSION, ) -> dict[int, int]: - """Map each ROM to the version of its game the grouped gallery shows. - - ROMs whose every version is hidden from the viewer or missing from disk - are left out. - """ + """Map each ROM to its game's grouped-gallery version, if one is visible and on disk.""" group_keys = self.get_sibling_group_keys(rom_ids, session=session) if not group_keys: return {} + # Filtering on member ids keeps the lookup on the primary key. + member_ids = sibling_groups.group_members(session, group_keys.keys()) group_key = sibling_group_key() hidden_last = ( @@ -1188,14 +1187,7 @@ class DBRomsHandler(DBBaseHandler): RomUser, and_(RomUser.rom_id == Rom.id, RomUser.user_id == user_id) ) .where( - # The group id when there is one, so the lookup stays on its index. - or_( - RomSiblingGroup.group_id.in_(set(group_keys.values())), - and_( - RomSiblingGroup.group_id.is_(None), - Rom.id.in_(group_keys.keys()), - ), - ), + Rom.id.in_(member_ids), Rom.missing_from_fs.is_(False), *visibility.clauses(), ) diff --git a/backend/handler/database/sibling_groups.py b/backend/handler/database/sibling_groups.py index 869432f6d..f66d5edb2 100644 --- a/backend/handler/database/sibling_groups.py +++ b/backend/handler/database/sibling_groups.py @@ -4,11 +4,14 @@ from collections.abc import Collection, Iterable, Iterator from itertools import batched from typing import Final -from sqlalchemy import delete, func, insert, select, tuple_ +from sqlalchemy import Insert, delete, func, select, tuple_ +from sqlalchemy.dialects import mysql as sa_mysql +from sqlalchemy.dialects import postgresql as sa_pg from sqlalchemy.orm import Session from sqlalchemy.sql.elements import ColumnElement from models.rom import Rom, RomIdentityKey, RomSiblingGroup +from utils.database import is_postgresql from utils.sibling_groups import sibling_groups IdentityKey = tuple[int, int, str] @@ -28,16 +31,21 @@ def sibling_group_key() -> ColumnElement[int]: return func.coalesce(RomSiblingGroup.group_id, Rom.id) -def group_keys(session: Session, rom_ids: Collection[int]) -> dict[int, int]: - """Each ROM's `sibling_group_key`.""" +def group_keys( + session: Session, rom_ids: Collection[int], *, present_only: bool = False +) -> dict[int, int]: + """Each ROM's `sibling_group_key`, skipping ROMs off disk when `present_only`.""" + query = select(Rom.id, sibling_group_key()).outerjoin( + RomSiblingGroup, RomSiblingGroup.rom_id == Rom.id + ) + if present_only: + query = query.where(Rom.missing_from_fs.is_(False)) keys: dict[int, int] = {} for chunk in batched(rom_ids, _CHUNK_SIZE, strict=False): keys.update( (rom_id, group_key) for rom_id, group_key in session.execute( - select(Rom.id, sibling_group_key()) - .outerjoin(RomSiblingGroup, RomSiblingGroup.rom_id == Rom.id) - .where(Rom.id.in_(chunk)) + query.where(Rom.id.in_(chunk)) ).all() ) return keys @@ -61,11 +69,8 @@ def group_members(session: Session, rom_ids: Collection[int]) -> set[int]: def regroup(session: Session, rom_ids: Collection[int]) -> None: - """Recompute the groups of `rom_ids` after their identity keys changed. - - Starts from the ROMs' current groups as well, since a ROM that lost a key - can split the group it leaves behind. - """ + """Recompute the groups of `rom_ids` after their identity keys changed.""" + # Their current groups too, since a ROM that lost a key can split the one it left. visited = group_members(session, rom_ids) frontier = set(visited) seen_keys: set[IdentityKey] = set() @@ -119,11 +124,9 @@ def _holders_of_keys( def _write( session: Session, groups: dict[int, int], *, scope: Collection[int] | None ) -> None: - """Store `groups` for the ROMs in `scope` (every ROM when None). - - Only the rows that changed are written, so a rescan that moves nothing - takes no row locks. - """ + """Store `groups` for the ROMs in `scope` (every ROM when None).""" + # Only the rows that changed are written, so a rescan that moves nothing + # takes no row locks. stored_query = select(RomSiblingGroup.rom_id, RomSiblingGroup.group_id) stored: dict[int, int] = {} if scope is None: @@ -139,12 +142,11 @@ def _write( ).all() ) - stale = [ - rom_id for rom_id, group_id in stored.items() if groups.get(rom_id) != group_id - ] + # Sorted, so two writers lock shared rows in the same order. + stale = sorted(rom_id for rom_id in stored if rom_id not in groups) fresh = [ {"rom_id": rom_id, "group_id": group_id} - for rom_id, group_id in groups.items() + for rom_id, group_id in sorted(groups.items()) if stored.get(rom_id) != group_id ] @@ -153,4 +155,16 @@ def _write( delete(RomSiblingGroup).where(RomSiblingGroup.rom_id.in_(chunk)) ) for rows in batched(fresh, _CHUNK_SIZE, strict=False): - session.execute(insert(RomSiblingGroup), list(rows)) + session.execute(_upsert(session, list(rows))) + + +def _upsert(session: Session, rows: list[dict[str, int]]) -> Insert: + """Insert `rows`, moving a row another writer committed since this one read it.""" + if is_postgresql(session.get_bind()): + pg_insert = sa_pg.insert(RomSiblingGroup).values(rows) + return pg_insert.on_conflict_do_update( + index_elements=["rom_id"], + set_={"group_id": pg_insert.excluded.group_id}, + ) + mysql_insert = sa_mysql.insert(RomSiblingGroup).values(rows) + return mysql_insert.on_duplicate_key_update(group_id=mysql_insert.inserted.group_id) diff --git a/backend/handler/recommendation/feed.py b/backend/handler/recommendation/feed.py index f3489a517..e4faef3a4 100644 --- a/backend/handler/recommendation/feed.py +++ b/backend/handler/recommendation/feed.py @@ -307,20 +307,18 @@ class FeedBuilder: def first_distinct_games[T]( batches: Iterable[Sequence[T]], rom_id_of: Callable[[T], int], *, want: int ) -> list[T]: - """The first `want` items that are each a different game, in order. - - Reads `batches` lazily, so a game with a dozen versions costs another - batch rather than a short list. - """ + """The first `want` on-disk items that are each a different game, in order.""" + # Lazy, so a game with a dozen versions costs another batch, not a short list. seen: set[int] = set() kept: list[T] = [] for batch in batches: group_keys = db_rom_handler.get_sibling_group_keys( - [rom_id_of(item) for item in batch] + [rom_id_of(item) for item in batch], present_only=True ) for item in batch: - group_key = group_keys.get(rom_id_of(item), rom_id_of(item)) - if group_key in seen: + # A version off disk leaves the game's slot to one on disk. + group_key = group_keys.get(rom_id_of(item)) + if group_key is None or group_key in seen: continue seen.add(group_key) kept.append(item) @@ -329,16 +327,23 @@ def first_distinct_games[T]( return kept -def hydrate_roms(rom_ids: Sequence[int]) -> dict[int, Rom]: +def hydrate_roms( + rom_ids: Sequence[int], *, include_missing: bool = False +) -> dict[int, Rom]: """Load ROMs through the shared `SimpleRomSchema` load path. Missing-from-disk ROMs are dropped here rather than in SQL, so the edge queries never have to join the wide `roms` table. + + Args: + rom_ids: The ROMs to load. + include_missing: Keep ROMs missing from disk, for `as_representatives` + to swap for a version on disk. """ return { rom.id: rom for rom in db_rom_handler.get_roms_simple_by_ids(list(rom_ids)) - if not rom.missing_from_fs + if include_missing or not rom.missing_from_fs } @@ -353,7 +358,7 @@ def get_cached_feed(user_id: int, limit: int) -> list[RecommendedRom] | None: except ValueError, TypeError: return None - roms = hydrate_roms([entry["rom_id"] for entry in entries]) + roms = hydrate_roms([entry["rom_id"] for entry in entries], include_missing=True) return [ RecommendedRom( diff --git a/backend/handler/recommendation/serving.py b/backend/handler/recommendation/serving.py index c44357806..e51250903 100644 --- a/backend/handler/recommendation/serving.py +++ b/backend/handler/recommendation/serving.py @@ -46,7 +46,7 @@ def similar_roms( lambda edge: edge.rom_id, group_keys, ) - roms = hydrate_roms([edge.rom_id for edge in edges]) + roms = hydrate_roms([edge.rom_id for edge in edges], include_missing=True) candidates = _visible_representatives( [ RecommendedRom( @@ -106,11 +106,7 @@ def recommended_roms( def _visible_representatives( items: Sequence[RecommendedRom], permissions: ResolvedPermissions ) -> list[RecommendedRom]: - """`as_representatives`, then the visibility cut. - - In that order, so a game whose top-ranked version is hidden from the - viewer is shown through a visible version rather than dropped. - """ + """`as_representatives` before the visibility cut, so a visible version stands in.""" return [ item for item in as_representatives(items, permissions) @@ -121,11 +117,8 @@ def _visible_representatives( def as_representatives( items: Sequence[RecommendedRom], permissions: ResolvedPermissions ) -> list[RecommendedRom]: - """Swap each ROM for the version of its game the grouped gallery shows. - - Resolved per request rather than ranked in, so a user's main-version pick - takes effect without waiting for a cached feed to expire. - """ + """Swap each ROM for the version of its game the grouped gallery shows.""" + # Per request, so a main-version pick applies without waiting out the cached feed. representatives = db_rom_handler.get_sibling_representatives( [item.rom.id for item in items], user_id=permissions.user_id, @@ -139,13 +132,16 @@ def as_representatives( swapped = hydrate_roms(list(swapped_ids)) if swapped_ids else {} result: list[RecommendedRom] = [] + # A feed cached before two groups merged holds a version of each. + emitted: set[int] = set() for item in items: representative_id = representatives.get(item.rom.id) - if representative_id is None: + if representative_id is None or representative_id in emitted: continue rom = swapped.get(representative_id, item.rom) if rom.id != representative_id: continue + emitted.add(representative_id) result.append(replace(item, rom=rom)) return result diff --git a/backend/tests/endpoints/test_recommendations.py b/backend/tests/endpoints/test_recommendations.py index 4dde87025..5dcdc2b4e 100644 --- a/backend/tests/endpoints/test_recommendations.py +++ b/backend/tests/endpoints/test_recommendations.py @@ -378,6 +378,25 @@ def test_similar_roms_show_a_visible_version_of_a_hidden_one( assert library["metroid"].id not in returned_ids +def test_similar_roms_show_an_on_disk_version_of_a_missing_one( + client: TestClient, access_token: str, platform: Platform +): + """The edges point at a version gone from disk; the game must still show.""" + library = build_library(platform) + metroid_europe = _metroid_europe(platform) + SimilarityBuilder().build() + db_rom_handler.update_rom(library["metroid"].id, {"missing_from_fs": True}) + + body = client.get( + f"/api/roms/{library['metroid_2'].id}/similar", + headers={"Authorization": f"Bearer {access_token}"}, + ).json() + + returned_ids = [entry["rom"]["id"] for entry in body] + assert metroid_europe.id in returned_ids + assert library["metroid"].id not in returned_ids + + def test_cold_start_reads_past_a_game_with_many_versions( client: TestClient, access_token: str, admin_user: User, platform: Platform ): diff --git a/backend/tests/handler/database/test_rom_identity_keys.py b/backend/tests/handler/database/test_rom_identity_keys.py index 19fca96c4..9a8c43a06 100644 --- a/backend/tests/handler/database/test_rom_identity_keys.py +++ b/backend/tests/handler/database/test_rom_identity_keys.py @@ -1,4 +1,4 @@ -"""Checks for the `rom_identity_keys` mirror that backs the `sibling_roms` view. +"""Checks for the `rom_identity_keys` mirror the sibling groups are built from. 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 @@ -56,7 +56,7 @@ def _keys(rom_id: int) -> set[tuple[int, int, str]]: def _view_rows(rom_id: int) -> list[int]: - """Raw `sibling_roms` rows, undeduped: the view emits one per match.""" + """Raw `sibling_roms` rows for one ROM.""" with sync_session.begin() as session: return sorted( session.scalars( diff --git a/backend/tests/handler/database/test_rom_sibling_groups.py b/backend/tests/handler/database/test_rom_sibling_groups.py index edcbeb980..0add488b2 100644 --- a/backend/tests/handler/database/test_rom_sibling_groups.py +++ b/backend/tests/handler/database/test_rom_sibling_groups.py @@ -1,7 +1,11 @@ +import threading +import time + from sqlalchemy import delete, select from tests.factories import make_rom -from handler.database import db_rom_handler +from handler.auth.rom_visibility import UNRESTRICTED +from handler.database import db_rom_handler, sibling_groups from handler.database.base_handler import sync_session from models.platform import Platform from models.rom import Rom, RomSiblingGroup, RomUser @@ -123,6 +127,52 @@ class TestSiblingGroups: assert _groups() == {first.id: first.id, bridge.id: first.id, last.id: first.id} + def test_two_writers_grouping_one_rom_both_commit(self, platform: Platform): + """The second writer reads before the first commits, then meets its row.""" + existing = make_rom(platform, "Raced (USA)", igdb_id=90) + first_grouped = threading.Event() + errors: list[Exception] = [] + + def write(name: str, *, after: threading.Event | None) -> None: + if after is not None: + after.wait(timeout=5) + try: + with sync_session.begin() as session: + rom = Rom( + platform_id=platform.id, + name=name, + fs_name=f"{name}.zip", + fs_path="roms", + igdb_id=90, + ) + session.add(rom) + session.flush() + sibling_groups.regroup(session, [rom.id]) + if after is None: + first_grouped.set() + # Holds the row lock while the second writer runs. + time.sleep(0.5) + except Exception as exc: + errors.append(exc) + + writers = [ + threading.Thread( + target=write, args=("Raced (Europe)",), kwargs={"after": None} + ), + threading.Thread( + target=write, args=("Raced (Japan)",), kwargs={"after": first_grouped} + ), + ] + for writer in writers: + writer.start() + for writer in writers: + writer.join() + + assert errors == [] + groups = _groups() + assert len(groups) == 3 + assert set(groups.values()) == {existing.id} + class TestSiblingRepresentatives: def test_every_version_maps_to_the_gallery_card( @@ -132,7 +182,9 @@ class TestSiblingRepresentatives: (card,) = _gallery(platform, admin_user.id) representatives = db_rom_handler.get_sibling_representatives( - [first.id, bridge.id, last.id], user_id=admin_user.id + [first.id, bridge.id, last.id], + user_id=admin_user.id, + visibility=UNRESTRICTED, ) assert representatives == {first.id: card, bridge.id: card, last.id: card} @@ -143,7 +195,7 @@ class TestSiblingRepresentatives: db_rom_handler.update_rom_user(rom_user.id, {"is_main_sibling": True}) representatives = db_rom_handler.get_sibling_representatives( - [first.id], user_id=admin_user.id + [first.id], user_id=admin_user.id, visibility=UNRESTRICTED ) assert representatives == {first.id: last.id} @@ -157,7 +209,7 @@ class TestSiblingRepresentatives: session.add(RomUser(rom_id=first.id, user_id=admin_user.id, hidden=True)) representatives = db_rom_handler.get_sibling_representatives( - [first.id], user_id=admin_user.id + [first.id], user_id=admin_user.id, visibility=UNRESTRICTED ) assert representatives[first.id] != first.id @@ -171,7 +223,7 @@ class TestSiblingRepresentatives: assert _gallery(platform, admin_user.id) == [first.id] assert db_rom_handler.get_sibling_representatives( - [second.id], user_id=admin_user.id + [second.id], user_id=admin_user.id, visibility=UNRESTRICTED ) == {second.id: first.id} def test_a_rom_without_siblings_represents_itself( @@ -180,5 +232,5 @@ class TestSiblingRepresentatives: rom = make_rom(platform, "Solo", igdb_id=70) assert db_rom_handler.get_sibling_representatives( - [rom.id], user_id=admin_user.id + [rom.id], user_id=admin_user.id, visibility=UNRESTRICTED ) == {rom.id: rom.id} 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 486d893e6..036108e8a 100644 --- a/backend/tests/handler/database/test_roms_group_by_index.py +++ b/backend/tests/handler/database/test_roms_group_by_index.py @@ -16,9 +16,8 @@ was paid four times over. 0107 widened the index to close the gap. 0108 added `generated_primary_region` for the same reason: region priority ranks each sibling, and `roms.regions` is JSON that no covering index can carry. -The failure mode is silent, and adding a metadata provider is the way back into -it: a new id column joins the window's COALESCE chain, the index does not follow -it, and the gallery quietly returns to full scans. +The failure mode is silent: a `roms` column the window starts reading that the +index does not follow quietly returns the gallery to full scans. """ import re diff --git a/backend/tests/handler/recommendation/test_feed.py b/backend/tests/handler/recommendation/test_feed.py index 0ba549e23..0f66d3a90 100644 --- a/backend/tests/handler/recommendation/test_feed.py +++ b/backend/tests/handler/recommendation/test_feed.py @@ -1,6 +1,7 @@ from datetime import datetime, timedelta, timezone import pytest +from tests.factories import make_rom from handler.database import db_rom_handler from handler.database.recommendations_handler import UserAffinityRow @@ -8,9 +9,11 @@ from handler.recommendation.feed import ( MIN_RECENCY_FACTOR, RECENCY_HALFLIFE_DAYS, _cache_key, + first_distinct_games, seed_affinity, ) from handler.redis_handler import sync_cache +from models.platform import Platform from models.rom import RomUserStatus NOW = datetime(2026, 8, 7, tzinfo=timezone.utc) @@ -164,3 +167,14 @@ class TestFeedCacheInvalidation: db_rom_handler.update_rom_user(rom_user.id, {"difficulty": 3}) assert sync_cache.get(_cache_key(admin_user.id, 10)) is not None + + +def test_a_version_off_disk_leaves_its_slot_to_one_on_disk(platform: Platform): + gone = make_rom(platform, "Game (USA)", igdb_id=7101) + kept = make_rom(platform, "Game (Europe)", igdb_id=7101) + other = make_rom(platform, "Other Game", igdb_id=7102) + db_rom_handler.update_rom(gone.id, {"missing_from_fs": True}) + + assert first_distinct_games( + [[gone.id, kept.id, other.id]], lambda rom_id: rom_id, want=2 + ) == [kept.id, other.id] diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index a6c0cd2d9..d83c7f297 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -533,7 +533,7 @@ def test_the_search_titles_revision_reverses_replays_and_fills(platform: Platfor def test_the_sibling_groups_revision_reverses_replays_and_backfills( platform: Platform, ): - """0158 groups a chain of different provider ids into one game.""" + """0162 groups a chain of different provider ids into one game.""" migration = _load_migration("0162_rom_sibling_groups.py") first = make_rom(platform, "Chain (USA)", igdb_id=10) bridge = make_rom(platform, "Chain (Europe)", igdb_id=10, ss_id=20)