refactor(scan): run a title-ids scan through the quick-scan file refresh

A quick scan already re-reads the title id of every existing rom through
refresh_rom_files, keeping stored hashes for unchanged files. A title-ids
scan now takes the same branch instead of the full _identify_rom and
scan_rom path, which drops its special cases in _should_get_rom_files,
_should_extract_title_ids, _should_hash_incrementally, the resource
short-circuit, the scan_rom base-field list and the similarity guard.

refresh_rom_files gains what that path gave the scan:
- an opt-in embed_title_ids, so EMBED_SWITCH_TITLE_IDS still renames
- persisting a reused row whose category extraction settled, which a quick
  scan dropped before because only new, changed or removed rows were synced
- identity_changed on the result, so an id-only change counts as updated

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-25 11:45:50 -04:00
parent 320a400f60
commit afa38d1df1
5 changed files with 132 additions and 101 deletions

View File

@@ -458,7 +458,8 @@ def _should_get_rom_files(
return bool(
newly_added
or scan_type in (ScanType.COMPLETE, ScanType.HASHES, ScanType.TITLE_IDS)
or (scan_type == ScanType.COMPLETE)
or (scan_type == ScanType.HASHES)
or (rom and rom.id in roms_ids)
)
@@ -478,7 +479,7 @@ def _should_extract_title_ids(scan_type: ScanType, rom: Rom) -> bool:
"""
return bool(
scan_type in (ScanType.COMPLETE, ScanType.HASHES, ScanType.TITLE_IDS)
scan_type in (ScanType.COMPLETE, ScanType.HASHES)
or not rom.title_id
or rom.platform_slug in SWITCH_PLATFORM_SLUGS
)
@@ -511,11 +512,10 @@ def _should_hash_incrementally(
rom: Rom | None,
roms_ids: list[int],
) -> bool:
"""Decide if a rom's unchanged files may keep their stored hashes
"""Decide if a selected rom's unchanged files may keep their stored hashes
Only COMPLETE and HASHES promise to re-read every byte. A quick scan does
not reach here: it reconciles an existing rom through `refresh_rom_files`.
A row with no stored hash is re-read either way.
Args:
scan_type (ScanType): Type of scan to be performed.
@@ -524,14 +524,9 @@ def _should_hash_incrementally(
"""
return bool(
rom
and (
scan_type == ScanType.TITLE_IDS
or (
scan_type in (ScanType.UPDATE, ScanType.UNMATCHED)
and rom.id in roms_ids
)
)
scan_type in (ScanType.UPDATE, ScanType.UNMATCHED)
and rom
and rom.id in roms_ids
)
@@ -616,10 +611,14 @@ async def _identify_rom(
if redis_client.get(STOP_SCAN_FLAG):
return
# A quick scan only reconciles an existing entry's files with disk, so it
# needs none of the metadata prelude below.
if rom is not None and scan_type == ScanType.QUICK:
refreshed = await refresh_rom_files(rom)
# Quick and title-ids scans only reconcile an existing entry's files with
# disk, so they need none of the metadata prelude below.
if rom is not None and scan_type in (ScanType.QUICK, ScanType.TITLE_IDS):
refreshed = await refresh_rom_files(
rom,
embed_title_ids=scan_type == ScanType.TITLE_IDS
and cm.get_config().EMBED_SWITCH_TITLE_IDS,
)
await scan_stats.increment(
socket_manager=socket_manager,
scanned_roms=1,
@@ -829,7 +828,8 @@ async def _identify_rom(
for saved in synced.files:
persist_soundtrack_cover(saved, _added_rom)
if scan_type in (ScanType.HASHES, ScanType.TITLE_IDS):
# Short circuit if the scan type is hashes
if scan_type == ScanType.HASHES:
return
await download_rom_resources(
@@ -1455,12 +1455,10 @@ async def scan_platforms(
# Otherwise the games scanned today have an empty "Similar games"
# section until the nightly build. Threaded: the scoring is CPU-bound.
# A title-ids scan leaves the metadata similar games key on alone.
if scan_type != ScanType.TITLE_IDS:
try:
await asyncio.to_thread(top_up_similarity, scanned_rom_ids)
except Exception as e:
log.error(f"Couldn't update recommendations after the scan: {e}")
try:
await asyncio.to_thread(top_up_similarity, scanned_rom_ids)
except Exception as e:
log.error(f"Couldn't update recommendations after the scan: {e}")
# Export metadata files if enabled in config
config = cm.get_config()

View File

@@ -53,10 +53,16 @@ class RomFilesRefresh:
new_files: int
updated_files: int
removed_files: int
identity_changed: bool = False
@property
def changed(self) -> bool:
return bool(self.new_files or self.updated_files or self.removed_files)
return bool(
self.new_files
or self.updated_files
or self.removed_files
or self.identity_changed
)
def loaded_rom_files(rom: Rom) -> list[RomFile]:
@@ -66,21 +72,25 @@ def loaded_rom_files(rom: Rom) -> list[RomFile]:
return db_rom_handler.rom_files_for_rom_id(rom.id)
async def refresh_rom_files(rom: Rom) -> RomFilesRefresh:
async def refresh_rom_files(rom: Rom, embed_title_ids: bool = False) -> RomFilesRefresh:
"""Reconcile a ROM's file rows with what is on disk, keeping the stored
hashes of files whose size and mtime are unchanged.
Args:
rom: A persisted ROM whose folder or file exists on disk.
embed_title_ids: Rename Switch files to carry the title id read from them.
Returns:
What changed, so callers can report it.
"""
async with _refresh_lock(rom.id):
return await _refresh(rom)
return await _refresh(rom, embed_title_ids)
async def _refresh(rom: Rom) -> RomFilesRefresh:
async def _refresh(rom: Rom, embed_title_ids: bool) -> RomFilesRefresh:
existing = loaded_rom_files(rom)
# Extraction can settle a reused row's category and embedding can rename it,
# both in place, so a reused row is compared against what it was loaded as.
loaded_as = {id(f): (f.file_name, f.category) for f in existing}
cnfg = cm.get_config()
calculate_hashes = not cnfg.SKIP_HASH_CALCULATION
parsed = await fs_rom_handler.get_rom_files(
@@ -97,12 +107,15 @@ async def _refresh(rom: Rom) -> RomFilesRefresh:
)
return RomFilesRefresh(0, 0, 0)
renamed_fs_name = (
await fs_rom_handler.embed_switch_title_ids(parsed) if embed_title_ids else None
)
existing_keys = {rom_file_key(f) for f in existing}
reused_ids = {id(f) for f in existing}
new_keys: set[RomFileKey] = set()
updated_keys: set[RomFileKey] = set()
for scanned in parsed.rom_files:
if id(scanned) in reused_ids:
if loaded_as.get(id(scanned)) == (scanned.file_name, scanned.category):
continue
key = rom_file_key(scanned)
(updated_keys if key in existing_keys else new_keys).add(key)
@@ -128,10 +141,15 @@ async def _refresh(rom: Rom) -> RomFilesRefresh:
if value != (getattr(rom, column) or ""):
rom_updates[column] = value
# Only written when the parse actually read an id, so a refresh that read
# none (extraction disabled, or every file unchanged) leaves the stored
# triple alone rather than blanking it.
if parsed.identity.title_id and parsed.identity != RomIdentity.from_rom(rom):
# none (extraction disabled, or no readable file) leaves the stored triple
# alone rather than blanking it.
identity_changed = bool(
parsed.identity.title_id and parsed.identity != RomIdentity.from_rom(rom)
)
if identity_changed:
rom_updates.update(parsed.identity.as_rom_attrs())
if renamed_fs_name:
rom_updates["fs_name"] = renamed_fs_name
if rom.missing_from_fs:
rom_updates["missing_from_fs"] = False
if rom_updates:
@@ -141,4 +159,5 @@ async def _refresh(rom: Rom) -> RomFilesRefresh:
new_files=len(new_keys),
updated_files=len(updated_keys),
removed_files=len(removed_keys),
identity_changed=identity_changed,
)

View File

@@ -1558,12 +1558,11 @@ async def scan_rom(
if field_value:
rom_attrs[field] = field_value
# Don't overwrite existing base fields on a partial rescan
# 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,
ScanType.TITLE_IDS,
):
# A ROM's name defaults to a filename-derived placeholder when first
# created. Treat that placeholder as "no name" so a freshly matched provider

View File

@@ -507,15 +507,6 @@ class TestScreenScraperScanReporting:
summary.assert_not_called()
def _rom_on(platform_slug: str, title_id: str | None = None) -> Rom:
# Built untyped and cast, since `platform_slug` is a read-only property.
rom = Mock(spec=Rom)
rom.id = 1
rom.title_id = title_id
rom.platform_slug = platform_slug
return cast(Rom, rom)
class TestShouldScanRom:
def test_new_platforms_scan_with_no_rom(self):
"""NEW_PLATFORMS should scan when rom is None"""
@@ -755,14 +746,24 @@ class TestShouldReparseTags:
class TestShouldExtractTitleIds:
"""Which rescans pay for another native parse of a rom's binaries."""
@staticmethod
def _rom(platform_slug: str, title_id: str | None) -> Rom:
# Built untyped and cast, since `platform_slug` is a read-only property.
rom = Mock(spec=Rom)
rom.title_id = title_id
rom.platform_slug = platform_slug
return cast(Rom, rom)
def test_a_stored_id_is_not_re_read(self):
rom = _rom_on("psp", "ULUS-10041")
rom = self._rom("psp", "ULUS-10041")
assert _should_extract_title_ids(ScanType.UPDATE, rom) is False
assert _should_extract_title_ids(ScanType.UNMATCHED, rom) is False
def test_a_rom_without_an_id_is_read(self):
assert _should_extract_title_ids(ScanType.UPDATE, _rom_on("psp", None)) is True
assert (
_should_extract_title_ids(ScanType.UPDATE, self._rom("psp", None)) is True
)
@pytest.mark.parametrize("scan_type", [ScanType.COMPLETE, ScanType.HASHES])
def test_a_rescan_that_re_reads_the_bytes_re_reads_the_id(
@@ -770,7 +771,7 @@ class TestShouldExtractTitleIds:
):
"""Replacing a file in place would otherwise leave the old id beside the
hashes of the new bytes."""
rom = _rom_on("psp", "ULUS-10041")
rom = self._rom("psp", "ULUS-10041")
assert _should_extract_title_ids(scan_type, rom) is True
@@ -778,17 +779,10 @@ class TestShouldExtractTitleIds:
def test_switch_always_re_reads(self, platform_slug: str):
"""The same parse settles the per-file categories, which a rebuild would
otherwise take from the folder names instead."""
rom = _rom_on(platform_slug, "0100ABCD12340000")
rom = self._rom(platform_slug, "0100ABCD12340000")
assert _should_extract_title_ids(ScanType.UPDATE, rom) is True
def test_a_title_ids_scan_re_reads_a_stored_id(self):
"""Refreshing the id is the whole point, so a stored one is no reason
to skip the rom."""
rom = _rom_on("ngc", "47414645")
assert _should_extract_title_ids(ScanType.TITLE_IDS, rom) is True
class TestIdentifyRomTagReparse:
"""A complete rescan re-reads filename tags onto an existing entry.
@@ -2119,16 +2113,6 @@ class TestPostScanRecommendations:
top_up.assert_called_once_with(set())
async def test_a_title_ids_scan_skips_the_top_up(self, patched, mocker):
"""Similar games key on metadata, which a title-ids scan leaves alone."""
top_up = mocker.patch.object(scan_module, "top_up_similarity")
await scan_platforms(
platform_ids=[], metadata_sources=[], scan_type=ScanType.TITLE_IDS
)
top_up.assert_not_called()
async def test_a_failure_to_index_does_not_fail_the_scan(self, patched, mocker):
mocker.patch.object(
scan_module, "top_up_similarity", side_effect=RuntimeError("boom")
@@ -2720,32 +2704,6 @@ class TestScanJobMeta:
assert scan_job_meta(scan_type)["task_name"] == expected
class TestShouldGetRomFiles:
def test_a_title_ids_scan_rebuilds_every_rom(self, rom: Rom):
"""Extraction reads the files, so the rows have to be walked even for a
rom no selection names."""
assert (
scan_module._should_get_rom_files(
scan_type=ScanType.TITLE_IDS,
rom=rom,
newly_added=False,
roms_ids=[],
)
is True
)
def test_a_metadata_scan_leaves_an_unselected_rom_alone(self, rom: Rom):
assert (
scan_module._should_get_rom_files(
scan_type=ScanType.UPDATE,
rom=rom,
newly_added=False,
roms_ids=[],
)
is False
)
class TestShouldHashIncrementally:
def test_selected_metadata_scans_are_incremental(self, rom: Rom):
assert _should_hash_incrementally(ScanType.UPDATE, rom, [rom.id]) is True
@@ -2757,15 +2715,6 @@ class TestShouldHashIncrementally:
def test_full_rescans_read_every_file(self, rom: Rom, scan_type: ScanType):
assert _should_hash_incrementally(scan_type, rom, [rom.id]) is False
def test_a_title_ids_scan_keeps_hashes_without_a_selection(self, rom: Rom):
"""It reads headers, so re-hashing a library it never looks at the
bytes of would be the bulk of its cost."""
assert _should_hash_incrementally(ScanType.TITLE_IDS, rom, []) is True
assert _should_hash_incrementally(ScanType.TITLE_IDS, rom, [rom.id]) is True
def test_a_missing_rom_is_never_incremental(self):
assert _should_hash_incrementally(ScanType.TITLE_IDS, None, []) is False
@pytest.fixture
def identify_harness(mocker):
@@ -2863,6 +2812,7 @@ def identify_harness(mocker):
)
return SimpleNamespace(
config=config,
db=db,
scan_rom=scan_rom,
get_rom_files=get_rom_files,
@@ -2877,6 +2827,21 @@ class TestIdentifyRomFiles:
"""A quick scan hands an existing rom to `refresh_rom_files` and skips the
metadata pipeline; a rom not yet in the database goes the regular way."""
@pytest.mark.parametrize(
"scan_type,embed",
[(ScanType.QUICK, False), (ScanType.TITLE_IDS, True)],
)
async def test_only_a_title_ids_scan_embeds_title_ids(
self, identify_harness, scan_type: ScanType, embed: bool
):
identify_harness.config.EMBED_SWITCH_TITLE_IDS = True
rom = identify_harness.existing_rom()
await identify_harness.run(rom, scan_type, [])
identify_harness.refresh.assert_awaited_once_with(rom, embed_title_ids=embed)
identify_harness.scan_rom.assert_not_called()
async def test_existing_rom_only_refreshes_its_files(self, identify_harness):
rom = identify_harness.existing_rom()
socket_manager = AsyncMock()
@@ -2890,7 +2855,7 @@ class TestIdentifyRomFiles:
scan_stats=scan_stats,
)
identify_harness.refresh.assert_awaited_once_with(rom)
identify_harness.refresh.assert_awaited_once_with(rom, embed_title_ids=False)
identify_harness.scan_rom.assert_not_called()
identify_harness.db.add_rom.assert_not_called()
scan_stats.increment.assert_awaited_once_with(

View File

@@ -264,8 +264,9 @@ async def test_a_newly_read_identity_is_persisted(platform, admin_user, library)
"get_rom_files",
AsyncMock(return_value=_unchanged_parse(rom, identity)),
):
await refresh_rom_files(rom)
result = await refresh_rom_files(rom)
assert result.changed
refreshed = db_rom_handler.get_rom(rom.id)
assert refreshed.title_id == "0100ABCD12340000"
assert refreshed.save_target == "0100ABCD12340000"
@@ -287,3 +288,52 @@ async def test_a_stored_identity_survives_a_parse_that_read_none(
await refresh_rom_files(rom)
assert db_rom_handler.get_rom(rom.id).title_id == "ULUS-10041"
async def test_a_category_settled_on_a_reused_row_is_persisted(
platform, admin_user, library
):
"""Extraction settles a Switch file's category on the row it reused."""
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
async def settle_category(*_args, **_kwargs) -> ParsedRomFiles:
parsed = _unchanged_parse(rom, RomIdentity())
parsed.rom_files[0].category = RomFileCategory.DLC
return parsed
with patch.object(fs_rom_handler, "get_rom_files", settle_category):
result = await refresh_rom_files(rom)
assert result.updated_files == 1
assert _files_by_name(rom.id)["game.bin"].category == RomFileCategory.DLC
async def test_embedding_renames_the_rows_and_the_rom(platform, admin_user, library):
rom = _folder_rom(platform, admin_user, library, {"game.nsp": b"game"})
renamed = "game [0100ABCD12340000][v0].nsp"
async def rename(parsed: ParsedRomFiles) -> str:
parsed.rom_files[0].file_name = renamed
return renamed
with (
patch.object(
fs_rom_handler,
"get_rom_files",
AsyncMock(return_value=_unchanged_parse(rom, RomIdentity())),
),
patch.object(fs_rom_handler, "embed_switch_title_ids", rename),
):
await refresh_rom_files(rom, embed_title_ids=True)
assert set(_files_by_name(rom.id)) == {renamed}
assert db_rom_handler.get_rom(rom.id).fs_name == renamed
async def test_embedding_is_opt_in(platform, admin_user, library, mocker):
rom = _folder_rom(platform, admin_user, library, {"game.nsp": b"game"})
embed = mocker.patch.object(fs_rom_handler, "embed_switch_title_ids")
await refresh_rom_files(rom)
embed.assert_not_called()