Every surface that enumerates roms to point at their files was fetching the
whole platform and discarding the file-less ones in Python. Give filter_roms a
`physical` filter to sit alongside `missing`, and pair the two in
HAS_FILE_ON_DISK_FILTERS, the query-side twin of Rom.has_file_on_disk.
- The device feeds lose _servable_roms(); the three get_roms_scalar calls spread
the filters instead, so the dropped roms no longer get their RomFile rows
selectin-loaded just to be thrown away.
- Both exporters filter in SQL. Pegasus was collecting and copying assets for
roms it went on to skip, and the ES-DE guard's `not rom` arm was dead.
- The bulk zip download applies them to its platform/collection selector. A
physical game contributes no files, so it only inflated the rom count in the
log line, the generated "N ROMs (crc).zip" filename, and the bulk cache
namespace. Roms named by explicit id still bypass this.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Unify manuals and walkthroughs on one document model instead of a
separate walkthrough subsystem. Walkthroughs are RomFiles under a new
WALKTHROUGH category with an optional RomFileDocMeta provenance sidecar,
and reading progress is a per-user RomFileUser row keyed on rom_file_id
so the same mechanism covers manuals and walkthroughs.
Backend:
- models: RomFileCategory.WALKTHROUGH, DocSource, RomFileDocMeta,
RomFileUser; migration 0110 (enum value + two tables, cross-DB)
- serve .txt/.html documents inline (HTML under a sandboxing CSP);
add .txt to allowed manual files
- endpoints: walkthrough upload / GameFAQs fetch / delete, and per-user
reading-progress GET (ROMS_READ) / PUT (ROMS_USER_WRITE, like notes, so a
kiosk guest capped to the read scopes cannot write)
- last_page is range-checked, so an out-of-range value is a 400 rather than
an integer column overflow
- the guide body is read under the size cap instead of being buffered in
full and truncated afterwards
- GameFAQs import extracts text only (stored as .txt); no remote HTML is
persisted or served. Host-allowlisted on top of the SSRF-safe client
- a Cloudflare bot challenge is detected and reported as "open it in your
browser and upload the text" instead of an opaque 403
- reading-progress upsert retries as an update on a unique-constraint
race, so concurrent saves for one user/file can't 500
- a GameFAQs guide is removed from disk again if indexing it fails,
rather than being left unreferenced
- tests for CRUD, progress, the GameFAQs parser/URL validation, and
hidden-rom masking on every walkthrough route
Frontend (v2):
- TextViewer (.txt/.html), useReadingProgress composable, WalkthroughSubtab
(upload + add-from-GameFAQs-URL + delete + progress), wired into MediaTab
- ManualSubtab renders .txt manuals; walkthrough category surfaced in
FilesTab; regenerated types; i18n keys across all locales
- a pending scroll position is committed before the viewer follows a new
document, so switching files mid-debounce no longer drops it
- WalkthroughSubtab gates upload, the GameFAQs URL field, and delete on
useCan("rom.edit"), as ManualSubtab already does
AI assistance: implemented with Claude Code (Opus 4.8). The data-model
design, backend, migration, tests, and v2 UI were AI-authored under human
direction. Alternative approach to #2892.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Three fixtures rebuilt the Rom literal that _add_rom already assembles, and
the RomFile boilerplate repeated six times. Adds _add_file, drops the
dict[str, object] cast that forced a type: ignore, and trims the comments.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Remove loader-option and query work the list endpoint discards:
- Batch the has_notes flag instead of eager-loading Rom.notes, whose
backrefs to roms and users are both lazy="joined".
- noload RomUser.user everywhere rom_users feeds RomUserSchema, which
carries no user fields.
- noload Rom.platform and Rom.metadatum in get_siblings_for_roms, where
load_only narrows columns but not relationships.
- Let callers that resolve siblings themselves skip the sibling
relationship load entirely.
- Eager-load RomFile.track_meta in get_files_for_roms, matching every
other call site.
- Order the page over bare ids and fetch rows by primary key when the rom
id index is off, instead of sorting the entity through a filesort.
- Derive the file-stat flags from the page's files when with_files is
set, instead of running three correlated subqueries per row.
- Index rom_files on (rom_id, category).
Claude-Session: https://claude.ai/code/session_01J1pbRJBY3PatzkB5skQNEU
region_names_for_priority expanded the configured shortcodes into a flat
list of region names and _region_rank turned each name's index into its
rank. Two names claiming one shortcode ("nl" for both Holland and
Netherlands) therefore ranked unequally, so a Holland-tagged rom always
beat a Netherlands-tagged one instead of both falling through to the
filename tiebreak. The helper's own comment claimed otherwise.
It now returns name -> rank keyed on the shortcode's position, so aliases
tie. Unknown and repeated shortcodes still contribute nothing rather than
shifting the ranks after them, which is now covered by tests too.
Reported by Greptile and Copilot on #4260.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The group_by_meta_id dedup window ordered each sibling group by
is_main_sibling then fs_name_no_ext, so absent a manual override the
gallery entry went to whichever filename sorted first: "(Demo)" beat
"(Europe)" beat "(USA)".
Two ordering terms now sit between those: a full release outranks a
pre-release, then the configured scan.priority.region order decides.
Release status comes first because a demo is not a substitute for the
game, so a Japanese release wins over a USA demo.
scan.priority.region already existed but only steered metadata and
artwork selection, so its description is reworded across all locales.
Regions live in a JSON column that no covering index can carry, and 0107
measured what one uncovered reference costs this window: the plan drops
from `type=index, Using index` to `type=ALL, key=NULL`, four times per
gallery page load. 0108 adds a STORED generated column over regions[0]
and covers it in idx_roms_sibling_cover instead, so the ranking reads a
scalar. The engine keeps it in sync and ALTER TABLE populates existing
rows, so no scan hook and no backfill are needed.
Pre-release detection matches the filename rather than the parsed `tags`
column: tags keep the dumper's casing, and fs_name_no_ext is already in
the index.
Reordering the priority list changes which rom represents a group, so the
cached gallery sidecars are dropped when the setting changes.
Closes#1528
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Ordering the gallery by a `roms_metadata` field joined the view back in and
sorted through it. `roms_metadata` is a thin view over STORED generated
columns on `roms` (migration 0098), so that join is `roms` to itself and it
leaves the sort key on a joined table, which no index can serve: the engine
filesorts the whole library for every page.
The generated columns are already indexed, so the three that are offered as
sorts now resolve straight to them and the join goes away. On a 120k-row
table this turns a full scan plus filesort into a 72-row index walk.
The remaining view columns are JSON arrays with no index and no sort that
offers them, so they keep reading the view.
Fixes#4067
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The Home "Random Pick" widget asked the API for the library total, then
for the single row at a random offset. Paging to offset N makes the
database walk and discard the N rows before it, so the pick got slower
the bigger the library: measured on an 83,000-game instance, 1.7s at the
median offset and 6.9s deep into the list, on every home page visit.
Adds GET /api/roms/random. It offers the query a batch of random primary
keys and takes any that exist, which is one index lookup per candidate
and unbiased, since every id in the table is equally likely to be
offered. A batch only misses when the query matches too little of the id
space, and it then falls back to counting the set and taking the row at a
random position, reading index entries rather than rows because the
statement selects nothing but the id. Both paths are uniform.
On the same 83,000-game library: 2.9ms median for an unscoped pick
(0.6% of picks take the fallback, 236ms), 19-25ms scoped to a platform.
The widget now resolves a pick in one request.
The endpoint takes the platform / collection scope parameters so the
gallery "Random ROM" buttons (#4068) can move onto it too.
Fixes#4066
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`hasheous_metadata` gains keys as RomM maps more of Hasheous' signature
sources, so rows written before `mame_redump_match` existed don't carry it.
On PostgreSQL `hasheous_metadata->>'mame_redump_match'` is then NULL, the OR
chain over the match flags evaluates to NULL instead of false, and `NOT (...)`
stays NULL: the unverified filter returned nothing for those rows until they
were rescanned.
Each extraction is now coalesced to false. The JSON path is untouched, since
SQLAlchemy compiles `as_boolean()` to a CASE whose ELSE branch already folds a
missing key into false.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The match flags on `hasheous_metadata` are keyed off Hasheous'
`SignatureSourceType` names, and two never lined up with what its API
actually returns:
* `MAMERedump`, the source holding Redump's disc images in CHD form, was
mapped to nothing at all. A CHD identified by its disc-data SHA1 matched,
got its metadata, and still read as unverified because no flag was set.
* `puredos_match` looked for `PureDOS`; the source is named `PureDOSDAT`, so
the flag was pinned to False for every ROM.
CHD matches now set `mame_redump_match`, which the verified filter counts and
which the Metadata tab folds into the existing Redump chip (same database,
different distribution format). Existing rows pick the flag up on their next
rescan.
Hasheous also exposes Pleasuredome, TotalDOSCollection, eXo, ScreenScraper and
Generic sources that RomM still maps to nothing; those are left alone since
folding them in widens what "verified" means.
Fixes#4030
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Removing the read-time recompute left the cached membership blind to
everything that is not a ROM edit. A save, a state, a status, or moving
a ROM in or out of a regular collection all change what `has_saves`,
`has_states`, `statuses`, `collection_id` and `favorite` match, so the
stored counts, covers and ROM-detail chips went stale until an unrelated
edit or the next scan.
Refresh from those paths too: save and state upload, delete and
visibility toggle, `update_rom_user` when a status is set, and adding or
removing collection members. Sharing an asset is included because
`has_saves` matches other users' public saves, so it moves collections
that are not the uploader's.
These changes leave the ROM row alone, so they pass `membership_only`
and only recount a collection when the ROM actually joined or left.
Autosaves land constantly, and without it every one of them would force
a full recount of any collection the ROM already belonged to.
Reported by Greptile on #4039.
Implemented with Claude Code (Opus 5), tests first, then reviewed and
verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Recomputing every smart collection after a delete scanned the library
once per collection, synchronously on the event loop and inside a single
write transaction. Ask instead which of the changed ids each collection
matches: that resolves as a primary-key lookup, so only the collections
actually holding one of them pay for a recount.
Follow the same refresh into `update_rom` and the metadata reset. Both
change exactly the fields the saved filters match on, so cached counts
and cover mosaics no longer wait for the next scan to catch up.
Guard every call site. The ROM write is already committed by the time
the refresh runs, so a failure there must not be reported back as a
failed edit, and must not cost a bulk delete its per-ROM report.
Drop the handler-level test for leaving a collection untouched on read;
the endpoint test covers that invariant through the route the bug was
reported against.
Follow-up review of f4ac78c46 (#4029). Implemented with Claude Code
(Opus 5), then reviewed and verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A smart collection re-ran its filters across the whole library on every
request, loaded every match into memory with its joined metadata, wrote
the membership back, and only then asked for the page being displayed.
The cost tracked library size rather than collection size, was paid twice
on first load and again on every scroll, and the write bumped updated_at,
which the covers embed as a ?ts= cache-buster.
Translate the stored filter_criteria into filter_roms keyword arguments
and apply them to a bare Rom.id select instead, so membership stays in
SQL and the database returns just the rows being rendered. The criteria
vocabulary is filter_roms' own, so this composes with the gallery's
filters. smart_collection_id is dropped from the criteria: the v2 create
dialog records the route it was opened from, so a collection built while
viewing another one carries its id, which would nest and could cycle.
Bind parameters for the MATCH clauses are now named after the term they
carry. A statement can hold two of them (the collection's search term and
the gallery's), and SQLAlchemy does not uniquify explicitly named text()
parameters, so a fixed name let one term overwrite the other.
The cached rom_ids / rom_count / path_covers_* columns still back the
collections list and the ROM detail page, so refresh them on write --
smart collection create and update, after a scan, and after ROMs are
deleted -- rather than as a side effect of browsing. They are computed
for the owner: the row is shared, so a per-user criterion like favorite
would otherwise describe whoever opened the collection last.
Regular collections and the favorites filter get the smaller half of the
same treatment: an indexed subquery over collections_roms instead of an
IN list built in Python. An unknown collection or smart collection now
returns nothing rather than falling through to the entire library.
Fixes#4029
AI assistance: implemented with Claude Code (Opus 5), tests first, then
reviewed and verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The search box offered "name, filename, hash", but the term only ever
reached roms.name and roms.fs_name. A term that is hex of exactly a
digest length now also matches the hash columns on roms and rom_files,
the latter being what makes multi-disc games findable by a file's hash.
The two sides are unioned rather than OR'd. No engine merges a full-text
index with a B-tree index, so OR-ing them costs the name side its index
and scans roms end to end (3.306s against 0.005s on 300k rows). Neither
table had an index on any hash column, so 0106 adds them.
Fixes#4008
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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>
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>