Files
romm/backend/utils/sibling_groups.py
Georges-Antoine Assi ff412aa09c 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>
2026-10-31 20:12:06 -04:00

38 lines
1.3 KiB
Python

from collections.abc import Hashable, Iterable
def sibling_groups(key_rows: Iterable[tuple[int, Hashable]]) -> dict[int, int]:
"""Group ROMs that are linked through any chain of shared identity keys.
Args:
key_rows: (rom id, identity key) pairs, one per key a ROM holds.
Returns:
Each ROM's group id (its group's lowest ROM id), for ROMs in a group
of two or more only.
"""
parent: dict[int, int] = {}
def find(rom_id: int) -> int:
root = parent.setdefault(rom_id, rom_id)
while root != parent[root]:
# Path halving keeps a long chain from making every lookup linear.
parent[root] = parent[parent[root]]
root = parent[root]
return root
key_owner: dict[Hashable, int] = {}
for rom_id, key in key_rows:
find(rom_id)
owner = key_owner.setdefault(key, rom_id)
left, right = find(owner), find(rom_id)
if left != right:
# The lower id wins, so a root is always its group's lowest member.
parent[max(left, right)] = min(left, right)
roots = {rom_id: find(rom_id) for rom_id in parent}
sizes: dict[int, int] = {}
for root in roots.values():
sizes[root] = sizes.get(root, 0) + 1
return {rom_id: root for rom_id, root in roots.items() if sizes[root] > 1}