fix(backend): weight a rating by the votes behind it in the cold-start feed

`average_rating` averages whatever providers happened to rate a game, so a
lone ScreenScraper 10/10 is indistinguishable from a broad consensus. The
cold-start feed ordered by that rating alone.

On a real 12.7k library exactly fourteen games scored a perfect 100, every one
of them a single ScreenScraper score with IGDB unrated. The feed returns
fifteen results, so it was reduced to listing those fourteen alphabetically:
"The Adventures of Batman & Robin", "Adventures of Lolo", "American Bass
Challenge", "Aussie Rules Footy". This is the first thing a new install shows
anyone, since nobody has play history on day one.

Storing IGDB's vote count lets the feed use a Bayesian average, shrinking a
rating toward the library mean in proportion to how little evidence backs it.
The same library now opens with A Link to the Past (1,710 votes), Uncharted 2
(2,216), Ocarina of Time (2,138) and GTA: San Andreas (4,012).

Games with no vote count -- most of them, since only IGDB reports one -- land
at the library mean rather than dropping out, which a test pins.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Sam DornanandClaude Opus 5 committed 2026-08-07 22:11:42 -05:00
1 parent da896efab5
commit 7c010ca732
6 files changed
+221 -12

No files matched your search

@@ -0,0 +1,107 @@
"""Expose IGDB's rating count so a rating can be weighted by its confidence
`average_rating` averages whatever providers rated a game, which makes a
single ScreenScraper 10/10 indistinguishable from a broad consensus. On a real
12.7k library exactly fourteen games scored a perfect 100, every one of them a
lone ScreenScraper score with IGDB unrated -- and the cold-start feed, which
orders by rating alone, recommended all fourteen alphabetically.
Storing IGDB's vote count lets that feed shrink a rating toward the library
mean in proportion to how little evidence backs it.
Only IGDB reports a count, and `manual_metadata` can override it like every
other generated facet.
Revision ID: 0110_rating_count_column
Revises: 0109_igdb_tag_columns
Create Date: 2026-08-08 00:00:00.000000
"""
from alembic import op # type: ignore[attr-defined]
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "0110_rating_count_column"
down_revision = "0109_igdb_tag_columns"
branch_labels = None
depends_on = None
_COLUMN = "generated_rating_count"
_SOURCES = ["manual_metadata", "igdb_metadata"]
# Restated in full because CREATE OR REPLACE VIEW rewrites every projection.
_VIEW_COLUMNS = [
("generated_genres", "genres"),
("generated_franchises", "franchises"),
("generated_collections", "collections"),
("generated_companies", "companies"),
("generated_game_modes", "game_modes"),
("generated_age_ratings", "age_ratings"),
("generated_keywords", "keywords"),
("generated_themes", "themes"),
("generated_player_perspectives", "player_perspectives"),
("generated_first_release_date", "first_release_date"),
("generated_average_rating", "average_rating"),
("generated_player_count", "player_count"),
]
def _maria_expr() -> str:
branches = [
f"NULLIF(JSON_VALUE({src}, '$.total_rating_count'), '')" for src in _SOURCES
]
return "CAST(COALESCE(" + ", ".join(branches) + ", 0) AS SIGNED)"
def _postgres_expr() -> str:
branches = [f"({src} ->> 'total_rating_count')" for src in _SOURCES]
return (
"COALESCE("
+ ", ".join(f"NULLIF({b}, '')::numeric" for b in branches)
+ ", 0)::bigint"
)
def _view_sql(is_pg: bool, columns: list[tuple[str, str]]) -> str:
projections = ",\n ".join(
# The view exposed player_count as text and PostgreSQL cannot change a
# column's type through CREATE OR REPLACE VIEW.
(
f"{name}::text AS {alias}"
if is_pg and alias == "player_count"
else f"{name} AS {alias}"
)
for name, alias in columns
)
return (
"CREATE OR REPLACE VIEW roms_metadata AS\n" # nosec B608
"SELECT\n"
" id AS rom_id,\n"
" NOW() AS created_at,\n"
" NOW() AS updated_at,\n"
f" {projections}\n"
"FROM roms"
)
def upgrade() -> None:
is_pg = is_postgresql(op.get_bind())
expr = _postgres_expr() if is_pg else _maria_expr()
column_type = "BIGINT" if is_pg else "BIGINT"
op.execute(
f"ALTER TABLE roms ADD COLUMN {_COLUMN} {column_type} " # nosec B608
f"GENERATED ALWAYS AS ({expr}) STORED"
)
op.execute(_view_sql(is_pg, _VIEW_COLUMNS + [(_COLUMN, "rating_count")]))
def downgrade() -> None:
is_pg = is_postgresql(op.get_bind())
# The view has to stop referencing the column before it can be dropped.
op.execute("DROP VIEW IF EXISTS roms_metadata")
op.execute(_view_sql(is_pg, _VIEW_COLUMNS).replace("CREATE OR REPLACE", "CREATE"))
op.execute(f"ALTER TABLE roms DROP COLUMN {_COLUMN}")
@@ -25,6 +25,11 @@ EDGE_INSERT_CHUNK_SIZE = 1_000
# relate its entire contents to itself.
MAX_CO_OCCURRENCE_SET_SIZE = 250
# Votes a rating needs before it is trusted on its own in the cold-start feed.
# Below this it is blended with the library mean; well above it, the raw rating
# carries. Tuned so a handful of votes cannot float an obscure game to the top.
BAYESIAN_PRIOR_VOTES = 50
class RomFeatureRow(NamedTuple):
"""The narrow slice of metadata the similarity build reads per ROM."""
@@ -384,7 +389,28 @@ class DBRecommendationsHandler(DBBaseHandler):
exclude_rom_ids: Sequence[int] = (),
session: Session = None, # type: ignore
) -> list[int]:
"""Cold-start feed: the best-reviewed games in the library."""
"""Cold-start feed: the best-reviewed games in the library.
Ranked by a Bayesian average rather than the raw rating. A rating
backed by few votes is pulled toward the library mean in proportion to
how little evidence supports it, so a lone provider's perfect score no
longer outranks a broadly-liked classic. Without this the feed was
fourteen games that one source rated 100, listed alphabetically.
"""
mean_rating = session.scalar(
select(func.avg(RomMetadata.average_rating)).where(
RomMetadata.average_rating.is_not(None)
)
)
prior = float(mean_rating or 0.0)
votes = func.coalesce(RomMetadata.rating_count, 0)
# (v * R + m * C) / (v + m): the standard shrinkage estimator, with m
# acting as "how many votes it takes to be believed on your own".
bayesian = (
votes * RomMetadata.average_rating + BAYESIAN_PRIOR_VOTES * prior
) / (votes + BAYESIAN_PRIOR_VOTES)
stmt = (
select(Rom.id)
.join(RomMetadata, RomMetadata.rom_id == Rom.id)
@@ -392,7 +418,7 @@ class DBRecommendationsHandler(DBBaseHandler):
Rom.missing_from_fs.is_(False),
RomMetadata.average_rating.is_not(None),
)
.order_by(RomMetadata.average_rating.desc(), Rom.name_sort_key.asc())
.order_by(bayesian.desc(), Rom.name_sort_key.asc())
.limit(limit)
)
+6
View File
@@ -119,6 +119,10 @@ class IGDBMetadataMultiplayerMode(TypedDict):
class IGDBMetadata(TypedDict):
total_rating: str | None
# How many votes back total_rating. A 10/10 from one source is not the
# same claim as 9/10 from a thousand, and the cold-start feed needs to
# tell them apart.
total_rating_count: int | None
aggregated_rating: str | None
first_release_date: int | None
youtube_video_id: str | None
@@ -259,6 +263,7 @@ def extract_metadata_from_igdb_rom(
{
"youtube_video_id": videos[0].get("video_id") if videos else None,
"total_rating": str(round(rom.get("total_rating", 0.0), 2)),
"total_rating_count": rom.get("total_rating_count", 0),
"aggregated_rating": str(round(rom.get("aggregated_rating", 0.0), 2)),
"first_release_date": rom.get("first_release_date", None),
"genres": [g.get("name", "") for g in genres if g.get("name")],
@@ -1085,6 +1090,7 @@ GAMES_FIELDS = (
"ports.slug",
"ports.name",
"ports.cover.url",
"total_rating_count",
"keywords.name",
"themes.name",
"player_perspectives.name",
+3
View File
@@ -268,6 +268,9 @@ class RomMetadata(BaseModel):
player_count: Mapped[str | None] = mapped_column(String(length=100), default="1")
first_release_date: Mapped[int | None] = mapped_column(BigInteger(), default=None)
average_rating: Mapped[float | None] = mapped_column(default=None)
# Votes behind `average_rating`, from IGDB. Zero where no provider
# reported one, which is how an unbacked perfect score is spotted.
rating_count: Mapped[int | None] = mapped_column(BigInteger(), default=0)
rom: Mapped[Rom] = relationship(lazy="joined", back_populates="metadatum")
@@ -24,6 +24,7 @@ def make_rom(
companies: list[str] | None = None,
similar_igdb_ids: list[int] | None = None,
average_rating: float | None = None,
rating_votes: int | None = None,
) -> Rom:
metadata: dict = {
"genres": genres or [],
@@ -35,6 +36,8 @@ def make_rom(
if average_rating is not None:
# IGDB's total_rating is carried as a string; the generated column casts it.
metadata["total_rating"] = str(average_rating)
if rating_votes is not None:
metadata["total_rating_count"] = rating_votes
if similar_igdb_ids:
metadata["similar_games"] = [
{"id": similar_id, "name": f"game-{similar_id}", "type": "similar"}
@@ -284,3 +287,58 @@ def test_build_on_an_empty_library_is_a_no_op():
assert stats.roms_indexed == 0
assert stats.edges_written == 0
def test_cold_start_prefers_a_well_voted_rating_over_a_lone_perfect_one(
platform: Platform,
):
"""Regression: the cold-start feed used to be topped by obscure games.
A single provider scoring something 100 is not evidence it is a great
game. On a real library exactly fourteen games hit a perfect 100, every
one a lone ScreenScraper score, and the feed recommended all of them
ahead of the classics.
"""
# Shrinkage is toward the library mean, so the library needs a realistic
# one. With only the two games below, the mean sits between them and the
# estimator has nothing to pull the outlier down to.
for index in range(12):
make_rom(
platform,
f"Ordinary Game {index}",
igdb_id=7100 + index,
genres=["Action"],
average_rating=60.0 + index,
rating_votes=40,
)
lone_perfect = make_rom(
platform,
"Obscure Sports Title",
igdb_id=7001,
genres=["Sport"],
average_rating=100.0,
rating_votes=1,
)
broadly_loved = make_rom(
platform,
"Beloved Classic",
igdb_id=7002,
genres=["Adventure"],
average_rating=94.0,
rating_votes=1800,
)
ranked = db_recommendation_handler.get_fallback_rom_ids(limit=10)
assert broadly_loved.id in ranked
assert ranked.index(broadly_loved.id) < ranked.index(lone_perfect.id)
def test_cold_start_still_returns_games_with_no_vote_count(platform: Platform):
"""Most providers report no count at all; those games must not vanish."""
unvoted = make_rom(
platform, "Unvoted Game", igdb_id=7003, genres=["RPG"], average_rating=88.0
)
assert unvoted.id in db_recommendation_handler.get_fallback_rom_ids(limit=25)
+19 -10
View File
@@ -23,6 +23,7 @@ import argparse
import asyncio
import os
import sys
from typing import Any
# Allow running as `python3 tools/backfill_igdb_tags.py` from backend/.
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -37,8 +38,16 @@ from utils.context import initialize_context # noqa: E402
# IGDB caps a single response at 500 rows.
BATCH_SIZE = 500
TAG_FIELDS = ("id", "keywords.name", "themes.name", "player_perspectives.name")
TAG_FIELDS = (
"id",
"keywords.name",
"themes.name",
"player_perspectives.name",
"total_rating_count",
)
TAG_KEYS = ("keywords", "themes", "player_perspectives")
# Scalar rather than a list of named entities, so it is merged separately.
SCALAR_KEYS = ("total_rating_count",)
def load_igdb_ids(limit: int | None) -> dict[int, int]:
@@ -58,19 +67,19 @@ def report_coverage() -> None:
).all()
total = len(rows)
have = {key: 0 for key in TAG_KEYS}
have = {key: 0 for key in TAG_KEYS + SCALAR_KEYS}
for (metadata,) in rows:
for key in TAG_KEYS:
for key in TAG_KEYS + SCALAR_KEYS:
if metadata and metadata.get(key):
have[key] += 1
print(f"IGDB-matched roms: {total:,}")
for key in TAG_KEYS:
for key in TAG_KEYS + SCALAR_KEYS:
share = (have[key] / total * 100) if total else 0
print(f" with {key:<20} {have[key]:>7,} ({share:.1f}%)")
async def fetch_tags(igdb_ids: list[int]) -> dict[int, dict[str, list[str]]]:
async def fetch_tags(igdb_ids: list[int]) -> dict[int, dict[str, Any]]:
"""Ask IGDB for just the three tag fields, in batches of BATCH_SIZE."""
results: dict[int, dict[str, list[str]]] = {}
@@ -86,14 +95,16 @@ async def fetch_tags(igdb_ids: list[int]) -> dict[int, dict[str, list[str]]]:
game_id = game.get("id")
if game_id is None:
continue
results[game_id] = {
values: dict[str, Any] = {
key: [
entry.get("name", "")
for entry in (game.get(key) or [])
if entry.get("name")
if isinstance(entry, dict) and entry.get("name")
]
for key in TAG_KEYS
}
values.update({key: game.get(key, 0) for key in SCALAR_KEYS})
results[game_id] = values
done = min(start + BATCH_SIZE, len(igdb_ids))
print(f" fetched {done:,}/{len(igdb_ids):,}")
@@ -101,9 +112,7 @@ async def fetch_tags(igdb_ids: list[int]) -> dict[int, dict[str, list[str]]]:
return results
def merge_tags(
rom_by_igdb_id: dict[int, int], tags: dict[int, dict[str, list[str]]]
) -> int:
def merge_tags(rom_by_igdb_id: dict[int, int], tags: dict[int, dict[str, Any]]) -> int:
"""Merge the fetched tags into each ROM's existing igdb_metadata blob."""
written = 0