Commit Graph

416 Commits

Author SHA1 Message Date
Sam Dornan
c2ee769df7 fix(roms): load the parent rom alongside a rom file so the schema validates (#4593)
`GET /api/roms/{id}/files` 500'd on its success path: `RomFileSchema` reads
`is_top_level`, which needs `file.rom`, and `get_rom_file_by_id` only loaded
`track_meta` and `doc_meta`. Validation happens after `begin_session` closes,
so the lazy load raised `DetachedInstanceError`. The parent rom now comes
along in the same load, narrowed to the columns `Rom.full_path` needs.

`last_modified` is nullable in the column but was required in the schema, so
a row added outside a scan validated to nothing. It is now nullable to match,
and the regenerated frontend type follows.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:20:16 -05:00
Sam Dornan
bba15f95f4 perf(backend): resolve roms without the related load in the file and props routes (#4590)
* perf(backend): resolve roms without the related load in the file and props routes

Eleven routes opened with `get_rom(id)` to reach two scalars: `id` for the
404 and `id` plus `platform_id` for `assert_rom_visible`. `get_rom` runs the
whole `with_details` eager load, so each request paid for the platform,
files, metadata, saves, states, screenshots, rom_users, siblings,
collections and notes of the rom. The bulk delete was worse: it ran inside a
per-id loop, so an N-id delete ran the graph N times.

Three narrow projections replace it, alongside the `get_rom_visibility` that
#4587 added for the rom-note routes:

  `get_rom_visibility`        id, platform_id
  `get_rom_visibility_label`  the above plus the name pair the file-delete
                              log lines print
  `get_rom_deletion_target`   the above plus fs_path and the joined platform
                              label the bulk delete logs when a rom's file is
                              already missing from disk

`assert_rom_visible` accepts either narrow row as well as a full `Rom`, so
the check itself is unchanged for every other caller.

Statement counts per request, captured with the `executed_statements`
fixture in `tests/endpoints/roms/test_visibility_loads.py`:

  PUT  /api/roms/{id}/props                       19 ->  9
  GET  /api/roms/{id}/soundtracks/metadata        15 ->  5
  GET  /api/roms/{rom_id}/files/{file_id}/progress 20 ->  8
  DELETE manuals / walkthroughs / screenshots /
         soundtracks files                         20 ->  8 each
  DELETE /api/roms/{rom_id}/files/{file_id}        20 ->  8
  GET  /api/roms/{id}/files (hidden 404)           25 -> 13
  GET  /api/roms/{id}/files/content/{name}         25 -> 13
  POST /api/roms/delete, 1 id                      16 ->  6
  POST /api/roms/delete, 5 ids                     64 -> 14

The marginal cost of each extra id in a bulk delete falls from 12 statements
to 2.

The upload handlers on the same routers are left alone: `receive_rom_file`
hands the rom to `prepare_upload_destination`, so they need the full entity.
`Rom.fs_resources_path` moves its format string into a module-level function
so `RomDeletionTarget` can compute the same value.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(backend): trim the change rationale out of the new docstrings

Greptile flagged the module docstring in the new test file, `_rom_lookup` and
`RomDeletionTarget` for carrying the reasoning behind the change rather than
describing what the code does. The rationale lives in the commit message and
the PR body, so the docstrings keep only the one sentence a reader needs.

The `assert_rom_visible` docstring loses the paragraph added alongside the
widened type union, which restated what the signature already shows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(roms): share one rom factory in the visibility-load guard

Step 3 of the pr-ready gauntlet (simplify). The bulk-delete test built its
three roms from an inline `Rom(...)` literal; `test_random.py` already keeps a
module-local `_add_rom(platform, name)` for exactly this, so the guard grows
the same helper instead of a second copy of the field list.

`_flat` had one caller, so it folds into `_rom_lookup`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:18:22 -05:00
Sam Dornan
d120602342 perf(backend): check rom-note visibility without the related load (#4587)
* perf(backend): check rom-note visibility without the related load

The five `/api/roms/{id}/notes*` routes each opened with `get_rom(id)` to
reach two scalars: `id` for the 404 and `id` plus `platform_id` for
`assert_rom_visible`. `get_rom` runs the whole `with_details` eager load, so
every note read or write paid for the platform, files, metadata, saves,
states, screenshots, rom_users, siblings, collections and notes of the rom,
about 12 statements.

`DBRomsHandler.get_rom_visibility` selects those two columns and nothing
else, and `assert_rom_visible` now takes the `RomVisibility` row it returns
as well as a full `Rom`, so no other caller of the check changes.

Measured on a 3,000-rom library with 300 notes on the target rom, one admin
request:

  GET  /api/roms/{id}/notes/identifiers  17 statements / 30,059 bytes -> 5 / 8,066
  POST /api/roms/{id}/notes              17 statements / 23,209 bytes -> 5 / 1,216

The server-side `Questions` delta per request falls from 33 to 21.

The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(roms): match the rom lookup across dialects

The notes-load guard pinned the exact SQL text of the visibility lookup,
including MariaDB's `?` bind placeholder. psycopg renders the same query
as `%(id_1)s::INTEGER`, so the assertion could never match on the
PostgreSQL leg of the CI matrix and all three tests would have failed
there. Compare a dialect-independent prefix instead.

Step 2 of the pr-ready gauntlet: correctness fix plus the comment and
docstring trims it flagged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test: drop the second copy of the statement-capture fixture

`test_released_days.py` carried its own `captured_sql`, the same
before_cursor_execute listener the notes-load guard now shares as
`executed_statements` from tests/conftest.py. Point that file at the
shared fixture and drop the now-unused imports.

Step 3 of the pr-ready gauntlet: reuse and simplification fixes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test: name the notes auth helper as the other endpoint tests do

Seven endpoint test modules already define `_auth` for the bearer header;
this file introduced a third name for the same one-liner.

Step 4 of the pr-ready gauntlet: review-polish consistency pass, after
trunk fmt and the affected-suite run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 11:30:33 -05:00
Sam Dornan
fd9a33bc35 fix(backend): return identifiers without building an ORM row per id (#4586)
* fix(backend): project the identifier endpoints onto the id column

The `/identifiers` routes for saves, states, firmware, platforms, smart
collections and rom notes each asked their handler for entities with
`only_fields=[Model.id]`. `load_only` narrows the selected columns but does
not cancel an eager relationship, so a `lazy="joined"` join still fired and a
full entity was still built for every row. The platforms route was the worst
of the six: `with_firmware` eager-loads every firmware row and its platform,
and `load_only` does not cancel that either.

Each handler grows a small query builder shared by its existing accessor and a
new `*_ids` accessor that projects onto the id column with
`with_only_columns`, which drops the entity and with it the eager joins. The
firmware accessor already applied `noload`, so its SQL is unchanged; it moves
to the projection only to stop building rows.

`/api/users/identifiers` and the two `/collections` callers that use more than
an id are left alone, because nothing eager fires for them.

The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Update backend/tests/endpoints/test_identifier_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* style(backend): drop the leading blank line black rejects

Removing the module docstring in the GitHub edit left an empty first line,
which is the only thing black wanted to change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(backend): drive the note-identifier test through the endpoint

Greptile flagged the handler-level test for bypassing the route's auth,
404, and visibility checks. It now issues the request the frontend would
and asserts the id-only projection holds among the route's own reads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(backend): fold the duplicate SQL-capture fixtures into the shared one

Step 3 of the PR-ready gauntlet (simplify). The shared
`executed_statements` fixture gains the two roms test files that still
declared byte-identical local copies, and the id-only assertions share one
statement parser instead of two.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(backend): tighten the get_platform_ids docstring to one line

Step 4 of the PR-ready gauntlet (review-polish).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-09-17 11:13:07 -05:00
Sam Dornan
24bc9b3da9 fix(roms): answer the id endpoints without building every Rom (#4584) 2026-09-17 09:37:38 -05: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
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
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
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
Georges-Antoine Assi
4219f56f10 Merge branch 'master' into claude/kind-goodall-0b77y7
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>
2026-09-07 16:24:59 -04:00
Georges-Antoine Assi
eef3e55d29 fix(gallery): join roms_metadata before the grouped dedup window
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>
2026-09-07 16:22:18 -04:00
Georges-Antoine Assi
e78a4aa1b9 chore(recommendations): cut the comments back to what the code cannot say
The engine carried its tuning history in its comments: measurement logs for
PIVOT_B, the weight a facet held before the company split, the shape of the
cold-start feed before the Bayesian average. None of that describes what the
code does now, and it belongs in the history rather than beside the values.

Also folds serving's ROM loader into feed's, which differed only by the
visibility filter applied afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 14:35:15 -04:00