Commit Graph

185 Commits

Author SHA1 Message Date
Georges-Antoine Assi
e427d8b093 fix(scan): fetch file rows per rom on quick scans (#5725)
* fix(scan): fetch file rows per rom on quick scans

A quick scan loaded every file row of a 200-rom batch up front, so a
platform with a few extracted multi-file games held hundreds of thousands
of RomFile objects at once and the worker was OOM-killed. Each rom now
fetches its own rows inside the scan semaphore, capping the rows held to
SCAN_WORKERS roms.

Refs #5706

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

* style(scan): shorten the batch lookup comment

Addresses Greptile's review on #5725.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:01:51 -05:00
Georges-Antoine Assi
20bff0830a fix(streaming): merge the webstation exit delta over the restored save archive (#5673)
* fix(streaming): merge the webstation exit delta over the restored save archive

A webstation exit export holds only the files changed since launch, but
RomM filed it as a standalone .saves.zip and the next launch restored only
the newest zip. A session that exited without an in-game save therefore
filed an archive with no save data, and the next Play booted without it.

The launch now records which native archive it restored on the session
record, and the exit pull lays the delta over that archive before filing
it, so every stored archive is a full snapshot.

Fixes #5544

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

* test(streaming): type the stored exit archive as bytes

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

* fix(streaming): skip the exit merge when the restored archive was replaced

PUT /saves/{id} rewrites a save in place under the same id, so the exit
merge could combine the session's delta with save data it never loaded.
Record the restored archive's content hash at launch next to its id, and
merge only while the base still has it; otherwise file the delta alone.

Addresses Greptile's review on #5673, including folding the
_over_restored_archive docstring into one sentence.

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

* refactor(streaming): drop ensure_zipfile_writable from the archive overlay

#5678 applies the zipfile_inflate64 fix where it is imported, and removed the helper.

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

* pr-ready: code-review

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

* pr-ready: simplify

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

* pr-ready: review-polish

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

* pr-ready: prose

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

* pr-ready: prose (code-review additions)

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

* fix(streaming): keep imported states, folders and the entry cap in the exit merge

A launch that imported a state left the base archive's states off the
container, so the exit merge now leaves them out too. The merge keeps
both archives' folders and refuses past the archive entry limit, so a
merged archive always gets a content hash. The webstation hydrate now
uploads the save its caller resolved instead of looking it up again.

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

* test(db): query a platform id no sequence can reach

Postgres keeps id sequences across tests, so a worker that has created
about a thousand platforms hands id 999 to the fixture's own platform.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:40:47 -05:00
Stu Anderson
0941b3033e feat(roms): load roms by an array of ids (#5663)
* feat(roms): load roms by an array of ids

GET /api/roms accepts up to 256 rom_ids and returns those roms in the
order given. Ids the caller can't see, or that don't exist, are left out.

Closes #5659

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

* fix(roms): code-review pass on rom_ids window

Reuse RomIdScope (dedupe, shared 500 cap), skip sidecar and grouped page
cache reads for a window by id, report offset 0 and the id count as limit,
and rename the shadowed rom_ids local in _transform.

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

* refactor(roms): simplify pass on rom_ids window

Return early for rom_ids before building the filtered query, the sidecars
or any cache key, through a shared _hydrate helper, so the paged path is
back to its prior shape. Tests use the headers fixture.

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

* test(roms): review-polish pass, cover a hidden platform in the rom_ids window

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

* fix(collections): refuse malformed virtual collection ids, require page-row visibility

A malformed virtual_collection_id raised an uncaught decode error (500) on
the gallery, random and bulk download routes. It is now a 422 at the query
boundary, and GET /collections/virtual/{id} answers 404.

get_page_rows_query takes visibility as a required argument, since it is
the access check on caller-supplied rom ids.

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

* feat(gallery): load scroll windows by rom id

Once the bootstrap holds the whole ordered id index, a window fetch sends
that slice as rom_ids, so the backend skips the filtered, offset-paged
query. Items are placed by id, since ids that went missing or hidden are
dropped from the response.

On a 100k-rom MariaDB library, a filtered grouped window went from
0.8-2.0 s to ~50 ms, and a deep ungrouped window from 106 to 50 ms.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-20 11:12:57 -05:00
kynrek
f9c8c8ab2a perf(roms): page grouped galleries from the cached id index (#5636)
* perf(roms): page grouped galleries from the cached id index

With group_by_meta_id, every gallery page ran the sibling-dedup window
over the whole library, because the frontend fetches pages with
with_rom_id_index=false. Grouped pages for the whole library or a plain
platform list now slice the versioned, cached id index instead, so only
the first page after a change pays for the window. Filtered, searched and
collection pages still run live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q367p1Ri2c1dKeYCpQgHeh

* fix(roms): share one cached key for grouped platform sidecars (pr-ready: code-review)

Grouped platform-only sets read their char index, id index and pages
from one key, deleting a platform invalidates the cached lists, and the
platform-only gate derives from has_scope().

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

* refactor(roms): simplify grouped sidecar caching (pr-ready: simplify)

Add RomFilterParams.has_only_platform_scope, share one str key base
between the sidecar key builders, collapse the total and index
branches, and dedupe the platform-key tests.

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

* test(roms): cover has_only_platform_scope (pr-ready: review-polish)

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

* perf(roms): page grouped galleries from a Redis list, bump on deletes

- Store the cached id index as a Redis list. A grouped page reads its
  window with LRANGE/LLEN instead of decoding the whole list.
- Page requests only read the cache; on a miss they run the live page
  query, so only the index request rebuilds the list.
- Cache grouped platform sets only for a single platform, and never
  store an empty list, so client-chosen platform ids can't grow Redis.
- delete_rom and delete_platform queue the after-commit version bump,
  replacing the hand-placed calls in the endpoints and cleanup task.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-18 18:48:02 -05:00
Georges-Antoine Assi
e813e4d666 chore(coherence): adopt Coherence with specs, invariants and a PR report (#5584)
* chore(coherence): adopt Coherence with specs, invariants and a PR report

Install @posthog/coherence as a frontend dev dependency and wire its
Claude Code hooks into the committed .claude/settings.json, so every
agent session in the repo gets the vocabulary, specs, journal and checks.
The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR.

Declare 23 components and the entrances that carry outside trust, and
six invariants, each refuted with a deliberate break before it counted:

- every /api route requires auth and its scopes, except a named public
  list (new route sweep in tests/endpoints/test_route_guards.py)
- a hidden rom, platform or firmware answers every id route exactly as
  a missing id would (new sweep over every method of every id route)
- the unscoped save, state and screenshot fetches by id are reached only
  from their own routers (chokepoints)
- validate_path never resolves outside its base folder

The PR workflow runs in comment mode: one report comment, failing only
when Coherence itself breaks. Trunk skips Prettier and markdownlint on
*.spec.md and *.practice.md, since Prettier escapes their globs.

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

* test(routes): satisfy mypy in the route guard sweep

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

* chore(coherence): record the worktree test database enactment

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

* fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps

Addresses Greptile's review on #5584.

The rom file delete and reading-progress routes answered "File not found"
for a hidden rom but "Rom with id N not found" for a missing one, so a
caller could tell them apart. They now raise the same not-found.

The route sweeps now reach the checks they claim to test: a protected
route with no scopes counts as public (its guard admits anyone), write
requests carry a body and upload name so validation can't answer first,
RomFile-keyed routes get a real file id, error bodies are compared with
the id normalized, and the rom routes are swept with the rom hidden
directly, through its platform, and by the unrated filter.

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

* fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review)

- Count a route as protected only when its endpoint is the scope-checking
  wrapper with non-empty scopes, not just when it declares the bearer scopes.
- Treat 401 and 403 like 422 as never reaching the visibility check, and
  sweep /api/streaming/states/{rom_id}.
- Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set.
- Use the shared setup-frontend action and ubuntu-24.04 in the workflow.

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

* refactor(tests): simplify route guard sweeps and path tests (simplify)

- Mark scope-guard wrappers with required_scopes so the auth sweep reads a
  public attribute instead of the private closure.
- Derive the entity regex from one segment list, ask each missing id once,
  and run the three hide scenarios through one sweep helper.
- Fold the new validate_path inputs into the existing valid, traversal and
  absolute path tests.

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

* chore(coherence): trim workflow comments (review-polish)

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

* test(filesystem): restore the validate_path property test the paths invariant cites

Filesystem.spec.md names test_validate_path_never_escapes_its_base as the
invariant's evidence, and Coherence selects it by name.

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

* chore(coherence): run hooks from the local binary instead of npx

Each hook calls frontend/node_modules/.bin/coherence directly and exits 0
when it isn't installed, so sessions without frontend deps (fresh
worktrees, backend-only setups, cloud setup still installing) don't report
a hook error on every tool call, and no hook pays npx's startup.

Also commits the journal and run records left by earlier sessions, which
.coherence/.gitignore keeps as durable records.

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

* refactor(tests): share the bearer, user token and hide helpers

Tests built the same Authorization headers and HiddenEntity rows in about
40 local copies, and two modules imported private helpers from other test
files. They now use bearer, user_headers and hide from tests/auth_helpers.py.

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

* refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware

Each route wrote the missing-row 404 and the hidden-row 404 separately and
had to keep them identical by hand. visible_rom_or_404,
visible_platform_or_404 and visible_firmware_or_404 take the lookup result
and raise one answer for both, either the standard not-found or a bespoke
detail. Re-reads after a write keep a plain not-found check, so an edit that
hides the row doesn't turn into a 404 after it succeeded.

The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name},
/roms/{file_id}/patch) name their path parameter file_id instead of id, so
the route sweep reads which id a route takes from its path and drops its
hand-kept list. URLs are unchanged.

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

* docs(setup): develop inside WSL on Windows

@posthog/coherence installs only on Linux and macOS, so npm install in
frontend/ fails on native Windows.

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

* chore(coherence): record the whole-repo chokepoint run

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

* chore(types): regenerate API types for the file_id patch route

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:53:46 -05:00
Terri
8a1e6280b1 feat(saves): add save channels and snapshots (#5198)
* feat(saves): add save channels and snapshots

* feat(saves): close spec gaps in save channels and hash with sigil

* feat(saves): play snapshots in the v2 player, which pushes snapshots

* fix(saves): code review: authorization, retention losses, held-save sync, batched responses

* refactor(saves): simplify pass

* refactor(saves): review-polish pass

* docs(saves): humanizer pass

* feat(saves): run every EmulatorJS page on the v2 player

* feat(saves): per-user snapshot pins

* feat(sigil): store the identity a save restore needs and pin sigil 0f05f25

* fix(saves): meet type-aware lint in the v2 player

* feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda

* feat(saves): convert saves for a core on download and list save layouts

* feat(saves): prune unreachable archival snapshots and empty detached channels on delete

* feat(saves): device sync from the token, held snapshots and shared-card pushes

* feat(saves): arc restores past abandoned snapshots and color channels by age

* fix(saves): code-review and security-audit fixes

* refactor(saves): simplify pass

* chore(saves): review-polish pass

* docs(saves): humanizer pass

* fix(sync): file RetroArch autosave versions as their channel's next snapshot

* fix(saves): address review findings and trim docstrings

* fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock

* test(saves): stub the detached-channels fetch in SaveDataTab stories

* feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff

* chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets

* docs(saves): drop v2 wording now that one UI remains

* chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets

* fix(sigil): treat a file too short for its format as routine during scans

* chore(migrations): renumber save channel migrations after upstream's 0154

* fix(snapshots): a hardcore switch on unchanged content makes a new current

* fix(sync): decide a channel's slot from its history and the device's snapshot

* chore(docker): pin sigil at 794d99f for PSP Store release save prefixes

* refactor(db): squash the save channel migrations into 0161

Fold the slot linking (0162) and the rom_files sigil identity columns (0163)
into 0161_save_channels, so the feature ships as one revision.

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

* fix(saves): close visibility and input gaps found in review (pr-ready step 2)

code-review --fix:
- negotiate_sync drops channel slots on ROMs hidden from the caller
- channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden
- a push copying a save from a hidden ROM answers 404
- _own_device applies require_token_device to bound client tokens
- adopting a legacy save syncs its sharing with the channel it joins

security-audit follow-ups:
- another user's detached public save or state is no longer downloadable
- profile and option values must be a single path segment
- companions are de-duplicated and capped at 8

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

* refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3)

simplify:
- readable_channel_or_404 and channels_on_files replace four copies of the
  channel 404 check and two copies of the file-fed channel listing
- readable_rom_asset_or_404 serves both public save and state downloads
- _own_device resolves through require_device; _clone_origin takes the source
- reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy
  and uuidv7; neutral forms default their required pattern to the allowed one
- RetroArch delete checks held rows in one query, a guarded upload lists the
  slot only without a channel head, and uploads are read off the event loop
- snapshotSession builds push requests once; player comment cleanups

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

* docs(saves): trim two docstrings to two lines (pr-ready step 4)

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

* fix(saves): answer held RetroArch paths with 423, mirror slot labels

- RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save
  and for a DELETE where only held rows sit at the path, instead of 409 and 404
- channelLabelForSlot returns null for blank and state_ slots, as the backend's
  channel_label does, so the player files them under no channel either
- document that sharing a channel lets every user read and push into it

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

* chore(docker): pin sigil at 85f88a8 for Switch .nup containers

* fix(snapshots): a save pushed in another shape or format makes a new current

* refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag

Nothing reads it, and the SAVE_SYNC block's presence already tells a
client the server speaks the snapshot API. Also trim the rom detail
channel field comments to one line each.

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

* refactor(frontend): use uuidv7 for every client-generated id

Drop the randomToken wrapper and the notification inbox's Math.random tab
id, so uuidv7 is the one helper that works outside a secure context.

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

* refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic

API:
- Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds.
- GET /snapshots is history only (channel_id required); GET /channels serves currents.
- A snapshot carries channel_id instead of an embedded channel.
- POST /saves/{id}/content takes the same query parameters as the GET, plus container_path.

Backend:
- Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil
  identity-hash path, unused relationships and composite snapshot indexes.
- One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and
  the shared reserve_version_name in the writer.
- The writer takes a visibility filter and checks the channel and parent itself.
- The restore handler picks per-game or merge; fewer wrapper types and tables.

Frontend:
- Channel delete uses the shared typed confirm; DeleteChannelDialog is gone.
- Held offline pushes go through a per-channel SnapshotSession.
- Remove the slot-based pending upload path.
- The timeline shares the fan's badge logic.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): release archival backups through module functions

The saves and states handlers each built a private DBSnapshotsHandler to
call release_backup and refresh_backup_digests, since they can't import
the shared instance. Both only ever ran inside the caller's session, so
they are now module functions taking it, like channel_for_slot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): share one deleted-assets handler instance

