* 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>
- Replace the inline bytes-to-text decodes with redis_handler.as_text
- Add utils.auth.token_device_id for a request's token-bound device
- Look up a group's member tokens in one query and close them in one pass
Co-Authored-By: Claude Opus 5.5 (1M context) <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>
compare_save_state decides a side changed from its timestamp, and
emulators rewrite a save on exit, so an untouched save looks new and a
server change elsewhere turns into a false conflict.
device_save_sync now records what each side held at the last sync
(last_sync_hash from the device, last_sync_server_hash from the server,
migration 0140). A baseline match proves that side unchanged; a mismatch
or NULL falls back to the timestamp logic, so this only removes
conflicts. It runs after the removed_at check in compare_save_state.
- Baselines are recorded only for versions the device provably holds:
confirm_download pins to the served version, update_save records the
client hash only when the file was uploaded, deduplicated uploads and
pushed saves record against the surviving save, and push-pull no-ops
record hashes only for identical content.
- Identical-content no-ops in negotiate and the watcher record a
boundary without re-tracking untracked saves.
- The SSH push-pull and file-transfer watcher paths hash device saves
through hash_save_file, matching compute_content_hash for zipped
saves, and treat unreadable saves as unknown.
Squashes rommapp/romm#4768 onto master.
Claude-Session: https://claude.ai/code/session_01WAKUdfLb6fyduEqaFbf5A8
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
- Move unrecorded_hash onto FSAssetsHandler, so sync_watcher and the
push-pull task no longer import handler.asset_store (and with it
scan_handler and every metadata provider, ~80 modules)
- Drop the PSP bundle's unrecorded_hash call: bundles are never slotted
- Skip the removal-times query when the device's copy already matches
- Restore per-row deletes in prune_slot: the single `id IN (...)` delete
from the review pass deadlocked the threaded removal test 3/10 runs on
MariaDB (0/25 per row)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Follow-up to #4789 from the code-review pass:
- PUT /api/saves/{id} records the replaced bytes of a never-hashed save
- rehash_save keeps updated_at, so a recompute is not read as a write
- unstamped legacy versions keep their removal time when another is lost
- prune_slot deletes its locked rows in one statement
- 0138 creates the slot index after the collation change
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
is_system was true exactly when system_key is set, so 0137 now drops it
after backfilling the key, and downgrade rebuilds it from the key. The
group API returns system_key instead, and the admin UI reads it for the
system tag and edit warning.
Co-Authored-By: Claude Opus 5.5 (1M context) <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>
Tests, fixtures and the e2e seed found the seeded groups by display name,
which an admin can edit and this PR just changed. A unique system_key
column (viewer/editor), added and backfilled by 0137, identifies them
instead, and get_system_group() replaces the name lookups.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Tell a device when the save it holds was deleted here
Deleting a save took its row, its file and its device pairings, leaving nothing
that says it ever existed. A negotiation then read a client still holding the
save as a client with a save the server lacks, answered "upload", and the next
launch put the deleted save back. There was no way to say "this is gone": the
protocol's actions are upload, download, conflict and no_op.
So a slot emptied on purpose is now remembered. `deleted_saves` keeps one row
per (user, rom, slot) with what the slot held and when it was emptied, written
by the delete endpoint, which is the only place a deletion is the owner's
decision rather than housekeeping: autocleanup rotating a version out leaves
newer rows in the slot and is never recorded.
Negotiation reads it only when the slot has no row left, and answers the new
"delete" action when the client's copy is the one that went: the same content
hash, or a copy last written before the deletion. Anything written after it is
progress the server never held, so that still answers "upload" -- emptying a
slot is not a licence to delete a newer save.
The generated frontend models are hand-edited to match: this environment has
only CPython 3.14.0rc2, which the locked pydantic cannot import, so the backend
will not start for `npm run generate`. Both edits are mechanical (the new
literal in the union, the new count field), and `npm run typecheck` passes
against them.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Decide a deletion by identity, and record it before the row goes
Three real findings from the review, and the layering rule.
The record was written after the save row and its file were gone, with two
transactions and a filesystem removal between them. Anything failing in that
window left a deletion nothing remembered, which is the resurrection this
change exists to prevent. It is written first now: a record for a save that is
somehow still there is never read, because a negotiation only consults it when
the slot has no row left.
The client's copy was matched on its own timestamp against the server's
deletion time. Those clocks are not comparable, and a device running slow
would have been told to delete progress it made after the deletion. The match
is now identity alone: the slot remembers every version it lost, capped at the
twenty most recent, and a client holding any of them is told to drop it.
Anything else is offered back, which costs a deletion that does not reach that
device rather than a save that is gone.
Recording replaced the row with a delete and an insert, which two deletions of
the same slot could race into a uniqueness error. It locks the row and merges
into it, with the house savepoint-and-catch for the case where there is no row
yet to lock.
The comparison itself moves to handler/sync/comparison.py beside
compare_save_state, where the endpoint delegates to it and the rule is tested
on its own.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Trim the new comments to the repo's rule
One or two lines each, with the rationale in the commit messages and the PR
description where the rule puts it. The model's docstring is one sentence, and
the comparison keeps its Args and Returns.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Sort comparison imports
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Widen the window a deletion is remembered in
A slot's record keeps a bounded list of the versions it lost, and the trim
drops the oldest, which are exactly the ones a long-offline device is
likeliest to still hold. At twenty, a device that missed twenty
delete-and-refill cycles of one slot comes back with a digest that has
aged out and is answered `upload`, which puts a deleted save back.
Raised to a hundred, where the device would have had to miss a hundred
manual deletions of the same slot. The residual is deliberate and cannot
be designed away by a longer list alone: past the bound the server does
not know those bytes were deleted, and the answer degrades to `upload`,
which fails by not propagating a deletion rather than by destroying a
save. A test now names that case so the next reader meets it as a choice
rather than as an oversight.
Found by Greptile on #4674.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Trim the retention comments back to the rule
Both were over the two-line limit, and the constant's was a six-line
design essay of exactly the kind the last round of this review already
removed from this PR. The reasoning belongs in the commit that made the
change and in the pull request, where it is.
What stays is the part the code cannot say: the trim drops the oldest,
and past the bound a device is answered `upload` rather than `delete`.
Found by Greptile on #4674.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U
* Name the deletion record for assets, not only saves
Unreleased, so the table can take a name that states can share later
without another migration.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Apply code-review fixes to deletion records
Record a deletion in short separate transactions so concurrent first
deletions no longer deadlock on MariaDB, hash a save that never
recorded one, keep a re-deleted version from being trimmed, scope the
negotiation's read to emptied slots, and require total_delete.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Simplify deletion records
Drop the unread deleted_at column, record from _delete_save so every
caller of it is covered, skip a record no hash could ever match, let
comparison decide delete vs upload with its reason, count actions once,
and fold the near-duplicate tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Polish the deletion record's index comment
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.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>
is_bound now resolves each name-matching save or state through the same
thumbnail lookup they use, instead of stopping at the name match. A name can
match several screenshots while the asset shows only the one its lookup
prefers, so a thumbnail nothing displays was kept after a delete.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Enforce the upload size cap on streamed bytes in the middleware, so
chunked uploads to every guarded route are bounded, not just RetroArch
- Flag vanished assets missing_from_fs from the manifest instead of
re-hashing them every sync
- Batch state screenshot lookups, filter PSP bundles in SQL, hash files
in one thread hop, and read only the requested PSP bundle members
- Reuse remove_screenshot and content_hash_of_bytes, merge the save and
state PUT branches, drop dead checks and trim docstrings and tests
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Deleting a save or state removed its thumbnail row and file unconditionally,
so a save and a state sharing a stem lost the shared preview when either one
went. Every delete path (single and bulk deletes, slot pruning, streaming
history pruning) now goes through release_thumbnail, which keeps:
- a thumbnail another save or state still matches by name, checked in SQL the
way their thumbnail lookup matches, so it follows the database collation;
- a gallery screenshot that only shares the stem by chance;
- the file, when dropping the row, if another row spells the same file in a
different case on a case-insensitive filesystem.
Renaming reuses the same is_bound check to decide whether a thumbnail is
shared, replacing the casefold helper.
Addresses Greptile's review on #4749.
Co-Authored-By: Claude Opus 5.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>
- PUT /collections/{id}/visibility and /collections/smart/{id}/visibility
flip is_public alone. The settings switch used the full update, which
rewrote membership from the client's rom_ids and ran the cover branch.
- update_save, update_state and update_screenshot derive the file-name
columns from file_name, like update_rom does for fs_name, so the rename
path hands them a name instead of building the columns itself.
- Name fields use notBlank, AssetEditDialog picks its own title from its
type, ScreenshotEditDialog shares one canSubmit, the collection tile and
row drop a virtual guard their callers already cover, and PublicBadge
uses the pill radius token.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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>