Commit Graph

580 Commits

Author SHA1 Message Date
zurdi
76b80e0e1a refactor(player): apply the simplify pass
Slot pruning is one locked handler query that selects only the tail of
the slot by column, so an upload no longer loads every joined version;
the retention tests share their seeding helpers. Both asset lists fold
their groups through one useGroupFold composable, render the owner chip
through one AssetOwnerChip, and AssetStrip tracks each group's newest
timestamp while it builds the group. The two upload dialogs share a
PendingFilesDropzone for the drop zone and file list. The slot title
and the newest-by-timestamp lookup live in the utils next to their
siblings. The split states layout aligns its label and content rows
with a subgrid instead of hand-matched heights, so AssetPreview loses
the consumer-driven eyebrow height. Stories take explicit ids.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:21:45 +02:00
zurdi
b536aced56 fix(player): apply the code-review findings
Correctness: the upload dialog seeds dropped files immediately (three of
its tests ran vacuously), dedupes them by name, submits on Enter and
rejects a blank slot name; slotted manual uploads are new versions even
when the bytes match; the core picker sees the nightly cores the player
offers; clearing a state hands the boot back to the save it displaced;
a slot or core group can be folded even while it holds the selection
and reopens when the selection moves into it; the entrance stagger
counts only rendered rows; the stream save picker keeps its flat list;
slot retention orders by id as a tiebreaker for same-second uploads.

Reuse: asset helpers shared by both lists move to v2/utils/assets.ts,
the write slot follows the picked save in one place, the upload payload
carries its type, and the endpoint's delete sequence is one helper.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:05:29 +02:00
Sam Dornan
1c20e77e41 Reject unusable smart collection criteria instead of dropping them
The real /code-review and /simplify passes over this PR, which an earlier
run substituted hand review for.

`from_stored_criteria` dropped the entries the model rejects. Dropping a
filter drops the constraint with it, so a row holding
`platform_ids: [3, "gba"]` widened from one platform to the whole library.
It now answers None, and the one caller turns that into a query matching
nothing: the loop over every smart collection still cannot be stopped by
one bad row, and a collection never shows more than its criteria claim.

`/api/roms/download` declared `collection_id` and `smart_collection_id`
unbounded while `get_roms_scalar` validates them through the model, so
`collection_id=0` raised inside the handler as a 500. They now carry the
`ge=1` the other two routes already declare, and fail at the boundary as
a 422.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 06:36:54 +00:00
Sam Dornan
8e61a38b7b Trim comments and docstrings to the repo's limits
Review polish over the whole change: every comment block over two lines
cut back, and the two carrying change history rather than current
behaviour rewritten to describe what the code does now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:38:05 +00:00
Sam Dornan
eb190a366b Simplify the review fixes
The tolerant validator rebuilds its input instead of deleting from it in
place, and tests the dropped names against the keys it holds rather than
filtering them out of the error list first.

The router test built two near-identical routes behind a branch; one route
with a plain parameter alongside the model covers both cases it asked
about.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:31:11 +00:00
Sam Dornan
8809f06729 Harden the filter model after code review
Three defects the review pass turned up:

`from_stored_criteria` raised on a smart collection whose stored
`filter_criteria` holds a value the model rejects. That JSON is written
unvalidated and read in a loop over every smart collection, so one bad row
stopped all the later ones from refreshing on any ROM write, and 500'd a
public smart collection. It now drops the entries it cannot honour, which
is what the criteria reader did before it validated anything.

Two comments claimed `metadata_providers` matches id columns on `Rom`. It
matches them on the facets mirror, so a reader trusting the comment
concludes the filter needs no join and cross-joins `roms_facets` into the
query. Corrected, and pinned by a test asserting every registered filter
joins the mirror exactly once.

