Commit Graph

4770 Commits

Author SHA1 Message Date
Bee
f50eacfcbd feat: add browser PICO-8 player
Add v2 browser playback for .p8 and .p8.png cartridges, backed by the
FAKE-08 WebAssembly runtime, with canvas rendering, audio, fullscreen and
keyboard, gamepad, mouse and touch input. Wires up platform detection,
play actions, routing, localization, gallery navigation, play-session
tracking and lifecycle cleanup.

The runtime is fetched in the emulator stage of docker/Dockerfile, pinned
by source commit and verified with sha256, so it is provisioned the same
way as EmulatorJS, Ruffle and js-dos rather than committed to the repo.

DISABLE_PICO8 gates the player, matching the existing DISABLE_EMULATOR_JS,
DISABLE_RUFFLE_RS and DISABLE_JSDOS toggles.

Based on #4383.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 17:59:52 -04:00
Georges-Antoine Assi
08f294d0fa Merge pull request #3571 from rommapp/claude/kind-goodall-0b77y7
feat: Per-platform custom library structure with non-destructive identity
2026-09-08 16:46:44 -04:00
Georges-Antoine Assi
892657465f fix: stage the config fixture for e2e and address review findings
The e2e job copied only the fixture library, not the config.yml declaring its
platform-folder-first layout, so the seeder scanned an empty library.

Reject `.` and `..` template sections: no directory listing yields either, so a
template carrying one discovered nothing and marked the platform's roms missing.

Drop the cached `full_path` when either half is set. A scan reads it and then
renames the file in place, which left the cached pair stale.

Point `build_physical_fs_name` at the index 0126 actually creates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 09:11:16 -04:00
Georges-Antoine Assi
568aa818de refactor: tighten the library structure naming and docstrings
Rename `FirmwareTemplate.platform_path` to `firmware_dir`: it returns the
firmware folder, while the same name on `StructureTemplate` returns the platform
folder. Name the watcher's index for the segment it points at.

Fold the two reads of a raw structure key into `_raw_template`, and drop the
docstrings that only restated a one-line delegation or a signature.

Remove `footer-create-summary-default`, which no component references and whose
copy still named Structure A.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:53:55 -04:00
Georges-Antoine Assi
a7ecfd96a9 feat!: make filesystem.structure the single library layout
`filesystem.structure` now spells out the whole layout rather than only the part
below a platform folder. A template is relative to the library root, `{platform}`
marks the platform folder, and `{game}` marks where a game begins.

Merge `{gameFile}` and `{gameDir}` into one `{game}` terminal. The information a
terminal carried was the depth, not the kind: at a declared level a file is a
game of its own and a folder is one multi-file game, which a stat answers. That
drops the two-template idiom for a level holding both, and `_discover_default_roms`
with it, since the default scan is now just `roms/{platform}/{game}`.

Retire the auto-detected `{platform}/roms` layout, along with
`filesystem.roms_folder` and `filesystem.firmware_folder`, which named one path
segment each that a template now contains. Both are refused at startup with the
template that reproduces the layout, so an instance that relied on either says so
instead of scanning an empty library and marking every rom missing. Firmware gets
its own `structure.firmware` key rather than following the rom layout implicitly.

`get_roms_fs_structure` keeps meaning the folder a platform's games start in, so
the `.physical` sentinel paths already in the database still resolve. Per-platform
overrides have to agree with `default` on where the platform folder sits;
relocating one platform needs platform discovery and the watcher to union several
roots, which is left out.

