Remove loader-option and query work the list endpoint discards:
- Batch the has_notes flag instead of eager-loading Rom.notes, whose
backrefs to roms and users are both lazy="joined".
- noload RomUser.user everywhere rom_users feeds RomUserSchema, which
carries no user fields.
- noload Rom.platform and Rom.metadatum in get_siblings_for_roms, where
load_only narrows columns but not relationships.
- Let callers that resolve siblings themselves skip the sibling
relationship load entirely.
- Eager-load RomFile.track_meta in get_files_for_roms, matching every
other call site.
- Order the page over bare ids and fetch rows by primary key when the rom
id index is off, instead of sorting the entity through a filesort.
- Derive the file-stat flags from the page's files when with_files is
set, instead of running three correlated subqueries per row.
- Index rom_files on (rom_id, category).
Claude-Session: https://claude.ai/code/session_01J1pbRJBY3PatzkB5skQNEU
Developer credentials are injected at build time, so a build made
outside our CI (packaged from source, e.g. nixpkgs) has none and
ScreenScraper refuses every request whatever the user account is.
The heartbeat now reports whether they are set, and the v2 metadata
sources page shows a warning banner naming the two environment
variables to set.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The LaunchBox name lookup rewrites a search term before hitting the
metadata index: " - " becomes ": ", and a trailing article is moved back
to the front. Both rewrites are anchored on literal spaces, so a dump
named with underscores reaches neither, and the folded fallback cannot
recover it either because the article is left in the wrong position.
Legend_of_Zelda,_The_-_A_Link_to_the_Past.smc missed every index stage
while its space-separated equivalent matched. Swap underscores for
spaces before the rewrites so both forms resolve to the same term.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two ways the 502 could fire on a page RomM can still read:
The hydration tag was matched by exact attribute order, so a CSP nonce or a
reordered attribute would have been reported as a rewrite. The id alone
identifies it.
`raise_for_status` lets a 3xx through, so a hop HLTB added later would reach
the parser as a page with no payload. Redirects are now followed; the client
validates every hop against SSRF, redirects included.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`ConnectTimeout` is the likely failure when HLTB is slow or unreachable, and
it is not a subclass of `ConnectError`, so it escaped `update_rom` as a bare
500 rather than the actionable 503 the other providers give.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`update_rom` fetches from every metadata provider whose ID changed, except
HLTB, which had no by-ID lookup at all. A hand-entered ID was stored and the
How Long to Beat tab stayed empty.
HLTB's API only exposes search, so `get_rom_by_id` reads the record from the
`__NEXT_DATA__` payload the game page already ships. The canonical
`/game/{id}` path is requested directly, as `/game?id=` answers with a
redirect the shared httpx client does not follow, and the game page dates a
release in full where search returns just the year.
A page RomM can no longer read raises 502 naming the cause instead of
reporting a game with no times, since that failure is otherwise
indistinguishable from the bug this fixes.
Fixes#2926
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)
Splitting on the shared separator pattern also split in-word hyphens, so
"spider-man 2" would have retried as "man 2" and invited a match on an
unrelated game. The retry fires on any rejected match rather than only an
empty result set, so it reaches that case far more readily than the Moby
and ScreenScraper retries do.
The term has already had " - " rewritten as ": " by this point, so a
series separator is a colon and any hyphen left is inside a word. Every
title the retry exists for splits identically.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A mark was dropped whenever it was not alphanumeric, and the accent strip
before it removed every mark carrying a combining class. Between them they
took the vowel signs and viramas Indic and Thai scripts spell with, so
"हिन्दी गेम" folded to "हनदगम" and titles differing only in those marks
collided.
A mark now only goes when it sits on a Latin letter, which is the case it
was meant for. Collisions across the dump are unchanged at 551 of 186505
keys, none differing in their digits, and the PlayStation 2 gain still
measures 96.7%.
Also build each game's dict once rather than per index write.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Folding to ASCII alone reduced a title written in another script to
whatever digits it carried, so "三國立志傳2" and "忍者村大战2" shared one key
and four Windows titles collapsed onto "2". Keeping every alphanumeric
character instead separates them and gives the 208 titles that folded to
nothing a key of their own.
Measured over all 187067 named games in the dump, colliding folded keys
drop from 597 to 551 and the PlayStation 2 gain is unchanged at 96.7%.
Every surviving collision is a punctuation variant of one game, and none
differ in their digits, so no entry in a series folds onto another.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
HowLongToBeat is searched with the filename, and a series prefix that one
side carries and the other does not sinks a strict similarity gate: "007:
Quantum of Solace" scores 0.838 against the catalogue's "Quantum of
Solace", just under 0.85, and a term long enough returns no results at
all. Every James Bond title on PlayStation 2 missed for one of those two
reasons.
Retry with the part after the last separator, the same recovery Moby and
ScreenScraper already make. The trigger is broader than theirs, which
only retry an empty result set: a scored-but-rejected result has to
retry too, since that is how "Quantum of Solace" fails.
Verified against the live API: all five PlayStation 2 James Bond titles
now resolve, and six subtitle-heavy titles that could plausibly match the
wrong game on a tail-only search are unaffected, because the full term
matches first.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
LaunchBox titles carry colons, diacritics and characters a filesystem
forbids that a ROM filename cannot, so an exact-key lookup misses games
the dump holds: "Burnout Revenge" against "Burnout: Revenge", "Asterix"
against "Astérix", "AC-DC" against "AC/DC".
Index every title under a folded form as well, and consult it only once
every exact form has missed so an exact hit still wins.
Measured over the 2585 Redump-style PlayStation 2 titles the dump names,
this lifts matching from 89.8% to 96.7%. All five colliding folded keys
are LaunchBox's own duplicate records for a single game.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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>
A "Reg-" prefix with nothing behind it stored an empty string as a
region. It now falls through to the ordinary tags like any other
unrecognized value.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
Review follow-ups on the region and language normalization.
Smart collections created by early versions store a single value under
`selected_region` / `selected_language` rather than a list, and
get_smart_collection_criteria still reads those keys. The migrations only
rewrote the list-valued ones, so a legacy collection kept filtering on "US"
against rows that had become "USA" and silently matched nothing. Both keys
are now handled, preserving each value's scalar or list shape.
The roms backfill also loaded every tagged row before writing anything, so
peak memory scaled with the library on a migration that runs at startup. It
now walks the table by id, holding one batch at a time. The collections pass
still reads in one go: that is one row per user-created collection.
Also strip the "Reg-" capture, since the separator class doesn't swallow a
following space and "[Reg- PAL]" stored " PAL" as its own facet value, and
add a test enforcing the REGION_ALIASES constraint that was only a comment.
Co-Authored-By: Claude Opus 5 <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
_parse_gamelist_xml read the whole file, ran two regex rewrites over it
and built a tree for the entire document before touching a single game.
On a platform with thousands of entries that tree dominates the scan's
memory, and it is discarded as soon as the per-game dict is built.
Stream top-level game/folder elements with iterparse instead, clearing
each once consumed. Measured on a synthetic 4.8 MB gamelist with 10,703
games, peak allocation drops from 33.3 MB to 3.4 MB.
ES-DE writes an <alternativeEmulator> sibling to <gameList>, which is
invalid multi-root XML that the incremental parser rejects, so those
files fall back to the previous strip-then-parse path. Entries are keyed
by filename, so re-reading elements already consumed before the failure
cannot corrupt the result.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
get_roms built a list of plain dicts for every entry, then rebuilt the
whole thing as FSRom instances and handed that to sorted(). Both lists
are alive at once, so a platform folder holding tens of thousands of
files carries two full copies plus the sorted output.
Build FSRom directly and sort in place. The nested flag is simply the
inverse of flat, so it no longer needs to be carried through an
intermediate dict.
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>
The MobyGames handler pre-encoded search terms with urllib's quote()
before passing them to MobyGamesService.list_games(), which encodes the
query itself via yarl's with_query(). Titles containing special
characters were therefore double-encoded and never matched:
'Sonic & Knuckles' -> title=Sonic+%2526+Knuckles
'... World + Bowser's Fury' -> title=...+%252B+Bowser%2527s+Fury
Pass the raw (unidecoded) term and let the service layer encode it
exactly once, matching how the ScreenScraper handler already works.
Adds regression tests for both the scan path (_search_rom) and the
manual-search path (get_matched_roms_by_name).
Same bug class as reported for ScreenScraper in #3467.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The zip and tar readers swallowed read failures and returned an empty
iterator, which the hashing path can't tell apart from an empty archive:
it falls back to hashing the container's raw bytes, so the ROM gets
hashes that match no hash database and nothing explains why.
Raise ArchiveReadError instead, as the 7z and rar readers already do, so
the fallback is logged. Member streaming is now wrapped too, since chunks
are consumed outside the reader's error handling and a bad CRC escaped as
a raw zipfile error rather than falling back.
Fixes#4159
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Hasheous has no separate Famicom data object; its NES platform (68) holds
the NES/Famicom signature sets. Without a mapping, the scan skipped the
Hasheous lookup entirely for Famicom ROMs, since it gates on hasheous_id.
Fixes#4157
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
miximage and miximage_v2 both mapped to the assets/miximages directory and to
the <miximage> tag, so the v2 art was dropped by the existing-destination
short-circuit in _copy_asset and the XML carried a duplicate tag. Route the v2
variant to assets/miximages_v2 and the <miximage_v2> tag, matching the folder
and tag the gamelist handler already reads back.
The gamelist handler discovers back covers and fanart (ES-DE backcovers/ and
fanart/ folders, <backcover> and <fanart> tags) but never recorded a local
path for them, so the gl.get("box2d_back_path") / gl.get("fanart_path")
fallbacks in both exporters could never resolve. Record those paths alongside
the media types the handler already persists, and declare title_screen_path,
which populate_rom_specific_paths already emitted.
Fixes#4128