Settings -> Library Management -> Missing made three whole-library passes
per request, two of which produced data the page never renders, and none
of which could be cached because "missing" counts as a filter.
- The tab now opts out of the char index, the filter values and the
ordered id index, so the endpoint serves its total from a plain COUNT.
- `missing_from_fs` gets a composite index with `name_sort_key`, and the
filter compiles to an equality: MariaDB does not treat `IS NOT FALSE`
as indexable, so the index would otherwise only ever be scanned end to
end. The column is NOT NULL, so both forms match the same rows.
- The filter-value list is keyed on the scope (search / platform /
collection) alone. It is built from a query that never applies the
row-level filters, so a filtered request now answers with, and warms,
the same whole-library entry an unfiltered one does.
Fixes#3992
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The Server Stats page ran two full scans of the multi-gigabyte `roms`
table on every visit: the metadata-coverage breakdown counted eleven
provider-id columns per platform, and the region breakdown pulled every
row's regions into Python. Both were returned in the same request as the
cheap summary counts, so the whole page stayed blank until they finished.
Mirror the provider match ids into the narrow `roms_facets` table
(migration 0102, kept in sync by the same triggers as the existing facet
columns) and read both breakdowns from it, so neither query touches
`roms`. Split the v2 Server Stats view into a summary-first request and a
separate breakdown request so the six top cards render immediately.
Fixes#3901
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rescans reconcile rom_files in place since #3900, so file ids survive a
rescan and no longer need routing around. Playlist and favorite entries
reference rom_file_id directly instead of (rom_id, md5_hash).
This drops the machinery the hash key required: soundtrack audio is no
longer force-hashed during scans (which overrode NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION), soundtrack uploads no longer hash on write,
adding an unhashed track no longer returns 400, and the min(file id)
subquery that collapsed identical copies within a rom is gone. Two files
with the same content are now two independently addressable tracks.
A file that leaves the library takes its entries with it via the FK
cascade, rather than leaving a dangling entry that resurrects if the
content comes back.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Spotify-style library features for soundtrack tracks: per-user favorites
(liked songs) and user-owned playlists with manual ordering and optional
public read-only sharing.
Track references are stored as (rom_id, md5_hash) rather than rom_file_id:
scans purge and re-insert rom_files rows, so file ids churn while rom ids
and content hashes are stable. Entries survive rescans and renames, and
resolve to the current file at query time; entries whose content is gone
are omitted from listings until the file returns.
To make the content hash reliably present, soundtrack audio files are now
always hashed individually during scans (including NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION, whose file-size concerns don't apply to audio),
and soundtrack uploads compute crc/md5/sha1 on write. Existing libraries
backfill via a HASHES scan; adding an unhashed track returns 400.
New playlists.read/playlists.write scopes are wired through the granular
permission system (PermEntity.PLAYLISTS); the migration mirrors every
group's collections grants onto the playlists entity so existing groups
keep working without admin intervention.
Endpoints under /api/music: favorites GET/POST/DELETE, is_favorite and
md5_hash on track rows, playlists CRUD, playlist tracks GET/POST/DELETE
and PUT /tracks/order.
virtual_collections was a view that unnested five JSON arrays per rom on
every read, so both the collection list and opening a single collection
scanned the whole library. Opening a collection with a handful of roms
cost as much as one with thousands, since the name is computed inside the
view and nothing can be narrowed down early.
Membership now lives in virtual_collection_roms, one narrow row per
(type, name, rom_id) plus that rom's covers, derived from the generated_*
columns and maintained by triggers on roms (deletions ride the foreign
key cascade). The view becomes a plain aggregate over that table, so the
model, schemas and API shape are unchanged, and filtering roms by a
virtual collection is an indexed subquery instead of an IN list of every
member id.
Covers are no longer aggregated in the view, which materialized every
member's cover path on every request; the handler resolves at most five
per collection, matching the smart collection cap and what both UIs
render.
On a synthetic 50k-rom library the list goes from 1.42s to 0.128s and a
single collection from 0.111s to 0.0006s, with identical output.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Building the filter dropdowns aggregated the facet columns straight off
`roms`. Those columns are cheap to compute since #3826, but they sit inline
with the raw provider-metadata blobs, so the aggregation read every row of a
multi-gigabyte table: seconds of pure disk reading on any database whose
buffer pool is smaller than the table (the stock 128-256 MB defaults always
are on a large library).
`roms_facets` holds only the filter values and is kept in sync by AFTER
INSERT/UPDATE triggers on `roms`, so every write path stays consistent
without an application hook. Deletes ride the ON DELETE CASCADE foreign key.
Fixes#3882
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Bound the user-authored fields. `description` (TEXT) and `custom_name`
(VARCHAR(400)) had no length constraint, so an oversized value reached the
database and surfaced as an unhandled DataError, turning a bad request into
a 500. Both are now validated against the column limits, which are defined
next to the columns so the bounds can't drift from the schema. The
`custom_name` case predates this branch but shares the line of code.
Make platform updates a true partial update. The shared API service took a
whole Platform object and sent every field, so the v1 rename drawer replayed
whatever description it happened to be holding; if another client had changed
the description in the meantime, renaming silently reverted it. The service
now takes explicit optional fields, so omitting one means "leave it alone"
rather than "write back my cached copy".
Watch the two form fields independently. Re-seeding both whenever either
canonical value changed meant a socket update touching only the name threw
away an unsaved description edit, and vice versa.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Custom platforms could only be distinguished by name, which is often not
enough context (e.g. a "Sega - Genesis/Mega Drive (Unofficial)" folder
holding aftermarket and unlicensed dumps). Platforms now carry an
optional free-text description, mirroring collections.
The column is nullable and defaults to "", matching custom_name, so a
rescan (which merges a freshly scanned Platform over the existing row)
leaves it untouched. update_platform patches only the fields sent, so an
omitted description is preserved and an empty string clears it.
Surfaced in the v2 UI only: the Settings tab name form now covers both
custom_name and description, and PlatformHead renders the description as
a chip alongside the metadata chips. v1 is frozen and gets no new UI, but
round-trips the field unchanged through the shared API service.
Closes#3402
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
GET /api/platforms and GET /api/stats both sum roms.fs_size_bytes but the
column was not in any index, forcing full reads of the wide, JSON-heavy roms
table (5-11s on large libraries). A composite index on
(platform_id, fs_size_bytes) turns both sums into index-only scans.
Fixes#3769
Generated-By: PostHog Code
Task-Id: e24ff248-6329-4b70-a826-9a9fee21411e
- Cast year to text in the /api/music years facet search so Postgres does
not error on lower(integer) (MariaDB/SQLite auto-cast, hiding it in CI)
- Escape LIKE wildcards in music search via new utils.database.escape_like
- Drop lazy="selectin" on RomFile.track_meta; eager-load only where the
metadata is serialized (get_rom already did; add the three soundtrack reads)
- Migration backfill uses a single query + fetchmany (repo idiom, see 0084)
instead of manual keyset paging, in both directions
- Guard the extensionless folder-conversion collision (stale row over a
directory the user already created on disk)
- Renumber migration 0093 -> 0094 after 0093_states_rom_user_index landed
RomM stores soundtracks but exposes no way to consume them as a music library: a
client has to enumerate ROMs and pull each one's tracks individually, and the
per-track metadata lives in the `rom_files.audio_meta` JSON blob, which is
unindexable on MariaDB, so any library-wide filter or sort degrades to a full
scan.
This adds a queryable, music-first API for soundtracks, backed by a typed and
indexed `track_meta` table migrated from that JSON.
It also lets users upload soundtracks, manuals, and screenshots to any ROM, not
only folder-based ones. When the target is a single-file ROM, the client warns
that the upload will migrate it to a multi-file (folder) structure, then performs
that migration in place automatically.
Addresses review feedback on #3615:
- Backend: merge the new filter column map with stats_handler's
`_METADATA_SOURCE_COLUMNS` into a single `METADATA_SOURCE_COLUMNS` in
models/rom.py, imported by both. It's the union of the two prior sets,
so the stats coverage breakdown now also reports `libretro`.
- Frontend: drop the duplicated provider list from utils; derive the
filter options from the `METADATA_PROVIDERS` registry via
`METADATA_PROVIDER_FILTER_OPTIONS` (added a `name` brand field). Both
filter drawers import from the registry now.
- collections_handler.py: revert the stray CRLF->LF normalization so the
diff is just the two smart-collection lines.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The patcher uploads the patched ROM and then fires a platform scan to
register it. When a second scan runs against the same platform around the
same time (a filesystem-watcher rescan, a scheduled rescan, or another
manual scan on a multi-worker setup), both scans could see the new file as
absent from the DB and each insert it, producing two identical library
entries for one patched file.
A platform folder can't physically hold two entries with the same name, so
a ROM is uniquely identified by (platform_id, fs_name). Enforce that with a
unique index instead of the previous plain index, which makes the duplicate
impossible. The scan's early ROM insert now adopts the row created by a
concurrent scan (catching the integrity error and skipping) instead of
failing, and ROM rename pre-checks for a name collision so it returns a
clean 409 rather than hitting the constraint.
Includes a migration that removes any pre-existing duplicates (keeping the
lowest id; dependents cascade) before upgrading the index to unique.
Fixes#3590
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0135UV8Xn2XHkRhjzhm9UptP
Collapse the Role enum from viewer/editor/admin to two kinds (admin/user);
non-admin access now comes entirely from permission groups + overrides.
Backend:
- Role -> StrEnum {USER, ADMIN}, VARCHAR-backed (native_enum=False); Role.coerce
maps legacy/unknown strings (incl. in-flight invites) to USER.
- Resolver: group-less users fall back to the default group (dropped the
role-based legacy fallback); kiosk caps all non-admins to read-only.
- OIDC editor/viewer claims both map to USER (env var names unchanged).
- Migration 0092 converts the native enum to VARCHAR and normalizes
ADMIN->admin, VIEWER/EDITOR->user.
- Updated endpoints, conftest fixtures, role/oidc/parity/db-handler tests, tools.
Frontend:
- v2 + v1 user management now use admin/user (dropdowns, defaults, getRoleIcon).
- Regenerated types (Role = 'user' | 'admin'); added role-user i18n to all locales.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The /api/roms list endpoint did several O(library) computations on every
request. On a 100k-rom library each request took 4-5s. This addresses the
dominant costs, all measured on a real 100k-rom MariaDB.
- Cache rom_id_index: the full ordered id list backing virtual scroll was
recomputed (the sibling-dedup window over the whole library) on every
request, even limit=1, and shipped uncached. Memoise the unscoped scan
under the same versioned cache as the other sidecars. 2815ms -> 7ms on hit.
- Slim the sibling-dedup query: the inner derived table materialized all of
Rom (including JSON metadata blobs) for 100k rows, and carried a wide unused
fs_name_no_ext through the window's temp table (spilling the sort to disk),
plus a pointless inner ORDER BY. Select only the columns the window needs.
2.79s -> 0.86s, identical results, no schema change.
- Rewrite with_char_index: replace row_number() over the whole library (full
materialization + double filesort) with a per-letter COUNT and an
accumulate. Identical output, drops a filesort layer.
- Add idx_roms_sibling_cover covering index for the sibling_roms view
self-join, so the 7-way metadata-id OR resolves from the index instead of
reading wide rows per parent. ~8x on dense pages warm, far more cold.
AI assistance: written with Claude Code (diagnosis, query rewrites, migration,
tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Introduced a new permission model with `PermissionGroup`, `UserPermissionOverride`, and `HiddenEntity` to manage access control.
- Added `DBPermissionsHandler` for handling permission-related database operations.
- Updated `User` model to include a foreign key to `PermissionGroup` and modified `oauth_scopes` to derive from the new permission model.
- Implemented tests to ensure the new permission model maintains parity with legacy access controls.
- Created documentation outlining the new permission system architecture and migration strategy.
- Introduced new API endpoints for updating visibility of saves and states.
- Added `is_public` property to `SaveSchema` and `StateSchema`.
- Created new models for user saves and states with visibility attributes.
- Updated the `SaveDataTab` component to differentiate between "Mine" and "Community" sections.
- Implemented visibility toggle functionality for user saves and states.
- Enhanced localization files to include new strings for visibility actions.
Drop the name_sort_key_custom flag/migration in favour of a flagless rule: a
key is "custom" when it no longer equals compute(name). Apply that consistently
across all three write paths so a manual sort key survives renames while a
derived key keeps following the name:
- @validates re-derives on name assignment only when the stored key still
matches the derived value; direct name_sort_key assignment stores a
normalized custom key (or reverts to derived when cleared). Handles both
kwarg orders at construction.
- update_rom mirrors the same check for the bulk update() path it bypasses.
- The edit endpoint only writes the key when the user actually changed the
field, delegating the untouched case to update_rom.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Collapse the separate `sort_name` column into `name_sort_key`, which is now
the single user-settable sort field: always normalized and indexed for fast
ordering, derived from `name` by default, and overridable. A new
`name_sort_key_custom` boolean marks user/metadata overrides so they survive
renames and rescans.
- Drop the `roms.sort_name` column; repurpose migration 0085 to add
`name_sort_key_custom`.
- Derive the key via `@validates("name")` unless pinned custom; the edit
dialog, unmatch flow, and ES-DE gamelist <sortname> set custom keys.
- update_rom / scan_rom keep the columns in sync explicitly (bulk update and
construction bypass / reorder the validator).
- Frontend: edit field drives name_sort_key (empty when auto), api sends the
override only when custom, regenerated types updated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Added RDropzone component for handling file uploads with a customizable interface.
- Integrated RDropzone into Patcher and Upload views, replacing previous drop zone implementations.
- Enhanced ScreenshotsTab with additional functionality for community screenshots, including visibility toggles and owner display.
- Updated styles for improved user experience and responsiveness.
- Created Storybook stories for RDropzone to demonstrate its usage and interaction.
- Implemented screenshot upload feature in the ROM management section.
- Added new API methods for uploading and removing screenshots.
- Enhanced UI to support drag-and-drop for screenshots and display uploaded images.
- Updated localization files for Russian, Simplified Chinese, and Traditional Chinese to include new screenshot-related strings.
- Improved the FilesTab and MediaTab components to manage screenshots effectively.
- Added delete functionality for user-uploaded screenshots with confirmation prompts.
- Updated styling for screenshot elements to improve user experience.
Centralize the *_no_tags / *_no_ext / *_extension columns (derived from a
file name) behind @validates hooks instead of computing them by hand at
every write site:
- Add pure helpers (compute_file_name_parts and friends) to models.base;
the filesystem base handler now delegates to them.
- Add @validates on Rom (fs_name), BaseAsset (file_name, inherited by all
asset subclasses), and Firmware (file_name).
- update_rom keeps the fs_name-derived columns in sync on bulk update(),
which also fixes the rename path never updating fs_extension.
- Drop the now-redundant computations at the scan/rename call sites.
Also fix the migration backfill loop and a pre-existing list[str | None]
type mismatch surfaced in scan_handler. Add tests for the helpers, the
validators, and the update_rom bulk-sync path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Replace the before_insert/before_update event listener with a
@validates("name") method on Rom. The sort key is now recomputed exactly
when name is assigned (ORM construction or mutation) rather than on every
flush of any field. Bulk update() still sets it explicitly in update_rom.
Also linearize the merged 0084 migration onto 0083_rom_category_soundtrack
so there is a single alembic head.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Implements RFC 8628-style device authorization so clients
(argosy-launcher, grout) can pair by display instead of manually
copying tokens. Device posts to an open /api/auth/device/init with
its identifier and requested scopes; the server returns device_code
+ user_code + QR URL. User scans QR, lands at /pair/device, approves
(optionally editing name/scopes/expiry); the device's next poll on
/api/auth/device/token returns a ClientToken bound 1:1 to a newly-
created (or deduped) Device record. Downstream endpoints
(/play-sessions, /sync/negotiate) infer device_id from the bound
token so the client doesn't have to ship it on every call.
- Migrations 0080/0081: devices.client_device_identifier (unique
per user) and client_tokens.device_id FK (ON DELETE SET NULL)
- Five new endpoints under /api/auth/device (init/pending/approve/
deny/token) with Redis-backed state, per-IP rate limits, and
RFC-compliant error codes (authorization_pending, slow_down,
expired_token, access_denied)
- HybridAuthBackend surfaces bound device_id on request.state and
bumps devices.last_seen with a 5-minute debounce
- /api/users/me returns current_device_id for bound tokens so a
device can identify itself from its token alone
- Frontend approval screen at /pair/device with editable scopes/
name/expiry (defaults to Never), 3s auto-close countdown
- ClientApiTokens settings list shows bound-device chip
- 20 i18n keys added to all 17 locales; generated models updated
- 52 new tests across 13 classes; full suite 1334 passed
Planning and review assisted by Claude Code.
Adds a few new indexes to handle full-text searches instead of doing
`ILIKE` matching, improving performance substantially.
Alongside that, a few other things were done in order to improve search
performance, such as caching filter values so they're not computed on
each request to /api/roms. Overall, this should have a very noticeable
impact on large collections when using the search feature.
Adopt master's ROM schema design (sibling_roms + files, batched
get_files_for_roms / get_siblings_for_roms) while preserving the v2-branch
features master lacks: per-user is_main_sibling on siblings and audio_meta
on rom files.
Conflict resolution:
- responses/rom.py: keep master's sibling_roms/files fields; re-graft
is_main_sibling via SiblingRomSchema.from_rom(rom, is_main_sibling=...);
restore the eager-relationship fallback in
SimpleRomSchema.from_orm_with_request (None sentinel) so the v2
/{id}/simple endpoint still returns siblings/files.
- roms_handler.py: get_siblings_for_roms now left-joins RomUser and returns
(Rom, is_main_sibling) tuples; keep both branch and master file helpers.
- drop the redundant branch-only sibling_ids field and
get_sibling_data_for_roms.
- generated types resolved to match (sibling_roms + files; RomFileSchema
keeps audio_meta and gains archive_members).
- update v2 components and the RelatedGameCard mock to read sibling_roms.
- fix stale exclude={"siblings"} -> "sibling_roms" in scan emit payloads.
- re-chain the audio_meta migration as 0083 (after master's 0082) to keep a
single Alembic head.
- package.json: union of branch tooling + master dependency bumps; lock
regenerated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
saves responses now include one device_syncs entry per device that has
synced a save, not just the caller's, so clients can tell which devices
hold a save. is_current is computed per entry and the caller's own entry
is ordered first for backward compatibility.
add a saves.origin_device_id column (migration 0081) recording the
device that created a save, set on initial upload only, surfaced as
origin_device_id on the save schema.