fix(ra): count RomM's own RA hash match as RetroAchievements verification (#4816)

* fix(ra): count RomM's own RA hash match as RetroAchievements verification

The RetroAchievements verification chip, the header Verified badge and the
library verified filter only read Hasheous' `ra_match` flag. RetroAchievements
hashes only part of some ROMs (NDS, PSP), so Hasheous never flags those from
their file hashes, and a ROM RomM matched to its RA game by RA hash still
showed a grey chip.

The RA handler now records `hash_match` in `ra_metadata` whenever the ROM's
RA hash is one RetroAchievements lists for the matched game, whichever route
found the game (hash lookup, Hasheous-supplied id, filename tag, update scan
or a manual edit). The frontend verification helper and the backend verified
filter count it alongside Hasheous' flag. Existing ROMs pick it up on their
next scan.

Fixes #4801

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* style: satisfy trunk isort and no-emdash-in-comment

Sort imports with the repo's .isort.cfg and replace the comment em-dashes
in MetadataTab.vue that trunk flags once the file is modified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): address code-review findings on the RA hash match

- A HASHES rescan whose RA lookup ran and found nothing clears
  `hash_match`, mirroring the Hasheous guard; a lookup that errored keeps it.
- A manual RA id change that can't be resolved no longer keeps the previous
  game's `hash_match`.
- `_search_rom` no longer caches a failed hash-list download ({}) as an
  empty index for the whole refresh window.
- Update the `verified` filter description and trim the romVerification
  header comment.

Step: pr-ready code-review (xhigh --fix)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): don't let a failed hash check block an RA ID lookup

`get_rom_by_id` now treats the hash-list check as secondary: on failure it
logs, keeps a match already recorded for the same game, and still returns
the game. A failed hash-list download raises "RetroAchievements
unavailable" instead of reading as "no match", so scans treat RA as
inconclusive and keep the stored flag.

Addresses the Copilot and Greptile review findings on ra_handler.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* refactor(ra): simplify the RA hash-match verification

- Cache the parsed RA hash index per platform, keyed by the cache file's
  mtime, so a scan parses it once instead of once per ROM.
- Check the hash only after `get_rom_by_id` has resolved the game.
- Give each frontend verification database its own `matches(rom)`, which
  drops the `ra_match` special case in the shared helper along with
  `matchesDatabase` and `VERIFICATION_KEYS`.

Step: pr-ready simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* style(v2): polish romVerification naming and comment

Rename the Hasheous matcher factory to `anyHasheousFlag` and trim the
VERIFICATION_DATABASES comment to two lines.

Step: pr-ready review-polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): keep a recorded hash match only for the same RA hash

When the hash-list check fails, `get_rom_by_id` now keeps a stored
`hash_match` only if both the game and the ROM's RA hash are unchanged, so
a rehashed ROM isn't left verified by a hash nobody checked. The
romVerification tests build on the shared typed `SimpleRom` fixture
instead of casting a bare object.

Addresses the Greptile review findings on ra_handler.py and
romVerification.test.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Dornan
2026-09-26 16:33:55 -04:00
committed by GitHub
parent 5b3d0bf544
commit cbfc904a48
14 changed files with 551 additions and 115 deletions

View File

@@ -1984,9 +1984,14 @@ async def update_rom(
cleaned_data.update({"launchbox_id": None, "launchbox_metadata": {}})
if cleaned_data["ra_id"] and int(cleaned_data["ra_id"]) != rom.ra_id:
ra_rom = await meta_ra_handler.get_rom_by_id(rom, ra_id=cleaned_data["ra_id"])
ra_rom = await meta_ra_handler.get_rom_by_id(
rom, ra_id=cleaned_data["ra_id"], ra_hash=rom.ra_hash
)
if ra_rom.get("ra_id"):
cleaned_data.update(ra_rom)
elif rom.ra_metadata and rom.ra_metadata.get("hash_match"):
# The kept blob's hash match was earned against the previous game.
cleaned_data["ra_metadata"] = {**rom.ra_metadata, "hash_match": False}
elif rom.ra_id and not cleaned_data["ra_id"]:
cleaned_data.update({"ra_id": None, "ra_metadata": {}})

View File

@@ -186,7 +186,9 @@ class RomFilterParams(BaseModel):
] = None
verified: Annotated[
bool | None,
Field(description="Whether the rom is verified by Hasheous."),
Field(
description="Whether the rom's hash matched a known database, via Hasheous or RetroAchievements."
),
] = None
has_soundtrack: Annotated[
bool | None,

View File

@@ -1280,7 +1280,8 @@ class DBRomsHandler(DBBaseHandler):
*(
func.coalesce(Rom.hasheous_metadata[key].as_boolean(), false())
for key in keys_to_check
)
),
func.coalesce(Rom.ra_metadata["hash_match"].as_boolean(), false()),
)
if not value:
predicate = not_(predicate)

View File

