Commit Graph

2283 Commits

Author SHA1 Message Date
Zurdi
1444b0454a Merge pull request #4550 from rommapp/claude/unify-rom-file-uploads
chore(uploads): manual file uploads into a ROM across the Files and Media tabs
2026-09-16 17:18:37 +02:00
zurdi
1f631e7962 Bound the refresh lock wait instead of spinning on sleep
ruff ASYNC110 flags a while loop whose body is only an await sleep. The
wait is now a bounded poll that gives up with a TimeoutError once the
lock expiry has elapsed, so a stuck holder cannot hang the upload.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 17:09:54 +02:00
zurdi
071787311d Take the refresh lock with SET NX instead of a Lua-backed Lock
redis-py releases its Lock through a Lua script, which the fakeredis CI
runs without, so every registration failed there with an unknown evalsha
command. The lock is now a SET NX EX with an owner token, released only
by its owner, the same shape the log forwarder already uses.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 17:03:59 +02:00
zurdi
e869ecb6b6 Enforce media allowlists and walkthrough provenance in the shared upload path
A folder the scanner maps to a media category now refuses files that
category cannot hold inside resolve_upload_destination, so the chunked
flow the v2 tabs use gets the same allowlist the media routes had, and
those routes drop their own copies. commit_upload records an upload
provenance for walkthrough files that arrive without one and returns the
registered row, which the walkthrough route uses for author and title.
The refresh lock moves to Redis so uploads landing on different gunicorn
workers cannot drop each other rows. An empty body filename is rejected
instead of falling back to the header.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 16:27:38 +02:00
zurdi
e8d2e26cff fix(tasks): a worker that announced its death is not live
`has_live_worker` reads each registered worker again and skips the
ones carrying a death date as well as the suspended ones, with both
states covered in the handler test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K
2026-09-16 16:25:13 +02:00
zurdi
be81b1c89b refactor(tasks): apply the simplify pass
`has_live_worker` asks RQ for the worker count and the suspension flag,
two constant-cost reads, instead of hydrating every registered worker.
The cleanup stats serialize through `dataclasses.asdict`, so a new
counter is declared in two places rather than three. The task endpoint
test takes the shared task fixture, the legacy-stats shim says when it
can go, and the two Settings specs share one axios-error helper under
`src/test-utils` while the games spec starts from a non-empty list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K
2026-09-16 16:16:00 +02:00
zurdi
83569d6678 fix(tasks): read older cleanup stats, and check the worker where it enqueues
Follow-up to #4548 from the code-review pass. Stats a 5.2.0 release
stored under `platform_id` are widened to `platform_ids` when a job is
reported, so listing old finished cleanups validates again. The live
worker check moves next to the queues as `has_live_worker`, with its
own tests, and the endpoint names the queue it enqueues on so the check
and the enqueue cannot drift apart. The cleanup tasks return the typed
stats the response schemas declare. The developer setup points the RQ
commands at the backend's own Redis settings through `-c config`, and
the architecture doc mentions the 503.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K
2026-09-16 15:57:59 +02:00
zurdi
f9f68dc0f1 Unify manual file uploads into a ROM across the Files and Media tabs
The Files tab streamed chunks through /roms/upload/* and registered the
result with the scanner listing, while each Media route (soundtracks,
screenshots, manual files, walkthrough files) carried its own copy of the
sanitize, promote, mkdir, stream, stat and DB upsert sequence. Those copies
crashed with FileNotFoundError on a file name outside Latin-1: the browser
sends the header as Latin-1 and the multipart field name as UTF-8, so the
parser target registered under the header name never received the part
and os.stat failed after the folder had been created.

handler/rom_upload.py now owns the shared ingestion (resolve and prepare
the destination, stage next to the target, move into place, refresh the
ROM's file rows through the scanner) and both the chunked completion and a
new receive_rom_file sit on it. The media routes only check the extension
and delegate; a body naming the part differently is a 400. /start gains an
optional body filename that wins over the header, so names outside Latin-1
arrive intact, and rom_id becomes optional in that body.

On the v2 frontend a single useRomFileUpload composable wraps the chunked
upload, the single-file conversion prompt, the toasts and the refetch; the
Files tab, Soundtrack panel, Screenshots subtab, Walkthrough subtab and the
manual "add to ROM folder" target all call it with their folder. The
service sends the real name in the body and a percent-encoded one in the
header. The v2-only uploadScreenshots/uploadWalkthroughFiles service
functions and the soundtrack-only toasts are gone. Media subtabs now
refuse an existing file name (409) like the Files tab, instead of
overwriting it silently.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1FgnCzXjM3rzkxggi7g6C
2026-09-16 15:29:22 +02:00
zurdi
7deb7f8693 refactor(states): share the asset removal helpers with saves
The save and state delete endpoints carried the same row, file and
screenshot removal sequence inline. `remove_asset_file` and
`remove_screenshot` now live in the asset store, and each endpoint
keeps a one-line `_delete_save` / `_delete_state` over them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 10:04:51 +02:00
zurdi
76b80e0e1a refactor(player): apply the simplify pass
Slot pruning is one locked handler query that selects only the tail of
the slot by column, so an upload no longer loads every joined version;
the retention tests share their seeding helpers. Both asset lists fold
their groups through one useGroupFold composable, render the owner chip
through one AssetOwnerChip, and AssetStrip tracks each group's newest
timestamp while it builds the group. The two upload dialogs share a
PendingFilesDropzone for the drop zone and file list. The slot title
and the newest-by-timestamp lookup live in the utils next to their
siblings. The split states layout aligns its label and content rows
with a subgrid instead of hand-matched heights, so AssetPreview loses
the consumer-driven eyebrow height. Stories take explicit ids.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:21:45 +02:00
zurdi
b536aced56 fix(player): apply the code-review findings
Correctness: the upload dialog seeds dropped files immediately (three of
its tests ran vacuously), dedupes them by name, submits on Enter and
rejects a blank slot name; slotted manual uploads are new versions even
when the bytes match; the core picker sees the nightly cores the player
offers; clearing a state hands the boot back to the save it displaced;
a slot or core group can be folded even while it holds the selection
and reopens when the selection moves into it; the entrance stagger
counts only rendered rows; the stream save picker keeps its flat list;
slot retention orders by id as a tiebreaker for same-second uploads.

Reuse: asset helpers shared by both lists move to v2/utils/assets.ts,
the write slot follows the picked save in one place, the upload payload
carries its type, and the endpoint's delete sequence is one helper.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:05:29 +02:00
Georges-Antoine Assi
fa8001c075 fix(scan): send Playmatch as a metadata source so the UI switch works
The Playmatch switch shipped its choice as a standalone `playmatch_enabled`
flag, but the backend gates the lookup on `MetadataSource.PLAYMATCH in apis`
and nothing ever read the flag, so UI-initiated scans never queried
Playmatch. Push `playmatch` into `apis` like `hasheous`, and drop the dead
flag from the payload and the scan plumbing.

Fixes #4505

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 17:23:21 -04:00
Georges-Antoine Assi
c0001bd27d style(streaming): trim the save-picker comments and the emulator compare
review-polish pass over the save-picker change.

Two comments carried more prose than the rule allows. The emulator comparison
re-normalized a value ResolvedContainer already lowercases at resolve time,
which the sibling state resolver relies on, so it now reads the same way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 12:09:45 -04:00
Georges-Antoine Assi
1c5255df1f refactor(streaming): resolve the picked save once and list it like a save
simplify pass over the save-picker change.

The claim validated the pick, dropped the resolved row and passed the bare id
down two layers, where hydration fetched and re-checked the same save. It now
carries the row the way the resume state and the memory card already are, so
the restorability rule has one home and the claim one lookup.

The picker holds the picked id rather than the row, so an id that is no longer
on offer falls back to the newest by construction instead of through a watch,
and the list of archives uses AssetList, the variant meant for saves, rather
than the tile strip whose thumbnail area a save never fills.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 11:58:59 -04:00
Georges-Antoine Assi
73b7725686 fix(streaming): report only the saves the broker can restore
code-review pass over the save-picker change.

The launch screen listed every save this emulator wrote, but the broker only
restores .zip archives, so a bare save file could be named as the one about to
be restored while a much older archive actually went up. One restorable list
now feeds the panel, the tab and the picker alike.

A claim that carries a pick looks the save up by id instead of loading every
save on the ROM to scan for it, and the emulator comparison normalizes both
sides so a config value that is not already lowercase cannot silently match
nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 11:39:46 -04:00
Georges-Antoine Assi
20d44b3bee Merge remote-tracking branch 'origin/master' into streaming-patches
# Conflicts:
#	backend/handler/streaming/states.py
2026-09-15 11:23:42 -04:00
Georges-Antoine Assi
a0aba1f51d Merge pull request #4478 from LoneAngelFayt/feat/streaming-webstation
fix(streaming): prefer the emulator's own screenshot for save-state thumbnails
2026-09-15 08:35:43 -04:00
Georges-Antoine Assi
62b6a7596b docs(streaming): trim the state-screenshot comments
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 07:41:22 -04:00
Georges-Antoine Assi
ef9983fc02 refactor(streaming): one home for the PNG check, one deadline for the frame
The magic-byte test moves behind `_is_png`, so the two places that need it (the
broker body, where the answer decides whether the embedded frame is tried, and
the filesystem sink) read as one rule instead of two. Narrowing the extract
catch back to the failures a savestate archive can raise keeps a programming
error loud rather than logging it as a missing thumbnail.

The frame fetch gets its own 10s deadline: it runs while the claim is still
held and the player waits on the exit screen, and a thumbnail does not need the
archive-transfer budget.

From the pr-ready simplify pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 07:37:33 -04:00
Georges-Antoine Assi
63129edb30 fix(streaming): reject a non-PNG broker frame and inflate off the loop
The broker's screenshot now shadows the frame PCSX2 embeds in its own state,
so a 200 that is not a PNG has to read as no frame rather than as an unusable
one, or the state lands with no thumbnail at all. Extraction moves onto a
thread alongside the fetch it falls back from, since the body it inflates runs
to hundreds of megabytes.

From the pr-ready code-review pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 07:30:06 -04:00
Zurdi
d4f81f097f Merge pull request #4487 from rommapp/claude/graphql-api-migration-vu20z2
refactor(roms): give the ROM filters a single home, and match them against the facets mirror
2026-09-14 23:46:48 +02:00
Zach Clendenen
fb0b389adb style(streaming): trim the save-picker comments to the facts
review-polish pass over the save-picker change.

The comments explaining why an older pick only lands where the broker clears
the save tree said the same thing in four places, so each one now carries only
what its own reader cannot get from the code. The save fixture in the launch
screen test becomes a typed factory, which the emulator-scoping case it did not
cover yet now uses.
2026-09-14 03:02:03 -05:00
Zach Clendenen
a9ec19b3d9 refactor(streaming): look the picked save up by id instead of scanning the list
simplify pass over the save-picker change.

`resolve_save_archive` loaded every save the user has for the ROM just to find
one row by id. `db_save_handler.get_save` is the owner-scoped point lookup the
save endpoints already use for exactly this, so call it and check the rom_id,
which drops a list load per claim that carries a pick.

The ROM scoping moves from the query into the check, so pin it with a test.
2026-09-14 02:51:47 -05:00
Zach Clendenen
b0d33be5b0 fix(streaming): order the launch screen saves the way the backend restores them
code-review pass (xhigh, --fix) over the save-picker change.

The launch screen inherited `user_saves` ordered by `updated_at` from the rom
schema, while the backend picks the archive to restore by `(created_at, id)`.
A content-hash rewrite on an older row was enough to make the two disagree, so
the no-picker panel could name a save the broker would not restore. The list
is now sorted the way the backend orders it.

Also give the restorability rule one home on the backend, so the validator and
the selector cannot drift, and correct a stale comment that still called the
memory card id claimSession's third argument.
2026-09-14 02:43:27 -05:00
Zach Clendenen
107d797292 feat(streaming): let the launch screen pick which save to restore
Containers whose broker clears the save tree before restoring can land an
archive older than the container's own files, so offer the pick there and
validate it at claim time.
2026-09-13 23:57:21 -05:00
Zach Clendenen
16c355e4d2 docs(streaming): correct how non-PCSX2 states get their thumbnail
The docstring said the other emulators write the frame as its own file,
served by /state-screenshot. romm-broker PR 36 removed state_screenshot_path()
from every emulator module and replaced it with a single pixelflux capture of
the stream, so there are no per-emulator frame files left. PCSX2 is still the
only format that embeds one, read only when the broker's capture 404s.
2026-09-13 23:41:51 -05:00
Zach Clendenen
a9aef8a8e9 fix(streaming): take state thumbnails from the broker's frame
The browser capture read #videoCanvas by id, but the default path routes
frames through a MediaStreamTrackGenerator into a hidden #videoStream, so
drawImage returned a transparent bitmap. That still carries PNG magic, so
the backend accepted it and filed a blank thumbnail against a good state.

pull_state_to_library now asks the broker for the container's own capture
first, which is the same route for every emulator, and falls back to an
embedded frame (PCSX2) only when the broker answers 404. The browser
capture, its Redis stash, and the /state-frame endpoint are gone.
2026-09-13 21:33:09 -05:00
zurdi
03d986bd55 fix: address the cover provider review
The providers row dropped a grid provider's match cover whenever that
provider was configured, even when its grid came back empty, so a
timed-out CDN probe hid the one Steam capsule the match had found. The
row now only drops a provider whose result set is actually in the grid.

A source listed twice in the cover priority handed the picker its
covers twice; the priority helper now keeps a source's first position
only, for every caller. The v1 cover dialog keys its panels by
provider as well as name, since both providers can return the same
title. The provider chips grow to the touch target on touch and
gamepad input.

The invalid-key regression test now raises the adapter's own exception
class, and the endpoint gate is covered with Steam as the only enabled
provider. A component test drives the dialog wiring: chips filter the
grid, Steam covers are handed off untouched, and the providers row
keeps a match cover whose grid is empty.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Untv32z88QMZ2yRSsTgGcC
2026-09-14 01:00:34 +02:00
zurdi
1afa59d9de feat: offer Steam as a cover art provider
The cover search dialog only reached SteamGridDB, so a PC game whose
capsule lives on Steam had no way to pick it up short of a full
re-match. Steam now joins SteamGridDB behind `GET /search/cover`,
ordered by the configured cover priority, and each result carries its
provider so the dialog can filter by source and credit the artwork.

The Steam handler builds the picker from the store search alone and
probes the CDN for the portrait capsule and the landscape header under
the same budget the match picker uses, so a slow CDN costs thumbnails
rather than the dialog. Hits with no artwork are dropped.

A failing provider costs only its own covers; a rejected SteamGridDB
key is still reported, since that is the user's to fix. The "search
cover" action in the edit dialog now opens whenever either provider is
enabled, and the game overview credits Steam-hosted covers.

The resource shape the picker consumes moves to the shared base handler
as `CoverResource` / `CoverResult`, since it is no longer SteamGridDB's
alone.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Untv32z88QMZ2yRSsTgGcC
2026-09-14 00:35:08 +02:00
Sam Dornan
4912f8d071 feat: offer Steam as a match provider for PC platforms (#4498) 2026-09-13 16:30:19 -05:00
Sam Dornan
1c20e77e41 Reject unusable smart collection criteria instead of dropping them
The real /code-review and /simplify passes over this PR, which an earlier
run substituted hand review for.

`from_stored_criteria` dropped the entries the model rejects. Dropping a
filter drops the constraint with it, so a row holding
`platform_ids: [3, "gba"]` widened from one platform to the whole library.
It now answers None, and the one caller turns that into a query matching
nothing: the loop over every smart collection still cannot be stopped by
one bad row, and a collection never shows more than its criteria claim.

`/api/roms/download` declared `collection_id` and `smart_collection_id`
unbounded while `get_roms_scalar` validates them through the model, so
`collection_id=0` raised inside the handler as a 500. They now carry the
`ge=1` the other two routes already declare, and fail at the boundary as
a 422.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 06:36:54 +00:00
Sam Dornan
8e61a38b7b Trim comments and docstrings to the repo's limits
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
2026-09-13 04:38:05 +00:00
Sam Dornan
eb190a366b Simplify the review fixes
The tolerant validator rebuilds its input instead of deleting from it in
place, and tests the dropped names against the keys it holds rather than
filtering them out of the error list first.

The router test built two near-identical routes behind a branch; one route
with a plain parameter alongside the model covers both cases it asked
about.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:31:11 +00:00
Sam Dornan
8809f06729 Harden the filter model after code review
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
2026-09-13 04:29:02 +00:00
Georges-Antoine Assi
1250b1231f refactor(streaming): collapse the screenshot source selection
Apply the simplify pass.

The selection ran four interleaved "is None" guards over a preference
boolean and called the broker from two identical sites. Draining the
stash up front makes the whole order one guard: ask the broker when
nothing better is in hand, then fall back to the browser frame.

Tests get a _screenshot_for() builder next to _state_for(), replacing
seven copies of the same seven-field Screenshot construction.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:42:16 -04:00
Georges-Antoine Assi
95a71a6539 fix(streaming): drain the stashed frame and ask the broker once
Apply the code-review pass over the screenshot preference order.

take_state_frame() was the only consumer that deletes the Redis key, so
once an emulator's own frame won, a stashed browser frame survived its
save and could become a later one's thumbnail. Drain it on every pull.
For RetroArch the unguarded final fallback re-issued the identical
/state-screenshot GET, a second blocking 60s request held while the
container reservation is still out. The retroarch literal moves to a
module-level _BROKER_FRAME_EMULATORS, next to the other per-emulator
tables, and extract_state_screenshot() catches anything the zip read
raises so a corrupt embedded PNG costs the thumbnail, not the state.

Tests cover the RetroArch broker preference, its fallback to the browser
frame, and the single broker request when neither source exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:33:14 -04:00
Sam Dornan
d981a897ff Merge remote-tracking branch 'origin/master' into claude/graphql-api-migration-vu20z2
# Conflicts:
#	backend/endpoints/roms/__init__.py
#	backend/handler/database/roms_handler.py
#	backend/tests/handler/database/test_roms_group_by_index.py
2026-09-13 00:32:39 +00:00
Sam Dornan
d145e77f47 Merge remote-tracking branch 'origin/master' into claude/graphql-api-migration-vu20z2
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-13 00:25:37 +00:00
Georges-Antoine Assi
35cab08efc Merge remote-tracking branch 'origin/master' into fix/group-sort-aggregate-4447
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>
2026-09-12 20:12:28 -04:00
Sam Dornan
2f38a33b07 perf(roms): match the gallery filters against the facets mirror
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
2026-09-12 23:32:50 +00:00
Sam Dornan
983e24d5f8 refactor(roms): carry the ROM filters as one model
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
2026-09-12 23:18:56 +00:00
Sam Dornan
08517f14ec refactor(roms): derive ROM filter dispatch from a registry
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
2026-09-12 22:46:46 +00:00
Zach Clendenen
2b77526a81 fix(streaming): prefer RetroArch's own screenshot over the browser frame
The browser-captured canvas frame is a lagging, lossy copy of the video
stream and can hold a torn or missing keyframe right after a scene
change (e.g. pausing), producing a corrupted save-state thumbnail even
though the state itself is fine. RetroArch already writes its own
thumbnail off the core's real framebuffer at save time, so prefer that
for RetroArch and fall back to the browser frame only if it's missing.
Other emulators, which write no thumbnail of their own, are unaffected.
2026-09-12 15:09:32 -05:00
Zach Clendenen
836654c1d4 fix(streaming): prefer PCSX2's embedded screenshot over the browser frame
PCSX2 embeds a screenshot in every .p2s savestate, already in hand from
the state download with no extra round-trip or framebuffer readback
risk. pull_state_to_library() tried the browser-captured frame first
regardless, which produced black thumbnails when that capture missed
the live canvas. Extract the embedded screenshot first for PCSX2 and
fall back to the browser frame only when it's unavailable; behavior
for every other emulator is unchanged since extract_state_screenshot()
always returns None for them.
2026-09-12 15:09:32 -05:00
zurdi
71c55224b1 fix(roms): apply admin visibility before the grouped dedup window
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
2026-09-11 21:07:03 +02:00
zurdi
dd500d77a6 review(pr-ready step 4): tighten the sort_key parameter comment
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
2026-09-11 20:58:35 +02:00
zurdi
67271ebef1 Merge remote-tracking branch 'origin/master' into fix/group-sort-aggregate-4447
# Conflicts:
#	backend/handler/database/roms_handler.py
#	backend/tests/handler/database/test_roms_hltb_length.py
#	backend/tests/handler/database/test_roms_metadata_sort.py
#	backend/tests/handler/database/test_roms_rom_user_sort.py
2026-09-11 20:47:20 +02:00
zurdi
59bda3e6fd review(pr-ready step 3): one sort resolution, one hidden predicate
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
2026-09-11 20:42:52 +02:00
zurdi
ea9063cb0a fix(roms): survive session reuse and cache failures in the bump queue
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
2026-09-11 20:36:31 +02:00
zurdi
6532e0636c review(pr-ready step 2): mask hidden siblings, one window sort, validate order_by
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
2026-09-11 20:31:57 +02:00