Merge pull request #4188 from sdornan/claude/single-file-rescan-perf-483f79

perf(scan): scope a rom-id scan to the selected roms
This commit is contained in:
Georges-Antoine Assi
2026-08-16 13:57:51 -04:00
committed by GitHub
3 changed files with 510 additions and 63 deletions

View File

@@ -611,6 +611,100 @@ async def _identify_rom(
)
async def _scan_selected_roms(
platform: Platform,
roms: list[Rom],
scan_type: ScanType,
roms_ids: list[int],
metadata_sources: list[str],
launchbox_remote_enabled: bool,
playmatch_enabled: bool,
socket_manager: socketio.AsyncRedisManager,
scan_stats: ScanStats,
) -> ScanStats:
"""Scan a hand-picked set of ROMs without touching the rest of their platform.
The work is resolved from the database rather than the filesystem, so none of
the platform-wide reconciliation `_identify_platform` does (directory
listings, the firmware pass, the missing-file sync, a skip-and-mark-present
pass over every other entry) applies here.
"""
if redis_client.get(STOP_SCAN_FLAG):
raise ScanStoppedException()
# Gamelist matches are served from a per-platform cache, so it has to be
# warm before any of these ROMs is scanned.
if MetadataSource.GAMELIST in metadata_sources:
await meta_gamelist_handler.populate_cache(platform)
await scan_stats.increment(
socket_manager=socket_manager,
scanned_platforms=1,
identified_platforms=1 if platform.is_identified else 0,
)
scan_semaphore = asyncio.Semaphore(SCAN_WORKERS)
async def scan_rom_with_semaphore(rom: Rom) -> None:
async with scan_semaphore:
# A library scan learns this from splitting the platform folder into
# files and directories; with no listing to consult, ask the path.
is_flat = await fs_rom_handler.file_exists(rom.full_path)
if not is_flat and not await fs_rom_handler.directory_exists(rom.full_path):
# A library scan never reaches an entry whose file is gone, since
# it walks the filesystem. Reaching one here must not resurrect
# it: scanning marks a ROM present unconditionally.
log.warning(
f"{hl(rom.fs_name)} is {hl('missing', color=LIGHTYELLOW)} from the "
"filesystem, skipping"
)
db_rom_handler.update_rom(rom.id, {"missing_from_fs": True})
await scan_stats.increment(
socket_manager=socket_manager, scanned_roms=1
)
return
await _identify_rom(
platform=platform,
fs_rom=FSRom(
fs_name=rom.fs_name,
flat=is_flat,
nested=not is_flat,
files=[],
crc_hash="",
md5_hash="",
sha1_hash="",
ra_hash="",
),
rom=rom,
scan_type=scan_type,
roms_ids=roms_ids,
metadata_sources=metadata_sources,
launchbox_remote_enabled=launchbox_remote_enabled,
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
)
results = await asyncio.gather(
*[scan_rom_with_semaphore(rom) for rom in roms], return_exceptions=True
)
for result, rom in zip(results, roms, strict=False):
if isinstance(result, Exception):
log.error(f"Error scanning ROM {rom.fs_name}: {result}")
# `_identify_rom` returns rather than raises when the flag is set, so a scan
# stopped mid-gather would otherwise fall through to the post-scan work and
# report itself done, leaving the flag set behind it.
if redis_client.get(STOP_SCAN_FLAG):
raise ScanStoppedException()
if MetadataSource.SS in metadata_sources:
log_ss_quota()
return scan_stats
async def _identify_platform(
platform_slug: str,
scan_type: ScanType,
@@ -867,18 +961,27 @@ async def scan_platforms(
socket_manager = _get_socket_manager()
scan_stats = ScanStats()
# A ROM-id-scoped scan resolves its work from the database, so it neither
# needs nor can afford the filesystem walk a library scan starts with.
scoped_roms_by_platform: dict[int, list[Rom]] = {}
if roms_ids:
for rom in db_rom_handler.get_roms_by_ids(roms_ids):
scoped_roms_by_platform.setdefault(rom.platform_id, []).append(rom)
# ScreenScraper's scan state is process-global, so a scan that never touches
# it must leave it alone: under DEV_MODE scans run in-process and can
# overlap, and resetting would drop the other scan's limits and skips.
if MetadataSource.SS in metadata_sources:
await begin_ss_scan()
try:
fs_platforms: list[str] = await fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:
log.error(e)
await socket_manager.emit("scan:done_ko", e.message)
return scan_stats
fs_platforms: list[str] = []
if not roms_ids:
try:
fs_platforms = await fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:
log.error(e)
await socket_manager.emit("scan:done_ko", e.message)
return scan_stats
# Clear the gamelist cache to ensure we're using fresh gamelist.xml data
meta_gamelist_handler.clear_cache()
@@ -891,42 +994,59 @@ async def scan_platforms(
# are provided, every filesystem platform is scanned.
db_platforms = db_platform_handler.get_platforms()
db_platforms_by_slug = {p.fs_slug: p for p in db_platforms}
db_platforms_by_id = {p.id: p for p in db_platforms}
# Selected platforms arrive as database ids and/or filesystem slugs.
selected_slugs = [p.fs_slug for p in db_platforms if p.id in platform_ids]
for fs_slug in platform_fs_slugs:
if fs_slug in selected_slugs:
continue
if fs_slug in db_platforms_by_slug or fs_slug in fs_platforms:
selected_slugs.append(fs_slug)
if roms_ids:
# A rom whose platform row is gone can't be scanned, so drop it here
# rather than count it toward a total the scan will never reach.
scoped_roms_by_platform = {
platform_id: scoped_roms
for platform_id, scoped_roms in scoped_roms_by_platform.items()
if platform_id in db_platforms_by_id
}
platform_list = sorted(
db_platforms_by_id[platform_id].fs_slug
for platform_id in scoped_roms_by_platform
)
total_platforms = len(scoped_roms_by_platform)
total_roms = sum(len(roms) for roms in scoped_roms_by_platform.values())
else:
# Selected platforms arrive as database ids and/or filesystem slugs.
selected_slugs = [p.fs_slug for p in db_platforms if p.id in platform_ids]
for fs_slug in platform_fs_slugs:
if fs_slug in selected_slugs:
continue
if fs_slug in db_platforms_by_slug or fs_slug in fs_platforms:
selected_slugs.append(fs_slug)
has_selection = bool(platform_ids or platform_fs_slugs)
platform_list = sorted(selected_slugs if has_selection else fs_platforms)
has_selection = bool(platform_ids or platform_fs_slugs)
platform_list = sorted(selected_slugs if has_selection else fs_platforms)
# A "new platforms" scan skips platforms that already exist in the database,
# so they must be excluded from the totals to keep the tracker accurate. This
# mirrors the existence check done per-platform in _identify_platform, reusing
# the platforms already fetched above instead of querying again per platform.
platforms_to_scan = platform_list
if scan_type == ScanType.NEW_PLATFORMS:
platforms_to_scan = [
platform_slug
for platform_slug in platform_list
if db_platforms_by_slug.get(platform_slug) is None
]
# A "new platforms" scan skips platforms that already exist in the database,
# so they must be excluded from the totals to keep the tracker accurate. This
# mirrors the existence check done per-platform in _identify_platform, reusing
# the platforms already fetched above instead of querying again per platform.
platforms_to_scan = platform_list
if scan_type == ScanType.NEW_PLATFORMS:
platforms_to_scan = [
platform_slug
for platform_slug in platform_list
if db_platforms_by_slug.get(platform_slug) is None
]
total_roms = 0
for platform_slug in platforms_to_scan:
try:
total_roms += await fs_rom_handler.count_roms(
Platform(fs_slug=platform_slug)
)
except RomsNotFoundException as e:
log.error(e)
total_platforms = len(platforms_to_scan)
total_roms = 0
for platform_slug in platforms_to_scan:
try:
total_roms += await fs_rom_handler.count_roms(
Platform(fs_slug=platform_slug)
)
except RomsNotFoundException as e:
log.error(e)
await scan_stats.update(
socket_manager=socket_manager,
total_platforms=len(platforms_to_scan),
total_platforms=total_platforms,
total_roms=total_roms,
)
@@ -936,34 +1056,50 @@ async def scan_platforms(
redis_client.delete(STOP_SCAN_FLAG)
try:
if len(platform_list) == 0:
log.warning(
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly."
f"{FOLDER_STRUCT_MSG}"
)
if roms_ids:
log.info(f"Scanning {hl(str(total_roms))} selected roms")
for platform_id, scoped_roms in scoped_roms_by_platform.items():
scan_stats = await _scan_selected_roms(
platform=db_platforms_by_id[platform_id],
roms=scoped_roms,
scan_type=scan_type,
roms_ids=roms_ids,
metadata_sources=metadata_sources,
launchbox_remote_enabled=launchbox_remote_enabled,
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
)
else:
log.info(
f"Found {hl(str(len(platform_list)))} platforms in the file system"
)
if len(platform_list) == 0:
log.warning(
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly."
f"{FOLDER_STRUCT_MSG}"
)
else:
log.info(
f"Found {hl(str(len(platform_list)))} platforms in the file system"
)
for platform_slug in platform_list:
scan_stats = await _identify_platform(
platform_slug=platform_slug,
scan_type=scan_type,
fs_platforms=fs_platforms,
roms_ids=roms_ids,
metadata_sources=metadata_sources,
launchbox_remote_enabled=launchbox_remote_enabled,
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
)
for platform_slug in platform_list:
scan_stats = await _identify_platform(
platform_slug=platform_slug,
scan_type=scan_type,
fs_platforms=fs_platforms,
roms_ids=roms_ids,
metadata_sources=metadata_sources,
launchbox_remote_enabled=launchbox_remote_enabled,
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
)
missed_platforms = db_platform_handler.mark_missing_platforms(fs_platforms)
if len(missed_platforms) > 0:
log.warning(f"{hl('Missing')} platforms from filesystem:")
for p in missed_platforms:
log.warning(f" - {p.slug} ({p.fs_slug})")
missed_platforms = db_platform_handler.mark_missing_platforms(fs_platforms)
if len(missed_platforms) > 0:
log.warning(f"{hl('Missing')} platforms from filesystem:")
for p in missed_platforms:
log.warning(f" - {p.slug} ({p.fs_slug})")
if MetadataSource.SS in metadata_sources:
log_ss_scan_summary()
@@ -974,10 +1110,14 @@ async def scan_platforms(
db_rom_handler.invalidate_filter_values_cache()
# Smart collection membership is derived from the library, and is no
# longer recomputed while serving a gallery page. The scan itself is
# done, so a failure here must not report it as one.
# longer recomputed while serving a gallery page. A scan scoped to a
# handful of ROMs only has to recount the collections those ROMs touch.
# The scan itself is done, so a failure here must not report it as one.
try:
db_collection_handler.refresh_smart_collections()
if roms_ids:
db_collection_handler.refresh_smart_collections_for_roms(roms_ids)
else:
db_collection_handler.refresh_smart_collections()
except Exception as e:
log.error(f"Couldn't refresh smart collections after the scan: {e}")

View File

@@ -651,6 +651,27 @@ class FSHandler:
async with lock:
return full_path.is_file()
async def directory_exists(self, path: str) -> bool:
"""
Check if a directory exists.
Args:
path: Relative path to the directory
Returns:
True if directory exists, False otherwise
"""
if not path:
raise ValueError("Directory path cannot be empty")
# Validate and normalize path
full_path = self.validate_path(path)
# Async thread-safe existence check
lock = await self._get_file_lock(str(full_path))
async with lock:
return full_path.is_dir()
async def get_file_size(self, file_path: str) -> int:
"""
Get the size of a file.

View File

@@ -9,6 +9,7 @@ from endpoints.sockets import scan as scan_module
from endpoints.sockets.scan import (
ScanStats,
_identify_rom,
_scan_selected_roms,
reject_unauthorized_scan,
scan_handler,
scan_platforms,
@@ -16,6 +17,7 @@ from endpoints.sockets.scan import (
stop_scan_handler,
)
from exceptions.fs_exceptions import FolderStructureNotMatchException
from exceptions.socket_exceptions import ScanStoppedException
from handler.auth.constants import Scope
from handler.database.roms_handler import SyncedRomFiles
from handler.filesystem.roms_handler import (
@@ -965,6 +967,290 @@ class TestIdentifyPlatformFirmwareReporting:
assert payload["new_firmware_count"] == 0
class TestScanSelectedRoms:
"""A ROM-id-scoped scan works off the database, not the platform folder."""
@pytest.fixture
def platform(self):
platform = Platform(name="Test", slug="test", fs_slug="test")
platform.id = 1
return platform
@pytest.fixture
def rom(self, platform):
rom = Rom(fs_name="Game.zip", fs_path="roms/test", platform_id=platform.id)
rom.id = 7
return rom
async def test_scans_the_selected_rom_without_listing_the_platform(
self, mocker, platform, rom
):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
mocker.patch.object(
scan_module.fs_rom_handler, "file_exists", AsyncMock(return_value=True)
)
get_roms = mocker.patch.object(
scan_module.fs_rom_handler, "get_roms", AsyncMock(return_value=[])
)
get_firmware = mocker.patch.object(
scan_module.fs_firmware_handler, "get_firmware", AsyncMock(return_value=[])
)
db_rom = mocker.patch.object(scan_module, "db_rom_handler")
identify = mocker.patch.object(
scan_module, "_identify_rom", side_effect=AsyncMock()
)
await _scan_selected_roms(
platform=platform,
roms=[rom],
scan_type=ScanType.COMPLETE,
roms_ids=[rom.id],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
identify.assert_called_once()
assert identify.call_args.kwargs["rom"] is rom
assert identify.call_args.kwargs["fs_rom"]["fs_name"] == "Game.zip"
# None of the platform-wide reconciliation a library scan does applies.
get_roms.assert_not_called()
get_firmware.assert_not_called()
db_rom.mark_missing_roms.assert_not_called()
db_rom.get_missing_rom_ids.assert_not_called()
db_rom.bulk_mark_present.assert_not_called()
async def test_a_rom_whose_file_is_gone_is_marked_missing_not_scanned(
self, mocker, platform, rom
):
"""A library scan never reaches a missing entry, since it walks the
filesystem. Scanning one here would clear its missing flag."""
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
mocker.patch.object(
scan_module.fs_rom_handler, "file_exists", AsyncMock(return_value=False)
)
mocker.patch.object(
scan_module.fs_rom_handler,
"directory_exists",
AsyncMock(return_value=False),
)
db_rom = mocker.patch.object(scan_module, "db_rom_handler")
identify = mocker.patch.object(
scan_module, "_identify_rom", side_effect=AsyncMock()
)
await _scan_selected_roms(
platform=platform,
roms=[rom],
scan_type=ScanType.COMPLETE,
roms_ids=[rom.id],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
identify.assert_not_called()
db_rom.update_rom.assert_called_once_with(rom.id, {"missing_from_fs": True})
async def test_a_multi_file_rom_is_reported_as_nested(self, mocker, platform, rom):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
mocker.patch.object(
scan_module.fs_rom_handler, "file_exists", AsyncMock(return_value=False)
)
mocker.patch.object(
scan_module.fs_rom_handler,
"directory_exists",
AsyncMock(return_value=True),
)
mocker.patch.object(scan_module, "db_rom_handler")
identify = mocker.patch.object(
scan_module, "_identify_rom", side_effect=AsyncMock()
)
await _scan_selected_roms(
platform=platform,
roms=[rom],
scan_type=ScanType.COMPLETE,
roms_ids=[rom.id],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
fs_rom = identify.call_args.kwargs["fs_rom"]
assert fs_rom["nested"] is True
assert fs_rom["flat"] is False
async def test_a_scan_stopped_mid_flight_raises(self, mocker, platform, rom):
"""`_identify_rom` returns rather than raises on the stop flag, so a stop
that lands after the run started has to be re-checked here or the scan
falls through to its post-scan work and reports itself done."""
# Unset when _scan_selected_roms starts, set by the time it finishes.
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(side_effect=[None, "1"]))
)
mocker.patch.object(
scan_module.fs_rom_handler, "file_exists", AsyncMock(return_value=True)
)
mocker.patch.object(scan_module, "db_rom_handler")
mocker.patch.object(scan_module, "_identify_rom", side_effect=AsyncMock())
with pytest.raises(ScanStoppedException):
await _scan_selected_roms(
platform=platform,
roms=[rom],
scan_type=ScanType.COMPLETE,
roms_ids=[rom.id],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
class TestScopedScanSkipsLibraryWork:
"""`scan_platforms` with `roms_ids` must not fall into the library pipeline."""
@pytest.fixture
def patched(self, mocker):
mocker.patch.object(
scan_module, "_get_socket_manager", return_value=AsyncMock()
)
mocker.patch.object(scan_module.meta_gamelist_handler, "clear_cache")
mocker.patch.object(
scan_module.db_rom_handler, "invalidate_filter_values_cache"
)
config = MagicMock()
config.GAMELIST_AUTO_EXPORT_ON_SCAN = False
config.PEGASUS_AUTO_EXPORT_ON_SCAN = False
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
platform = MagicMock(id=1, fs_slug="test")
mocker.patch.object(
scan_module.db_platform_handler, "get_platforms", return_value=[platform]
)
rom = MagicMock(id=7, platform_id=1)
mocker.patch.object(
scan_module.db_rom_handler, "get_roms_by_ids", return_value=[rom]
)
async def fake_scoped(**kwargs):
return kwargs["scan_stats"]
return {
"scoped": mocker.patch.object(
scan_module, "_scan_selected_roms", side_effect=fake_scoped
),
"identify_platform": mocker.patch.object(
scan_module, "_identify_platform", side_effect=AsyncMock()
),
"get_platforms": mocker.patch.object(
scan_module.fs_platform_handler, "get_platforms", AsyncMock()
),
"count_roms": mocker.patch.object(
scan_module.fs_rom_handler, "count_roms", AsyncMock(return_value=100)
),
"mark_missing_platforms": mocker.patch.object(
scan_module.db_platform_handler,
"mark_missing_platforms",
return_value=[],
),
"refresh_all": mocker.patch.object(
scan_module.db_collection_handler, "refresh_smart_collections"
),
"refresh_scoped": mocker.patch.object(
scan_module.db_collection_handler, "refresh_smart_collections_for_roms"
),
}
async def test_platform_pipeline_is_skipped(self, patched):
result = await scan_platforms(
platform_ids=[1],
metadata_sources=[],
scan_type=ScanType.COMPLETE,
roms_ids=[7],
)
patched["scoped"].assert_called_once()
patched["identify_platform"].assert_not_called()
patched["get_platforms"].assert_not_called()
patched["count_roms"].assert_not_called()
patched["mark_missing_platforms"].assert_not_called()
# Totals come from the selection, not from counting the platform folder.
assert result.total_platforms == 1
assert result.total_roms == 1
async def test_totals_exclude_roms_whose_platform_is_gone(self, patched, mocker):
"""A rom whose platform row vanished can't be scanned, so counting it
would leave the tracker short of its own total forever."""
mocker.patch.object(
scan_module.db_rom_handler,
"get_roms_by_ids",
return_value=[
MagicMock(id=7, platform_id=1),
MagicMock(id=8, platform_id=99),
],
)
result = await scan_platforms(
platform_ids=[1],
metadata_sources=[],
scan_type=ScanType.COMPLETE,
roms_ids=[7, 8],
)
# Only platform 1 exists, so only its rom is counted and scanned.
assert result.total_platforms == 1
assert result.total_roms == 1
patched["scoped"].assert_called_once()
assert [r.id for r in patched["scoped"].call_args.kwargs["roms"]] == [7]
async def test_only_the_selected_roms_smart_collections_are_recounted(
self, patched
):
await scan_platforms(
platform_ids=[1],
metadata_sources=[],
scan_type=ScanType.COMPLETE,
roms_ids=[7],
)
patched["refresh_scoped"].assert_called_once_with([7])
patched["refresh_all"].assert_not_called()
async def test_a_library_scan_still_recounts_everything(self, patched, mocker):
mocker.patch.object(
scan_module.fs_platform_handler,
"get_platforms",
AsyncMock(return_value=["test"]),
)
await scan_platforms(
platform_ids=[],
metadata_sources=[],
scan_type=ScanType.COMPLETE,
)
patched["refresh_all"].assert_called_once()
patched["refresh_scoped"].assert_not_called()
class TestGetPico8CoverUrl:
"""Tests for the PICO-8 cover art URL helper on FSRomsHandler."""