@@ -21,7 +21,7 @@ from logger.logger import log
from models.rom import Rom
from utils.platform_slugs import UniversalPlatformSlug as UPS
from .base_handler import BaseRom, MetadataHandler
from .base_handler import BaseRom, MetadataHandler, unavailable
# Regex to detect RetroAchievements ID tags in filenames like (ra-12345)
RA_TAG_REGEX = re.compile(r"\(ra-(\d+)\)", re.IGNORECASE)
@@ -56,6 +56,8 @@ class RAMetadata(TypedDict):
publishers: list[str]
developers: list[str]
achievements: list[RAGameRomAchievement]
# The ROM's RA hash is one RetroAchievements lists for this game.
hash_match: NotRequired[bool]
class RAGameRom(BaseRom):
@@ -85,7 +87,7 @@ class RAUserProgression(TypedDict):
def extract_metadata_from_rom_details(
rom: Rom, rom_details: RAGameExtendedDetails
rom: Rom, rom_details: RAGameExtendedDetails, hash_match: bool
) -> RAMetadata:
def parse_release_timestamp() -> int | None:
release_date_str = rom_details.get("Released")
@@ -127,6 +129,7 @@ def extract_metadata_from_rom_details(
)
for achievement in rom_details.get("Achievements", {}).values()
],
hash_match=hash_match,
)
@@ -134,6 +137,8 @@ class RAHandler(MetadataHandler):
def __init__(self) -> None:
self.ra_service = RetroAchievementsService()
self.HASHES_FILE_NAME = "ra_hashes_v3.json"
# Parsed hash index per platform id, with the cache file mtime it came from.
self._hash_indexes: dict[int, tuple[float, dict[str, int]]] = {}
@classmethod
def is_enabled(cls) -> bool:
@@ -196,6 +201,10 @@ class RAHandler(MetadataHandler):
only_games_with_achievements=True,
include_hashes=True,
)
# A failed request comes back as {}, which must not be cached as an
# empty index for the whole refresh window.
if not isinstance(roms, list):
raise unavailable("RetroAchievements")
hash_index = {h.lower(): r["ID"] for r in roms for h in r.get("Hashes", ())}
@@ -210,14 +219,34 @@ class RAHandler(MetadataHandler):
self.HASHES_FILE_NAME,
)
else:
# Read the hash index from the JSON file
json_file_bytes = await fs_resource_handler.read_file(
self._get_hashes_file_path(rom.platform.id)
)
hash_index = json.loads(json_file_bytes.decode("utf-8"))
file_path = self._get_hashes_file_path(rom.platform.id)
full_path = fs_resource_handler.validate_path(file_path)
mtime = (await AnyioPath(str(full_path)).stat()).st_mtime
cached = self._hash_indexes.get(rom.platform.id)
if cached and cached[0] == mtime:
hash_index = cached[1]
else:
json_file_bytes = await fs_resource_handler.read_file(file_path)
hash_index = json.loads(json_file_bytes.decode("utf-8"))
self._hash_indexes[rom.platform.id] = (mtime, hash_index)
return hash_index.get(ra_hash.lower())
async def _hash_matches(self, rom: Rom, ra_hash: str | None, ra_id: int) -> bool:
if not ra_hash:
return False
try:
return await self._search_rom(rom, ra_hash) == ra_id
except Exception as exc:
# A failed check must not block the ID lookup, nor drop a match
# already recorded for this game and hash.
log.warning(f"Couldn't check the RetroAchievements hash list: {exc}")
return (
rom.ra_id == ra_id
and rom.ra_hash == ra_hash
and bool((rom.ra_metadata or {}).get("hash_match"))
)
def get_platform(self, slug: str) -> RAGamesPlatform:
if slug not in RA_PLATFORM_LIST:
return RAGamesPlatform(ra_id=None, slug=slug)
@@ -238,7 +267,9 @@ class RAHandler(MetadataHandler):
ra_id_from_tag = self.extract_ra_id_from_filename(rom.fs_name)
if ra_id_from_tag:
log.debug(f"Found RetroAchievements ID tag in filename: {ra_id_from_tag}")
rom_by_id = await self.get_rom_by_id(rom=rom, ra_id=ra_id_from_tag)
rom_by_id = await self.get_rom_by_id(
rom=rom, ra_id=ra_id_from_tag, ra_hash=ra_hash
)
if rom_by_id["ra_id"]:
log.debug(
f"Successfully matched ROM by RetroAchievements ID tag: {rom.fs_name} -> {ra_id_from_tag}"
@@ -277,19 +308,25 @@ class RAHandler(MetadataHandler):
)
]
),
ra_metadata=extract_metadata_from_rom_details(rom, rom_details),
ra_metadata=extract_metadata_from_rom_details(
rom, rom_details, hash_match=True
),
)
except KeyError:
return RAGameRom(ra_id=None)
async def get_rom_by_id(self, rom: Rom, ra_id: int) -> RAGameRom:
async def get_rom_by_id(
self, rom: Rom, ra_id: int, ra_hash: str | None = None
) -> RAGameRom:
if not ra_id:
return RAGameRom(ra_id=None)
try:
rom_details = await self.ra_service.get_game_extended_details(ra_id)
game_id = rom_details["ID"]
hash_match = await self._hash_matches(rom, ra_hash, ra_id)
return RAGameRom(
ra_id=rom_details["ID"],
ra_id=game_id,
name=rom_details.get("Title", ""),
url_cover=(
f"https://media.retroachievements.org{rom_details['ImageTitle']}"
@@ -305,7 +342,9 @@ class RAHandler(MetadataHandler):
)
]
),
ra_metadata=extract_metadata_from_rom_details(rom, rom_details),
ra_metadata=extract_metadata_from_rom_details(
rom, rom_details, hash_match=hash_match
),
)
except KeyError:
return RAGameRom(ra_id=None)

