Files
romm/backend/tests/handler/database/test_roms_group_by_index.py
Sam Dornan 5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00

155 lines
5.8 KiB
Python

"""The "Group ROMs" dedup window and the index that has to cover it.
Grouping collapses versions of the same game into one gallery entry with a
window function. The window materializes a narrow subquery first, because
carrying the wide `roms` row (every provider's raw metadata) through the window
spills its sort to disk. That narrowing only pays off if the index carries every
column the subquery reads: a covering index is all-or-nothing, so one missing
column drops the plan to a full table scan.
`idx_roms_sibling_cover` was added in 0090 for the `sibling_roms` self-join and
did not cover `flashpoint_id` or `fs_name_no_ext`, which the window needs for
its partition tail and its sort tiebreaker. The gallery issues the grouped query
up to four times per page load (page, count, char index, id index), so the scan
was paid four times over. 0107 widened the index to close the gap.
0108 added `generated_primary_region` for the same reason: region priority ranks
each sibling, and `roms.regions` is JSON that no covering index can carry.
The failure mode is silent, and adding a metadata provider is the way back into
it: a new id column joins the window's COALESCE chain, the index does not follow
it, and the gallery quietly returns to full scans.
"""
import re
from typing import Any, cast
from sqlalchemy import Table, inspect
from sqlalchemy.dialects import mysql
from sqlalchemy.sql import Subquery
from sqlalchemy.sql.expression import Select
from tests.conftest import engine
from handler.database import db_rom_handler
from handler.database.rom_filters import RomFilterParams
from models.rom import Rom
# Taken off the model rather than repeated, so these checks read as "the
# migrations and the window agree with the declared index".
INDEX_COLUMNS = [
column.name
for column in next(
index
for index in cast(Table, Rom.__table__).indexes
if index.name == "idx_roms_sibling_cover"
).columns
]
def _subqueries(clause, found: list[Subquery] | None = None) -> list[Subquery]:
found = found if found is not None else []
for child in clause.get_children():
if isinstance(child, Subquery):
found.append(child)
_subqueries(child.element, found)
elif hasattr(child, "get_children"):
_subqueries(child, found)
return found
def _grouped_query(order_by: str = "", user_id: int | None = None):
query, _ = db_rom_handler.get_roms_query(order_by=order_by, user_id=user_id)
return db_rom_handler.filter_roms(
query=query,
filters=RomFilterParams(group_by_meta_id=True),
order_by=order_by,
user_id=user_id,
)
def _dedup_window_subquery(
order_by: str = "", user_id: int | None = None
) -> Select[Any]:
"""The narrow `roms` subquery the grouped query materializes for its window."""
for subquery in _subqueries(_grouped_query(order_by, user_id)):
if not isinstance(subquery.element, Select):
continue
if any(
getattr(column, "table", None) is Rom.__table__
for column in subquery.element.selected_columns
):
return subquery.element
raise AssertionError("the grouped query no longer materializes a roms subquery")
def _dedup_window_select(order_by: str = "", user_id: int | None = None) -> Select[Any]:
"""The SELECT that computes `row_num` (and any group aggregate)."""
for subquery in _subqueries(_grouped_query(order_by, user_id)):
if not isinstance(subquery.element, Select):
continue
if any(
getattr(column, "key", None) == "row_num"
for column in subquery.element.selected_columns
):
return subquery.element
raise AssertionError("the grouped query no longer builds a row_number window")
def _dedup_window_columns() -> set[str]:
"""The `roms` columns the window selects directly."""
return {
column.name
for column in _dedup_window_subquery().selected_columns
if getattr(column, "table", None) is Rom.__table__
}
def _dedup_window_referenced_columns(
order_by: str = "", user_id: int | None = None
) -> set[str]:
"""Every `roms` column the window's SQL reads, expressions included.
Selecting a bare column is only one way in: a CASE or a function call over
an uncovered column reads it just the same while carrying no `.table`, so
the compiled SQL is what has to be inspected. Compiled at the window level
(which nests the narrow roms subquery), so a sort key aggregated straight
off `roms` is caught too.
"""
sql = str(
_dedup_window_select(order_by=order_by, user_id=user_id).compile(
dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}
)
)
return set(re.findall(r"\broms\.(\w+)", sql))
class TestSiblingCoverIndex:
def test_migrations_create_covering_index(self):
indexes = [
index["column_names"] for index in inspect(engine).get_indexes("roms")
]
assert INDEX_COLUMNS in indexes
class TestGroupByMetaIdCoverage:
def test_dedup_window_reads_only_covered_columns(self):
assert _dedup_window_columns() <= set(INDEX_COLUMNS)
def test_dedup_window_expressions_read_only_covered_columns(self):
assert _dedup_window_referenced_columns() <= set(INDEX_COLUMNS)
def test_dedup_window_excludes_the_wide_metadata_columns(self):
assert not {
column for column in _dedup_window_columns() if column.endswith("_metadata")
}
def test_rom_user_sorted_window_reads_only_covered_columns(self):
# The grouped sort aggregate reads its key off the window's rom_user
# join; a roms-side key would break out of the covering index here.
referenced = _dedup_window_referenced_columns(order_by="last_played", user_id=1)
assert referenced <= set(INDEX_COLUMNS)