Files
romm/backend/handler/database/recommendations_handler.py
Sam Dornan 4f59480ae5 fix(backend): correct ranking defects found on a real library
Validating the index against a 12.7k-game library surfaced four problems a
synthetic fixture could not, because each depends on the shape of real
metadata.

Stop penalising well-documented games. Vectors were L2-normalised, on the
assumption that facet counts behave like document length in text retrieval.
They do not: a long document repeating a word is not more relevant, but a game
tagged with three genres and two franchises genuinely has more in common than
one carrying a single tag. Normalising by a vector's own length made every top
match a sparsely-tagged entry -- a Mario compilation matched Golf, F-1 Race and
Pinball (6-8 tokens each) while the actual Mario platformers (12-16 tokens)
were nowhere in the list. Scaling by the library average instead returns
Yoshi's Island, Super Mario 64 and Donkey Kong.

Two hypotheses were measured and rejected on the way: franchise coherence via
genre entropy (Metroid scored higher than Mario, so no signal) and the
franchise/genre weight ratio (five configurations, none of which moved the
result).

Suppress duplicates against each other, not just against the source. Two discs
of one release share an igdb_id and platform, so both took a slot in the same
list. The same game ported to another platform gets its own igdb_id, so it
needs a title comparison rather than an id one.

Diversify across series. Similarity ranking alone made the section a franchise
filter -- five Metroid games for Super Metroid. Slots are reserved at build
time so the stored graph always carries cross-series options, and the per-
series cap is applied when serving so the policy can change without a rebuild.
Capped-out entries backfill a short list in score order.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 21:17:00 -05:00

397 lines
13 KiB
Python

