`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>
* 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>
* fix(collections): project identifier columns instead of loading whole collections
`GET /api/collections/identifiers` reads only ids, owners and visibility, but
the accessor it called eagerly loaded every rom of every collection
(`@with_roms`) and built a full `User` per row (`Collection.user` is
`lazy="joined"`). A column projection drops both, while `load_only` cannot
cancel either one.
Measured on a seeded database of 100 collections and 200 roms (20,000
memberships): rows read 20,100 to 100, statements 2 to 1, SQL text 1,172 to
113 bytes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(collections): keep the new identifier assertions to one-line comments
The repo caps comments at one line when the rationale is not recoverable
from the code, and test docstrings at one sentence, so the m2m reasoning
belongs in the PR body rather than repeated at the call sites.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* 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>
* 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>
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>
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>
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
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
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
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
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>
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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#4449Fixes#4450
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
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>
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
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
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>
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>
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
`sibling_roms` matched on seven providers, the gallery's dedup window on
those plus `flashpoint_id`, and the recommendation feed on those plus
`steam_id`. Three lists, so a pair sharing only a Steam or Flashpoint id
was the same game to one reader and two games to another.
They are one list now. `rom_identity_keys` carries all nine providers,
which makes `provider_id` a varchar since `flashpoint_id` is a string,
and the dedup window's cover index grows by `steam_id` so the window
keeps its indexed plan.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A rom written between the backfill and the trigger creation got no key
rows, and nothing short of a later edit to one of its identity columns
would have noticed. Both writes skip a row that is already there, so the
two steps can overlap.
Also correct the revision the docstrings point at and the claim that
IDENTITY_ID_FIELDS contains the group_by_meta_id window's columns.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Master keyed the unique roms index on the full path digest, so the
resolution keeps its two indexes and this branch's comment on
idx_roms_sibling_cover, which no longer backs the sibling_roms view.
Both sides added a 0126 revision off 0125; rom_identity_keys moves to
0127 behind master's unique_rom_full_path.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comment and docstring pass over the `released_days` change: cut the copies of
rationale that already live next to the thing they describe, and drop the
sentences defending obvious choices.
`RELEASED_DAY_REGEX` now carries the calendar ranges, so a match is a valid day
and `parse_released_days` needs no sentinel pair and no second range check.
`release_day_ranges` stops re-sorting what `epoch_ms_in_ranges` already sorts.
`anniversaryQuery`'s return type is a named export, so the widget imports it
instead of unwrapping a `ReturnType`, and the widget's two reset paths share
`showEmptyDay`.
`loadMore` is `loadNextPage`, since it appends one page rather than the rest.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`GET /api/roms` already does what `/roms/anniversaries` hand-rolled: it selects
ordered ids over the filtered set, takes the total from that index, hydrates
only the page asked for, and re-projects the rows into id order. So the widget
now asks it for a page rather than owning an endpoint that pulls the whole day.
`released_days` on the list endpoint takes days as "M-D", matching any year, and
`released_before_year` bounds them. Both go through `filter_roms`, so the same
day-of-year match is available to the gallery filters and to smart-collection
criteria, and the range union stays where it was: still sargable, still a
covering index range scan on `idx_roms_generated_first_release_date`, no SQL
date function and no dialect branching. Verified on a 73k-rom database that the
plan through the list endpoint's join is unchanged: `type=range`,
`Using where; Using index`, no filesort.
The filter means exactly what it says, so the calendar policy moved to the
client, where the clock it depends on already lived. `anniversaryQuery` picks
the days and the year bound off the viewer's own date: it skips 1 January,
where several providers park year-only metadata, rolls 29 February onto 28
February in a non-leap year, and bounds the years at the viewer's own. The
server no longer has to second-guess a timezone offset, so the 31 December
asked for on 1 January UTC correction is gone rather than fixed.
Consequences for the widget: the counter is the day's real total instead of one
clipped at a 500-row ceiling that no longer exists, and a card costs one page
of 24 rather than up to 4 MB up front. Paging backwards stays in memory;
only moving past the loaded pages fetches, with the spinner on the arrow so
focus is never yanked mid-page. A failed page keeps the card on screen.
`released_days` is added to the list endpoint's unscoped-cache gate: the
sidecar keys encode no filters, so a narrowed page must not be served under the
shared "all" key. Covered by a test that primes the unscoped key first.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The 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>
The endpoint answered with every match for the day, so response size
tracked the library rather than the request: the busiest real date on a
96k-rom library is 1,101 roms at roughly 8 KiB of SimpleRomSchema each,
and the 1 January early-return was the only thing holding that off
~23,000.
The ceiling goes on the id selection rather than the response, so it
bounds the hydration and the serialization too, which is where the weight
is. It rides the existing index-ordered range scan, so the plan does not
change and the engine stops early instead of walking the whole union.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The 24-item cap was measured against the largest library available and
does not earn its place: on a 96k-rom library the day-of-year index range
scan costs 3.7 ms whether it matches 114 rows or 22,914, so the cap saved
roughly 40 ms and 0.7 MB on a typical day while truncating every single
day of the year (median 132 matches/day, and 100% of days exceed 24).
Removing it also makes the widget's counter a real total rather than a
ceiling, which was the substance of the review comment about "24 / 24"
implying a complete list.
This makes the 1 January skip load-bearing for response size as well as
accuracy: it is the one day that would otherwise answer with 22,914 rows
(28% of all dated roms), where the busiest real day is 1,101.
Addresses the "Result cap hides anniversaries" review comment on #4396.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>