Files
romm/backend/tests/handler/auth/test_rom_visibility.py
Ryan Farthing c6b5f0ae11 fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes (#5313)
* fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes

Platform.rom_count and fs_size_bytes are column properties over every rom
row on the platform, and the platform endpoints only filter hidden
platforms. So the platform header's "In library" count and "On disk" size
included roms hidden from the caller (directly, or by an age limit), while
the gallery left them out. Server Stats was off the same way: its
per-platform metadata coverage divides /api/stats' visibility-filtered
match counts by the unfiltered rom_count, so a restricted user saw
coverage too low and platform counts and sizes too high.

For a restricted caller, the list, detail and update endpoints now subtract
the totals of the roms RomVisibilityFilter hides
(DBStatsHandler.get_hidden_rom_totals_by_platform, next to the other
per-platform aggregates). Direct hides are matched by primary key, so a
few hidden roms cost a few lookups rather than a pass over every rom on
the platform. Admins and other unrestricted callers keep the model's
values and skip the query.

On a generated library of 50 platforms and 100k roms (MariaDB), the
platform list takes ~44 ms; this adds ~4 ms with 100 roms hidden, ~44 ms
with 5,000, and ~60 ms with an age limit (min_age isn't indexed, so that
case scans the platforms' roms).

Fixes #5312

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): read the hidden roms' totals in the platform query

Addresses Greptile's review of #5313:

- Counts can become negative: the hidden totals came from a second query,
  so a rom added between the two could be subtracted without having been
  counted. They now come from a grouped subquery outer-joined into the
  statement that computes the full totals, so both read one snapshot (on
  PostgreSQL's READ COMMITTED too, which a shared transaction wouldn't
  give).
- Counting rules live in endpoints: the endpoint helper is gone.
  get_platform and get_platforms take the caller's RomVisibilityFilter
  (unrestricted by default) and return platforms with the visible totals;
  DBStatsHandler.get_hidden_rom_totals_by_platform is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): code-review fixes for visible platform totals

- Re-read rows with populate_existing so a shared session never subtracts twice
- Narrow the hidden-totals subquery to the one platform get_platform reads
- Re-read after update only for restricted callers, and 404 instead of leaking full totals
- Test the update endpoint's restricted totals and the shared-session read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(platforms): simplify pass on visible platform totals

Gate the row clause in one condition with a why comment, fold the MariaDB
narrowing reason into the docstring, and drop restating comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): count only visible roms in /supported and RetroArch listings

- Move the hidden-ROM predicate into RomVisibilityFilter.hidden_on_visible_platforms_clause,
  with the age rule spelled as ranges an index on min_age can serve
- get_platforms reads hidden platforms from the visibility filter instead of a
  second hidden_platform_ids argument
- /api/platforms/supported lists a hidden platform as unmatched and counts only
  the caller's ROMs on the rest
- RetroArch WebDAV skips a platform whose ROMs are all hidden from the caller

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(roms): index platform_id, min_age, fs_size_bytes for age-limited totals

On a 73k-ROM copy of a real library (MariaDB 13), GET /api/platforms for an
age-limited user went from 208 ms to 55 ms: the hidden-totals aggregate is now
an index-only scan instead of a full scan of the wide roms rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-29 10:48:04 -04:00

183 lines
6.1 KiB
Python