`as_query_dependency` silently mis-built a route for a field with an alias
or a `default_factory`, the latter sharing one mutable default across
requests. Both now fail at startup, and the helper has the tests it
shipped without.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:29:02 +00:00
Sam Dornan
d981a897ff Merge remote-tracking branch 'origin/master' into claude/graphql-api-migration-vu20z2
# Conflicts:
#	backend/endpoints/roms/__init__.py
#	backend/handler/database/roms_handler.py
#	backend/tests/handler/database/test_roms_group_by_index.py
2026-09-13 00:32:39 +00:00
Sam Dornan
d145e77f47 Merge remote-tracking branch 'origin/master' into claude/graphql-api-migration-vu20z2
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-13 00:25:37 +00:00
Georges-Antoine Assi
35cab08efc Merge remote-tracking branch 'origin/master' into fix/group-sort-aggregate-4447
Resolves the overlap with #4463's per-user sidecar cache versions: the
endpoint keeps the resolved sort key while adopting master's
normalise-once ordering params and single sidecar cache key, and
`sorts_by_rom_user_column` now answers from `_resolve_gallery_sort_key`
so the cache key and the ORDER BY agree on what a RomUser sort is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:12:28 -04:00
Sam Dornan
2f38a33b07 perf(roms): match the gallery filters against the facets mirror
Every multi-value filter matched against either `roms` or the
`roms_metadata` view over it. Both carry the raw provider-metadata blobs
inline, so evaluating a facet predicate reads the whole wide table, and no
index can serve a JSON containment test.

`roms_facets` already holds exactly these values in a narrow, trigger-
maintained mirror (0100, extended by 0103 and 0112), and the dropdown
queries and the stats coverage breakdown already read it for this reason.
The filters now read it too, so applying any of them costs one join to a
table that is a fraction of the size.

On a seeded 40k-game library (139 MB of `roms` against 8 MB of
`roms_facets`, stock 128 MB buffer pool), through `filter_roms`:

    total count      374 ms -> 70 ms
    rom id index     615 ms -> 74 ms
    page (limit 50)  1.5 ms -> 1.3 ms

Both sidecars run on every gallery request, since `with_total` and
`with_rom_id_index` default on. The page query was already fast: it stops
early on an indexed sort, so it never had to evaluate the predicate for
the whole library.

Matching is unchanged: every mirrored column is byte-equal to its source
across all 40k rows, no rom is missing its facets row, and each filter
selects the same ids as before under every logic operator. The mirror also
covers the provider id columns, so `metadata_providers` moves with the
rest rather than being the one filter left reading `roms`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-12 23:32:50 +00:00
Sam Dornan
983e24d5f8 refactor(roms): carry the ROM filters as one model
The filter vocabulary (13 multi-value filters with their logic operators,
plus the boolean and scope filters) was written out in five places: the
`/api/roms` query parameters, `filter_roms`'s 63-line signature, the
`kwargs.get` block in `get_roms_scalar`, the criteria translation in
`get_smart_collection_criteria`, and the `is_unscoped` test that decides
what may be cached.

That last one is the dangerous copy. The gallery's sidecar caches are keyed
on user/order/grouping but not on the filters, so a filter missing from
`is_unscoped` would let one user's narrowed gallery be stored under, and
served from, the shared "all" key.

`RomFilterParams` becomes the single home. The route takes it as a
dependency, `filter_roms` reads its fields, and smart collections rebuild
it from their stored criteria (legacy `selected_*` keys and the
`platform_id` scalar included, keeping `from_stored_criteria` the only
place that knows about them). `has_filters` now reads the model's own
fields, so a filter added later counts towards the cache gate without
anyone remembering to list it, and a test asserts that for every field.

The route reaches the model through `as_query_dependency` rather than
`Annotated[RomFilterParams, Query()]`, because FastAPI expands a query
model into its fields only when the model is a route's *only* query
parameter. `/api/roms` has a dozen others, so the native form would leave
one required parameter named `filters`: the schema would advertise it, the
generated client would be built from that, and a request carrying the
fields themselves would be rejected. A dependency's parameters are
flattened individually, so building one from the model keeps the fields.
An endpoint test pins that, since the failure is silent.

