`sibling_roms` matched on seven providers, the gallery's dedup window on
those plus `flashpoint_id`, and the recommendation feed on those plus
`steam_id`. Three lists, so a pair sharing only a Steam or Flashpoint id
was the same game to one reader and two games to another.
They are one list now. `rom_identity_keys` carries all nine providers,
which makes `provider_id` a varchar since `flashpoint_id` is a string,
and the dedup window's cover index grows by `steam_id` so the window
keeps its indexed plan.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A rom written between the backfill and the trigger creation got no key
rows, and nothing short of a later edit to one of its identity columns
would have noticed. Both writes skip a row that is already there, so the
two steps can overlap.
Also correct the revision the docstrings point at and the claim that
IDENTITY_ID_FIELDS contains the group_by_meta_id window's columns.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Master keyed the unique roms index on the full path digest, so the
resolution keeps its two indexes and this branch's comment on
idx_roms_sibling_cover, which no longer backs the sibling_roms view.
Both sides added a 0126 revision off 0125; rom_identity_keys moves to
0127 behind master's unique_rom_full_path.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comment and docstring pass over the `released_days` change: cut the copies of
rationale that already live next to the thing they describe, and drop the
sentences defending obvious choices.
`RELEASED_DAY_REGEX` now carries the calendar ranges, so a match is a valid day
and `parse_released_days` needs no sentinel pair and no second range check.
`release_day_ranges` stops re-sorting what `epoch_ms_in_ranges` already sorts.
`anniversaryQuery`'s return type is a named export, so the widget imports it
instead of unwrapping a `ReturnType`, and the widget's two reset paths share
`showEmptyDay`.
`loadMore` is `loadNextPage`, since it appends one page rather than the rest.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`GET /api/roms` already does what `/roms/anniversaries` hand-rolled: it selects
ordered ids over the filtered set, takes the total from that index, hydrates
only the page asked for, and re-projects the rows into id order. So the widget
now asks it for a page rather than owning an endpoint that pulls the whole day.
`released_days` on the list endpoint takes days as "M-D", matching any year, and
`released_before_year` bounds them. Both go through `filter_roms`, so the same
day-of-year match is available to the gallery filters and to smart-collection
criteria, and the range union stays where it was: still sargable, still a
covering index range scan on `idx_roms_generated_first_release_date`, no SQL
date function and no dialect branching. Verified on a 73k-rom database that the
plan through the list endpoint's join is unchanged: `type=range`,
`Using where; Using index`, no filesort.
The filter means exactly what it says, so the calendar policy moved to the
client, where the clock it depends on already lived. `anniversaryQuery` picks
the days and the year bound off the viewer's own date: it skips 1 January,
where several providers park year-only metadata, rolls 29 February onto 28
February in a non-leap year, and bounds the years at the viewer's own. The
server no longer has to second-guess a timezone offset, so the 31 December
asked for on 1 January UTC correction is gone rather than fixed.
Consequences for the widget: the counter is the day's real total instead of one
clipped at a 500-row ceiling that no longer exists, and a card costs one page
of 24 rather than up to 4 MB up front. Paging backwards stays in memory;
only moving past the loaded pages fetches, with the spinner on the arrow so
focus is never yanked mid-page. A failed page keeps the card on screen.
`released_days` is added to the list endpoint's unscoped-cache gate: the
sidecar keys encode no filters, so a narrowed page must not be served under the
shared "all" key. Covered by a test that primes the unscoped key first.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The endpoint answered with every match for the day, so response size
tracked the library rather than the request: the busiest real date on a
96k-rom library is 1,101 roms at roughly 8 KiB of SimpleRomSchema each,
and the 1 January early-return was the only thing holding that off
~23,000.
The ceiling goes on the id selection rather than the response, so it
bounds the hydration and the serialization too, which is where the weight
is. It rides the existing index-ordered range scan, so the plan does not
change and the engine stops early instead of walking the whole union.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The 24-item cap was measured against the largest library available and
does not earn its place: on a 96k-rom library the day-of-year index range
scan costs 3.7 ms whether it matches 114 rows or 22,914, so the cap saved
roughly 40 ms and 0.7 MB on a typical day while truncating every single
day of the year (median 132 matches/day, and 100% of days exceed 24).
Removing it also makes the widget's counter a real total rather than a
ceiling, which was the substance of the review comment about "24 / 24"
implying a complete list.
This makes the 1 January skip load-bearing for response size as well as
accuracy: it is the one day that would otherwise answer with 22,914 rows
(28% of all dated roms), where the busiest real day is 1,101.
Addresses the "Result cap hides anniversaries" review comment on #4396.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Clients send their own local month and day, so around the new year the
server's UTC date can name a different year. 31 December asked for on
1 January UTC bounded the search at the wrong year, letting a release
from the viewer's current year through as an anniversary of itself.
A timezone offset moves the calendar by at most a day, so 31 December /
1 January is the only pair that can disagree, and 1 January already
returns nothing.
Addresses the "Mixed clocks include new releases" review comment on #4396.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Shows games released on today's date in an earlier year, one at a time,
with arrows to page through the rest. Sits in the Home widget rail beside
Random pick and Library stats, with its own Settings toggle (default on)
and an entry in the drag-reorder list.
New endpoint GET /api/roms/anniversaries, ROMS_READ, whole-library,
returning up to 24 SimpleRomSchema oldest release first. Clients send
their own local month and day so "today" matches the calendar in front of
the user rather than the server's UTC clock.
The day-of-year match is a union of one-day ranges over
generated_first_release_date rather than MONTH()/DAY() on the value.
Ranges are sargable, so idx_roms_generated_first_release_date serves both
the match and the sort as one covering range scan: 195 rows examined and
~2 ms against 63,334 rows and ~70 ms for the function predicate on a
100k-row table. Emitting no SQL date function also means no dialect
branching and no migration.
1 January returns empty. Several providers park year-only metadata there
(ScreenScraper parses a bare year with %Y, CSDb publishes nothing else,
IGDB reports year precision as 1 January), so nothing in the stored data
tells a real 1 January release apart from an unknown day. Leap-day
releases roll onto 28 February in non-leap years.
Visibility follows /random: filter on hidden platforms and roms, then
re-check each hydrated row with perms.can_see_rom.
Closes#3440
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Migration 0126 samples `rom_identity_keys` right after its backfill, which
on a fresh install runs while the table is still empty. The first scan then
fills it through the triggers, and MariaDB keeps planning `sibling_roms`
against the empty sample: measured on 37k key rows, one gallery page's
sibling statement takes 891.7 ms in that state against 2.1 ms once resampled,
which is worse than the 550.7 ms the view it replaces cost.
InnoDB's auto-recalc does not cover it. It fires and updates the stored row
count, but the plan does not change until the table is reopened or analyzed:
90 s after a trigger-paced fill, `mysql.innodb_table_stats` was correct and
the plan was still the block-nested-loop one.
Addresses the "Fresh Installs Keep Stale Statistics" review comment on #4394.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`sibling_roms` was a view that self-joined `roms` on an OR of seven
equalities across seven columns. The compared values come from the joined
row, so no index can drive that OR: MariaDB answers it by block-nested-loop
scanning every ROM on the platform. Every gallery page paid that for its
version badges, and the gallery's "Versions" filter asked the same view for
an EXISTS over the whole library.
Migration 0126 moves the ids into `rom_identity_keys`, one narrow row per
ROM per provider it matched, and redefines `sibling_roms` as a self-join of
that table. Triggers on `roms` keep it in sync, guarded by `NEW.x <=> OLD.x`
so the writes that touch no identity id skip the resync; deletes ride the
foreign key's cascade. This is the move 0101 made for `virtual_collections`.
Matching is unchanged: the same seven providers, still scoped to a platform.
No application code changes and no API shape changes.
Measured on a clone of a real 96k-ROM, 123-platform library:
GET /api/roms?duplicate=true 977,571 ms -> 22,149 ms (45x)
PlayStation gallery (9,196) 1,039.0 ms -> 382.2 ms (2.7x)
Arcade gallery (7,719) 844.5 ms -> 296.2 ms (2.9x)
all-games gallery 3,023.9 ms -> 2,690.5 ms (1.1x)
The all-games page barely moves because its rows are drawn from 123 mostly
small platforms, so the per-platform scan was cheap per row. Its residual is
almost entirely the group_by_meta_id dedup window (2,535 ms of 2,676 ms
measured on the same clone), a separate problem.
The view deliberately has no DISTINCT: a pair matched by two providers emits
two rows, and DISTINCT would stop the view merging into the caller's query
at 11x the cost. Both readers already collapse duplicates.
The ANALYZE after the backfill is load-bearing. Without sampled statistics
the optimizer estimates thousands of rows per lookup and picks a worse join
order for the rest of the list query, leaving the gallery slower than before
this ran.
Fixes#4391
Related to #4382
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Conflict resolution notes:
- Locale rom.json: master sorted and reworked every file; took master's and
re-inserted `location` / `location-copied` in sorted position. Added them to
the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
(master), and the scan loop keeps master's early missing-sync plus its
restored-rom emit alongside this branch's relocation pass. The relocation
filter now applies only to the identify loop, so a relocated rom is no longer
re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
`purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
premise that same-named files in different folders are distinct games.
Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
all share one folder, so a duplicate title is still rejected.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The genre/franchise/company/publisher/developer/collection/age-rating/
player-count filters read from `roms_metadata`, but the join was added at the
end of `filter_roms`, after the "Group ROMs" block had already derived its
dedup window from the query. The window therefore filtered on a table it never
joined: the database cross-joined `roms` against `roms_metadata` (a view over
`roms`), which SQLAlchemy reports as a cartesian product.
Besides the cost, the window then ranked every ROM in the library rather than
the matching ones, so a game whose matching version was not the group's primary
one disappeared from the gallery entirely.
Fixes#4389
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
0123 appends steam_metadata to the generated facet chains, but every test
seeded its library through igdb_metadata, so nothing held the wiring in
place: a Steam-only game reaching roms_facets, and the builder indexing it,
were both untested. Both assertions fail when the blob is written to a
provider the chains do not list.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Files added to an already-scanned folder ROM could only be picked up by a
complete or hashes rescan, which rehash every known file. The new `files`
scan type scans new games like quick and re-lists the files of existing
folder ROMs, hashing only new or changed files and recomputing the
ROM-level hashes only when a top-level file changed. Per-rom update and
unmatched scans reuse the same incremental mode, and the filesystem watcher
enqueues it instead of quick.
Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a
current mtime to about 128 seconds), adds the CHEAT value missing from the
PostgreSQL category enum, maps `patches/` to the patch category and
excludes upload temp files from scans.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
Steam's genres, companies, developers, publishers, game modes, release
date and Metacritic score were stored by 0115 but read by nothing: the
generated columns behind roms_metadata, roms_facets and the
recommendations index never listed steam_metadata as a source. 0115
deferred that on purpose, since changing a STORED generated column
rebuilds the roms table, and asked for it to ride with a migration that
already does. 0118 and 0119 are that migration, so 0120 rebuilds the
seven affected columns with Steam appended at the lowest precedence.
Only rows carrying Steam metadata can change value, so the facet mirror
and virtual-collection membership are refreshed for those alone. Round
tripped on MariaDB 11 and PostgreSQL 16, asserting the view, facet and
membership rows at each step.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The portrait-capsule HEAD request was the one Steam call living outside
SteamService, with its own session, user-agent and timeout. It moves in as
get_library_capsule_url, following LibretroThumbnailsService.head, so the
handler just picks the capsule or falls back to the header image.
get_app_details grows a filters passthrough, and the heartbeat asks for
"basic" instead of pulling a whole store page to read one success flag.
Guard the facet mirror against a provider that reaches the model but not a
migration's trigger column list: test_every_provider_id_is_mirrored writes
every METADATA_SOURCE_COLUMNS id and asserts each roms_facets twin follows.
Verified against triggers rebuilt without steam_id, where it fails naming
the missing provider.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The saves handler carried two ROM filters that ANDed together, and the states
handler had only the singular one, so the same "which ROMs" question had three
answers across two sibling handlers. Collapse both onto rom_ids: a single-ROM
lookup is just a one-element scope, which is what the three internal callers in
the saves endpoint now pass.
That leaves the routes to fold their own public rom_id param into the scope.
Rather than write the fold twice, narrow_rom_id_scope joins utils/validation
beside RomIdScope, keeping the documented "combined with rom_id" semantics: both
filters still apply together, so the effective scope is their intersection.
GET /api/states gains the rom_ids param GET /api/saves got in #4304, declared
with the same shared RomIdScope, so a client syncing a known set of ROMs can
discover states the same way it discovers saves, under the same cap and the same
422 on a bad scope.
One behaviour shift falls out of the handler's old falsy check: rom_id=0 used to
be ignored and return the whole library, and now scopes to nothing, which is
what RomIdScope's positive-ID rule says a zero means.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comma-separated ID params in this codebase are a download-route convention
(/roms/download, and the two file_ids params), built by hand for URLs the
browser navigates to. Every JSON API route that takes a list of IDs repeats
the parameter instead, and roms' platform_ids documents that form explicitly.
GET /api/saves is a JSON route, so it should match those.
Declare the scope once as a shared RomIdScope annotation: the cap and the
positive-ID rule become schema constraints that both routes enforce alike and
that now appear in the OpenAPI schema as maxItems and exclusiveMinimum, so
clients can read the limits instead of discovering them from an error. That
drops the hand-rolled parser and the two validation-to-HTTPException
translations; a bad scope is a 422 on both routes.
One semantic change: the query param can no longer express an explicit empty
scope, since an omitted parameter is the only empty form. Negotiate keeps it,
as a JSON body can still send [].
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The scope validator and its cap were sitting in the saves DB handler, which
made two endpoints the first non-test callers to import a behavioral symbol
straight through the handler.database facade, for a helper with no DB content
and that get_saves never calls. They belong beside the repo's other
endpoint-facing validators.
Fold the comma-separated ID parse into a shared parse_comma_separated_ids so
the "comma-separated integers" message the tests assert on has one home, and
call it from the ROM download route that already had it inline. Both scope
validators now raise ValidationError like the rest of the module, which lets
negotiate validate in the endpoint body next to its other request-shape
checks: the two routes reject a bad scope with the same 400 instead of one
returning 400 and the other 422.
Also narrow the sync-record lookup to the newest row per slot (superseded rows
were fetched and discarded), and share one second_rom / second_save fixture
instead of three near-identical builders across the new tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The cleanup tasks took a single platform_id while both Missing tabs
offer a multi-select, so picking two platforms ran the unscoped
cleanup over the whole library. The confirmation dialog still named
the selection, so the tab deleted more than it said it would.
Take platform_ids on both cleanup tasks and filter firmware by the
whole list, so what runs matches what the dialog names.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sync clients that hold a subset of the library had no bounded way to ask
for the saves relevant to the ROMs on the device: `GET /api/saves` filters
one ROM at a time, and negotiation always evaluated the user's whole
slotted save set, offering downloads for ROMs the device cannot play.
Add a `rom_ids` scope to both. `GET /api/saves` takes a comma-separated
list (matching the `/roms/download` convention) and `POST /api/sync/negotiate`
takes a list in the request body, so a client with many ROMs is not bound by
URL length. Negotiation widens the scope with the ROMs the client sent saves
for, so a client save is never misread as an upload because its ROM was
omitted. The scope is read-only: an omitted ROM is outside the request, never
a deletion signal.
Both share one limit and one validation rule in the saves handler, and both
reject a scope that is non-positive or over the cap rather than truncating.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Swap the hand-rolled platform picker in MissingFirmwareSection for the
shared PlatformSelect, and fold the triplicated firmware builder in the
tests into an add_firmware factory fixture.
Keep Platform out of list_firmware: the relationship is lazy="joined",
so every row also ran Platform's rom_count and fs_size_bytes aggregate
subqueries over roms, for data no caller reads.
In useTaskCompletion, the resolver already identifies the live wait, so
drop the parallel generation counter and the unused cancel export.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Metadata providers (ScreenScraper, RetroAchievements, LaunchBox,
Flashpoint, gamelist, IGDB) distinguish the publisher from the developer
of a game, but RomM amalgamated both into a single `companies` list at
ingestion, so the distinction was unrecoverable. This adds `publishers`
and `developers` as new, refined fields end to end while keeping
`companies` (the merged union) working exactly as before.
Backend:
- Handlers now emit publishers/developers alongside the unchanged
companies list; IGDB requests the involved_companies developer/
publisher flags to split by role.
- Migration 0112 adds generated_publishers/generated_developers columns
on roms, projects them through the roms_metadata view, mirrors them
into roms_facets, and adds publisher/developer virtual-collection
types (triggers/functions rebuilt for MariaDB/MySQL + PostgreSQL).
- Filters, facets, endpoints, smart collections and the gamelist/pegasus
exporters all carry the new fields; exporters prefer the explicit
split and fall back to the companies heuristic for un-rescanned ROMs.
Frontend (v2):
- Shared filter store + API service, gallery filter drawer, URL
persistence, game detail display (Developers/Publishers with a
Companies fallback), edit dialog, smart-collection criteria, and a
publisher/developer "group virtual collections by" option.
- Also relabels the confusing "company"->"Developer" group-by option
to "Company" now that a proper Developer option exists.
Fixes#3518
Co-Authored-By: Claude Opus 4.8 (1M context) <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>
A rom parsed its filename tags when it was first inserted and never again,
so a change to parse_tags only reached rows scanned after it. The freshly
parsed values were built for every rom but only consumed on the insert
path, and scan_rom reseeded the tag columns from the existing row, so no
scan type could refresh them.
A complete rescan (or an explicit per-rom selection) now writes them back.
A hashes rescan still doesn't, since it is scoped to re-reading file bytes.
scan_rom also carries "version" forward now. It was the one tag column
missing from its attrs, so a re-parsed version would have been dropped, as
the value written by the reassociation path already was.
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>
A scan flags firmware whose file vanished, but nothing could act on the
flag: stale BIOS entries could only be found by opening each platform's
Firmware tab one at a time, the player still offered them (auto-selecting
the sole entry, so the game failed to boot with nothing pointing at the
BIOS), and platform firmware counts included them.
Adds a `missing` filter to the firmware list endpoint, a
`cleanup_missing_firmware` manual task alongside the ROM one, and a
Missing firmware tab in Library management that lists every flagged entry
library-wide with a bulk cleanup. The player now asks for present
firmware only, and firmware selection moved to a `playerFirmware` util
that never picks a missing entry. `firmware_count` counts only firmware
present on disk; the rows themselves still ship so the Firmware tab can
strike them through.
`FirmwareSchema` gains `platform_id` so the library-wide list can group
by platform.
Fixes#4075
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 bug 0107 fixes was silent: the window grew two columns the index never
followed, and nothing failed. Pin the shape the migrations build, and assert the
window reads only columns that index covers, so the next metadata provider added
to the COALESCE chain fails here instead of quietly restoring the full scan.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The hash search tests reached membership through
`get_smart_collection_roms`, which no longer exists now that a smart
collection is served as a composed query. Ask for the collection the way
the gallery does instead, so the criterion is still exercised end to end.
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>
The gamelist branch of generated_first_release_date is gated on an
8-digits/T/6-digits regex, which does not prove the digits form a real
date. EmulationStation, ES-DE and Skyscraper write "00000000T000000" for
an unknown release date, and make_timestamp raises on it. Because the
column is STORED, that aborts the 0098 ALTER TABLE on upgrade, and any
later INSERT of such a ROM on installs already past 0098.
romm_gamelist_epoch_ms now traps the error and returns NULL, matching the
range guard the MariaDB branch already applied. 0105 replaces the
function in place for installs that have already run 0098.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Asserting the model declares the index only restates `models/rom.py`. The
migration test covers what matters: the index exists in a database the
migrations built. Also pin the predicate test to the literal it compiles
to, so an unrelated `IS NOT NULL` elsewhere in the query cannot fail it.
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>
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>