The saves handler built its own DBDeletedAssetsHandler because it can't
import the package's instance. The instance is now built in
deleted_assets_handler.py and re-exported by the package, so both use it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:59:19 -05:00
Georges-Antoine Assi
a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* docs: state that ROM visibility is enforced as access control

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

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

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

* fix(saves): answer a hidden ROM's save summary like a missing one

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

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

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

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

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

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

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

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

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

* test: start the scan audience before emitting from scan_rom

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

* docs: apply humanizer pass on the visibility rule

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

* fix(streaming): don't mount a memory card on a hidden platform

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

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

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

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:33:11 -05:00
Georges-Antoine Assi
37e4ca304d fix: permission, validation and resource-limit hardening (#5496)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:39:30 -05:00
Georges-Antoine Assi
f66950551a fix(sync): bind device tokens to their device; dial only known push-pull hosts (#5460)
* fix(sync): bind device tokens to their device; dial only known push-pull hosts

A client token paired to one device could read, reconfigure, delete, sync
saves for and record play sessions as any other device of the same user.
Device CRUD, sync negotiate/complete, push-pull trigger, the save device
resolver and play-session ingest now treat another device as not found for
a bound token, through a shared require_token_device helper. GET /api/devices
lists only the bound device.

Push-pull let any user with devices.write point ssh_host at any host and
port, and the connection error surfaced through the sync session, so the
worker could be used to probe the internal network. The SSH handler now
refuses a host with no trusted key or CA in the admin's known_hosts before
dialling it, which keeps LAN handhelds working while nothing else is
reached.

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

* fix(device): revoke a deleted device's tokens; scope registration matches

Addresses Greptile review on #5460. Deleting a device now deletes the client
tokens paired to it, since the foreign key's SET NULL turned them into unbound
tokens that reach every device. Registration with a bound token only matches
its own device by fingerprint, so it can no longer reset syncs or overwrite
capabilities on another device.

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

* fix(sync): bind heartbeat, sync session and online reads; pin push-pull ports

pr-ready step 2 (code-review xhigh --fix).

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

* refactor(device): one require_device helper; parse known_hosts once

pr-ready step 3 (simplify).

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

* test(sync): narrow await_args before reading known_hosts

pr-ready step 4 (review-polish).

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

* docs(sync): plainer comments on the push-pull allowlist and token revoke

pr-ready step 5 (humanizer).

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

* fix(device): keep bound tokens off other tokens; cascade tokens with their device

A device-bound token can no longer create tokens, or regenerate, pair or
revoke a token of another device or an unbound one. The save session_id
counter only counts a session of the caller's bound device.

client_tokens.device_id now cascades on device delete (0159), so no path
can leave an unbound token behind, and deleting a device records a
client_token.revoke audit event for each token it takes.

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

* chore(env): drop the push-pull allowlist note from env.template

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:57:33 -05:00
Georges-Antoine Assi
900fe515ea fix(sync): match RetroArch saves named after a ROM's files (#5445)
* fix(sync): match RetroArch saves named after a ROM's files

RetroArch names a save after the file it launched, so a disc or a
translation inside a multi-file game folder uploaded a save that matched
no ROM. When no ROM carries the name, saves now resolve to the ROM owning
a file with that stem. Those saves stay unslotted under their own name,
since a ROM's autosave lineage holds one save per core and the discs
would overwrite each other. States keep matching on the ROM name only,
because their slots are advertised under it.

Fixes #5364

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

* fix(sync): write a case-variant reupload to the stored save's own file

Addresses Greptile review on #5445.

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

* fix(sync): match a stored save's name in any case on PostgreSQL

The RetroArch save lookup relied on MariaDB's case-insensitive collation, so
on PostgreSQL a reupload in another case created a second save instead of
replacing the stored one.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 08:48:42 -05:00
Sam Dornan
183ee3b89f feat(platforms): enrich discovery cards and preserve AVIF animations (#5433)
Fetch original launch years and current platform logos during scans, retain curated platform icons, and show launch year and type on responsive discovery cards. Preserve animated AVIF frames during thumbnail and WebP conversion.

Closes rommapp/romm#5432

Authored with Codex assistance, including implementation and tests.
2026-11-01 19:23:51 -06:00
Sam Dornan
1642a323c0 fix(sort): strip only configured articles, and keep custom sort keys as typed (#5429) 2026-10-31 19:17:00 -05:00
alexcastgonz
81b617459b fix(db): bump client token and device last-used timestamps without a prior read (#5384)
* fix(db): bump client token and device last-used timestamps without a prior read

update_last_used() and update_last_seen_debounced() read the row with
session.get() and then updated it in the same transaction. When two requests
with the same Client API Token ran concurrently and both passed the debounce
check, the second UPDATE hit MariaDB error 1020 (Record has changed since last
read), so a read-only GET returned HTTP 500. Make each a single conditional
UPDATE that only touches the row when the debounce window has passed.

Fixes #5379

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

* test(db): code-review fixes for last-used race tests

Reuse the executed_statements fixture, scope race listeners to
sync_engine, add the device race test, drop an unused fixture, and
apply trunk fmt.

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

* refactor(db): simplify pass on last-used race fix

Share the race hook as tests/db_race_stubs.run_before_first, look tokens
up by id in tests, trim duplicated docstrings, and state the handler
comment as current behaviour.

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

* docs(db): humanizer pass on last-used handler comments

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

* fix(db): run MariaDB and MySQL sessions at READ COMMITTED

MariaDB 11.6+ turns on innodb_snapshot_isolation, so at REPEATABLE READ any
transaction that reads a row and then writes it fails with error 1020
("Record has changed since last read") when another transaction committed
to that row in between. READ COMMITTED, PostgreSQL's default, takes a fresh
snapshot per statement and removes the whole class of failures.

A server logging binlog_format=STATEMENT refuses InnoDB writes below
REPEATABLE READ, so its sessions keep the default and log a warning once.

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

* perf(auth): skip last-used and last-active writes inside the debounce window

Client-token auth bumped the token, the device and the user on every
request, the user with an undebounced UPDATE plus a re-SELECT. The token's
loaded last_used_at now gates the token and device bumps, and
set_last_active checks the loaded last_active and bumps through a
debounced conditional UPDATE, so a request inside the window writes
nothing and takes no row lock.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-29 12:23:31 -04:00
Ryan Farthing
c6b5f0ae11 fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes (#5313)
* fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes

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

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

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

Fixes #5312

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

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

Addresses Greptile's review of #5313:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-29 10:48:04 -04:00
Stu Anderson
6bf6554c97 perf(roms): cheaper grouped gallery window on PostgreSQL and MariaDB (#5267)
* feat(tools): time the two statements behind one gallery window

Builds the page-ids and load-by-id statements the way GET /api/roms does,
runs each under EXPLAIN (ANALYZE) in a read-only transaction, and prints the
execution time with the plan nodes that spend the most of it. PostgreSQL only.

Baseline on a 100,000-rom seed, grouping on, window 0+72, median of 3:
  page ids    1490.6 ms (hash join 441, roms_pkey scan 371, sort 302)
  load rows    892.3 ms (hash join 467, sort 318)
  total       2382.9 ms

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

* perf(roms): load a window's rows by id without re-running the sibling grouping

The ids a window loads were already picked by the grouped query, so the load
re-ranked the whole library only to confirm them. It now builds its select from
filter_roms with no filters (same loader options, file stats and hidden-roms
check) and narrows it to the page's ids.

Measured on a 100,000-rom seed, grouping on, window 0+72, median of 3:
  load rows by id   892.3 ms -> 1.3 ms
  both statements  2382.9 ms -> 1481.9 ms

Page ids are unchanged at about 1.48 s. The new tests compile the SQL only and
were not run here: they need the test database.

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

* perf(roms): rank pre-releases with one regex instead of six LIKEs

The sibling-dedup window evaluated six leading-wildcard ILIKEs on every rom's
filename. One case-insensitive regex over the same tags matches the same names
and reads each name once. The pattern is built from PRERELEASE_FILENAME_TAGS so
the tag list stays the only place a tag is named.

Measured on a 100,000-rom seed, grouping on, window 0+72, page-ids statement:
  median 1480.6 ms -> 1243.5 ms
  hash join under the sort, own time 455 ms -> 182 ms

The new tests check the pattern against the old rule on sample filenames and
that both dialects compile to a single match; they were not run here (they need
the test database).

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

* feat(tools): time searches and filters with --filters on the gallery timing tool

Takes RomFilterParams as JSON, so a search term, a platform or any filter can be
timed the way the plain gallery is. On a 100,000-rom seed a search costs 26 to
220 ms for a window's ids, and the broad filters (matched, verified, a status)
cost 430 to 1,145 ms because the sibling ranking covers almost every rom.

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

* fix(roms): keep the status filter when loading a window's rows by id

A page picked with statuses=hidden was reloaded under the default that hides
hidden roms, so its items came back empty while the total stayed non-zero.
The row load now carries the request's statuses and statuses_logic, and
nothing else.

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

* fix(tools): time searches as the endpoint runs them and accept group_by_meta_id in --filters

The timing tool now passes the search term to the query and defaults to the
endpoint's empty sort, so a search is timed with its relevance ordering. The
JSON filters merge over the grouped default (--ungrouped still wins), so a full
RomFilterParams can be pasted without a duplicate keyword.

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

* docs(roms): cut change rationale from the new docstrings and test headers

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

* test(roms): type the hidden-status page test

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

* test(roms): satisfy the CI mypy config in the hidden-status page test

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

* refactor(roms): load a window's rows with loader options only

The by-id row load reused filter_roms with a statuses-only RomFilterParams,
which tied its correctness to knowing which predicates apply by default.
Split the loader options out of filter_roms into _with_rom_loaders, and have
get_page_rows_query apply only those plus the id list and the visibility
clauses (the cached id index's key does not carry visibility).

Keep the six ILIKEs for the pre-release rank on PostgreSQL, where they
measured ~13% faster than the regex on whole-library windows (100k roms),
and use the regex on MariaDB, where it measured ~25% faster.

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

* fix(roms): apply code-review findings on the window row load

pr-ready step 2 (code-review xhigh --fix): drop the dead loader flags from
the ids query, align the timing tool's sort args and --repeat with the
endpoint, tighten comments, and stop the hidden-status test inserting a
RomUser twice.

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

* refactor(roms): drop filter_roms loader flags no caller sets

pr-ready step 3 (simplify): the gallery card loaders moved to
get_page_rows_query, so filter_roms no longer takes include_file_stats,
include_siblings or include_notes. The page-rows test compiles through
the shared compile_sql helper.

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

* docs(roms): trim the pre-release pattern comment

pr-ready step 4 (review-polish).

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

* docs(roms): plainer docstring on the grouped-query yardstick test

pr-ready step 5 (humanizer).

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

* refactor(roms): build every rom card loader from one list

with_details, with_simple_details and filter_roms each kept their own
copy of the SimpleRomSchema loads, and the copies had drifted: the
filter_roms siblings skipped load_only. All three, and the gallery's
page-row load, now build from _rom_card_loaders. Feeds still skip the
track and doc metadata they never read.

The real-row pre-release test pins the accent-sensitive match on both
PostgreSQL and MariaDB.

The timing tool now applies the user's rom visibility, times the eager
loads the row query triggers, and keeps parallel plan nodes in
wall-clock time.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-28 19:47:37 -04:00
Georges-Antoine Assi
3a79911b2f Revert "feat: classify ROMs by release type (homebrew, hack, translation, ...) (#5363)" (#5365)
This reverts commit 08acaa9ea.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:21:22 -04:00
Sam Dornan
08acaa9ea9 feat: classify ROMs by release type (homebrew, hack, translation, ...) (#5363) 2026-10-26 21:34:35 -05:00
Georges-Antoine Assi
92b6421e65 fix(saves): make a deduplicated slot upload the slot head (#5204)
* fix(saves): make a deduplicated slot upload the slot head

A slotted upload whose bytes match an older version in the slot returned
that version without touching its updated_at, so the slot's newest save
stayed one the device had moved away from. A client re-downloading the
slot head then restored the wrong save. Bump the matched version before
pruning so it becomes the head and survives the cap. A retry of the
current head is left alone so other devices don't see a spurious update.

Fixes #5200

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(saves): promote a deduplicated save in the handler, past same-second heads

Addresses Greptile review on #5204: the head promotion moves out of the
endpoint into db_save_handler.promote_to_slot_head, and the promoted
timestamp is at least a second past the current head's, so a head written
in the same second can no longer win the id tiebreak.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 13:53:25 -04:00
Georges-Antoine Assi
f89f6ef185 fix(security): check collection ownership in the ROM filters (#5201)
* fix(security): check collection ownership in the ROM filters

The collection endpoints refuse a private collection to anyone but its
owner, but the ROM listing endpoints accepted the same id as a
collection_id or smart_collection_id filter without checking it. Any
user (or a kiosk visitor) could list, randomly pick from and bulk
download another user's private collections and Favourites, and re-share
one through a public smart collection scoped to it.

The membership filters now match only collections that are public or
owned by the caller. A collection_id inside smart collection criteria is
checked against the smart collection's owner, both when the criteria are
saved and when they are evaluated.

Reported by Takaya Sato (dagadjno).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(security): clear stale smart collection caches across owners

Addresses Greptile's review on #5201. Smart collections cache their
membership on the row, so one scoped to another user's private
collection kept serving the members it cached before the ownership
check. Migration 0152 empties those caches on upgrade, and sharing or
unsharing a collection now refreshes the smart collections scoped to
it. Also covers a second user listing a public smart collection scoped
to its owner's private collection.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(collections): harden smart collection scope refreshes (code-review)

Allow re-saving a smart collection whose stored scope was since lost,
reject non-object criteria in from_stored_criteria, guard the scoped
refresh, and refresh smart collections when a collection's ROMs are
replaced or the collection is deleted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(collections): share the refresh wrapper and trim scope tests (simplify)

Move the scoped smart collection refresh next to the existing wrapper,
match the scope on the raw criteria before refreshing, batch the
migration update, and fold the duplicate unshare test into helpers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(migrations): describe the cleared smart scopes by current behavior (review-polish)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(roms): state the collection filter comment plainly (humanizer)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 13:20:26 -04:00
Georges-Antoine Assi
57ebac8efe perf(sync): resolve RetroArch core aliases in one query (#5192)
* fix(sync): resolve RetroArch paths across emulators sharing a core folder

Several RomM emulator ids map to one RetroArch folder (mednafen_psx_hw,
beetle_psx_hw and the raw "Beetle PSX HW" all sync through
saves/Beetle PSX HW/). The manifest built paths from whichever id an
asset carried, but GET parsed the folder back to the canonical id and
matched it exactly, so an asset filed under another alias was advertised
and then 404'd. Uploads also started a second autosave history beside
the alias's.

The manifest now lists the newest asset per folder, and GET, PUT and
DELETE resolve a path across every alias. Rewrites of an existing
unslotted save or state stay under that row's own emulator.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): prefer on-disk alias saves and share newest-per-key grouping

pr-ready step 2 (code-review --fix).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): one alias helper and a lineage computed once

pr-ready step 3 (simplify).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): type the alias fixture's asset kind

pr-ready step 4 (review-polish).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): isolate the asset dir per RetroArch sync test

The alias tests write different bytes to the same asset paths, and
user and ROM ids repeat across xdist worker databases, so parallel
runs raced on those files.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(sync): resolve RetroArch core aliases in one query

The saves handler now filters on a collection of lineages and looks up a file name across several folders, so the RetroArch alias resolvers issue one query each instead of one per alias.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(sync): filter a RetroArch delete to autosave and unslotted saves in SQL

Addresses Greptile's review on #5192: saves_at_path loaded every slot of
the matching lineages and dropped the named slots in Python.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 18:54:27 -04:00
Georges-Antoine Assi
a1466d9233 perf(tasks): batch RetroAchievements status writes, make add_rom_user race-safe (#5179)
* perf(tasks): batch RetroAchievements progress sync reads

Add get_roms_by_ra_ids and get_rom_users_by_rom_ids (single index-backed
IN queries, no eager joins) and fold the per-user feed to {ra_id: status}
so each user costs 2 reads plus writes instead of 2 reads per game.

* fix(tasks): skip joined eager-loads in RA sync batch reads

* style(tasks): trim batch-read comments to house style

* fix(tasks): sync every ROM sharing an ra_id, skip empty rom set early

* fix(tasks): raiseload instead of deprecated noload, fix CI failures

* fix(tasks): apply code-review fixes to RA progress sync batching

pr-ready step 2 (code-review xhigh --fix): load only id/ra_id for the
batched ROM read, flatten the sync loop, isolate per-user status sync
failures, log the ROM id, add a real-row test, and move the batched
RomUser getter next to its siblings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(tasks): simplify RA progress sync batching and its tests

pr-ready step 3 (simplify): select (id, ra_id) columns instead of Rom
entities, drop early returns the getters already short-circuit, and
fold the mocked sync tests into shared helpers and one parametrized
status-transition test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style(tasks): trim batched RomUser getter comment

pr-ready step 4 (review-polish).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(tasks): tighten unknown-award test docstring

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(tasks): batch RA status writes and make add_rom_user race-safe

set_rom_user_statuses writes one user's statuses in a single
transaction: it inserts missing RomUser rows, then runs one conditional
UPDATE per distinct status. The RETIRED/NEVER_PLAYING guard lives in the
WHERE clause, so a status the user sets mid-sync is never overwritten,
and the per-user cache bumps are queued once.

add_rom_user now inserts inside a savepoint and returns the existing row
when a concurrent writer won the unique (rom_id, user_id) insert, so the
sync no longer needs a catch-all around each user.

A rolled-back savepoint fires after_rollback, which drops every queued
user cache bump, so bumps are queued only after the savepoints finish.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(tasks): skip existing rom_user rows in the batch insert

Addresses Greptile review on #5179. The batch read existing rows before
inserting, so under MariaDB's REPEATABLE READ a row another writer
committed in between raised IntegrityError, and the fallback SELECT (or a
FOR UPDATE read, which MariaDB's snapshot isolation refuses) could not see
it. The insert now skips duplicates itself (ON CONFLICT DO NOTHING /
INSERT IGNORE) with no prior read. The race test commits the competing row
right before the INSERT instead of mocking the lookup. Also trims the
set_rom_user_statuses docstring to one sentence.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(tasks): apply code-review fixes to batched RA status writes

Batch set_rom_user_statuses to stay under PostgreSQL's bind parameter
cap, keep queued cache bumps across a rolled-back savepoint, fold the
single-caller insert helper into add_rom_user, and fix stale comments.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(tasks): apply simplify pass to batched RA status writes

Group by status before batching to drop a loop level, name the
user-owned statuses, split the dialect insert out of the execute call,
and share a status lookup across the write tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(tasks): type the dialect insert for mypy (review-polish)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Shreeniwas <105774423+Shreeniwas1@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 18:31:34 -04:00
Georges-Antoine Assi
3b8eabdb77 feat(sync): sync RetroArch Cloud Sync saves through save slots (#5170)
* feat(sync): sync RetroArch Cloud Sync saves through save slots

RetroArch saves were unslotted and overwritten in place, so they never
reached the slot-based sync the native clients use, and a bad upload
replaced the only copy.

A save path now serves the newest slotted version for its ROM, core and
extension, from any slot, under RetroArch's own file name. An upload adds
a version to that slot (or autosave), skips unchanged bytes, and prunes to
MAX_SAVES_PER_SLOT. A delete removes every save the path covers, so none
resurfaces on the next sync. Unslotted saves keep serving until the first
slotted upload; PSP bundles and states are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): lock RetroArch save uploads and prune per core and extension

Addresses Greptile's review on #5170:
- Move the RetroArch save upload into sync_handler.store_save_version,
  leaving the endpoint to validate and map the result to a status.
- Hold a Redis lock per (user, rom, core, extension) across the lookup,
  write, scan and row update, so concurrent same-second uploads never file
  two rows over one tagged file. A lock timeout answers 503.
- Prune only the uploaded path's core and extension in the slot, so
  another core's or a .rtc's current save is never dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): pr-ready code-review fixes for RetroArch save slots

- Scope an extensionless prune to dotless file names, since every name
  ends in an empty extension.
- Treat only NULL slots as unslotted in the manifest, matching the query
  it replaced and the PSP bundle lookup.
- Share one helper for the slot versions a RetroArch path covers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): pr-ready simplify pass for RetroArch save slots

- Scope a slot prune by save ids, so the versions a RetroArch path covers
  are decided once in Python instead of again in SQL.
- One newest-per-key helper for states and save versions, and
  resolve_save_by_slot reuses it.
- A canonical_save_file_name helper next to the state one.
- The upload builds its tagged name once, checks its length in the
  handler, and finds a same-second version in the list it already loaded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): pr-ready review-polish pass

Drop a comment the canonical_save_file_name helper now says.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): map RetroArch saves onto autosave lineages with unique version names

- Only RetroArch's .srm goes through slots, as the autosave versions of
  its ROM and core. Companion files such as .rtc stay single unslotted
  saves, so a slot never offers a clock file as the save.
- RetroArch reads, writes and deletes in autosave only, leaving named
  slots alone.
- Every slot prune, web uploads included, is scoped to the uploaded save's
  lineage (emulator and extension), so one core's uploads never drop
  another's only save.
- The manifest lists the newest version under the client's spelling of
  the game when it still names the ROM.
- reserve_version_name moves a taken tag on a second and claims it in
  Redis, so same-second, concurrent or repeated-hour uploads from either
  endpoint never share a file. The RetroArch lock and its 503 go.
- The manifest reads only the newest version per lineage, through one
  window query.
- An upload is hashed before it is written, so an unchanged re-send
  writes nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): seed the client-spelled save instead of uploading it

Uploading TEST_ROM.srm only resolves to the test_rom ROM under MariaDB's
case-insensitive collation, so the test 409'd on PostgreSQL. Seeding the
version directly still checks that the manifest keeps the client's
spelling of the game.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): resolve RetroArch saves to ROMs case-insensitively on PostgreSQL

Cloud Sync matches a save's game name to a ROM's fs_name_no_ext. MariaDB's
collation ignores case, but PostgreSQL compared exactly, so TEST_ROM.srm
never reached the test_rom ROM. PostgreSQL now compares lowercased names,
served by a new expression index (0150), and the endpoint test uploads the
differently-cased name again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): address Greptile review on RetroArch save slots

- add_save derives the prune lineage from the tagged name it stores, so a
  dotted upload such as game.rev.srm is counted against its own versions.
- Deleting a RetroArch .srm path also removes unslotted saves in that
  lineage spelled in another case, which the manifest hid behind the
  autosave head and PostgreSQL's exact match left behind.
- reserve_version_name looks up existing versions off the event loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 18:30:57 -04:00
Georges-Antoine Assi
75e8a9efae fix(sync): keep RetroArch Cloud Sync from stalling the event loop (#5171)
* fix(sync): keep RetroArch Cloud Sync from stalling the event loop

Basic auth ran its bcrypt check (~250ms) on the event loop for every
WebDAV request, and the manifest ran its queries there too, so parallel
RetroArch requests queued behind each other. Both now run in a thread.

Cloud Sync resolves every save and state to a ROM by fs_name_no_ext,
which no index led with; 0149 adds one so unmatched uploads fail fast.

The upload dialog now offers a core for saves as well as states, so a
manually uploaded save lands in the core folder RetroArch reads, and its
slot hint says only unslotted saves reach RetroArch.

Refs #5158

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover manifest queries running off the event loop

Addresses Greptile review on #5171: trim the 0149 migration docstring to
its summary, annotate the new MockConnection constructor, and add
regression tests that build_manifest and list_manifest_paths query from a
worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): mark Basic-auth users active off the event loop

pr-ready step 2 (code-review): run the user lookup, password check and
set_last_active in one worker-thread hop, and test that SaveDataTab offers
save cores and forwards the picked core on upload.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(v2): build SaveDataTab test saves and states from shared fixtures

pr-ready step 3 (simplify): replace the hand-cast UserSaveSchema and
UserStateSchema stubs with saveFixture/stateFixture plus toUserSave/toUserState.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): drop restating index comment and type the test spy

pr-ready step 4 (review-polish): remove the comment that only restated
idx_roms_fs_name_no_ext, and type the manifest test's get_saves spy so mypy
passes across the backend.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): check the password grant's credentials off the event loop

The OAuth password grant ran bcrypt (~250ms) on the event loop, stalling
every other request the worker was serving.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): run RetroArch WebDAV database work off the event loop

GET, PUT, DELETE and PROPFIND resolved ROMs, looked up and wrote save,
state and screenshot rows, and listed whole platforms synchronously inside
async handlers; the PSP bundle helpers did the same. Each now runs that
work in a worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(saves): keep another core's same-named save on upload

A slot-less upload matched an existing save by file name alone, so
uploading game.srm for a second core rewrote the first core's row to the
new folder and deleted its file. The lookup now only matches a save made
with the requested core. Clients that send no core still match any, so
device conflict detection is unchanged, preferring a save filed under no
core.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(v2): file a save picked with a core out of the slots

RetroArch Cloud Sync only lists unslotted saves, so picking a core in the
upload dialog moves an untouched slot from autosave to "No slot", and
clearing the core moves it back. A slot the user picked is kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(i18n): restore the original upload slot hint

Picking a core now files a save out of the slots, so the hint no longer
needs to explain RetroArch Cloud Sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 14:37:36 -04:00
Shreeniwas
361e18cc56 perf(tasks): batch RetroAchievements progress sync reads (#5144)
* perf(tasks): batch RetroAchievements progress sync reads

Add get_roms_by_ra_ids and get_rom_users_by_rom_ids (single index-backed
IN queries, no eager joins) and fold the per-user feed to {ra_id: status}
so each user costs 2 reads plus writes instead of 2 reads per game.

* fix(tasks): skip joined eager-loads in RA sync batch reads

* style(tasks): trim batch-read comments to house style

* fix(tasks): sync every ROM sharing an ra_id, skip empty rom set early

* fix(tasks): raiseload instead of deprecated noload, fix CI failures

* fix(tasks): apply code-review fixes to RA progress sync batching

pr-ready step 2 (code-review xhigh --fix): load only id/ra_id for the
batched ROM read, flatten the sync loop, isolate per-user status sync
failures, log the ROM id, add a real-row test, and move the batched
RomUser getter next to its siblings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(tasks): simplify RA progress sync batching and its tests

pr-ready step 3 (simplify): select (id, ra_id) columns instead of Rom
entities, drop early returns the getters already short-circuit, and
fold the mocked sync tests into shared helpers and one parametrized
status-transition test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style(tasks): trim batched RomUser getter comment

pr-ready step 4 (review-polish).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(tasks): tighten unknown-award test docstring

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 12:43:39 -04:00
Georges-Antoine Assi
ad0146a88e chore(trunk): fix the scheduled trunk check-all failures (#5141)
* chore(trunk): fix the scheduled trunk check-all failures

- Ignore hadolint DL3008 on the runtime stage apt-get, matching the
  emulator-download stage
- Build alias-search test ROMs with tests.factories.make_rom instead of
  the banned add_rom
- Drop a bandit B405 ignore that suppresses nothing
- Bump fast-uri to 3.1.8 for GHSA-hrr3-gc8f-f4qj

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(tests): type the alias-search rom helper kwargs as Any

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 08:05:38 -04:00
Sam Dornan
aa1c038004 fix(activity): send play activity only to users who can see the ROM (#5121) 2026-10-04 14:15:46 -04:00
Georges-Antoine Assi
f8b3173bea feat: searchable alternative titles for ROMs (#5111)
* feat: searchable alternative titles for ROMs

Add an editable "Alternative titles" field to manual metadata, folded
into the search titles alongside provider aliases. IGDB localization
titles now join the ROM's alternative names, and the canonical IGDB
name is kept as one when a regional title is displayed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: list hand-added titles in alternative_names, test the field

Address Greptile review on #5111: the response's alternative_names now
appends the hand-added titles to the first provider's, and the Alternative
titles field gets a component test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test: type the alternative titles field lookup

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: code-review pass on alternative titles

Validate title lists from client-written metadata in one helper, list
hand-added titles first so the search text cap never drops them, and
let the titles combobox keep commas inside a title.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor: simplify pass on alternative titles

Dedupe IGDB titles once in build_igdb_rom, inline the manual title
source, and reword the combobox comma comment.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs: review-polish pass on alternative titles

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs: humanizer pass on alternative titles

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: hand-set alternative titles override, providers join

A non-empty manual list replaces every provider's titles, in the list
and in search; otherwise every provider's titles are joined. IGDB and
Hasheous store every title they know, the canonical name and regional
localizations included, and the ROM's displayed name is left out only
when listing them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: validate manual metadata on ROM update

A malformed raw_manual_metadata is rejected with a 422 instead of being
stored and failing every later response for that ROM.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: list each alternative title once however it is spaced

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 13:12:40 -04:00
Sam Dornan
c402da2599 test: platform fixture factories for the backend and frontend (#5119) 2026-10-04 13:11:33 -04:00
Sam Dornan
3204037797 fix(auth): validate reset passwords and make the last-admin guard atomic, with tests (#5106) 2026-10-04 10:18:15 -04:00
Sam Dornan
ef3128e154 Hide ROMs above a user's or group's age limit (#5081) 2026-10-03 18:26:52 -04:00
Sam Dornan
b3ad84c296 Route ROM visibility through a single RomVisibilityFilter (#5064)
Replace the hidden_platform_ids/hidden_rom_ids parameter pairs with one
RomVisibilityFilter that builds the WHERE clauses and checks loaded ROMs,
so a new visibility rule (the age-rating cap for #2013) lands in one place.
No behaviour change; the visibility-filtered queries send the same SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wc3NzFkv97CXavLyZg5kJE
2026-10-03 10:46:47 -04:00
Zach Clendenen
10865b8663 perf(roms): faster smart collection and filter value queries (#5069)
* perf(roms): stop MariaDB rescanning the library for smart collections

MariaDB plans the smart collection membership IN (subquery) as a semi-join that rescans every rom per page query. A NO_SEMIJOIN hint keeps it a plain subquery; other dialects don't emit the hint.

* perf(roms): parse each distinct filter value list once

The filter dropdown query decoded every JSON column of every row. The columns are now read as text, deduplicated, and each distinct list is parsed once. PostgreSQL decodes JSON in the driver, so its lists are merged as returned.

* test(roms): cover repeated filter value lists in pr-ready code review

* refactor(roms): pr-ready simplify pass

* style(roms): pr-ready polish

* fix(roms): address Greptile review

Fold filter value rows in batches of 5000 instead of materializing the whole result, keeping the parse-each-distinct-list-once dedup across batches, so /api/roms/filters no longer holds one row per ROM in memory (Greptile: filter requests retain every row). The repeated-lists test now runs with a batch size of 2 to cover the cross-batch path.

* fix(roms): pr-ready code review fixes

- Cast filter JSON columns to text in SQL, so PostgreSQL gets the
  parse-once saving and a scalar JSONB value no longer crashes json.loads
- Stream filter rows with yield_per instead of only partitioning
- Name the JSON filter columns instead of hard-coding positions
- Add optimizer_hint_on_mysql next to force_index_on_mysql, with tests
- Make the repeated-lists test span batches regardless of row order

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(roms): pr-ready simplify pass

Collect each filter column's distinct JSON texts and parse them once at
the end, and key the JSON filter columns by their RomFiltersDict field so
the positional unpack and per-field return go away.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style(roms): pr-ready polish

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 10:29:25 -04:00
Zach Clendenen
b1f4ac4888 fix(db): keep iterated query results away from the cyclic GC (#5068)
* fix(roms): read filter values with .all() so the GC never frees the cursor

Looping over the filter-values Result directly makes SQLAlchemy 2.1 memoize
an iterator closure that captures the Result, which puts the CursorResult,
its execution context and the mariadb cursor in a reference cycle. The
cyclic GC then frees them on whatever thread triggers a collection, and
under concurrent gallery requests that segfaults the mariadb connector
(1.1.14, Python 3.14) inside the pool checkout. .all() never builds that
closure, so nothing is left for the GC.

* fix(roms): address pr-ready code review

* style(roms): pr-ready polish

* fix(db): read every iterated query result with .all()

The same reference cycle that segfaulted the filter values also hits smart
collection matching on every save, the screenshot binding check, playlist and
favourite adds, the recommendation reads and the stopword probe. The IGDB
related-games stream keeps yield_per and closes its Result with a with block.
A source scan test now fails on any Result iterated directly.

* fix(roms): address Greptile review

Keep gc.garbage entries that predate the filter-values cursor test: only the
objects this test collects are inspected and removed, so a runner that already
saves garbage keeps its list intact (Greptile, test_rom_facets.py).

* pr-ready: code-review fixes

Keep a generator's begin_session open until it finishes, read the
streamed IGDB scan by partition, and widen the iterated-Result guard to
names, unpacking, yield from and iterating methods.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* pr-ready: simplify

Share the app-source AST scan between the two guard tests, fold the
generator session's two branches into one nullcontext, and drop the
call-site comment the guard test already carries.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(db): flag iterated legacy session.query() results

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 10:06:49 -04:00
Georges-Antoine Assi
05bf29fe09 feat(converto): read per-file title ids with rom-converto during scans (#5031)
* feat(converto): read per-file title ids with rom-converto during scans

The title-id half of #5002: rom-converto's info runs fill rom_files.title_id
and title_version, sigil fills what rom-converto can't read and keeps owning
save targets, and roms in a scan batch share info runs of up to 64 files.
A converto_read_at marker lets quick scans backfill files rom-converto has
not read yet. converto.scan_metadata (config.yml only) turns it off.

The other per-file fields and embedded images stay out until a UI reads them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the same-content check that keeps unread title ids

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): queue unread files in one pass over the built rows

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): address Greptile review on #5031

- A file refresh now persists converto_read_at when rom-converto's read
  confirms a reused row's stored title id, so the file isn't re-read on
  every refresh.
- RomConvertoService.read_infos splits its paths into info runs of at
  most INFO_BATCH_SIZE, so a rom with many files can't send them all
  through one run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): apply code-review fixes

- A stored file title id counts as rom-converto's only once rom-converto
  has read the row, so a stale sigil id can't override a fresh extraction.
- Fresh hashes decide whether unread title ids still describe a file,
  ahead of a size and mtime a copy can preserve.
- One rom's failed candidate listing no longer aborts its scan batch.
- The info paths file's cleanup can't raise out of read_infos.
- _rom_file_order sorts by Path like _TitleIdSource.order.
- Restored the in-place reconcile test for _identify_rom.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): apply simplify pass

- sync_rom_files reads 'rom-converto read this pass' off converto_read_at
  instead of an inspected set threaded through ParsedRomFiles, FSRom, the
  scan socket and the refresh.
- One _converto_may_read check serves the scan and the batch candidates.
- converto_candidates reuses _list_rom_dir, validates paths off the event
  loop and is best-effort itself, so the scan socket gathers it plainly.
- get_rom_files builds rom-converto paths from the validated rom dir
  instead of validating each file again.
- _rom_level_identity returns early on sigil's extraction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(converto): apply review-polish pass

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): drop the shared info batch

Sharing rom-converto info runs across a scan batch saved about 2 ms per
rom (one process start) in exchange for a second directory walk per
rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket
wiring. Each rom now reads its own files; read_infos still caps a run
at INFO_RUN_MAX_FILES.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the rom-converto columns inline

Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so
_copy_scanned_columns keeps master's frozenset keep_when_unset.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 13:49:40 -04:00
Sam Dornan
fb61cbe882 feat(search): Search provider aliases through search_titles and drop generated_search_aliases (#5003)
* Search on search_titles and drop generated_search_aliases

The gallery filter matched provider aliases through a generated column
built from the JSON text, so escaped characters (MariaDB's \uXXXX
storage, tabs, quotes) were out of its reach, and ranking already reads
the folded titles in `search_titles`. Point the MariaDB FULLTEXT index
and the PostgreSQL trigram index at `search_titles` and drop the
generated column. Migration 0147, not yet released, makes the swap; its
downgrade rebuilds 0146's column and index from a frozen copy of their
SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Rebuild roms after the search titles backfill on MariaDB

Filling `search_titles` grows every row in place, which leaves InnoDB's
pages split and slowed the FULLTEXT search by 10 to 25 ms on 40,000
ROMs. One table rebuild after a backfill that filled rows restores it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready code review: describe the alias search test case as it stands

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready simplify: read the legacy column name off the 0147 migration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready review-polish: describe the rebuild as the code does it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Freeze 0147's provider list and always rebuild roms on MariaDB

- The backfill and the downgrade's copy of 0146's column read a frozen
  provider list instead of `ALTERNATIVE_NAME_SOURCES`, so a later provider
  can't change what this revision selects or rebuilds.
- The table rebuild runs on every MariaDB/MySQL upgrade: a run that stopped
  after the fill but before the rebuild left nothing to fill on retry.
- Two comments describe why, not what the migration replaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Fold 0146 and 0147 into one search titles revision

Neither revision has shipped, so `0146_roms_search_titles` takes the
roms table from 0145 straight to `search_titles` and its search index,
and `generated_search_aliases` never exists. The search indexes are
dropped first, so the column is added and filled with no index to
maintain, and the index is built once over the filled rows.

Databases on a nightly that ran either old revision need resetting to
0145 before upgrading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Keep the search titles migration under 0146's revision ID

The folded revision now rewrites 0146_roms_search_aliases in place
rather than adding a new ID. A nightly database that already ran the
old 0146 or 0147 still needs resetting to 0145 before upgrading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Say why 0146 adds search_titles ahead of ensure_roms_columns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 22:01:40 -04:00
Sam Dornan
3b4e230b7c Upgrade SQLAlchemy to 2.1 (#5007) 2026-10-01 19:17:30 -04:00
Sam Dornan
a31136cd21 Keep the FULLTEXT index on searches with short words or stopwords (#4970) 2026-09-30 22:45:44 -04:00
Sam Dornan
5d93201874 feat(search): rank multi-word searches by phrase on PostgreSQL (#4977) 2026-09-30 20:05:43 -04:00
Sam Dornan
fed6fc9172 refactor(db): follow-ups to the derived-state fixes (#4969) 2026-09-30 19:00:30 -04:00
Sam Dornan
79fbce6beb test(backend): build test rows through shared factories and enforce them with ruff (#4972)
* test(backend): build test ROMs through one make_rom factory

Tests created Rom rows by hand in dozens of places, each spelling out the
same slug and filename fields and deriving the slug inline. Production never
computes a slug from a name, so this was test-only filler duplicated across
files.

tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension,
**overrides), which fills the slug and filename columns and persists through
db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and
the local helpers and inline constructors across 35 test files now use it.
Each test keeps its filename shape (underscored stems in the FULLTEXT search
tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared
across files keep their exact slugs.

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

* test(backend): keep extensionless filenames intact in scan_stubs.add_rom

rpartition(".") on a name with no dot returned an empty stem and the whole
name as the extension, so make_rom stored ".README" for "README".
os.path.splitext leaves such names whole.

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

* test(backend): build test saves, states and screenshots through factories

Tests built Save, State and Screenshot rows by hand across about 20 files,
each spelling out file_name_no_tags, file_name_no_ext and file_extension
although BaseAsset already derives them from file_name.

tests/factories.py adds make_save, make_state and make_screenshot. Each sets
the rom and user ids, the file name, and a default file_path under the rom's
platform, applies overrides last, and persists through the matching db
handler. The conftest asset fixtures and the persisted constructors and local
helpers now use them. Rows a test observes keep their file_path, emulator,
slot, size and hash, and a filename part stays an override wherever it
differs from what the model derives.

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

* test(backend): ban direct add_* persistence in tests via ruff TID251

The factories only stay the one home for test rows if nothing routes
around them. Ruff's banned-api rule now flags db_rom_handler.add_rom,
db_save_handler.add_save, db_state_handler.add_state and
db_screenshot_handler.add_screenshot anywhere under tests/ except
tests/factories.py. Production code is unaffected.

The remaining add_rom calls move onto make_rom: the unique-path, soundtrack
and id-index tests in test_roms_handler.py, the scan tests in
test_fastapi.py, physical and missing rows in the feed, download and model
tests, and the name=None exporter rows. Scan tests keep a filename-derived
placeholder as the name, which scan_rom treats the same as no name. Three
calls keep a noqa: the tests of how add_rom merges a partial scanned row,
and the rescan test that persists scan_rom's output as a scan does.

The backend skill and the architecture doc now point at tests/factories.py.

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

* test(backend): move the firmware and client-token factories into tests/factories.py

The add_firmware and add_device_token conftest fixtures returned a builder,
unlike the importable make_* functions. They become make_firmware and
make_device_token alongside them, with the same defaults, and their callers
import them rather than requesting a fixture. make_device_token now draws the
raw credential from auth_handler.generate_client_token, so it carries the
real rmm_ prefix instead of restating it, and the hand-built client tokens in
the auth tests use it too.

The ruff TID251 ban now also covers db_firmware_handler.add_firmware and
db_client_token_handler.add_token under tests/.

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

* docs: point at every test factory, not just the ROM and asset ones

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:01:56 -05:00
Sam Dornan
5f50afa123 Search the gallery by providers' alternative titles (#4941)
* Search the gallery by providers' alternative titles

A search for "FF9" or "Final Fantasy 9" did not find "Final Fantasy IX":
the gallery search only matched roms.name and roms.fs_name, while the
alternative titles IGDB, MobyGames and ScreenScraper report lived in the
raw metadata blobs where no index reaches.

Add generated_search_aliases, a STORED generated column the engine fills
from those blobs, so every write path (scans, metadata refreshes, the
bulk update_rom, raw metadata edits) keeps it current with no backfill.
Migration 0145 rebuilds the MariaDB/MySQL FULLTEXT index over
(name, fs_name, aliases) and adds a pg_trgm GIN index on PostgreSQL, and
the search matches the column on both paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

* Compare the alias JSON type under the table's collation

On a utf8mb3_unicode_ci table, JSON_TYPE's result and the 'ARRAY'
literal carry different collations, so creating the generated column
failed with an illegal mix. CAST re-derives it, as _maria_text does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

* pr-ready step 2 (code-review): defer the alias column, share search columns

Loading a ROM no longer fetches generated_search_aliases, which only the
gallery search reads. The FULLTEXT match and the ILIKE fallback both take
their columns from one ROM_SEARCH_COLUMNS tuple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

* pr-ready step 3 (simplify): register the search indexes, share the CAST

Both search indexes join the generated-column index registry, so any
later rebuild of the alias column puts them back instead of leaving
MariaDB's FULLTEXT index narrowed (and every MATCH failing) or the
PostgreSQL trgm index gone. 0145 shrinks to ensure_roms_columns plus
retiring 0084's index, and its downgrade guards DROP COLUMN with
has_column, since MySQL has no DROP COLUMN IF EXISTS.

_maria_char carries the collation CAST that _maria_text and the alias
expression share, the alias expression extracts each array twice
instead of three times, and the dialect test runs the handler's own
_fulltext_match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

* Store the search aliases as plain titles

The alias column held each provider's array as JSON text, so a short
ILIKE search for '"', ',' or '[' matched every ROM with any alias. Both
engines print an array as ["a", "b"] however it was stored, so the
expression strips the brackets and quotes and keeps the titles
separated by spaces, which search terms can never match on their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

* Shorten the alias-search docstrings to one sentence

The migration and test-module docstrings explained the design in
several paragraphs; AGENTS.md asks for one sentence. The design notes
live in the PR description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-09-30 13:16:13 -05:00
Sam Dornan
b5070cd984 fix(backend): keep derived rom state in step with its source (#4931) 2026-09-30 11:49:11 -04:00
Claude
42e5b5d119 Remove the no-emdash Trunk linter after a one-time sweep
The linter ran over every Markdown file and Python comment, so full-repo
trunk runs on master kept failing on em-dashes that predate it. Replace
the existing ones once and drop the check. The AGENTS.md rule stays, the
v2 ESLint rule stays, and pr-ready's humanizer pass catches new ones in
prose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RyamrxVw5BzEidVzm68LY7
2026-09-28 16:59:56 +00:00
Georges-Antoine Assi
185e0ca03f test(roms): cover a status-filtered grouped sort
Addresses Greptile's review on #4878: a sibling the status filter drops
must not drive its group's last_played position.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 10:55:49 -04:00
Georges-Antoine Assi
389b420d14 fix(roms): pick grouped representatives among siblings the user can see
The grouped gallery's dedup window ranked every sibling before the
per-user status/hidden filter ran, so hiding the rom that won row_num = 1
removed the whole group even when visible siblings existed. The same
happened with a status filter matching only a non-primary sibling.

Build the per-user visibility predicate once and use it to rank matching
siblings first in the window, mask the group sort aggregate, and filter
the outer query. The window's base subquery is unchanged, so the covered
dedup plan is unaffected.

Fixes #4466

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 10:41:13 -04:00
Georges-Antoine Assi
96e2c2ad42 refactor(backend): pr-ready follow-ups for device installs
- 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>
2026-09-27 15:04:56 -04:00
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* 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>
2026-09-26 16:32:29 -05:00
Sam Dornan
cbfc904a48 fix(ra): count RomM's own RA hash match as RetroAchievements verification (#4816)
* 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>
2026-09-26 15:33:55 -05:00
Sam Dornan
5b3d0bf544 feat(sync): record a per-device save baseline to prove what did not change (#4768)
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>
2026-09-26 15:05:57 -05:00
Sam Dornan
9c1e6b2d86 refactor(backend): move engine-specific query SQL out of handlers into utils/sql_dialect.py (#4793) 2026-09-26 13:48:33 -04:00