The API contract is unchanged: `/api/roms` still takes the same 58 query
parameters with identical types, descriptions, defaults and constraints,
and regenerating the frontend types from the new schema produces a
byte-identical `src/__generated__`. Only the order of the parameters in
the OpenAPI array differs, since FastAPI lists a dependency's parameters
after the route's own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-12 23:18:56 +00:00
Sam Dornan
08517f14ec refactor(roms): derive ROM filter dispatch from a registry
The ten JSON-array facet filters (genres, franchises, collections,
companies, publishers, developers, age_ratings, regions, languages, tags)
had ten near-identical `_filter_by_*` methods differing only in the column
they matched on, and `filter_roms` then restated the same vocabulary twice
more: once in `filters_to_apply` and once in the `needs_metadata_join`
list that decides whether the query joins `roms_metadata`.

That second list is the risk: a new metadata-backed filter that is added
to `filters_to_apply` but forgotten in `needs_metadata_join` compiles and
runs, but silently cross-joins `roms` against `roms_metadata` under
`group_by_meta_id`, ranking the whole library instead of the matches.

Introduce `ROM_FILTER_SPECS`, one declarative row per filter carrying its
name, how its values are matched and the column they match against. The
join decision is now derived from the column's own mapper, so it cannot
drift from the filters it guards, and one `_apply_filter_spec` replaces
the ten methods.

`statuses` stays in `filter_roms`: it matches against RomUser, runs after
the grouping window rather than with the rest, and carries the default
"hide hidden roms" behaviour.

The generated SQL is byte-identical across 18 cases covering every filter,
all three logic operators, grouping and per-user scoping.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-12 22:46:46 +00:00
zurdi
71c55224b1 fix(roms): apply admin visibility before the grouped dedup window
Review follow-up from Greptile on the PR: the aggregate masked only the
personal RomUser.hidden flag, so a sibling hidden through admin
hidden_rom_ids/hidden_platform_ids could still drive its group's
position. The admin visibility filters now apply before the dedup
window builds, so a permission-hidden sibling can neither represent a
group nor feed its sort key, and a permission-hidden representative no
longer hides its whole group.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 21:07:03 +02:00
zurdi
dd500d77a6 review(pr-ready step 4): tighten the sort_key parameter comment
Polish pass: the A-D sweep found the merged diff already in shape;
one three-line parameter comment ran long. 165 tests across the
affected suites pass on the merged tree and trunk fmt/check are clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 20:58:35 +02:00
zurdi
67271ebef1 Merge remote-tracking branch 'origin/master' into fix/group-sort-aggregate-4447
# Conflicts:
#	backend/handler/database/roms_handler.py
#	backend/tests/handler/database/test_roms_hltb_length.py
#	backend/tests/handler/database/test_roms_metadata_sort.py
#	backend/tests/handler/database/test_roms_rom_user_sort.py
2026-09-11 20:47:20 +02:00
zurdi
59bda3e6fd review(pr-ready step 3): one sort resolution, one hidden predicate
Simplify pass:
- get_roms_query returns the resolved _GallerySortKey and filter_roms
  accepts it, so one request resolves the sort once and the grouped
  aggregate cannot disagree with the ordering the query was built with.
- _GallerySortKey carries a single source tag instead of two mutually
  exclusive booleans.
- _rom_user_not_hidden() replaces the three copies of the null-safe
  visibility predicate.
- _GROUP_SORT_AGGREGATE_TYPES trimmed to the types RomUser has
  (DateTime, Integer); Date/Numeric were unreachable.
- order_dir normalizes once per entry point.

Skipped, deliberately: folding dedup_subquery into the join condition
(plan-pinned SQL) and a single-owner ORDER BY refactor (touches every
get_roms_query caller). Compiled SQL is unchanged, per the shape tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 20:42:52 +02:00
zurdi
ea9063cb0a fix(roms): survive session reuse and cache failures in the bump queue
Review follow-ups from Copilot and Greptile on the PR:
- The after_commit flush now pops the queued bumps and the armed flag,
  so a reused session's next transaction re-arms instead of queueing
  into a map nothing will flush; a rollback discards the queue the
  same way.
- A cache failure after commit logs instead of raising: the write is
  already durable, so a transient Redis error must not turn a
  successful mutation into an apparent failure.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 20:36:31 +02:00
