diff --git a/backend/handler/metadata/hasheous_handler.py b/backend/handler/metadata/hasheous_handler.py index 3dd1133b1..406c5eea6 100644 --- a/backend/handler/metadata/hasheous_handler.py +++ b/backend/handler/metadata/hasheous_handler.py @@ -231,19 +231,26 @@ class HasheousHandler(MetadataHandler): ra_id=platform["ra_id"], ) - async def lookup_rom(self, platform_slug: str, files: list[RomFile]) -> HasheousRom: + async def lookup_rom( + self, platform_slug: str, files: list[RomFile] + ) -> tuple[HasheousRom, bool]: """Identify a ROM by its file hashes. Returns a HasheousRom with the matched IDs, or an empty match if the lookup fails. The lookup is best-effort and never raises to the caller, so an unreachable Hasheous can't abort a scan. + + The second value tells the two empty matches apart: True means Hasheous + answered and knows nothing about these hashes, False means we never got + an answer (disabled, no hashes to send, or the request failed). Only the + former is safe to treat as "this ROM is not in any database". """ fallback_rom = HasheousRom( hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None ) if not self.is_enabled(): - return fallback_rom + return fallback_rom, False filtered_files = [ file @@ -284,7 +291,7 @@ class HasheousHandler(MetadataHandler): "No hashes provided for Hasheous lookup. " "At least one of md5, sha1, or crc is required." ) - return fallback_rom + return fallback_rom, False try: hasheous_game = await self._request( @@ -297,10 +304,10 @@ class HasheousHandler(MetadataHandler): ) except Exception as exc: log.error("Hasheous hash lookup failed, skipping: %s", exc) - return fallback_rom + return fallback_rom, False if not hasheous_game: - return fallback_rom + return fallback_rom, True metadata = hasheous_game.get("metadata", []) attributes = hasheous_game.get("attributes", []) @@ -331,24 +338,27 @@ class HasheousHandler(MetadataHandler): url_cover = f"https://hasheous.org{attr['link']}" break - return HasheousRom( - hasheous_id=hasheous_game["id"], - name=hasheous_game.get("name", ""), - igdb_id=int(igdb_id) if igdb_id else None, - tgdb_id=int(tgdb_id) if tgdb_id else None, - ra_id=int(ra_id) if ra_id else None, - url_cover=url_cover, - hasheous_metadata=HasheousMetadata( - tosec_match="TOSEC" in signatures, - mame_arcade_match="MAMEArcade" in signatures, - mame_mess_match="MAMEMess" in signatures, - nointro_match="NoIntros" in signatures, - redump_match="Redump" in signatures, - whdload_match="WHDLoad" in signatures, - ra_match="RetroAchievements" in signatures, - fbneo_match="FBNeo" in signatures, - puredos_match="PureDOS" in signatures, + return ( + HasheousRom( + hasheous_id=hasheous_game["id"], + name=hasheous_game.get("name", ""), + igdb_id=int(igdb_id) if igdb_id else None, + tgdb_id=int(tgdb_id) if tgdb_id else None, + ra_id=int(ra_id) if ra_id else None, + url_cover=url_cover, + hasheous_metadata=HasheousMetadata( + tosec_match="TOSEC" in signatures, + mame_arcade_match="MAMEArcade" in signatures, + mame_mess_match="MAMEMess" in signatures, + nointro_match="NoIntros" in signatures, + redump_match="Redump" in signatures, + whdload_match="WHDLoad" in signatures, + ra_match="RetroAchievements" in signatures, + fbneo_match="FBNeo" in signatures, + puredos_match="PureDOS" in signatures, + ), ), + True, ) async def get_igdb_game(self, hasheous_rom: HasheousRom) -> HasheousRom: diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index a17360124..35ec04cbf 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -444,13 +444,14 @@ async def scan_rom( gamelist_id=None, ) - async def fetch_hasheous_hash_match() -> HasheousRom: + async def fetch_hasheous_hash_match() -> tuple[HasheousRom, bool]: if ( MetadataSource.HASHEOUS in metadata_sources and platform.hasheous_id and ( newly_added or scan_type == ScanType.COMPLETE + or scan_type == ScanType.HASHES or (scan_type == ScanType.UPDATE and rom.hasheous_id) or ( scan_type == ScanType.UNMATCHED @@ -463,7 +464,10 @@ async def scan_rom( platform.slug, get_match_files() ) - return HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + return ( + HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None), + False, + ) _added_rom = db_rom_handler.add_rom(Rom(**rom_attrs)) _added_rom.is_identifying = True @@ -488,7 +492,7 @@ async def scan_rom( # Run hash fetches concurrently ( playmatch_hash_match, - hasheous_hash_match, + (hasheous_hash_match, hasheous_lookup_conclusive), ) = await asyncio.gather( fetch_playmatch_hash_match(), fetch_hasheous_hash_match(), @@ -817,6 +821,7 @@ async def scan_rom( and ( newly_added or scan_type == ScanType.COMPLETE + or scan_type == ScanType.HASHES or (scan_type == ScanType.UPDATE and rom.hasheous_id) or ( scan_type == ScanType.UNMATCHED @@ -1014,9 +1019,11 @@ async def scan_rom( if field_value: rom_attrs[field] = field_value - # Don't overwrite existing base fields on update and unmatched scans - if not newly_added and ( - scan_type == ScanType.UNMATCHED or scan_type == ScanType.UPDATE + # Don't overwrite existing base fields on update, unmatched and hashes scans + if not newly_added and scan_type in ( + ScanType.UNMATCHED, + ScanType.UPDATE, + ScanType.HASHES, ): # A ROM's name defaults to a filename-derived placeholder when first # created. Treat that placeholder as "no name" so a freshly matched provider @@ -1048,6 +1055,18 @@ async def scan_rom( } ) + # A rehash that no longer matches must drop the previous Hasheous match, or + # the ROM keeps showing verification flags earned by hashes it no longer has. + # Only a conclusive lookup clears them, so an unreachable Hasheous can't + # silently de-verify a library. + if ( + scan_type == ScanType.HASHES + and hasheous_lookup_conclusive + and not hasheous_hash_match.get("hasheous_id") + ): + rom_attrs["hasheous_id"] = None + rom_attrs["hasheous_metadata"] = {} + # Use PICO-8 cartridge PNG as cover art if no cover is set. # PICO-8 .p8.png files are valid PNG images whose visual content is the # cartridge label, so the ROM file itself serves as the cover art. diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index e8b82303c..53f5bd60e 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -14,7 +14,7 @@ from handler.metadata import ( meta_sgdb_handler, meta_ss_handler, ) -from handler.metadata.hasheous_handler import HasheousRom +from handler.metadata.hasheous_handler import HasheousMetadata, HasheousRom from handler.metadata.ra_handler import RAGameRom from handler.metadata.ss_handler import ( SSRom, @@ -136,7 +136,7 @@ async def test_scan_rom_complete_clears_unselected_metadata( ra_id=None, name="Mock Hasheous Game", ) - mock_lookup.return_value = hasheous_result + mock_lookup.return_value = (hasheous_result, True) mock_get_igdb.return_value = hasheous_result mock_get_ra.return_value = hasheous_result @@ -344,7 +344,7 @@ async def test_scan_rom_unmatched_replaces_placeholder_name( ra_id=None, name="Snow Bros.", ) - mock_lookup.return_value = hasheous_result + mock_lookup.return_value = (hasheous_result, True) mock_get_igdb.return_value = hasheous_result mock_get_ra.return_value = hasheous_result @@ -407,7 +407,7 @@ async def test_scan_rom_unmatched_preserves_custom_name( ra_id=None, name="Snow Bros.", ) - mock_lookup.return_value = hasheous_result + mock_lookup.return_value = (hasheous_result, True) mock_get_igdb.return_value = hasheous_result mock_get_ra.return_value = hasheous_result @@ -465,7 +465,7 @@ async def test_scan_rom_unmatched_no_match_uses_parsed_name( placeholder into the parsed name (tags and extension stripped), so the title is clean and a follow-up search uses the parsed name.""" no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) - mock_lookup.return_value = no_match + mock_lookup.return_value = (no_match, True) mock_get_igdb.return_value = no_match mock_get_ra.return_value = no_match @@ -512,6 +512,207 @@ async def test_scan_rom_unmatched_no_match_uses_parsed_name( assert result.name == "Snow Brothers" +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_hasheous_handler, "get_ra_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "get_igdb_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "lookup_rom", new_callable=AsyncMock) +async def test_scan_rom_hashes_rematches_hasheous( + mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled +): + """A HASHES rescan must re-run the Hasheous hash lookup, so a ROM whose + hashes were wrong picks up its signature matches (the verified flags) + without needing a complete rescan.""" + hasheous_result = HasheousRom( + hasheous_id=999, + igdb_id=None, + tgdb_id=None, + ra_id=None, + name="Snow Bros.", + hasheous_metadata=HasheousMetadata( + tosec_match=False, + mame_arcade_match=False, + mame_mess_match=False, + nointro_match=True, + redump_match=False, + whdload_match=False, + ra_match=True, + fbneo_match=False, + puredos_match=False, + ), + ) + mock_lookup.return_value = (hasheous_result, True) + mock_get_igdb.return_value = hasheous_result + mock_get_ra.return_value = hasheous_result + + platform = Platform( + id=1, slug="n64", fs_slug="n64", name="Nintendo 64", igdb_id=4, hasheous_id=64 + ) + platform = db_platform_handler.add_platform(platform) + + # ROM that never matched Hasheous because its hashes were wrong. + rom = Rom( + platform_id=platform.id, + fs_name="Snow Brothers (USA).7z", + fs_name_no_tags="Snow Brothers", + fs_name_no_ext="Snow Brothers (USA)", + fs_extension="7z", + fs_path="n64/Snow Brothers (USA)", + name="My Custom Title", + hasheous_id=None, + hasheous_metadata={}, + fs_size_bytes=1024, + tags=[], + ) + rom = db_rom_handler.add_rom(rom) + + async with initialize_context(): + result = await scan_rom( + platform=platform, + scan_type=ScanType.HASHES, + rom=rom, + fs_rom={ + "fs_name": "Snow Brothers (USA).7z", + "flat": True, + "nested": False, + "files": [], + "crc_hash": "newcrc", + "md5_hash": "newmd5", + "sha1_hash": "newsha1", + "ra_hash": "newrahash", + }, + metadata_sources=[MetadataSource.HASHEOUS], + newly_added=False, + ) + + mock_lookup.assert_called_once() + assert result.hasheous_id == 999 + assert result.hasheous_metadata["nointro_match"] is True + assert result.hasheous_metadata["ra_match"] is True + # A rehash must not rewrite user-visible fields. + assert result.name == "My Custom Title" + + +def _stale_hasheous_rom(platform: Platform) -> Rom: + """A ROM carrying a Hasheous match (and its verification flags) earned by + hashes it is about to lose.""" + return db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + fs_name="Snow Brothers (USA).7z", + fs_name_no_tags="Snow Brothers", + fs_name_no_ext="Snow Brothers (USA)", + fs_extension="7z", + fs_path="n64/Snow Brothers (USA)", + name="Snow Bros.", + hasheous_id=999, + hasheous_metadata={"nointro_match": True, "ra_match": True}, + fs_size_bytes=1024, + tags=[], + ) + ) + + +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_hasheous_handler, "get_ra_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "get_igdb_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "lookup_rom", new_callable=AsyncMock) +async def test_scan_rom_hashes_clears_stale_hasheous_match( + mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled +): + """A HASHES rescan whose new hashes no longer match must drop the previous + Hasheous match, so the ROM stops reporting verification flags it earned with + hashes it no longer has.""" + no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + # Hasheous answered and knows nothing about the new hashes. + mock_lookup.return_value = (no_match, True) + mock_get_igdb.return_value = no_match + mock_get_ra.return_value = no_match + + platform = db_platform_handler.add_platform( + Platform( + id=1, + slug="n64", + fs_slug="n64", + name="Nintendo 64", + igdb_id=4, + hasheous_id=64, + ) + ) + rom = _stale_hasheous_rom(platform) + + async with initialize_context(): + result = await scan_rom( + platform=platform, + scan_type=ScanType.HASHES, + rom=rom, + fs_rom={ + "fs_name": "Snow Brothers (USA).7z", + "flat": True, + "nested": False, + "files": [], + "crc_hash": "changedcrc", + "md5_hash": "changedmd5", + "sha1_hash": "changedsha1", + "ra_hash": "", + }, + metadata_sources=[MetadataSource.HASHEOUS], + newly_added=False, + ) + + assert result.hasheous_id is None + assert result.hasheous_metadata == {} + + +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_hasheous_handler, "get_ra_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "get_igdb_game", new_callable=AsyncMock) +@patch.object(meta_hasheous_handler, "lookup_rom", new_callable=AsyncMock) +async def test_scan_rom_hashes_keeps_match_when_hasheous_unreachable( + mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled +): + """An inconclusive lookup (Hasheous down, no hashes to send) must leave the + existing match alone, so an outage can't silently de-verify a library.""" + no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + # Same empty match, but we never got an answer. + mock_lookup.return_value = (no_match, False) + mock_get_igdb.return_value = no_match + mock_get_ra.return_value = no_match + + platform = db_platform_handler.add_platform( + Platform( + id=1, + slug="n64", + fs_slug="n64", + name="Nintendo 64", + igdb_id=4, + hasheous_id=64, + ) + ) + rom = _stale_hasheous_rom(platform) + + async with initialize_context(): + result = await scan_rom( + platform=platform, + scan_type=ScanType.HASHES, + rom=rom, + fs_rom={ + "fs_name": "Snow Brothers (USA).7z", + "flat": True, + "nested": False, + "files": [], + "crc_hash": "changedcrc", + "md5_hash": "changedmd5", + "sha1_hash": "changedsha1", + "ra_hash": "", + }, + metadata_sources=[MetadataSource.HASHEOUS], + newly_added=False, + ) + + assert result.hasheous_id == 999 + assert result.hasheous_metadata == {"nointro_match": True, "ra_match": True} + + def _top_level_rom_file(**kwargs) -> RomFile: """Build a RomFile whose `is_top_level` cached_property is pre-seeded to True, so it passes lookup_rom's filtering without a persisted rom.""" @@ -556,9 +757,11 @@ async def test_lookup_rom_sends_all_top_level_file_hashes( _top_level_rom_file(file_name="nohash.bin", file_size_bytes=50), ] - result = await meta_hasheous_handler.lookup_rom("n64", files) + result, conclusive = await meta_hasheous_handler.lookup_rom("n64", files) assert result["hasheous_id"] is None + # Hasheous answered, it just knows nothing about these hashes. + assert conclusive is True mock_request.assert_called_once() sent_data = mock_request.call_args.kwargs["data"] assert sent_data == [ @@ -573,9 +776,11 @@ async def test_lookup_rom_skips_request_when_no_hashes(mock_is_enabled, mock_req """lookup_rom must not hit the API when no file has any usable hash.""" files = [_top_level_rom_file(file_name="nohash.bin", file_size_bytes=50)] - result = await meta_hasheous_handler.lookup_rom("n64", files) + result, conclusive = await meta_hasheous_handler.lookup_rom("n64", files) assert result["hasheous_id"] is None + # Nothing was asked, so the empty match says nothing about the ROM. + assert conclusive is False mock_request.assert_not_called()