The setup wizard reports `library_ready` plus the configured template instead of
a `struct_a`/`struct_b` discriminator, so the banner shows the layout in force
rather than guessing it client-side.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:39:21 -04: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
30212cdf66 Merge pull request #4393 from rommapp/fix/quiet-rq-scheduler-heartbeat-logs
Quiet RQ's per-tick scheduler heartbeat log line
2026-09-07 21:57:00 -04:00
Georges-Antoine Assi
b62dbb5d9c Trim the noise-filter comments and cover the worker wiring
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 21:43:11 -04:00
Georges-Antoine Assi
ade76effbb Quiet RQ's per-tick scheduler heartbeat log line
Each worker started with --with-scheduler forks a scheduler that logs
"Scheduler sending heartbeat to <queues>" on every 1s tick. With
LOGLEVEL=DEBUG that is two lines per second, which drowns out the rest of
the log.

Generalize the existing registry-cleanup filter to cover RQ's periodic
noise and install it on the rq.scheduler logger before the worker forks
the scheduler off.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 21:38:38 -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
a73667a5ca refactor: rename the parsed template type to StructureTemplate
`LibraryStructure` named two unrelated things: the A/B enum for which of
RomM's two folder layouts a library uses, and this branch's parsed
per-platform template. Both were imported into handler/filesystem.

The parsed template is now `StructureTemplate`, with `parse_library_structure`
and `parse_platform_structures` following it to `parse_structure_template` and
`parse_platform_templates`. `LibraryStructure` again refers only to the enum.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:50:08 -04:00
Georges-Antoine Assi
3b91f7a112 fix: key filesystem.structure case-insensitively like system.platforms
`system.platforms` lowercases its folder-name keys so lookups ignore case,
but `filesystem.structure` matched `fs_slug` exactly. A folder written the
same way in both blocks (`Atari - 2600`) bound its platform correctly while
its structure template silently did not apply.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:22:23 -04:00
Georges-Antoine Assi
9dcaf89890 fix: address PR review feedback on library structure and relocation
A grouping folder is no longer also a game. With `{gameDir}` and
`{category}/{gameFile}` declared together, the category folder was surfaced
as a multi-file game *and* descended into, listing its contents twice. A
folder any template descends into is now treated as a grouping level.

Relocation runs for every platform, not only those with a custom structure.
Dropping a platform's template moves every game back to the platform root,
which previously read as a library of new games and orphaned all the saves,
play history, favorites and collection membership. A library whose paths are
unchanged still costs one query and no hashing. This also removes the need
for a manual "apply relocation" toggle.

Physical games are excluded from relocation candidates: they have no file, so
they read as having disappeared from their path on every scan.

A near-miss on the terminal macro (`{gameFolder}` for `{gameDir}`) now names
the offending section instead of only reporting a missing terminal.

Documents two limits the QA pass asked about: a move that also compresses or
extracts the game changes its size and is not detected (the size pre-filter
runs before hashing), and how reverting to the default layout behaves.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:01:33 -04:00
Georges-Antoine Assi
4219f56f10 Merge branch 'master' into claude/kind-goodall-0b77y7
Conflict resolution notes:

