Commit Graph

1886 Commits

Author SHA1 Message Date
Georges-Antoine Assi
117f420dca Merge pull request #4013 from rommapp/fix/hashes-scan-rematches-hasheous
fix(backend): re-run the Hasheous hash lookup on a hashes scan
2026-07-30 19:23:56 -04:00
Georges-Antoine Assi
50d4372b2b refactor(backend): drop redundant comment on the hashes scan gate
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 19:18:40 -04:00
Georges-Antoine Assi
11f570fede fix(backend): clear a stale Hasheous match when a rehash no longer matches
A rehashed ROM whose new hashes no longer match Hasheous kept its old
`hasheous_id` and `hasheous_metadata`: the merge loop only writes truthy
values, so an empty match cannot overwrite the values seeded from the
existing ROM, and the verification flags stayed on a ROM that no longer
earned them.

Clearing on any empty match would be wrong, though: `lookup_rom` returns the
same empty fallback whether Hasheous answered "unknown hashes" or was simply
unreachable (#2236), so an outage would silently de-verify a whole library.
Have `lookup_rom` return whether it reached a definitive answer, mirroring
`meta_ss_handler.lookup_rom`, and only clear the match on a conclusive miss.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 19:13:57 -04:00
Georges-Antoine Assi
fee2724a0e Merge pull request #3989 from Spinnich/feat/screenscraper-quota-awareness
feat(screenscraper): pace and report scans against the account's reported limits
2026-07-30 17:52:10 -04:00
Georges-Antoine Assi
a55d50998e refactor(screenscraper): move the scan reporting into ss_handler
Priming the account, the quota lines and the end-of-scan skip list are
ScreenScraper's own bookkeeping, so they move out of the scan socket and
behind begin_scan(), log_quota() and log_scan_summary(). The scan keeps
only the decision it owns: whether this scan uses ScreenScraper at all.

The quota-line bookkeeping joins the skipped ROMs in a _ScanState
instance, so the tracking that resets together lives together and needs
no global statement.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 17:43:32 -04:00
Georges-Antoine Assi
7ce4f1d255 Merge pull request #4005 from Spinnich/fix/missing-tab-sidecar-perf
perf(roms): stop the Missing tab scanning the whole library
2026-07-30 15:06:59 -04:00
Georges-Antoine Assi
6fd2d9576c fix(backend): re-run the Hasheous hash lookup on a hashes scan
A ROM's "verified" state comes entirely from the Hasheous signature match
flags in `hasheous_metadata`, but `ScanType.HASHES` was missing from both
Hasheous gates in `scan_rom`. A rehash recomputed the file hashes and then
never re-asked Hasheous about them, so the verification chips stayed dark
(#4001). RetroAchievements was already gated in, which is why its provider
icon appeared while nothing lit up.

A follow-up update scan didn't help either: that branch is gated on
`rom.hasheous_id`, which is never set for a ROM that has yet to match.

Add `HASHES` to `fetch_hasheous_hash_match` and `fetch_hasheous_rom`, and
to the "don't overwrite existing base fields" branch: Hasheous now returns
a name/cover/summary on a rehash, and `_identify_rom` short-circuits before
the cover download, so a changed `url_cover` would point at an image that
is never fetched.

Fixes #4001

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 14:53:46 -04:00
Georges-Antoine Assi
2882f9711a Restore DMCA placeholder comment on the grid filter
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:41:55 -04:00
Georges-Antoine Assi
77925db009 Drop redundant DMCA placeholder comments
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:41:16 -04:00
Georges-Antoine Assi
6217235c4e Skip DMCA-locked grids when scraping SteamGridDB
SteamGridDB does not remove assets taken down under DMCA; it returns them
with "lock": true and strips the URL signature, so the CDN serves a
placeholder image reading "This asset has been removed in response to a
DMCA takedown notice" for both the full asset and its thumbnail.

Filter locked grids in _get_game_covers, the single funnel for scan
matching, ID lookups and the manual cover picker.

Closes #4003

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:21:00 -04:00
Spinnich
fdb000576a perf(roms): stop the Missing tab scanning the whole library
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>
2026-07-30 12:13:03 +00:00
Spinnich
c7284f02d2 Merge remote-tracking branch 'upstream/master' into feat/screenscraper-quota-awareness
# Conflicts:
#	backend/endpoints/sockets/scan.py
2026-07-29 14:01:06 +00:00
Spinnich
c2786429fd fix(screenscraper): address review feedback on quota awareness
Four points from the PR review:

- Leave the process-global ScreenScraper state alone when a scan does not use
  ScreenScraper. DEV_MODE runs scans in-process, so overlapping scans could
  otherwise clear each other's learned limits and skipped ROMs.
- Return pacing to the defaults when the per-scan state resets. Priming re-reads
  the account moments later; should that fail, the conservative default is safe
  for whatever account the credentials now name, whereas the previous scan's
  allowance may be more than this one is entitled to.
- Stop a rate-limited ROM from trying the next lookup. A refusal that survives
  the retry now propagates out of the handler and is caught once per ROM in
  fetch_ss_rom, instead of being swallowed per call site and sending the caller
  on to spend another retried request against a budget that is already gone.
  _is_daily_quota_error excludes the rate-limit 429 so the two stay distinct.
- Hand the request slot back before inspecting and re-encoding a cover, so
  local image work no longer holds a ScreenScraper thread.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 13:55:19 +00:00
Georges-Antoine Assi
57f4fd21d0 cleanup 2026-07-28 23:01:07 -04:00
Georges-Antoine Assi
8c12ac86a1 fix(launchbox): keep the heartbeat honest during a first import
The store is written in batches, so an initial import answers for the
names committed so far long before it holds the whole dump. Checking
that the name index exists reported the provider healthy off a fraction
of the entries, and a run that died partway left it that way for good.

Flag the initial import and clear it once a run completes, so only a
finished import counts as healthy. A refresh keeps serving the previous
dump, so it is not flagged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 22:22:06 -04:00
Georges-Antoine Assi
52940ea3d4 fix(launchbox): stop the cloud provider from silently matching nothing
LaunchBox cloud lookups read from a Redis store that only the metadata
update task fills, but nothing surfaced when that store was empty. The
provider reported healthy, every search returned zero results, and the
logs said nothing.

- heartbeat now reports unhealthy until the store is populated, and an
  empty store logs what to set to fix it
- the update task can be run manually whenever LAUNCHBOX_API_ENABLED is
  on, instead of also requiring the scheduled-update flag
- the ~600k entry dump was buffered into a single pipeline, peaking at
  1.7GB of RSS and writing nothing at all if the job was killed part way
  through. Writes now go out in batches and parsed elements are dropped
  as they are consumed, which caps the run at ~260MB. The task also gets
  its own timeout, since the default 5 minutes does not cover a 100MB
  download plus a 500MB parse
- alternate name lookups ignored the platform, so "Super Mario World" on
  PlayStation matched Super Mario Bros.
- Coleco ADAM was spelled wrong, and Famicom / Super Famicom pointed at
  platform names LaunchBox does not use

Fixes #3981

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 19:55:16 -04:00
Spinnich
5fb27a55f9 feat(screenscraper): make scanning aware of the account's reported limits
ScreenScraper returns the account's allowances on every response, but only
maxthreads was read. Use the rest:

- Pace requests against the reported maxrequestspermin (falling back to the
  documented threads x 50), so fast lookups can no longer overrun the
  per-minute budget without ever exceeding the thread cap.
- Report the remaining daily and unrecognized-ROM quotas after each platform
  and at the end of a scan, and warn once when either drops below 10%.
- Hint once per scan when SCAN_WORKERS is below the thread allowance (scans
  slower than the account allows) or above it (extra workers just queue).
- Raise a distinct error when a request is refused twice for exceeding the
  rate, so the ROM is reported as skipped in the scan summary instead of being
  saved with no ScreenScraper data.
- Route ScreenScraper media downloads (covers, screenshots, manuals, mixed
  media) through the same limiters, since they are api2 endpoints that count
  against the same allowances, and derive their timeout from the account's
  advertised download speed.

Fixes #3978

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 17:09:52 +00:00
Ryan McClelland
32f9ac1b90 fix(resources): handle write failures when the disk is full
The streamed resource downloads wrapped their writes in `except
httpx.TransportError`, which does not cover the `OSError` raised by
`f.write()` when the filesystem is out of space. The error escaped the
handler and the partially written file stayed on disk.

A truncated file is worse than a missing one: it satisfies the
`cover_exists` / `screenshots_exist` checks and the `file_exists` guards
in `store_ra_badge` and `store_media_file`, so later scans skip it and
never refetch it. The artwork stays permanently corrupt.

Catch `OSError` on every resource write path (covers, screenshots,
manuals, RA badges, media files and uploaded artwork) and remove the
partial file so the next scan refetches it. A stream that drops
mid-transfer leaves the same truncated file, so the transport-error
branches now discard it too. The cleanup helper swallows its own
`OSError` so it can never mask the original failure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 13:34:41 -07:00
Georges-Antoine Assi
9b0f281df1 Bind note update/delete to the rom in the path
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>
2026-07-26 16:42:58 -04:00
Georges-Antoine Assi
96833892ce security: enforce asset upload limits before spooling, cover screenshots
Addresses the Greptile review on #3952.

- Reject oversized asset uploads from Content-Length in middleware, before
  FastAPI parses and spools the multipart body to temporary storage. The
  handler-level check stays as a backstop for chunked requests.
- Apply the limit to screenshot fields on the save, state and standalone
  screenshot endpoints, not just the primary file.
- Clamp the autocleanup limit to at least 1 so a non-positive value cannot
  wipe every save in a slot.
- Document the new settings in env.template.

Rename MAX_SAVE_UPLOAD_SIZE_BYTES to MAX_ASSET_UPLOAD_SIZE_BYTES now that it
covers states and screenshots too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 09:24:42 -04:00
Georges-Antoine Assi
49d1ae71b2 Fix smart collections dropping newer filters
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>
2026-07-25 13:53:02 -04:00
Georges-Antoine Assi
7d844c735d add miximage v2 support gamelist 2026-07-25 09:13:39 -04:00
Georges-Antoine Assi
93a128965b Merge pull request #3936 from Spinnich/fix/rom-detail-smart-collections
fix(roms): list the smart collections a ROM belongs to on its detail view
2026-07-24 21:38:13 -04:00
Spinnich
c6c80d8239 perf(roms): resolve smart-collection membership in SQL, not Python
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>
2026-07-24 14:57:43 +00:00
Georges-Antoine Assi
fa63d7b5b5 Merge pull request #3917 from rommapp/feature/scan-region-mode
Add scan.priority.region_mode to let config regions drive media selection
2026-07-23 18:11:18 -04:00
Georges-Antoine Assi
36b7c228bc Address review: guard region_mode type and scope it to media
Non-string region_mode values (YAML list/mapping) now take the
warn-and-fallback path instead of raising TypeError on the frozenset
membership check during startup.

get_preferred_regions only applies prefer_config reordering when
selecting media (for_media=True); name and release-date selection keep
the rom-tags-first ordering, matching the documented scope.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 17:52:44 -04:00
Georges-Antoine Assi
36e86dce30 Merge pull request #3918 from rommapp/fix/duplicate-media-screenshots
Stop storing fanart and title_screen twice when screenshots are enabled
2026-07-23 17:09:03 -04:00
Georges-Antoine Assi
6666019ce5 Stop duplicating fanart and title_screen into screenshots
ScreenScraper scraping added the fanart and title-screen URLs to
url_screenshots even though the same images are persisted to their
dedicated fanart/ and title_screen/ media folders, downloading and
storing every image twice. Restrict url_screenshots to the actual
screenshot media type; the dedicated media still renders in the artwork
gallery. The gamelist handler had the same pattern with title_screen
and gets the same fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:47:22 -04:00
Georges-Antoine Assi
67eab49a72 Add scan.priority.region_mode to prefer config regions for media
New opt-in config key scan.priority.region_mode with values
prefer_rom_tags (default, current behavior) and prefer_config. With
prefer_config, the configured region priority outranks the rom's
filename region tags when selecting ScreenScraper media, and the rom's
own tags remain the fallback when the configured regions have no media.
Unknown values warn and fall back to prefer_rom_tags, and the key
survives runtime config-file rewrites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:46:38 -04:00
Georges-Antoine Assi
a82615f4a7 Treat Playmatch plain-text health response as healthy
The Playmatch /api/v2/health endpoint returns the plain-text body
"Healthy", but heartbeat() routed it through the JSON-parsing
_request(), so decoding always failed and the Metadata Sources page
showed "Connection failed" for a healthy service. Do a raw GET and
treat any 2xx response as healthy, matching the Hasheous handler.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:45:54 -04:00
Georges-Antoine Assi
e2827b9886 Merge branch 'master' into fix/server-stats-breakdown-perf 2026-07-23 15:50:08 -04:00
Georges-Antoine Assi
5744e2e518 Merge pull request #3896 from tmgast/feature/music-playlists
Add music favorites and playlists API
2026-07-23 15:14:54 -04:00
Spinnich
f69e4756a7 perf(stats): aggregate server-stats breakdowns from roms_facets
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>
2026-07-23 17:27:09 +00:00
Georges-Antoine Assi
c99154a5d0 Merge pull request #3903 from rommapp/fix/emit-restored-roms-during-platform-scan
fix(scan): emit a client update for ROMs that are no longer missing
2026-07-23 12:48:24 -04:00
Georges-Antoine Assi
a84ad2289d refactor(music): key playlists and favorites on rom_file_id
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>
2026-07-23 10:58:53 -04:00
Georges-Antoine Assi
8c5e3d8eae Merge branch 'master' into feature/music-playlists 2026-07-23 10:48:53 -04:00
Georges-Antoine Assi
559cc7f7ea fix(scan): keep a soundtrack cover path when its unlink fails
remove_persisted_cover swallowed OSError, so clearing cover_path
regardless dropped the only reference to a file still on disk. It now
reports whether the file is gone, and the path is kept for the next scan
to retry when it isn't.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 10:41:30 -04:00
Georges-Antoine Assi
5548f314d5 refactor(scan): fold track metadata into the rom file reconciliation
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>
2026-07-23 10:32:26 -04:00
Georges-Antoine Assi
1ee41f9a66 fix(scan): don't write NULL over NOT NULL columns when reconciling files
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>
2026-07-23 10:08:01 -04:00
Georges-Antoine Assi
d9050eb4cc fix(scan): unlink soundtrack covers orphaned by dropped track metadata
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>
2026-07-23 09:44:12 -04:00
Georges-Antoine Assi
71c04f186b fix(scan): emit a client update for ROMs that are no longer missing
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>
2026-07-23 09:40:17 -04:00
Georges-Antoine Assi
21cc044bf1 fix(scan): clear a soundtrack cover that's gone from the audio file
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>
2026-07-23 09:24:19 -04:00
Georges-Antoine Assi
83ad2b3132 fix(scan): reconcile rom_files in place instead of purging them
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>
2026-07-23 08:54:50 -04:00
Georges-Antoine Assi
42059a41d6 Merge pull request #3887 from rommapp/fix/rar-archive-hashing
fix(archives): read RAR archives through bsdtar so they can be hashed
2026-07-23 08:08:37 -04:00
Georges-Antoine Assi
969d9b3f9e fix(archives): fail archive hashing when a member can't be read
A member that failed or timed out mid-archive ended the member stream
silently, so the caller kept the composite hash built from the members
that happened to succeed. Raise ArchiveReadError instead and fall back to
hashing the archive's raw bytes, with no archive_members recorded.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 07:37:39 -04:00
nendo
8a39bf0b20 Address review: per-row insert conflict handling and scoped append dedupe
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.
2026-07-23 15:47:05 +09:00
nendo
70e583b9a0 Add music favorites and playlists API
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.
2026-07-23 15:32:32 +09:00
Georges-Antoine Assi
91e098614e perf(backend): look up virtual collection covers per collection
_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>
2026-07-22 21:52:59 -04:00
Georges-Antoine Assi
15554f905e Merge branch 'master' into perf/materialize-virtual-collections 2026-07-22 20:17:16 -04:00
Georges-Antoine Assi
753556af7b perf(backend): materialize virtual collection membership
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>
2026-07-22 10:06:05 -04:00