* feat(emulatorjs): expose download cache enable setting
* pr-ready: code-review
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: simplify
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: review-polish
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(config): move cache_limit under emulatorjs.cache and read config.yml strictly
emulatorjs.cache.limit replaces emulatorjs.cache_limit, which is still read
with a deprecation warning and is rewritten to the new key on the next save.
Every config.yml read now goes through one reader that exits with code 3 when
a parent block is not a dictionary (e.g. `netplay: true`), where get_nested
silently fell back to the default.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(emulatorjs): clear every EmulatorJS cache and keep nightly's cache size
The clear-cache dialog now also deletes EmulatorJS-bios (4.2.3) and
EmulatorJS-Cache (nightly), which kept serving downloaded files.
Nightly turns EJS_CacheLimit, a per-file byte cap in 4.2.3, into its total
cache size in MB, so a limit under 1 MiB gave a 0 MB cache. Passing
cacheMaxSizeMB explicitly keeps nightly at its own 4096 MB default.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(utils): drop get_nested
The config loader reads config.yml through its own strict reader now, so
get_nested has no callers left.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(sync): sync RetroArch Cloud Sync saves through save slots
RetroArch saves were unslotted and overwritten in place, so they never
reached the slot-based sync the native clients use, and a bad upload
replaced the only copy.
A save path now serves the newest slotted version for its ROM, core and
extension, from any slot, under RetroArch's own file name. An upload adds
a version to that slot (or autosave), skips unchanged bytes, and prunes to
MAX_SAVES_PER_SLOT. A delete removes every save the path covers, so none
resurfaces on the next sync. Unslotted saves keep serving until the first
slotted upload; PSP bundles and states are unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): lock RetroArch save uploads and prune per core and extension
Addresses Greptile's review on #5170:
- Move the RetroArch save upload into sync_handler.store_save_version,
leaving the endpoint to validate and map the result to a status.
- Hold a Redis lock per (user, rom, core, extension) across the lookup,
write, scan and row update, so concurrent same-second uploads never file
two rows over one tagged file. A lock timeout answers 503.
- Prune only the uploaded path's core and extension in the slot, so
another core's or a .rtc's current save is never dropped.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): pr-ready code-review fixes for RetroArch save slots
- Scope an extensionless prune to dotless file names, since every name
ends in an empty extension.
- Treat only NULL slots as unslotted in the manifest, matching the query
it replaced and the PSP bundle lookup.
- Share one helper for the slot versions a RetroArch path covers.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(sync): pr-ready simplify pass for RetroArch save slots
- Scope a slot prune by save ids, so the versions a RetroArch path covers
are decided once in Python instead of again in SQL.
- One newest-per-key helper for states and save versions, and
resolve_save_by_slot reuses it.
- A canonical_save_file_name helper next to the state one.
- The upload builds its tagged name once, checks its length in the
handler, and finds a same-second version in the list it already loaded.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(sync): pr-ready review-polish pass
Drop a comment the canonical_save_file_name helper now says.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): map RetroArch saves onto autosave lineages with unique version names
- Only RetroArch's .srm goes through slots, as the autosave versions of
its ROM and core. Companion files such as .rtc stay single unslotted
saves, so a slot never offers a clock file as the save.
- RetroArch reads, writes and deletes in autosave only, leaving named
slots alone.
- Every slot prune, web uploads included, is scoped to the uploaded save's
lineage (emulator and extension), so one core's uploads never drop
another's only save.
- The manifest lists the newest version under the client's spelling of
the game when it still names the ROM.
- reserve_version_name moves a taken tag on a second and claims it in
Redis, so same-second, concurrent or repeated-hour uploads from either
endpoint never share a file. The RetroArch lock and its 503 go.
- The manifest reads only the newest version per lineage, through one
window query.
- An upload is hashed before it is written, so an unchanged re-send
writes nothing.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(sync): seed the client-spelled save instead of uploading it
Uploading TEST_ROM.srm only resolves to the test_rom ROM under MariaDB's
case-insensitive collation, so the test 409'd on PostgreSQL. Seeding the
version directly still checks that the manifest keeps the client's
spelling of the game.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): resolve RetroArch saves to ROMs case-insensitively on PostgreSQL
Cloud Sync matches a save's game name to a ROM's fs_name_no_ext. MariaDB's
collation ignores case, but PostgreSQL compared exactly, so TEST_ROM.srm
never reached the test_rom ROM. PostgreSQL now compares lowercased names,
served by a new expression index (0150), and the endpoint test uploads the
differently-cased name again.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): address Greptile review on RetroArch save slots
- add_save derives the prune lineage from the tagged name it stores, so a
dotted upload such as game.rev.srm is counted against its own versions.
- Deleting a RetroArch .srm path also removes unslotted saves in that
lineage spelled in another case, which the manifest hid behind the
autosave head and PostgreSQL's exact match left behind.
- reserve_version_name looks up existing versions off the event loop.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(config): read config.yml values with a plain dict walk
pydash.get parses the path and probes every container type on each call, and the scan reads config values per rom. A dotted-path lookup over the parsed YAML dicts returns the same values.
* fix(config): address Greptile review
Drop the _config_get docstring, which restated the four-line dict walk below it (AGENTS.md comment discipline).
* refactor(config): move nested config lookup to utils.database as get_nested
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Search on search_titles and drop generated_search_aliases
The gallery filter matched provider aliases through a generated column
built from the JSON text, so escaped characters (MariaDB's \uXXXX
storage, tabs, quotes) were out of its reach, and ranking already reads
the folded titles in `search_titles`. Point the MariaDB FULLTEXT index
and the PostgreSQL trigram index at `search_titles` and drop the
generated column. Migration 0147, not yet released, makes the swap; its
downgrade rebuilds 0146's column and index from a frozen copy of their
SQL.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* Rebuild roms after the search titles backfill on MariaDB
Filling `search_titles` grows every row in place, which leaves InnoDB's
pages split and slowed the FULLTEXT search by 10 to 25 ms on 40,000
ROMs. One table rebuild after a backfill that filled rows restores it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* pr-ready code review: describe the alias search test case as it stands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* pr-ready simplify: read the legacy column name off the 0147 migration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* pr-ready review-polish: describe the rebuild as the code does it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* Freeze 0147's provider list and always rebuild roms on MariaDB
- The backfill and the downgrade's copy of 0146's column read a frozen
provider list instead of `ALTERNATIVE_NAME_SOURCES`, so a later provider
can't change what this revision selects or rebuilds.
- The table rebuild runs on every MariaDB/MySQL upgrade: a run that stopped
after the fill but before the rebuild left nothing to fill on retry.
- Two comments describe why, not what the migration replaces.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* Fold 0146 and 0147 into one search titles revision
Neither revision has shipped, so `0146_roms_search_titles` takes the
roms table from 0145 straight to `search_titles` and its search index,
and `generated_search_aliases` never exists. The search indexes are
dropped first, so the column is added and filled with no index to
maintain, and the index is built once over the filled rows.
Databases on a nightly that ran either old revision need resetting to
0145 before upgrading.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* Keep the search titles migration under 0146's revision ID
The folded revision now rewrites 0146_roms_search_aliases in place
rather than adding a new ID. A nightly database that already ran the
old 0146 or 0147 still needs resetting to 0145 before upgrading.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
* Say why 0146 adds search_titles ahead of ensure_roms_columns
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Search the gallery by providers' alternative titles
A search for "FF9" or "Final Fantasy 9" did not find "Final Fantasy IX":
the gallery search only matched roms.name and roms.fs_name, while the
alternative titles IGDB, MobyGames and ScreenScraper report lived in the
raw metadata blobs where no index reaches.
Add generated_search_aliases, a STORED generated column the engine fills
from those blobs, so every write path (scans, metadata refreshes, the
bulk update_rom, raw metadata edits) keeps it current with no backfill.
Migration 0145 rebuilds the MariaDB/MySQL FULLTEXT index over
(name, fs_name, aliases) and adds a pg_trgm GIN index on PostgreSQL, and
the search matches the column on both paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
* Compare the alias JSON type under the table's collation
On a utf8mb3_unicode_ci table, JSON_TYPE's result and the 'ARRAY'
literal carry different collations, so creating the generated column
failed with an illegal mix. CAST re-derives it, as _maria_text does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
* pr-ready step 2 (code-review): defer the alias column, share search columns
Loading a ROM no longer fetches generated_search_aliases, which only the
gallery search reads. The FULLTEXT match and the ILIKE fallback both take
their columns from one ROM_SEARCH_COLUMNS tuple.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
* pr-ready step 3 (simplify): register the search indexes, share the CAST
Both search indexes join the generated-column index registry, so any
later rebuild of the alias column puts them back instead of leaving
MariaDB's FULLTEXT index narrowed (and every MATCH failing) or the
PostgreSQL trgm index gone. 0145 shrinks to ensure_roms_columns plus
retiring 0084's index, and its downgrade guards DROP COLUMN with
has_column, since MySQL has no DROP COLUMN IF EXISTS.
_maria_char carries the collation CAST that _maria_text and the alias
expression share, the alias expression extracts each array twice
instead of three times, and the dialect test runs the handler's own
_fulltext_match.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
* Store the search aliases as plain titles
The alias column held each provider's array as JSON text, so a short
ILIKE search for '"', ',' or '[' matched every ROM with any alias. Both
engines print an array as ["a", "b"] however it was stored, so the
expression strips the brackets and quotes and keeps the titles
separated by spaces, which search terms can never match on their own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
* Shorten the alias-search docstrings to one sentence
The migration and test-module docstrings explained the design in
several paragraphs; AGENTS.md asks for one sentence. The design notes
live in the PR description.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A62FTdVyav4wK5Nkj55MGy
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
* 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>
* 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>
Trigger names are schema-wide, so the fixed probe name could name an
operator's own trigger, and DROP TRIGGER IF EXISTS would really remove it.
A fresh uuid per call makes the statement a guaranteed no-op, so the only
error it can raise is the refusal it is looking for.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The gate tested command names alembic never passes: it hands its environment
the per-command `fn` name, so `do_stamp` and `display_version` are what reach
it. Pin that with a canary over the closure the gate matches.
Probe before reading the applied heads, so only a server that refuses pays for
the lookup and the other dialects pay nothing, and fold the tests into the
module they mirror.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Verified against MariaDB 10.11, 11.3 and 11.8 with binary logging on: BINLOG
ADMIN does not lift the denial, only SUPER or the global flag does, and MySQL
8.4 never denies at all. The message said otherwise.
The probe also ran for every command that loads this env, so `current` and
`stamp` failed over a privilege they never need, while a downgrade at head
skipped the probe and could still half-drop a schema. Gate it on the commands
that execute revisions instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
MySQL and MariaDB reject every trigger statement, DROP TRIGGER IF EXISTS
included, while binary logging is on and the database user holds neither
SUPER nor BINLOG ADMIN. Ten revisions install triggers, so any of them
could abort startup with a raw traceback and leave a half-migrated schema
behind.
Probe the privilege once, before the first pending revision runs, and
fail with the two server-side fixes spelled out.
Fixes#3932
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Give the "which columns does this table already have" set a home as
`column_names`, and define `has_column` over it: 0098, 0112 and 0123 each
spelled it inline, and 0112 paid one full reflection of `roms` per candidate
column.
Use the builtin idempotency flags wherever they reach. 0121 was the last
revision guarding a column and an index by hand, and 0122 had two code paths
emitting the same statements; both now match 0111/0126/0128.
Skip 0126's digest backfill once the column is NOT NULL, so a replay no longer
full-scans `roms` to match zero rows.
Drop the test helpers that re-derived what `_schema_of` already returns, and
collapse the four-way `has_column` parametrize, two cases of which were really
schema assertions about 0112 and 0121.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
MySQL and MariaDB auto-commit each DDL statement, so a revision that dies
partway keeps what it created while alembic_version stays behind. Every
start after that replays it and dies on a duplicate object, hiding whatever
actually stopped the upgrade and leaving the instance on a half-migrated
schema.
Eleven revisions create something ahead of a step that can fail. Most take
the guard alembic already offers; three need more:
- 0122 declares its indexes inline so InnoDB adopts one for the foreign key,
and alembic issues those as their own statements, so `if_not_exists` on
the table would not cover them. It reflects the table instead and fills in
whichever index is missing.
- 0123 rebuilds its generated columns in one ALTER TABLE, so it now drops
only the columns that are there and re-adds them all.
- 0126 resumes at whichever of its four steps the previous run reached.
`full_path_digest_sql` also coalesces a NULL fs_path/fs_name to match
`compute_full_path_hash`, since the disagreement folded the whole row to
NULL and aborted 0126 at its NOT NULL step.
Combines #4479 and #4481, whose fixes are carried here in full.
Co-Authored-By: Sam Dornan <sam.dornan@athleticgreens.com>
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>
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>
Cut the comments that explain rather than note: the migration's four-paragraph
docstring, the upload-path and digest-SQL docstrings, and the mark-missing note
in the scan loop. Drop an em-dash from LocationChip's header per CLAUDE.md.
Reword 0126's downgrade error so it no longer embeds a SELECT, which bandit
reads as string-built SQL, and mark the dialect-selected backfill nosec B608 the
way the other migrations do.
Add the LocationChip test its HashChip sibling already had, covering the copy
going through useClipboard (the composable is what applies the secure-context
guard).
Co-Authored-By: Claude Opus 5 (1M context) <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>
Cut the docstrings back to the one paragraph the surrounding migrations use,
and drop the comments that restate the index name next to them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The list covered firmware and the music tables but not saves.user_id,
states.user_id, screenshots.user_id, rom_file_user.user_id,
memory_cards.platform_id or streaming_container_adoptions.decided_by_user_id,
so a user delete still sequentially scanned the three largest per-user tables
on PostgreSQL, which is the case the pass set out to fix.
Add a test that recomputes the rule (a single-column foreign key whose column
leads no index, primary key or unique constraint) from the model metadata, so
the next model foreign key cannot be forgotten silently.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`play_sessions.device_id` and `play_sessions.sync_session_id` were left out of
the PostgreSQL foreign-key list, which is inconsistent with the criterion 0124
states for itself: a column queried directly or walked by `ON DELETE` needs a
real index there. Every other index on the table leads with `user_id`, so
`device_id` is only ever a second column and `sync_session_id` appeared in no
index at all. Both are `ON DELETE SET NULL`, so deleting a device or a sync
session made PostgreSQL scan the whole table.
That scan grows with every session played. On a 60k-row table with 1200 rows
pointing at one device, the row lookup behind the SET NULL goes from a 7.6ms
sequential scan to a 0.14ms index probe, taking the statement from 53ms to
38ms; the remainder is row rewriting no index avoids.
The `device_id` query filter in `get_existing_session_keys` is already served
by `uq_play_session_identity`, since it leads with `user_id` too, so this is
about the delete path rather than that lookup.
MariaDB is unaffected: InnoDB already created implicit indexes on all three
columns, which is why these are dialect-gated.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
`trunk_check` reported `backend/utils/database.py` as unformatted. Adding the
index constants pulled the file into trunk's modified-file scope, which
surfaced a formatting deviation that predates this branch: black 26.5.1 drops
the redundant parentheses from an `except` tuple, which PEP 758 makes valid
syntax on the Python 3.14 this project requires. Three `except` clauses in
otherwise untouched helpers change as a result; the file cannot pass
`trunk fmt` without them.
Also collapses the AUTOGENERATE_EXEMPT_INDEX_NAMES assignment onto one line,
which is the same formatter's doing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
Adding a composite index that leads with a foreign-key column lets InnoDB
re-point the constraint at it and discard the implicit single-column index.
Reversing 0122 then failed with "Cannot drop index 'ix_rom_user_user_rom':
needed in a foreign key constraint" on `rom_user.user_id`, and would have on
`screenshots.rom_id`. The downgrade now restores those two implicit indexes
first, and a full up/down/up cycle leaves the schema byte-identical to a
database that never ran the migration.
Also sets `path_separator = os` in alembic.ini, silencing the deprecation
warning about the legacy space/comma/colon path splitting. `prepend_sys_path`
holds a single entry, so the behaviour is unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
Four query shapes had no index that could serve both their predicate and
their sort, and a class of foreign-key columns was relying on an implicit
index that only MariaDB and MySQL provide.
New portable indexes:
- `screenshots (rom_id, user_id)`. `Save.screenshot` / `State.screenshot`
resolve a thumbnail per row, so this lookup runs once per card on the
continue-playing rail. 0093 added the equivalent to `states` and noted
`saves` already had it; `screenshots` was missed.
- `rom_user (user_id, rom_id)` and `rom_user (user_id, last_played)`.
`unique_rom_user_props` leads with `rom_id`, which covers the gallery's
outer join but not the reverse direction, where sorting or scoping by a
per-user column starts from this table.
- `roms (platform_id, name_sort_key)`. The gallery is browsed one platform
at a time and ordered by name, and no index carried both columns. On a
120k-row library across 20 platforms this takes the first page from
5.8ms/1568 buffers to 0.6ms/75 buffers. Deep offsets converge, since the
skipped rows are walked either way.
New PostgreSQL-only foreign-key indexes:
MariaDB and MySQL index every foreign key whose column is not already some
index's leftmost prefix; PostgreSQL does not. Eight such columns are queried
directly or walked by `ON DELETE`, so they get a real index there. Creating
them everywhere would leave the other backends with duplicates, so they are
dialect-gated and exempt from autogenerate.
Model/schema reconciliation:
Fifteen live indexes existed only in the migrations. Worse, `alembic/env.py`
never imported six models, so `devices`, `client_tokens`, `device_save_sync`,
`sync_sessions`, `play_sessions` and `streaming_container_adoptions` were
absent from the metadata autogenerate compares against, and autogenerate in
fact failed outright resolving `saves.origin_device_id`. With the imports
fixed it would have proposed dropping every one of those indexes.
Declares all of them on their models, matches `PlaySession` to the unique
index 0076 actually created, and adds a test that fails on any future index
drift so this cannot silently recur.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
- Cast year to text in the /api/music years facet search so Postgres does
not error on lower(integer) (MariaDB/SQLite auto-cast, hiding it in CI)
- Escape LIKE wildcards in music search via new utils.database.escape_like
- Drop lazy="selectin" on RomFile.track_meta; eager-load only where the
metadata is serialized (get_rom already did; add the three soundtrack reads)
- Migration backfill uses a single query + fetchmany (repo idiom, see 0084)
instead of manual keyset paging, in both directions
- Guard the extensionless folder-conversion collision (stale row over a
directory the user already created on disk)
- Renumber migration 0093 -> 0094 after 0093_states_rom_user_index landed
Fix existing JSON array util `json_array_contains_value`, and add two
new utils: `json_array_contains_any` and `json_array_contains_all`.
These utils have been tested with arrays of strings and integers, on the
following database engine versions:
- PostgreSQL: 12, 13, 14, 15, 16, 17, 18
- MySQL: 8.0, 8.4, 9.0, 9.4
- MariaDB: 10.5, 10.6, 10.11, 11.4, 11.8, 12.0
Fix `json_array_contains_value` function to use the `@>` operator for
checking if a JSON array contains a value in PostgreSQL. This is
necessary because the `has_key` function only works for string values.
Also, remove `get_rom_collections` method, as it was doing the same
thing as `get_collections_by_rom_id`.
Fixes#1441.
This change introduces PostgreSQL compatibility, by implementing the
following changes:
* Use `JSONB` instead of `JSON` for PostgreSQL databases. This is
achieved by creating a custom `CustomJSON` type that uses `JSONB` on
PostgreSQL and `JSON` on other databases, leveraging the variant
mechanism of SQLAlchemy.
* Add `is_postgresql` function to check if the current database is
PostgreSQL. Commonly used for migrations, but can be used to determine
how to build queries based on the database engine.
* Add `json_array_contains_value` function to check if a JSON array
includes a specific value. This function is needed as it's
engine-specific.
Support for PostgreSQL is on a best-effort basis, and it relies on the
community for continued support and testing. The project's main database
is MariaDB.
Closes#667.