zurdi
6532e0636c review(pr-ready step 2): mask hidden siblings, one window sort, validate order_by
Code-review pass fixes:
- A hidden sibling's key is masked to NULL inside the group aggregate,
  so a rom the user hid can no longer drive its group's position.
- The aggregate shares row_number's window spec with a whole-partition
  frame, so MariaDB sorts the derived table once instead of twice.
- _mapped_sort_column resolves order_by only to mapped columns; a
  relationship or dunder name now falls back to the name sort instead
  of raising while the ORDER BY is built.
- filter_roms takes everything after the query keyword-only.
- Tests: hidden-sibling behavior test, grouped id-index test, the
  covering-index check compiles the window-level SELECT, alias-free
  ORDER BY assertions, MariaDB-dialect null-safe join assertion, and
  _make_rom/_ordered_names replace the copied fixture helpers.

Known and deliberate, per review: the aggregate is direction-dependent
(MAX on desc, MIN on asc), rating's 0 sentinel stays a real key, and
non-aggregated (enum, lexical, roms-side) keys keep representative
semantics. The stale-sidecar gap it flagged is fixed separately by the
per-user cache versioning PR.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 20:31:57 +02:00
zurdi
b037b0df8d review(pr-ready step 3): split per-user counters, queue bumps until commit
Simplify pass over the sidecar invalidation change:
- Split the per-user version into sort (sidecar:user_ver) and sibling
  (sidecar:user_sib_ver) counters so an is_main_sibling toggle only
  refreshes grouped-gallery entries, not every sorted index.
- Queue cache bumps in session.info and flush them once from a one-shot
  after_commit listener, deduped per user, instead of bumping inline
  (and possibly repeatedly) before the write is durable.
- Give unscoped filter values their own cache key builder instead of
  overloading the sidecar key with kwargs.
- Normalize order_by/order_dir casing once at the top of get_roms and
  hoist the single sidecar cache key shared by the char and id indexes.
- Rework TestRomUserCacheVersion delta-style; the add-bump test now
  seeds its own bare rom since the rom fixture pre-pairs admin_user.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 19:48:41 +02:00
zurdi
3c1b190bff review(pr-ready step 2): close the invalidation gaps the key left open
Code-review pass: the cache key builder lowercases order_by before the
version gate (a mixed-case sort cached under an unversioned key that
writes never rotated); grouped galleries embed the per-user version
too, since is_main_sibling picks their representative; the bump moved
to an after_commit hook so a rollback never bumps and a concurrent
reader cannot cache pre-commit rows under the new version; and the
filter-values sidecar opts out of the rotation, since hidden, the one
RomUser column it reads, already bumps the global version.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 19:48:35 +02:00
zurdi
ced6eb60e3 fix(roms): invalidate a user's gallery sidecars on rom_user writes
The rom_id_index/char_index sidecars are memoised under keys whose
version only hidden writes bump, so a gallery sorted by a per-user
column kept serving the pre-write order for up to seven days after a
play, a rating, or a status change.

update_rom_user now bumps a per-user version counter, and the unscoped
sidecar cache key embeds it whenever the sort resolves to a rom_user
column, so every writer (the props endpoint, save and state uploads,
play sessions, the RetroAchievements sync) invalidates exactly that
user's per-user-sorted entries. Name and metadata sorts keep their
shared keys, the global hidden bump is untouched, and superseded
per-user entries age out by TTL instead of needing keys-set
bookkeeping.

Fixes #4448

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 19:48:35 +02:00
zurdi
a7e44d9fd2 fix(roms): sort grouped galleries by the group aggregate
With group_by_meta_id, the sibling-dedup window picks each group's
representative by main-sibling/prerelease/region rank, and the outer
ORDER BY only ever saw that rom's own sort key, so a group whose
rank-preferred copy was never touched sorted into the NULL tail even
when another sibling was played yesterday.

