- The audit read endpoint keeps the access decision but hands the
category filter to the DB handler, which expands it to actions.
- Trim the log viewer's header comment to two lines and drop its
em-dashes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- record() takes the request as its actor, and a target can be a
function: the lookups that name it now run inside the recorder's error
handling, and for downloads only once the dedupe lets them record.
That also restores the minimal visibility query on the file route.
- One changed_fields/change pair for rom, user, collection and platform
edits, one collection helper, AuditActor.anonymous, a shared
count_in_window and current_device_id, one test helper for recorded
events and one fixture for audit events.
- The describers share simple/counted/visibility builders and the
eventData readers with notifications, join lists per locale, and treat
any *.delete as unlinked.
- EventLog builds one item list with the phase folded in, keeps each
event's sentence across pages, formats days once, and loads users
through the users store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Hide events on roms of a hidden platform from non-admins.
- Pin later pages to the highest matching id the API returns, not the
first row's: rows are ordered by when they happened, so a play synced
late has a higher id than newer events and was dropped.
- Cap recorded failed sign-ins per address, dedupe reset requests and
record them in the background with the email, and hash claim keys.
- Keep another user's private collection by id only in bulk downloads.
- Check a Range start without int(), which raises past 4300 digits.
- Clear the list when a reload fails, load more only once it's shown,
report a cover change only when the user made one, label only rom and
platform unhides, accept an actor kind the API doesn't know.
- One client IP helper, date-fns for today and yesterday, one time
formatter for the list, no em-dashes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A persistent record of what users, or RomM itself, did. Admins read
everyone's events through GET /api/audit-events; anyone else gets only
their own. Events older than AUDIT_LOG_RETENTION_DAYS (90 by default,
0 keeps them) are pruned nightly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A queued delivery checks the channel is still confirmed before it
sends, so mail doesn't reach an address swapped in since it was queued.
- A redirect counts as a failed delivery, naming where it pointed, since
redirects aren't followed and it used to be recorded as sent.
- The per-user channel cap is counted and inserted under a lock on the
user's row, so concurrent adds can't go past it.
- The Channels tab drops a reload that raced a change made meanwhile,
reverts only `enabled` when a toggle is refused, and holds the delete
button while its request runs.
- Trim the migration's docstring to one sentence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A channel's min_level is its own enum (info, warning, error), so the
API refuses `success` and neither the list nor the dialog maps it.
- One home each for the admin-reaches-the-LAN rule (the DB handler now
returns the owner's role) and for describing a failed delivery.
- One webhook config builder for create and update, which drops the
secret of a Discord webhook on both.
- SMTP_SECURITY outside starttls/tls/none leaves email off, so the
heartbeat says so, with a warning at startup.
- The attempts counter gets its TTL in the same round trip as INCR.
- Deliveries group channels by user and serialize a notification only
when a channel wants it.
- The v2 side reuses errorMessage (now with a fallback) instead of its
own detail parsing, mirrors the backend length limits as constants,
shares one channel test factory, and derives `created` on save from
the list instead of carrying it on the event.
- Drop RBadge's inline override, which nothing needs now that an inline
badge gets no anchor class, and trim docstrings to one sentence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each user can add channels that forward their notifications: a webhook
posting RomM's JSON (optionally HMAC-signed), a Discord embed or an ntfy
message, or an email address confirmed with a code. A channel filters by
minimum level and by topic, and every stored notification that passes goes
out in its own RQ job, retried three times; ten failures in a row turn the
channel off and tell its owner.
Channel configs are sealed with a key derived from ROMM_AUTH_SECRET_KEY,
since a webhook URL carries its own token. Only an admin's webhooks may
reach private addresses; everyone else's go through the SSRF guard. Email
goes out over the SMTP_* settings, which the heartbeat reports as
NOTIFICATIONS.EMAIL_ENABLED.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A persisted snackbar toasts at once with the caller's options; what this
tab sends is marked with its tab id, so the socket echo of it adds the row
without a second toast. The toast no longer depends on which of the
request and the push arrives first.
- v2 logout disconnects the socket, which otherwise stays in the user's rooms
until the next login.
- notify_scan_end takes one required outcome, the stats or the error.
- Inboxes are trimmed only for users over the cap, found in one query, and
pushes go out one after another on one Redis connection.
- The log forwarder and the sync emitters use the shared write manager.
- One makeNotification fixture for the frontend tests; small dead code gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- One home for pushing to a user's room: `SocketHandler.emit_to_user`, on a
write-only manager kept per event loop and on the server's own channel.
Streaming's push_to_user and the sync and scan emitters use it too.
- Notifications are stored in one transaction per send, so a broadcast is one
commit, and pushed concurrently. Recipients are resolved from id and
enabled only, and the actor is loaded with just the fields it shows.
- notify_user_or_admins holds the "whoever started it, else the admins"
rule both the scan and the task runner applied by hand.
- A scan notifies from finish(), so no exit path can forget it.
- `data` is never null, dropping its guards; the toast host, the inbox and
the admin form share one tone icon map; the inbox icon uses RAvatar.
- The store keeps its list when a socket echo changes nothing, and small
dead parameters and duplicated lists are gone.
- The socket reconnect after a logout moved from the inbox to AppLayout,
since every v2 feature depends on the socket's identity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Security:
- The netplay socket server shared the main server's Redis channel while
letting unauthenticated clients name their own rooms, so a netplay socket
in room `user:N` or `admin` received that user's pushes and the admin log
stream. Netplay now has a channel of its own.
- Notifying other users also requires users.write on the token, so an admin
token scoped to me.write can only notify its owner.
- The create payload rejects NUL characters, NaN/Infinity in data and an
empty recipients list instead of failing in the database; mark-read takes
at most as many ids as an inbox holds.
Correctness and cleanup:
- The inbox is cleared whenever the signed-in user changes, so a failed
fetch can't leave the previous user's notifications on screen.
- Enter no longer sends the admin form, where an unfinished title would go
out to everyone.
- A notification without its own icon shows its level's, in the list and in
a pushed toast alike, from one LEVEL_ICONS map.
- One write-only Redis manager per event loop instead of one per push.
- Tests for the inbox socket wiring; em-dashes and long docstrings trimmed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Toasts disappear after a few seconds, and nothing reaches a user who has no
tab open. Notifications are now stored per user and kept until dismissed, so
what a background job or another user did is waiting the next time RomM is
opened.
Backend:
- `notifications` table (0130) with kind, level, data, actor and read_at, capped
at the newest 200 per user.
- /api/notifications: list, mark read, dismiss one, dismiss all.
- notify()/notify_admins() store the row and push `notifications:new` to the
user's socket room; read/dismiss push to the user's other tabs.
- Producers: a scan's end (to whoever started it; an unattended scan tells
the admins when it failed or found new games), a manual task's end (to who
ran it; a scheduled task's failure to the admins), an admin ending someone's
stream, and an admin changing someone's role.
Frontend (v2):
- Unread count badge on the navbar avatar, and a Notifications entry in the
user menu and settings sidebar.
- Notifications view: marks what it shows read, links each row to what it is
about, dismiss one or all.
- Live toast for a new notification, except scans, which already toast.
- The text is rendered from the kind in the reader's language (18 locales).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The folding rule was written three times in two phrasings: as a filter,
as its own inverse inside the auto-open check, and as an arithmetic
difference for the chevron count. A slot band now partitions into
`pinned` and `hidden` once where it is built, so the rule has one home
and the filter stops re-running per render.
Also:
- A band carries its newest asset instead of the id, so ranking no
longer scans the band to find it again inside a sort comparator.
- `HIDDEN_ASSET_ANNOTATIONS` derives from `AssetAnnotations`, so a third
annotation field cannot be added without also being masked.
- `normalize_asset_labels` keys the dedupe off a dict, folding each label
once, and rejects an oversized set as soon as it crosses the cap
instead of after walking the whole body.
- The clear button's absolute placement moved onto the stage that wants
it, so the inline variant no longer un-sets it.
- Two duplicated label ternaries became computeds.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016bZ7R3xC73MZu1vTNuatPK
A filename and a timestamp cannot tell apart a 100% run from a speedrun
seed, so saves and states carry two owner-only annotations: a favorite
heart that sorts them ahead of their band, and a set of free-text labels.
Backend adds `is_favorite` and a JSON `labels` to both tables, with
`PUT /{saves,states}/{id}/{favorite,labels}` mirroring the existing
visibility toggle. Labels are trimmed, de-duplicated case-insensitively
and capped. Both routes write with `touch=False`, so annotating a save
leaves `updated_at` alone: it is not a write to the bytes, and device
sync reads that column to decide staleness.
In v2 the Save data tab grows a heart and a labels button per row, the
labels dialog suggests the labels already used on the ROM, and favorites
lead their slot or core without ever folding the newest version away.
The heart glyph shows only on the launch screens, where the toggle that
would otherwise say it is not there. Phones give the row four bands:
name, labels, facts, buttons.
Closes#942
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016bZ7R3xC73MZu1vTNuatPK
* 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>
* fix(collections): project identifier columns instead of loading whole collections
`GET /api/collections/identifiers` reads only ids, owners and visibility, but
the accessor it called eagerly loaded every rom of every collection
(`@with_roms`) and built a full `User` per row (`Collection.user` is
`lazy="joined"`). A column projection drops both, while `load_only` cannot
cancel either one.
Measured on a seeded database of 100 collections and 200 roms (20,000
memberships): rows read 20,100 to 100, statements 2 to 1, SQL text 1,172 to
113 bytes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(collections): keep the new identifier assertions to one-line comments
The repo caps comments at one line when the rationale is not recoverable
from the code, and test docstrings at one sentence, so the m2m reasoning
belongs in the PR body rather than repeated at the call sites.
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>
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>
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>
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
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
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
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