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>
update_rom_note and delete_rom_note selected on note_id and user_id only,
so the rom resolved from the path never constrained which note was
touched. Pairing a note id with any other rom id in the path reached that
note regardless.
Both handlers now filter on rom_id as well, and the endpoints pass the
rom they resolved.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Smart collections silently ignored several filters at both ends:
- The backend never applied has_soundtrack, has_saves, has_states, or
player_counts from stored criteria, so a "has soundtrack" smart
collection contained every game. get_roms_scalar also dropped
has_soundtrack before it reached filter_roms.
- The v2 criteria serializer had no fields for has_saves/has_states and
only stored tri-state filters when true, so "unmatched" or "has
saves" produced empty criteria and the no-filters guard blocked the
save.
Criteria now carry saves/states filters and explicit false states, the
backend applies them, and summaries render negative states with the
existing "show-not-*" labels.
Fixes#3888
Co-Authored-By: Claude Fable 5 <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>
The two halves always ran together, and the column copy they shared is
now a single helper.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A scanned row leaves unset columns as None and the model defaults only
apply on insert, so the reconciliation path could write NULL into
file_size_bytes or has_embedded_cover. Unset values now leave the stored
value alone.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A file that stopped carrying audio tags, or vanished from disk, had its
track_meta row dropped (directly or by cascade), leaving its persisted
cover on disk with nothing pointing at it.
sync_rom_files now reports those cover paths so the scan unlinks them,
keeping filesystem work out of the database handler.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A platform scan already clears `missing_from_fs` for an entry whose file
came back under the same name, but the ROM is skipped by `should_scan_rom`
so nothing emits `scan:scanning_rom` for it. An open gallery keeps showing
the stale "missing" badge until a refetch, which reads as the platform scan
ignoring missing games (a single-game scan does emit, and looks fixed).
Snapshot the flagged ids before the pre-loop sync clears them, then emit for
the restored entries after `bulk_mark_present`.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Reusing the file row across rescans meant a track that kept its tags but
lost its embedded cover held on to the old cover_path, so the music API
kept serving an obsolete image and its file was never removed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Rescans deleted and re-inserted every rom_files row, so file ids churned
on each scan and anything keyed on them (track metadata, persisted
soundtrack covers) was orphaned.
Rows are now matched by path first, then by content hash so a file
renamed or moved inside the ROM keeps its id, mirroring the ROM-level
reassociation. Only changed columns are written, vanished files are
deleted, and archive_members is carried over (the hand-written copy
dropped it).
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>
When more than one missing entry shares the same CRC/MD5/SHA1 (e.g.
duplicate content stored twice), limit(1) returned an arbitrary row, so
reassociation could move user data onto the wrong game nondeterministically.
Fetch up to two matches and reassociate only when exactly one exists;
otherwise fall back to creating a new entry.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The reassociation lookup OR'd the individual hashes across the Rom and its
RomFiles, so a lone CRC32 collision (or one shared child-file hash) could
move an unrelated missing entry onto the scanned file, attaching the wrong
collections, notes, and assets. Require all three of CRC, MD5, and SHA1 to
match on the ROM row instead; any missing hash yields no match.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When a ROM file is renamed or moved, the scan matched files to DB rows
solely by (platform_id, fs_name), so the old row was flagged missing and
the renamed file became a brand-new entry, orphaning all user data
(collections, notes, per-user status, uploaded saves/states/screenshots).
Now, when a scanned file matches no existing fs_name, the scan hashes it
first and looks for an existing missing_from_fs entry on the same platform
with a matching hash. On a match it moves that entry onto the new file and
clears its missing state, preserving user data linked by rom_id, instead
of inserting a duplicate. Empty hashes never match, so non-hashable
platforms and SKIP_HASH_CALCULATION fall back to creating a new entry.
File hashing is hoisted so it runs once per new file and is reused for
both the reassociation probe and the downstream scan.
Fixes#3618
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
bulk_mark_present issued an unconditional UPDATE setting missing_from_fs=False
on every matched row, including rows already present. Since Rom.updated_at has
onupdate=utc_now, every scan re-stamped all skipped/unchanged ROMs of a
platform, defeating updated_after-based incremental consumers and busting every
cover URL (?ts={updated_at}) on each scan.
Mirror the missing-side guard (mark_missing_roms) by restricting the UPDATE to
rows that actually flip via Rom.missing_from_fs.is_(True), so an unchanged
platform issues no updates.
Fixes#3836
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The home rails ("recently added" / "continue playing") request 15 cards
but the endpoint always computed rom_id_index, the complete ordered list
of every matching rom id that backs gallery virtual scroll. On large
libraries this ran a full-table scan and shipped hundreds of KB of ids
to render 15 cards.
Add a with_rom_id_index query param (defaults to true, mirroring the
existing with_char_index / with_filter_values flags). When false, skip
building the index and serve the page directly via offset/limit off the
sort index, with a lightweight count for total. The home rail fetches
pass false.
Fixes#3770
Generated-By: PostHog Code
Task-Id: 45dbad45-bd7c-4cf3-8e8f-105f174f4386
The v2 gallery per-card endpoint reused get_rom, which runs the full
detail eager-load (saves, states, screenshots, collections) that
SimpleRomSchema never serializes, making cards slow to hydrate.
Add get_rom_simple backed by a with_simple_details decorator that loads
only what SimpleRomSchema needs: platform, metadatum, rom_users, files,
sibling_roms (+ their rom_users), notes, and the deferred file-count
columns.
Fixes#3771
Generated-By: PostHog Code
Task-Id: 9233f519-079f-4990-8b48-9d12c81440b4
- 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.
The has-saves / has-states filters matched only the current user's own
saves/states. Match public (community) ones too, so a ROM with another
user's shared save/state is surfaced by the filter — mirroring the
owner-or-public visibility used elsewhere (get_rom_shared_saves/states).
Generated-By: PostHog Code
Task-Id: feda1257-eb36-4566-9898-528087459416
The /api/roms filter_values dict is cached in Redis keyed only by a
runtime data-version that survives app upgrades. When a filter field is
added (e.g. tags), entries written by the previous version lack the new
key, so the response fails validation (filter_values.tags "Field
required") and returns 500 until the entry's 7-day TTL elapses or a scan
invalidates it.
Embed a schema version in the cache key so reads after an upgrade ignore
entries written under the old shape and recompute instead. Pre-namespace
keys are bypassed for free by the changed key format. Bump
ROM_FILTERS_CACHE_SCHEMA_VERSION whenever the cached dict gains or loses
a field.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The single-rom endpoints (`/{id}/simple`, `/{id}`) build SiblingRomSchema
from the eager-loaded `sibling_roms` relationship. `_visible_siblings`
filters those siblings with `perms.can_see_rom(s.id, s.platform_id)`, but
the `with_details` loader restricts sibling columns via `load_only` and did
not include `platform_id`. Reading the deferred attribute after the session
closed triggered a lazy load on a detached instance, raising
DetachedInstanceError.
Add `Rom.platform_id` to the sibling `load_only` so the permission check
reads an already-loaded column.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds a "Tag" gallery filter so a library can be narrowed by the custom
tags parsed from filenames (No-Intro / Redump nomenclature, e.g. Proto,
Beta, Demo), mirroring the existing data-derived multi-value filters
(regions, languages). Closes#3546.
Backend:
- New `_filter_by_tags` over `Rom.tags` with any/all/none logic; wired
through filter_roms, get_roms_scalar, the /roms endpoint (tags +
tags_logic), and the unscoped cache gate.
- Tags are data-derived, so the selectable list is surfaced via
filter_values: added to _collect_filter_values, with_filter_values,
get_rom_filters, and RomFiltersDict.
- Smart collections apply the criterion via get_smart_collection_roms.
Frontend (v1 + v2):
- Wired into the galleryFilter store, rom API service, request cache key,
both filter drawers, v2 URL persistence, the v2 refetch watcher, and
smart-collection serialization/summary + create dialog.
- Added the `platform.tag` key to all locales (distinct from the existing
`platform.tags` section heading).
Tests:
- Backend handler (any/all/none + unknown-value), endpoint, filter_values,
and smart-collection coverage.
- Frontend smartCollectionCriteria serialization/summary coverage.
AI assistance: implemented with Claude Code (Anthropic).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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>
Adds a "Metadata provider" gallery filter so a library can be narrowed by
which providers each ROM matched (IGDB, MobyGames, ScreenScraper, etc.),
mirroring the existing multi-value filters (player count, age rating).
Backend:
- New `_filter_by_metadata_providers` keyed off each provider's id column
on Rom, with any/all/none logic; wired through filter_roms,
get_roms_scalar, the /roms endpoint, and the unscoped cache gate.
- Smart collections apply the criterion via get_smart_collection_roms.
- Unknown provider slugs are ignored (no-op) so stale bookmarks or
hand-edited URLs don't error.
Frontend (v1 + v2):
- Shared METADATA_PROVIDER_OPTIONS registry; provider list is a fixed set
rather than data-derived, so options are static.
- Wired into the galleryFilter store, rom API service, request cache key,
both filter drawers, v2 URL persistence, the v2 refetch watcher, and
smart-collection serialization/summary.
- Added the `platform.metadata-provider` key to all locales.
Tests:
- Backend handler, endpoint, and smart-collection coverage (any/all/none
plus unknown-slug).
- Frontend smartCollectionCriteria serialization/summary coverage.
Also normalized collections_handler.py to LF (it was the only CRLF file in
the backend, which tripped git-diff-check on the edited lines).
AI assistance: implemented with Claude Code (Anthropic).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resolves the CI blocker and a cluster of opt-out visibility "fail-open"
gaps surfaced in review of the granular permission system.
Security / correctness:
- admin oauth_scopes projection keeps canonical FULL_SCOPES order
(order_scopes) instead of sorting alphabetically, fixing the red
test_user.py::test_admin on MariaDB + Postgres.
- default-group hides no longer fail open: the resolver resolves the
effective (own-or-default) group before the hidden-entity lookup.
- /roms/by-hash and /roms/by-metadata-provider now 404-mask hidden roms.
- USERS-entity grant no longer enables admin creation: add_user and
invite-link require a real admin to mint admin accounts.
Visibility leaks closed on secondary read paths:
- feeds, sibling roms (list query + single-rom schemas), /stats counts
and per-platform breakdowns, collection rom_ids/rom_count, search_rom.
Hardening / cleanups:
- firmware/platform PUT 404-mask hidden entities; group rename conflict
returns 400 not 500; guard against removing the last default group;
kiosk read-only enforced at the fine layer; add_hidden_entity rejects
non-cascading entity types.
Frontend:
- permissionGroups.ensureLoaded coalesces concurrent callers on one
in-flight request; permissions.setGrants resets isAdmin/hidden;
CreateUserDialog no longer orphans a user when group assignment fails;
HiddenGamesPicker search rows are native buttons (keyboard/gamepad);
invite-role labels and group swatch aria-label use i18n; drop dead code
(originalRole, unused permissionsApi export).
AI assistance: changes authored with Claude Code (Claude Opus), driven by
the Copilot review and a multi-agent adversarial review, then verified
(backend pytest, frontend typecheck/vitest, i18n parity, trunk).
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>
- Added new permission handling in `backend/handler/auth/dependencies.py` to support fine-grained, DB-backed permission checks.
- Enhanced user role update logic in `backend/endpoints/user.py` to prevent demotion of the last admin.
- Introduced `hidden_platform_ids` and `hidden_rom_ids` parameters in various database handlers to manage visibility based on admin settings.
- Created new endpoints for managing permission groups, user memberships, and hidden entities in `backend/tests/endpoints/test_permissions_admin.py`.
- Added tests for permissions visibility and CRUD operations in `backend/tests/endpoints/test_permissions_visibility.py` and `backend/tests/endpoints/test_permissions_me.py`.
- Updated archive handling in `backend/utils/archives.py` to improve error logging and timeout management during extraction.
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>
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>