View File

@@ -1136,12 +1136,16 @@ async def scan_rom(
f"{hl(str(h_ra_id), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
extra=LOGGER_MODULE_NAME,
)
return await meta_ra_handler.get_rom_by_id(rom=rom, ra_id=h_ra_id)
return await meta_ra_handler.get_rom_by_id(
rom=rom, ra_id=h_ra_id, ra_hash=rom_attrs["ra_hash"]
)
if (scan_type == ScanType.UPDATE and rom.ra_id) or (
scan_type == ScanType.UNMATCHED and rom.ra_id and not rom.ra_metadata
):
return await meta_ra_handler.get_rom_by_id(rom=rom, ra_id=rom.ra_id)
return await meta_ra_handler.get_rom_by_id(
rom=rom, ra_id=rom.ra_id, ra_hash=rom_attrs["ra_hash"]
)
else:
return await meta_ra_handler.get_rom(
rom=rom, ra_hash=rom_attrs["ra_hash"]
@@ -1466,6 +1470,16 @@ async def scan_rom(
rom_attrs["hasheous_id"] = None
rom_attrs["hasheous_metadata"] = {}
# Same for the RA hash match, once an RA lookup that ran found nothing.
ra_metadata = rom_attrs.get("ra_metadata") or {}
if (
scan_type == ScanType.HASHES
and MetadataSource.RA in attempted_sources
and not ra_handler_rom.get("ra_id")
and ra_metadata.get("hash_match")
):
rom_attrs["ra_metadata"] = {**ra_metadata, "hash_match": False}
# A skipped source's tags can't be told apart on the row, so each hash source
# keeps the ones its dump gave in its own blob.
for source_name in HASH_MATCHED_TAG_SOURCES:

View File

@@ -1730,6 +1730,31 @@ class TestUpdateMetadataIDs:
assert body["ra_id"] == MOCK_RA_ID
assert get_rom_by_id_mock.called
@patch.object(RAHandler, "get_rom_by_id", return_value=RAGameRom(ra_id=None))
def test_update_rom_ra_id_drops_the_previous_games_hash_match(
self,
get_rom_by_id_mock: AsyncMock,
client: TestClient,
access_token: str,
rom: Rom,
):
"""A relink RA can't resolve keeps the old blob, but not its verification."""
db_rom_handler.update_rom(
rom.id,
{"ra_id": 1, "ra_metadata": {"achievements": [], "hash_match": True}},
)
response = client.put(
f"/api/roms/{rom.id}",
headers={"Authorization": f"Bearer {access_token}"},
data={"ra_id": str(MOCK_RA_ID)},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["ra_id"] == MOCK_RA_ID
assert body["merged_ra_metadata"]["hash_match"] is False
@patch.object(
LaunchboxHandler,
"get_rom_by_id",

View File

@@ -1,4 +1,4 @@
"""The `verified` filter over the Hasheous signature-match flags.
"""The `verified` filter over the Hasheous signature-match flags and RA hash match.
`hasheous_metadata` is a JSON blob whose keys grow as RomM maps more of
Hasheous' signature sources (`mame_redump_match` was the latest addition), so
@@ -34,7 +34,13 @@ LEGACY_KEYS = [
]
def _add_rom(platform: Platform, user: User, name: str, metadata: dict) -> Rom:
def _add_rom(
platform: Platform,
user: User,
name: str,
metadata: dict,
ra_metadata: dict | None = None,
) -> Rom:
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
@@ -46,6 +52,7 @@ def _add_rom(platform: Platform, user: User, name: str, metadata: dict) -> Rom:
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
hasheous_metadata=metadata,
ra_metadata=ra_metadata,
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=user.id)
@@ -84,6 +91,30 @@ def chd_verified_rom(platform: Platform, admin_user: User) -> Rom:
)
@pytest.fixture
def ra_hash_verified_rom(platform: Platform, admin_user: User) -> Rom:
"""Hasheous flagged nothing, but the ROM's RA hash is in RA's list."""
return _add_rom(
platform,
admin_user,
"ra_hash_verified",
{key: False for key in LEGACY_KEYS},
ra_metadata={"achievements": [], "hash_match": True},
)
@pytest.fixture
def ra_id_only_rom(platform: Platform, admin_user: User) -> Rom:
"""Linked to an RA game whose hash list doesn't carry this ROM's RA hash."""
return _add_rom(
platform,
admin_user,
"ra_id_only",
{key: False for key in LEGACY_KEYS},
ra_metadata={"achievements": [], "hash_match": False},
)
class TestVerifiedFilter:
def test_unverified_keeps_roms_missing_the_newest_key(
self,
@@ -116,6 +147,20 @@ class TestVerifiedFilter:
assert [r.id for r in roms] == [rom.id]
def test_verified_includes_an_ra_hash_match(
self,
admin_user: User,
ra_hash_verified_rom: Rom,
ra_id_only_rom: Rom,
):
verified = db_rom_handler.get_roms_scalar(user_id=admin_user.id, verified=True)
unverified = db_rom_handler.get_roms_scalar(
user_id=admin_user.id, verified=False
)
assert [r.id for r in verified] == [ra_hash_verified_rom.id]
assert [r.id for r in unverified] == [ra_id_only_rom.id]
class TestVerifiedPostgresPredicate:
@pytest.mark.parametrize("verified", [True, False])
@@ -132,3 +177,6 @@ class TestVerifiedPostgresPredicate:
f"coalesce(CAST((roms.hasheous_metadata ->> '{key}') AS BOOLEAN), "
"false)"
) in sql
assert (
"coalesce(CAST((roms.ra_metadata ->> 'hash_match') AS BOOLEAN), false)"
) in sql

View File

@@ -1,12 +1,14 @@
"""Tests for the RetroAchievements metadata handler."""
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import cast
from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi import HTTPException
from tests.handler.metadata.conftest import local_timezone
from adapters.services.retroachievements_types import RAGameExtendedDetails
@@ -36,7 +38,9 @@ def test_release_date_is_utc_midnight_whatever_the_host_timezone():
# CI runs in UTC, so a naive timestamp only shows its drift under another zone.
details = cast(RAGameExtendedDetails, {"Released": "1991-08-23 00:00:00"})
with local_timezone("Asia/Tokyo"):
metadata = ra_handler.extract_metadata_from_rom_details(MagicMock(), details)
metadata = ra_handler.extract_metadata_from_rom_details(
MagicMock(), details, hash_match=False
)
expected = datetime(1991, 8, 23, tzinfo=timezone.utc).timestamp()
assert metadata["first_release_date"] == int(expected)
@@ -123,6 +127,24 @@ class TestSearchRom:
assert ra_id == 10210
get_game_list.assert_not_awaited()
async def test_parses_the_cached_index_once_until_it_changes(
self, handler: RAHandler, monkeypatch: pytest.MonkeyPatch, resources_dir: Path
):
cache_file = resources_dir / handler.HASHES_FILE_NAME
cache_file.write_bytes(json.dumps({"abcdef": 10210}).encode("utf-8"))
read_file = ra_handler.fs_resource_handler.read_file
assert await handler._search_rom(self._make_rom(), "abcdef") == 10210
assert await handler._search_rom(self._make_rom(), "abcdef") == 10210
assert read_file.await_count == 1 # type: ignore[attr-defined]
cache_file.write_bytes(json.dumps({"abcdef": 10211}).encode("utf-8"))
stat = cache_file.stat()
os.utime(cache_file, (stat.st_atime, stat.st_mtime + 1))
assert await handler._search_rom(self._make_rom(), "abcdef") == 10211
assert read_file.await_count == 2 # type: ignore[attr-defined]
async def test_ignores_an_unfiltered_index_from_an_older_version(
self, handler: RAHandler, monkeypatch: pytest.MonkeyPatch, resources_dir: Path
):
@@ -138,8 +160,120 @@ class TestSearchRom:
get_game_list.assert_awaited_once()
assert ra_id == 10210
async def test_does_not_cache_a_failed_download(
self, handler: RAHandler, monkeypatch: pytest.MonkeyPatch, resources_dir: Path
):
"""The service answers a failed request with {}, not a game list."""
monkeypatch.setattr(
handler.ra_service, "get_game_list", AsyncMock(return_value={})
)
with pytest.raises(HTTPException):
await handler._search_rom(self._make_rom(), "abcdef")
assert not (resources_dir / handler.HASHES_FILE_NAME).exists()
async def test_returns_none_without_a_platform_ra_id(self, handler: RAHandler):
rom = self._make_rom()
rom.platform.ra_id = None
assert await handler._search_rom(rom, "abcdef") is None
class TestHashMatch:
"""`hash_match` says whether RA lists the ROM's RA hash for the matched game."""
GAME_DETAILS = {"ID": 17353, "Title": "Game", "Achievements": {}}
@pytest.fixture
def rom(self) -> MagicMock:
rom = MagicMock()
rom.fs_name = "game.nds"
rom.platform.id = 1
rom.platform.ra_id = 18
return rom
@pytest.fixture(autouse=True)
def _stub_service(self, handler: RAHandler, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
handler.ra_service,
"get_game_extended_details",
AsyncMock(return_value=self.GAME_DETAILS),
)
monkeypatch.setattr(
handler,
"_search_rom",
AsyncMock(side_effect=lambda _rom, ra_hash: {"abcdef": 17353}.get(ra_hash)),
)
async def test_a_hash_lookup_match_is_a_hash_match(
self, handler: RAHandler, rom: MagicMock
):
result = await handler.get_rom(rom, ra_hash="abcdef")
assert result["ra_id"] == 17353
assert result["ra_metadata"]["hash_match"] is True
async def test_an_id_match_whose_hash_ra_lists_is_a_hash_match(
self, handler: RAHandler, rom: MagicMock
):
"""A Hasheous-supplied RA id still counts when RA lists the ROM's hash."""
result = await handler.get_rom_by_id(rom, ra_id=17353, ra_hash="abcdef")
assert result["ra_metadata"]["hash_match"] is True
@pytest.mark.parametrize("ra_hash", [None, "", "ffffff"])
async def test_an_id_match_without_a_listed_hash_is_not(
self, handler: RAHandler, rom: MagicMock, ra_hash: str | None
):
result = await handler.get_rom_by_id(rom, ra_id=17353, ra_hash=ra_hash)
assert result["ra_id"] == 17353
assert result["ra_metadata"]["hash_match"] is False
async def test_a_hash_listed_for_another_game_is_not(
self, handler: RAHandler, rom: MagicMock
):
result = await handler.get_rom_by_id(rom, ra_id=1, ra_hash="abcdef")
assert result["ra_metadata"]["hash_match"] is False
async def test_a_failed_hash_check_still_returns_the_game(
self, handler: RAHandler, rom: MagicMock, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(
handler, "_search_rom", AsyncMock(side_effect=HTTPException(503))
)
rom.ra_id = None
result = await handler.get_rom_by_id(rom, ra_id=17353, ra_hash="abcdef")
assert result["ra_id"] == 17353
assert result["ra_metadata"]["hash_match"] is False
async def test_a_failed_hash_check_keeps_the_recorded_match(
self, handler: RAHandler, rom: MagicMock, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(
handler, "_search_rom", AsyncMock(side_effect=HTTPException(503))
)
rom.ra_id = 17353
rom.ra_hash = "abcdef"
rom.ra_metadata = {"hash_match": True}
result = await handler.get_rom_by_id(rom, ra_id=17353, ra_hash="abcdef")
assert result["ra_metadata"]["hash_match"] is True
async def test_a_failed_hash_check_drops_the_match_for_a_new_hash(
self, handler: RAHandler, rom: MagicMock, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(
handler, "_search_rom", AsyncMock(side_effect=HTTPException(503))
)
rom.ra_id = 17353
rom.ra_hash = "abcdef"
rom.ra_metadata = {"hash_match": True}
result = await handler.get_rom_by_id(rom, ra_id=17353, ra_hash="ffffff")
assert result["ra_metadata"]["hash_match"] is False

View File

@@ -1,7 +1,7 @@
import logging
import re
from contextlib import contextmanager
from unittest.mock import AsyncMock, patch
from unittest.mock import ANY, AsyncMock, patch
import pytest
from fastapi import HTTPException, status
@@ -946,6 +946,142 @@ async def test_scan_rom_hashes_keeps_match_when_hasheous_unreachable(
assert result.hasheous_metadata == {"nointro_match": True, "ra_match": True}
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
@patch.object(meta_ra_handler, "_search_rom", new_callable=AsyncMock)
@patch.object(
meta_ra_handler.ra_service, "get_game_extended_details", new_callable=AsyncMock
)
@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_marks_an_ra_hash_match_hasheous_cannot_see(
mock_lookup,
mock_get_igdb,
mock_get_ra,
mock_ra_details,
mock_ra_search,
mock_playmatch_enabled,
):
"""RA hashes only part of an NDS ROM, so Hasheous never flags `ra_match` for
its file hashes; the scan-time RA hash lookup has to count instead."""
hasheous_match = HasheousRom(
hasheous_id=123,
igdb_id=None,
tgdb_id=None,
ra_id=17353,
hasheous_metadata=HasheousMetadata(nointro_match=True, ra_match=False), # type: ignore[typeddict-item]
)
mock_lookup.return_value = (hasheous_match, True)
mock_get_igdb.return_value = hasheous_match
mock_get_ra.return_value = hasheous_match
mock_ra_details.return_value = {"ID": 17353, "Title": "Game", "Achievements": {}}
mock_ra_search.return_value = 17353
platform = db_platform_handler.add_platform(
Platform(
id=1,
slug="nds",
fs_slug="nds",
name="Nintendo DS",
ra_id=18,
hasheous_id=20,
)
)
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
fs_name="Game (USA).7z",
fs_name_no_tags="Game",
fs_name_no_ext="Game (USA)",
fs_extension="7z",
fs_path="nds",
name="Game",
ra_hash="fedcba9876543210fedcba9876543210",
fs_size_bytes=1024,
tags=[],
)
)
async with initialize_context():
result = await scan_rom(
platform=platform,
scan_type=ScanType.HASHES,
rom=rom,
fs_rom={
"fs_name": rom.fs_name,
"fs_path": rom.fs_path,
"flat": True,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
},
metadata_sources=[MetadataSource.HASHEOUS, MetadataSource.RA],
newly_added=False,
)
mock_ra_search.assert_awaited_once_with(ANY, "fedcba9876543210fedcba9876543210")
assert result.ra_id == 17353
assert (result.hasheous_metadata or {}).get("ra_match") is False
assert (result.ra_metadata or {}).get("hash_match") is True
@pytest.mark.parametrize(
("ra_result", "expected"),
[(RAGameRom(ra_id=None), False), (RuntimeError("RA down"), True)],
)
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
@patch.object(meta_ra_handler, "get_rom", new_callable=AsyncMock)
async def test_scan_rom_hashes_drops_an_ra_hash_match_the_new_hash_lost(
mock_get_rom, mock_playmatch_enabled, ra_result, expected
):
"""Only an RA lookup that answered clears the flag; a failed one keeps it."""
mock_get_rom.side_effect = [ra_result]
platform = db_platform_handler.add_platform(
Platform(id=1, slug="nds", fs_slug="nds", name="Nintendo DS", ra_id=18)
)
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
fs_name="Game (USA).nds",
fs_name_no_tags="Game",
fs_name_no_ext="Game (USA)",
fs_extension="nds",
fs_path="nds",
name="Game",
ra_id=17353,
ra_hash="fedcba9876543210fedcba9876543210",
ra_metadata={"achievements": [], "hash_match": True},
fs_size_bytes=1024,
tags=[],
)
)
async with initialize_context():
result = await scan_rom(
platform=platform,
scan_type=ScanType.HASHES,
rom=rom,
fs_rom={
"fs_name": rom.fs_name,
"fs_path": rom.fs_path,
"flat": True,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
},
metadata_sources=[MetadataSource.RA],
newly_added=False,
)
assert result.ra_id == 17353
assert (result.ra_metadata or {}).get("hash_match") is expected
@contextmanager
def _capture_romm_logs(caplog):
"""The "romm" logger has propagate=False, so caplog's handler has to be

View File

@@ -10,5 +10,6 @@ export type RomRAMetadata = {
publishers?: Array<string>;
developers?: Array<string>;
achievements?: Array<RAGameRomAchievement>;
hash_match?: boolean;
};

View File

@@ -51,3 +51,31 @@ describe("MetadataTab hash rows", () => {
expect(hashLabels(chd)).toEqual(["SHA-1", "CHD SHA-1", "MD5", "CRC", "RA"]);
});
});
describe("MetadataTab verification chips", () => {
function raChipTone(r: DetailedRom) {
return shallowMount(MetadataTab, { props: { rom: r } })
.findAllComponents({ name: "RTag" })
.find((c) => c.props("text") === "RetroAchievements")
?.props("tone");
}
it("lights RetroAchievements for a scan-time RA hash match", () => {
const matched = rom({
hasheous_metadata: { nointro_match: true, ra_match: false },
merged_ra_metadata: { hash_match: true },
} as Partial<DetailedRom>);
expect(raChipTone(matched)).toBe("success");
});
it("leaves RetroAchievements neutral without any RA hash match", () => {
const linkedOnly = rom({
ra_id: 17353,
hasheous_metadata: { ra_match: false },
merged_ra_metadata: { hash_match: false },
} as Partial<DetailedRom>);
expect(raChipTone(linkedOnly)).toBe("neutral");
});
});

View File

@@ -1,12 +1,12 @@
<script setup lang="ts">
// MetadataTab — four sections, top to bottom:
// 1. File info — name, size, and the platform-native ids when present.
// 2. Hashes — SHA-1, MD5, CRC, RA, all mono. RTag with eyebrow label.
// MetadataTab: four sections, top to bottom:
// 1. File info: name, size, and the platform-native ids when present.
// 2. Hashes: SHA-1, MD5, CRC, RA, all mono. RTag with eyebrow label.
// Same order as the files list so the two tabs read alike.
// 3. Verification — RTag per database; tone="success" for match,
// neutral for miss. Same source of truth (Hasheous match flags) as
// the "Verified" badge in the header, via `VERIFICATION_DATABASES`.
// 4. Metadata sources — ProviderGrid (linked + unlinked).
// 3. Verification: RTag per database; tone="success" for match,
// neutral for miss. Same source of truth as the "Verified" badge in
// the header, via `VERIFICATION_DATABASES`.
// 4. Metadata sources: ProviderGrid (linked + unlinked).
import { RTag } from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
@@ -14,10 +14,7 @@ import type { DetailedRom } from "@/stores/roms";
import { formatBytes } from "@/utils";
import ProviderGrid from "@/v2/components/GameDetails/ProviderGrid.vue";
import HashChip from "@/v2/components/shared/HashChip.vue";
import {
matchesDatabase,
VERIFICATION_DATABASES,
} from "@/v2/utils/romVerification";
import { VERIFICATION_DATABASES } from "@/v2/utils/romVerification";
defineOptions({ inheritAttrs: false });
@@ -45,7 +42,7 @@ const fileRows = computed<Row[]>(() => {
// render as a dash via the fallback chip below.
const hashRows = computed<{ label: string; value: string | null }[]>(() => {
const r = props.rom;
// CHD SHA-1 lives on the file, not the ROM — surface it at ROM level
// CHD SHA-1 lives on the file, not the ROM; surface it at ROM level
// only when the ROM is a single CHD file. Skipped (not dashed) when
// not applicable since most ROMs aren't CHDs.
const chdSha1 = r.has_simple_single_file
@@ -66,11 +63,11 @@ type Verification = { label: string; match: boolean };
// Per-database match badges, driven by the shared VERIFICATION_DATABASES
// so this list stays in lockstep with the header badge and the backend
// filter. A match means the ROM's hash was found in that database (via
// Hasheous), which is what "verified" communicates.
// Hasheous or the RA hash lookup), which is what "verified" communicates.
const verifications = computed<Verification[]>(() =>
VERIFICATION_DATABASES.map((db) => ({
label: db.label,
match: matchesDatabase(props.rom, db.keys),
match: db.matches(props.rom),
})),
);
@@ -110,8 +107,8 @@ const downloadUrls = computed(() => {
</div>
</section>
<!-- 2. Hashes — click-to-copy via HashChip; absent hashes still
render a "—" pill so the row layout stays predictable. -->
<!-- 2. Hashes: click-to-copy via HashChip; absent hashes still
render a dash pill so the row layout stays predictable. -->
<section class="metadata-tab__section">
<h3 class="metadata-tab__heading">{{ t("rom.hashes-label") }}</h3>
<div class="metadata-tab__inline">
@@ -175,7 +172,7 @@ const downloadUrls = computed(() => {
color: var(--r-color-fg);
}
/* File info — two-column rows on wide screens, stacked on narrow. */
/* File info: two-column rows on wide screens, stacked on narrow. */
.metadata-tab__rows {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
@@ -200,7 +197,7 @@ const downloadUrls = computed(() => {
word-break: break-all;
}
/* Hashes & Verification — inline row, wraps when narrow. */
/* Hashes & Verification: inline row, wraps when narrow. */
.metadata-tab__inline {
display: flex;
flex-wrap: wrap;

View File

@@ -1,16 +1,30 @@
import { describe, expect, it } from "vitest";
import type { RomHasheousMetadata } from "@/__generated__";
import type { RomHasheousMetadata, RomRAMetadata } from "@/__generated__";
import type { SimpleRom } from "@/stores/roms";
import {
isRomVerified,
matchesDatabase,
VERIFICATION_DATABASES,
VERIFICATION_KEYS,
} from "./romVerification";
import { rom as listRom } from "@/v2/components/Gallery/listRowFixture";
import { isRomVerified, VERIFICATION_DATABASES } from "./romVerification";
// Only `hasheous_metadata` is read; cast a minimal stub to SimpleRom.
const rom = (hasheous_metadata?: RomHasheousMetadata | null): SimpleRom =>
({ hasheous_metadata }) as SimpleRom;
const rom = (
hasheous_metadata: RomHasheousMetadata | null = null,
merged_ra_metadata: RomRAMetadata | null = null,
): SimpleRom => listRom({ hasheous_metadata, merged_ra_metadata });
const database = (label: string) =>
VERIFICATION_DATABASES.find((db) => db.label === label)!;
// Every Hasheous flag the backend's `_filter_by_verified` counts.
const HASHEOUS_KEYS: (keyof RomHasheousMetadata)[] = [
"tosec_match",
"mame_arcade_match",
"mame_mess_match",
"nointro_match",
"redump_match",
"mame_redump_match",
"whdload_match",
"ra_match",
"fbneo_match",
"puredos_match",
];
describe("isRomVerified", () => {
it("is false when there is no hasheous metadata", () => {
@@ -27,48 +41,46 @@ describe("isRomVerified", () => {
});
it("is true when any single database matched", () => {
for (const key of VERIFICATION_KEYS) {
for (const key of HASHEOUS_KEYS) {
expect(isRomVerified(rom({ [key]: true }))).toBe(true);
}
});
it("is true for an RA hash match alone", () => {
expect(isRomVerified(rom(null, { hash_match: true }))).toBe(true);
expect(isRomVerified(rom(null, { hash_match: false }))).toBe(false);
});
});
describe("matchesDatabase", () => {
describe("VERIFICATION_DATABASES", () => {
it("matches MAME on either the arcade or the mess flag", () => {
const mame = VERIFICATION_DATABASES.find((db) => db.label === "MAME")!;
expect(matchesDatabase(rom(), mame.keys)).toBe(false);
expect(matchesDatabase(rom({ mame_arcade_match: true }), mame.keys)).toBe(
true,
);
expect(matchesDatabase(rom({ mame_mess_match: true }), mame.keys)).toBe(
true,
);
const mame = database("MAME");
expect(mame.matches(rom())).toBe(false);
expect(mame.matches(rom({ mame_arcade_match: true }))).toBe(true);
expect(mame.matches(rom({ mame_mess_match: true }))).toBe(true);
});
it("matches Redump on either the disc-image or the CHD flag", () => {
const redump = VERIFICATION_DATABASES.find((db) => db.label === "Redump")!;
expect(matchesDatabase(rom({ redump_match: true }), redump.keys)).toBe(
true,
);
const redump = database("Redump");
expect(redump.matches(rom({ redump_match: true }))).toBe(true);
// Hasheous indexes CHD conversions under its own MAMERedump source.
expect(matchesDatabase(rom({ mame_redump_match: true }), redump.keys)).toBe(
expect(redump.matches(rom({ mame_redump_match: true }))).toBe(true);
});
it("matches RetroAchievements on Hasheous' flag or the RA hash match", () => {
const ra = database("RetroAchievements");
expect(ra.matches(rom({ ra_match: true }))).toBe(true);
expect(ra.matches(rom({ ra_match: false }, { hash_match: true }))).toBe(
true,
);
expect(ra.matches(rom(null, { hash_match: false }))).toBe(false);
});
it("treats RetroAchievements as a database match (ra_match, not ra_id)", () => {
const ra = VERIFICATION_DATABASES.find(
(db) => db.label === "RetroAchievements",
)!;
expect(ra.keys).toEqual(["ra_match"]);
expect(matchesDatabase(rom({ ra_match: true }), ra.keys)).toBe(true);
});
});
describe("VERIFICATION_KEYS", () => {
it("is the flattened set of every database's match flags", () => {
expect(VERIFICATION_KEYS).toEqual(
VERIFICATION_DATABASES.flatMap((db) => db.keys),
);
it("does not credit an RA hash match to other databases", () => {
const raHashMatch = rom(null, { hash_match: true });
for (const db of VERIFICATION_DATABASES) {
if (db.label === "RetroAchievements") continue;
expect(db.matches(raHashMatch)).toBe(false);
}
});
});

View File

@@ -1,46 +1,40 @@
// romVerification — single source of truth for what "verified" means: a
// ROM whose file hash matched a known ROM database (via Hasheous). Mirrors
// the backend's `_filter_by_verified` (roms_handler.py) so the header
// badge, the per-database chips in the Metadata tab, and the library
// "verified" filter all agree. Merely having a computed hash
// (crc/md5/sha1) does NOT make a ROM verified.
// "Verified" means the ROM's hash matched a known database (via Hasheous or
// the RA hash list). Mirrors the backend's `_filter_by_verified`.
import type { RomHasheousMetadata } from "@/__generated__";
import type { SimpleRom } from "@/stores/roms";
// Each database this ROM's hash can be checked against, with the Hasheous
// match flag(s) that count as a hit. MAME reports Arcade and MESS
// separately; either one means the ROM matched MAME. Redump likewise
// reports disc images and their CHD conversions separately. Order is the
// display order for the Metadata tab chips.
export const VERIFICATION_DATABASES: {
label: string;
keys: (keyof RomHasheousMetadata)[];
}[] = [
{ label: "TOSEC", keys: ["tosec_match"] },
{ label: "No-Intro", keys: ["nointro_match"] },
{ label: "Redump", keys: ["redump_match", "mame_redump_match"] },
{ label: "MAME", keys: ["mame_arcade_match", "mame_mess_match"] },
{ label: "FBNeo", keys: ["fbneo_match"] },
{ label: "WHDLoad", keys: ["whdload_match"] },
{ label: "PureDOS", keys: ["puredos_match"] },
{ label: "RetroAchievements", keys: ["ra_match"] },
];
type Matcher = (rom: SimpleRom) => boolean;
// Flattened match flags, i.e. the exact set the backend filters on.
export const VERIFICATION_KEYS: (keyof RomHasheousMetadata)[] =
VERIFICATION_DATABASES.flatMap((db) => db.keys);
// Whether a single database matched for this ROM.
export function matchesDatabase(
rom: SimpleRom,
keys: (keyof RomHasheousMetadata)[],
): boolean {
const h = rom.hasheous_metadata;
if (!h) return false;
return keys.some((key) => Boolean(h[key]));
function anyHasheousFlag(...keys: (keyof RomHasheousMetadata)[]): Matcher {
return (rom) => keys.some((key) => Boolean(rom.hasheous_metadata?.[key]));
}
// MAME (arcade/MESS) and Redump (disc/CHD) each report two flags; either counts.
// Order is the display order for the Metadata tab chips.
export const VERIFICATION_DATABASES: { label: string; matches: Matcher }[] = [
{ label: "TOSEC", matches: anyHasheousFlag("tosec_match") },
{ label: "No-Intro", matches: anyHasheousFlag("nointro_match") },
{
label: "Redump",
matches: anyHasheousFlag("redump_match", "mame_redump_match"),
},
{
label: "MAME",
matches: anyHasheousFlag("mame_arcade_match", "mame_mess_match"),
},
{ label: "FBNeo", matches: anyHasheousFlag("fbneo_match") },
{ label: "WHDLoad", matches: anyHasheousFlag("whdload_match") },
{ label: "PureDOS", matches: anyHasheousFlag("puredos_match") },
{
label: "RetroAchievements",
// RA hashes only part of some ROMs (NDS, PSP), which Hasheous can't match.
matches: (rom) =>
anyHasheousFlag("ra_match")(rom) ||
Boolean(rom.merged_ra_metadata?.hash_match),
},
];
// Whether the ROM is verified against any known database.
export function isRomVerified(rom: SimpleRom): boolean {
return matchesDatabase(rom, VERIFICATION_KEYS);
return VERIFICATION_DATABASES.some((db) => db.matches(rom));
}