from __future__ import annotations
from collections.abc import Iterator, Sequence
from typing import Any, NamedTuple
from sqlalchemy import delete, func, insert, select
from sqlalchemy.orm import Session
from decorators.database import begin_session
from models.collection import CollectionRom
from models.play_session import PlaySession
from models.recommendation import RomSimilarity
from models.rom import Rom, RomFacets, RomMetadata, RomUser
from .base_handler import DBBaseHandler
# Streaming chunk for the wide `roms` scan that reads the IGDB metadata blobs.
IGDB_SCAN_CHUNK_SIZE = 500
# Rows per INSERT when rewriting the similarity table.
EDGE_INSERT_CHUNK_SIZE = 1_000
# Co-occurrence sets larger than this say more about the collector than the
# games: a 900-ROM "Everything" collection would otherwise emit 400k pairs and
# relate its entire contents to itself.
MAX_CO_OCCURRENCE_SET_SIZE = 250
class RomFeatureRow(NamedTuple):
"""The narrow slice of metadata the similarity build reads per ROM."""
rom_id: int
platform_id: int
title_key: str | None
genres: list[str] | None
franchises: list[str] | None
collections: list[str] | None
companies: list[str] | None
game_modes: list[str] | None
first_release_date: int | None
average_rating: float | None
class UserAffinityRow(NamedTuple):
"""One ROM the user has engaged with, and how strongly."""
rom_id: int
rating: int | None
difficulty: int | None
completion: int | None
status: str | None
last_played: Any | None
now_playing: bool
backlogged: bool
hidden: bool
playtime_ms: int
class SimilarRomEdge(NamedTuple):
rom_id: int
score: float
reasons: list[dict[str, Any]]
class DBRecommendationsHandler(DBBaseHandler):
# --- Similarity build inputs -------------------------------------------------
@begin_session
def get_feature_rows(
self, session: Session = None # type: ignore
) -> list[RomFeatureRow]:
"""Every ROM's facet values, for building the library-wide IDF.
Reads `roms_facets` rather than `roms` on purpose: the facet values are
mirrored there precisely so aggregations never touch the wide rows with
their provider-metadata blobs.
"""
stmt = (
select(
RomFacets.rom_id,
RomFacets.platform_id,
Rom.name_sort_key,
RomFacets.genres,
RomFacets.franchises,
RomFacets.collections,
RomFacets.companies,
RomFacets.game_modes,
RomMetadata.first_release_date,
RomMetadata.average_rating,
)
.join(Rom, Rom.id == RomFacets.rom_id)
.outerjoin(RomMetadata, RomMetadata.rom_id == RomFacets.rom_id)
.where(Rom.missing_from_fs.is_(False))
)
return [RomFeatureRow(*row) for row in session.execute(stmt).all()]
@begin_session
def get_rom_igdb_ids(
self, session: Session = None # type: ignore
) -> dict[int, int]:
"""ROM id -> IGDB id.
Keyed by ROM id, not IGDB id: the relationship is many-to-one (region
and revision variants of one game share an IGDB id), and keying the
other way would silently drop every duplicate but one -- which is
exactly the set the duplicate suppression needs to see.
"""
stmt = select(RomFacets.rom_id, RomFacets.igdb_id).where(
RomFacets.igdb_id.is_not(None)
)
return {rom_id: igdb_id for rom_id, igdb_id in session.execute(stmt).all()}
@begin_session
def iter_igdb_related(
self, session: Session = None # type: ignore
) -> Iterator[tuple[int, list[int]]]:
"""Stream each ROM's IGDB related-game ids out of its metadata blob.
Yields in chunks because this is the one query that has to read the
wide `roms` row; everything else in the build works off narrow tables.
"""
stmt = (
select(Rom.id, Rom.igdb_metadata)
.where(Rom.igdb_id.is_not(None), Rom.missing_from_fs.is_(False))
.execution_options(yield_per=IGDB_SCAN_CHUNK_SIZE)
)
for rom_id, metadata in session.execute(stmt):
if not metadata:
continue
related_ids: list[int] = []
for bucket in (
"similar_games",
"remakes",
"remasters",
"expanded_games",
"ports",
"expansions",
"dlcs",
):
for entry in metadata.get(bucket) or ():
entry_id = entry.get("id") if isinstance(entry, dict) else None
if isinstance(entry_id, int):
related_ids.append(entry_id)
if related_ids:
yield rom_id, related_ids
@begin_session
def get_collection_membership_sets(
self, session: Session = None # type: ignore
) -> list[list[int]]:
"""ROM ids grouped by user collection, for co-membership scoring."""
stmt = select(CollectionRom.collection_id, CollectionRom.rom_id).order_by(
CollectionRom.collection_id
)
return self._group_second_by_first(session.execute(stmt).all())
@begin_session
def get_played_sets(
self, session: Session = None # type: ignore
) -> list[list[int]]:
"""ROM ids grouped by user, restricted to games they actually played.
This is the item-based collaborative signal. On a single-user server it
degrades gracefully into "things I play together" rather than vanishing.
"""
stmt = (
select(RomUser.user_id, RomUser.rom_id)
.where(RomUser.last_played.is_not(None))
.order_by(RomUser.user_id)
)
return self._group_second_by_first(session.execute(stmt).all())
@staticmethod
def _group_second_by_first(rows: Sequence[Any]) -> list[list[int]]:
"""Bucket (key, rom_id) rows into per-key id lists, dropping the noisy ones.
Singletons carry no pair information and oversized sets carry mostly
noise, so neither is worth handing to the pair counter.
"""
grouped: dict[int, list[int]] = {}
for key, rom_id in rows:
grouped.setdefault(key, []).append(rom_id)
return [
ids
for ids in grouped.values()
if 1 < len(ids) <= MAX_CO_OCCURRENCE_SET_SIZE
]
# --- Similarity build output -------------------------------------------------
@begin_session
def replace_similarity_edges(
self,
rom_ids: Sequence[int],
edges: Sequence[dict[str, Any]],
session: Session = None, # type: ignore
) -> int:
"""Swap in a batch of ROMs' edges.
Scoped to `rom_ids` rather than truncating the table so the build can
commit incrementally: a task that dies halfway leaves stale edges for
the ROMs it never reached, not an empty recommendations table.
"""
if not rom_ids:
return 0
session.execute(delete(RomSimilarity).where(RomSimilarity.rom_id.in_(rom_ids)))
written = 0
for start in range(0, len(edges), EDGE_INSERT_CHUNK_SIZE):
chunk = edges[start : start + EDGE_INSERT_CHUNK_SIZE]
if chunk:
session.execute(insert(RomSimilarity), chunk)
written += len(chunk)
return written
@begin_session
def delete_all_similarity_edges(
self, session: Session = None # type: ignore
) -> None:
session.execute(delete(RomSimilarity))
@begin_session
def count_similarity_edges(self, session: Session = None) -> int: # type: ignore
return session.scalar(select(func.count()).select_from(RomSimilarity)) or 0
# --- Reads -------------------------------------------------------------------
@begin_session
def get_similar_rom_edges(
self,
rom_id: int,
limit: int = 20,
session: Session = None, # type: ignore
) -> list[SimilarRomEdge]:
"""Top precomputed neighbours of one ROM, best first.
Returns ids rather than ROMs so every caller hydrates through the same
`SimpleRomSchema` load path instead of each growing its own.
"""
stmt = (
select(
RomSimilarity.related_rom_id,
RomSimilarity.score,
RomSimilarity.reasons,
)
.where(RomSimilarity.rom_id == rom_id)
.order_by(RomSimilarity.score.desc(), RomSimilarity.related_rom_id.asc())
.limit(limit)
)
return [
SimilarRomEdge(rom_id=related_id, score=score, reasons=reasons or [])
for related_id, score, reasons in session.execute(stmt).all()
]
@begin_session
def get_neighbours_for_roms(
self,
rom_ids: Sequence[int],
limit_per_rom: int = 20,
session: Session = None, # type: ignore
) -> list[tuple[int, int, float, list[dict[str, Any]]]]:
"""Edges fanning out from a set of seed ROMs, for the personalised feed.
Returns raw (seed_rom_id, related_rom_id, score, reasons) tuples; the
ranking handler hydrates only the ROMs that survive its cut.
"""
if not rom_ids:
return []
stmt = (
select(
RomSimilarity.rom_id,
RomSimilarity.related_rom_id,
RomSimilarity.score,
RomSimilarity.reasons,
)
.where(RomSimilarity.rom_id.in_(rom_ids))
.order_by(RomSimilarity.rom_id, RomSimilarity.score.desc())
)
# Trim per seed in Python: a per-group LIMIT needs a window function,
# and the row counts here are already bounded by the build's top-N cut.
per_seed: dict[int, int] = {}
results: list[tuple[int, int, float, list[dict[str, Any]]]] = []
for seed_id, related_id, score, reasons in session.execute(stmt):
taken = per_seed.get(seed_id, 0)
if taken >= limit_per_rom:
continue
per_seed[seed_id] = taken + 1
results.append((seed_id, related_id, score, reasons or []))
return results
@begin_session
def get_user_affinity(
self,
user_id: int,
session: Session = None, # type: ignore
) -> list[UserAffinityRow]:
"""Everything the user has done with each ROM, plus total playtime.
Playtime comes from `play_sessions` (the accurate signal) while the
rest comes from `rom_user`; a ROM can appear with either or both.
"""
playtime_subq = (
select(
PlaySession.rom_id.label("rom_id"),
func.coalesce(func.sum(PlaySession.duration_ms), 0).label(
"playtime_ms"
),
)
.where(PlaySession.user_id == user_id, PlaySession.rom_id.is_not(None))
.group_by(PlaySession.rom_id)
.subquery()
)
stmt = (
select(
RomUser.rom_id,
RomUser.rating,
RomUser.difficulty,
RomUser.completion,
RomUser.status,
RomUser.last_played,
RomUser.now_playing,
RomUser.backlogged,
RomUser.hidden,
func.coalesce(playtime_subq.c.playtime_ms, 0),
)
.outerjoin(playtime_subq, playtime_subq.c.rom_id == RomUser.rom_id)
.where(RomUser.user_id == user_id)
)
return [
UserAffinityRow(
rom_id=row[0],
rating=row[1],
difficulty=row[2],
completion=row[3],
status=row[4].value if hasattr(row[4], "value") else row[4],
last_played=row[5],
now_playing=bool(row[6]),
backlogged=bool(row[7]),
hidden=bool(row[8]),
playtime_ms=int(row[9] or 0),
)
for row in session.execute(stmt).all()
]
@begin_session
def get_rom_names(
self,
rom_ids: Sequence[int],
session: Session = None, # type: ignore
) -> dict[int, str]:
"""Display names only, for the "Because you played X" attribution."""
if not rom_ids:
return {}
stmt = select(Rom.id, Rom.name, Rom.fs_name).where(Rom.id.in_(rom_ids))
return {
rom_id: name or fs_name
for rom_id, name, fs_name in session.execute(stmt).all()
}
@begin_session
def get_fallback_rom_ids(
self,
limit: int,
exclude_rom_ids: Sequence[int] = (),
session: Session = None, # type: ignore
) -> list[int]:
"""Cold-start feed: the best-reviewed games in the library."""
stmt = (
select(Rom.id)
.join(RomMetadata, RomMetadata.rom_id == Rom.id)
.where(
Rom.missing_from_fs.is_(False),
RomMetadata.average_rating.is_not(None),
)
.order_by(RomMetadata.average_rating.desc(), Rom.name_sort_key.asc())
.limit(limit)
)
if exclude_rom_ids:
stmt = stmt.where(Rom.id.not_in(exclude_rom_ids))
return list(session.execute(stmt).scalars().all())