RomUser-column sorts now aggregate the key across the group inside
the existing window pass (MAX descending, MIN ascending, so a group
lands in the NULL bucket only when every sibling's key is NULL), and
the outer ordering reads that group value through a null-safe outer
join that keeps the covering-index plan (the inner-join and CTE
shapes measured 3-7x worse; this one is ~1.55x master on the one
family it fixes and compiles byte-identically everywhere else). The
displayed representative stays the rank-preferred one. Metadata and
Rom-side grouped sorts keep representative order deliberately, since
materializing a roms-side key into the window drops it off
idx_roms_sibling_cover, the regression migration 0107 prevents.

Fixes #4447

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 19:37:15 +02:00
zurdi
13b0ba4e3d review(pr-ready step 3): one nulls-last helper, marker-driven zero fold
Simplify pass: the dialect-aware NULL placement becomes a module
helper shared with the music-track ordering, which gains index-order
reads in the three cases that never needed the emulation term. The
zero-as-unset rule moves from a name frozenset onto the columns
themselves (mapped_column info markers), the ordering block stops
rebinding one name through four types, driver pinning collapses into
two conftest fixtures, and the dialect matrix lives in one
parametrized test instead of two per-family copies.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 15:17:32 +02:00
zurdi
fbc32aa017 review(pr-ready step 2): one NULL-placement mechanism, honestly priced
Code-review pass: the rom_user and metadata NULL handling collapse
into a single block built from the folded sort key, with PostgreSQL
on native NULLS LAST for both families and the leading IS NULL term
emitted only where an engine needs it (non-PG ascending), so the
redundant terms and the raw-vs-folded hazard are gone. The zero-as-
unset column set moves to models/rom.py beside the columns it
describes, the hltb query-shape test folds into the metadata
parametrize, and the comments that overclaimed index behavior after
the change now state the measured cost instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 15:02:16 +02:00
zurdi
2974d3c8e2 fix(roms): sort unset per-user and metadata keys last on every engine
Ascending rating/difficulty/completion sorts split visually identical
"unrated" games into two buckets: touched-but-unrated rows carry the
NOT NULL default 0 and led the list while never-touched games trailed
it. The three zero-default sort keys are now wrapped in NULLIF(col, 0)
so both unset shapes share the final bucket, tiebroken by rom id.

Metadata sorts kept each engine's default NULL placement: MariaDB led
ascending release-date sorts with the wall of unmatched roms while
PostgreSQL trailed it. NULLs now land last on every engine in both
directions, emitted per dialect to keep index reads where the engine
allows them: PostgreSQL uses native NULLS LAST, MariaDB descending
already places NULLs last on the plain index read, and only MariaDB
ascending pays a measured filesort (EXPLAIN at 30k roms: 51ms index
read to ~150ms), the one case the engine cannot serve from a
single-column index.

Fixes #4449
Fixes #4450

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
2026-09-11 13:06:05 +02:00
Georges-Antoine Assi
da3c5b773c refactor(roms): simplify the rom_user sort and its cache keys
Fold the three sidecar key builders into one `_sidecar_redis_key`, so the
key shape lives in one place and no sidecar can omit the schema version.

Carry the RomUser branch forward as a flag instead of re-deriving it from
the resolved column's `class_`, and state the char index guard positively
now that the fallback it described is gone (`Enum` subclasses `String`).

Collapse the two near-identical sort fixtures into one library, and assert
the user restriction is absent from the WHERE clause rather than counting
substring occurrences.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 16:29:52 -04:00
zurdi
33c73a3fbe fix(roms): serve the char index only for lexically ordered sorts
The alpha strip's offsets only mean anything when the rows are ordered
by the letters being counted. Sorts that fell back to the name column
(dates, ratings) and native enum sorts (the database orders those by
declaration order) produced name-based offsets into a differently
ordered result, so strip jumps landed on the wrong rows. Skip the
sidecar for those sorts before touching the cache; the strip renders
its letters disabled. This also retires the letter walk's NULL bucket
and enum cast, which no such sort can reach any more.

Version the char_index and rom_id_index cache keys with the release
schema marker, like filter_values already does, so sidecars cached
before an ordering-semantics change stop being served after a deploy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ND1wfNV3vKwu8Mfinn4WkA
2026-09-10 18:39:29 +02:00
zurdi
e566f41c9d Merge origin/master into fix/rom-user-sort-4100
Combines the NULLS-last ordering with master's direction-following id
tiebreaker: the tiebreaker joins the filtered ordering tuple.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ND1wfNV3vKwu8Mfinn4WkA
2026-09-10 18:25:22 +02:00
zurdi
fb0800a893 fix(roms): keep unplayed games when sorting by a rom_user column
Sorting GET /api/roms by a per-user column (last_played, rating,
status, ...) re-applied the RomUser user filter as a WHERE clause,
collapsing the user-scoped LEFT JOIN into an inner join: every rom the
user had never touched vanished from the results and from the reported
total.

Drop the redundant filter (the join's ON clause already scopes the
rows) and pin NULL sort keys last in both directions with a leading
IS NULL term, which MariaDB, MySQL, and PostgreSQL all support. The
char-index letter walk mirrors the same NULL bucket through a shared
predicate so alpha-strip offsets stay aligned, and enum letter sources
are cast to String so PostgreSQL can take substring() of them.

Fixes #4100

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ND1wfNV3vKwu8Mfinn4WkA
2026-09-10 17:12:41 +02:00
Georges-Antoine Assi
6b86f7afd5 Merge pull request #4411 from rommapp/fix/db-pool-recycle
fix(db): recycle pooled connections before the server drops them
2026-09-10 11:01:32 -04:00
Georges-Antoine Assi
21d9a7f3c6 refactor(db): give the pool recycle sentinel one home
An operator's `0` means "off", but SQLAlchemy gates recycling on
`_recycle > -1`, so a literal 0 recycles on every checkout: a fresh
connect and auth handshake per pool checkout. Mapping it to -1 is
therefore load-bearing, but doing it at the engine left the value
defined in `config` and corrected in `base_handler`, so a second
consumer could reasonably pass the raw constant and reintroduce the
footgun. Fold the mapping into the constant.

Also drop the `wait_timeout` figure the comment attributed to MariaDB.
Its default is 28800s; 600s is a value some hosts lower it to, not a
MariaDB one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 10:48:54 -04:00
Georges-Antoine Assi
6b2ca96397 fix(db): recycle pooled connections before the server drops them
The engine sets `pool_pre_ping` but no `pool_recycle`, so a connection
the database closed for being idle is still handed out, and the ping on
that half-closed socket blocks the worker until TCP gives up: tens of
seconds to minutes of an unresponsive API for every request that draws
it, while a fresh connection to the same server answers instantly.

Default to 300s, under the lowest `wait_timeout` MariaDB is commonly
configured with, and make it settable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 20:25:36 -04:00
Sam Dornan
3a1ada011b Sort and filter the library by game length
HowLongToBeat times were only readable one game at a time, on a game's
detail page. This makes main-story length a property of the library:

* `generated_hltb_main_story` (migration 0128) is a STORED generated
  column over `hltb_metadata`, indexed, so the sort walks an index and
  the range filter composes into SQL.
* `GET /roms` takes `hltb_main_story_min` / `hltb_main_story_max` in
  seconds, either side optional, and `order_by=hltb_main_story`.
* The v2 gallery gets a sortable Length column in list mode and a
  game-length range (in hours) in the filter drawer, both surviving a
  bookmark via `?lengthMin` / `?lengthMax` and savable as a smart
  collection.

A rom HowLongToBeat has no time for derives NULL, so either comparison
drops it; the drawer says so rather than letting it read as a bug.

Closes #4232

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAn4d3drsdnEKeVuvkMNpU
2026-09-09 22:44:02 +00:00
Georges-Antoine Assi
083ea5f953 perf(gallery): match siblings on every identity id
`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>
2026-09-09 15:42:56 -04:00
Georges-Antoine Assi
dc27acd284 fix(gallery): create the identity triggers before the backfill
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>
2026-09-09 14:09:49 -04:00
Georges-Antoine Assi
954aa79041 Merge branch 'master' into perf/sibling-roms-materialize
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>
2026-09-09 13:47:47 -04:00
Georges-Antoine Assi
a8385cdaa8 style(anniversaries): trim the comments and simplify the day parser
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>
2026-09-09 12:34:49 -04:00
Georges-Antoine Assi
976dd09930 refactor(anniversaries): read the day off the shared rom list
`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>
2026-09-09 12:02:32 -04:00
Georges-Antoine Assi
500d449382 fix(anniversaries): stabilize the ordering and recover from a failed load
The day's ordering breaks ties on the rom id. Every rom released on the
same calendar day carries the same timestamp, so without it the paging
order, and which rows the 500 ceiling keeps, varied between requests.
MariaDB plans it the same way: still a covering index range scan, no
filesort.

The widget clears the loaded day when a request fails, so the rollover
check retries it. Claiming the day up front held the error copy until
local midnight, and the card offers no way to ask again.

Also pins the clock in `test_defaults_to_todays_utc_date`, which failed
on 1 January and raised on 29 February; corrects the Czech 2-4 plural
form, which the locale's own rule reaches; and drops "scope" from the
endpoint docstring, where it read as a claim about the auth scope
declared right above it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:34:11 -04:00
Georges-Antoine Assi
b65cc76edc style(anniversaries): fit the ceiling's comment on one line
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:04:07 -04:00
Georges-Antoine Assi
68e27d866c fix(anniversaries): cap the day's result set
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>
2026-09-09 11:00:54 -04:00
Georges-Antoine Assi
907ae7a79f Merge branch 'master' into feat/game-anniversary-widget 2026-09-09 10:23:08 -04:00
Georges-Antoine Assi
08f294d0fa Merge pull request #3571 from rommapp/claude/kind-goodall-0b77y7
feat: Per-platform custom library structure with non-destructive identity
2026-09-08 16:46:44 -04:00
Spinnich
47e89132f7 feat(anniversaries): return every match for the day
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>
2026-09-08 19:11:44 +00:00
Spinnich
38f5adffc6 fix(anniversaries): take the year from the day asked for, not the server's
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>
2026-09-08 17:58:46 +00:00
Spinnich
868a5c03e7 feat(home): add a game anniversary widget
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>
2026-09-08 17:31:27 +00:00
Spinnich
6a3d207ece perf(gallery): resample the identity keys after a scan fills them
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>
2026-09-08 11:06:41 +00:00
Spinnich
e60007d37c docs(gallery): correct the comments the materialized keys invalidated
`idx_roms_sibling_cover` no longer backs a self-join over `roms`, only the
`group_by_meta_id` dedup window, so the index comment named a reader that
does not exist and would mislead anyone weighing whether the index can be
narrowed.

The view's per-provider columns keep their names but a row now fills only
its own provider's, so "the view's shape is unchanged" read as a promise
about the values too.

`recommendations_handler` matches on a list that is wider than the sibling
list by `steam_id`; its comment pointed at the sibling list instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 10:39:32 +00:00
Georges-Antoine Assi
f105622513 fix: address code review on the library structure unique index and relocation
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>
2026-09-07 19:14:58 -04:00
Georges-Antoine Assi
9dcaf89890 fix: address PR review feedback on library structure and relocation
A grouping folder is no longer also a game. With `{gameDir}` and
`{category}/{gameFile}` declared together, the category folder was surfaced
as a multi-file game *and* descended into, listing its contents twice. A
folder any template descends into is now treated as a grouping level.

Relocation runs for every platform, not only those with a custom structure.
Dropping a platform's template moves every game back to the platform root,
which previously read as a library of new games and orphaned all the saves,
play history, favorites and collection membership. A library whose paths are
unchanged still costs one query and no hashing. This also removes the need
for a manual "apply relocation" toggle.

Physical games are excluded from relocation candidates: they have no file, so
they read as having disappeared from their path on every scan.

A near-miss on the terminal macro (`{gameFolder}` for `{gameDir}`) now names
the offending section instead of only reporting a missing terminal.

Documents two limits the QA pass asked about: a move that also compresses or
extracts the game changes its size and is not detected (the size pre-filter
runs before hashing), and how reverting to the default layout behaves.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:01:33 -04:00