From d4f3d8be83a3512fca8a2b3f89a6760afefdb898 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Sep 2026 20:25:42 -0400 Subject: [PATCH 1/5] perf(metadata): stop storing the metadata dumps twice over in the cache The LaunchBox import wrote the whole game record into three hashes: once under its database id, and again under its title and folded title. The Switch TitleDB import wrote every entry twice, once per id it is looked up by. Both title indexes and the product id index now hold the id of the record they point at, and the reader follows it. Image lists also carried a `DatabaseID` repeating the field they are stored under, plus a `CRC32` no lookup reads. Measured on a full import of both dumps into the bundled valkey: 941MB -> 466MB of `used_memory`. An index written by an earlier import still holds whole records, so a lookup keeps answering off it until the next update rewrites the store. Fixes #4395 Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 22 +++++++- .../launchbox_handler/remote_source.py | 28 ++++++++-- .../scheduled/update_launchbox_metadata.py | 35 +++++++++---- .../tasks/scheduled/update_switch_titledb.py | 6 ++- .../handler/metadata/test_base_handler.py | 24 +++++++++ .../metadata/test_launchbox_handler.py | 52 +++++++++++++++++++ .../tasks/test_update_launchbox_metadata.py | 21 ++++++++ .../tests/tasks/test_update_switch_titledb.py | 38 +++++++------- 8 files changed, 189 insertions(+), 37 deletions(-) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index e56857a4b..d45e6bd7d 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -305,13 +305,31 @@ class MetadataHandler(abc.ABC): log.error("Could not find the Switch productID index file in cache") return search_term, None - index_entry = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + index_entry = await self._switch_product_id_entry(product_id) if index_entry: - index_entry = json.loads(index_entry) return index_entry["name"], index_entry return search_term, None + @staticmethod + async def _switch_product_id_entry(product_id: str) -> dict | None: + """Resolve a Switch product id to its titleID index entry. + + The product id index holds the title id of the entry. A store imported + before it was de-duplicated holds the entry itself, so it keeps + answering until the next update rewrites it. + """ + raw = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + if not raw: + return None + + value = json.loads(raw) + if isinstance(value, dict): + return value + + entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, value) + return json.loads(entry) if entry else None + async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 7ee9f58ae..d2586b1d6 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -25,6 +25,18 @@ class RemoteSource: return None return json.loads(entry) + async def _follow_title_index(self, entry: str) -> dict | None: + """Resolve a title index hit to the record it points at. + + A hit holds the database id of the record. A store imported before the + title indexes were de-duplicated holds the whole record instead, so it + keeps answering until the next import rewrites it. + """ + value = json.loads(entry) + if isinstance(value, dict): + return value + return await self.get_by_id(value) + async def get_rom( self, file_name: str, @@ -64,8 +76,12 @@ class RemoteSource: metadata_name_index_entry = await async_cache.hget( LAUNCHBOX_METADATA_NAME_KEY, f"{candidate}:{platform_name}" ) - if metadata_name_index_entry: - return json.loads(metadata_name_index_entry) + if not metadata_name_index_entry: + continue + + entry = await self._follow_title_index(metadata_name_index_entry) + if entry: + return entry for candidate in candidates: metadata_alternate_name_index_entry = await async_cache.hget( @@ -101,8 +117,12 @@ class RemoteSource: folded_index_entry = await async_cache.hget( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}" ) - if folded_index_entry: - return json.loads(folded_index_entry) + if not folded_index_entry: + continue + + entry = await self._follow_title_index(folded_index_entry) + if entry: + return entry return None diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index a1314a168..0ca128e9b 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -41,6 +41,10 @@ CACHE_WRITE_BATCH_SIZE: Final[int] = 2000 # Downloading ~100MB and parsing it takes far longer than an ordinary task. LAUNCHBOX_TASK_TIMEOUT: Final[int] = max(TASK_TIMEOUT, 30 * 60) +# `DatabaseID` repeats the field an image list is stored under and `CRC32` has +# no reader, and the dump holds 1.3M images, so dropping the pair saves ~100MB. +GAME_IMAGE_FIELDS: Final[frozenset[str]] = frozenset({"FileName", "Type", "Region"}) + class BatchedCacheWriter: """Queues cache writes on a pipeline, flushing every `batch_size` entries.""" @@ -62,8 +66,10 @@ class BatchedCacheWriter: self._queued = 0 -def _element_to_dict(elem: Any) -> dict[str, Any]: - return {child.tag: child.text for child in elem} +def _element_to_dict(elem: Any, fields: frozenset[str] | None = None) -> dict[str, Any]: + return { + child.tag: child.text for child in elem if fields is None or child.tag in fields + } def _iter_elements(source: Any) -> Iterator[Any]: @@ -177,30 +183,37 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): for elem in _iter_elements(f): if elem.tag == "Game": id_elem = elem.find("DatabaseID") - if id_elem is not None and id_elem.text: + database_id = ( + id_elem.text.strip() + if id_elem is not None and id_elem.text + else None + ) + if database_id: await writer.hset( LAUNCHBOX_METADATA_DATABASE_ID_KEY, - id_elem.text.strip(), + database_id, _element_to_dict(elem), ) name_elem = elem.find("Name") platform_elem = elem.find("Platform") if ( - name_elem is not None + database_id + and name_elem is not None and name_elem.text and platform_elem is not None and platform_elem.text ): platform_name = platform_elem.text.strip() - game = _element_to_dict(elem) - # Use a unique combination of name and platform as the key + # The title indexes hold the id of the + # record, not a second and third copy + # of it: each costs ~120MB of cache. await writer.hset( LAUNCHBOX_METADATA_NAME_KEY, f"{name_elem.text.strip().lower()}" f":{platform_name}", - game, + database_id, ) folded = fold_title(name_elem.text) @@ -208,7 +221,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): await writer.hset( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}", - game, + database_id, ) elif elem.tag == "GameAlternateName": @@ -242,7 +255,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): current_game_image_db_id = image_id current_game_images.append( - _element_to_dict(elem) + _element_to_dict( + elem, GAME_IMAGE_FIELDS + ) ) # Store the last game's images diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 48142f697..d290d2781 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -52,10 +52,12 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): processed_items += len(data_batch) update_stats.update(processed=processed_items) + # The product id index points at the titleID index entry rather than + # holding a second copy of it, which costs ~60MB of cache. for data_batch in batched(relevant_data.items(), 2000, strict=False): product_map = { - v["id"]: json.dumps(v) - for v in dict(data_batch).values() + v["id"]: json.dumps(title_id) + for title_id, v in data_batch if v.get("id") } if product_map: diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index e657e9f5a..421af5c77 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -337,6 +337,30 @@ class TestMetadataHandlerMethods: ) assert result[0] == "Product Game" + async def test_switch_productid_format_follows_title_id( + self, handler: MetadataHandler + ): + """The product id index holds the title id of its titleID index entry.""" + with patch.object( + async_cache, "exists", new_callable=AsyncMock + ) as mock_exists, patch.object( + async_cache, "hget", new_callable=AsyncMock + ) as mock_hget: + mock_exists.return_value = True + mock_hget.side_effect = [ + json.dumps("70010000000025"), + json.dumps({"name": "Product Game"}), + ] + + rom = Rom(fs_name="Game.nsp", title_id="0100ABCD12340000") + result = await handler._switch_productid_format(rom, "Game.nsp", "original") + + assert mock_hget.await_args_list[1].args == ( + "romm:switch_titledb", # SWITCH_TITLEDB_INDEX_KEY + "70010000000025", + ) + assert result[0] == "Product Game" + @pytest.mark.parametrize( ("title_id", "fs_name", "expected"), [ diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 750f510a9..6408f18f4 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -596,6 +596,58 @@ class TestRemoteSourceGetRom: assert result is not None assert result.get("DatabaseID", None) == "1234" + async def test_name_match_follows_database_id(self, source: RemoteSource): + """A title index hit holds the id of the record, not the record.""" + + async def side_effect(key, _field): + if key == LAUNCHBOX_METADATA_NAME_KEY: + return json.dumps("1234") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: + return json.dumps(REMOTE_ENTRY) + return None + + with patch.object( + async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect + ): + result = await source.get_rom( + "super mario bros.", "nes", assume_cache_present=True + ) + assert result is not None + assert result.get("Name", None) == "Super Mario Bros." + + async def test_folded_name_match_follows_database_id(self, source: RemoteSource): + async def side_effect(key, _field): + if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: + return json.dumps("1234") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: + return json.dumps(REMOTE_ENTRY) + return None + + with patch.object( + async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect + ): + result = await source.get_rom( + "super mario bros", "nes", assume_cache_present=True + ) + assert result is not None + assert result.get("Name", None) == "Super Mario Bros." + + async def test_title_index_pointing_at_missing_record(self, source: RemoteSource): + """A refresh that dropped the record leaves the index pointing nowhere.""" + + async def side_effect(key, _field): + if key == LAUNCHBOX_METADATA_NAME_KEY: + return json.dumps("1234") + return None + + with patch.object( + async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect + ): + result = await source.get_rom( + "super mario bros.", "nes", assume_cache_present=True + ) + assert result is None + async def test_alternate_name_match(self, source: RemoteSource): alt_entry = {"DatabaseID": "1234"} diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index 190aadcd6..b92f9dbd4 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -1,4 +1,6 @@ +import json import os +from typing import Any from unittest.mock import AsyncMock, patch import anyio @@ -210,6 +212,25 @@ class TestUpdateLaunchboxMetadataTask: assert fields(metadata_image_calls) == {"12345"} assert fields(mame_calls) == {"mario.zip", "pacman.zip"} + def values(calls) -> list[Any]: + return [ + json.loads(value) + for call in calls + for value in call[1]["mapping"].values() + ] + + # The title indexes point at the record, rather than repeating it. + assert sorted(values(metadata_name_calls)) == ["12345", "67890"] + assert sorted(values(metadata_folded_calls)) == ["12345", "67890"] + + # Images keep only the fields media selection reads. + assert values(metadata_image_calls) == [ + [ + {"FileName": "super_mario_64.jpg", "Type": "Cover"}, + {"FileName": "super_mario_64_screenshot.jpg", "Type": "Screenshot"}, + ] + ] + @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") async def test_empty_xml_elements_handling( diff --git a/backend/tests/tasks/test_update_switch_titledb.py b/backend/tests/tasks/test_update_switch_titledb.py index 8f5283f7b..987e1eab5 100644 --- a/backend/tests/tasks/test_update_switch_titledb.py +++ b/backend/tests/tasks/test_update_switch_titledb.py @@ -19,22 +19,24 @@ class TestUpdateSwitchTitleDBTask: @pytest.fixture def sample_titledb_data(self): + # The dump keys entries by title id and carries the application id as + # `id`, so the two indexes are keyed differently. return { - "0100000000010000": { + "70010000000025": { "id": "0100000000010000", "name": "Super Mario Odyssey", "publisher": "Nintendo", "region": "US", "version": "1.3.0", }, - "0100000000020000": { + "70010000000041": { "id": "0100000000020000", "name": "The Legend of Zelda: Breath of the Wild", "publisher": "Nintendo", "region": "US", "version": "1.6.0", }, - "0100000000030000": { + "70010000000046": { "id": "0100000000030000", "name": "Mario Kart 8 Deluxe", "publisher": "Nintendo", @@ -45,7 +47,7 @@ class TestUpdateSwitchTitleDBTask: "id": "should_be_filtered", "name": "Should not appear", }, - "0100000000040000": None, # None value to test filtering + "70010000000052": None, # None value to test filtering } @pytest.fixture @@ -218,9 +220,10 @@ class TestUpdateSwitchTitleDBTask: mock_async_cache_pipeline, mock_super_run, task, + sample_titledb_data, sample_json_content, ): - """Test that product ID mapping works correctly""" + """The product id index points at its titleID index entry.""" mock_super_run.return_value = sample_json_content mock_pipe = AsyncMock() @@ -230,22 +233,19 @@ class TestUpdateSwitchTitleDBTask: await task.run(force=True) - # Find product ID calls hset_calls = mock_pipe.hset.call_args_list - product_calls = [ - call for call in hset_calls if call[0][0] == SWITCH_PRODUCT_ID_KEY - ] + product_mapping = { + product_id: json.loads(raw) + for call in hset_calls + if call[0][0] == SWITCH_PRODUCT_ID_KEY + for product_id, raw in call[1]["mapping"].items() + } - assert len(product_calls) > 0 - - # Verify product mapping structure - for call in product_calls: - args, kwargs = call - if "mapping" in kwargs: - mapping = kwargs["mapping"] - for product_id, data_json in mapping.items(): - data = json.loads(data_json) - assert data.get("id") == product_id + assert product_mapping == { + entry["id"]: title_id + for title_id, entry in sample_titledb_data.items() + if title_id and entry + } @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") From ea44dfd9cfd40edcca2e29e419f7faa928ad7dab Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Sep 2026 13:17:44 -0400 Subject: [PATCH 2/5] refactor(metadata): fold the index follows into one lookup each The title index reader now takes the key and field it reads, so the two call sites lose their intermediate hit variable, and the alternate name path follows its id through `get_by_id` like the other two. The Switch titleID read is shared between the two lookups that do it. The LaunchBox import reads the `Game` fields with `findtext`, and the Switch import queues both indexes from one pass over the batches. The image projection moves next to the `LaunchboxImage` type it fills. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 20 ++++---- .../launchbox_handler/remote_source.py | 39 ++++++---------- .../metadata/launchbox_handler/types.py | 8 ++++ .../scheduled/update_launchbox_metadata.py | 46 +++++++------------ .../tasks/scheduled/update_switch_titledb.py | 16 ++++--- .../handler/metadata/test_base_handler.py | 3 +- .../metadata/test_launchbox_handler.py | 34 +++++--------- 7 files changed, 72 insertions(+), 94 deletions(-) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index d45e6bd7d..020c73589 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -277,9 +277,8 @@ class MetadataHandler(abc.ABC): log.error("Could not find the Switch titleID index file in cache") return search_term, None - index_entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) + index_entry = await self._switch_titledb_entry(title_id) if index_entry: - index_entry = json.loads(index_entry) return index_entry["name"], index_entry return search_term, None @@ -312,12 +311,16 @@ class MetadataHandler(abc.ABC): return search_term, None @staticmethod - async def _switch_product_id_entry(product_id: str) -> dict | None: - """Resolve a Switch product id to its titleID index entry. + async def _switch_titledb_entry(title_id: str) -> dict | None: + entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) + return json.loads(entry) if entry else None - The product id index holds the title id of the entry. A store imported - before it was de-duplicated holds the entry itself, so it keeps - answering until the next update rewrites it. + @classmethod + async def _switch_product_id_entry(cls, product_id: str) -> dict | None: + """Resolve a Switch product id to the title id its index entry holds. + + A store imported before the index was de-duplicated holds the titleID + entry itself, so it keeps answering until the next update. """ raw = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) if not raw: @@ -327,8 +330,7 @@ class MetadataHandler(abc.ABC): if isinstance(value, dict): return value - entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, value) - return json.loads(entry) if entry else None + return await cls._switch_titledb_entry(value) async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index d2586b1d6..9880270db 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -25,14 +25,17 @@ class RemoteSource: return None return json.loads(entry) - async def _follow_title_index(self, entry: str) -> dict | None: - """Resolve a title index hit to the record it points at. + async def _lookup_title_index(self, key: str, field: str) -> dict | None: + """Read a title index hit and resolve the database id it holds. - A hit holds the database id of the record. A store imported before the - title indexes were de-duplicated holds the whole record instead, so it - keeps answering until the next import rewrites it. + A store imported before the title indexes were de-duplicated holds the + whole record instead, so it keeps answering until the next import. """ - value = json.loads(entry) + raw = await async_cache.hget(key, field) + if not raw: + return None + + value = json.loads(raw) if isinstance(value, dict): return value return await self.get_by_id(value) @@ -73,13 +76,9 @@ class RemoteSource: candidates = list(dict.fromkeys(candidates)) for candidate in candidates: - metadata_name_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_NAME_KEY, f"{candidate}:{platform_name}" ) - if not metadata_name_index_entry: - continue - - entry = await self._follow_title_index(metadata_name_index_entry) if entry: return entry @@ -90,19 +89,13 @@ class RemoteSource: if not metadata_alternate_name_index_entry: continue - metadata_alternate_name_index_entry = json.loads( - metadata_alternate_name_index_entry - ) - database_id = metadata_alternate_name_index_entry["DatabaseID"] - metadata_database_index_entry = await async_cache.hget( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, database_id - ) - if not metadata_database_index_entry: + database_id = json.loads(metadata_alternate_name_index_entry)["DatabaseID"] + entry = await self.get_by_id(database_id) + if not entry: continue # The alternate name index is not keyed by platform, so a hit can # point at a same-titled game on a completely different system. - entry = json.loads(metadata_database_index_entry) if entry.get("Platform") == platform_name: return entry @@ -114,13 +107,9 @@ class RemoteSource: folded = fold_title(candidate) if not folded: continue - folded_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}" ) - if not folded_index_entry: - continue - - entry = await self._follow_title_index(folded_index_entry) if entry: return entry diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 75efa3713..aab000cf5 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -39,6 +39,14 @@ class LaunchboxImage(TypedDict): region: NotRequired[str] +# The fields an image list is imported with. `DatabaseID` repeats the field the +# list is stored under and `CRC32` has no reader, and the dump holds 1.3M +# images, so dropping the pair saves ~100MB of cache. +LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( + {"FileName", "Type", "Region"} +) + + class LaunchboxPlatform(TypedDict): slug: str launchbox_id: int | None diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 0ca128e9b..b6d83218b 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -16,6 +16,7 @@ from config import ( from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_FILES_KEY, + LAUNCHBOX_IMAGE_FIELDS, LAUNCHBOX_MAME_KEY, LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -41,10 +42,6 @@ CACHE_WRITE_BATCH_SIZE: Final[int] = 2000 # Downloading ~100MB and parsing it takes far longer than an ordinary task. LAUNCHBOX_TASK_TIMEOUT: Final[int] = max(TASK_TIMEOUT, 30 * 60) -# `DatabaseID` repeats the field an image list is stored under and `CRC32` has -# no reader, and the dump holds 1.3M images, so dropping the pair saves ~100MB. -GAME_IMAGE_FIELDS: Final[frozenset[str]] = frozenset({"FileName", "Type", "Region"}) - class BatchedCacheWriter: """Queues cache writes on a pipeline, flushing every `batch_size` entries.""" @@ -67,9 +64,9 @@ class BatchedCacheWriter: def _element_to_dict(elem: Any, fields: frozenset[str] | None = None) -> dict[str, Any]: - return { - child.tag: child.text for child in elem if fields is None or child.tag in fields - } + if fields is None: + return {child.tag: child.text for child in elem} + return {child.tag: child.text for child in elem if child.tag in fields} def _iter_elements(source: Any) -> Iterator[Any]: @@ -182,12 +179,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): for elem in _iter_elements(f): if elem.tag == "Game": - id_elem = elem.find("DatabaseID") database_id = ( - id_elem.text.strip() - if id_elem is not None and id_elem.text - else None - ) + elem.findtext("DatabaseID") or "" + ).strip() if database_id: await writer.hset( LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -195,28 +189,20 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): _element_to_dict(elem), ) - name_elem = elem.find("Name") - platform_elem = elem.find("Platform") - if ( - database_id - and name_elem is not None - and name_elem.text - and platform_elem is not None - and platform_elem.text - ): - platform_name = platform_elem.text.strip() - - # The title indexes hold the id of the - # record, not a second and third copy - # of it: each costs ~120MB of cache. + name = (elem.findtext("Name") or "").strip() + platform_name = ( + elem.findtext("Platform") or "" + ).strip() + if database_id and name and platform_name: + # Storing the id rather than the record: + # each copy costs ~120MB of cache. await writer.hset( LAUNCHBOX_METADATA_NAME_KEY, - f"{name_elem.text.strip().lower()}" - f":{platform_name}", + f"{name.lower()}:{platform_name}", database_id, ) - folded = fold_title(name_elem.text) + folded = fold_title(name) if folded: await writer.hset( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, @@ -256,7 +242,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): current_game_image_db_id = image_id current_game_images.append( _element_to_dict( - elem, GAME_IMAGE_FIELDS + elem, LAUNCHBOX_IMAGE_FIELDS ) ) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index d290d2781..419d11950 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -47,14 +47,13 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): async with async_cache.pipeline() as pipe: for data_batch in batched(relevant_data.items(), 2000, strict=False): - titledb_map = {k: json.dumps(v) for k, v in dict(data_batch).items()} - await pipe.hset(SWITCH_TITLEDB_INDEX_KEY, mapping=titledb_map) - processed_items += len(data_batch) - update_stats.update(processed=processed_items) + await pipe.hset( + SWITCH_TITLEDB_INDEX_KEY, + mapping={title_id: json.dumps(v) for title_id, v in data_batch}, + ) - # The product id index points at the titleID index entry rather than - # holding a second copy of it, which costs ~60MB of cache. - for data_batch in batched(relevant_data.items(), 2000, strict=False): + # The product id index points at the titleID index entry rather + # than holding a second copy of it, which costs ~60MB of cache. product_map = { v["id"]: json.dumps(title_id) for title_id, v in data_batch @@ -62,6 +61,9 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): } if product_map: await pipe.hset(SWITCH_PRODUCT_ID_KEY, mapping=product_map) + + processed_items += len(data_batch) + update_stats.update(processed=processed_items) await pipe.execute() # Final progress update diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index 421af5c77..8e3a63902 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -29,6 +29,7 @@ from handler.metadata.base_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_INDEX_KEY from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -356,7 +357,7 @@ class TestMetadataHandlerMethods: result = await handler._switch_productid_format(rom, "Game.nsp", "original") assert mock_hget.await_args_list[1].args == ( - "romm:switch_titledb", # SWITCH_TITLEDB_INDEX_KEY + SWITCH_TITLEDB_INDEX_KEY, "70010000000025", ) assert result[0] == "Product Game" diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 6408f18f4..757056fd8 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -596,11 +596,20 @@ class TestRemoteSourceGetRom: assert result is not None assert result.get("DatabaseID", None) == "1234" - async def test_name_match_follows_database_id(self, source: RemoteSource): + @pytest.mark.parametrize( + ("index_key", "file_name"), + [ + (LAUNCHBOX_METADATA_NAME_KEY, "super mario bros."), + (LAUNCHBOX_METADATA_FOLDED_NAME_KEY, "super mario bros"), + ], + ) + async def test_title_index_follows_database_id( + self, source: RemoteSource, index_key: str, file_name: str + ): """A title index hit holds the id of the record, not the record.""" async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_NAME_KEY: + if key == index_key: return json.dumps("1234") if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(REMOTE_ENTRY) @@ -609,26 +618,7 @@ class TestRemoteSourceGetRom: with patch.object( async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect ): - result = await source.get_rom( - "super mario bros.", "nes", assume_cache_present=True - ) - assert result is not None - assert result.get("Name", None) == "Super Mario Bros." - - async def test_folded_name_match_follows_database_id(self, source: RemoteSource): - async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: - return json.dumps("1234") - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(REMOTE_ENTRY) - return None - - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): - result = await source.get_rom( - "super mario bros", "nes", assume_cache_present=True - ) + result = await source.get_rom(file_name, "nes", assume_cache_present=True) assert result is not None assert result.get("Name", None) == "Super Mario Bros." From 13aaf54921ddf670358a99234d26a84730e61ed9 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Sep 2026 13:19:30 -0400 Subject: [PATCH 3/5] docs(metadata): trim the cache index comments to the fact each carries Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 5 ++--- backend/handler/metadata/launchbox_handler/remote_source.py | 3 +-- backend/handler/metadata/launchbox_handler/types.py | 5 ++--- backend/tasks/scheduled/update_launchbox_metadata.py | 4 ++-- backend/tasks/scheduled/update_switch_titledb.py | 3 +-- 5 files changed, 8 insertions(+), 12 deletions(-) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 020c73589..e6f459199 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -317,10 +317,9 @@ class MetadataHandler(abc.ABC): @classmethod async def _switch_product_id_entry(cls, product_id: str) -> dict | None: - """Resolve a Switch product id to the title id its index entry holds. + """Resolve a Switch product id to the titleID entry its index points at. - A store imported before the index was de-duplicated holds the titleID - entry itself, so it keeps answering until the next update. + An index written by an earlier import holds the entry itself. """ raw = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) if not raw: diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 9880270db..40f1c274b 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -28,8 +28,7 @@ class RemoteSource: async def _lookup_title_index(self, key: str, field: str) -> dict | None: """Read a title index hit and resolve the database id it holds. - A store imported before the title indexes were de-duplicated holds the - whole record instead, so it keeps answering until the next import. + An index written by an earlier import holds the whole record instead. """ raw = await async_cache.hget(key, field) if not raw: diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index aab000cf5..a7f39dd84 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -39,9 +39,8 @@ class LaunchboxImage(TypedDict): region: NotRequired[str] -# The fields an image list is imported with. `DatabaseID` repeats the field the -# list is stored under and `CRC32` has no reader, and the dump holds 1.3M -# images, so dropping the pair saves ~100MB of cache. +# `DatabaseID` repeats the field the list is stored under and `CRC32` has no +# reader; across the dump's 1.3M images the pair costs ~100MB of cache. LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( {"FileName", "Type", "Region"} ) diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index b6d83218b..76bdddaa5 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -194,8 +194,8 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): elem.findtext("Platform") or "" ).strip() if database_id and name and platform_name: - # Storing the id rather than the record: - # each copy costs ~120MB of cache. + # A full copy of the record here + # costs ~120MB of cache. await writer.hset( LAUNCHBOX_METADATA_NAME_KEY, f"{name.lower()}:{platform_name}", diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 419d11950..3170272f3 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -52,8 +52,7 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): mapping={title_id: json.dumps(v) for title_id, v in data_batch}, ) - # The product id index points at the titleID index entry rather - # than holding a second copy of it, which costs ~60MB of cache. + # A second copy of each entry here costs ~60MB of cache. product_map = { v["id"]: json.dumps(title_id) for title_id, v in data_batch From 721197476aa53de46d3cfef7c2d1f63bbcd64249 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Sep 2026 15:45:32 -0400 Subject: [PATCH 4/5] perf(metadata): rebuild a metadata store an older release wrote The readers tolerated both the old and the new shape of every index this branch changed, which left two shapes supported forever and, on an install whose scheduled update is off, meant the old store answered every lookup and the saving never landed at all. Each store now carries a schema stamp. A store whose stamp is missing or stale reads as unpopulated, is dropped at startup, and has its import queued the way the WebP backfill is, so the shape change causes the rebuild instead of being worked around. The readers know one shape again. The projection each store is written with moves next to its key, and the three stores that had none get one: Mame.xml kept 24 fields per record to serve `Name`, Files.xml kept the platform and filename its cache key already carries, and an alternate name entry kept the name it is stored under. Together with the image list that is ~135MB. Measured against the real dump: the eight LaunchBox hashes hold 385MB, and a store stamped by an earlier release is dropped at startup for 386MB of `used_memory` reclaimed. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 36 ++++---- .../metadata/launchbox_handler/handler.py | 10 +++ .../launchbox_handler/remote_source.py | 14 +-- .../metadata/launchbox_handler/types.py | 24 ++++- backend/startup.py | 53 ++++++++++- .../scheduled/update_launchbox_metadata.py | 25 +++++- .../tasks/scheduled/update_switch_titledb.py | 15 ++++ .../handler/metadata/test_base_handler.py | 61 +++++++------ .../metadata/test_launchbox_handler.py | 42 ++++++--- .../tests/handler/metadata/test_ss_handler.py | 7 ++ .../tests/tasks/fixtures/sample_metadata.zip | Bin 2480 -> 2508 bytes .../tasks/test_update_launchbox_metadata.py | 30 ++++++- backend/tests/test_startup.py | 63 +++++++++++++ backend/tests/utils/test_cache.py | 85 +++++++++++++++++- backend/utils/cache.py | 32 +++++++ 15 files changed, 421 insertions(+), 76 deletions(-) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index e6f459199..677eb5d2d 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -15,7 +15,10 @@ from logger.logger import log from tasks.scheduled.update_switch_titledb import ( SWITCH_PRODUCT_ID_KEY, SWITCH_TITLEDB_INDEX_KEY, + SWITCH_TITLEDB_SCHEMA_KEY, + SWITCH_TITLEDB_SCHEMA_VERSION, ) +from utils.cache import is_cache_schema_current from utils.context import ctx_httpx_client from utils.switch import derive_base_title_id @@ -273,8 +276,8 @@ class MetadataHandler(abc.ABC): ) -> tuple[str, dict | None]: title_id = match.group(1) - if not (await async_cache.exists(SWITCH_TITLEDB_INDEX_KEY)): - log.error("Could not find the Switch titleID index file in cache") + if not await self._is_switch_titledb_current(): + log.error("Could not find a current Switch titleID index in cache") return search_term, None index_entry = await self._switch_titledb_entry(title_id) @@ -300,8 +303,8 @@ class MetadataHandler(abc.ABC): # low 12 bits, and only the base has a titledb entry. product_id = derive_base_title_id(product_id) or product_id - if not (await async_cache.exists(SWITCH_PRODUCT_ID_KEY)): - log.error("Could not find the Switch productID index file in cache") + if not await self._is_switch_titledb_current(): + log.error("Could not find a current Switch productID index in cache") return search_term, None index_entry = await self._switch_product_id_entry(product_id) @@ -310,6 +313,16 @@ class MetadataHandler(abc.ABC): return search_term, None + @staticmethod + async def _is_switch_titledb_current() -> bool: + """Whether both Switch indexes were written by the current import.""" + if not await is_cache_schema_current( + async_cache, SWITCH_TITLEDB_SCHEMA_KEY, SWITCH_TITLEDB_SCHEMA_VERSION + ): + return False + + return bool(await async_cache.exists(SWITCH_TITLEDB_INDEX_KEY)) + @staticmethod async def _switch_titledb_entry(title_id: str) -> dict | None: entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) @@ -317,19 +330,12 @@ class MetadataHandler(abc.ABC): @classmethod async def _switch_product_id_entry(cls, product_id: str) -> dict | None: - """Resolve a Switch product id to the titleID entry its index points at. - - An index written by an earlier import holds the entry itself. - """ - raw = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) - if not raw: + """Resolve a Switch product id to the titleID entry its index points at.""" + title_id = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + if not title_id: return None - value = json.loads(raw) - if isinstance(value, dict): - return value - - return await cls._switch_titledb_entry(value) + return await cls._switch_titledb_entry(json.loads(title_id)) async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 5625b6e7b..00ad5b870 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -4,6 +4,7 @@ from config import LAUNCHBOX_API_ENABLED from handler.filesystem import fs_rom_handler from handler.redis_handler import async_cache from logger.logger import log +from utils.cache import is_cache_schema_current from utils.database import safe_int from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -16,6 +17,8 @@ from .types import ( DASH_COLON_REGEX, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, LAUNCHBOX_PLATFORMS_DIR, LAUNCHBOX_TAG_REGEX, LaunchboxPlatform, @@ -42,6 +45,13 @@ class LaunchboxHandler(MetadataHandler): @staticmethod async def is_remote_store_populated() -> bool: + if not await is_cache_schema_current( + async_cache, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, + ): + return False + return bool(await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY)) @staticmethod diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 40f1c274b..20865b561 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -26,18 +26,12 @@ class RemoteSource: return json.loads(entry) async def _lookup_title_index(self, key: str, field: str) -> dict | None: - """Read a title index hit and resolve the database id it holds. - - An index written by an earlier import holds the whole record instead. - """ - raw = await async_cache.hget(key, field) - if not raw: + """Read a title index hit and resolve the database id it holds.""" + database_id = await async_cache.hget(key, field) + if not database_id: return None - value = json.loads(raw) - if isinstance(value, dict): - return value - return await self.get_by_id(value) + return await self.get_by_id(json.loads(database_id)) async def get_rom( self, diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index a7f39dd84..80a305246 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -21,6 +21,23 @@ LAUNCHBOX_FILES_KEY: Final[str] = "romm:launchbox_files" LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY: Final[str] = ( "romm:launchbox_metadata_initial_import" ) +LAUNCHBOX_METADATA_SCHEMA_KEY: Final[str] = "romm:launchbox_metadata_schema" + +# Bumped whenever an import changes what a store holds, so a store an older +# release wrote is dropped and rebuilt rather than read as the current shape. +LAUNCHBOX_METADATA_SCHEMA_VERSION: Final[int] = 1 + +# Every hash the import fills, dropped together when the schema moves on. +LAUNCHBOX_STORE_KEYS: Final[tuple[str, ...]] = ( + LAUNCHBOX_PLATFORMS_KEY, + LAUNCHBOX_METADATA_DATABASE_ID_KEY, + LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, + LAUNCHBOX_METADATA_FOLDED_NAME_KEY, + LAUNCHBOX_METADATA_IMAGE_KEY, + LAUNCHBOX_MAME_KEY, + LAUNCHBOX_FILES_KEY, +) LAUNCHBOX_LOCAL_DIR: Final[Path] = Path(ROMM_BASE_PATH) / "launchbox" LAUNCHBOX_PLATFORMS_DIR: Final[Path] = LAUNCHBOX_LOCAL_DIR / "Data" / "Platforms" @@ -39,11 +56,14 @@ class LaunchboxImage(TypedDict): region: NotRequired[str] -# `DatabaseID` repeats the field the list is stored under and `CRC32` has no -# reader; across the dump's 1.3M images the pair costs ~100MB of cache. +# What each store keeps of its dump element: the fields its reader reads, and +# never one the cache key already carries. Together these drop ~135MB. LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( {"FileName", "Type", "Region"} ) +LAUNCHBOX_FILE_FIELDS: Final[frozenset[str]] = frozenset({"GameName"}) +LAUNCHBOX_MAME_FIELDS: Final[frozenset[str]] = frozenset({"Name"}) +LAUNCHBOX_ALTERNATE_NAME_FIELDS: Final[frozenset[str]] = frozenset({"DatabaseID"}) class LaunchboxPlatform(TypedDict): diff --git a/backend/startup.py b/backend/startup.py index c496bd7dd..1ce50b04f 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -8,7 +8,11 @@ from rq.exceptions import DuplicateJobError from rq.job import Job from rq.utils import as_text -from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN +from config import ( + ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, + LAUNCHBOX_API_ENABLED, + SENTRY_DSN, +) from config.config_manager import config_manager as cm from handler.database import db_save_handler from handler.metadata.base_handler import ( @@ -20,6 +24,11 @@ from handler.metadata.base_handler import ( PSP_SERIAL_INDEX_KEY, SCUMMVM_INDEX_KEY, ) +from handler.metadata.launchbox_handler.types import ( + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_STORE_KEYS, +) from handler.redis_handler import ( async_cache, default_queue, @@ -31,14 +40,21 @@ from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY from tasks.registry import enqueue_task +from tasks.scheduled.update_switch_titledb import ( + SWITCH_TITLEDB_SCHEMA_KEY, + SWITCH_TITLEDB_SCHEMA_VERSION, + SWITCH_TITLEDB_STORE_KEYS, +) from utils import get_version -from utils.cache import conditionally_set_cache +from utils.cache import conditionally_set_cache, drop_stale_cache_store from utils.context import initialize_context tracer = trace.get_tracer(__name__) RECOMPUTE_SAVE_HASHES_JOB_ID = "recompute_save_content_hashes_bootstrap" CONVERT_IMAGES_TO_WEBP_JOB_ID = "convert_images_to_webp_bootstrap" +UPDATE_LAUNCHBOX_METADATA_JOB_ID = "update_launchbox_metadata_bootstrap" +UPDATE_SWITCH_TITLEDB_JOB_ID = "update_switch_titledb_bootstrap" def _enqueue_backfill(task_name: str, job_id: str) -> None: @@ -87,6 +103,34 @@ def _enqueue_convert_images_to_webp() -> None: _enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID) +async def _rebuild_outdated_metadata_stores() -> None: + """Drop the metadata stores an older release wrote and queue their rebuild. + + Lookups read the current shape only, so an old store answers nothing while + still holding several hundred MB of cache. + """ + if await drop_stale_cache_store( + async_cache, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_STORE_KEYS, + ): + log.info("Dropped a LaunchBox metadata store left by an older release") + if LAUNCHBOX_API_ENABLED: + _enqueue_backfill( + "update_launchbox_metadata", UPDATE_LAUNCHBOX_METADATA_JOB_ID + ) + + if await drop_stale_cache_store( + async_cache, + SWITCH_TITLEDB_SCHEMA_KEY, + SWITCH_TITLEDB_SCHEMA_VERSION, + SWITCH_TITLEDB_STORE_KEYS, + ): + log.info("Dropped a Switch TitleDB store left by an older release") + _enqueue_backfill("update_switch_titledb", UPDATE_SWITCH_TITLEDB_JOB_ID) + + # Keys the rq-scheduler process left behind, now owned by the cron config. LEGACY_SCHEDULED_JOBS_KEY = "rq:scheduler:scheduled_jobs" LEGACY_SCHEDULER_KEYS = ( @@ -148,6 +192,11 @@ async def main() -> None: _enqueue_recompute_save_hashes_if_needed() + try: + await _rebuild_outdated_metadata_stores() + except Exception: + log.exception("Failed to check the metadata stores for an older shape") + log.info("Initializing cache with fixtures data") await conditionally_set_cache( async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json" diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 76bdddaa5..14a87c7bc 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -15,8 +15,11 @@ from config import ( ) from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( + LAUNCHBOX_ALTERNATE_NAME_FIELDS, + LAUNCHBOX_FILE_FIELDS, LAUNCHBOX_FILES_KEY, LAUNCHBOX_IMAGE_FIELDS, + LAUNCHBOX_MAME_FIELDS, LAUNCHBOX_MAME_KEY, LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -24,12 +27,15 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, LAUNCHBOX_PLATFORMS_KEY, ) from handler.metadata.launchbox_handler.utils import fold_title from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType +from utils.cache import stamp_cache_schema from utils.context import initialize_context from . import UpdateStats @@ -219,7 +225,10 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): await writer.hset( LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, alternate_name_elem.text.strip().lower(), - _element_to_dict(elem), + _element_to_dict( + elem, + LAUNCHBOX_ALTERNATE_NAME_FIELDS, + ), ) elif elem.tag == "GameImage": @@ -272,7 +281,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): await writer.hset( LAUNCHBOX_MAME_KEY, filename_elem.text.strip(), - _element_to_dict(elem), + _element_to_dict( + elem, LAUNCHBOX_MAME_FIELDS + ), ) await writer.flush() @@ -300,7 +311,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): LAUNCHBOX_FILES_KEY, f"{filename_elem.text.strip().lower()}" f":{platform_elem.text.strip()}", - _element_to_dict(elem), + _element_to_dict( + elem, LAUNCHBOX_FILE_FIELDS + ), ) await writer.flush() @@ -311,6 +324,12 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): log.error("Bad zip file in launchbox metadata update") return update_stats.to_dict() + await stamp_cache_schema( + async_cache, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, + ) + # Also clears a flag left behind by an earlier run that died partway. await async_cache.delete(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 3170272f3..ce0ef9b1b 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -9,12 +9,23 @@ from config import ( from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType +from utils.cache import stamp_cache_schema from utils.context import initialize_context from . import UpdateStats SWITCH_TITLEDB_INDEX_KEY: Final = "romm:switch_titledb" SWITCH_PRODUCT_ID_KEY: Final = "romm:switch_product_id" +SWITCH_TITLEDB_SCHEMA_KEY: Final = "romm:switch_titledb_schema" + +# Bumped whenever an import changes what the indexes hold, so a store an older +# release wrote is dropped and rebuilt rather than read as the current shape. +SWITCH_TITLEDB_SCHEMA_VERSION: Final[int] = 1 + +SWITCH_TITLEDB_STORE_KEYS: Final[tuple[str, ...]] = ( + SWITCH_TITLEDB_INDEX_KEY, + SWITCH_PRODUCT_ID_KEY, +) class UpdateSwitchTitleDBTask(RemoteFilePullTask): @@ -65,6 +76,10 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): update_stats.update(processed=processed_items) await pipe.execute() + await stamp_cache_schema( + async_cache, SWITCH_TITLEDB_SCHEMA_KEY, SWITCH_TITLEDB_SCHEMA_VERSION + ) + # Final progress update update_stats.update(processed=processed_items) log.info("Scheduled switch titledb update completed!") diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index 8e3a63902..094c6ab3a 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -29,7 +29,12 @@ from handler.metadata.base_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom -from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_INDEX_KEY +from tasks.scheduled.update_switch_titledb import ( + SWITCH_PRODUCT_ID_KEY, + SWITCH_TITLEDB_INDEX_KEY, + SWITCH_TITLEDB_SCHEMA_KEY, + SWITCH_TITLEDB_SCHEMA_VERSION, +) from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -113,6 +118,17 @@ class TestNormalizeSearchTerm: assert cache_info2.hits == cache_info1.hits + 1 +def current_schema_get() -> AsyncMock: + """Answer the schema stamp read with the version the readers expect.""" + + async def get(key: str) -> str | None: + if key == SWITCH_TITLEDB_SCHEMA_KEY: + return str(SWITCH_TITLEDB_SCHEMA_VERSION) + return None + + return AsyncMock(side_effect=get) + + class TestMetadataHandlerMethods: """Test MetadataHandler instance methods.""" @@ -269,6 +285,8 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( + async_cache, "get", current_schema_get() + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True @@ -324,27 +342,8 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( - async_cache, "hget", new_callable=AsyncMock - ) as mock_hget: - mock_exists.return_value = True - mock_hget.return_value = json.dumps({"name": "Product Game"}) - - rom = Rom(fs_name="Game.nsp", title_id=product_id) - result = await handler._switch_productid_format(rom, "Game.nsp", "original") - - mock_hget.assert_called_once_with( - "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY - "0100ABCD12340000", - ) - assert result[0] == "Product Game" - - async def test_switch_productid_format_follows_title_id( - self, handler: MetadataHandler - ): - """The product id index holds the title id of its titleID index entry.""" - with patch.object( - async_cache, "exists", new_callable=AsyncMock - ) as mock_exists, patch.object( + async_cache, "get", current_schema_get() + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True @@ -353,13 +352,14 @@ class TestMetadataHandlerMethods: json.dumps({"name": "Product Game"}), ] - rom = Rom(fs_name="Game.nsp", title_id="0100ABCD12340000") + rom = Rom(fs_name="Game.nsp", title_id=product_id) result = await handler._switch_productid_format(rom, "Game.nsp", "original") - assert mock_hget.await_args_list[1].args == ( - SWITCH_TITLEDB_INDEX_KEY, - "70010000000025", - ) + # The product id index holds the title id of its titleID entry. + assert [call.args for call in mock_hget.await_args_list] == [ + (SWITCH_PRODUCT_ID_KEY, "0100ABCD12340000"), + (SWITCH_TITLEDB_INDEX_KEY, "70010000000025"), + ] assert result[0] == "Product Game" @pytest.mark.parametrize( @@ -389,6 +389,8 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( + async_cache, "get", current_schema_get() + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True @@ -399,10 +401,7 @@ class TestMetadataHandlerMethods: if expected is None: mock_hget.assert_not_called() else: - mock_hget.assert_called_once_with( - "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY - expected, - ) + mock_hget.assert_called_once_with(SWITCH_PRODUCT_ID_KEY, expected) @pytest.mark.asyncio async def test_mame_format_found(self, handler: MetadataHandler): diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 757056fd8..0fa8f2f4a 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -40,6 +40,8 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, LaunchboxImage, LaunchboxMetadata, MediaRequest, @@ -99,6 +101,18 @@ SAMPLE_N64_XML = """\ """ + +def current_schema_get() -> AsyncMock: + """Answer the schema stamp read with the version the readers expect.""" + + async def get(key: str) -> str | None: + if key == LAUNCHBOX_METADATA_SCHEMA_KEY: + return str(LAUNCHBOX_METADATA_SCHEMA_VERSION) + return None + + return AsyncMock(side_effect=get) + + REMOTE_ENTRY = { "DatabaseID": "1234", "Name": "Super Mario Bros.", @@ -694,6 +708,8 @@ class TestRemoteSourceGetRom: key == LAUNCHBOX_METADATA_NAME_KEY and field == "the legend of zelda: ocarina of time:Nintendo 64" ): + return json.dumps("161") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(entry) return None @@ -733,6 +749,8 @@ class TestRemoteSourceGetRom: async def side_effect(key, field): if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY and field == folded_field: + return json.dumps("77") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(entry) return None @@ -776,11 +794,13 @@ class TestRemoteSourceGetRom: exact = {"DatabaseID": "1", "Name": "Burnout Revenge"} folded = {"DatabaseID": "2", "Name": "Burnout: Revenge"} - async def side_effect(key, _field): + async def side_effect(key, field): if key == LAUNCHBOX_METADATA_NAME_KEY: - return json.dumps(exact) + return json.dumps("1") if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: - return json.dumps(folded) + return json.dumps("2") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: + return json.dumps(exact if field == "1" else folded) return None with patch.object( @@ -815,20 +835,17 @@ class TestRemoteSourceGetRomByFileName: return RemoteSource() async def test_file_name_resolves_to_title(self, source: RemoteSource): - file_entry = { - "Platform": "Commodore Amiga", - "FileName": "1943_v1.3", - "GameName": "1943: The Battle of Midway", - } game_entry = {"DatabaseID": "999", "Name": "1943: The Battle of Midway"} async def side_effect(key, field): if key == LAUNCHBOX_FILES_KEY and field == "1943_v1.3:Commodore Amiga": - return json.dumps(file_entry) + return json.dumps({"GameName": "1943: The Battle of Midway"}) if ( key == LAUNCHBOX_METADATA_NAME_KEY and field == "1943: The Battle of Midway:Commodore Amiga" ): + return json.dumps("999") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(game_entry) return None @@ -1342,6 +1359,7 @@ class TestRemoteMatchLocalImages: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr(async_cache, "get", current_schema_get()) with patch( "handler.metadata.launchbox_handler.handler.fs_rom_handler" @@ -1473,6 +1491,7 @@ class TestLaunchboxHandlerHeartbeat: patch.object( async_cache, "exists", self._cache_exists(LAUNCHBOX_METADATA_NAME_KEY) ), + patch.object(async_cache, "get", current_schema_get()), ): assert await handler.heartbeat() is True @@ -1528,6 +1547,7 @@ class TestLaunchboxHandlerGetRom: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr(async_cache, "get", current_schema_get()) return h async def test_disabled_returns_fallback( @@ -1694,7 +1714,8 @@ class TestLaunchboxHandlerGetRom: LAUNCHBOX_METADATA_NAME_KEY, "the legend of zelda: a link to the past" ":Super Nintendo Entertainment System", - ): json.dumps(entry) + ): json.dumps("5678"), + (LAUNCHBOX_METADATA_DATABASE_ID_KEY, "5678"): json.dumps(entry), } async def hget(key, field): @@ -1878,6 +1899,7 @@ class TestLaunchboxHandlerSearch: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr(async_cache, "get", current_schema_get()) return h async def test_get_matched_roms_by_name_disabled_returns_empty( diff --git a/backend/tests/handler/metadata/test_ss_handler.py b/backend/tests/handler/metadata/test_ss_handler.py index 83fce45d3..91128e8ab 100644 --- a/backend/tests/handler/metadata/test_ss_handler.py +++ b/backend/tests/handler/metadata/test_ss_handler.py @@ -39,6 +39,7 @@ from handler.metadata.ss_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_SCHEMA_VERSION def _make_config( @@ -1909,6 +1910,12 @@ class TestSonySerialFilenames: return_value=True, ), patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists, + patch.object( + async_cache, + "get", + new_callable=AsyncMock, + return_value=str(SWITCH_TITLEDB_SCHEMA_VERSION), + ), patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, patch.object( SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None diff --git a/backend/tests/tasks/fixtures/sample_metadata.zip b/backend/tests/tasks/fixtures/sample_metadata.zip index 1930545e306bedcf2571509529144bd5106ea598..89879a3c0078c92eb7ae3487f4eadf36fdcd76ef 100644 GIT binary patch delta 278 zcmV+x0qOp*6U-B^!T|{uJ=@K|0001@lgj}of0dBS3W7ishW9?j;9e(bV{n?lg{u_7 zTC_ZkLk>7IGHOUqpO-*`3OcL*w)i-3=v77T!ZyqCx(DXK z5j)Mx$n=9wP>EPpf;nV37-c#{vn52KmBxR_damhv50lKhT3C{dOA=Yr_&`^ayv4R_ zLDed25&JW7hTKa~ z|Idkv|A5?lgruu?KLN9r0u2QT7Cqa|zyJUMqLZu#Ujed{33c@fHh4((iC3_p)9Bx}EQWqnF z`T!vY4KzQbR*Fw=(ty^XW;!S58$K@9qwe4-eXp!3$+}n(kVe?6GPjak&TYOSb(P_s z4@TS@JBG}-maXb!l|gtI;~{*d3ZS`Hwsf_>hqyPW_ zSd+*HUjvo`0F%!GER+2Q43lCA9sxCzfe29nyOYxhTmfE_FbPrvMg{IMJ+00665Yv2F? diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index b92f9dbd4..80fb227ad 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -17,6 +17,8 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_SCHEMA_KEY, + LAUNCHBOX_METADATA_SCHEMA_VERSION, LAUNCHBOX_PLATFORMS_KEY, ) from handler.redis_handler import async_cache @@ -231,6 +233,18 @@ class TestUpdateLaunchboxMetadataTask: ] ] + # Every other store keeps its reader's field, and never one the key + # already carries: the fixture's Platform, FileType and Size all go. + assert values(metadata_alt_calls) == [{"DatabaseID": "12345"}] + assert values(files_calls) == [ + {"GameName": "Super Mario 64"}, + {"GameName": "Crash Bandicoot"}, + ] + assert values(mame_calls) == [ + {"Name": "Super Mario Bros."}, + {"Name": "Pac-Man"}, + ] + @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") async def test_empty_xml_elements_handling( @@ -455,12 +469,16 @@ class TestInitialImportFlag: with ( patch.object(async_cache, "exists", AsyncMock(return_value=0)), + patch.object(async_cache, "get", AsyncMock(return_value=None)), patch.object(async_cache, "set", AsyncMock()) as mock_set, patch.object(async_cache, "delete", AsyncMock()) as mock_delete, ): await task.run(force=True) - mock_set.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1") + assert [call.args for call in mock_set.await_args_list] == [ + (LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1"), + (LAUNCHBOX_METADATA_SCHEMA_KEY, str(LAUNCHBOX_METADATA_SCHEMA_VERSION)), + ] mock_delete.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) @patch.object(RemoteFilePullTask, "run") @@ -475,12 +493,20 @@ class TestInitialImportFlag: with ( patch.object(async_cache, "exists", AsyncMock(return_value=1)), + patch.object( + async_cache, + "get", + AsyncMock(return_value=str(LAUNCHBOX_METADATA_SCHEMA_VERSION)), + ), patch.object(async_cache, "set", AsyncMock()) as mock_set, patch.object(async_cache, "delete", AsyncMock()), ): await task.run(force=True) - mock_set.assert_not_awaited() + # Only the schema stamp, never the initial-import flag. + mock_set.assert_awaited_once_with( + LAUNCHBOX_METADATA_SCHEMA_KEY, str(LAUNCHBOX_METADATA_SCHEMA_VERSION) + ) @patch.object(RemoteFilePullTask, "run") async def test_flag_survives_a_failed_run( diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index 6d049207a..14dd50f73 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -1,5 +1,7 @@ """Tests for startup-time auto-enqueue of the recompute task.""" +from unittest.mock import AsyncMock + import pytest import startup from rq.exceptions import DuplicateJobError @@ -128,3 +130,64 @@ class TestDropLegacySchedulerState: redis.zrange.side_effect = RuntimeError("redis gone") startup._drop_legacy_scheduler_state() + + +class TestRebuildOutdatedMetadataStores: + """A store an older release wrote is dropped, and its rebuild queued.""" + + async def test_stale_launchbox_store_is_dropped_and_rebuilt( + self, mocker, enqueue_task + ): + mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", True) + drop = mocker.patch.object( + startup, "drop_stale_cache_store", new_callable=AsyncMock + ) + drop.side_effect = [True, False] + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_called_once_with( + "update_launchbox_metadata", + job_id=startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, + unique=True, + ) + + async def test_launchbox_rebuild_waits_on_the_provider_being_enabled( + self, mocker, enqueue_task + ): + """Dropping reclaims the memory; refilling it would serve nobody.""" + mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", False) + drop = mocker.patch.object( + startup, "drop_stale_cache_store", new_callable=AsyncMock + ) + drop.side_effect = [True, False] + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_not_called() + + async def test_stale_switch_store_is_dropped_and_rebuilt( + self, mocker, enqueue_task + ): + drop = mocker.patch.object( + startup, "drop_stale_cache_store", new_callable=AsyncMock + ) + drop.side_effect = [False, True] + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_called_once_with( + "update_switch_titledb", + job_id=startup.UPDATE_SWITCH_TITLEDB_JOB_ID, + unique=True, + ) + + async def test_current_stores_queue_nothing(self, mocker, enqueue_task): + drop = mocker.patch.object( + startup, "drop_stale_cache_store", new_callable=AsyncMock + ) + drop.return_value = False + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_not_called() diff --git a/backend/tests/utils/test_cache.py b/backend/tests/utils/test_cache.py index cf39b8c7d..8112bde0f 100644 --- a/backend/tests/utils/test_cache.py +++ b/backend/tests/utils/test_cache.py @@ -1,8 +1,15 @@ from unittest.mock import AsyncMock +import pytest + from handler.metadata.base_handler import MAME_XML_KEY, METADATA_FIXTURES_DIR from handler.redis_handler import async_cache -from utils.cache import conditionally_set_cache +from utils.cache import ( + conditionally_set_cache, + drop_stale_cache_store, + is_cache_schema_current, + stamp_cache_schema, +) class TestConditionallySetCache: @@ -82,3 +89,79 @@ class TestConditionallySetCache: ) mock_cache_pipeline.assert_not_called() + + +class TestCacheSchema: + """A store is read only while its stamp matches the readers' shape.""" + + async def test_matching_stamp_is_current(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="2" + ) + + assert ( + await is_cache_schema_current(async_cache, "romm:store_schema", 2) is True + ) + + @pytest.mark.parametrize("stamped", [None, "1", "not-a-version"]) + async def test_other_stamps_are_stale(self, mocker, stamped: str | None): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=stamped + ) + + assert ( + await is_cache_schema_current(async_cache, "romm:store_schema", 2) is False + ) + + async def test_stamp_records_the_version(self, mocker): + mock_set = mocker.patch.object(async_cache, "set", new_callable=AsyncMock) + + await stamp_cache_schema(async_cache, "romm:store_schema", 2) + + mock_set.assert_awaited_once_with("romm:store_schema", "2") + + async def test_stale_store_is_dropped_with_its_stamp(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="1" + ) + mocker.patch.object( + async_cache, "exists", new_callable=AsyncMock, return_value=1 + ) + mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) + + dropped = await drop_stale_cache_store( + async_cache, "romm:store_schema", 2, ("romm:a", "romm:b") + ) + + assert dropped is True + mock_delete.assert_awaited_once_with("romm:a", "romm:b", "romm:store_schema") + + async def test_current_store_is_left_alone(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="2" + ) + mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) + + dropped = await drop_stale_cache_store( + async_cache, "romm:store_schema", 2, ("romm:a",) + ) + + assert dropped is False + mock_delete.assert_not_awaited() + + async def test_store_that_was_never_filled_is_not_a_drop(self, mocker): + """An install that never imported has nothing to rebuild.""" + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=None + ) + mocker.patch.object( + async_cache, "exists", new_callable=AsyncMock, return_value=0 + ) + mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) + + dropped = await drop_stale_cache_store( + async_cache, "romm:store_schema", 2, ("romm:a",) + ) + + assert dropped is False + mock_delete.assert_not_awaited() diff --git a/backend/utils/cache.py b/backend/utils/cache.py index f2b825b24..1cfd96b05 100644 --- a/backend/utils/cache.py +++ b/backend/utils/cache.py @@ -1,5 +1,6 @@ import hashlib import json +from collections.abc import Sequence from itertools import batched from pathlib import Path @@ -49,3 +50,34 @@ async def conditionally_set_cache(cache: AsyncRedis, key: str, file_path: Path) except Exception as e: # Log the error but don't fail - this allows migrations to run even if Redis is not available log.warning(f"Failed to initialize cache for {key}: {e}") + + +async def is_cache_schema_current( + cache: AsyncRedis, schema_key: str, version: int +) -> bool: + """Whether the store stamped at `schema_key` holds the shape readers expect.""" + return await cache.get(schema_key) == str(version) + + +async def stamp_cache_schema(cache: AsyncRedis, schema_key: str, version: int) -> None: + """Record the shape a completed import left the store in.""" + await cache.set(schema_key, str(version)) + + +async def drop_stale_cache_store( + cache: AsyncRedis, schema_key: str, version: int, keys: Sequence[str] +) -> bool: + """Delete a store an older release wrote, returning whether anything went. + + Readers only understand the current shape, so an unstamped store answers + nothing while still holding its memory. + """ + if await is_cache_schema_current(cache, schema_key, version): + return False + + present = [key for key in keys if await cache.exists(key)] + if not present: + return False + + await cache.delete(*present, schema_key) + return True From decd5c61c4e3506582534dd2d2353b6779954d53 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Sep 2026 16:10:09 -0400 Subject: [PATCH 5/5] refactor(cache): make the versioned store a type rather than three constants The schema key, its version and the keys they cover were three constants per store, retyped at each of the six places that used them and interchangeable enough that one store's version could be checked against another's keys. They are a `VersionedCacheStore` now, so a store is declared once and the startup drop is a loop over a table. The two reader gates were the same four lines, and a third read path was still checking the data key without the stamp, so the LaunchBox entry points disagreed about what populated meant. All three call one helper. The drop probed each key before deleting it, spending a round trip per key to learn what `unlink` reports anyway, and `delete` freed the store on the main thread. Both imports also merge into their hashes, so each now drops a stale store itself rather than trusting the drop to have happened at startup. The alternate name index holds the bare id its reader wants, like the two title indexes beside it, and follows through the same helper. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 16 ++-- .../metadata/launchbox_handler/handler.py | 16 ++-- .../launchbox_handler/remote_source.py | 15 ++-- .../metadata/launchbox_handler/types.py | 33 ++++---- backend/startup.py | 61 ++++++-------- .../scheduled/update_launchbox_metadata.py | 34 ++++---- .../tasks/scheduled/update_switch_titledb.py | 26 +++--- backend/tests/handler/metadata/conftest.py | 13 +++ .../handler/metadata/test_base_handler.py | 21 ++--- .../metadata/test_launchbox_handler.py | 31 ++++--- .../tests/handler/metadata/test_ss_handler.py | 10 +-- .../tasks/test_update_launchbox_metadata.py | 33 +++----- backend/tests/test_startup.py | 55 ++++++++----- backend/tests/utils/test_cache.py | 82 ++++++++++++------- backend/utils/cache.py | 68 +++++++++------ 15 files changed, 267 insertions(+), 247 deletions(-) create mode 100644 backend/tests/handler/metadata/conftest.py diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 677eb5d2d..7f8af5caa 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -15,10 +15,9 @@ from logger.logger import log from tasks.scheduled.update_switch_titledb import ( SWITCH_PRODUCT_ID_KEY, SWITCH_TITLEDB_INDEX_KEY, - SWITCH_TITLEDB_SCHEMA_KEY, - SWITCH_TITLEDB_SCHEMA_VERSION, + SWITCH_TITLEDB_STORE, ) -from utils.cache import is_cache_schema_current +from utils.cache import is_cache_store_ready from utils.context import ctx_httpx_client from utils.switch import derive_base_title_id @@ -315,13 +314,10 @@ class MetadataHandler(abc.ABC): @staticmethod async def _is_switch_titledb_current() -> bool: - """Whether both Switch indexes were written by the current import.""" - if not await is_cache_schema_current( - async_cache, SWITCH_TITLEDB_SCHEMA_KEY, SWITCH_TITLEDB_SCHEMA_VERSION - ): - return False - - return bool(await async_cache.exists(SWITCH_TITLEDB_INDEX_KEY)) + """Whether the titleID index was written by the current import.""" + return await is_cache_store_ready( + async_cache, SWITCH_TITLEDB_STORE, SWITCH_TITLEDB_INDEX_KEY + ) @staticmethod async def _switch_titledb_entry(title_id: str) -> dict | None: diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 00ad5b870..27001675f 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -4,7 +4,7 @@ from config import LAUNCHBOX_API_ENABLED from handler.filesystem import fs_rom_handler from handler.redis_handler import async_cache from logger.logger import log -from utils.cache import is_cache_schema_current +from utils.cache import is_cache_store_ready from utils.database import safe_int from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -17,8 +17,7 @@ from .types import ( DASH_COLON_REGEX, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_DIR, LAUNCHBOX_TAG_REGEX, LaunchboxPlatform, @@ -45,14 +44,9 @@ class LaunchboxHandler(MetadataHandler): @staticmethod async def is_remote_store_populated() -> bool: - if not await is_cache_schema_current( - async_cache, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, - ): - return False - - return bool(await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY)) + return await is_cache_store_ready( + async_cache, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_METADATA_NAME_KEY + ) @staticmethod async def is_remote_store_importing() -> bool: diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 20865b561..a1f75f35a 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -2,6 +2,7 @@ import json from handler.redis_handler import async_cache from logger.logger import log +from utils.cache import is_cache_store_ready from .platforms import get_platform from .types import ( @@ -12,6 +13,7 @@ from .types import ( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, ) from .utils import deinvert_article, file_name_forms, fold_title @@ -40,10 +42,10 @@ class RemoteSource: *, assume_cache_present: bool = False, ) -> dict | None: - if not assume_cache_present and not ( - await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY) + if not assume_cache_present and not await is_cache_store_ready( + async_cache, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_METADATA_NAME_KEY ): - log.error("Could not find the Launchbox Metadata.xml file in cache") + log.error("Could not find a current Launchbox Metadata.xml in cache") return None lb_platform = get_platform(platform_slug) @@ -76,14 +78,9 @@ class RemoteSource: return entry for candidate in candidates: - metadata_alternate_name_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, candidate ) - if not metadata_alternate_name_index_entry: - continue - - database_id = json.loads(metadata_alternate_name_index_entry)["DatabaseID"] - entry = await self.get_by_id(database_id) if not entry: continue diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 80a305246..018d24a14 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -4,6 +4,7 @@ from pathlib import Path from typing import Final, NotRequired, TypedDict from config import ROMM_BASE_PATH +from utils.cache import VersionedCacheStore from ..base_handler import BaseRom @@ -21,22 +22,21 @@ LAUNCHBOX_FILES_KEY: Final[str] = "romm:launchbox_files" LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY: Final[str] = ( "romm:launchbox_metadata_initial_import" ) -LAUNCHBOX_METADATA_SCHEMA_KEY: Final[str] = "romm:launchbox_metadata_schema" -# Bumped whenever an import changes what a store holds, so a store an older -# release wrote is dropped and rebuilt rather than read as the current shape. -LAUNCHBOX_METADATA_SCHEMA_VERSION: Final[int] = 1 - -# Every hash the import fills, dropped together when the schema moves on. -LAUNCHBOX_STORE_KEYS: Final[tuple[str, ...]] = ( - LAUNCHBOX_PLATFORMS_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_FILES_KEY, +# Every hash the Metadata.zip import fills, dropped together on a schema bump. +LAUNCHBOX_METADATA_STORE: Final[VersionedCacheStore] = VersionedCacheStore( + schema_key="romm:launchbox_metadata_schema", + version=1, + keys=( + LAUNCHBOX_PLATFORMS_KEY, + LAUNCHBOX_METADATA_DATABASE_ID_KEY, + LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, + LAUNCHBOX_METADATA_FOLDED_NAME_KEY, + LAUNCHBOX_METADATA_IMAGE_KEY, + LAUNCHBOX_MAME_KEY, + LAUNCHBOX_FILES_KEY, + ), ) LAUNCHBOX_LOCAL_DIR: Final[Path] = Path(ROMM_BASE_PATH) / "launchbox" @@ -57,13 +57,12 @@ class LaunchboxImage(TypedDict): # What each store keeps of its dump element: the fields its reader reads, and -# never one the cache key already carries. Together these drop ~135MB. +# never one the cache key already carries. LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( {"FileName", "Type", "Region"} ) LAUNCHBOX_FILE_FIELDS: Final[frozenset[str]] = frozenset({"GameName"}) LAUNCHBOX_MAME_FIELDS: Final[frozenset[str]] = frozenset({"Name"}) -LAUNCHBOX_ALTERNATE_NAME_FIELDS: Final[frozenset[str]] = frozenset({"DatabaseID"}) class LaunchboxPlatform(TypedDict): diff --git a/backend/startup.py b/backend/startup.py index 1ce50b04f..79ce134d3 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -24,11 +24,7 @@ from handler.metadata.base_handler import ( PSP_SERIAL_INDEX_KEY, SCUMMVM_INDEX_KEY, ) -from handler.metadata.launchbox_handler.types import ( - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, - LAUNCHBOX_STORE_KEYS, -) +from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from handler.redis_handler import ( async_cache, default_queue, @@ -40,11 +36,7 @@ from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY from tasks.registry import enqueue_task -from tasks.scheduled.update_switch_titledb import ( - SWITCH_TITLEDB_SCHEMA_KEY, - SWITCH_TITLEDB_SCHEMA_VERSION, - SWITCH_TITLEDB_STORE_KEYS, -) +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils import get_version from utils.cache import conditionally_set_cache, drop_stale_cache_store from utils.context import initialize_context @@ -103,32 +95,33 @@ def _enqueue_convert_images_to_webp() -> None: _enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID) +# A provider that is off reclaims its store's memory without queueing a +# download nothing would read. +VERSIONED_METADATA_STORES = ( + ( + LAUNCHBOX_METADATA_STORE, + "update_launchbox_metadata", + UPDATE_LAUNCHBOX_METADATA_JOB_ID, + LAUNCHBOX_API_ENABLED, + ), + ( + SWITCH_TITLEDB_STORE, + "update_switch_titledb", + UPDATE_SWITCH_TITLEDB_JOB_ID, + True, + ), +) + + async def _rebuild_outdated_metadata_stores() -> None: - """Drop the metadata stores an older release wrote and queue their rebuild. + """Drop the metadata stores an older release wrote and queue their rebuild.""" + for store, task_name, job_id, rebuild in VERSIONED_METADATA_STORES: + if not await drop_stale_cache_store(async_cache, store): + continue - Lookups read the current shape only, so an old store answers nothing while - still holding several hundred MB of cache. - """ - if await drop_stale_cache_store( - async_cache, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, - LAUNCHBOX_STORE_KEYS, - ): - log.info("Dropped a LaunchBox metadata store left by an older release") - if LAUNCHBOX_API_ENABLED: - _enqueue_backfill( - "update_launchbox_metadata", UPDATE_LAUNCHBOX_METADATA_JOB_ID - ) - - if await drop_stale_cache_store( - async_cache, - SWITCH_TITLEDB_SCHEMA_KEY, - SWITCH_TITLEDB_SCHEMA_VERSION, - SWITCH_TITLEDB_STORE_KEYS, - ): - log.info("Dropped a Switch TitleDB store left by an older release") - _enqueue_backfill("update_switch_titledb", UPDATE_SWITCH_TITLEDB_JOB_ID) + log.info(f"Dropped the {task_name} store left by an older release") + if rebuild: + _enqueue_backfill(task_name, job_id) # Keys the rq-scheduler process left behind, now owned by the cron config. diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 14a87c7bc..c1c4b1f61 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -15,7 +15,6 @@ from config import ( ) from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( - LAUNCHBOX_ALTERNATE_NAME_FIELDS, LAUNCHBOX_FILE_FIELDS, LAUNCHBOX_FILES_KEY, LAUNCHBOX_IMAGE_FIELDS, @@ -27,15 +26,14 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_KEY, ) from handler.metadata.launchbox_handler.utils import fold_title from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType -from utils.cache import stamp_cache_schema +from utils.cache import drop_stale_cache_store, stamp_cache_schema from utils.context import initialize_context from . import UpdateStats @@ -143,6 +141,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): if not await meta_launchbox_handler.is_remote_store_populated(): await async_cache.set(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1") + # An import merges into its hashes, so an older release's rows go first. + await drop_stale_cache_store(async_cache, LAUNCHBOX_METADATA_STORE) + try: zip_file_bytes = BytesIO(content) with zipfile.ZipFile(zip_file_bytes) as z: @@ -217,18 +218,17 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): ) elif elem.tag == "GameAlternateName": - alternate_name_elem = elem.find("AlternateName") - if ( - alternate_name_elem is not None - and alternate_name_elem.text - ): + alternate_name = ( + elem.findtext("AlternateName") or "" + ).strip() + alternate_id = ( + elem.findtext("DatabaseID") or "" + ).strip() + if alternate_name and alternate_id: await writer.hset( LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - alternate_name_elem.text.strip().lower(), - _element_to_dict( - elem, - LAUNCHBOX_ALTERNATE_NAME_FIELDS, - ), + alternate_name.lower(), + alternate_id, ) elif elem.tag == "GameImage": @@ -324,11 +324,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): log.error("Bad zip file in launchbox metadata update") return update_stats.to_dict() - await stamp_cache_schema( - async_cache, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, - ) + await stamp_cache_schema(async_cache, LAUNCHBOX_METADATA_STORE) # Also clears a flag left behind by an earlier run that died partway. await async_cache.delete(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index ce0ef9b1b..7743fa4cb 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -9,22 +9,21 @@ from config import ( from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType -from utils.cache import stamp_cache_schema +from utils.cache import ( + VersionedCacheStore, + drop_stale_cache_store, + stamp_cache_schema, +) from utils.context import initialize_context from . import UpdateStats SWITCH_TITLEDB_INDEX_KEY: Final = "romm:switch_titledb" SWITCH_PRODUCT_ID_KEY: Final = "romm:switch_product_id" -SWITCH_TITLEDB_SCHEMA_KEY: Final = "romm:switch_titledb_schema" - -# Bumped whenever an import changes what the indexes hold, so a store an older -# release wrote is dropped and rebuilt rather than read as the current shape. -SWITCH_TITLEDB_SCHEMA_VERSION: Final[int] = 1 - -SWITCH_TITLEDB_STORE_KEYS: Final[tuple[str, ...]] = ( - SWITCH_TITLEDB_INDEX_KEY, - SWITCH_PRODUCT_ID_KEY, +SWITCH_TITLEDB_STORE: Final = VersionedCacheStore( + schema_key="romm:switch_titledb_schema", + version=1, + keys=(SWITCH_TITLEDB_INDEX_KEY, SWITCH_PRODUCT_ID_KEY), ) @@ -48,6 +47,9 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): if content is None: return update_stats.to_dict() + # An import merges into its hashes, so an older release's rows go first. + await drop_stale_cache_store(async_cache, SWITCH_TITLEDB_STORE) + index_json = json.loads(content) relevant_data = {k: v for k, v in index_json.items() if k and v} total_items = len(relevant_data) @@ -76,9 +78,7 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): update_stats.update(processed=processed_items) await pipe.execute() - await stamp_cache_schema( - async_cache, SWITCH_TITLEDB_SCHEMA_KEY, SWITCH_TITLEDB_SCHEMA_VERSION - ) + await stamp_cache_schema(async_cache, SWITCH_TITLEDB_STORE) # Final progress update update_stats.update(processed=processed_items) diff --git a/backend/tests/handler/metadata/conftest.py b/backend/tests/handler/metadata/conftest.py new file mode 100644 index 000000000..e1496aad8 --- /dev/null +++ b/backend/tests/handler/metadata/conftest.py @@ -0,0 +1,13 @@ +from unittest.mock import AsyncMock + +from utils.cache import VersionedCacheStore + + +def schema_stamp_get(*stores: VersionedCacheStore) -> AsyncMock: + """Mock `async_cache.get` so the given stores read as currently stamped.""" + stamps = {store.schema_key: str(store.version) for store in stores} + + async def get(key: str) -> str | None: + return stamps.get(key) + + return AsyncMock(side_effect=get) diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index 094c6ab3a..5925fcf5a 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -6,6 +6,7 @@ from urllib.parse import parse_qsl, urlparse import httpx import pytest +from tests.handler.metadata.conftest import schema_stamp_get from handler.metadata import base_handler from handler.metadata.base_handler import ( @@ -32,8 +33,7 @@ from models.rom import Rom from tasks.scheduled.update_switch_titledb import ( SWITCH_PRODUCT_ID_KEY, SWITCH_TITLEDB_INDEX_KEY, - SWITCH_TITLEDB_SCHEMA_KEY, - SWITCH_TITLEDB_SCHEMA_VERSION, + SWITCH_TITLEDB_STORE, ) from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -118,17 +118,6 @@ class TestNormalizeSearchTerm: assert cache_info2.hits == cache_info1.hits + 1 -def current_schema_get() -> AsyncMock: - """Answer the schema stamp read with the version the readers expect.""" - - async def get(key: str) -> str | None: - if key == SWITCH_TITLEDB_SCHEMA_KEY: - return str(SWITCH_TITLEDB_SCHEMA_VERSION) - return None - - return AsyncMock(side_effect=get) - - class TestMetadataHandlerMethods: """Test MetadataHandler instance methods.""" @@ -285,7 +274,7 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( - async_cache, "get", current_schema_get() + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: @@ -342,7 +331,7 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( - async_cache, "get", current_schema_get() + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: @@ -389,7 +378,7 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( - async_cache, "get", current_schema_get() + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 0fa8f2f4a..ff0fc3c72 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -16,6 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest from anyio import Path as AnyioPath from defusedxml import ElementTree as ET +from tests.handler.metadata.conftest import schema_stamp_get from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.local_source import LocalSource @@ -40,8 +41,7 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_METADATA_STORE, LaunchboxImage, LaunchboxMetadata, MediaRequest, @@ -102,17 +102,6 @@ SAMPLE_N64_XML = """\ """ -def current_schema_get() -> AsyncMock: - """Answer the schema stamp read with the version the readers expect.""" - - async def get(key: str) -> str | None: - if key == LAUNCHBOX_METADATA_SCHEMA_KEY: - return str(LAUNCHBOX_METADATA_SCHEMA_VERSION) - return None - - return AsyncMock(side_effect=get) - - REMOTE_ENTRY = { "DatabaseID": "1234", "Name": "Super Mario Bros.", @@ -1359,7 +1348,9 @@ class TestRemoteMatchLocalImages: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) - monkeypatch.setattr(async_cache, "get", current_schema_get()) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) with patch( "handler.metadata.launchbox_handler.handler.fs_rom_handler" @@ -1491,7 +1482,9 @@ class TestLaunchboxHandlerHeartbeat: patch.object( async_cache, "exists", self._cache_exists(LAUNCHBOX_METADATA_NAME_KEY) ), - patch.object(async_cache, "get", current_schema_get()), + patch.object( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ), ): assert await handler.heartbeat() is True @@ -1547,7 +1540,9 @@ class TestLaunchboxHandlerGetRom: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) - monkeypatch.setattr(async_cache, "get", current_schema_get()) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) return h async def test_disabled_returns_fallback( @@ -1899,7 +1894,9 @@ class TestLaunchboxHandlerSearch: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) - monkeypatch.setattr(async_cache, "get", current_schema_get()) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) return h async def test_get_matched_roms_by_name_disabled_returns_empty( diff --git a/backend/tests/handler/metadata/test_ss_handler.py b/backend/tests/handler/metadata/test_ss_handler.py index 91128e8ab..79daaa8df 100644 --- a/backend/tests/handler/metadata/test_ss_handler.py +++ b/backend/tests/handler/metadata/test_ss_handler.py @@ -7,6 +7,7 @@ from urllib.parse import parse_qs, urlparse import pytest from fastapi import HTTPException, status +from tests.handler.metadata.conftest import schema_stamp_get from adapters.services.screenscraper import ( ScreenScraperCredentialsError, @@ -39,7 +40,7 @@ from handler.metadata.ss_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom -from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_SCHEMA_VERSION +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE def _make_config( @@ -1910,12 +1911,7 @@ class TestSonySerialFilenames: return_value=True, ), patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists, - patch.object( - async_cache, - "get", - new_callable=AsyncMock, - return_value=str(SWITCH_TITLEDB_SCHEMA_VERSION), - ), + patch.object(async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE)), patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, patch.object( SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index 80fb227ad..219f77392 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -17,8 +17,7 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_SCHEMA_KEY, - LAUNCHBOX_METADATA_SCHEMA_VERSION, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_KEY, ) from handler.redis_handler import async_cache @@ -233,9 +232,10 @@ class TestUpdateLaunchboxMetadataTask: ] ] - # Every other store keeps its reader's field, and never one the key - # already carries: the fixture's Platform, FileType and Size all go. - assert values(metadata_alt_calls) == [{"DatabaseID": "12345"}] + # The alternate name index points at the record like the other two. + assert values(metadata_alt_calls) == ["12345"] + + # A store keeps its reader's field, never one the key already carries. assert values(files_calls) == [ {"GameName": "Super Mario 64"}, {"GameName": "Crash Bandicoot"}, @@ -368,18 +368,8 @@ class TestUpdateLaunchboxMetadataTaskIntegration: # Verify that all expected Redis keys were used redis_keys_used = [call[0][0] for call in hset_calls] - expected_keys = [ - LAUNCHBOX_PLATFORMS_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_FILES_KEY, - ] - - for expected_key in expected_keys: + # The tuple the schema drop deletes has to name every key written. + for expected_key in LAUNCHBOX_METADATA_STORE.keys: assert ( expected_key in redis_keys_used ), f"Expected key {expected_key} not found in Redis operations" @@ -477,7 +467,10 @@ class TestInitialImportFlag: assert [call.args for call in mock_set.await_args_list] == [ (LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1"), - (LAUNCHBOX_METADATA_SCHEMA_KEY, str(LAUNCHBOX_METADATA_SCHEMA_VERSION)), + ( + LAUNCHBOX_METADATA_STORE.schema_key, + str(LAUNCHBOX_METADATA_STORE.version), + ), ] mock_delete.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) @@ -496,7 +489,7 @@ class TestInitialImportFlag: patch.object( async_cache, "get", - AsyncMock(return_value=str(LAUNCHBOX_METADATA_SCHEMA_VERSION)), + AsyncMock(return_value=str(LAUNCHBOX_METADATA_STORE.version)), ), patch.object(async_cache, "set", AsyncMock()) as mock_set, patch.object(async_cache, "delete", AsyncMock()), @@ -505,7 +498,7 @@ class TestInitialImportFlag: # Only the schema stamp, never the initial-import flag. mock_set.assert_awaited_once_with( - LAUNCHBOX_METADATA_SCHEMA_KEY, str(LAUNCHBOX_METADATA_SCHEMA_VERSION) + LAUNCHBOX_METADATA_STORE.schema_key, str(LAUNCHBOX_METADATA_STORE.version) ) @patch.object(RemoteFilePullTask, "run") diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index 14dd50f73..f34825ad4 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -7,7 +7,10 @@ import startup from rq.exceptions import DuplicateJobError from rq.job import JOB_ID_PATTERN +from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from tasks.registry import get_task +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE +from utils.cache import VersionedCacheStore @pytest.fixture @@ -135,14 +138,25 @@ class TestDropLegacySchedulerState: class TestRebuildOutdatedMetadataStores: """A store an older release wrote is dropped, and its rebuild queued.""" + @pytest.fixture + def drop_stale(self, mocker): + """Report only the stores named as stale, whatever order they run in.""" + + def patch_drop(*stale: VersionedCacheStore): + async def drop(_cache, store): + return store in stale + + return mocker.patch.object( + startup, "drop_stale_cache_store", new=AsyncMock(side_effect=drop) + ) + + return patch_drop + async def test_stale_launchbox_store_is_dropped_and_rebuilt( - self, mocker, enqueue_task + self, mocker, drop_stale, enqueue_task ): mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", True) - drop = mocker.patch.object( - startup, "drop_stale_cache_store", new_callable=AsyncMock - ) - drop.side_effect = [True, False] + drop_stale(LAUNCHBOX_METADATA_STORE) await startup._rebuild_outdated_metadata_stores() @@ -153,26 +167,32 @@ class TestRebuildOutdatedMetadataStores: ) async def test_launchbox_rebuild_waits_on_the_provider_being_enabled( - self, mocker, enqueue_task + self, mocker, drop_stale, enqueue_task ): """Dropping reclaims the memory; refilling it would serve nobody.""" mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", False) - drop = mocker.patch.object( - startup, "drop_stale_cache_store", new_callable=AsyncMock + mocker.patch.object( + startup, + "VERSIONED_METADATA_STORES", + ( + ( + LAUNCHBOX_METADATA_STORE, + "update_launchbox_metadata", + startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, + False, + ), + ), ) - drop.side_effect = [True, False] + drop_stale(LAUNCHBOX_METADATA_STORE) await startup._rebuild_outdated_metadata_stores() enqueue_task.assert_not_called() async def test_stale_switch_store_is_dropped_and_rebuilt( - self, mocker, enqueue_task + self, drop_stale, enqueue_task ): - drop = mocker.patch.object( - startup, "drop_stale_cache_store", new_callable=AsyncMock - ) - drop.side_effect = [False, True] + drop_stale(SWITCH_TITLEDB_STORE) await startup._rebuild_outdated_metadata_stores() @@ -182,11 +202,8 @@ class TestRebuildOutdatedMetadataStores: unique=True, ) - async def test_current_stores_queue_nothing(self, mocker, enqueue_task): - drop = mocker.patch.object( - startup, "drop_stale_cache_store", new_callable=AsyncMock - ) - drop.return_value = False + async def test_current_stores_queue_nothing(self, drop_stale, enqueue_task): + drop_stale() await startup._rebuild_outdated_metadata_stores() diff --git a/backend/tests/utils/test_cache.py b/backend/tests/utils/test_cache.py index 8112bde0f..4934f08a5 100644 --- a/backend/tests/utils/test_cache.py +++ b/backend/tests/utils/test_cache.py @@ -5,9 +5,11 @@ import pytest from handler.metadata.base_handler import MAME_XML_KEY, METADATA_FIXTURES_DIR from handler.redis_handler import async_cache from utils.cache import ( + VersionedCacheStore, conditionally_set_cache, drop_stale_cache_store, is_cache_schema_current, + is_cache_store_ready, stamp_cache_schema, ) @@ -94,14 +96,16 @@ class TestConditionallySetCache: class TestCacheSchema: """A store is read only while its stamp matches the readers' shape.""" + STORE = VersionedCacheStore( + schema_key="romm:store_schema", version=2, keys=("romm:a", "romm:b") + ) + async def test_matching_stamp_is_current(self, mocker): mocker.patch.object( async_cache, "get", new_callable=AsyncMock, return_value="2" ) - assert ( - await is_cache_schema_current(async_cache, "romm:store_schema", 2) is True - ) + assert await is_cache_schema_current(async_cache, self.STORE) is True @pytest.mark.parametrize("stamped", [None, "1", "not-a-version"]) async def test_other_stamps_are_stale(self, mocker, stamped: str | None): @@ -109,14 +113,12 @@ class TestCacheSchema: async_cache, "get", new_callable=AsyncMock, return_value=stamped ) - assert ( - await is_cache_schema_current(async_cache, "romm:store_schema", 2) is False - ) + assert await is_cache_schema_current(async_cache, self.STORE) is False async def test_stamp_records_the_version(self, mocker): mock_set = mocker.patch.object(async_cache, "set", new_callable=AsyncMock) - await stamp_cache_schema(async_cache, "romm:store_schema", 2) + await stamp_cache_schema(async_cache, self.STORE) mock_set.assert_awaited_once_with("romm:store_schema", "2") @@ -124,30 +126,24 @@ class TestCacheSchema: mocker.patch.object( async_cache, "get", new_callable=AsyncMock, return_value="1" ) - mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=1 - ) - mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) - - dropped = await drop_stale_cache_store( - async_cache, "romm:store_schema", 2, ("romm:a", "romm:b") + mock_unlink = mocker.patch.object( + async_cache, "unlink", new_callable=AsyncMock, return_value=2 ) - assert dropped is True - mock_delete.assert_awaited_once_with("romm:a", "romm:b", "romm:store_schema") + assert await drop_stale_cache_store(async_cache, self.STORE) is True + assert [call.args for call in mock_unlink.await_args_list] == [ + ("romm:a", "romm:b"), + ("romm:store_schema",), + ] async def test_current_store_is_left_alone(self, mocker): mocker.patch.object( async_cache, "get", new_callable=AsyncMock, return_value="2" ) - mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) + mock_unlink = mocker.patch.object(async_cache, "unlink", new_callable=AsyncMock) - dropped = await drop_stale_cache_store( - async_cache, "romm:store_schema", 2, ("romm:a",) - ) - - assert dropped is False - mock_delete.assert_not_awaited() + assert await drop_stale_cache_store(async_cache, self.STORE) is False + mock_unlink.assert_not_awaited() async def test_store_that_was_never_filled_is_not_a_drop(self, mocker): """An install that never imported has nothing to rebuild.""" @@ -155,13 +151,37 @@ class TestCacheSchema: async_cache, "get", new_callable=AsyncMock, return_value=None ) mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=0 - ) - mock_delete = mocker.patch.object(async_cache, "delete", new_callable=AsyncMock) - - dropped = await drop_stale_cache_store( - async_cache, "romm:store_schema", 2, ("romm:a",) + async_cache, "unlink", new_callable=AsyncMock, return_value=0 ) - assert dropped is False - mock_delete.assert_not_awaited() + assert await drop_stale_cache_store(async_cache, self.STORE) is False + + +class TestCacheStoreReady: + """The reader gate: stamped with the current shape, and actually filled.""" + + STORE = VersionedCacheStore( + schema_key="romm:store_schema", version=2, keys=("romm:a",) + ) + + @pytest.mark.parametrize( + ("stamped", "present", "expected"), + [ + ("2", 1, True), + ("1", 1, False), + (None, 1, False), + # A hash an eviction policy reclaimed leaves the stamp behind. + ("2", 0, False), + ], + ids=["ready", "stale", "unstamped", "evicted"], + ) + async def test_gate(self, mocker, stamped, present, expected): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=stamped + ) + mocker.patch.object( + async_cache, "exists", new_callable=AsyncMock, return_value=present + ) + + result = await is_cache_store_ready(async_cache, self.STORE, "romm:a") + assert result is expected diff --git a/backend/utils/cache.py b/backend/utils/cache.py index 1cfd96b05..675b3d007 100644 --- a/backend/utils/cache.py +++ b/backend/utils/cache.py @@ -1,8 +1,8 @@ import hashlib import json -from collections.abc import Sequence from itertools import batched from pathlib import Path +from typing import NamedTuple from anyio import open_file from redis.asyncio import Redis as AsyncRedis @@ -52,32 +52,52 @@ async def conditionally_set_cache(cache: AsyncRedis, key: str, file_path: Path) log.warning(f"Failed to initialize cache for {key}: {e}") -async def is_cache_schema_current( - cache: AsyncRedis, schema_key: str, version: int -) -> bool: - """Whether the store stamped at `schema_key` holds the shape readers expect.""" - return await cache.get(schema_key) == str(version) +class VersionedCacheStore(NamedTuple): + """A group of cache keys filled together, stamped with the shape they hold. - -async def stamp_cache_schema(cache: AsyncRedis, schema_key: str, version: int) -> None: - """Record the shape a completed import left the store in.""" - await cache.set(schema_key, str(version)) - - -async def drop_stale_cache_store( - cache: AsyncRedis, schema_key: str, version: int, keys: Sequence[str] -) -> bool: - """Delete a store an older release wrote, returning whether anything went. - - Readers only understand the current shape, so an unstamped store answers - nothing while still holding its memory. + Bump `version` when an import changes that shape, so a store an older + release wrote is dropped rather than read as the current one. """ - if await is_cache_schema_current(cache, schema_key, version): + + schema_key: str + version: int + keys: tuple[str, ...] + + +async def is_cache_schema_current( + cache: AsyncRedis, store: VersionedCacheStore +) -> bool: + """Whether the store holds the shape its readers expect.""" + return await cache.get(store.schema_key) == str(store.version) + + +async def stamp_cache_schema(cache: AsyncRedis, store: VersionedCacheStore) -> None: + """Record the shape a completed import left the store in.""" + await cache.set(store.schema_key, str(store.version)) + + +async def is_cache_store_ready( + cache: AsyncRedis, store: VersionedCacheStore, data_key: str +) -> bool: + """Whether `data_key` holds entries an import wrote under the current shape. + + The stamp alone would trust a hash an eviction policy has since reclaimed. + """ + if not await is_cache_schema_current(cache, store): return False - present = [key for key in keys if await cache.exists(key)] - if not present: + return bool(await cache.exists(data_key)) + + +async def drop_stale_cache_store(cache: AsyncRedis, store: VersionedCacheStore) -> bool: + """Delete a store an older release wrote, returning whether one was there. + + `unlink` frees the hundreds of MB a metadata store holds off the main + thread, so a boot does not stall every other client. + """ + if await is_cache_schema_current(cache, store): return False - await cache.delete(*present, schema_key) - return True + dropped = await cache.unlink(*store.keys) + await cache.unlink(store.schema_key) + return bool(dropped)