Commit Graph

139 Commits

Author SHA1 Message Date
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00
Sam Dornan
cbfc904a48 fix(ra): count RomM's own RA hash match as RetroAchievements verification (#4816)
* fix(ra): count RomM's own RA hash match as RetroAchievements verification

The RetroAchievements verification chip, the header Verified badge and the
library verified filter only read Hasheous' `ra_match` flag. RetroAchievements
hashes only part of some ROMs (NDS, PSP), so Hasheous never flags those from
their file hashes, and a ROM RomM matched to its RA game by RA hash still
showed a grey chip.

The RA handler now records `hash_match` in `ra_metadata` whenever the ROM's
RA hash is one RetroAchievements lists for the matched game, whichever route
found the game (hash lookup, Hasheous-supplied id, filename tag, update scan
or a manual edit). The frontend verification helper and the backend verified
filter count it alongside Hasheous' flag. Existing ROMs pick it up on their
next scan.

Fixes #4801

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* style: satisfy trunk isort and no-emdash-in-comment

Sort imports with the repo's .isort.cfg and replace the comment em-dashes
in MetadataTab.vue that trunk flags once the file is modified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): address code-review findings on the RA hash match

- A HASHES rescan whose RA lookup ran and found nothing clears
  `hash_match`, mirroring the Hasheous guard; a lookup that errored keeps it.
- A manual RA id change that can't be resolved no longer keeps the previous
  game's `hash_match`.
- `_search_rom` no longer caches a failed hash-list download ({}) as an
  empty index for the whole refresh window.
- Update the `verified` filter description and trim the romVerification
  header comment.

Step: pr-ready code-review (xhigh --fix)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): don't let a failed hash check block an RA ID lookup

`get_rom_by_id` now treats the hash-list check as secondary: on failure it
logs, keeps a match already recorded for the same game, and still returns
the game. A failed hash-list download raises "RetroAchievements
unavailable" instead of reading as "no match", so scans treat RA as
inconclusive and keep the stored flag.

Addresses the Copilot and Greptile review findings on ra_handler.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* refactor(ra): simplify the RA hash-match verification

- Cache the parsed RA hash index per platform, keyed by the cache file's
  mtime, so a scan parses it once instead of once per ROM.
- Check the hash only after `get_rom_by_id` has resolved the game.
- Give each frontend verification database its own `matches(rom)`, which
  drops the `ra_match` special case in the shared helper along with
  `matchesDatabase` and `VERIFICATION_KEYS`.

Step: pr-ready simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* style(v2): polish romVerification naming and comment

Rename the Hasheous matcher factory to `anyHasheousFlag` and trim the
VERIFICATION_DATABASES comment to two lines.

Step: pr-ready review-polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

* fix(ra): keep a recorded hash match only for the same RA hash

When the hash-list check fails, `get_rom_by_id` now keeps a stored
`hash_match` only if both the game and the ROM's RA hash are unchanged, so
a rehashed ROM isn't left verified by a hash nobody checked. The
romVerification tests build on the shared typed `SimpleRom` fixture
instead of casting a bare object.

