perf(scan): skip the second write and reload for newly inserted roms (#5070)

* perf(scan): skip the second write and reload for newly inserted roms

A new rom is inserted and reloaded by the socket scan just before scan_rom, which then merged and reloaded it again before identification. Only existing roms take that write now. The insert carries the file hashes, size and title id so a scan that stops early still leaves a row rename detection can match.

* refactor(scan): address pr-ready code review

* chore(scan): pr-ready code-review pass

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(scan): pr-ready simplify pass

Fold the new insert tests into TestIdentifyRomReassociation, rename
_added_rom to scanning_rom, and name the emit test after both checks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(scan): pr-ready review-polish pass

Assert the unset file columns one by one, since mypy rejects comparing
the int-typed fs_size_bytes against None in a tuple.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Zach Clendenen
2026-10-03 09:23:13 -05:00
committed by GitHub
parent b1f4ac4888
commit 6fb4e4ea1b
4 changed files with 91 additions and 28 deletions

View File

@@ -76,6 +76,7 @@ from handler.scan_handler import (
build_hashless_fs_rom,
download_rom_resources,
emit_scanning_rom,
fs_rom_file_attrs,
get_enabled_metadata_sources,
persist_soundtrack_cover,
scan_firmware,
@@ -696,6 +697,9 @@ async def _identify_rom(
f"{hl(rom.name or rom.fs_name, color=BLUE)} by file hash"
)
else:
# Insert with the hashes too, so a scan that dies before its final
# write still leaves a row that rename detection can match.
rom_attrs.update(fs_rom_file_attrs(fs_rom))
try:
rom = db_rom_handler.add_rom(Rom(**rom_attrs))
except IntegrityError:

View File

@@ -231,6 +231,26 @@ def build_hashless_fs_rom(fs_name: str, fs_path: str, *, flat: bool) -> FSRom:
return build_empty_fs_rom(fs_name, fs_path, flat=flat)
def fs_rom_file_attrs(fs_rom: FSRom) -> dict[str, Any]:
"""The hash, size and title id columns a listed `fs_rom` sets on its rom."""
if not fs_rom["files"]:
return {}
attrs: dict[str, Any] = {
"crc_hash": fs_rom["crc_hash"],
"md5_hash": fs_rom["md5_hash"],
"sha1_hash": fs_rom["sha1_hash"],
"ra_hash": fs_rom["ra_hash"],
"fs_size_bytes": sum(file.file_size_bytes for file in fs_rom["files"]),
}
# Only when extraction produced an id, so a hash-only or extraction-disabled
# rescan can't wipe the stored one.
identity = fs_rom.get("identity")
if identity and identity.title_id:
attrs.update(identity.as_rom_attrs())
return attrs
def get_main_platform_igdb_id(platform: Platform) -> int | None:
cnfg = cm.get_config()
@@ -608,27 +628,12 @@ async def scan_rom(
"upc": rom.upc,
}
# Check if files have been parsed and hashed
if len(fs_rom["files"]) > 0:
filesize = sum([file.file_size_bytes for file in fs_rom["files"]])
rom_attrs.update(
{
"crc_hash": fs_rom["crc_hash"],
"md5_hash": fs_rom["md5_hash"],
"sha1_hash": fs_rom["sha1_hash"],
"ra_hash": fs_rom["ra_hash"],
"fs_size_bytes": filesize,
}
)
# Only overwrite title id values when extraction produced them, so a
# hash-only or extraction-disabled rescan can't wipe existing ones.
identity = fs_rom.get("identity")
if identity and identity.title_id:
rom_attrs.update(identity.as_rom_attrs())
# Metadata matching reads the id off the instance, so a first scan
# searches by what was just extracted rather than the old value.
rom.title_id = identity.title_id
file_attrs = fs_rom_file_attrs(fs_rom)
rom_attrs.update(file_attrs)
if file_attrs.get("title_id"):
# Metadata matching reads the id off the instance, so a rescan searches
# by what was just extracted rather than the stored value.
rom.title_id = file_attrs["title_id"]
# Update properties from existing rom if not a complete rescan
if not newly_added and scan_type != ScanType.COMPLETE:
@@ -774,11 +779,13 @@ async def scan_rom(
False,
)
_added_rom = db_rom_handler.add_rom(Rom(**rom_attrs))
_added_rom.is_identifying = True
# A new rom is already the reloaded row its caller inserted. An existing one
# is written so its rescanned columns land before identification.
scanning_rom = rom if newly_added else db_rom_handler.add_rom(Rom(**rom_attrs))
scanning_rom.is_identifying = True
if socket_manager:
await emit_scanning_rom(socket_manager, _added_rom, is_new=newly_added)
await emit_scanning_rom(socket_manager, scanning_rom, is_new=newly_added)
# Run hash fetches concurrently
(

View File

@@ -1212,6 +1212,52 @@ class TestIdentifyRomReassociation:
created = db.add_rom.call_args_list[0].args[0]
assert isinstance(created, Rom)
assert created.fs_name == "New Name.zip"
# Hashes without listed files are not inserted.
assert created.crc_hash is None
assert created.fs_size_bytes is None
assert created.title_id is None
async def test_new_entry_is_inserted_with_hashes(self, patched, mocker):
db, platform = patched
db.get_matching_missing_rom.return_value = None
mocker.patch.object(
fs_rom_handler,
"get_rom_files",
AsyncMock(
return_value=ParsedRomFiles(
rom_files=[
RomFile(
file_name="New Name.zip",
file_path="test/roms",
file_size_bytes=1024,
),
RomFile(
file_name="New Name [DLC].zip",
file_path="test/roms",
file_size_bytes=512,
),
],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="ra",
identity=RomIdentity(title_id="0100ABCD12340000"),
)
),
)
await self._run(platform)
created = db.add_rom.call_args_list[0].args[0]
expected = {
"crc_hash": "crc",
"md5_hash": "md5",
"sha1_hash": "sha1",
"ra_hash": "ra",
"fs_size_bytes": 1536,
"title_id": "0100ABCD12340000",
}
assert {key: getattr(created, key) for key in expected} == expected
class TestIdentifyRomTitleIdEmbedRename:

View File

@@ -10,7 +10,7 @@ from tests.factories import make_rom
from tests.handler.scan_stubs import add_n64_platform, add_rom
from adapters.services.screenscraper import ScreenScraperRateLimitError
from handler.database import db_platform_handler
from handler.database import db_platform_handler, db_rom_handler
from handler.filesystem.roms_handler import FSRom
from handler.metadata import (
meta_demozoo_handler,
@@ -1792,14 +1792,17 @@ async def test_scan_rom_games_still_use_fuzzy_catalog_covers(
@pytest.mark.parametrize("newly_added", [True, False])
async def test_scan_rom_emit_flags_new_roms(newly_added: bool):
"""Clients count a ROM toward its platform's games off `is_new`."""
async def test_scan_rom_flags_new_roms_and_writes_existing_ones(
newly_added: bool, mocker
):
"""Clients count a ROM off `is_new`, and only an existing one is written first."""
platform = db_platform_handler.add_platform(
Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64")
)
rom = make_rom(platform, "Game", fs_extension="z64", fs_path="n64", tags=[])
socket_manager = AsyncMock()
add_rom_spy = mocker.spy(db_rom_handler, "add_rom")
async with initialize_context():
await scan_rom(
platform=platform,
@@ -1811,9 +1814,12 @@ async def test_scan_rom_emit_flags_new_roms(newly_added: bool):
socket_manager=socket_manager,
)
assert add_rom_spy.call_count == (0 if newly_added else 1)
payloads = [
call.args[1]
for call in socket_manager.emit.await_args_list
if call.args[0] == "scan:scanning_rom"
]
assert [payload["is_new"] for payload in payloads] == [newly_added]
assert [(p["is_new"], p["is_identifying"], p["id"]) for p in payloads] == [
(newly_added, True, rom.id)
]