test(roms): pin the derived file stats to the subqueries they replace

The with_files path computes multi_file, top_level_file_count and
has_soundtrack in Python; the other path reads them from correlated
subqueries. The differential test asserts both answer the same for a
flat file, a folder with two top-level files, a nested single file, a
soundtrack folder and a rom with no files at all, so neither predicate
can be edited without the other.

Also assert a rom's files load in a fixed number of queries rather than
one per file.

Claude-Session: https://claude.ai/code/session_01J1pbRJBY3PatzkB5skQNEU
This commit is contained in:
nendo
2026-08-22 08:49:42 +09:00
parent 97d2f7b5b7
commit 1c40160201
3 changed files with 258 additions and 8 deletions

View File

@@ -695,8 +695,7 @@ def get_roms(
tags_logic=tags_logic,
group_by_meta_id=group_by_meta_id,
updated_after=updated_after,
# The page's files answer all three flags, so the correlated subqueries
# are only worth running when the caller isn't asking for files.
# The page's files answer all three flags without the subqueries.
include_file_stats=not with_files,
# Siblings and the notes indicator are resolved per page below.
include_siblings=False,
@@ -878,9 +877,8 @@ def get_roms(
if with_rom_id_index:
page_ids = list(rom_id_index[params.offset : params.offset + params.limit])
else:
# Order the page over bare ids, then fetch the rows by primary key.
# Sorting the entity directly carries every JSON metadata blob
# through the sort for a page that only keeps `limit` of them.
# Ordering the entity itself carries every JSON metadata blob
# through the sort, for a page that keeps `limit` of them.
page_ids = list(
session.scalars(
query.with_only_columns(Rom.id)

View File

@@ -772,10 +772,10 @@ Rom.top_level_file_count = column_property(
def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None:
"""Fill the three deferred file-stat columns from an already-loaded file list.
"""Fill the deferred file-stat columns from an already-loaded file list.
Mirrors the subqueries above; keep the predicates in step with them. Note
`RomFile.is_top_level` is a different rule and is not interchangeable here.
These predicates mirror the subqueries above, not `RomFile.is_top_level`,
which answers a different question and disagrees on nested files.
"""
set_committed_value(
rom, "multi_file", any(f.file_path != rom.fs_path for f in files)

View File

@@ -0,0 +1,252 @@
from collections.abc import Iterator
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from sqlalchemy import event
from handler.database import db_rom_handler
from handler.database.base_handler import sync_engine
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory
from models.user import User
LAST_MODIFIED = 1700000000.0
FILE_STAT_FIELDS = (
"has_simple_single_file",
"has_nested_single_file",
"has_multiple_files",
"has_soundtrack",
)
def _add_rom(admin_user: User, platform: Platform, name: str, fs_name: str) -> Rom:
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name=name,
slug=f"{name}_slug",
fs_name=fs_name,
fs_name_no_tags=name,
fs_name_no_ext=name,
fs_extension=fs_name.rpartition(".")[2] if "." in fs_name else "",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
return rom
@pytest.fixture
def fileless_rom(admin_user: User, platform: Platform) -> Rom:
"""A ROM with no file rows at all, as a scan leaves one missing from disk."""
return _add_rom(admin_user, platform, "fileless_rom", "fileless_rom.zip")
@pytest.fixture
def flat_rom(admin_user: User, platform: Platform) -> Rom:
"""A single file sitting directly in the platform's roms directory."""
rom = _add_rom(admin_user, platform, "flat_rom", "flat_rom.zip")
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name="flat_rom.zip",
file_path=rom.fs_path,
file_size_bytes=10,
last_modified=LAST_MODIFIED,
category=RomFileCategory.GAME,
)
)
return rom
@pytest.fixture
def folder_rom(admin_user: User, platform: Platform) -> Rom:
"""A folder ROM with two files side by side at its top level."""
rom = _add_rom(admin_user, platform, "folder_rom", "folder_rom")
file_path = f"{rom.fs_path}/folder_rom"
for file_name in ("game.bin", "readme.txt"):
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name=file_name,
file_path=file_path,
file_size_bytes=10,
last_modified=LAST_MODIFIED,
category=RomFileCategory.GAME,
)
)
return rom
@pytest.fixture
def nested_rom(admin_user: User, platform: Platform) -> Rom:
"""A folder ROM whose only content file sits in a subdirectory."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="nested_rom",
slug="nested_rom_slug",
fs_name="nested_rom",
fs_name_no_tags="nested_rom",
fs_name_no_ext="nested_rom",
fs_extension="",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name="disc.bin",
file_path=f"{platform.slug}/roms/nested_rom/data",
file_size_bytes=10,
last_modified=LAST_MODIFIED,
category=RomFileCategory.GAME,
)
)
return rom
@pytest.fixture
def soundtrack_rom(admin_user: User, platform: Platform) -> Rom:
"""A folder ROM carrying a game file and a soundtrack track."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="ost_rom",
slug="ost_rom_slug",
fs_name="ost_rom",
fs_name_no_tags="ost_rom",
fs_name_no_ext="ost_rom",
fs_extension="",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
file_path = f"{platform.slug}/roms/ost_rom"
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name="game.bin",
file_path=file_path,
file_size_bytes=10,
last_modified=LAST_MODIFIED,
category=RomFileCategory.GAME,
)
)
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name="01.mp3",
file_path=f"{file_path}/ost",
file_size_bytes=5,
last_modified=LAST_MODIFIED,
category=RomFileCategory.SOUNDTRACK,
)
)
return rom
def _fetch_one(
client: TestClient, access_token: str, platform: Platform, *, with_files: bool
) -> dict[str, object]:
response = client.get(
"/api/roms",
headers={"Authorization": f"Bearer {access_token}"},
params={"platform_ids": platform.id, "with_files": with_files},
)
assert response.status_code == status.HTTP_200_OK
items = response.json()["items"]
assert len(items) == 1
return items[0]
@pytest.mark.parametrize(
"rom_fixture",
["flat_rom", "folder_rom", "nested_rom", "soundtrack_rom", "fileless_rom"],
)
def test_file_stats_match_between_derived_and_sql_paths(
client: TestClient,
access_token: str,
platform: Platform,
rom_fixture: str,
request: pytest.FixtureRequest,
) -> None:
"""`with_files=true` derives the flags in Python; `false` reads the subqueries.
Both have to answer the same for every file layout, so this pins the two
implementations to each other rather than to a hardcoded expectation.
"""
request.getfixturevalue(rom_fixture)
derived = _fetch_one(client, access_token, platform, with_files=True)
from_sql = _fetch_one(client, access_token, platform, with_files=False)
assert {field: derived[field] for field in FILE_STAT_FIELDS} == {
field: from_sql[field] for field in FILE_STAT_FIELDS
}
@pytest.fixture
def query_counter() -> Iterator[list[str]]:
statements: list[str] = []
def before_execute(
conn: object,
cursor: object,
statement: str,
parameters: object,
context: object,
executemany: bool,
) -> None:
statements.append(statement)
event.listen(sync_engine, "before_cursor_execute", before_execute)
try:
yield statements
finally:
event.remove(sync_engine, "before_cursor_execute", before_execute)
def test_with_files_query_count_does_not_scale_with_file_count(
client: TestClient,
access_token: str,
platform: Platform,
admin_user: User,
query_counter: list[str],
) -> None:
"""Track metadata is eager-loaded, so files are fetched in a fixed number
of queries rather than one per file."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="many_files_rom",
slug="many_files_rom_slug",
fs_name="many_files_rom",
fs_name_no_tags="many_files_rom",
fs_name_no_ext="many_files_rom",
fs_extension="",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
for index in range(25):
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name=f"{index:02d}.mp3",
file_path=f"{platform.slug}/roms/many_files_rom/ost",
file_size_bytes=5,
last_modified=LAST_MODIFIED,
category=RomFileCategory.SOUNDTRACK,
)
)
query_counter.clear()
item = _fetch_one(client, access_token, platform, with_files=True)
assert len(item["files"]) == 25 # type: ignore[arg-type]
track_meta_queries = [s for s in query_counter if "track_meta" in s]
assert len(track_meta_queries) <= 1