Commit Graph

650 Commits

Author SHA1 Message Date
Sam Dornan
14fc8d9930 fix: treat every disc descriptor as a disc, not just .cue (#4532)
* Treat every disc descriptor as a disc, not just .cue

playlist_files keyed on .cue alone, so a Dreamcast .gdi set, a CloneCD
.ccd set and an Alcohol .mds set all fell through to "every file is a
disc" -- the descriptor and the raw tracks it cannot boot without were
listed side by side.

The three readers of the rule each got that wrong in their own way: the
playlist shipped inside the download zip named non-bootable tracks, and
the in-browser disc swapper offered them as discs.

Key on a set of descriptor extensions instead, so no one sheet format is
privileged over the others. The shape is unchanged -- descriptors if any,
else everything -- and so is the download zip, which lists every file
regardless.

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

* Keep a disc that stands on its own beside a descriptor

Selecting descriptors and discarding everything else assumed a multi-file
ROM is all one format. It is not: a .chd sitting beside a .gdi boots on
its own, and returning only the .gdi dropped it from the playlist and
from the swapper's targets.

Exclude the raw tracks a sheet points at instead of keeping only sheets.
The tracks are still not discs, so every case the previous commit fixed
stays fixed, and a disc no sheet describes now survives.

This also settles the same bug on the .cue path, which predates this
branch: disc1.cue + disc1.bin + disc2.chd used to list the cue alone.

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

* Count a sheet's audio tracks as tracks

A .cue names its CDDA tracks the same way it names its data track, so a
.wav or .flac beside one is data, not a disc. The playlist listed them.

Brings the list in step with the shell's own in src/main/discs/m3u.ts,
which has carried the audio formats since it was written.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 11:05:03 -05:00
Georges-Antoine Assi
827aef4221 Merge pull request #4490 from rommapp/fix/trigger-ddl-privilege-guard-3932
fix(migrations): name the fix when the server denies trigger DDL
2026-09-15 09:25:37 -04:00
Georges-Antoine Assi
78ba4c4721 fix(migrations): give the trigger-DDL probe a name no schema can hold
Trigger names are schema-wide, so the fixed probe name could name an
operator's own trigger, and DROP TRIGGER IF EXISTS would really remove it.
A fresh uuid per call makes the statement a guaranteed no-op, so the only
error it can raise is the refusal it is looking for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 09:20:54 -04:00
Georges-Antoine Assi
60e4e385b5 Merge remote-tracking branch 'origin/master' into fix/zip-rom-patching
# Conflicts:
#	frontend/src/locales/zh_CN/patcher.json
2026-09-14 18:44:46 -04:00
Georges-Antoine Assi
ff335ea2c0 fix(patcher): keep zipfile errors matchable and stop forcing ZIP64
A module-level exception tuple freezes zipfile.BadZipFile, but seven test
modules reload the zipfile module, which rebinds the class. After any of
them runs, a corrupt archive escaped the handler and surfaced as a raw
BadZipFile instead of a 400. Look the class up at raise time instead.
NotImplementedError goes with it, being a RuntimeError subclass.

Declare each rebuilt entry's final size instead of passing force_zip64,
so zipfile marks an entry ZIP64 only when it needs to; a patched ROM
handed to a basic unzip implementation was otherwise rejected even though
the unpatched archive loaded fine.

Drop the extracted and patched intermediates once they are consumed,
rather than holding three full-size copies for the life of the download.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 18:41:47 -04:00
Zurdi
d4f81f097f Merge pull request #4487 from rommapp/claude/graphql-api-migration-vu20z2
refactor(roms): give the ROM filters a single home, and match them against the facets mirror
2026-09-14 23:46:48 +02:00
Kyle Benzo
d8a32ab7dd fix(patcher): preserve output filesystem errors 2026-09-14 13:01:53 -07:00
Kyle Benzo
fad8b2943d fix(patcher): use archive fallback for zip extraction 2026-09-14 12:55:08 -07:00
kylebenzo
3e73579614 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-14 12:49:58 -07:00
Georges-Antoine Assi
07f5a1d005 refactor(migrations): tighten the roms catalog (simplify)
- `rebuild_generated_columns` owns the index drop, since it is the one
  place a column is dropped, so 0123's downgrade gets it too.
- `ensure_roms_columns` builds its action list first and runs on it, and
  no longer re-reflects the table to re-test a column it just added.
- One list behind `STEAM_FED_COLUMNS`, and `INHERITED_COLUMNS` says what
  the set difference at the use site used to.
- 0112 builds the view through `roms_metadata_view_sql`, and 0126 drops
  the add-column branch the shared copy made unreachable.
- Tests share one generated-expression helper and read index and column
  names off the module that owns them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 07:29:28 -04:00
Georges-Antoine Assi
e3f34a4562 fix(migrations): harden the roms catalog replays (code-review)
- `drop_roms_columns` drops a composite index that still spans a column
  it removes before the ALTER: MariaDB and MySQL would otherwise keep the
  index over the remaining columns, so 0126's unique index left by a run
  that died before its stamp would become UNIQUE (platform_id).
- `ensure_roms_columns` recreates `roms_metadata` whenever it is absent,
  so a run that died between its ALTER and the CREATE VIEW gets the view
  back on the replay instead of only when a rebuild is pending.
- A generated column the engine does not reflect as computed counts as
  not reading Steam and is rebuilt, rather than raising a KeyError.
- One home for the `steam_metadata` column name, imported by 0123.
- Tests pin the lost view, the leftover MariaDB default and the surviving
  unique index; the ALTER recorder matches `roms` as a whole word.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 07:14:10 -04:00
Georges-Antoine Assi
fa402ba234 fix(migrations): drop every front-loaded roms column on 0108's downgrade
0108 adds every column of the 5.3.0 catalog, so a chain that stopped
before a later revision and then downgrades to 0107 used to keep that
revision's columns, including a NOT NULL full_path_hash on MariaDB that
5.2.0 could no longer insert around. `drop_roms_columns()` now removes
whatever of the catalog is still there in one ALTER TABLE, restores the
pre-Steam expressions on the 0098 columns, recreates the view over what
remains and drops the PostgreSQL enum type.

The plain column list no longer needs a connection, so the enum type is
created just before the ALTER that needs it and dropped through one
helper shared with 0116.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 22:17:12 -04:00
Georges-Antoine Assi
f18ee70281 perf(migrations): add the 5.3.0 roms columns in one table copy
Every ALTER TABLE roms copies the whole table: the FULLTEXT index from
0084 rules out ALGORITHM=INSTANT (its hidden FTS_DOC_ID column survives
even a DROP INDEX), and a STORED generated column takes ALGORITHM=COPY on
every engine. The 5.2.0 -> 5.3.0 chain issued 21 such ALTERs, one per
revision, so a library with a JSON blob per provider on every row paid
for 21 copies.

`utils/roms_columns.py` now declares every column the chain puts on
`roms`, plain and generated, and `ensure_roms_columns()` adds whatever
the table lacks in a single ALTER TABLE. Each revision that used to add
its own columns calls it instead, so the first one to run on a database
does the copy and the rest find their columns in place. A table whose
generated columns predate 0123 is recognised by the provider they do not
read yet and rebuilt at the current definition in the same statement.

On MariaDB the copy also fills `full_path_hash` through a column
referencing DEFAULT that is dropped right after, so 0126 no longer runs a
whole-table UPDATE through the roms_facets triggers followed by a NOT NULL
rebuild.

Measured on a 73k-ROM copy of the dev library (MariaDB 11.3.2, 128 MB
buffer pool): 168.5s -> 48.9s for 5.2.0 -> head, with one 16s copy where
there were 21 rebuilds. The resulting schema is identical to the old
chain's on MariaDB and PostgreSQL, and a fresh install lands on the same
schema on MariaDB 10.11.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 19:17:49 -04:00
Georges-Antoine Assi
8c1ea8c083 review(pr-ready step 4): sharpen the gate name and trim the guard prose
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 07:58:48 -04:00
Georges-Antoine Assi
c4e9f1c934 review(pr-ready step 3): one predicate, one test home, real command names
The gate tested command names alembic never passes: it hands its environment
the per-command `fn` name, so `do_stamp` and `display_version` are what reach
it. Pin that with a canary over the closure the gate matches.

Probe before reading the applied heads, so only a server that refuses pays for
the lookup and the other dialects pay nothing, and fold the tests into the
module they mirror.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 07:56:55 -04:00
Georges-Antoine Assi
c644fd8058 review(pr-ready step 2): name SUPER as the fix, and probe only when revisions run
Verified against MariaDB 10.11, 11.3 and 11.8 with binary logging on: BINLOG
ADMIN does not lift the denial, only SUPER or the global flag does, and MySQL
8.4 never denies at all. The message said otherwise.

The probe also ran for every command that loads this env, so `current` and
`stamp` failed over a privilege they never need, while a downgrade at head
skipped the probe and could still half-drop a schema. Gate it on the commands
that execute revisions instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 07:50:03 -04:00
Georges-Antoine Assi
fe75def1f8 fix(migrations): name the fix when the server denies trigger DDL
MySQL and MariaDB reject every trigger statement, DROP TRIGGER IF EXISTS
included, while binary logging is on and the database user holds neither
SUPER nor BINLOG ADMIN. Ten revisions install triggers, so any of them
could abort startup with a raw traceback and leave a half-migrated schema
behind.

Probe the privilege once, before the first pending revision runs, and
fail with the two server-side fixes spelled out.

Fixes #3932

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 07:21:53 -04:00
Sam Dornan
8e61a38b7b Trim comments and docstrings to the repo's limits
Review polish over the whole change: every comment block over two lines
cut back, and the two carrying change history rather than current
behaviour rewritten to describe what the code does now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:38:05 +00:00
Sam Dornan
8809f06729 Harden the filter model after code review
Three defects the review pass turned up:

`from_stored_criteria` raised on a smart collection whose stored
`filter_criteria` holds a value the model rejects. That JSON is written
unvalidated and read in a loop over every smart collection, so one bad row
stopped all the later ones from refreshing on any ROM write, and 500'd a
public smart collection. It now drops the entries it cannot honour, which
is what the criteria reader did before it validated anything.

Two comments claimed `metadata_providers` matches id columns on `Rom`. It
matches them on the facets mirror, so a reader trusting the comment
concludes the filter needs no join and cross-joins `roms_facets` into the
query. Corrected, and pinned by a test asserting every registered filter
joins the mirror exactly once.

`as_query_dependency` silently mis-built a route for a field with an alias
or a `default_factory`, the latter sharing one mutable default across
requests. Both now fail at startup, and the helper has the tests it
shipped without.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:29:02 +00:00
Sam Dornan
d145e77f47 Merge remote-tracking branch 'origin/master' into claude/graphql-api-migration-vu20z2
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-13 00:25:37 +00:00
Georges-Antoine Assi
45f2e5be95 chore(migrations): settle on one spelling for the replay guards
Give the "which columns does this table already have" set a home as
`column_names`, and define `has_column` over it: 0098, 0112 and 0123 each
spelled it inline, and 0112 paid one full reflection of `roms` per candidate
column.

Use the builtin idempotency flags wherever they reach. 0121 was the last
revision guarding a column and an index by hand, and 0122 had two code paths
emitting the same statements; both now match 0111/0126/0128.

Skip 0126's digest backfill once the column is NOT NULL, so a replay no longer
full-scans `roms` to match zero rows.

Drop the test helpers that re-derived what `_schema_of` already returns, and
collapse the four-way `has_column` parametrize, two cases of which were really
schema assertions about 0112 and 0121.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 19:44:15 -04:00
Sam Dornan
983e24d5f8 refactor(roms): carry the ROM filters as one model
The filter vocabulary (13 multi-value filters with their logic operators,
plus the boolean and scope filters) was written out in five places: the
`/api/roms` query parameters, `filter_roms`'s 63-line signature, the
`kwargs.get` block in `get_roms_scalar`, the criteria translation in
`get_smart_collection_criteria`, and the `is_unscoped` test that decides
what may be cached.

That last one is the dangerous copy. The gallery's sidecar caches are keyed
on user/order/grouping but not on the filters, so a filter missing from
`is_unscoped` would let one user's narrowed gallery be stored under, and
served from, the shared "all" key.

`RomFilterParams` becomes the single home. The route takes it as a
dependency, `filter_roms` reads its fields, and smart collections rebuild
it from their stored criteria (legacy `selected_*` keys and the
`platform_id` scalar included, keeping `from_stored_criteria` the only
place that knows about them). `has_filters` now reads the model's own
fields, so a filter added later counts towards the cache gate without
anyone remembering to list it, and a test asserts that for every field.

The route reaches the model through `as_query_dependency` rather than
`Annotated[RomFilterParams, Query()]`, because FastAPI expands a query
model into its fields only when the model is a route's *only* query
parameter. `/api/roms` has a dozen others, so the native form would leave
one required parameter named `filters`: the schema would advertise it, the
generated client would be built from that, and a request carrying the
fields themselves would be rejected. A dependency's parameters are
flattened individually, so building one from the model keeps the fields.
An endpoint test pins that, since the failure is silent.

The API contract is unchanged: `/api/roms` still takes the same 58 query
parameters with identical types, descriptions, defaults and constraints,
and regenerating the frontend types from the new schema produces a
byte-identical `src/__generated__`. Only the order of the parameters in
the OpenAPI array differs, since FastAPI lists a dependency's parameters
after the route's own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-12 23:18:56 +00:00
Georges-Antoine Assi
ec5929b005 fix(migrations): let every 5.3.0 revision be replayed
MySQL and MariaDB auto-commit each DDL statement, so a revision that dies
partway keeps what it created while alembic_version stays behind. Every
start after that replays it and dies on a duplicate object, hiding whatever
actually stopped the upgrade and leaving the instance on a half-migrated
schema.

Eleven revisions create something ahead of a step that can fail. Most take
the guard alembic already offers; three need more:

- 0122 declares its indexes inline so InnoDB adopts one for the foreign key,
  and alembic issues those as their own statements, so `if_not_exists` on
  the table would not cover them. It reflects the table instead and fills in
  whichever index is missing.
- 0123 rebuilds its generated columns in one ALTER TABLE, so it now drops
  only the columns that are there and re-adds them all.
- 0126 resumes at whichever of its four steps the previous run reached.

`full_path_digest_sql` also coalesces a NULL fs_path/fs_name to match
`compute_full_path_hash`, since the disagreement folded the whole row to
NULL and aborted 0126 at its NOT NULL step.

Combines #4479 and #4481, whose fixes are carried here in full.

Co-Authored-By: Sam Dornan <sam.dornan@athleticgreens.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 17:58:12 -04:00
Kyle Benzo
7a1f012f15 fix(patcher): address PR code review 2026-09-11 21:25:32 -07:00
Kyle Benzo
3511214fe7 fix(patcher): patch ROM members inside ZIP archives 2026-09-11 21:23:20 -07:00
Georges-Antoine Assi
44f7e5d51d Merge pull request #4416 from rommapp/fix/launchbox-cache-duplication
perf(metadata): stop storing the metadata dumps twice over in the cache
2026-09-10 16:13:55 -04:00
Georges-Antoine Assi
decd5c61c4 refactor(cache): make the versioned store a type rather than three constants
The schema key, its version and the keys they cover were three constants per
store, retyped at each of the six places that used them and interchangeable
enough that one store's version could be checked against another's keys. They
are a `VersionedCacheStore` now, so a store is declared once and the startup
drop is a loop over a table.

The two reader gates were the same four lines, and a third read path was
still checking the data key without the stamp, so the LaunchBox entry points
disagreed about what populated meant. All three call one helper.

The drop probed each key before deleting it, spending a round trip per key to
learn what `unlink` reports anyway, and `delete` freed the store on the main
thread. Both imports also merge into their hashes, so each now drops a stale
store itself rather than trusting the drop to have happened at startup.

The alternate name index holds the bare id its reader wants, like the two
title indexes beside it, and follows through the same helper.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 16:10:09 -04:00
Georges-Antoine Assi
721197476a perf(metadata): rebuild a metadata store an older release wrote
The readers tolerated both the old and the new shape of every index this
branch changed, which left two shapes supported forever and, on an install
whose scheduled update is off, meant the old store answered every lookup
and the saving never landed at all.

Each store now carries a schema stamp. A store whose stamp is missing or
stale reads as unpopulated, is dropped at startup, and has its import
queued the way the WebP backfill is, so the shape change causes the
rebuild instead of being worked around. The readers know one shape again.

The projection each store is written with moves next to its key, and the
three stores that had none get one: Mame.xml kept 24 fields per record to
serve `Name`, Files.xml kept the platform and filename its cache key
already carries, and an alternate name entry kept the name it is stored
under. Together with the image list that is ~135MB.

Measured against the real dump: the eight LaunchBox hashes hold 385MB, and
a store stamped by an earlier release is dropped at startup for 386MB of
`used_memory` reclaimed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 15:45:32 -04:00
Georges-Antoine Assi
38cd2b6620 fix(auth): sanitize the username an OIDC provider hands us
`preferred_username` was stored verbatim, so a provider that issues
`first.last` created an account whose username RomM's own rules reject.
The account works for login but cannot be edited afterwards: every write
through the users endpoints re-runs `validate_username` on it.

Coerce the name to the allowed charset at registration, falling back to
the email local part when nothing usable survives, and suffix it until it
is free since the column is unique.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 20:37:12 -04:00
Georges-Antoine Assi
ce42873424 Merge pull request #4396 from Spinnich/feat/game-anniversary-widget
feat(home): add a game anniversary widget
2026-09-09 13:42:18 -04:00
Georges-Antoine Assi
a8385cdaa8 style(anniversaries): trim the comments and simplify the day parser
Comment and docstring pass over the `released_days` change: cut the copies of
rationale that already live next to the thing they describe, and drop the
sentences defending obvious choices.

`RELEASED_DAY_REGEX` now carries the calendar ranges, so a match is a valid day
and `parse_released_days` needs no sentinel pair and no second range check.
`release_day_ranges` stops re-sorting what `epoch_ms_in_ranges` already sorts.
`anniversaryQuery`'s return type is a named export, so the widget imports it
instead of unwrapping a `ReturnType`, and the widget's two reset paths share
`showEmptyDay`.

`loadMore` is `loadNextPage`, since it appends one page rather than the rest.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 12:34:49 -04:00
Georges-Antoine Assi
976dd09930 refactor(anniversaries): read the day off the shared rom list
`GET /api/roms` already does what `/roms/anniversaries` hand-rolled: it selects
ordered ids over the filtered set, takes the total from that index, hydrates
only the page asked for, and re-projects the rows into id order. So the widget
now asks it for a page rather than owning an endpoint that pulls the whole day.

`released_days` on the list endpoint takes days as "M-D", matching any year, and
`released_before_year` bounds them. Both go through `filter_roms`, so the same
day-of-year match is available to the gallery filters and to smart-collection
criteria, and the range union stays where it was: still sargable, still a
covering index range scan on `idx_roms_generated_first_release_date`, no SQL
date function and no dialect branching. Verified on a 73k-rom database that the
plan through the list endpoint's join is unchanged: `type=range`,
`Using where; Using index`, no filesort.

The filter means exactly what it says, so the calendar policy moved to the
client, where the clock it depends on already lived. `anniversaryQuery` picks
the days and the year bound off the viewer's own date: it skips 1 January,
where several providers park year-only metadata, rolls 29 February onto 28
February in a non-leap year, and bounds the years at the viewer's own. The
server no longer has to second-guess a timezone offset, so the 31 December
asked for on 1 January UTC correction is gone rather than fixed.

Consequences for the widget: the counter is the day's real total instead of one
clipped at a 500-row ceiling that no longer exists, and a card costs one page
of 24 rather than up to 4 MB up front. Paging backwards stays in memory;
only moving past the loaded pages fetches, with the spinner on the arrow so
focus is never yanked mid-page. A failed page keeps the card on screen.

`released_days` is added to the list endpoint's unscoped-cache gate: the
sidecar keys encode no filters, so a narrowed page must not be served under the
shared "all" key. Covered by a test that primes the unscoped key first.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 12:02:32 -04:00
Georges-Antoine Assi
0abff94157 security: strip control characters from names reaching the mod_zip manifest
The mod_zip manifest that streams multi-file downloads is line-oriented, and
the NAME field of each record was interpolated from a rom file's full_path
verbatim. A line feed in that path would split the record and forge an extra
archive entry pointing at any internal nginx location.

sanitize_filename now drops the whole C0 range plus DEL instead of only null
bytes, so a control character cannot enter fs_name through a rename or an
upload. ZipContentLine scrubs the same range from the entry name, which is a
path and so cannot go through sanitize_filename, and rejects a location that
was not URL-encoded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:17:52 -04:00
Georges-Antoine Assi
907ae7a79f Merge branch 'master' into feat/game-anniversary-widget 2026-09-09 10:23:08 -04:00
Spinnich
868a5c03e7 feat(home): add a game anniversary widget
Shows games released on today's date in an earlier year, one at a time,
with arrows to page through the rest. Sits in the Home widget rail beside
Random pick and Library stats, with its own Settings toggle (default on)
and an entry in the drag-reorder list.

New endpoint GET /api/roms/anniversaries, ROMS_READ, whole-library,
returning up to 24 SimpleRomSchema oldest release first. Clients send
their own local month and day so "today" matches the calendar in front of
the user rather than the server's UTC clock.

The day-of-year match is a union of one-day ranges over
generated_first_release_date rather than MONTH()/DAY() on the value.
Ranges are sargable, so idx_roms_generated_first_release_date serves both
the match and the sort as one covering range scan: 195 rows examined and
~2 ms against 63,334 rows and ~70 ms for the function predicate on a
100k-row table. Emitting no SQL date function also means no dialect
branching and no migration.

1 January returns empty. Several providers park year-only metadata there
(ScreenScraper parses a bare year with %Y, CSDb publishes nothing else,
IGDB reports year precision as 1 January), so nothing in the stored data
tells a real 1 January release apart from an unknown day. Leap-day
releases roll onto 28 February in non-leap years.

Visibility follows /random: filter on hidden platforms and roms, then
re-check each hydrated row with perms.can_see_rom.

Closes #3440

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 17:31:27 +00:00
Georges-Antoine Assi
dd7f46b52c fix: make metadata exports and matching follow the library structure
Testing the custom library structure against a live library turned up four
defects, all of them a path being reduced to a bare file name.

Both exporters wrote a rom's `fs_name` alone, so every game a template nests
was exported as if it sat in the platform folder: ES-DE and Pegasus could not
find any of them. They now write the rom's path relative to the platform
folder, the folder the metadata files themselves live in, and copy exported
media into the matching subfolder so two identically named roms keep their own
artwork.

Merging into an existing gamelist.xml / metadata.pegasus.txt keyed entries by
file name too, so identically named roms in different folders both merged into
the first entry and produced duplicates. Entries are now keyed by path, with a
Pegasus block matched by the folder its listed files sit in.

Reading a gamelist.xml had the same collision: two roms sharing a file name
both took the metadata of whichever entry was parsed last. A rom's own path now
wins, and a bare file name stays a fallback key for the tools that write those,
dropped when two entries share it.

Default discovery surfaced hidden folders as multi-file games, unlike
structured discovery which skips them. exclude_multi_roms now owns that rule
for both.

Also validate `exclude`'s exclusion_type: an unknown value reached
`Config.__getattribute__` and returned a 500 rather than a 422.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 07:31:05 -04:00
Georges-Antoine Assi
6b01e9943e refactor: trim review-pass comments and cover LocationChip
Cut the comments that explain rather than note: the migration's four-paragraph
docstring, the upload-path and digest-SQL docstrings, and the mark-missing note
in the scan loop. Drop an em-dash from LocationChip's header per CLAUDE.md.

Reword 0126's downgrade error so it no longer embeds a SELECT, which bandit
reads as string-built SQL, and mark the dialect-selected backfill nosec B608 the
way the other migrations do.

Add the LocationChip test its HashChip sibling already had, covering the copy
going through useClipboard (the composable is what applies the secure-context
guard).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 20:17:28 -04:00
Georges-Antoine Assi
f105622513 fix: address code review on the library structure unique index and relocation
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.

Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.

Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.

Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.

Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:14:58 -04:00
Georges-Antoine Assi
ebe8002e12 Merge pull request #4387 from Spinnich/perf/scan-read-chunk-size
perf(scan): read files in 256 KiB chunks instead of 8 KiB
2026-09-07 14:26:46 -04:00
Georges-Antoine Assi
e51bedffe9 cleanup 2026-09-07 14:21:14 -04:00
Spinnich
abade695c7 perf(scan): read files in 256 KiB chunks instead of 8 KiB
Hashing runs in threads via asyncio.to_thread, and hashlib/zlib release
the GIL per chunk. At 8 KiB the threads hand the GIL back so often that
concurrent scans contend rather than overlap, which capped scan
concurrency and made high worker counts actively harmful.

Hashing 1.96 GiB of real ROM files at 8 workers goes from 154 MiB/s to
666 MiB/s (4.3x). Single-worker throughput is unchanged (108 vs 114
MiB/s), so this is not read-syscall overhead; it only bites under
concurrency. 256 KiB is the knee, 1 MiB measured no better.

The chunk bounds a streaming read, so peak memory is one chunk per
in-flight file, a few MiB at any realistic worker count.

Digests are unaffected: all 67 files in the test library produce
byte-identical crc/md5/sha1 at 8 KiB, 64 KiB, 256 KiB and 1 MiB.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 17:55:19 +00:00
Georges-Antoine Assi
e320bf5ed4 style(backend): tighten the index comments and docstrings
Cut the docstrings back to the one paragraph the surrounding migrations use,
and drop the comments that restate the index name next to them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 13:02:38 -04:00
Georges-Antoine Assi
055700bfed perf(backend): index the last unindexed foreign keys on PostgreSQL
The list covered firmware and the music tables but not saves.user_id,
states.user_id, screenshots.user_id, rom_file_user.user_id,
memory_cards.platform_id or streaming_container_adoptions.decided_by_user_id,
so a user delete still sequentially scanned the three largest per-user tables
on PostgreSQL, which is the case the pass set out to fix.

Add a test that recomputes the rule (a single-column foreign key whose column
leads no index, primary key or unique constraint) from the model metadata, so
the next model foreign key cannot be forgotten silently.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 12:57:01 -04:00
Sam Dornan
75a88fbb68 perf(backend): index the remaining play_sessions foreign keys on PostgreSQL
`play_sessions.device_id` and `play_sessions.sync_session_id` were left out of
the PostgreSQL foreign-key list, which is inconsistent with the criterion 0124
states for itself: a column queried directly or walked by `ON DELETE` needs a
real index there. Every other index on the table leads with `user_id`, so
`device_id` is only ever a second column and `sync_session_id` appeared in no
index at all. Both are `ON DELETE SET NULL`, so deleting a device or a sync
session made PostgreSQL scan the whole table.

That scan grows with every session played. On a 60k-row table with 1200 rows
pointing at one device, the row lookup behind the SET NULL goes from a 7.6ms
sequential scan to a 0.14ms index probe, taking the statement from 53ms to
38ms; the remainder is row rewriting no index avoids.

The `device_id` query filter in `get_existing_session_keys` is already served
by `uq_play_session_identity`, since it leads with `user_id` too, so this is
about the delete path rather than that lookup.

MariaDB is unaffected: InnoDB already created implicit indexes on all three
columns, which is why these are dialect-gated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 14:49:32 +00:00
Sam Dornan
5bb2ae1c8c Merge branch 'master' of https://github.com/rommapp/romm into claude/database-performance-indexing-9t14uh
# Conflicts:
#	backend/alembic/env.py
2026-09-07 14:33:47 +00:00
Sam Dornan
c6c993bebc style(backend): format utils/database.py with the pinned black
`trunk_check` reported `backend/utils/database.py` as unformatted. Adding the
index constants pulled the file into trunk's modified-file scope, which
surfaced a formatting deviation that predates this branch: black 26.5.1 drops
the redundant parentheses from an `except` tuple, which PEP 758 makes valid
syntax on the Python 3.14 this project requires. Three `except` clauses in
otherwise untouched helpers change as a result; the file cannot pass
`trunk fmt` without them.

Also collapses the AUTOGENERATE_EXEMPT_INDEX_NAMES assignment onto one line,
which is the same formatter's doing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 14:10:23 +00:00
Sam Dornan
c3b32a7710 fix(backend): make the 0122 downgrade work on MariaDB, and trim comments
Adding a composite index that leads with a foreign-key column lets InnoDB
re-point the constraint at it and discard the implicit single-column index.
Reversing 0122 then failed with "Cannot drop index 'ix_rom_user_user_rom':
needed in a foreign key constraint" on `rom_user.user_id`, and would have on
`screenshots.rom_id`. The downgrade now restores those two implicit indexes
first, and a full up/down/up cycle leaves the schema byte-identical to a
database that never ran the migration.

Also sets `path_separator = os` in alembic.ini, silencing the deprecation
warning about the legacy space/comma/colon path splitting. `prepend_sys_path`
holds a single entry, so the behaviour is unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 14:04:01 +00:00
Sam Dornan
a429c4b9db perf(backend): add the missing gallery indexes and reconcile model/schema drift
Four query shapes had no index that could serve both their predicate and
their sort, and a class of foreign-key columns was relying on an implicit
index that only MariaDB and MySQL provide.

New portable indexes:

- `screenshots (rom_id, user_id)`. `Save.screenshot` / `State.screenshot`
  resolve a thumbnail per row, so this lookup runs once per card on the
  continue-playing rail. 0093 added the equivalent to `states` and noted
  `saves` already had it; `screenshots` was missed.
- `rom_user (user_id, rom_id)` and `rom_user (user_id, last_played)`.
  `unique_rom_user_props` leads with `rom_id`, which covers the gallery's
  outer join but not the reverse direction, where sorting or scoping by a
  per-user column starts from this table.
- `roms (platform_id, name_sort_key)`. The gallery is browsed one platform
  at a time and ordered by name, and no index carried both columns. On a
  120k-row library across 20 platforms this takes the first page from
  5.8ms/1568 buffers to 0.6ms/75 buffers. Deep offsets converge, since the
  skipped rows are walked either way.

New PostgreSQL-only foreign-key indexes:

MariaDB and MySQL index every foreign key whose column is not already some
index's leftmost prefix; PostgreSQL does not. Eight such columns are queried
directly or walked by `ON DELETE`, so they get a real index there. Creating
them everywhere would leave the other backends with duplicates, so they are
dialect-gated and exempt from autogenerate.

Model/schema reconciliation:

Fifteen live indexes existed only in the migrations. Worse, `alembic/env.py`
never imported six models, so `devices`, `client_tokens`, `device_save_sync`,
`sync_sessions`, `play_sessions` and `streaming_container_adoptions` were
absent from the metadata autogenerate compares against, and autogenerate in
fact failed outright resolving `saves.origin_device_id`. With the imports
fixed it would have proposed dropping every one of those indexes.

Declares all of them on their models, matches `PlaySession` to the unique
index 0076 actually created, and adds a test that fails on any future index
drift so this cannot silently recur.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 13:46:35 +00:00
Georges-Antoine Assi
1393f4196e Merge remote-tracking branch 'origin/master' into claude/pr-4367-status-sql1q9
# Conflicts:
#	backend/tests/utils/test_gamelist_exporter.py
#	backend/tests/utils/test_pegasus_exporter.py
#	backend/utils/pegasus_exporter.py
2026-09-06 11:08:58 -04:00
Sam Dornan
4364513ae5 fix(export): keep both a logo and a marquee in the Pegasus export
Pegasus logo and marquee both land in ES-DE's marquees folder. With the
same extension the second copy was skipped as already present, and the
metadata pointed both keys at the first file. A destination already
claimed by another source now gets the asset key appended to its name.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Dye15Zspts7hBruKYsPuT
2026-09-06 12:34:18 +00:00