perf(tasks): walk resource directories with os.scandir

The orphaned resource cleanup listed the resource tree through
`anyio.Path`, which dispatches to a worker thread for every entry it
yields and again for every `is_dir()` call. On a library with ~30k ROM
resource directories that is ~60k thread round trips to read data the
directory listing already contains.

Measured on a 30,262-directory library (Raspberry Pi 4, ext4):

    anyio iterdir + is_dir()   50.3s
    os.scandir                  0.15s

`os.scandir` reports the entry type from the directory read itself, so
no per-entry stat is needed. The walk moves into a helper run once via
`asyncio.to_thread`, keeping the event loop free while doing the whole
traversal in a single thread hop rather than tens of thousands.

Cold and warm runs of the old code were within 1% of each other, so this
was thread-dispatch overhead rather than disk I/O.

A directory that cannot be listed now logs and yields an empty set
instead of aborting the walk, so one unreadable platform cannot strand
every other platform's orphans.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Ryan McClelland
2026-07-27 14:29:30 -07:00
parent 4b83bf0e5d
commit 4bf8f5a15c
2 changed files with 86 additions and 15 deletions

View File

@@ -1,3 +1,4 @@
import asyncio
import os
import shutil
from dataclasses import dataclass
@@ -16,6 +17,34 @@ from tasks.tasks import PeriodicTask, TaskType, update_job_meta
from utils.context import initialize_context
def _numeric_subdirs(path: str) -> set[int]:
"""Numeric-named subdirectories of `path`, as ints."""
try:
with os.scandir(path) as entries:
return {
int(entry.name)
for entry in entries
if entry.name.isdigit() and entry.is_dir()
}
except OSError as exc:
log.error(f"Unable to list resource directory {path}: {str(exc)}")
return set()
def _scan_resource_dirs(roms_resources_path: str) -> dict[int, set[int]]:
"""Map each platform id on disk to the ROM ids that have a resource directory.
`os.scandir` reports the entry type from the directory read itself, so this
walks tens of thousands of entries without a stat call per entry.
"""
return {
platform_id: _numeric_subdirs(
os.path.join(roms_resources_path, str(platform_id))
)
for platform_id in _numeric_subdirs(roms_resources_path)
}
@dataclass
class CleanupStats:
"""Statistics for cleanup operations."""
@@ -107,11 +136,10 @@ class CleanupOrphanedResourcesTask(PeriodicTask):
)
# Count total platforms and ROMs for progress tracking
platform_dirs: set[int] = {
int(entry.name)
async for entry in roms_resources_dir.iterdir()
if entry.name.isdigit() and await entry.is_dir()
}
rom_dirs_by_platform: dict[int, set[int]] = await asyncio.to_thread(
_scan_resource_dirs, roms_resources_path
)
platform_dirs = set(rom_dirs_by_platform)
# An empty library alongside artwork on disk is far more likely to be a
# database that is unavailable or mid-migration than one that was really
@@ -125,16 +153,6 @@ class CleanupOrphanedResourcesTask(PeriodicTask):
)
return cleanup_stats.to_dict()
rom_dirs_by_platform: dict[int, set[int]] = {}
for platform_dir in platform_dirs:
platform_path = os.path.join(roms_resources_path, str(platform_dir))
platform_dir_path = AnyioPath(platform_path)
rom_dirs_by_platform[platform_dir] = {
int(entry.name)
async for entry in platform_dir_path.iterdir()
if entry.name.isdigit() and await entry.is_dir()
}
cleanup_stats.update(
platforms_in_fs=len(platform_dirs),
roms_in_fs=sum(len(rom_dirs) for rom_dirs in rom_dirs_by_platform.values()),

View File

@@ -1,3 +1,4 @@
import os
from types import SimpleNamespace
from unittest.mock import patch
@@ -126,3 +127,55 @@ class TestCleanupOrphanedResourcesRun:
assert stats["platforms_in_fs"] == 0
assert stats["removed_fs_platforms"] == 0
class TestScanResourceDirs:
"""The resource tree walk backing the cleanup task."""
@staticmethod
def _make_tree(root, layout: dict[int, list[int]]) -> None:
for platform_id, rom_ids in layout.items():
for rom_id in rom_ids:
(root / str(platform_id) / str(rom_id)).mkdir(parents=True)
def test_maps_platforms_to_rom_dirs(self, tmp_path):
self._make_tree(tmp_path, {1: [10, 11], 2: [20]})
assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10, 11}, 2: {20}}
def test_ignores_non_numeric_names(self, tmp_path):
self._make_tree(tmp_path, {1: [10]})
(tmp_path / "not-a-platform").mkdir()
(tmp_path / "1" / "not-a-rom").mkdir()
assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10}}
def test_ignores_files(self, tmp_path):
self._make_tree(tmp_path, {1: [10]})
(tmp_path / "2").write_text("stray file named like a platform")
(tmp_path / "1" / "20").write_text("stray file named like a rom")
assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10}}
def test_empty_tree(self, tmp_path):
assert mod._scan_resource_dirs(str(tmp_path)) == {}
def test_platform_with_no_rom_dirs(self, tmp_path):
(tmp_path / "1").mkdir()
assert mod._scan_resource_dirs(str(tmp_path)) == {1: set()}
def test_unreadable_directory_yields_empty_set(self, tmp_path):
# A directory that disappears or denies access must not abort the walk,
# otherwise one bad platform would strand every other platform's orphans.
self._make_tree(tmp_path, {1: [10]})
real_scandir = os.scandir
def flaky_scandir(path):
if path.endswith(os.sep + "1"):
raise PermissionError(13, "Permission denied")
return real_scandir(path)
with patch.object(mod.os, "scandir", side_effect=flaky_scandir):
assert mod._scan_resource_dirs(str(tmp_path)) == {1: set()}