* fix(scan): fetch file rows per rom on quick scans
A quick scan loaded every file row of a 200-rom batch up front, so a
platform with a few extracted multi-file games held hundreds of thousands
of RomFile objects at once and the worker was OOM-killed. Each rom now
fetches its own rows inside the scan semaphore, capping the rows held to
SCAN_WORKERS roms.
Refs #5706
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style(scan): shorten the batch lookup comment
Addresses Greptile's review on #5725.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(saves): add save channels and snapshots
* feat(saves): close spec gaps in save channels and hash with sigil
* feat(saves): play snapshots in the v2 player, which pushes snapshots
* fix(saves): code review: authorization, retention losses, held-save sync, batched responses
* refactor(saves): simplify pass
* refactor(saves): review-polish pass
* docs(saves): humanizer pass
* feat(saves): run every EmulatorJS page on the v2 player
* feat(saves): per-user snapshot pins
* feat(sigil): store the identity a save restore needs and pin sigil 0f05f25
* fix(saves): meet type-aware lint in the v2 player
* feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda
* feat(saves): convert saves for a core on download and list save layouts
* feat(saves): prune unreachable archival snapshots and empty detached channels on delete
* feat(saves): device sync from the token, held snapshots and shared-card pushes
* feat(saves): arc restores past abandoned snapshots and color channels by age
* fix(saves): code-review and security-audit fixes
* refactor(saves): simplify pass
* chore(saves): review-polish pass
* docs(saves): humanizer pass
* fix(sync): file RetroArch autosave versions as their channel's next snapshot
* fix(saves): address review findings and trim docstrings
* fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock
* test(saves): stub the detached-channels fetch in SaveDataTab stories
* feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff
* chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets
* docs(saves): drop v2 wording now that one UI remains
* chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets
* fix(sigil): treat a file too short for its format as routine during scans
* chore(migrations): renumber save channel migrations after upstream's 0154
* fix(snapshots): a hardcore switch on unchanged content makes a new current
* fix(sync): decide a channel's slot from its history and the device's snapshot
* chore(docker): pin sigil at 794d99f for PSP Store release save prefixes
* refactor(db): squash the save channel migrations into 0161
Fold the slot linking (0162) and the rom_files sigil identity columns (0163)
into 0161_save_channels, so the feature ships as one revision.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(saves): close visibility and input gaps found in review (pr-ready step 2)
code-review --fix:
- negotiate_sync drops channel slots on ROMs hidden from the caller
- channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden
- a push copying a save from a hidden ROM answers 404
- _own_device applies require_token_device to bound client tokens
- adopting a legacy save syncs its sharing with the channel it joins
security-audit follow-ups:
- another user's detached public save or state is no longer downloadable
- profile and option values must be a single path segment
- companions are de-duplicated and capped at 8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3)
simplify:
- readable_channel_or_404 and channels_on_files replace four copies of the
channel 404 check and two copies of the file-fed channel listing
- readable_rom_asset_or_404 serves both public save and state downloads
- _own_device resolves through require_device; _clone_origin takes the source
- reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy
and uuidv7; neutral forms default their required pattern to the allowed one
- RetroArch delete checks held rows in one query, a guarded upload lists the
slot only without a channel head, and uploads are read off the event loop
- snapshotSession builds push requests once; player comment cleanups
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(saves): trim two docstrings to two lines (pr-ready step 4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(saves): answer held RetroArch paths with 423, mirror slot labels
- RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save
and for a DELETE where only held rows sit at the path, instead of 409 and 404
- channelLabelForSlot returns null for blank and state_ slots, as the backend's
channel_label does, so the player files them under no channel either
- document that sharing a channel lets every user read and push into it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(docker): pin sigil at 85f88a8 for Switch .nup containers
* fix(snapshots): a save pushed in another shape or format makes a new current
* refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag
Nothing reads it, and the SAVE_SYNC block's presence already tells a
client the server speaks the snapshot API. Also trim the rom detail
channel field comments to one line each.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(frontend): use uuidv7 for every client-generated id
Drop the randomToken wrapper and the notification inbox's Math.random tab
id, so uuidv7 is the one helper that works outside a secure context.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic
API:
- Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds.
- GET /snapshots is history only (channel_id required); GET /channels serves currents.
- A snapshot carries channel_id instead of an embedded channel.
- POST /saves/{id}/content takes the same query parameters as the GET, plus container_path.
Backend:
- Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil
identity-hash path, unused relationships and composite snapshot indexes.
- One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and
the shared reserve_version_name in the writer.
- The writer takes a visibility filter and checks the channel and parent itself.
- The restore handler picks per-game or merge; fewer wrapper types and tables.
Frontend:
- Channel delete uses the shared typed confirm; DeleteChannelDialog is gone.
- Held offline pushes go through a per-channel SnapshotSession.
- Remove the slot-based pending upload path.
- The timeline shares the fan's badge logic.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* refactor(saves): release archival backups through module functions
The saves and states handlers each built a private DBSnapshotsHandler to
call release_backup and refresh_backup_digests, since they can't import
the shared instance. Both only ever ran inside the caller's session, so
they are now module functions taking it, like channel_for_slot.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* refactor(saves): share one deleted-assets handler instance
The saves handler built its own DBDeletedAssetsHandler because it can't
import the package's instance. The instance is now built in
deleted_assets_handler.py and re-exported by the package, so both use it.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sync): match RetroArch saves named after a ROM's files
RetroArch names a save after the file it launched, so a disc or a
translation inside a multi-file game folder uploaded a save that matched
no ROM. When no ROM carries the name, saves now resolve to the ROM owning
a file with that stem. Those saves stay unslotted under their own name,
since a ROM's autosave lineage holds one save per core and the discs
would overwrite each other. States keep matching on the ROM name only,
because their slots are advertised under it.
Fixes#5364
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sync): write a case-variant reupload to the stored save's own file
Addresses Greptile review on #5445.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sync): match a stored save's name in any case on PostgreSQL
The RetroArch save lookup relied on MariaDB's case-insensitive collation, so
on PostgreSQL a reupload in another case created a second save instead of
replacing the stored one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* perf(tasks): batch RetroAchievements progress sync reads
Add get_roms_by_ra_ids and get_rom_users_by_rom_ids (single index-backed
IN queries, no eager joins) and fold the per-user feed to {ra_id: status}
so each user costs 2 reads plus writes instead of 2 reads per game.
* fix(tasks): skip joined eager-loads in RA sync batch reads
* style(tasks): trim batch-read comments to house style
* fix(tasks): sync every ROM sharing an ra_id, skip empty rom set early
* fix(tasks): raiseload instead of deprecated noload, fix CI failures
* fix(tasks): apply code-review fixes to RA progress sync batching
pr-ready step 2 (code-review xhigh --fix): load only id/ra_id for the
batched ROM read, flatten the sync loop, isolate per-user status sync
failures, log the ROM id, add a real-row test, and move the batched
RomUser getter next to its siblings.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(tasks): simplify RA progress sync batching and its tests
pr-ready step 3 (simplify): select (id, ra_id) columns instead of Rom
entities, drop early returns the getters already short-circuit, and
fold the mocked sync tests into shared helpers and one parametrized
status-transition test.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* style(tasks): trim batched RomUser getter comment
pr-ready step 4 (review-polish).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(tasks): tighten unknown-award test docstring
pr-ready step 5 (humanizer).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(tasks): batch RA status writes and make add_rom_user race-safe
set_rom_user_statuses writes one user's statuses in a single
transaction: it inserts missing RomUser rows, then runs one conditional
UPDATE per distinct status. The RETIRED/NEVER_PLAYING guard lives in the
WHERE clause, so a status the user sets mid-sync is never overwritten,
and the per-user cache bumps are queued once.
add_rom_user now inserts inside a savepoint and returns the existing row
when a concurrent writer won the unique (rom_id, user_id) insert, so the
sync no longer needs a catch-all around each user.
A rolled-back savepoint fires after_rollback, which drops every queued
user cache bump, so bumps are queued only after the savepoints finish.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(tasks): skip existing rom_user rows in the batch insert
Addresses Greptile review on #5179. The batch read existing rows before
inserting, so under MariaDB's REPEATABLE READ a row another writer
committed in between raised IntegrityError, and the fallback SELECT (or a
FOR UPDATE read, which MariaDB's snapshot isolation refuses) could not see
it. The insert now skips duplicates itself (ON CONFLICT DO NOTHING /
INSERT IGNORE) with no prior read. The race test commits the competing row
right before the INSERT instead of mocking the lookup. Also trims the
set_rom_user_statuses docstring to one sentence.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(tasks): apply code-review fixes to batched RA status writes
Batch set_rom_user_statuses to stay under PostgreSQL's bind parameter
cap, keep queued cache bumps across a rolled-back savepoint, fold the
single-caller insert helper into add_rom_user, and fix stale comments.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(tasks): apply simplify pass to batched RA status writes
Group by status before batching to drop a loop level, name the
user-owned statuses, split the dialect insert out of the execute call,
and share a status lookup across the write tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(tasks): type the dialect insert for mypy (review-polish)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Shreeniwas <105774423+Shreeniwas1@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <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(tasks): batch RetroAchievements progress sync reads
Add get_roms_by_ra_ids and get_rom_users_by_rom_ids (single index-backed
IN queries, no eager joins) and fold the per-user feed to {ra_id: status}
so each user costs 2 reads plus writes instead of 2 reads per game.
* fix(tasks): skip joined eager-loads in RA sync batch reads
* style(tasks): trim batch-read comments to house style
* fix(tasks): sync every ROM sharing an ra_id, skip empty rom set early
* fix(tasks): raiseload instead of deprecated noload, fix CI failures
* fix(tasks): apply code-review fixes to RA progress sync batching
pr-ready step 2 (code-review xhigh --fix): load only id/ra_id for the
batched ROM read, flatten the sync loop, isolate per-user status sync
failures, log the ROM id, add a real-row test, and move the batched
RomUser getter next to its siblings.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(tasks): simplify RA progress sync batching and its tests
pr-ready step 3 (simplify): select (id, ra_id) columns instead of Rom
entities, drop early returns the getters already short-circuit, and
fold the mocked sync tests into shared helpers and one parametrized
status-transition test.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* style(tasks): trim batched RomUser getter comment
pr-ready step 4 (review-polish).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(tasks): tighten unknown-award test docstring
pr-ready step 5 (humanizer).
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>
Replace the hidden_platform_ids/hidden_rom_ids parameter pairs with one
RomVisibilityFilter that builds the WHERE clauses and checks loaded ROMs,
so a new visibility rule (the age-rating cap for #2013) lands in one place.
No behaviour change; the visibility-filtered queries send the same SQL.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wc3NzFkv97CXavLyZg5kJE
* feat(converto): read per-file title ids with rom-converto during scans
The title-id half of #5002: rom-converto's info runs fill rom_files.title_id
and title_version, sigil fills what rom-converto can't read and keeps owning
save targets, and roms in a scan batch share info runs of up to 64 files.
A converto_read_at marker lets quick scans backfill files rom-converto has
not read yet. converto.scan_metadata (config.yml only) turns it off.
The other per-file fields and embedded images stay out until a UI reads them.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(converto): name the same-content check that keeps unread title ids
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(converto): queue unread files in one pass over the built rows
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(converto): address Greptile review on #5031
- A file refresh now persists converto_read_at when rom-converto's read
confirms a reused row's stored title id, so the file isn't re-read on
every refresh.
- RomConvertoService.read_infos splits its paths into info runs of at
most INFO_BATCH_SIZE, so a rom with many files can't send them all
through one run.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(converto): apply code-review fixes
- A stored file title id counts as rom-converto's only once rom-converto
has read the row, so a stale sigil id can't override a fresh extraction.
- Fresh hashes decide whether unread title ids still describe a file,
ahead of a size and mtime a copy can preserve.
- One rom's failed candidate listing no longer aborts its scan batch.
- The info paths file's cleanup can't raise out of read_infos.
- _rom_file_order sorts by Path like _TitleIdSource.order.
- Restored the in-place reconcile test for _identify_rom.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(converto): apply simplify pass
- sync_rom_files reads 'rom-converto read this pass' off converto_read_at
instead of an inspected set threaded through ParsedRomFiles, FSRom, the
scan socket and the refresh.
- One _converto_may_read check serves the scan and the batch candidates.
- converto_candidates reuses _list_rom_dir, validates paths off the event
loop and is best-effort itself, so the scan socket gathers it plainly.
- get_rom_files builds rom-converto paths from the validated rom dir
instead of validating each file again.
- _rom_level_identity returns early on sigil's extraction.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(converto): apply review-polish pass
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(converto): drop the shared info batch
Sharing rom-converto info runs across a scan batch saved about 2 ms per
rom (one process start) in exchange for a second directory walk per
rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket
wiring. Each rom now reads its own files; read_infos still caps a run
at INFO_RUN_MAX_FILES.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(converto): name the rom-converto columns inline
Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so
_copy_scanned_columns keeps master's frozenset keep_when_unset.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(backend): build test ROMs through one make_rom factory
Tests created Rom rows by hand in dozens of places, each spelling out the
same slug and filename fields and deriving the slug inline. Production never
computes a slug from a name, so this was test-only filler duplicated across
files.
tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension,
**overrides), which fills the slug and filename columns and persists through
db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and
the local helpers and inline constructors across 35 test files now use it.
Each test keeps its filename shape (underscored stems in the FULLTEXT search
tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared
across files keep their exact slugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend): keep extensionless filenames intact in scan_stubs.add_rom
rpartition(".") on a name with no dot returned an empty stem and the whole
name as the extension, so make_rom stored ".README" for "README".
os.path.splitext leaves such names whole.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend): build test saves, states and screenshots through factories
Tests built Save, State and Screenshot rows by hand across about 20 files,
each spelling out file_name_no_tags, file_name_no_ext and file_extension
although BaseAsset already derives them from file_name.
tests/factories.py adds make_save, make_state and make_screenshot. Each sets
the rom and user ids, the file name, and a default file_path under the rom's
platform, applies overrides last, and persists through the matching db
handler. The conftest asset fixtures and the persisted constructors and local
helpers now use them. Rows a test observes keep their file_path, emulator,
slot, size and hash, and a filename part stays an override wherever it
differs from what the model derives.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend): ban direct add_* persistence in tests via ruff TID251
The factories only stay the one home for test rows if nothing routes
around them. Ruff's banned-api rule now flags db_rom_handler.add_rom,
db_save_handler.add_save, db_state_handler.add_state and
db_screenshot_handler.add_screenshot anywhere under tests/ except
tests/factories.py. Production code is unaffected.
The remaining add_rom calls move onto make_rom: the unique-path, soundtrack
and id-index tests in test_roms_handler.py, the scan tests in
test_fastapi.py, physical and missing rows in the feed, download and model
tests, and the name=None exporter rows. Scan tests keep a filename-derived
placeholder as the name, which scan_rom treats the same as no name. Three
calls keep a noqa: the tests of how add_rom merges a partial scanned row,
and the rescan test that persists scan_rom's output as a scan does.
The backend skill and the architecture doc now point at tests/factories.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend): move the firmware and client-token factories into tests/factories.py
The add_firmware and add_device_token conftest fixtures returned a builder,
unlike the importable make_* functions. They become make_firmware and
make_device_token alongside them, with the same defaults, and their callers
import them rather than requesting a fixture. make_device_token now draws the
raw credential from auth_handler.generate_client_token, so it carries the
real rmm_ prefix instead of restating it, and the hand-built client tokens in
the auth tests use it too.
The ruff TID251 ban now also covers db_firmware_handler.add_firmware and
db_client_token_handler.add_token under tests/.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: point at every test factory, not just the ROM and asset ones
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The linter ran over every Markdown file and Python comment, so full-repo
trunk runs on master kept failing on em-dashes that predate it. Replace
the existing ones once and drop the check. The AGENTS.md rule stays, the
v2 ESLint rule stays, and pr-ready's humanizer pass catches new ones in
prose.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RyamrxVw5BzEidVzm68LY7
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Conflict resolution notes:
- Locale rom.json: master sorted and reworked every file; took master's and
re-inserted `location` / `location-copied` in sorted position. Added them to
the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
(master), and the scan loop keeps master's early missing-sync plus its
restored-rom emit alongside this branch's relocation pass. The relocation
filter now applies only to the identify loop, so a relocated rom is no longer
re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
`purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
premise that same-named files in different folders are distinct games.
Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
all share one folder, so a duplicate title is still rejected.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Files added to an already-scanned folder ROM could only be picked up by a
complete or hashes rescan, which rehash every known file. The new `files`
scan type scans new games like quick and re-lists the files of existing
folder ROMs, hashing only new or changed files and recomputing the
ROM-level hashes only when a top-level file changed. Per-rom update and
unmatched scans reuse the same incremental mode, and the filesystem watcher
enqueues it instead of quick.
Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a
current mtime to about 128 seconds), adds the CHEAT value missing from the
PostgreSQL category enum, maps `patches/` to the patch category and
excludes upload temp files from scans.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
A rom parsed its filename tags when it was first inserted and never again,
so a change to parse_tags only reached rows scanned after it. The freshly
parsed values were built for every rom but only consumed on the insert
path, and scan_rom reseeded the tag columns from the existing row, so no
scan type could refresh them.
A complete rescan (or an explicit per-rom selection) now writes them back.
A hashes rescan still doesn't, since it is scoped to re-reading file bytes.
scan_rom also carries "version" forward now. It was the one tag column
missing from its attrs, so a re-parsed version would have been dropped, as
the value written by the reassociation path already was.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Smart collections silently ignored several filters at both ends:
- The backend never applied has_soundtrack, has_saves, has_states, or
player_counts from stored criteria, so a "has soundtrack" smart
collection contained every game. get_roms_scalar also dropped
has_soundtrack before it reached filter_roms.
- The v2 criteria serializer had no fields for has_saves/has_states and
only stored tri-state filters when true, so "unmatched" or "has
saves" produced empty criteria and the no-filters guard blocked the
save.
Criteria now carry saves/states filters and explicit false states, the
backend applies them, and summaries render negative states with the
existing "show-not-*" labels.
Fixes#3888
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A scanned row leaves unset columns as None and the model defaults only
apply on insert, so the reconciliation path could write NULL into
file_size_bytes or has_embedded_cover. Unset values now leave the stored
value alone.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A file that stopped carrying audio tags, or vanished from disk, had its
track_meta row dropped (directly or by cascade), leaving its persisted
cover on disk with nothing pointing at it.
sync_rom_files now reports those cover paths so the scan unlinks them,
keeping filesystem work out of the database handler.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Rescans deleted and re-inserted every rom_files row, so file ids churned
on each scan and anything keyed on them (track metadata, persisted
soundtrack covers) was orphaned.
Rows are now matched by path first, then by content hash so a file
renamed or moved inside the ROM keeps its id, mirroring the ROM-level
reassociation. Only changed columns are written, vanished files are
deleted, and archive_members is carried over (the hand-written copy
dropped it).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The has-saves / has-states filters matched only the current user's own
saves/states. Match public (community) ones too, so a ROM with another
user's shared save/state is surfaced by the filter — mirroring the
owner-or-public visibility used elsewhere (get_rom_shared_saves/states).
Generated-By: PostHog Code
Task-Id: feda1257-eb36-4566-9898-528087459416
The patcher uploads the patched ROM and then fires a platform scan to
register it. When a second scan runs against the same platform around the
same time (a filesystem-watcher rescan, a scheduled rescan, or another
manual scan on a multi-worker setup), both scans could see the new file as
absent from the DB and each insert it, producing two identical library
entries for one patched file.
A platform folder can't physically hold two entries with the same name, so
a ROM is uniquely identified by (platform_id, fs_name). Enforce that with a
unique index instead of the previous plain index, which makes the duplicate
impossible. The scan's early ROM insert now adopts the row created by a
concurrent scan (catching the integrity error and skipping) instead of
failing, and ROM rename pre-checks for a name collision so it returns a
clean 409 rather than hitting the constraint.
Includes a migration that removes any pre-existing duplicates (keeping the
lowest id; dependents cascade) before upgrading the index to unique.
Fixes#3590
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0135UV8Xn2XHkRhjzhm9UptP
Drop the name_sort_key_custom flag/migration in favour of a flagless rule: a
key is "custom" when it no longer equals compute(name). Apply that consistently
across all three write paths so a manual sort key survives renames while a
derived key keeps following the name:
- @validates re-derives on name assignment only when the stored key still
matches the derived value; direct name_sort_key assignment stores a
normalized custom key (or reverts to derived when cleared). Handles both
kwarg orders at construction.
- update_rom mirrors the same check for the bulk update() path it bypasses.
- The edit endpoint only writes the key when the user actually changed the
field, delegating the untouched case to update_rom.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Collapse the separate `sort_name` column into `name_sort_key`, which is now
the single user-settable sort field: always normalized and indexed for fast
ordering, derived from `name` by default, and overridable. A new
`name_sort_key_custom` boolean marks user/metadata overrides so they survive
renames and rescans.
- Drop the `roms.sort_name` column; repurpose migration 0085 to add
`name_sort_key_custom`.
- Derive the key via `@validates("name")` unless pinned custom; the edit
dialog, unmatch flow, and ES-DE gamelist <sortname> set custom keys.
- update_rom / scan_rom keep the columns in sync explicitly (bulk update and
construction bypass / reorder the validator).
- Frontend: edit field drives name_sort_key (empty when auto), api sends the
override only when custom, regenerated types updated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Centralize the *_no_tags / *_no_ext / *_extension columns (derived from a
file name) behind @validates hooks instead of computing them by hand at
every write site:
- Add pure helpers (compute_file_name_parts and friends) to models.base;
the filesystem base handler now delegates to them.
- Add @validates on Rom (fs_name), BaseAsset (file_name, inherited by all
asset subclasses), and Firmware (file_name).
- update_rom keeps the fs_name-derived columns in sync on bulk update(),
which also fixes the rename path never updating fs_extension.
- Drop the now-redundant computations at the scan/rename call sites.
Also fix the migration backfill loop and a pre-existing list[str | None]
type mismatch surfaced in scan_handler. Add tests for the helpers, the
validators, and the update_rom bulk-sync path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>