`from_stored_criteria` answers None now, so the tests reading fields off it
need the same narrowing helper the collections tests use, and two splats
need annotating where the model's fields are heterogeneous.
These are mypy findings the local check missed: `.trunk/configs/mypy.ini`
sets `check_untyped_defs`, without which mypy skips the bodies of
unannotated test functions entirely, and Trunk passes changed files
explicitly, which bypasses that config's `exclude` of `tests`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
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
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 Copilot on the PR: query-shape coverage for
relationship and dunder order_by values, with and without a user,
asserting they resolve to the name sort without raising.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
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
After merging master, the dialect-aware ordering drops the leading
IS NULL term on non-PostgreSQL descending sorts and adds it to
nullable metadata keys; the shape tests now assert that form and pin
the MariaDB driver where the emulation branch is what they check.
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
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
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 endpoint answered with every match for the day, so response size
tracked the library rather than the request: the busiest real date on a
96k-rom library is 1,101 roms at roughly 8 KiB of SimpleRomSchema each,
and the 1 January early-return was the only thing holding that off
~23,000.
The ceiling goes on the id selection rather than the response, so it
bounds the hydration and the serialization too, which is where the weight
is. It rides the existing index-ordered range scan, so the plan does not
change and the engine stops early instead of walking the whole union.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The 24-item cap was measured against the largest library available and
does not earn its place: on a 96k-rom library the day-of-year index range
scan costs 3.7 ms whether it matches 114 rows or 22,914, so the cap saved
roughly 40 ms and 0.7 MB on a typical day while truncating every single
day of the year (median 132 matches/day, and 100% of days exceed 24).
Removing it also makes the widget's counter a real total rather than a
ceiling, which was the substance of the review comment about "24 / 24"
implying a complete list.
This makes the 1 January skip load-bearing for response size as well as
accuracy: it is the one day that would otherwise answer with 22,914 rows
(28% of all dated roms), where the busiest real day is 1,101.
Addresses the "Result cap hides anniversaries" review comment on #4396.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Clients send their own local month and day, so around the new year the
server's UTC date can name a different year. 31 December asked for on
1 January UTC bounded the search at the wrong year, letting a release
from the viewer's current year through as an anniversary of itself.
A timezone offset moves the calendar by at most a day, so 31 December /
1 January is the only pair that can disagree, and 1 January already
returns nothing.
Addresses the "Mixed clocks include new releases" review comment on #4396.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Shows games released on today's date in an earlier year, one at a time,
with arrows to page through the rest. Sits in the Home widget rail beside
Random pick and Library stats, with its own Settings toggle (default on)
and an entry in the drag-reorder list.
New endpoint GET /api/roms/anniversaries, ROMS_READ, whole-library,
returning up to 24 SimpleRomSchema oldest release first. Clients send
their own local month and day so "today" matches the calendar in front of
the user rather than the server's UTC clock.
The day-of-year match is a union of one-day ranges over
generated_first_release_date rather than MONTH()/DAY() on the value.
Ranges are sargable, so idx_roms_generated_first_release_date serves both
the match and the sort as one covering range scan: 195 rows examined and
~2 ms against 63,334 rows and ~70 ms for the function predicate on a
100k-row table. Emitting no SQL date function also means no dialect
branching and no migration.
1 January returns empty. Several providers park year-only metadata there
(ScreenScraper parses a bare year with %Y, CSDb publishes nothing else,
IGDB reports year precision as 1 January), so nothing in the stored data
tells a real 1 January release apart from an unknown day. Leap-day
releases roll onto 28 February in non-leap years.
Visibility follows /random: filter on hidden platforms and roms, then
re-check each hydrated row with perms.can_see_rom.
Closes#3440
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Migration 0126 samples `rom_identity_keys` right after its backfill, which
on a fresh install runs while the table is still empty. The first scan then
fills it through the triggers, and MariaDB keeps planning `sibling_roms`
against the empty sample: measured on 37k key rows, one gallery page's
sibling statement takes 891.7 ms in that state against 2.1 ms once resampled,
which is worse than the 550.7 ms the view it replaces cost.
InnoDB's auto-recalc does not cover it. It fires and updates the stored row
count, but the plan does not change until the table is reopened or analyzed:
90 s after a trigger-paced fill, `mysql.innodb_table_stats` was correct and
the plan was still the block-nested-loop one.
Addresses the "Fresh Installs Keep Stale Statistics" review comment on #4394.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`sibling_roms` was a view that self-joined `roms` on an OR of seven
equalities across seven columns. The compared values come from the joined
row, so no index can drive that OR: MariaDB answers it by block-nested-loop
scanning every ROM on the platform. Every gallery page paid that for its
version badges, and the gallery's "Versions" filter asked the same view for
an EXISTS over the whole library.
Migration 0126 moves the ids into `rom_identity_keys`, one narrow row per
ROM per provider it matched, and redefines `sibling_roms` as a self-join of
that table. Triggers on `roms` keep it in sync, guarded by `NEW.x <=> OLD.x`
so the writes that touch no identity id skip the resync; deletes ride the
foreign key's cascade. This is the move 0101 made for `virtual_collections`.
Matching is unchanged: the same seven providers, still scoped to a platform.
No application code changes and no API shape changes.
Measured on a clone of a real 96k-ROM, 123-platform library:
GET /api/roms?duplicate=true 977,571 ms -> 22,149 ms (45x)
PlayStation gallery (9,196) 1,039.0 ms -> 382.2 ms (2.7x)
Arcade gallery (7,719) 844.5 ms -> 296.2 ms (2.9x)
all-games gallery 3,023.9 ms -> 2,690.5 ms (1.1x)
The all-games page barely moves because its rows are drawn from 123 mostly
small platforms, so the per-platform scan was cheap per row. Its residual is
almost entirely the group_by_meta_id dedup window (2,535 ms of 2,676 ms
measured on the same clone), a separate problem.
The view deliberately has no DISTINCT: a pair matched by two providers emits
two rows, and DISTINCT would stop the view merging into the caller's query
at 11x the cost. Both readers already collapse duplicates.
The ANALYZE after the backfill is load-bearing. Without sampled statistics
the optimizer estimates thousands of rows per lookup and picks a worse join
order for the rest of the list query, leaving the gallery slower than before
this ran.
Fixes#4391
Related to #4382
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Conflict resolution notes:
- Locale rom.json: master sorted and reworked every file; took master's and
re-inserted `location` / `location-copied` in sorted position. Added them to
the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
(master), and the scan loop keeps master's early missing-sync plus its
restored-rom emit alongside this branch's relocation pass. The relocation
filter now applies only to the identify loop, so a relocated rom is no longer
re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
`purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
premise that same-named files in different folders are distinct games.
Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
all share one folder, so a duplicate title is still rejected.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The genre/franchise/company/publisher/developer/collection/age-rating/
player-count filters read from `roms_metadata`, but the join was added at the
end of `filter_roms`, after the "Group ROMs" block had already derived its
dedup window from the query. The window therefore filtered on a table it never
joined: the database cross-joined `roms` against `roms_metadata` (a view over
`roms`), which SQLAlchemy reports as a cartesian product.
Besides the cost, the window then ranked every ROM in the library rather than
the matching ones, so a game whose matching version was not the group's primary
one disappeared from the gallery entirely.
Fixes#4389
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
0123 appends steam_metadata to the generated facet chains, but every test
seeded its library through igdb_metadata, so nothing held the wiring in
place: a Steam-only game reaching roms_facets, and the builder indexing it,
were both untested. Both assertions fail when the blob is written to a
provider the chains do not list.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Files added to an already-scanned folder ROM could only be picked up by a
complete or hashes rescan, which rehash every known file. The new `files`
scan type scans new games like quick and re-lists the files of existing
folder ROMs, hashing only new or changed files and recomputing the
ROM-level hashes only when a top-level file changed. Per-rom update and
unmatched scans reuse the same incremental mode, and the filesystem watcher
enqueues it instead of quick.
Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a
current mtime to about 128 seconds), adds the CHEAT value missing from the
PostgreSQL category enum, maps `patches/` to the patch category and
excludes upload temp files from scans.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
Steam's genres, companies, developers, publishers, game modes, release
date and Metacritic score were stored by 0115 but read by nothing: the
generated columns behind roms_metadata, roms_facets and the
recommendations index never listed steam_metadata as a source. 0115
deferred that on purpose, since changing a STORED generated column
rebuilds the roms table, and asked for it to ride with a migration that
already does. 0118 and 0119 are that migration, so 0120 rebuilds the
seven affected columns with Steam appended at the lowest precedence.
Only rows carrying Steam metadata can change value, so the facet mirror
and virtual-collection membership are refreshed for those alone. Round
tripped on MariaDB 11 and PostgreSQL 16, asserting the view, facet and
membership rows at each step.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>