Addresses the Greptile review findings on ra_handler.py and
romVerification.test.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LfQbq2ZUFK53NMXPNktdaM

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 15:33:55 -05:00
Sam Dornan
5b3d0bf544 feat(sync): record a per-device save baseline to prove what did not change (#4768)
compare_save_state decides a side changed from its timestamp, and
emulators rewrite a save on exit, so an untouched save looks new and a
server change elsewhere turns into a false conflict.

device_save_sync now records what each side held at the last sync
(last_sync_hash from the device, last_sync_server_hash from the server,
migration 0140). A baseline match proves that side unchanged; a mismatch
or NULL falls back to the timestamp logic, so this only removes
conflicts. It runs after the removed_at check in compare_save_state.

- Baselines are recorded only for versions the device provably holds:
  confirm_download pins to the served version, update_save records the
  client hash only when the file was uploaded, deduplicated uploads and
  pushed saves record against the surviving save, and push-pull no-ops
  record hashes only for identical content.
- Identical-content no-ops in negotiate and the watcher record a
  boundary without re-tracking untracked saves.
- The SSH push-pull and file-transfer watcher paths hash device saves
  through hash_save_file, matching compute_content_hash for zipped
  saves, and treat unreadable saves as unknown.

Squashes rommapp/romm#4768 onto master.



Claude-Session: https://claude.ai/code/session_01WAKUdfLb6fyduEqaFbf5A8

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 15:05:57 -05:00
Sam Dornan
9c1e6b2d86 refactor(backend): move engine-specific query SQL out of handlers into utils/sql_dialect.py (#4793) 2026-09-26 13:48:33 -04:00
Georges-Antoine Assi
f0d42102d0 fix(sync): code-review fixes for deleted-save tracking
Follow-up to #4789 from the code-review pass:
- PUT /api/saves/{id} records the replaced bytes of a never-hashed save
- rehash_save keeps updated_at, so a recompute is not read as a write
- unstamped legacy versions keep their removal time when another is lost
- prune_slot deletes its locked rows in one statement
- 0138 creates the slot index after the collation change

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 12:59:17 -04:00
Sam Dornan
d1ce4e3db2 fix(sync): make deleted-save tracking exact, complete, and effective on filled slots (#4789) 2026-09-26 12:33:54 -04:00
Sam Dornan
2c71226887 ci: run mypy in its own workflow instead of through Trunk (#4724) 2026-09-25 21:37:01 -04:00
Sam Dornan
63cd9eb1b8 fix(backend): replace the legacy Query API with Select and type the session decorators (#4730) 2026-09-25 21:19:02 -04:00
Sam Dornan
3a1f1f0e9c feat(sync): tell a device when the save it holds was deleted here (#4674)
* Tell a device when the save it holds was deleted here

Deleting a save took its row, its file and its device pairings, leaving nothing
that says it ever existed. A negotiation then read a client still holding the
save as a client with a save the server lacks, answered "upload", and the next
launch put the deleted save back. There was no way to say "this is gone": the
protocol's actions are upload, download, conflict and no_op.

So a slot emptied on purpose is now remembered. `deleted_saves` keeps one row
per (user, rom, slot) with what the slot held and when it was emptied, written
by the delete endpoint, which is the only place a deletion is the owner's
decision rather than housekeeping: autocleanup rotating a version out leaves
newer rows in the slot and is never recorded.

Negotiation reads it only when the slot has no row left, and answers the new
"delete" action when the client's copy is the one that went: the same content
hash, or a copy last written before the deletion. Anything written after it is
progress the server never held, so that still answers "upload" -- emptying a
slot is not a licence to delete a newer save.

The generated frontend models are hand-edited to match: this environment has
only CPython 3.14.0rc2, which the locked pydantic cannot import, so the backend
will not start for `npm run generate`. Both edits are mechanical (the new
literal in the union, the new count field), and `npm run typecheck` passes
against them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Decide a deletion by identity, and record it before the row goes

Three real findings from the review, and the layering rule.

The record was written after the save row and its file were gone, with two
transactions and a filesystem removal between them. Anything failing in that
window left a deletion nothing remembered, which is the resurrection this
change exists to prevent. It is written first now: a record for a save that is
somehow still there is never read, because a negotiation only consults it when
the slot has no row left.

The client's copy was matched on its own timestamp against the server's
deletion time. Those clocks are not comparable, and a device running slow
would have been told to delete progress it made after the deletion. The match
is now identity alone: the slot remembers every version it lost, capped at the
twenty most recent, and a client holding any of them is told to drop it.
Anything else is offered back, which costs a deletion that does not reach that
device rather than a save that is gone.

Recording replaced the row with a delete and an insert, which two deletions of
the same slot could race into a uniqueness error. It locks the row and merges
into it, with the house savepoint-and-catch for the case where there is no row
yet to lock.

The comparison itself moves to handler/sync/comparison.py beside
compare_save_state, where the endpoint delegates to it and the rule is tested
on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Trim the new comments to the repo's rule

One or two lines each, with the rationale in the commit messages and the PR
description where the rule puts it. The model's docstring is one sentence, and
the comparison keeps its Args and Returns.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Sort comparison imports

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Widen the window a deletion is remembered in

A slot's record keeps a bounded list of the versions it lost, and the trim
drops the oldest, which are exactly the ones a long-offline device is
likeliest to still hold. At twenty, a device that missed twenty
delete-and-refill cycles of one slot comes back with a digest that has
aged out and is answered `upload`, which puts a deleted save back.

Raised to a hundred, where the device would have had to miss a hundred
manual deletions of the same slot. The residual is deliberate and cannot
be designed away by a longer list alone: past the bound the server does
not know those bytes were deleted, and the answer degrades to `upload`,
which fails by not propagating a deletion rather than by destroying a
save. A test now names that case so the next reader meets it as a choice
rather than as an oversight.

Found by Greptile on #4674.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Trim the retention comments back to the rule

Both were over the two-line limit, and the constant's was a six-line
design essay of exactly the kind the last round of this review already
removed from this PR. The reasoning belongs in the commit that made the
change and in the pull request, where it is.

What stays is the part the code cannot say: the trim drops the oldest,
and past the bound a device is answered `upload` rather than `delete`.

Found by Greptile on #4674.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U

* Name the deletion record for assets, not only saves

Unreleased, so the table can take a name that states can share later
without another migration.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Apply code-review fixes to deletion records

Record a deletion in short separate transactions so concurrent first
deletions no longer deadlock on MariaDB, hash a save that never
recorded one, keep a re-deleted version from being trimmed, scope the
negotiation's read to emptied slots, and require total_delete.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Simplify deletion records

Drop the unread deleted_at column, record from _delete_save so every
caller of it is covered, skip a record no hash could ever match, let
comparison decide delete vs upload with its reason, count actions once,
and fold the near-duplicate tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Polish the deletion record's index comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-09-25 12:21:46 -05:00
Sam Dornan
7dd35aa139 fix(sync): give a sync session the life of one launch, and drop the dead play-session link (#4670) 2026-09-25 10:14:09 -04:00
Sam Dornan
abd061f59a perf(backend): read the gallery sorts out of an index (#4647)
* perf(backend): read the nullable gallery sorts out of an index

Sorting the gallery by release date, rating or HowLongToBeat time placed
unset roms last with `ORDER BY <column> IS NULL, <column>`. The leading
term is an expression, so MariaDB and MySQL could not read the order out
of `idx_roms_<column>` and filesorted instead. PostgreSQL had the mirror
problem descending: `DESC NULLS LAST` does not match the index's own
order, so it fell back to a sequential scan.

Neither engine paid this once. v2 window fetches send no sidecars, so
each scroll window is its own `ORDER BY ... LIMIT 72 OFFSET n` over the
full filtered set, and `roms` carries a JSON metadata blob per provider
on every row.

Each column now carries a STORED `_unset` flag with an
`idx_roms_<column>_sort` pair the ascending sort leads with, and
PostgreSQL gets an `idx_roms_<column>_desc` for the descending one. Row
order is unchanged in both directions.

Measured on PostgreSQL 16 over 120k roms, first page:

  ascending    30.6 ms / 8109 buffers -> 0.074 ms / 13 buffers
  descending   33.5 ms / 8091 buffers -> 0.112 ms / 14 buffers

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* fix(backend): rebuild a sort index MariaDB narrowed instead of dropped

Testing the previous commit against MariaDB rather than PostgreSQL alone
turned up a real bug in it.

The two engines leave a dropped generated column in different states:
PostgreSQL drops every index that reads it, while MariaDB and MySQL keep
a composite one over the columns that survive. `_restore_generated_indexes`
only created indexes missing by name, so on MariaDB the rebuild path in
`ensure_roms_columns` (a chain predating 0123) would leave
`idx_roms_<column>_sort` narrowed to the unset flag alone and the
ascending gallery sort walking half an index.

It now reconciles on the columns an index spans, not just its name, and
`_drop_index_sql` gives the two dialects their own DROP INDEX spelling.

Also corrects the flag columns' comments: MariaDB accepts no NOT NULL on
a generated column in either position, so they are nullable in the DDL on
both engines. `IS NULL` never evaluates to NULL, so no row carries one.

Verified on MariaDB 10.11 over 120k roms. The ascending page went from
`rows=116503, Using index; Using filesort` to `rows=72, Using index`,
134 ms to 6 ms, with the same plan once the rom_user join is added.
Migration, schema and flag values also checked under utf8mb3_unicode_ci,
the collation these expressions are most fragile under.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* style(backend): give the sort-flag rationale one home

Greptile flagged the comment blocks in this PR against CLAUDE.md's
comment discipline. The length was a symptom: the same explanation of
why MariaDB cannot index the NULLS LAST emulation appeared in four
places. It now lives once, beside `SORTABLE_NULLABLE_ROM_COLUMNS`, and
the other sites say only what is local to them.

No behaviour change; the migration docstrings are left as they are,
matching the narrative style every recent revision uses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* fix(backend): drop the sort indexes with the rest of the catalog

Copilot pointed out that `ensure_roms_columns` installs the `_unset`
columns long before 0129 runs, so a chain that stops short and then
downgrades leaves them behind. Checking that turned up a real leak next
to it: 0108's downgrade, which the module documents as removing whatever
of the catalog such a chain still carries, was leaving two indexes.

A descending sort index reads a value column this module inherited
rather than added, so `drop_roms_columns` re-adds that column and the
index over it survives. `_drop_sort_indexes` now takes them explicitly.
PostgreSQL only, since no other engine has those indexes.

The flag columns themselves are not a leak: the catalog front-loads every
column it owns, so at 0127 the table already carries 0123's
`generated_keywords`, `generated_themes` and `generated_rating_count`
too. Verified on both engines that a 0128 to 0127 downgrade leaves the
table writable with the flags still computing, and that re-upgrading
restores the pair, narrowed index included.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* style(backend): tighten the teardown docstrings and the test annotation

Two more from Greptile, both worth taking even though the reasoning
behind each was off.

`_drop_sort_indexes` and its test now carry a summary plus one line,
matching `drop_roms_columns` right above them, and the parametrized
metadata argument is typed instead of a bare `dict`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* perf(backend): index the remaining gallery sorts (#4644)

* perf(backend): span the gallery sort indexes through the id tiebreak

The gallery appends `id` to every ORDER BY, but `idx_roms_<column>_sort`
stopped at the value and `idx_roms_<column>_desc` at the value alone. On
PostgreSQL that leaves every tie to be sorted, and unset metadata is a single
tie covering the whole bucket: a scroll window inside it fell back to a Seq
Scan and an external merge sort. Both indexes now carry `id` in the sort's own
direction, which InnoDB was already appending for MariaDB and MySQL.

Measured on 120k roms, a window at offset 100000 (inside the unset bucket),
all three columns, both directions:

  PostgreSQL ascending   119 ms, external merge sort  ->  15 ms, index only
  PostgreSQL descending   92 ms, incremental sort     ->  13 ms, index only
  MariaDB, both          already index-only; unchanged

No sort node remains in any of the twelve plans. Also trims the docstrings and
comments this change touches to the repo's one-or-two-line rule.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* test(backend): pin the reflected order of the descending sort indexes

The existing assertion read column names only, which a default ascending index
satisfies just as well, and `AUTOGENERATE_EXEMPT_INDEX_NAMES` keeps the drift
check away from these. Asserts the reflected `column_sorting` instead, and its
absence on the ascending pair.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* fix(backend): declare the unset flags nullable, as their DDL is

`Mapped[bool]` inferred NOT NULL while both engines create the column nullable,
MariaDB because it takes no NOT NULL on a generated column. The four generated
columns beside them already match their DDL. The annotation stays `bool`, since
`IS NULL` never yields NULL.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8

* fix(backend): renumber the gallery sort revisions after 0132

master gained its own 0129-0132 while this branch was open, and both
chains started from 0128_hltb_main_story_column, leaving alembic with
two heads (`upgrade head` fails with MultipleHeads).

0129_indexed_gallery_sorts -> 0133, now revising 0132_audit_events;
0130_gallery_sort_indexes -> 0134. No content change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC

* fix(backend): re-chain the renamed gallery sort revisions onto 0132

The previous commit renamed the files but left their revision IDs and
parent as they were. 0133 now revises 0132_audit_events, and both IDs
match their filenames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 14:56:43 -05:00
zurdi
c2c2dd6380 refactor(audit): address Greptile's second review
- The audit read endpoint keeps the access decision but hands the
  category filter to the DB handler, which expands it to actions.
- Trim the log viewer's header comment to two lines and drop its
  em-dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:03:45 +02:00
zurdi
6298e7bf8c fix(audit): apply the pr-ready code review
- Hide events on roms of a hidden platform from non-admins.
- Pin later pages to the highest matching id the API returns, not the
  first row's: rows are ordered by when they happened, so a play synced
  late has a higher id than newer events and was dropped.
- Cap recorded failed sign-ins per address, dedupe reset requests and
  record them in the background with the email, and hash claim keys.
- Keep another user's private collection by id only in bulk downloads.
- Check a Range start without int(), which raises past 4300 digits.
- Clear the list when a reload fails, load more only once it's shown,
  report a cover change only when the user made one, label only rom and
  platform unhides, accept an actor kind the API doesn't know.
- One client IP helper, date-fns for today and yesterday, one time
  formatter for the list, no em-dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:30:47 +02:00
zurdi
0afbe2ef57 feat(audit): add the audit_events table, recorder and read API
A persistent record of what users, or RomM itself, did. Admins read
everyone's events through GET /api/audit-events; anyone else gets only
their own. Events older than AUDIT_LOG_RETENTION_DAYS (90 by default,
0 keeps them) are pruned nightly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:05:59 +02:00
Sam Dornan
17830e5b7d test: fix the type errors mypy can now see in the test suite (#4708) 2026-09-22 16:01:21 -04:00
Sam Dornan
552cf7c213 fix(config): show folder mappings whose folder name is not lowercase (#4676) 2026-09-21 19:52:40 -04: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
108381803e Narrow the stored-criteria Optional in tests
`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
2026-09-13 06:49:35 +00:00
Sam Dornan
1c20e77e41 Reject unusable smart collection criteria instead of dropping them
The real /code-review and /simplify passes over this PR, which an earlier
run substituted hand review for.

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 06:36:54 +00:00
Sam Dornan
eac8f22d5e Sort imports with the repo's isort config
`known_first_party` lives in `.trunk/configs/.isort.cfg`, so `handler` and
`models` group after the third-party block, not with it.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 04:38:05 +00:00
Sam Dornan
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
4c3d052cbd test(roms): pin the name-sort fallback for non-column order_by values
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
2026-09-11 21:13:50 +02: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
d02c77805f test(roms): align shape assertions with merged NULLS LAST semantics
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
2026-09-11 20:52:04 +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
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