chore(seeder): use realistic metadata (#5641)

* chore(seeder): fill IGDB and ScreenScraper metadata to real-world size

Seeded provider JSON was about half the size of a real library's, so
gallery benchmarks understated decode and payload cost. IGDB now carries
keywords, platforms, realistic alternative names and always ten similar
games; ScreenScraper carries every media url and path key a match stores.
List lengths follow percentiles measured on a 9,172-game library.

New values draw from a per-game stream, so every other column, every
fill rate and the library shape match the previous seed exactly.

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

* fix(seeder): wipe snapshots before the saves and states they hold

--wipe failed on any database with save-channel snapshots, because
snapshots reference saves and states with ON DELETE RESTRICT.

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

* chore(seeder): tighten comments to what the code shows

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

* fix(seeder): draw distinct keywords and test the snapshot wipe order

A keyword list now samples without replacement from a pool larger than the
longest measured list (213), so long lists keep their distinct values.
A test pins that snapshots are wiped before the saves and states they hold.

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

* fix(seeder): apply code-review fixes to realistic metadata

Insert ROMs 100 rows per statement, seed the metadata stream from
provider and drawn facts so it follows --seed, fill search_titles and
min_age on Core-inserted rows, sample real distinct IGDB platforms, and
derive SS media kinds from SSMetadataMedia.

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

* refactor(seeder): simplify realistic metadata builders

Share the alias and similar-games builders between providers, pass rom
rows straight to compute_search_titles and compute_min_age, and name the
SS media kinds that carry a path. Output is unchanged for a given seed.

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

* docs(seeder): humanizer pass on extra_rng comment

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

* fix(seeder): fill every scan key, match similar-game slugs, pin the main stream

Seeded IGDB and ScreenScraper metadata now carry every required key of
IGDBMetadata and SSMetadata (publishers, developers, themes, player
perspectives, rating count, physical disc), so the facet columns that
read them are populated. Similar-game slugs follow their names without
shifting the main stream, and a test pins the main stream's position
after the builders so a draw moved onto it fails loudly.

compute_derived_columns in models/rom.py now derives search_titles and
min_age from a mapping, shared by the insert listener and the seeder.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
This commit is contained in:
Stu Anderson
2026-11-20 07:15:08 -06:00
committed by GitHub
parent 38d0a671df
commit eff94b8766
3 changed files with 261 additions and 27 deletions

View File

@@ -1502,9 +1502,26 @@ def rom_search_titles(rom: Rom) -> str:
return compute_search_titles(rom.name, alternative_name_metadata(rom))
DERIVED_SOURCE_COLUMNS = (*SEARCH_TITLE_COLUMNS, *MIN_AGE_SOURCE_COLUMNS)
def compute_derived_columns(values: Mapping[str, Any]) -> dict[str, Any]:
"""The columns a ROM insert derives from its own values.
Args:
values: Each `DERIVED_SOURCE_COLUMNS` column's value, by column name.
"""
return {
"search_titles": compute_search_titles(values.get("name"), values),
"min_age": compute_min_age(values),
}
@event.listens_for(Rom, "before_insert")
def _set_search_titles(_mapper: Any, _connection: Any, rom: Rom) -> None:
rom.search_titles = rom_search_titles(rom)
def _set_derived_columns(_mapper: Any, _connection: Any, rom: Rom) -> None:
values = {column: getattr(rom, column) for column in DERIVED_SOURCE_COLUMNS}
for column, value in compute_derived_columns(values).items():
setattr(rom, column, value)
@event.listens_for(Rom, "before_update")
@@ -1523,11 +1540,6 @@ def rom_min_age(rom: Rom) -> int | None:
)
@event.listens_for(Rom, "before_insert")
def _set_min_age(_mapper: Any, _connection: Any, rom: Rom) -> None:
rom.min_age = rom_min_age(rom)
@event.listens_for(Rom, "before_update")
def _refresh_min_age(_mapper: Any, _connection: Any, rom: Rom) -> None:
state = inspect(rom)

View File

