From d4f3d8be83a3512fca8a2b3f89a6760afefdb898 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Sep 2026 20:25:42 -0400 Subject: [PATCH] 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")