From d800d60c32ece59200f46d2d29070dced6cbe1dd Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 19:44:36 -0400 Subject: [PATCH 1/2] fix(scan): don't report an unanswered lookup as a confirmed miss lookup_rom already tells a real "nothing knows these hashes" apart from a provider that never answered, and only the HASHES de-verify guard read it. A 429, a 500 or a timeout therefore logged the ROM as not identified in the same words as a genuine coverage gap, and the reporter spent two days treating transient failures as gaps. Track the sources that gave no answer and say so in the outcome. Retrying in-scan, or persisting a revisit marker, would change what the nightly QUICK scan covers, so it is deliberately not part of this. Refs #4398 Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/scan_handler.py | 32 +++++++-- backend/tests/handler/test_fastapi.py | 100 ++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 5 deletions(-) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 473f928e3..8b53100fe 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -585,6 +585,10 @@ async def scan_rom( # no id for it never enters the set, so a rescan can't clear what it can't redo. attempted_sources: set[MetadataSource] = set() + # Sources this scan asked and never got an answer from. A miss they did not + # rule out is not a coverage gap, so the outcome must not be reported as one. + inconclusive_sources: set[MetadataSource] = set() + def resolve_fetch(source: MetadataSource, result: Any, fallback: Any) -> Any: """Unwrap a gathered lookup, falling back to an empty match when it failed.""" if not isinstance(result, BaseException): @@ -595,6 +599,7 @@ async def scan_rom( # A provider that blew up ruled nothing out, so it no longer counts as # attempted and a complete rescan keeps the id it already had. attempted_sources.discard(source) + inconclusive_sources.add(source) log.error( f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}", extra=LOGGER_MODULE_NAME, @@ -651,9 +656,14 @@ async def scan_rom( ) ) ): - return await meta_hasheous_handler.lookup_rom( + match, conclusive = await meta_hasheous_handler.lookup_rom( platform.slug, get_match_files() ) + # Hasheous swallows its own failures, so an empty match that is not + # conclusive is the only sign the lookup never got an answer. + if not conclusive: + inconclusive_sources.add(MetadataSource.HASHEOUS) + return match, conclusive return ( HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None), @@ -1473,10 +1483,22 @@ async def scan_rom( and not rom_attrs.get("steam_id") and not rom_attrs.get("gamelist_id") ): - log.warning( - f"{hl(rom_attrs['fs_name'])} not identified {emoji.EMOJI_CROSS_MARK}", - extra=LOGGER_MODULE_NAME, - ) + if inconclusive_sources: + # Reporting a plain "not identified" here writes the ROM up as a + # coverage gap the providers confirmed, when one of them simply + # never answered. + silent = ", ".join(hl(source) for source in sorted(inconclusive_sources)) + log.warning( + f"{hl(rom_attrs['fs_name'])} not identified, but {silent} gave " + f"no answer, so this is not a confirmed miss - an UNMATCHED " + f"scan will retry it {emoji.EMOJI_WARNING}", + extra=LOGGER_MODULE_NAME, + ) + else: + log.warning( + f"{hl(rom_attrs['fs_name'])} not identified {emoji.EMOJI_CROSS_MARK}", + extra=LOGGER_MODULE_NAME, + ) return Rom(**rom_attrs) async def fetch_sgdb_details(playmatch_rom: PlaymatchRomMatch) -> SGDBRom: diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index 91b25fd3e..9c371cc72 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -1,3 +1,5 @@ +import logging +from contextlib import contextmanager from unittest.mock import AsyncMock, patch import pytest @@ -941,6 +943,104 @@ async def test_scan_rom_hashes_keeps_match_when_hasheous_unreachable( assert result.hasheous_metadata == {"nointro_match": True, "ra_match": True} +@contextmanager +def _capture_romm_logs(caplog): + """The "romm" logger has propagate=False, so caplog's handler has to be + attached to it directly rather than to the root.""" + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with caplog.at_level(logging.WARNING, logger="romm"): + yield + finally: + romm_logger.removeHandler(caplog.handler) + + +async def _scan_unmatched_rom(platform: Platform) -> Rom: + """Scan a rom nothing identifies, so the outcome is the miss branch.""" + rom = db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + fs_name="Nothing Knows This (USA).7z", + fs_name_no_tags="Nothing Knows This", + fs_name_no_ext="Nothing Knows This (USA)", + fs_extension="7z", + fs_path="n64/Nothing Knows This (USA)", + fs_size_bytes=1024, + tags=[], + ) + ) + return await scan_rom( + platform=platform, + scan_type=ScanType.UNMATCHED, + rom=rom, + fs_rom={ + "fs_name": rom.fs_name, + "fs_path": rom.fs_path, + "flat": True, + "files": [], + "crc_hash": "crc", + "md5_hash": "md5", + "sha1_hash": "sha1", + "ra_hash": "", + }, + metadata_sources=[MetadataSource.HASHEOUS], + newly_added=False, + ) + + +@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_says_an_unanswered_miss_is_not_confirmed( + mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled, caplog +): + """A provider that never answered has ruled nothing out, so the outcome + must not read as a coverage gap the provider confirmed.""" + no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + 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", hasheous_id=64) + ) + + async with initialize_context(): + with _capture_romm_logs(caplog): + result = await _scan_unmatched_rom(platform) + + assert result.hasheous_id is None + assert "not a confirmed miss" in caplog.text + assert "hasheous" in caplog.text + + +@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_still_reports_a_confirmed_miss_plainly( + mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled, caplog +): + """Hasheous answering "I don't know these hashes" is a real coverage gap.""" + no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + 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", hasheous_id=64) + ) + + async with initialize_context(): + with _capture_romm_logs(caplog): + await _scan_unmatched_rom(platform) + + assert "not identified" in caplog.text + assert "gave no answer" not in caplog.text + + 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.""" From d6eba3297a8a88d0a42a656392ca2a62ae17f3de Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 16 Sep 2026 18:38:47 -0400 Subject: [PATCH 2/2] fix(scan): treat every silent provider as inconclusive ScreenScraper catches its own rate limit and breaker, so the miss they cause never reaches resolve_fetch and was still written up as confirmed. Hasheous had the opposite gap: an unanswered hash lookup still counted as attempted, so a complete rescan cleared the id the lookup could not redo, and a disabled handler reports the same flag as an outage without ever having been consulted. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/scan_handler.py | 26 ++++-- backend/tests/handler/test_fastapi.py | 84 +++++++++++++++++-- .../handler/test_scan_complete_rescan_ids.py | 46 +++++++++- 3 files changed, 140 insertions(+), 16 deletions(-) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 8b53100fe..54ff4094a 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -589,6 +589,13 @@ async def scan_rom( # rule out is not a coverage gap, so the outcome must not be reported as one. inconclusive_sources: set[MetadataSource] = set() + def note_inconclusive(source: MetadataSource) -> None: + """Record a source that was consulted and never answered.""" + # It ruled nothing out, so it stops counting as attempted too and a + # complete rescan keeps the id it already had. + attempted_sources.discard(source) + inconclusive_sources.add(source) + def resolve_fetch(source: MetadataSource, result: Any, fallback: Any) -> Any: """Unwrap a gathered lookup, falling back to an empty match when it failed.""" if not isinstance(result, BaseException): @@ -596,10 +603,7 @@ async def scan_rom( if not isinstance(result, Exception): raise result - # A provider that blew up ruled nothing out, so it no longer counts as - # attempted and a complete rescan keeps the id it already had. - attempted_sources.discard(source) - inconclusive_sources.add(source) + note_inconclusive(source) log.error( f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}", extra=LOGGER_MODULE_NAME, @@ -660,9 +664,10 @@ async def scan_rom( platform.slug, get_match_files() ) # Hasheous swallows its own failures, so an empty match that is not - # conclusive is the only sign the lookup never got an answer. - if not conclusive: - inconclusive_sources.add(MetadataSource.HASHEOUS) + # conclusive is the only sign the lookup never got an answer. A + # disabled handler reports the same flag without being consulted. + if not conclusive and meta_hasheous_handler.is_enabled(): + note_inconclusive(MetadataSource.HASHEOUS) return match, conclusive return ( @@ -1012,7 +1017,7 @@ async def scan_rom( return SSRom(ss_id=None) finally: if short_circuited: - attempted_sources.discard(MetadataSource.SS) + note_inconclusive(MetadataSource.SS) return SSRom(ss_id=None) @@ -1101,7 +1106,10 @@ async def scan_rom( ) ) ): - attempted_sources.add(MetadataSource.HASHEOUS) + # The hash lookup is the only thing that identifies a rom here, so one + # that never answered leaves a complete rescan nothing to redo. + if MetadataSource.HASHEOUS not in inconclusive_sources: + attempted_sources.add(MetadataSource.HASHEOUS) ( igdb_game, ra_game, diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index 9c371cc72..6b6732680 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -1,4 +1,5 @@ import logging +import re from contextlib import contextmanager from unittest.mock import AsyncMock, patch @@ -33,6 +34,7 @@ from handler.scan_handler import ( scan_platform, scan_rom, ) +from logger.formatter import strip_ansi from models.platform import Platform from models.rom import Rom, RomFile, RomIdentity, SaveTargetLayout from utils.context import initialize_context @@ -956,7 +958,13 @@ def _capture_romm_logs(caplog): romm_logger.removeHandler(caplog.handler) -async def _scan_unmatched_rom(platform: Platform) -> Rom: +def _silent_sources(log_text: str) -> list[str]: + """The sources the miss outcome named as unanswered, stripped of color codes.""" + match = re.search(r"not identified, but (.+?) gave no answer", strip_ansi(log_text)) + return match.group(1).split(", ") if match else [] + + +async def _scan_unmatched_rom(platform: Platform, metadata_sources: list[str]) -> Rom: """Scan a rom nothing identifies, so the outcome is the miss branch.""" rom = db_rom_handler.add_rom( Rom( @@ -984,17 +992,23 @@ async def _scan_unmatched_rom(platform: Platform) -> Rom: "sha1_hash": "sha1", "ra_hash": "", }, - metadata_sources=[MetadataSource.HASHEOUS], + metadata_sources=metadata_sources, newly_added=False, ) @patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_hasheous_handler, "is_enabled", return_value=True) @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_says_an_unanswered_miss_is_not_confirmed( - mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled, caplog + mock_lookup, + mock_get_igdb, + mock_get_ra, + mock_hasheous_enabled, + mock_playmatch_enabled, + caplog, ): """A provider that never answered has ruled nothing out, so the outcome must not read as a coverage gap the provider confirmed.""" @@ -1009,11 +1023,11 @@ async def test_scan_rom_says_an_unanswered_miss_is_not_confirmed( async with initialize_context(): with _capture_romm_logs(caplog): - result = await _scan_unmatched_rom(platform) + result = await _scan_unmatched_rom(platform, [MetadataSource.HASHEOUS]) assert result.hasheous_id is None assert "not a confirmed miss" in caplog.text - assert "hasheous" in caplog.text + assert "hasheous" in _silent_sources(caplog.text) @patch.object(meta_playmatch_handler, "is_enabled", return_value=False) @@ -1035,12 +1049,70 @@ async def test_scan_rom_still_reports_a_confirmed_miss_plainly( async with initialize_context(): with _capture_romm_logs(caplog): - await _scan_unmatched_rom(platform) + await _scan_unmatched_rom(platform, [MetadataSource.HASHEOUS]) assert "not identified" in caplog.text assert "gave no answer" not in caplog.text +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_hasheous_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_does_not_blame_a_disabled_hasheous( + mock_lookup, + mock_get_igdb, + mock_get_ra, + mock_hasheous_enabled, + mock_playmatch_enabled, + caplog, +): + """A disabled Hasheous reports the same flag as an outage, but it was never + consulted, so the miss is not waiting on it.""" + no_match = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) + 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", hasheous_id=64) + ) + + async with initialize_context(): + with _capture_romm_logs(caplog): + await _scan_unmatched_rom(platform, [MetadataSource.HASHEOUS]) + + assert "not a confirmed miss" not in caplog.text + assert "not identified" in caplog.text + + +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_ss_handler, "get_rom", new_callable=AsyncMock) +@patch.object(meta_ss_handler, "lookup_rom", new_callable=AsyncMock) +async def test_scan_rom_says_a_screenscraper_outage_is_not_confirmed( + mock_ss_lookup, mock_ss_get_rom, mock_playmatch_enabled, caplog +): + """ScreenScraper catches its own rate limit and breaker, so the outcome sees + an empty match rather than the exception the generic path reports.""" + reset_rate_limited_roms() + mock_ss_lookup.side_effect = ScreenScraperRateLimitError() + + platform = db_platform_handler.add_platform( + Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64", ss_id=4) + ) + + async with initialize_context(): + with _capture_romm_logs(caplog): + await _scan_unmatched_rom(platform, [MetadataSource.SS]) + + mock_ss_get_rom.assert_not_awaited() + assert "not a confirmed miss" in caplog.text + assert "ss" in _silent_sources(caplog.text) + + reset_rate_limited_roms() + + 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.""" diff --git a/backend/tests/handler/test_scan_complete_rescan_ids.py b/backend/tests/handler/test_scan_complete_rescan_ids.py index ba14b6664..dc21652e1 100644 --- a/backend/tests/handler/test_scan_complete_rescan_ids.py +++ b/backend/tests/handler/test_scan_complete_rescan_ids.py @@ -12,6 +12,7 @@ from fastapi import HTTPException from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan from handler.database import db_rom_handler +from handler.metadata.hasheous_handler import HasheousRom from handler.metadata.igdb_handler import IGDBRom from handler.metadata.pouet_handler import PouetRom from handler.metadata.sgdb_handler import SGDBRom @@ -25,6 +26,7 @@ STALE_MOBY_ID = 42 STALE_SGDB_ID = 777 STALE_POUET_ID = 106640 STALE_SS_ID = 314 +STALE_HASHEOUS_ID = 2718 MISS = IGDBRom(igdb_id=None) SGDB_MISS = SGDBRom(sgdb_id=None) @@ -33,6 +35,7 @@ MATCH = IGDBRom(igdb_id=9999, name="A Real Game") UNREACHABLE = HTTPException(status_code=503, detail="provider is down") SS_MISS = SSRom(ss_id=None) SS_SHORT_CIRCUITED = ScreenScraperExhaustedError(SS_MISS) +HASHEOUS_MISS = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None) def _lookup(result: Any) -> AsyncMock: @@ -52,9 +55,13 @@ async def _rescan( platform_igdb_id: int | None = 4, ss_lookup_result: tuple[SSRom, bool] | Exception = (SS_MISS, False), ss_get_rom_result: SSRom | Exception = SS_MISS, + platform_hasheous_id: int | None = None, + hasheous_lookup_result: tuple[HasheousRom, bool] = (HASHEOUS_MISS, True), ) -> Rom: """Rescan a ROM carrying hand-set IDs, and persist the result.""" - platform = add_n64_platform(igdb_id=platform_igdb_id, ss_id=14) + platform = add_n64_platform( + igdb_id=platform_igdb_id, ss_id=14, hasheous_id=platform_hasheous_id + ) rom = add_rom( platform, FS_NAME, @@ -66,6 +73,7 @@ async def _rescan( sgdb_id=STALE_SGDB_ID, pouet_id=STALE_POUET_ID, ss_id=STALE_SS_ID, + hasheous_id=STALE_HASHEOUS_ID, ) igdb_mock = _lookup(igdb_result) @@ -87,6 +95,21 @@ async def _rescan( "handler.scan_handler.meta_ss_handler.get_rom", new=_lookup(ss_get_rom_result), ), + patch( + "handler.scan_handler.meta_hasheous_handler.is_enabled", return_value=True + ), + patch( + "handler.scan_handler.meta_hasheous_handler.lookup_rom", + new=_lookup(hasheous_lookup_result), + ), + patch( + "handler.scan_handler.meta_hasheous_handler.get_igdb_game", + new=_lookup(HASHEOUS_MISS), + ), + patch( + "handler.scan_handler.meta_hasheous_handler.get_ra_game", + new=_lookup(HASHEOUS_MISS), + ), ): scanned = await run_scan( platform, rom, scan_type=scan_type, metadata_sources=sources @@ -155,6 +178,27 @@ async def test_a_screenscraper_breaker_that_recovers_mid_rom_keeps_its_id(): assert saved.ss_id == STALE_SS_ID +async def test_a_hasheous_lookup_that_never_answered_keeps_its_id(): + """Hasheous swallows its own failures, so the conclusive flag is all a rescan + has to tell an outage from a miss it confirmed.""" + saved = await _rescan( + [MetadataSource.IGDB, MetadataSource.HASHEOUS], + platform_hasheous_id=64, + hasheous_lookup_result=(HASHEOUS_MISS, False), + ) + + assert saved.hasheous_id == STALE_HASHEOUS_ID + + +async def test_a_hasheous_miss_it_confirmed_still_drops_its_id(): + saved = await _rescan( + [MetadataSource.IGDB, MetadataSource.HASHEOUS], + platform_hasheous_id=64, + ) + + assert saved.hasheous_id is None + + async def test_a_selected_screenscraper_that_misses_still_drops_its_id(): saved = await _rescan([MetadataSource.IGDB, MetadataSource.SS])