Merge pull request #4534 from rommapp/claude/fix-4398-inconclusive-scan

fix(scan): don't report an unanswered lookup as a confirmed miss
This commit is contained in:
Georges-Antoine Assi
2026-09-16 19:05:45 -04:00
committed by GitHub
3 changed files with 257 additions and 11 deletions

View File

@@ -584,6 +584,17 @@ 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 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):
@@ -591,9 +602,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)
note_inconclusive(source)
log.error(
f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}",
extra=LOGGER_MODULE_NAME,
@@ -650,9 +659,15 @@ 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. 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 (
HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None),
@@ -1001,7 +1016,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)
@@ -1090,7 +1105,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,
@@ -1472,10 +1490,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:

View File

@@ -1,3 +1,6 @@
import logging
import re
from contextlib import contextmanager
from unittest.mock import AsyncMock, patch
import pytest
@@ -31,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
@@ -941,6 +945,174 @@ 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)
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(
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=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_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."""
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, [MetadataSource.HASHEOUS])
assert result.hasheous_id is None
assert "not a confirmed miss" in caplog.text
assert "hasheous" in _silent_sources(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, [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."""

View File

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