Files
romm/backend/handler/recommendation/serving.py
Georges-Antoine Assi 68709e79a7 fix(siblings): group versions by connected component everywhere (#5430)
* fix(siblings): group versions by connected component everywhere

The game page's siblings matched on any shared provider id, while the
gallery's group_by_meta_id window partitioned on the first non-null id in
a fixed provider order. A version matched by IGDB and ScreenScraper and
one matched by ScreenScraper alone were siblings on the game page but two
gallery cards. The recommendation surfaces didn't group at all: the
cold-start row ranks by rating, which every version shares, so one game
filled it.

rom_sibling_groups now stores each ROM's connected component over
rom_identity_keys, kept in step by add_rom/update_rom/delete_rom and
rebuilt after a scan. The sibling_roms view, the gallery window and the
recommendations all read it: the feed and similar games collapse each
game to one entry, exclude the other versions of a played game, and
show the version the grouped gallery shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(siblings): answer the Versions filter from rom_sibling_groups

Only a ROM with another version has a group row, so "has versions" is a
primary-key probe rather than an EXISTS over the sibling_roms self-join.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(siblings): break representative ties by id; restore Versions filter

Versions often share a filename stem and region, and without a final key
the version that represents a group could change between queries.

The "Versions" filter goes back to EXISTS over sibling_roms: measured on
a 100k-ROM library it takes the same time as the direct group-row probe
(107 ms each), since the view merges into the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(migrations): renumber rom_sibling_groups to 0158 after master's 0157

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): address Greptile review on sibling grouping

- Swap each recommendation to its visible representative before the
  visibility cut, so a game whose top-ranked version is hidden shows
  through a visible one instead of disappearing.
- Read candidates in batches until enough distinct games remain, so a
  game with more versions than one overfetch batch no longer crowds out
  the rest of the feed; the cold-start query pages with an id tiebreak.
- Shorten the 0158 migration and RomSiblingGroup docstrings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(recommendations): use the shared auth helpers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose (code-review fixes)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): hide only the hidden version, as the gallery does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(siblings): regroup only on identity changes and scope the post-scan repair

add_rom skips the regroup when the merge changed no identity column. The
post-scan repair regroups the scanned ROMs for a ROM-scoped scan and
rebuilds only the scanned platforms otherwise, since no group spans two
platforms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:07:57 -05:00

145 lines
4.9 KiB
Python

"""The read path behind both recommendation surfaces.
"Similar games" and the personalised feed differ only in where their ranking
comes from; everything after that (rank deep, hydrate, drop what the viewer
cannot see, cap by series, truncate) is shared.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import replace
from handler.auth.permissions import ResolvedPermissions
from handler.database import db_recommendation_handler, db_rom_handler
from handler.recommendation.diversity import (
OVERFETCH_FACTOR,
cap_by_series,
collapse_sibling_groups,
)
from handler.recommendation.feed import (
FeedBuilder,
RecommendedRom,
get_cached_feed,
hydrate_roms,
set_cached_feed,
)
# Extra depth for a viewer whose visibility rules hide ROMs: ranking exactly
# `limit` and filtering afterwards hands them a short row, or an empty one.
VISIBILITY_OVERFETCH = 3
def similar_roms(
rom_id: int, *, limit: int, permissions: ResolvedPermissions
) -> list[RecommendedRom]:
"""The library's closest games to one ROM, best first."""
edges = db_recommendation_handler.get_similar_rom_edges(
rom_id, limit=_ranked_depth(limit, permissions)
)
group_keys = db_rom_handler.get_sibling_group_keys(
[rom_id, *(edge.rom_id for edge in edges)]
)
edges = collapse_sibling_groups(
edges,
lambda edge: edge.rom_id,
group_keys,
seen={group_keys.get(rom_id, rom_id)},
)
roms = hydrate_roms([edge.rom_id for edge in edges], include_missing=True)
candidates = _visible_representatives(
[
RecommendedRom(
rom=roms[edge.rom_id], score=edge.score, reasons=edge.reasons
)
for edge in edges
if edge.rom_id in roms
],
permissions,
)
# Without the cap this section is just the franchise the user is already
# looking at: five Metroid games for Super Metroid.
return cap_by_series(candidates, lambda item: item.rom, limit=limit)
def recommended_roms(
user_id: int,
*,
limit: int,
permissions: ResolvedPermissions,
refresh: bool = False,
) -> list[RecommendedRom]:
"""The personalised feed, ranked on demand and cached per user.
The cache lives here rather than in the endpoint so no caller can rank a
feed without populating it, or read a stale one after an exclusion changes.
"""
ranked_limit = (
limit * VISIBILITY_OVERFETCH
if not permissions.rom_visibility.is_unrestricted
else limit
)
feed = None if refresh else get_cached_feed(user_id, ranked_limit)
if feed is None:
feed = FeedBuilder(user_id).build(limit=ranked_limit)
set_cached_feed(user_id, ranked_limit, feed)
# Visibility is applied after the cache so a permission change takes effect
# without waiting for the entry to expire.
visible = _visible_representatives(feed, permissions)[:limit]
hidden_seeds = db_rom_handler.get_hidden_rom_ids_among(
[item.seed_rom_id for item in visible if item.seed_rom_id is not None],
permissions.rom_visibility,
)
return [
(
replace(item, seed_rom_id=None, seed_rom_name=None)
if item.seed_rom_id in hidden_seeds
else item
)
for item in visible
]
def _visible_representatives(
items: Sequence[RecommendedRom], permissions: ResolvedPermissions
) -> list[RecommendedRom]:
"""Swap in each game's representative, then drop what the viewer can't see."""
# Swapping first lets a visible version stand in for a hidden one, and
# resolving per request applies a main-version pick without waiting out the cache.
representatives = db_rom_handler.get_sibling_representatives(
[item.rom.id for item in items],
user_id=permissions.user_id,
visibility=permissions.rom_visibility,
)
swapped_ids = {
representatives[item.rom.id]
for item in items
if representatives.get(item.rom.id, item.rom.id) != item.rom.id
}
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 or representative_id in emitted:
continue
rom = swapped.get(representative_id, item.rom)
if rom.id != representative_id or not permissions.can_see_rom(rom):
continue
emitted.add(representative_id)
result.append(replace(item, rom=rom))
return result
def _ranked_depth(limit: int, permissions: ResolvedPermissions) -> int:
"""How deep to rank so `limit` entries survive the cuts below."""
depth = limit * OVERFETCH_FACTOR
if permissions.rom_visibility.is_unrestricted:
return depth
return depth * VISIBILITY_OVERFETCH