- Locale rom.json: master sorted and reworked every file; took master's and
  re-inserted `location` / `location-copied` in sorted position. Added them to
  the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
  and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
  master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
  (master), and the scan loop keeps master's early missing-sync plus its
  restored-rom emit alongside this branch's relocation pass. The relocation
  filter now applies only to the identify loop, so a relocated rom is no longer
  re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
  `purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
  premise that same-named files in different folders are distinct games.
  Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
  all share one folder, so a duplicate title is still rejected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 16:24:59 -04:00
Georges-Antoine Assi
eef3e55d29 fix(gallery): join roms_metadata before the grouped dedup window
The genre/franchise/company/publisher/developer/collection/age-rating/
player-count filters read from `roms_metadata`, but the join was added at the
end of `filter_roms`, after the "Group ROMs" block had already derived its
dedup window from the query. The window therefore filtered on a table it never
joined: the database cross-joined `roms` against `roms_metadata` (a view over
`roms`), which SQLAlchemy reports as a cartesian product.

Besides the cost, the window then ranked every ROM in the library rather than
the matching ones, so a game whose matching version was not the group's primary
one disappeared from the gallery entirely.

Fixes #4389

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 16:22:18 -04:00
Georges-Antoine Assi
3fd66c517e Merge pull request #4386 from Spinnich/perf/scan-workers-default
perf(scan): default to 4 scan workers instead of 1
2026-09-07 14:29:38 -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
eb7d72a500 Merge remote-tracking branch 'origin/master' into perf/scan-workers-default
# Conflicts:
#	examples/docker-compose.example.yml
2026-09-07 14:23:47 -04:00
Georges-Antoine Assi
e51bedffe9 cleanup 2026-09-07 14:21:14 -04:00
Spinnich
e090574eff perf(scan): default to 4 scan workers instead of 1
Hashing 1.96 GiB of real ROM files is 2.2x faster at 4 concurrent
workers than at 1 (108 -> 240 MiB/s on 16 cores, 108 -> 264 MiB/s
pinned to 4 cores). Pinned to 2 cores it is still 1.6x, so the new
default costs nothing on small hosts.

Metadata providers cap themselves independently of this value, so the
extra workers queue rather than exceed an allowance: ScreenScraper holds
a concurrency limiter set to the account's advertised thread count, and
the other adapters pace their own request rate. Database work in the
scan path is synchronous on the event loop, so it serializes regardless
and the connection pool is unaffected.

The compose example advised one worker per CPU, which overshoots on a
large host. Both it and env.template now say what raising this actually
buys, since metadata is paced no matter how many workers there are.

Only installs that never set SCAN_WORKERS move; any explicit value is
preserved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 17:56:27 +00: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
49b4f7fbcc Merge pull request #4384 from sdornan/claude/database-performance-indexing-9t14uh
perf(backend): add missing gallery indexes and reconcile model/schema index drift
2026-09-07 13:45:12 -04: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
ed57e30a41 refactor(backend): drop two more redundant indexes and trim the prose
ix_memory_card_versions_card and ix_devices_user_id are leftmost prefixes of a
wider index on the same table, the shape 0125 exists to remove, so move them
there rather than declaring them on the models.

Also replace the deprecated version_path_separator that path_separator was
added alongside, and cut the migration and model comments that restate each
other or explain the change rather than the schema.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 12:57:08 -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
Georges-Antoine Assi
fba415115e refactor(backend): load every model from one place
env.py listed the model modules by hand so autogenerate would see them, and
this branch had already had to patch six omissions into that list. Walk the
package instead, from a helper the index-drift test can share.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 12:56:52 -04:00
Georges-Antoine Assi
7b2baaa545 refactor(config): rename EJS_AUTO_SAVE_SYNC to EJS_ENABLE_AUTO_SAVE_SYNC
The config.yml key (emulatorjs.auto_save_sync) is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 11:08:02 -04:00
Sam Dornan
0609818a05 test(backend): make the index-drift test self-contained
The comparison read whatever `BaseModel.metadata` happened to hold, which is
populated as a side effect of `tests/conftest.py` importing fourteen model
modules for its `clear_database` fixture. A table missing from the metadata
makes `compare_metadata` report every one of its indexes as removed, so the
test's result depended on imports that exist for an unrelated reason: shrink
that fixture and the test starts reporting drift that isn't there.

It now walks `models/` and imports every module itself, so a newly added
model is covered without anyone remembering to, and asserts up front that no
database table is missing from the metadata. Without that guard an incomplete
metadata is indistinguishable from real drift in the failure output.

Verified standalone and in the full suite on PostgreSQL 16 and MariaDB 11.4;
the guard exempts `alembic_version`, which has no model.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 14:55:50 +00: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
Georges-Antoine Assi
1443f66cf5 Merge branch 'master' into feat/auto-save-sync 2026-09-07 10:24:48 -04: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
0ec3e5a22a perf(backend): drop two indexes that duplicate a wider one
`idx_rom_files_rom_id` (0079) is the leftmost prefix of
`idx_rom_files_rom_id_category` (0109), and `idx_rom_notes_rom_user` is the
leftmost prefix of `unique_rom_user_note_title` on
`(rom_id, user_id, title)`. Both only cost writes now.

MariaDB re-points a foreign key at another qualifying index when the one it
was using is dropped, and both columns keep such an index, so the
constraints stay enforced.

`collections_roms.unique_collection_rom` looks like a third case, since it
repeats that table's primary key column for column, but on PostgreSQL that
name belongs to the primary key itself and dropping it drops the key. Left
alone rather than shipping something whose meaning changes per backend.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 13:46:50 +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
b930a37448 Merge remote-tracking branch 'origin/master' into fix/ss-quota-breaker-recovery
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-06 22:54:48 -04:00
Georges-Antoine Assi
f9b6b4dc9a fix(screenscraper): check refused credentials before re-checking the quota
The quota guard ran first, so an armed breaker sitting on top of a refused
credential set sent the account probe every 60 seconds with credentials
ScreenScraper had already rejected. The probe could learn nothing: its 403
was caught and the credentials breaker restored, and the caller was then
told about the quota anyway. Ordering the credentials guard first spends no
request on it and reports the refusal the operator actually has to fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 22:49:03 -04:00
Georges-Antoine Assi
345dddd98b revert(search): keep the compact gather
The paired (name, coroutine) form cost 20 lines of vertical space to buy a
correct provider name in one error log, which zip's strict=True already guards
the length of. The comment and docstring trims from the same pass stay.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:44:10 -04:00
Georges-Antoine Assi
424b9cb75d refactor(search): pair each provider lookup with its name
The resolver took the provider names as a second tuple that had to stay in the
same order as the gather, which a reordered lookup would silently break. Pairing
the name with its coroutine follows the shape scan_handler already uses for
provider_fetches, and folds the gather into the resolver.

Also trims the comments and docstrings the review pass flagged as over-long.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:40:26 -04:00
Georges-Antoine Assi
ebfc8c7966 fix(search): stop one provider's failure from emptying the dialog
The metadata search gathers every provider without return_exceptions, so an
unreachable IGDB took ScreenScraper's, MobyGames', Flashpoint's, LaunchBox's
and Demozoo's matches down with it and the user got a 500 instead of the
matches that had already come back.

Both gathers now collect exceptions and resolve them per provider, mirroring
the resolve_fetch pattern the scan already uses. int(search_term) is evaluated
before the gather, so an invalid ID still reports as a client error.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:35:32 -04:00
Georges-Antoine Assi
6161f8057d refactor(screenscraper): report a short-circuited lookup per rom
A tripped breaker answers in ScreenScraper's place, so the empty match it
produces is not a miss and must not clear the rom's stored ss_id. The scan
learned that by sampling the module-wide is_breaker_tripped() at three points,
which reads another rom's trip as this rom's evidence.

SSHandler now raises ScreenScraperExhaustedError instead of swallowing the
breaker's error, carrying the match it would have returned so the name the
filename lookup derives locally (Switch title database, MAME, PS2 OPL) still
reaches the scan. fetch_ss_rom catches it the way it already catches
ScreenScraperRateLimitError, and drops ScreenScraper from attempted_sources
from a plain local, so the signal is exactly this rom's own lookups.

Also folds in a cleanup pass over the branch: the dead default_factory arm in
_ScanState.reset(), one home for the ssuserInfos.php path, asyncio.wait_for
around the quota probe so it cannot block behind a media download holding the
concurrency slot, and shared fixtures for the ScreenScraper tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:35:25 -04:00
Georges-Antoine Assi
cfa4afe5ab fix(db): keep 0123's generated columns off a utf8mb3 collation clash
MariaDB resolves JSON_UNQUOTE under the connection charset while a literal
in a generated column takes the table's, so the NOT IN and REGEXP guards
were an illegal mix on a server configured for utf8mb3_unicode_ci, and the
whole ALTER failed. 0098 already routes those operands through
CAST(... AS CHAR); this reuses the same helper for the columns 0123 rebuilds
and the three it adds.

Verified from an empty schema on all three configurations CI covers:
mariadb utf8mb3_unicode_ci, mariadb utf8mb4_general_ci and postgres.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:54:07 -04:00
Georges-Antoine Assi
17bd4207a0 Merge remote-tracking branch 'origin/master' into claude/igdb-keywords-themes-perspectives 2026-09-06 18:48:46 -04:00
Georges-Antoine Assi
d94a280f31 fix(backend): let the recommendations inspector import its own package
The tool reached `decorators.database` through `handler.auth.permissions`
before anything had initialised `handler.database`, which is the order the
cycle between the two does not survive. It could not start at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:38:36 -04:00
Georges-Antoine Assi
0b1f6f7c80 feat(recommendations): index a scanned rom before the nightly build
A game added today had no edges until the 5:30 AM rebuild, so its "Similar
games" section was empty and nothing could reach it from a feed.

`build_for` scores a handful of ROMs against the current library instead of
sweeping every pair, and folds them into the stored neighbour lists of the
games they matched so the new game is reachable from both directions. The
full build is the same sweep with every ROM as a target, so the two paths
share one implementation rather than drifting.

The scan hands over the ids it wrote. Past MAX_TOP_UP_ROMS the incremental
path saves nothing, so that case queues a rebuild rather than blocking the
scan on work a rebuild would redo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:38:32 -04:00
Georges-Antoine Assi
00bf206b46 chore(backend): cut a log nobody reads and a comment that ran long
The sigil import-time debug line never printed at the default INFO level,
and the binding's absence already reaches the UI through
SigilService.is_enabled() on /heartbeat.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:00:25 -04:00
Georges-Antoine Assi
714c99693b fix(recommendations): weight a co-occurrence by the evidence behind it
Co-play and co-collection were a bare cosine, which saturates at 1.0 the
moment two games are always seen together. On a single-user server, the
common case, that is every pair of games the owner has played: the signal
became a flat +0.15 on all of them rather than something that discriminates
between them, and a genuinely similar unplayed game needed a content score of
0.273 just to draw level. Tetris and Madden were neighbours.

The cosine is now damped by the number of sightings behind it, the way
`get_fallback_rom_ids` shrinks a rating toward the mean by its vote count. A
lone sighting keeps a quarter of its weight, which leaves it under
MIN_EDGE_SCORE on its own, while a pair a whole server agrees on is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:04:32 -04:00
Georges-Antoine Assi
d84fa1101e fix(recommendations): guard the vote count and the similar-games auth
The rating-count column cast whatever `total_rating_count` held straight to
a number, without the digit guard every other numeric branch in the
migration carries. The metadata blobs are writable verbatim through the raw
metadata form, so a library holding a non-numeric value could not migrate at
all: PostgreSQL aborts the ALTER TABLE on `invalid input syntax for type
numeric`. The MariaDB branch also reached for JSON_VALUE, which MySQL only
gained in 8.0.21, below the 8.0 the docs advertise.

`/roms/{id}/similar` was gated behind DISABLE_DOWNLOAD_ENDPOINT_AUTH while
resolving permissions unconditionally, so with that flag set an anonymous
request hit `UnauthenticatedUser.role` and 500'd. It is not a download
endpoint; it now requires ROMS_READ, as /api/recommendations does.

The details page also fetched similar games with the feature switched off,
and OverviewTab took a `webp` prop for state it already reads from
useWebpSupport.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 16:40:12 -04:00
Georges-Antoine Assi
6a96a64b21 test(backend): cover the Steam facets the engine scores on
0123 appends steam_metadata to the generated facet chains, but every test
seeded its library through igdb_metadata, so nothing held the wiring in
place: a Steam-only game reaching roms_facets, and the builder indexing it,
were both untested. Both assertions fail when the blob is written to a
provider the chains do not list.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 14:39:19 -04:00