* fix(roms): read full country names in filenames as regions
No-Intro writes full country names, e.g. (Poland) or (Czech Republic).
parse_tags only resolved the names listed in REGIONS, so the regions added
from the provider vocabulary were stored as other tags. Add those names to
the filename region aliases, skipping any that a language vocabulary claims.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
* chore(roms): shorten region alias comment per Greptile review
Addresses Greptile's comment-length finding on #5578.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
* feat(scan): recognize Brazilian Portuguese as a language
Add "Pt-BR" (Brazilian Portuguese) to the filename language table, so
"(Pt-BR)" and "(T-Pt-BR)" no longer fall back to an unrecognized tag or
to European Portuguese, and show the Brazilian flag for it in the UI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): read the regional variant ahead of a translation's version
"[T+Pt-BR1.1_Grp]" kept the version in the lookup and fell back to
Portuguese. Match only the two-letter variant that opens the patch, and
cover the Brazilian flag in the frontend tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style(scan): apply black formatting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): look a file named by several titles up by each of them
No-Intro and Redump name a game released under several titles by all of
them, joined by " ~ ". Each file-name lookup now tries the full name
first and then each title, tags and extension kept, until one matches;
SteamGridDB searches the titles too. Only the title is split, never a
tag group.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9
* fix(scan): search each SteamGridDB name once
From Greptile's review: a title can repeat a name a provider already
gave, so SteamGridDB's candidate names are deduplicated, first position
kept, with a test. The new test module's docstring is one sentence, as
AGENTS.md asks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9
* fix(scan): keep the full-name answer on a miss and cap title lookups
pr-ready step 2 (code-review xhigh --fix): return the full name's result when
every title misses, dedupe and cap titles at 4, and stop wrapping CSDb, whose
lookup only reads a (csdb-N) tag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(scan): give SteamGridDB the bare titles and inline lookup args
pr-ready step 3 (simplify): add compute_titles so SteamGridDB stops re-attaching
and re-stripping tags, inline the Moby and SS platform ids, and merge the two
all-miss tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): keep the narrowed Moby and SS platform ids for mypy
pr-ready step 4 (review-polish): the locals inlined in step 3 narrow the
optional platform ids, which a lambda body cannot do; restore them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(scan): reword the title cap comment
pr-ready step 5 (humanizer).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
* fix(docker): boot when the container runs as a non-default UID
Unraid runs the container as 99:100, which can't write to the image's
/romm (owned by 1000, mode 755), only to the mounted subfolders. The
PSP pending dir at /romm/cache/retroarch_sync was created at import
time, so every gunicorn worker failed to boot.
- Buffer pending PSP save files under the user's assets folder
(assets/users/<user>/retroarch/psp_pending/), beside the other
RetroArch Cloud Sync files and outside the client-reachable blob
categories.
- Move the zip and rom-converto download caches to /tmp/romm/cache,
and point nginx's internal /cache/ alias there.
- Put gunicorn's control socket in /tmp/gunicorn instead of
$HOME/.gunicorn, since HOME is / for that UID.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(docker): honor ROMM_TMP_PATH for caches, explain an unwritable sync folder
- The download caches live under $ROMM_TMP_PATH/cache when it's set,
so installs with a small Docker disk (Unraid's docker.img) can point
them at a share. The entrypoint exports the same path for nginx's
/cache/ alias.
- With ENABLE_SYNC_FOLDER_WATCHER on and /romm/sync not writable, /init
warns and skips the watcher instead of dying on mkdir under errexit.
- The compose example lists the /romm/sync mount the sync features need.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(sync): cover reading back and clearing buffered PSP files
Addresses Greptile's review on #5189.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): apply code-review findings to PSP pending buffer
Remove the emptied psp_pending folder after a merge, define the sync
folder path once in init, update the architecture doc's PSP and blob
locations, and drop a stale .gitignore entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(sync): apply simplify findings to PSP pending cleanup
Clear the buffered folder with remove_directory, let the startup check
own creating the sync folder, and reword the test fixture docstring.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): cap buffered PSP files and drop them on delete
Buffered files for an unresolved save folder now count against the
bundle limits, so a folder can't fill the assets share and then fail
every merge once it resolves. A DELETE also removes the buffered copy,
so a deleted file isn't merged back when the folder resolves.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(docker): check the sync folder for push-pull sync too
ENABLE_SYNC_PUSH_PULL keeps SSH keys and device saves under /romm/sync
as well, so an unwritable folder now disables it with the watcher and
warns at boot instead of failing when the task runs.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(docker): strip whitespace from env vars like the backend does
The backend strips every variable it reads, while the init script and
nginx templates used raw values, so a padded ROMM_TMP_PATH sent nginx's
/cache/ alias somewhere the backend never writes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(config): drop the CACHE_BASE_PATH comment
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(docker): say which backend config strips env whitespace
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* revert(docker): drop the entrypoint env whitespace trimming
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(sync): apply pr-ready code-review findings
Gate push-pull on its SSH keys path rather than a writable sync folder,
accept the same truthy values as the backend, and clear only the merged
PSP pending files so another worker's buffered file survives.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor: apply pr-ready simplify findings
Share one truthy pattern across init's flag checks (the watcher gates
now accept the same values as the backend), disable gunicorn's unused
control socket instead of placing it, derive the converts redirect from
its own cache path, and factor the unknown PSP folder in tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(docker): apply pr-ready humanizer pass to the sync mount note
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(fs): create handler base folders on first write, skip leftover temp files
FSHandler no longer mkdirs its base path when constructed, so a module-level
handler rooted at an unmounted or unwritable folder can't take down boot;
every write path already creates its parent folders. Blob listings skip
.romm_tmp_ files a crashed write left behind, so they are never merged into
a PSP bundle or advertised in the sync manifest. The prefix now lives in one
TEMP_FILE_PREFIX constant.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
pr-ready step 2 (code-review xhigh --fix): byte-check screenshot, rename
and ROM fs_name paths, fit streaming save archive names, cap email and
collection names, log duplicate collections at warning.
Upload names were held to FILE_NAME_MAX_LENGTH, 450 characters, but
ext4, XFS, Btrfs and ZFS cap a name at 255 bytes. A longer name passed
validation and the write failed with ENAMETOOLONG, a 500. Non-ASCII
names hit it early: a Japanese title reaches 255 bytes at about 85
characters.
Check the encoded length in the shared write path and in the save and
state uploads, so those return 400. Saves are checked after the slot's
datetime tag is added, since the tag adds 22 bytes. Memory card version
files trim the card name to fit, because a 255-character card name
leaves no room for the timestamp.
* perf(gamelist): validate media tag paths once per directory
A full-platform gamelist parse ran validate_path on every media tag,
about a dozen lstat calls each, which added up to tens of seconds per
platform on NFS/SMB mounts.
FSHandler.cached_path_validator returns a validate_path equivalent that
runs the lexical checks per call but hits the disk once per distinct
parent directory. The leaf needs no syscall: validate_path accepts a
symlinked leaf, and a plain one resolves inside its checked directory.
The gamelist parse builds one per pass and threads it to the media tag
and directory-entry checks.
On a 1,500-entry gamelist with six media tags per entry, lstat calls
drop from 108,140 to 200.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U5CmSdodtG5s2MiH9y65LE
* test(gamelist): pin one validate_path call per media folder
Condense cached_path_validator's docstring to one sentence, and assert
the exact per-folder call counts in the gamelist parse test, with the
media index stubbed so only the parse's own validation is counted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U5CmSdodtG5s2MiH9y65LE
---------
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
* 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>
- Enforce the upload size cap on streamed bytes in the middleware, so
chunked uploads to every guarded route are bounded, not just RetroArch
- Flag vanished assets missing_from_fs from the manifest instead of
re-hashing them every sync
- Batch state screenshot lookups, filter PSP bundles in SQL, hash files
in one thread hop, and read only the requested PSP bundle members
- Reuse remove_screenshot and content_hash_of_bytes, merge the save and
state PUT branches, drop dead checks and trim docstrings and tests
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Every manifest read (GET and each PROPFIND) hashes every save and state
row, and failures aren't cached, so a DB row whose file is gone logged a
debug line on every sync. A missing file is expected there; other OSErrors
are still logged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- Keep a shared thumbnail in place when its new name resolves to the same
file, so a case-only rename on a case-insensitive filesystem no longer
fails with a conflict trying to copy the thumbnail onto itself.
- Build the user in the collection dialog tests with a typed userFixture
instead of casting a partial object.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Resolve PSP folder paths from the same bundle set the manifest lists
(visible ROM, unslotted, newest per folder), so GET/PUT/DELETE can no
longer hit a slotted history bundle or a hidden ROM's bundle.
- Split validate_path's base-directory case out of its startswith guard,
so CodeQL recognizes the guard as a py/path-injection sanitizer.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- Hoist the file MD5 onto FSHandler; drop the blob handler copy
- Share path splitting, slot recency, cached MD5 and ROM visibility helpers
- Remove dead code (get_state_by_path, RomFile.file_ids, unused params)
- Scope WebDAV rom listing to one query; look up a single platform by slug
- Query saves once per manifest and batch ROM name resolution
- Read only the requested PSP bundle member; hash bundles from memory
- Single separator-safe lexical check in validate_path; same joined-path
validation in write_file_streamed
- Stop stripping + on ROM rename, the download path encodes it (#2746)
- Trim comments to the repo's comment rules
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- A shared thumbnail stays untouched only when the rename keeps its name
exactly; a case-only change gets its own copy, since PostgreSQL matches
screenshot names case-sensitively.
- copy_to_new_file removes the file it created when the fallback copy fails
partway, so a retry does not meet a half-written thumbnail.
- rename_asset's docstring drops a Returns block the signature already says.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A shared thumbnail whose stem the rename keeps stays as it is, instead of
being copied onto itself.
- The thumbnail copy goes through FSHandler.copy_to_new_file, which links or
creates exclusively, so a screenshot another worker wrote at that name is
refused instead of replaced.
- Collection settings hand a saved collection to the parent only while it is
still the one on screen, so a late visibility or Apply answer cannot swap
in the collection the user navigated away from.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- rename_file links then unlinks, so a name another worker took after the
check is refused instead of replaced; filesystems without hard links fall
back to rename.
- rename_asset owns the whole rename: the thumbnail and asset rows commit
in one transaction, and a failed commit moves the files back.
- A thumbnail another save or state still resolves is copied for the
renamed asset instead of moved away from the other one.
- Collection Apply and the visibility switch wait for each other.
- The collection settings test builds its fixture with a typed factory,
the RSwitch label-slot story uses a colour token, and the moved assets
fixture keeps a one-line docstring.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remaining py/path-injection alerts flowed through write_file's
filename argument (cloud-sync blob PUTs), which only went through
os.path.basename. Validating the full directory + filename path routes
it through validate_path's normpath guard too.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Swap xml.sax.saxutils.escape for html.escape(quote=False), which bandit
does not flag as an XML parser import. Add a normpath + startswith guard
to validate_path so CodeQL recognizes it as a path-injection sanitizer.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Saves and states could only be renamed by downloading, renaming and
uploading them again (#2653).
Backend: PUT /api/saves/{id}/file-name and PUT /api/states/{id}/file-name
rename the file on disk and the row, and take the auto-captured thumbnail
along so it stays bound by stem. A name another save/state of the ROM
holds, or one that would bind another screenshot, is a 409. Renaming
keeps updated_at, like the other annotations, so device sync does not
see a new version.
Frontend (v2): the Save data tab's per-row actions are now download,
edit, favorite and delete. Edit opens one form with the file name (stem
preselected), labels and visibility; a taken name is flagged in the
field. Public saves and states carry the same globe badge as shared
screenshots. RTextField now puts `autofocus` on its native field, which
is what RDialog looks for, so autofocused fields in dialogs get focus
instead of the close button.
Fixes#2653
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(metadata): read a fan translation's tag and target language
A translated dump is playable in the language it was translated into, but the
tag saying so was kept verbatim, so the rom was filed under no language at all
and the filter drawer grew one throwaway value per patch: "T+Eng1.1_RPGe" and
"T-Eng0.98_DeJap" are the same thing to a reader and two different facets to
the gallery.
The GoodTools, TOSEC and plain spellings now resolve to one "Translation" tag,
and the language the patch targets joins the rom's languages, so a Japanese
game translated into English answers a search for English and reaches an
emulator as English. A translation into a language RomM cannot name is still
tagged, and a tag that merely starts with "tr", like "Trainer", is left alone.
The group and patch version the raw tag carries are dropped, since nothing
reads them and keeping them is what splits the facet.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
* feat(metadata): read the spaced form of a GoodTools translation tag
"[T Fre]" separates with a space rather than a sign, and it is the spelling a
real ScreenScraper dump carries: its entry for "Super Mario Bros. (W) [T Fre]"
is flagged as a translation into French. The tag was read only as "T+Fre" or
"T-Fre", so that dump came out untranslated and unlanguaged.
A space carries no meaning of its own, unlike the sign, so this spelling counts
only when the word after it names a language: "(T Rex)" stays an ordinary tag.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
* style(metadata): trim the translation alias comment to two lines
Greptile flagged it against the repo's comment discipline: four lines, and
the product as the actor.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
* feat(metadata): resolve the short forms of a translation tag's language
"[T-En]" already resolved through the filename language vocabulary; the
non-ISO abbreviations "Ge", "Sp", "Du", "Gr" and "Jp" did not, so those
dumps were tagged without a language. Tests now cover both forms.
Also trims three comments and four test docstrings Greptile flagged
against the repo's comment discipline.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
* fix(metadata): stop reading a hyphenated word as a translation
"(T-Rex)" matched the GoodTools superseded form and became a Translation
tag. A superseded patch carries its version and group, so require that,
or a language the vocabulary names, before the bare "T-" form counts.
"[T+Tha]" still tags, since no ordinary word takes that shape.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
* style(metadata): trim the translation regex comment to two lines
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4mTJZ63Bvafv3stpiGsHC
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
`filesystem.structure` now spells out the whole layout rather than only the part
below a platform folder. A template is relative to the library root, `{platform}`
marks the platform folder, and `{game}` marks where a game begins.
Merge `{gameFile}` and `{gameDir}` into one `{game}` terminal. The information a
terminal carried was the depth, not the kind: at a declared level a file is a
game of its own and a folder is one multi-file game, which a stat answers. That
drops the two-template idiom for a level holding both, and `_discover_default_roms`
with it, since the default scan is now just `roms/{platform}/{game}`.
Retire the auto-detected `{platform}/roms` layout, along with
`filesystem.roms_folder` and `filesystem.firmware_folder`, which named one path
segment each that a template now contains. Both are refused at startup with the
template that reproduces the layout, so an instance that relied on either says so
instead of scanning an empty library and marking every rom missing. Firmware gets
its own `structure.firmware` key rather than following the rom layout implicitly.
`get_roms_fs_structure` keeps meaning the folder a platform's games start in, so
the `.physical` sentinel paths already in the database still resolve. Per-platform
overrides have to agree with `default` on where the platform folder sits;
relocating one platform needs platform discovery and the watcher to union several
roots, which is left out.
The setup wizard reports `library_ready` plus the configured template instead of
a `struct_a`/`struct_b` discriminator, so the banner shows the layout in force
rather than guessing it client-side.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Give 0o644 a single home in utils/filesystem as SERVED_FILE_MODE, used by
both the ZIP cache and FSHandler._atomic_write. Collapse the mode repair to
one call site behind a single stat per cache hit, close the temp descriptor
unconditionally, and log the build where the namespace is already in scope.
Deduplicate the test fixtures and drive the concurrency test with a barrier
on flock instead of a sleep, so the race is guaranteed rather than timed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
region_names_for_priority expanded the configured shortcodes into a flat
list of region names and _region_rank turned each name's index into its
rank. Two names claiming one shortcode ("nl" for both Holland and
Netherlands) therefore ranked unequally, so a Holland-tagged rom always
beat a Netherlands-tagged one instead of both falling through to the
filename tiebreak. The helper's own comment claimed otherwise.
It now returns name -> rank keyed on the shortcode's position, so aliases
tie. Unknown and repeated shortcodes still contribute nothing rather than
shifting the ranks after them, which is now covered by tests too.
Reported by Greptile and Copilot on #4260.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The group_by_meta_id dedup window ordered each sibling group by
is_main_sibling then fs_name_no_ext, so absent a manual override the
gallery entry went to whichever filename sorted first: "(Demo)" beat
"(Europe)" beat "(USA)".
Two ordering terms now sit between those: a full release outranks a
pre-release, then the configured scan.priority.region order decides.
Release status comes first because a demo is not a substitute for the
game, so a Japanese release wins over a USA demo.
scan.priority.region already existed but only steered metadata and
artwork selection, so its description is reworded across all locales.
Regions live in a JSON column that no covering index can carry, and 0107
measured what one uncovered reference costs this window: the plan drops
from `type=index, Using index` to `type=ALL, key=NULL`, four times per
gallery page load. 0108 adds a STORED generated column over regions[0]
and covers it in idx_roms_sibling_cover instead, so the ranking reads a
scalar. The engine keeps it in sync and ALTER TABLE populates existing
rows, so no scan hook and no backfill are needed.
Pre-release detection matches the filename rather than the parsed `tags`
column: tags keep the dumper's casing, and fs_name_no_ext is already in
the index.
Reordering the priority list changes which rom represents a group, so the
cached gallery sidecars are dropped when the setting changes.
Closes#1528
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
_atomic_write cleaned up in `except Exception`, which does not catch
CancelledError. Stopping a scan mid-download therefore stranded a
`.romm_tmp_*` file per cancelled transfer. Catch BaseException instead.
This also covers uploads, which have always gone through this path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YKbk4cDmdKKMcBxGmsRVT5
Streamed downloads opened the destination directly, so an interrupted
transfer truncated the file in place. A truncated file is worse than a
missing one: it still satisfies the *_exists checks, so later scans skip
it and never refetch. The error paths cleaned it up, but only when the
process survived to run them, which a SIGKILL or host reboot does not.
write_file_streamed now writes to a temp file in the destination
directory and renames it over the target once the caller's block
completes, reusing the _atomic_write helper uploads already use. The
handle closes before the rename, so the target never sees a partial
flush.
The _discard_partial_file calls that followed a streamed write are gone.
There is no longer a partial file to remove, and the target now holds
either nothing or the previous good copy, which those calls would
delete. Refreshing a cover no longer costs the existing one when the
transfer dies.
The two disk-full tests patched write_file_streamed itself, so they were
asserting against the non-atomicity this removes. They now fail the
write from the response stream and exercise the real path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 9b81fef29564d053c0ba4bb21f2192e0b9dc1f50)
Region tags now resolve only through the canonical REGIONS names and
shortcodes, so alternate spellings such as (US) or (EU) stay plain tags.
Existing rows keep whatever parse_tags wrote for them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
parse_tags only canonicalized a region or language written as a shortcode.
A tag written as a name kept the filename's casing, and a "Reg-" prefixed
code outside the shortcode table was stored verbatim, so one library could
hold "USA", "usa", "Usa" and "US" as four values. Each became its own entry
in the filter dropdowns and its own bucket in the platform stats.
Both kinds now resolve through a case-insensitive lookup, with a region
alias table for the spellings the frontend's regionToEmoji already knew
about (US, EU, EUR, JP, BRA, CHN, GLOBAL) plus WR for World.
The region pass runs before the language pass but after both exact-code
checks, because Nl/NL and No/NO differ only by case: exact matching keeps
Dutch and Norwegian, and a lowercased "nl" resolves to the region.
Migrations 0108 and 0109 rewrite rows scanned before this. They also
normalize smart_collections.filter_criteria, whose saved values are
exact-matched against roms.regions, so a collection filtering on "US"
would otherwise silently match nothing. roms_facets follows through the
triggers added in 0100.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Streaming means valid entries are consumed before the parser reaches
any damage further down the file, so a truncated or corrupt gamelist
returned whatever had been read so far. The previous full-document
parse rejected such a file outright and imported nothing.
Clear the accumulated entries when a parse error escapes both the
incremental pass and the fallback, restoring that behavior. Errors
raised while building an entry still keep what was read, as before.
Also filter the fallback path to game/folder elements so it matches the
incremental path, and hoist the lowercase filename and suffix tuple out
of the per-extension loop in exclude_single_files.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
exclude_single_files collected every excluded name into a list, then
filtered the input against it with `f not in excluded_files`. That
membership test rescans the list once per file, so a platform folder
holding tens of thousands of loose files spends most of the call in
list scans rather than pattern matching.
Decide per file in a single pass instead. Behavior is unchanged,
including for duplicate file names.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
A scan with `roms_ids` set only narrowed which roms get metadata, not the
work around them: it still listed the platform folder, re-resolved the
platform's metadata, re-hashed every firmware file, synced the whole
platform's missing-file state twice, and walked every other rom in batches
to mark it present. Rescanning one file therefore cost time proportional to
the platform, not to the file.
Resolve a scoped scan's work from the database instead, via a new
`_scan_selected_roms` that skips all of the platform-wide reconciliation.
The gamelist cache warm-up stays, since hash matching reads from it.
`refresh_smart_collections` was likewise recomputing every smart collection
across the whole library after any scan; a scoped one now uses the targeted
`refresh_smart_collections_for_roms`.
A library scan never reaches an entry whose file is gone, since it walks the
filesystem. A database-driven one does, and scanning marks a rom present
unconditionally, so the scoped path checks the path first and marks it
missing rather than resurrecting it. That check needs `directory_exists`
alongside `file_exists`, which also derives `flat`/`nested` for the `FSRom`
a library scan gets from splitting its listing.
Co-Authored-By: Claude Opus 5 <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>
Apply the same lazy-factory pattern to FSLaunchboxHandler and FSSyncHandler
that ssh_sync_handler now uses. With both opt-in features deferred to
first-use, the tolerate_missing_base escape hatch on FSHandler is no longer
needed — every handler now fails loudly on mkdir failure, which is the
right behavior for the always-on core paths (assets, library, resources).
Touched call sites:
- resources_handler._resolve_local_file_uri (launchbox)
- sync_watcher.py, endpoints/device.py, tasks/manual/sync_folder_scan.py
(fs_sync)
Net effect:
- Default installs never poke /romm/launchbox or /romm/sync at startup.
- Misconfigured opt-in users get a clear, actionable PermissionError at
the call site instead of a silent warning followed by mystery failures.
- tolerate_missing_base, its tests, and one stale log import are gone.
Importer (gamelist/launchbox file:// flows) and exporters (gamelist.xml,
metadata.pegasus.txt local exports) now hardlink media assets when source
and destination share a filesystem, falling back transparently to a copy
on EXDEV / EPERM / EOPNOTSUPP / EMLINK / EACCES (cross-device, FAT32,
exFAT, network mounts, etc.). Saves disk space and is effectively
instantaneous on large files (videos, manuals, miximages).
Covers keep a real copy (allow_link=False) because _store_cover resizes
the small cover in place via PIL.Image.save, which would truncate the
shared inode and corrupt the user's source image.
Also makes FSSyncHandler tolerate a missing/unwritable /romm/sync at
startup: an OSError from mkdir now logs a warning instead of crashing
the whole app at module-import time. Sync calls still fail at use time
if the mount remains broken — the right place to surface the error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rom.regions can contain raw filename text like "europe" or "EUROPE"
(filename parsing in roms_handler doesn't normalize casing), so the
direct dict lookup missed those tags and the locale silently fell back
to scan.priority.region. Replace the dict access with a helper that
lowercases both sides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a ROM filename carries a region tag (e.g. (Europe)), use that
region first when picking artwork and localized titles, falling back to
the configured scan.priority.region. Previously the configured priority
was the only signal, so a US-first config would force US covers onto
European ROMs even when an EU asset was available.
Adds a shared name->provider-shortcode map and threads the rom through
the IGDB and SS lookup APIs so the rom-aware locale/region selection
can run for both providers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>