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>
The detail response listed a ROM's smart collections by loading every
own/public smart collection and scanning its cached rom_ids list in
Python. rom_ids grows with library size, so this got heavier on large
libraries on every detail load.
Push containment + visibility into the query via the existing cross-DB
json_array_contains_value helper (JSON_CONTAINS on MariaDB/MySQL, @>/?
on Postgres), returning only the matching rows with id/name/is_public.
The schema mapper no longer filters, so smart_for_user becomes the plain
from_smart_collections mapping. Behavior is unchanged.
Co-Authored-By: Claude Opus 4.8 <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>
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>
A concurrent duplicate no longer rolls back the whole batch and reports
zero added; each row inserts under its own savepoint, so conflicting rows
skip and the rest land with a truthful count. The pre-insert dedupe query
now filters to the candidate rom ids instead of loading every existing
entry for the playlist or user.
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.
_attach_covers ranked every membership row with a window function and
only then kept the first five per collection, so the collection list kept
a full scan proportional to library size (0.77s of a 0.92s list on a 50k
rom library) even though the view lookup itself is now indexed.
Each collection instead gets its own primary-key lookup capped at
MAX_VIRTUAL_COLLECTION_COVERS, batched into UNION ALL statements, so the
cost follows the number of collections. The covers returned are
unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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>
A slot-less POST /api/saves behaves as a filename upsert, and two
details combined into silent save corruption.
1. get_save_by_filename only filtered by slot when one was passed, so a
slot-less lookup could match (and overwrite) a save row living in a
named slot. Scope slot=None to the null-slot save (Save.slot IS NULL)
so a slot-less upload can never adopt a row from another slot.
get_save_by_content_hash keeps its documented cross-slot slot=None
behavior (dedup-only, non-destructive).
2. The upsert branch only wrote file_size_bytes and content_hash while
the bytes landed under a path derived from the request's emulator, so
the row's hash could disagree with the file it still pointed at. Also
persist file_path/emulator, and remove the now-orphaned file when the
row's location changes.
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>
This was the only CRLF-encoded file in the backend; every other Python
source uses LF. The earlier minimal-diff workaround left it mixed, so
convert it fully to LF (the repo standard) for internal consistency.
No logic changes in this commit. The only behavioural change to this file
in the PR remains the two lines added to get_smart_collection_roms
(metadata_providers + metadata_providers_logic).
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>