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) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-10 15:45:32 -04:00
parent 13aaf54921
commit 721197476a
15 changed files with 421 additions and 76 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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,

View File

@@ -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):

View File

@@ -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"

View File

@@ -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)

View File

@@ -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!")

View File

@@ -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):

View File

@@ -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 = """\
</LaunchBox>
"""
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(

View File

@@ -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

View File

@@ -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(

View File

@@ -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()

View File

@@ -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()

View File

@@ -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