"""Pure unit tests for the shared ROM visibility rule (no DB needed)."""
from tests.sql_dialects import MARIADB_DIALECT, compile_sql
from handler.auth.permissions import ResolvedPermissions
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from models.rom import RomFacets, RomVisibility
def _perms(*, is_admin: bool) -> ResolvedPermissions:
return ResolvedPermissions(
is_admin=is_admin,
user_id=1,
grants=frozenset(),
hidden_platform_ids=frozenset({5}),
hidden_rom_ids=frozenset({99}),
)
def test_unrestricted_adds_no_clauses():
assert UNRESTRICTED.is_unrestricted
assert UNRESTRICTED.clauses() == []
assert UNRESTRICTED.allows(RomVisibility(id=99, platform_id=5, min_age=None))
def test_hides_by_platform_and_by_rom():
visibility = RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
assert not visibility.is_unrestricted
assert not visibility.allows(RomVisibility(id=1, platform_id=5, min_age=None))
assert not visibility.allows(RomVisibility(id=99, platform_id=6, min_age=None))
assert visibility.allows(RomVisibility(id=1, platform_id=6, min_age=None))
def test_clauses_filter_the_given_columns():
visibility = RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
clauses = visibility.clauses(
platform_id_col=RomFacets.platform_id, rom_id_col=RomFacets.rom_id
)
assert [compile_sql(c, MARIADB_DIALECT) for c in clauses] == [
"(roms_facets.platform_id NOT IN (__[POSTCOMPILE_platform_id_1]))",
"(roms_facets.rom_id NOT IN (__[POSTCOMPILE_rom_id_1]))",
]
def test_row_hidden_clause_matches_the_rows_its_rules_keep_out():
visibility = RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
row_hidden = visibility.row_hidden_clause()
assert row_hidden is not None
assert compile_sql(row_hidden, MARIADB_DIALECT) == (
"roms.platform_id IN (__[POSTCOMPILE_platform_id_1])"
)
def test_direct_hides_alone_need_no_row_clause():
assert (
RomVisibilityFilter(hidden_rom_ids=frozenset({99})).row_hidden_clause() is None
)
assert UNRESTRICTED.row_hidden_clause() is None
def test_hidden_on_visible_platforms_clause_skips_hidden_platforms():
visibility = RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
hidden = visibility.hidden_on_visible_platforms_clause()
assert hidden is not None
assert compile_sql(hidden, MARIADB_DIALECT) == ("roms.id IN (__[POSTCOMPILE_id_1])")
assert (
RomVisibilityFilter(
hidden_platform_ids=frozenset({5})
).hidden_on_visible_platforms_clause()
is None
)
def test_the_hidden_age_clause_is_a_range_per_setting():
def sql(visibility: RomVisibilityFilter) -> str:
hidden = visibility.hidden_on_visible_platforms_clause()
assert hidden is not None
return compile_sql(hidden, MARIADB_DIALECT)
assert sql(RomVisibilityFilter(age_limit=12)) == "roms.min_age > :min_age_1"
assert sql(RomVisibilityFilter(age_limit=12, hide_unrated_roms=True)) == (
"roms.min_age IS NULL OR roms.min_age > :min_age_1"
)
assert sql(RomVisibilityFilter(hide_unrated_roms=True)) == "roms.min_age IS NULL"
def test_admin_permissions_are_unrestricted():
assert _perms(is_admin=True).rom_visibility is UNRESTRICTED
def test_user_permissions_carry_their_hides():
perms = _perms(is_admin=False)
assert perms.rom_visibility == RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
assert not perms.can_see_rom(RomVisibility(id=99, platform_id=6, min_age=None))
def _rom(rom_id: int, min_age: int | None, platform_id: int = 1) -> RomVisibility:
return RomVisibility(id=rom_id, platform_id=platform_id, min_age=min_age)
def test_an_age_limit_hides_roms_rated_above_it():
visibility = RomVisibilityFilter(age_limit=12)
assert not visibility.is_unrestricted
assert visibility.allows(_rom(1, 12))
assert not visibility.allows(_rom(2, 17))
# Unrated ROMs stay visible unless asked otherwise.
assert visibility.allows(_rom(3, None))
def test_hide_unrated_hides_roms_no_rating_covers():
with_limit = RomVisibilityFilter(age_limit=12, hide_unrated_roms=True)
alone = RomVisibilityFilter(hide_unrated_roms=True)
assert not with_limit.allows(_rom(1, None))
assert with_limit.allows(_rom(2, 3))
assert not alone.allows(_rom(1, None))
assert alone.allows(_rom(2, 18))
def test_the_age_clause_compiles_per_setting():
def sql(visibility: RomVisibilityFilter) -> list[str]:
return [compile_sql(c, MARIADB_DIALECT) for c in visibility.clauses()]
assert sql(RomVisibilityFilter(age_limit=12)) == [
"roms.min_age IS NULL OR roms.min_age <= :min_age_1"
]
assert sql(RomVisibilityFilter(age_limit=12, hide_unrated_roms=True)) == [
"roms.min_age IS NOT NULL AND roms.min_age <= :min_age_1"
]
assert sql(RomVisibilityFilter(hide_unrated_roms=True)) == [
"roms.min_age IS NOT NULL"
]
def test_the_age_rule_reads_the_facets_mirror_when_asked():
clauses = RomVisibilityFilter(age_limit=12, hidden_rom_ids=frozenset({7})).clauses(
platform_id_col=RomFacets.platform_id,
rom_id_col=RomFacets.rom_id,
min_age_col=RomFacets.min_age,
)
assert [compile_sql(c, MARIADB_DIALECT) for c in clauses] == [
"roms_facets.min_age IS NULL OR roms_facets.min_age <= :min_age_1",
"(roms_facets.rom_id NOT IN (__[POSTCOMPILE_rom_id_1]))",
]
def test_user_permissions_carry_their_age_settings():
perms = ResolvedPermissions(
is_admin=False,
user_id=1,
grants=frozenset(),
hidden_platform_ids=frozenset(),
hidden_rom_ids=frozenset(),
age_limit=10,
hide_unrated_roms=True,
)
assert perms.rom_visibility == RomVisibilityFilter(
age_limit=10, hide_unrated_roms=True
)
assert perms.can_see_rom(_rom(4, 10))
assert not perms.can_see_rom(_rom(5, 13))