* perf(backend): pipeline multi-command Redis writes
- upload_chunk records a chunk with SADD, EXPIRE and SCARD in one
transaction instead of three round trips, so a failure between them
can no longer leave the chunk set without a TTL.
- bind_to_login_session does its SADD and EXPIRE in one transaction for
the same reason.
- close_login_sessions reads and deletes a session's socket set in one
transaction, so a socket binding in between is not dropped unseen.
- Logout deletes the session and removes it from the user's set in one
pipeline.
- complete_chunked_upload reads the chunk set once instead of SCARD then
SMEMBERS; cancel and invalidate_filter_values_cache delete their keys
in one call.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv
* fix(backend): refuse a socket bind that lands after its session's revocation
- bind_to_login_session checks the login session still exists in the
same transaction as its SADD. Revocation deletes the session before it
reads the socket set, so a bind that finds it gone removes itself and
authenticate treats the socket as anonymous.
- complete_chunked_upload keeps its SCARD fast path and reads the
members only to name the missing chunks.
- cancel_chunked_upload removes the temporary files before touching
Redis.
- Tests check each pipelined write executes as one MULTI/EXEC.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv
* fix(backend): close an upload session before removing its files on cancel
A chunk PUT that passes the session check after the temporary directory
is gone fails with a 500; deleting the session first turns it into a 404.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv
* fix(backend): answer a chunk write cut short by a cancel with 404
A PUT that passed the session check before the cancel removed its
directory fails writing; it now re-reads the session and returns the
same 404 as a PUT that arrives after the cancel, instead of a 500.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv
* chore(backend): remove a stray Redis snapshot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
- Reject installs of a rom missing from the filesystem
- Keep a request created during a device discard indexed
- Hold a strong reference to the device socket keepalive task
- Never raise from emit_permissions_changed after a committed change
- Map only a missing install request to 404, not any KeyError
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 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>
* fix(ra): count RomM's own RA hash match as RetroAchievements verification
The RetroAchievements verification chip, the header Verified badge and the
library verified filter only read Hasheous' `ra_match` flag. RetroAchievements
hashes only part of some ROMs (NDS, PSP), so Hasheous never flags those from
their file hashes, and a ROM RomM matched to its RA game by RA hash still
showed a grey chip.
The RA handler now records `hash_match` in `ra_metadata` whenever the ROM's
RA hash is one RetroAchievements lists for the matched game, whichever route
found the game (hash lookup, Hasheous-supplied id, filename tag, update scan
or a manual edit). The frontend verification helper and the backend verified
filter count it alongside Hasheous' flag. Existing ROMs pick it up on their
next scan.
Fixes#4801
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* style: satisfy trunk isort and no-emdash-in-comment
Sort imports with the repo's .isort.cfg and replace the comment em-dashes
in MetadataTab.vue that trunk flags once the file is modified.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* fix(ra): address code-review findings on the RA hash match
- A HASHES rescan whose RA lookup ran and found nothing clears
`hash_match`, mirroring the Hasheous guard; a lookup that errored keeps it.
- A manual RA id change that can't be resolved no longer keeps the previous
game's `hash_match`.
- `_search_rom` no longer caches a failed hash-list download ({}) as an
empty index for the whole refresh window.
- Update the `verified` filter description and trim the romVerification
header comment.
Step: pr-ready code-review (xhigh --fix)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* fix(ra): don't let a failed hash check block an RA ID lookup
`get_rom_by_id` now treats the hash-list check as secondary: on failure it
logs, keeps a match already recorded for the same game, and still returns
the game. A failed hash-list download raises "RetroAchievements
unavailable" instead of reading as "no match", so scans treat RA as
inconclusive and keep the stored flag.
Addresses the Copilot and Greptile review findings on ra_handler.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* refactor(ra): simplify the RA hash-match verification
- Cache the parsed RA hash index per platform, keyed by the cache file's
mtime, so a scan parses it once instead of once per ROM.
- Check the hash only after `get_rom_by_id` has resolved the game.
- Give each frontend verification database its own `matches(rom)`, which
drops the `ra_match` special case in the shared helper along with
`matchesDatabase` and `VERIFICATION_KEYS`.
Step: pr-ready simplify
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* style(v2): polish romVerification naming and comment
Rename the Hasheous matcher factory to `anyHasheousFlag` and trim the
VERIFICATION_DATABASES comment to two lines.
Step: pr-ready review-polish
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
* fix(ra): keep a recorded hash match only for the same RA hash
When the hash-list check fails, `get_rom_by_id` now keeps a stored
`hash_match` only if both the game and the ROM's RA hash are unchanged, so
a rehashed ROM isn't left verified by a hash nobody checked. The
romVerification tests build on the shared typed `SimpleRom` fixture
instead of casting a bare object.
Addresses the Greptile review findings on ra_handler.py and
romVerification.test.ts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Cap the default selection at the pin limit, settle writes on the live
rom_user, gate pin controls on roms.user.write, dedupe keys server-side,
store resets as SQL NULL, and reuse MediaShelfItem for artwork entries.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The overview's media section was fixed to scraped screenshots plus videos.
Each user can now pin any screenshot (scraped, game folder, their own or a
community upload), any artwork and any video to their own overview, in any
order.
Pins live on rom_user.pinned_media as an ordered list of stable keys
(scraped:<url>, file:<id>, screenshot:<id>, artwork:<key>), written through
the existing PUT /roms/{id}/props. NULL keeps the default selection, so
nothing changes until a user pins or unpins something, and "Reset to
default" returns to it. Keys whose media disappears are skipped, not
pruned.
- The Artwork subtab's shelf becomes MediaShelf, shared with the overview.
- The Screenshots subtab gains a read-only "Scraped" section so scraped
screenshots can be unpinned too.
- Toggles are optimistic and chained so rapid clicks land in order.
- pinned_media is left out of the per-user sort cache bump.
Supersedes #4512.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(backend): read the nullable gallery sorts out of an index
Sorting the gallery by release date, rating or HowLongToBeat time placed
unset roms last with `ORDER BY <column> IS NULL, <column>`. The leading
term is an expression, so MariaDB and MySQL could not read the order out
of `idx_roms_<column>` and filesorted instead. PostgreSQL had the mirror
problem descending: `DESC NULLS LAST` does not match the index's own
order, so it fell back to a sequential scan.
Neither engine paid this once. v2 window fetches send no sidecars, so
each scroll window is its own `ORDER BY ... LIMIT 72 OFFSET n` over the
full filtered set, and `roms` carries a JSON metadata blob per provider
on every row.
Each column now carries a STORED `_unset` flag with an
`idx_roms_<column>_sort` pair the ascending sort leads with, and
PostgreSQL gets an `idx_roms_<column>_desc` for the descending one. Row
order is unchanged in both directions.
Measured on PostgreSQL 16 over 120k roms, first page:
ascending 30.6 ms / 8109 buffers -> 0.074 ms / 13 buffers
descending 33.5 ms / 8091 buffers -> 0.112 ms / 14 buffers
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* fix(backend): rebuild a sort index MariaDB narrowed instead of dropped
Testing the previous commit against MariaDB rather than PostgreSQL alone
turned up a real bug in it.
The two engines leave a dropped generated column in different states:
PostgreSQL drops every index that reads it, while MariaDB and MySQL keep
a composite one over the columns that survive. `_restore_generated_indexes`
only created indexes missing by name, so on MariaDB the rebuild path in
`ensure_roms_columns` (a chain predating 0123) would leave
`idx_roms_<column>_sort` narrowed to the unset flag alone and the
ascending gallery sort walking half an index.
It now reconciles on the columns an index spans, not just its name, and
`_drop_index_sql` gives the two dialects their own DROP INDEX spelling.
Also corrects the flag columns' comments: MariaDB accepts no NOT NULL on
a generated column in either position, so they are nullable in the DDL on
both engines. `IS NULL` never evaluates to NULL, so no row carries one.
Verified on MariaDB 10.11 over 120k roms. The ascending page went from
`rows=116503, Using index; Using filesort` to `rows=72, Using index`,
134 ms to 6 ms, with the same plan once the rom_user join is added.
Migration, schema and flag values also checked under utf8mb3_unicode_ci,
the collation these expressions are most fragile under.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* style(backend): give the sort-flag rationale one home
Greptile flagged the comment blocks in this PR against CLAUDE.md's
comment discipline. The length was a symptom: the same explanation of
why MariaDB cannot index the NULLS LAST emulation appeared in four
places. It now lives once, beside `SORTABLE_NULLABLE_ROM_COLUMNS`, and
the other sites say only what is local to them.
No behaviour change; the migration docstrings are left as they are,
matching the narrative style every recent revision uses.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* fix(backend): drop the sort indexes with the rest of the catalog
Copilot pointed out that `ensure_roms_columns` installs the `_unset`
columns long before 0129 runs, so a chain that stops short and then
downgrades leaves them behind. Checking that turned up a real leak next
to it: 0108's downgrade, which the module documents as removing whatever
of the catalog such a chain still carries, was leaving two indexes.
A descending sort index reads a value column this module inherited
rather than added, so `drop_roms_columns` re-adds that column and the
index over it survives. `_drop_sort_indexes` now takes them explicitly.
PostgreSQL only, since no other engine has those indexes.
The flag columns themselves are not a leak: the catalog front-loads every
column it owns, so at 0127 the table already carries 0123's
`generated_keywords`, `generated_themes` and `generated_rating_count`
too. Verified on both engines that a 0128 to 0127 downgrade leaves the
table writable with the flags still computing, and that re-upgrading
restores the pair, narrowed index included.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* style(backend): tighten the teardown docstrings and the test annotation
Two more from Greptile, both worth taking even though the reasoning
behind each was off.
`_drop_sort_indexes` and its test now carry a summary plus one line,
matching `drop_roms_columns` right above them, and the parametrized
metadata argument is typed instead of a bare `dict`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* perf(backend): index the remaining gallery sorts (#4644)
* perf(backend): span the gallery sort indexes through the id tiebreak
The gallery appends `id` to every ORDER BY, but `idx_roms_<column>_sort`
stopped at the value and `idx_roms_<column>_desc` at the value alone. On
PostgreSQL that leaves every tie to be sorted, and unset metadata is a single
tie covering the whole bucket: a scroll window inside it fell back to a Seq
Scan and an external merge sort. Both indexes now carry `id` in the sort's own
direction, which InnoDB was already appending for MariaDB and MySQL.
Measured on 120k roms, a window at offset 100000 (inside the unset bucket),
all three columns, both directions:
PostgreSQL ascending 119 ms, external merge sort -> 15 ms, index only
PostgreSQL descending 92 ms, incremental sort -> 13 ms, index only
MariaDB, both already index-only; unchanged
No sort node remains in any of the twelve plans. Also trims the docstrings and
comments this change touches to the repo's one-or-two-line rule.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* test(backend): pin the reflected order of the descending sort indexes
The existing assertion read column names only, which a default ascending index
satisfies just as well, and `AUTOGENERATE_EXEMPT_INDEX_NAMES` keeps the drift
check away from these. Asserts the reflected `column_sorting` instead, and its
absence on the ascending pair.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* fix(backend): declare the unset flags nullable, as their DDL is
`Mapped[bool]` inferred NOT NULL while both engines create the column nullable,
MariaDB because it takes no NOT NULL on a generated column. The four generated
columns beside them already match their DDL. The annotation stays `bool`, since
`IS NULL` never yields NULL.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8
* fix(backend): renumber the gallery sort revisions after 0132
master gained its own 0129-0132 while this branch was open, and both
chains started from 0128_hltb_main_story_column, leaving alembic with
two heads (`upgrade head` fails with MultipleHeads).
0129_indexed_gallery_sorts -> 0133, now revising 0132_audit_events;
0130_gallery_sort_indexes -> 0134. No content change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC
* fix(backend): re-chain the renamed gallery sort revisions onto 0132
The previous commit renamed the files but left their revision IDs and
parent as they were. 0133 now revises 0132_audit_events, and both IDs
match their filenames.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
- Hoist the file MD5 onto FSHandler; drop the blob handler copy
- Share path splitting, slot recency, cached MD5 and ROM visibility helpers
- Remove dead code (get_state_by_path, RomFile.file_ids, unused params)
- Scope WebDAV rom listing to one query; look up a single platform by slug
- Query saves once per manifest and batch ROM name resolution
- Read only the requested PSP bundle member; hash bundles from memory
- Single separator-safe lexical check in validate_path; same joined-path
validation in write_file_streamed
- Stop stripping + on ROM rename, the download path encodes it (#2746)
- Trim comments to the repo's comment rules
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(backend): make type ignores match what mypy reports
Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.
Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.
Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.
The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp
* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes
A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.
endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.
handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.
handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.
endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.
tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.
Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp
* fix(backend): keep gamelist media keys in one place
Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.
The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The ROM list and /roms/filters responses already validate every
filter_values key as a list, so the API never sends nulls. Make that
contract explicit: the handler now returns RomFiltersDict directly
(moved to handler/database/rom_filters.py to avoid an import cycle),
which drops the mypy typeddict-item ignores in the endpoints. Endpoint
tests pin that every key is present and a list, including for a ROM
with no metadata and with with_filter_values=false.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`GET /api/roms/{id}/files` 500'd on its success path: `RomFileSchema` reads
`is_top_level`, which needs `file.rom`, and `get_rom_file_by_id` only loaded
`track_meta` and `doc_meta`. Validation happens after `begin_session` closes,
so the lazy load raised `DetachedInstanceError`. The parent rom now comes
along in the same load, narrowed to the columns `Rom.full_path` needs.
`last_modified` is nullable in the column but was required in the schema, so
a row added outside a scan validated to nothing. It is now nullable to match,
and the regenerated frontend type follows.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* perf(backend): resolve roms without the related load in the file and props routes
Eleven routes opened with `get_rom(id)` to reach two scalars: `id` for the
404 and `id` plus `platform_id` for `assert_rom_visible`. `get_rom` runs the
whole `with_details` eager load, so each request paid for the platform,
files, metadata, saves, states, screenshots, rom_users, siblings,
collections and notes of the rom. The bulk delete was worse: it ran inside a
per-id loop, so an N-id delete ran the graph N times.
Three narrow projections replace it, alongside the `get_rom_visibility` that
#4587 added for the rom-note routes:
`get_rom_visibility` id, platform_id
`get_rom_visibility_label` the above plus the name pair the file-delete
log lines print
`get_rom_deletion_target` the above plus fs_path and the joined platform
label the bulk delete logs when a rom's file is
already missing from disk
`assert_rom_visible` accepts either narrow row as well as a full `Rom`, so
the check itself is unchanged for every other caller.
Statement counts per request, captured with the `executed_statements`
fixture in `tests/endpoints/roms/test_visibility_loads.py`:
PUT /api/roms/{id}/props 19 -> 9
GET /api/roms/{id}/soundtracks/metadata 15 -> 5
GET /api/roms/{rom_id}/files/{file_id}/progress 20 -> 8
DELETE manuals / walkthroughs / screenshots /
soundtracks files 20 -> 8 each
DELETE /api/roms/{rom_id}/files/{file_id} 20 -> 8
GET /api/roms/{id}/files (hidden 404) 25 -> 13
GET /api/roms/{id}/files/content/{name} 25 -> 13
POST /api/roms/delete, 1 id 16 -> 6
POST /api/roms/delete, 5 ids 64 -> 14
The marginal cost of each extra id in a bulk delete falls from 12 statements
to 2.
The upload handlers on the same routers are left alone: `receive_rom_file`
hands the rom to `prepare_upload_destination`, so they need the full entity.
`Rom.fs_resources_path` moves its format string into a module-level function
so `RomDeletionTarget` can compute the same value.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* docs(backend): trim the change rationale out of the new docstrings
Greptile flagged the module docstring in the new test file, `_rom_lookup` and
`RomDeletionTarget` for carrying the reasoning behind the change rather than
describing what the code does. The rationale lives in the commit message and
the PR body, so the docstrings keep only the one sentence a reader needs.
The `assert_rom_visible` docstring loses the paragraph added alongside the
widened type union, which restated what the signature already shows.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(roms): share one rom factory in the visibility-load guard
Step 3 of the pr-ready gauntlet (simplify). The bulk-delete test built its
three roms from an inline `Rom(...)` literal; `test_random.py` already keeps a
module-local `_add_rom(platform, name)` for exactly this, so the guard grows
the same helper instead of a second copy of the field list.
`_flat` had one caller, so it folds into `_rom_lookup`.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* perf(backend): check rom-note visibility without the related load
The five `/api/roms/{id}/notes*` routes each opened with `get_rom(id)` to
reach two scalars: `id` for the 404 and `id` plus `platform_id` for
`assert_rom_visible`. `get_rom` runs the whole `with_details` eager load, so
every note read or write paid for the platform, files, metadata, saves,
states, screenshots, rom_users, siblings, collections and notes of the rom,
about 12 statements.
`DBRomsHandler.get_rom_visibility` selects those two columns and nothing
else, and `assert_rom_visible` now takes the `RomVisibility` row it returns
as well as a full `Rom`, so no other caller of the check changes.
Measured on a 3,000-rom library with 300 notes on the target rom, one admin
request:
GET /api/roms/{id}/notes/identifiers 17 statements / 30,059 bytes -> 5 / 8,066
POST /api/roms/{id}/notes 17 statements / 23,209 bytes -> 5 / 1,216
The server-side `Questions` delta per request falls from 33 to 21.
The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(roms): match the rom lookup across dialects
The notes-load guard pinned the exact SQL text of the visibility lookup,
including MariaDB's `?` bind placeholder. psycopg renders the same query
as `%(id_1)s::INTEGER`, so the assertion could never match on the
PostgreSQL leg of the CI matrix and all three tests would have failed
there. Compare a dialect-independent prefix instead.
Step 2 of the pr-ready gauntlet: correctness fix plus the comment and
docstring trims it flagged.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test: drop the second copy of the statement-capture fixture
`test_released_days.py` carried its own `captured_sql`, the same
before_cursor_execute listener the notes-load guard now shares as
`executed_statements` from tests/conftest.py. Point that file at the
shared fixture and drop the now-unused imports.
Step 3 of the pr-ready gauntlet: reuse and simplification fixes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test: name the notes auth helper as the other endpoint tests do
Seven endpoint test modules already define `_auth` for the bearer header;
this file introduced a third name for the same one-liner.
Step 4 of the pr-ready gauntlet: review-polish consistency pass, after
trunk fmt and the affected-suite run.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* fix(backend): project the identifier endpoints onto the id column
The `/identifiers` routes for saves, states, firmware, platforms, smart
collections and rom notes each asked their handler for entities with
`only_fields=[Model.id]`. `load_only` narrows the selected columns but does
not cancel an eager relationship, so a `lazy="joined"` join still fired and a
full entity was still built for every row. The platforms route was the worst
of the six: `with_firmware` eager-loads every firmware row and its platform,
and `load_only` does not cancel that either.
Each handler grows a small query builder shared by its existing accessor and a
new `*_ids` accessor that projects onto the id column with
`with_only_columns`, which drops the entity and with it the eager joins. The
firmware accessor already applied `noload`, so its SQL is unchanged; it moves
to the projection only to stop building rows.
`/api/users/identifiers` and the two `/collections` callers that use more than
an id are left alone, because nothing eager fires for them.
The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* Update backend/tests/endpoints/test_identifier_endpoints.py
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
* style(backend): drop the leading blank line black rejects
Removing the module docstring in the GitHub edit left an empty first line,
which is the only thing black wanted to change.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(backend): drive the note-identifier test through the endpoint
Greptile flagged the handler-level test for bypassing the route's auth,
404, and visibility checks. It now issues the request the frontend would
and asserts the id-only projection holds among the route's own reads.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* refactor(backend): fold the duplicate SQL-capture fixtures into the shared one
Step 3 of the PR-ready gauntlet (simplify). The shared
`executed_statements` fixture gains the two roms test files that still
declared byte-identical local copies, and the id-only assertions share one
statement parser instead of two.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* docs(backend): tighten the get_platform_ids docstring to one line
Step 4 of the PR-ready gauntlet (review-polish).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Review polish over the whole change: every comment block over two lines
cut back, and the two carrying change history rather than current
behaviour rewritten to describe what the code does now.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
Three defects the review pass turned up:
`from_stored_criteria` raised on a smart collection whose stored
`filter_criteria` holds a value the model rejects. That JSON is written
unvalidated and read in a loop over every smart collection, so one bad row
stopped all the later ones from refreshing on any ROM write, and 500'd a
public smart collection. It now drops the entries it cannot honour, which
is what the criteria reader did before it validated anything.
Two comments claimed `metadata_providers` matches id columns on `Rom`. It
matches them on the facets mirror, so a reader trusting the comment
concludes the filter needs no join and cross-joins `roms_facets` into the
query. Corrected, and pinned by a test asserting every registered filter
joins the mirror exactly once.
`as_query_dependency` silently mis-built a route for a field with an alias
or a `default_factory`, the latter sharing one mutable default across
requests. Both now fail at startup, and the helper has the tests it
shipped without.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
Resolves the overlap with #4463's per-user sidecar cache versions: the
endpoint keeps the resolved sort key while adopting master's
normalise-once ordering params and single sidecar cache key, and
`sorts_by_rom_user_column` now answers from `_resolve_gallery_sort_key`
so the cache key and the ORDER BY agree on what a RomUser sort is.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Every multi-value filter matched against either `roms` or the
`roms_metadata` view over it. Both carry the raw provider-metadata blobs
inline, so evaluating a facet predicate reads the whole wide table, and no
index can serve a JSON containment test.
`roms_facets` already holds exactly these values in a narrow, trigger-
maintained mirror (0100, extended by 0103 and 0112), and the dropdown
queries and the stats coverage breakdown already read it for this reason.
The filters now read it too, so applying any of them costs one join to a
table that is a fraction of the size.
On a seeded 40k-game library (139 MB of `roms` against 8 MB of
`roms_facets`, stock 128 MB buffer pool), through `filter_roms`:
total count 374 ms -> 70 ms
rom id index 615 ms -> 74 ms
page (limit 50) 1.5 ms -> 1.3 ms
Both sidecars run on every gallery request, since `with_total` and
`with_rom_id_index` default on. The page query was already fast: it stops
early on an indexed sort, so it never had to evaluate the predicate for
the whole library.
Matching is unchanged: every mirrored column is byte-equal to its source
across all 40k rows, no rom is missing its facets row, and each filter
selects the same ids as before under every logic operator. The mirror also
covers the provider id columns, so `metadata_providers` moves with the
rest rather than being the one filter left reading `roms`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
The filter vocabulary (13 multi-value filters with their logic operators,
plus the boolean and scope filters) was written out in five places: the
`/api/roms` query parameters, `filter_roms`'s 63-line signature, the
`kwargs.get` block in `get_roms_scalar`, the criteria translation in
`get_smart_collection_criteria`, and the `is_unscoped` test that decides
what may be cached.
That last one is the dangerous copy. The gallery's sidecar caches are keyed
on user/order/grouping but not on the filters, so a filter missing from
`is_unscoped` would let one user's narrowed gallery be stored under, and
served from, the shared "all" key.
`RomFilterParams` becomes the single home. The route takes it as a
dependency, `filter_roms` reads its fields, and smart collections rebuild
it from their stored criteria (legacy `selected_*` keys and the
`platform_id` scalar included, keeping `from_stored_criteria` the only
place that knows about them). `has_filters` now reads the model's own
fields, so a filter added later counts towards the cache gate without
anyone remembering to list it, and a test asserts that for every field.
The route reaches the model through `as_query_dependency` rather than
`Annotated[RomFilterParams, Query()]`, because FastAPI expands a query
model into its fields only when the model is a route's *only* query
parameter. `/api/roms` has a dozen others, so the native form would leave
one required parameter named `filters`: the schema would advertise it, the
generated client would be built from that, and a request carrying the
fields themselves would be rejected. A dependency's parameters are
flattened individually, so building one from the model keeps the fields.
An endpoint test pins that, since the failure is silent.
The API contract is unchanged: `/api/roms` still takes the same 58 query
parameters with identical types, descriptions, defaults and constraints,
and regenerating the frontend types from the new schema produces a
byte-identical `src/__generated__`. Only the order of the parameters in
the OpenAPI array differs, since FastAPI lists a dependency's parameters
after the route's own.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
The ten JSON-array facet filters (genres, franchises, collections,
companies, publishers, developers, age_ratings, regions, languages, tags)
had ten near-identical `_filter_by_*` methods differing only in the column
they matched on, and `filter_roms` then restated the same vocabulary twice
more: once in `filters_to_apply` and once in the `needs_metadata_join`
list that decides whether the query joins `roms_metadata`.
That second list is the risk: a new metadata-backed filter that is added
to `filters_to_apply` but forgotten in `needs_metadata_join` compiles and
runs, but silently cross-joins `roms` against `roms_metadata` under
`group_by_meta_id`, ranking the whole library instead of the matches.
Introduce `ROM_FILTER_SPECS`, one declarative row per filter carrying its
name, how its values are matched and the column they match against. The
join decision is now derived from the column's own mapper, so it cannot
drift from the filters it guards, and one `_apply_filter_spec` replaces
the ten methods.
`statuses` stays in `filter_roms`: it matches against RomUser, runs after
the grouping window rather than with the rest, and carries the default
"hide hidden roms" behaviour.
The generated SQL is byte-identical across 18 cases covering every filter,
all three logic operators, grouping and per-user scoping.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
Review follow-up from Greptile on the PR: the aggregate masked only the
personal RomUser.hidden flag, so a sibling hidden through admin
hidden_rom_ids/hidden_platform_ids could still drive its group's
position. The admin visibility filters now apply before the dedup
window builds, so a permission-hidden sibling can neither represent a
group nor feed its sort key, and a permission-hidden representative no
longer hides its whole group.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Polish pass: the A-D sweep found the merged diff already in shape;
one three-line parameter comment ran long. 165 tests across the
affected suites pass on the merged tree and trunk fmt/check are clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Simplify pass:
- get_roms_query returns the resolved _GallerySortKey and filter_roms
accepts it, so one request resolves the sort once and the grouped
aggregate cannot disagree with the ordering the query was built with.
- _GallerySortKey carries a single source tag instead of two mutually
exclusive booleans.
- _rom_user_not_hidden() replaces the three copies of the null-safe
visibility predicate.
- _GROUP_SORT_AGGREGATE_TYPES trimmed to the types RomUser has
(DateTime, Integer); Date/Numeric were unreachable.
- order_dir normalizes once per entry point.
Skipped, deliberately: folding dedup_subquery into the join condition
(plan-pinned SQL) and a single-owner ORDER BY refactor (touches every
get_roms_query caller). Compiled SQL is unchanged, per the shape tests.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Review follow-ups from Copilot and Greptile on the PR:
- The after_commit flush now pops the queued bumps and the armed flag,
so a reused session's next transaction re-arms instead of queueing
into a map nothing will flush; a rollback discards the queue the
same way.
- A cache failure after commit logs instead of raising: the write is
already durable, so a transient Redis error must not turn a
successful mutation into an apparent failure.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Code-review pass fixes:
- A hidden sibling's key is masked to NULL inside the group aggregate,
so a rom the user hid can no longer drive its group's position.
- The aggregate shares row_number's window spec with a whole-partition
frame, so MariaDB sorts the derived table once instead of twice.
- _mapped_sort_column resolves order_by only to mapped columns; a
relationship or dunder name now falls back to the name sort instead
of raising while the ORDER BY is built.
- filter_roms takes everything after the query keyword-only.
- Tests: hidden-sibling behavior test, grouped id-index test, the
covering-index check compiles the window-level SELECT, alias-free
ORDER BY assertions, MariaDB-dialect null-safe join assertion, and
_make_rom/_ordered_names replace the copied fixture helpers.
Known and deliberate, per review: the aggregate is direction-dependent
(MAX on desc, MIN on asc), rating's 0 sentinel stays a real key, and
non-aggregated (enum, lexical, roms-side) keys keep representative
semantics. The stale-sidecar gap it flagged is fixed separately by the
per-user cache versioning PR.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Simplify pass over the sidecar invalidation change:
- Split the per-user version into sort (sidecar:user_ver) and sibling
(sidecar:user_sib_ver) counters so an is_main_sibling toggle only
refreshes grouped-gallery entries, not every sorted index.
- Queue cache bumps in session.info and flush them once from a one-shot
after_commit listener, deduped per user, instead of bumping inline
(and possibly repeatedly) before the write is durable.
- Give unscoped filter values their own cache key builder instead of
overloading the sidecar key with kwargs.
- Normalize order_by/order_dir casing once at the top of get_roms and
hoist the single sidecar cache key shared by the char and id indexes.
- Rework TestRomUserCacheVersion delta-style; the add-bump test now
seeds its own bare rom since the rom fixture pre-pairs admin_user.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Code-review pass: the cache key builder lowercases order_by before the
version gate (a mixed-case sort cached under an unversioned key that
writes never rotated); grouped galleries embed the per-user version
too, since is_main_sibling picks their representative; the bump moved
to an after_commit hook so a rollback never bumps and a concurrent
reader cannot cache pre-commit rows under the new version; and the
filter-values sidecar opts out of the rotation, since hidden, the one
RomUser column it reads, already bumps the global version.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
The rom_id_index/char_index sidecars are memoised under keys whose
version only hidden writes bump, so a gallery sorted by a per-user
column kept serving the pre-write order for up to seven days after a
play, a rating, or a status change.
update_rom_user now bumps a per-user version counter, and the unscoped
sidecar cache key embeds it whenever the sort resolves to a rom_user
column, so every writer (the props endpoint, save and state uploads,
play sessions, the RetroAchievements sync) invalidates exactly that
user's per-user-sorted entries. Name and metadata sorts keep their
shared keys, the global hidden bump is untouched, and superseded
per-user entries age out by TTL instead of needing keys-set
bookkeeping.
Fixes#4448
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
With group_by_meta_id, the sibling-dedup window picks each group's
representative by main-sibling/prerelease/region rank, and the outer
ORDER BY only ever saw that rom's own sort key, so a group whose
rank-preferred copy was never touched sorted into the NULL tail even
when another sibling was played yesterday.
RomUser-column sorts now aggregate the key across the group inside
the existing window pass (MAX descending, MIN ascending, so a group
lands in the NULL bucket only when every sibling's key is NULL), and
the outer ordering reads that group value through a null-safe outer
join that keeps the covering-index plan (the inner-join and CTE
shapes measured 3-7x worse; this one is ~1.55x master on the one
family it fixes and compiles byte-identically everywhere else). The
displayed representative stays the rank-preferred one. Metadata and
Rom-side grouped sorts keep representative order deliberately, since
materializing a roms-side key into the window drops it off
idx_roms_sibling_cover, the regression migration 0107 prevents.
Fixes#4447
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Simplify pass: the dialect-aware NULL placement becomes a module
helper shared with the music-track ordering, which gains index-order
reads in the three cases that never needed the emulation term. The
zero-as-unset rule moves from a name frozenset onto the columns
themselves (mapped_column info markers), the ordering block stops
rebinding one name through four types, driver pinning collapses into
two conftest fixtures, and the dialect matrix lives in one
parametrized test instead of two per-family copies.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Code-review pass: the rom_user and metadata NULL handling collapse
into a single block built from the folded sort key, with PostgreSQL
on native NULLS LAST for both families and the leading IS NULL term
emitted only where an engine needs it (non-PG ascending), so the
redundant terms and the raw-vs-folded hazard are gone. The zero-as-
unset column set moves to models/rom.py beside the columns it
describes, the hltb query-shape test folds into the metadata
parametrize, and the comments that overclaimed index behavior after
the change now state the measured cost instead.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
Ascending rating/difficulty/completion sorts split visually identical
"unrated" games into two buckets: touched-but-unrated rows carry the
NOT NULL default 0 and led the list while never-touched games trailed
it. The three zero-default sort keys are now wrapped in NULLIF(col, 0)
so both unset shapes share the final bucket, tiebroken by rom id.
Metadata sorts kept each engine's default NULL placement: MariaDB led
ascending release-date sorts with the wall of unmatched roms while
PostgreSQL trailed it. NULLs now land last on every engine in both
directions, emitted per dialect to keep index reads where the engine
allows them: PostgreSQL uses native NULLS LAST, MariaDB descending
already places NULLs last on the plain index read, and only MariaDB
ascending pays a measured filesort (EXPLAIN at 30k roms: 51ms index
read to ~150ms), the one case the engine cannot serve from a
single-column index.
Fixes#4449Fixes#4450
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L