@@ -1,3 +1,4 @@
import random
import sys
from collections.abc import Callable
from datetime import datetime, tzinfo
@@ -11,9 +12,13 @@ from tools import generate_test_data
from handler.database import db_rom_handler
from handler.database.base_handler import sync_engine
from models.rom import Rom
from handler.metadata.igdb_handler import IGDBMetadata
from handler.metadata.ss_handler import SSMetadata
from models.rom import SEARCH_TITLE_SEPARATOR, Rom, fold_search_title
IMAGE_FIELDS = {"path_cover_s", "path_cover_l", "path_screenshots"}
# Drawn from the per-game metadata stream, or derived from what it draws.
EXTRA_FIELDS = {"igdb_metadata", "ss_metadata", "search_titles"}
class _FrozenDatetime(datetime):
@@ -32,7 +37,9 @@ def _rom_rows(
"""Run the seeder, recording rom rows instead of inserting anything."""
rows: list[dict[str, Any]] = []
def record(conn: object, model: type, batch: list[dict[str, Any]]) -> None:
def record(
conn: object, model: type, batch: list[dict[str, Any]], chunk: int = 0
) -> None:
if model is Rom:
rows.extend(batch)
@@ -130,3 +137,106 @@ def test_a_cache_failure_still_reports_the_saved_seed(
assert "could not rotate the gallery cache" in captured.err
assert "Done in" in captured.out
assert len(rows) == 24
def _facts(seed: int) -> dict[str, Any]:
return generate_test_data.make_facts(random.Random(seed), {})
def _without_metadata_extras(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [{k: v for k, v in row.items() if k not in EXTRA_FIELDS} for row in rows]
def test_metadata_extras_never_shift_the_rows(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
seeded = _rom_rows(monkeypatch, tmp_path / "seeded")
monkeypatch.setattr(generate_test_data, "extra_rng", lambda *_: random.Random(0))
reseeded = _rom_rows(monkeypatch, tmp_path / "reseeded")
assert _without_metadata_extras(seeded) == _without_metadata_extras(reseeded)
def test_rom_rows_carry_their_aliases_and_min_age(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
rows = _rom_rows(monkeypatch, tmp_path)
aliased = next(r for r in rows if r["igdb_metadata"].get("alternative_names"))
search_titles = aliased["search_titles"].split(SEARCH_TITLE_SEPARATOR)
for alias in aliased["igdb_metadata"]["alternative_names"]:
assert fold_search_title(alias) in search_titles
assert any(row["min_age"] is not None for row in rows)
def test_ss_metadata_links_every_media_kind() -> None:
metadata = generate_test_data.build_ss_metadata(random.Random(1), _facts(1))
for kind in generate_test_data.SS_MEDIA_KINDS:
assert metadata[f"{kind}_url"].startswith("https://")
has_path = kind in generate_test_data.SS_PATH_KINDS
assert (f"{kind}_path" in metadata) == has_path
def test_list_lengths_follow_the_measured_shape() -> None:
rng = random.Random(7)
least, p50, _, _, top = generate_test_data.LIST_SHAPES["igdb.keywords"]
lengths = sorted(
generate_test_data.sample_length(rng, "igdb.keywords") for _ in range(4000)
)
assert least <= lengths[0] and lengths[-1] <= top
assert abs(lengths[len(lengths) // 2] - p50) <= 1
def test_the_longest_keyword_list_holds_distinct_keywords() -> None:
top = generate_test_data.LIST_SHAPES["igdb.keywords"][-1]
keywords = generate_test_data.KEYWORDS
assert len(set(keywords)) == len(keywords) >= top
def test_a_wipe_clears_snapshots_before_the_saves_and_states_they_hold() -> None:
class _Recorder:
def __init__(self) -> None:
self.deleted: list[str] = []
def execute(self, statement: Any) -> None:
self.deleted.append(str(statement).removeprefix("DELETE FROM "))
conn = _Recorder()
generate_test_data._wipe(conn) # type: ignore[arg-type]
assert conn.deleted.index("snapshots") < conn.deleted.index("states")
assert conn.deleted.index("snapshots") < conn.deleted.index("saves")
def test_igdb_metadata_always_has_ten_similar_games() -> None:
metadata = generate_test_data.build_igdb_metadata(random.Random(3), _facts(3))
assert len(metadata["similar_games"]) == 10
for game in metadata["similar_games"]:
assert game["slug"] == generate_test_data.slugify(game["name"])
def test_metadata_holds_every_key_a_scan_stores() -> None:
igdb = generate_test_data.build_igdb_metadata(random.Random(4), _facts(4))
ss = generate_test_data.build_ss_metadata(random.Random(4), _facts(4))
assert IGDBMetadata.__required_keys__ <= igdb.keys()
assert SSMetadata.__required_keys__ <= ss.keys()
def test_metadata_builders_draw_a_fixed_count_from_the_main_stream() -> None:
rng = random.Random(11)
for _ in range(20):
facts = generate_test_data.make_facts(rng, {})
generate_test_data.build_igdb_metadata(rng, facts)
generate_test_data.build_ss_metadata(rng, facts)
# A new draw on `rng` shifts every later row for a given --seed; draw from
# `extra_rng` instead, or update this value if the shift is intended.
assert rng.random() == 0.7712019761851616

View File

@@ -28,7 +28,7 @@ from collections.abc import Callable, Iterable, Iterator
from concurrent.futures import ProcessPoolExecutor
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Any
from typing import Any, get_type_hints
# Allow running as `python3 tools/generate_test_data.py` from backend/.
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -50,7 +50,10 @@ from config import RESOURCES_BASE_PATH # noqa: E402
from handler.database import db_rom_handler # noqa: E402
from handler.database.base_handler import sync_engine # noqa: E402
from handler.metadata.moby_handler import MOBYGAMES_PLATFORM_LIST # noqa: E402
from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST # noqa: E402
from handler.metadata.ss_handler import ( # noqa: E402
SCREENSAVER_PLATFORM_LIST,
SSMetadataMedia,
)
from handler.recommendation import invalidate_all_cached_feeds # noqa: E402
from models.assets import Save, Screenshot, State # noqa: E402
from models.base import BaseModel, compute_file_name_parts # noqa: E402
@@ -78,6 +81,7 @@ from models.rom import ( # noqa: E402
RomUser,
RomUserStatus,
TrackMeta,
compute_derived_columns,
compute_full_path_hash,
compute_name_sort_key,
)
@@ -379,12 +383,79 @@ EXTENSIONS_BY_SLUG: dict[str, list[str]] = {
DISC_HINTS = ("ps", "dc", "saturn", "cd", "ngc", "wii", "psp", "3do", "cdi")
_KEYWORD_TOPICS = [
"boss fight", "pixel art", "side-scrolling", "time limit", "power-ups",
"high score", "save point", "password system", "multiple endings",
"dungeon", "level selection", "unlockable content", "wall jump",
"difficulty level", "invincibility", "secret area", "sequel", "spin-off",
] # fmt: skip
_KEYWORD_QUALIFIERS = [
"hidden", "timed", "optional", "scripted", "branching", "random", "classic",
"late-game", "early-game", "co-op", "bonus", "final", "chained", "layered",
"silent", "rare",
] # fmt: skip
# Larger than the longest keyword list in `LIST_SHAPES`, so a draw without
# replacement can fill it with distinct values.
KEYWORDS = [
*_KEYWORD_TOPICS,
*(f"{q} {t}" for q in _KEYWORD_QUALIFIERS for t in _KEYWORD_TOPICS),
]
IGDB_THEMES = [
"Action", "Fantasy", "Science fiction", "Horror", "Thriller", "Survival",
"Historical", "Stealth", "Comedy", "Business", "Drama", "Non-fiction",
"Sandbox", "Educational", "Kids", "Open world", "Warfare", "Party", "4X",
"Mystery", "Romance",
] # fmt: skip
IGDB_PLAYER_PERSPECTIVES = [
"First person", "Third person", "Bird view / Isometric", "Side view",
"Text", "Auditory", "Virtual Reality",
] # fmt: skip
IGDB_PLATFORMS = [
{"igdb_id": p["id"], "name": p["name"]} for p in IGDB_PLATFORM_LIST.values()
]
# (least, p50, p90, p99, max) list lengths, measured 2026-11-17 on one
# 9,172-game library.
LIST_SHAPES: dict[str, tuple[int, int, int, int, int]] = {
"igdb.alternative_names": (0, 2, 6, 11, 16),
"igdb.keywords": (0, 5, 26, 80, 213),
"igdb.platforms": (0, 2, 5, 10, 17),
"ss.alternative_names": (0, 3, 4, 8, 12),
}
_SS_MEDIA_KEYS = get_type_hints(SSMetadataMedia)
SS_MEDIA_KINDS = tuple(
key.removesuffix("_url") for key in _SS_MEDIA_KEYS if key.endswith("_url")
)
SS_PATH_KINDS = tuple(
kind for kind in SS_MEDIA_KINDS if f"{kind}_path" in _SS_MEDIA_KEYS
)
# ---------------------------------------------------------------------------
# Small helpers.
# ---------------------------------------------------------------------------
def sample_length(rng: random.Random, key: str) -> int:
"""A list length whose percentiles match `LIST_SHAPES[key]`."""
least, p50, p90, p99, top = LIST_SHAPES[key]
u = rng.random()
if u < 0.5:
return rng.randint(least, p50)
if u < 0.9:
return rng.randint(p50, p90)
if u < 0.99:
return rng.randint(p90, p99)
return rng.randint(p99, top)
def extra_rng(f: dict[str, Any], provider: str) -> random.Random:
"""A per-game stream for one provider's metadata, so the main stream never shifts."""
# Keyed on facts the main stream drew, so it follows `--seed` and siblings
# (which copy those facts) get the same metadata.
key = f"{provider}:{f['slug']}:{f['release_ts']}:{f['rating']}"
return random.Random(key) # nosec B311
def rand_hex(rng: random.Random, nbytes: int) -> str:
return "%0*x" % (nbytes * 2, rng.getrandbits(nbytes * 8))
@@ -507,17 +578,51 @@ def _cover_url(rng: random.Random) -> str:
)
def _similar_game(rng: random.Random) -> dict[str, Any]:
game_id, name = rng.randint(1, 300000), make_title(rng)
make_title(rng) # Discarded, to keep the main stream aligned for a given --seed.
return {
"id": game_id,
"name": name,
"slug": slugify(name),
"type": "similar",
"cover_url": _cover_url(rng),
}
def _similar_games(rng: random.Random, more: random.Random) -> list[dict[str, Any]]:
games = [_similar_game(rng) for _ in range(rng.randint(0, 4))]
# Every measured IGDB match had ten.
return games + [_similar_game(more) for _ in range(10 - len(games))]
def _alternative_names(more: random.Random, f: dict[str, Any], shape: str) -> list[str]:
return [
f"{f['title']} ({more.choice(REGIONS)})"
for _ in range(sample_length(more, shape))
]
def build_igdb_metadata(rng: random.Random, f: dict[str, Any]) -> dict[str, Any]:
more = extra_rng(f, "igdb")
return {
"total_rating": str(f["rating"]),
"total_rating_count": more.randint(1, 1000),
"aggregated_rating": str(round(f["rating"] - rng.uniform(0, 8), 2)),
"first_release_date": f["release_ts"],
"youtube_video_id": rand_hex(rng, 6),
"genres": f["genres"],
"keywords": more.sample(KEYWORDS, sample_length(more, "igdb.keywords")),
"themes": more.sample(IGDB_THEMES, more.randint(0, 3)),
"player_perspectives": more.sample(
IGDB_PLAYER_PERSPECTIVES, more.randint(1, 2)
),
"franchises": f["franchises"],
"alternative_names": [f["title"].split(":")[0]],
"alternative_names": _alternative_names(more, f, "igdb.alternative_names"),
"collections": [f["franchises"][0]] if f["franchises"] else [],
"companies": f["companies"],
"publishers": f["companies"][-1:],
"developers": f["companies"][:1],
"game_modes": f["game_modes"],
"age_ratings": [
{
@@ -527,7 +632,7 @@ def build_igdb_metadata(rng: random.Random, f: dict[str, Any]) -> dict[str, Any]
}
for r in f["age_ratings"]
],
"platforms": [],
"platforms": more.sample(IGDB_PLATFORMS, sample_length(more, "igdb.platforms")),
"multiplayer_modes": [],
"player_count": f["player_count"],
"expansions": [],
@@ -536,16 +641,7 @@ def build_igdb_metadata(rng: random.Random, f: dict[str, Any]) -> dict[str, Any]
"remakes": [],
"expanded_games": [],
"ports": [],
"similar_games": [
{
"id": rng.randint(1, 300000),
"name": make_title(rng),
"slug": slugify(make_title(rng)),
"type": "similar",
"cover_url": _cover_url(rng),
}
for _ in range(rng.randint(0, 4))
],
"similar_games": _similar_games(rng, more),
}
@@ -565,21 +661,31 @@ def build_moby_metadata(
def build_ss_metadata(rng: random.Random, f: dict[str, Any]) -> dict[str, Any]:
more = extra_rng(f, "ss")
game_id, system_id = rng.randint(1, 999999), rng.randint(1, 999999)
media_url = (
"https://neoclone.screenscraper.fr/api2/mediaJeu.php?softname=romm"
f"&systemeid={system_id}&jeuid={game_id}&media="
)
return {
**{f"{kind}_url": f"{media_url}{kind}(wor)" for kind in SS_MEDIA_KINDS},
**dict.fromkeys(f"{kind}_path" for kind in SS_PATH_KINDS),
"physical_disc": 1,
"physical_extra_discs": [],
"ss_score": str(round(f["rating"] / 10, 1)),
"first_release_date": f["release_ts"],
"alternative_names": [f["title"].split(":")[0]],
"alternative_names": _alternative_names(more, f, "ss.alternative_names"),
"age_ratings": [
{"rating": r.split(":")[1], "category": r.split(":")[0]}
for r in f["age_ratings"]
],
"companies": f["companies"],
"publishers": f["companies"][-1:],
"developers": f["companies"][:1],
"franchises": f["franchises"],
"game_modes": f["game_modes"],
"genres": f["genres"],
"player_count": f["player_count"],
"box2d_url": f"https://www.screenscraper.fr/image.php?gameid={rng.randint(1, 999999)}",
"screenshot_url": f"https://www.screenscraper.fr/image.php?gameid={rng.randint(1, 999999)}",
}
@@ -1255,6 +1361,8 @@ def _seed(args: argparse.Namespace, image_pool: ProcessPoolExecutor | None) -> i
"updated_at": created,
}
)
# A Core insert skips the mapper events that fill these on the model.
rom_rows[-1].update(compute_derived_columns(rom_rows[-1]))
# Rom files: one per disc, plus the occasional manual.
n_files = rng.randint(2, 4) if multi_disc else 1
@@ -1521,7 +1629,9 @@ def _seed(args: argparse.Namespace, image_pool: ProcessPoolExecutor | None) -> i
if not args.dry_run:
with sync_engine.begin() as conn:
bulk_insert(conn, Rom, rom_rows)
# Each rom row carries several KB of metadata JSON, and a
# 1000-row statement can drop the connection.
bulk_insert(conn, Rom, rom_rows, chunk=100)
bulk_insert(conn, RomFile, file_rows)
bulk_insert(conn, TrackMeta, track_rows)
bulk_insert(conn, RomUser, ru_rows)
@@ -1741,6 +1851,8 @@ def _wipe(conn: Connection) -> None:
"rom_notes",
"rom_user",
"screenshots",
# Holds saves and states back with RESTRICT; its pins and states cascade.
"snapshots",
"states",
"saves",
"track_meta",