Rename `FirmwareTemplate.platform_path` to `firmware_dir`: it returns the
firmware folder, while the same name on `StructureTemplate` returns the platform
folder. Name the watcher's index for the segment it points at.
Fold the two reads of a raw structure key into `_raw_template`, and drop the
docstrings that only restated a one-line delegation or a signature.
Remove `footer-create-summary-default`, which no component references and whose
copy still named Structure A.
Co-Authored-By: Claude Opus 5 (1M context) <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>
Testing the custom library structure against a live library turned up four
defects, all of them a path being reduced to a bare file name.
Both exporters wrote a rom's `fs_name` alone, so every game a template nests
was exported as if it sat in the platform folder: ES-DE and Pegasus could not
find any of them. They now write the rom's path relative to the platform
folder, the folder the metadata files themselves live in, and copy exported
media into the matching subfolder so two identically named roms keep their own
artwork.
Merging into an existing gamelist.xml / metadata.pegasus.txt keyed entries by
file name too, so identically named roms in different folders both merged into
the first entry and produced duplicates. Entries are now keyed by path, with a
Pegasus block matched by the folder its listed files sit in.
Reading a gamelist.xml had the same collision: two roms sharing a file name
both took the metadata of whichever entry was parsed last. A rom's own path now
wins, and a bare file name stays a fallback key for the tools that write those,
dropped when two entries share it.
Default discovery surfaced hidden folders as multi-file games, unlike
structured discovery which skips them. exclude_multi_roms now owns that rule
for both.
Also validate `exclude`'s exclusion_type: an unknown value reached
`Config.__getattribute__` and returned a 500 rather than a 422.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Each worker started with --with-scheduler forks a scheduler that logs
"Scheduler sending heartbeat to <queues>" on every 1s tick. With
LOGLEVEL=DEBUG that is two lines per second, which drowns out the rest of
the log.
Generalize the existing registry-cleanup filter to cover RQ's periodic
noise and install it on the rq.scheduler logger before the worker forks
the scheduler off.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A grouping folder is no longer also a game. With `{gameDir}` and
`{category}/{gameFile}` declared together, the category folder was surfaced
as a multi-file game *and* descended into, listing its contents twice. A
folder any template descends into is now treated as a grouping level.
Relocation runs for every platform, not only those with a custom structure.
Dropping a platform's template moves every game back to the platform root,
which previously read as a library of new games and orphaned all the saves,
play history, favorites and collection membership. A library whose paths are
unchanged still costs one query and no hashing. This also removes the need
for a manual "apply relocation" toggle.
Physical games are excluded from relocation candidates: they have no file, so
they read as having disappeared from their path on every scan.
A near-miss on the terminal macro (`{gameFolder}` for `{gameDir}`) now names
the offending section instead of only reporting a missing terminal.
Documents two limits the QA pass asked about: a move that also compresses or
extracts the game changes its size and is not detected (the size pre-filter
runs before hashing), and how reverting to the default layout behaves.
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>
The genre/franchise/company/publisher/developer/collection/age-rating/
player-count filters read from `roms_metadata`, but the join was added at the
end of `filter_roms`, after the "Group ROMs" block had already derived its
dedup window from the query. The window therefore filtered on a table it never
joined: the database cross-joined `roms` against `roms_metadata` (a view over
`roms`), which SQLAlchemy reports as a cartesian product.
Besides the cost, the window then ranked every ROM in the library rather than
the matching ones, so a game whose matching version was not the group's primary
one disappeared from the gallery entirely.
Fixes#4389
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A tripped breaker answers in ScreenScraper's place, so the empty match it
produces is not a miss and must not clear the rom's stored ss_id. The scan
learned that by sampling the module-wide is_breaker_tripped() at three points,
which reads another rom's trip as this rom's evidence.
SSHandler now raises ScreenScraperExhaustedError instead of swallowing the
breaker's error, carrying the match it would have returned so the name the
filename lookup derives locally (Switch title database, MAME, PS2 OPL) still
reaches the scan. fetch_ss_rom catches it the way it already catches
ScreenScraperRateLimitError, and drops ScreenScraper from attempted_sources
from a plain local, so the signal is exactly this rom's own lookups.
Also folds in a cleanup pass over the branch: the dead default_factory arm in
_ScanState.reset(), one home for the ssuserInfos.php path, asyncio.wait_for
around the quota probe so it cannot block behind a media download holding the
concurrency slot, and shared fixtures for the ScreenScraper tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A game added today had no edges until the 5:30 AM rebuild, so its "Similar
games" section was empty and nothing could reach it from a feed.
`build_for` scores a handful of ROMs against the current library instead of
sweeping every pair, and folds them into the stored neighbour lists of the
games they matched so the new game is reachable from both directions. The
full build is the same sweep with every ROM as a target, so the two paths
share one implementation rather than drifting.
The scan hands over the ids it wrote. Past MAX_TOP_UP_ROMS the incremental
path saves nothing, so that case queues a rebuild rather than blocking the
scan on work a rebuild would redo.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-play and co-collection were a bare cosine, which saturates at 1.0 the
moment two games are always seen together. On a single-user server, the
common case, that is every pair of games the owner has played: the signal
became a flat +0.15 on all of them rather than something that discriminates
between them, and a genuinely similar unplayed game needed a content score of
0.273 just to draw level. Tetris and Madden were neighbours.
The cosine is now damped by the number of sightings behind it, the way
`get_fallback_rom_ids` shrinks a rating toward the mean by its vote count. A
lone sighting keeps a quarter of its weight, which leaves it under
MIN_EDGE_SCORE on its own, while a pair a whole server agrees on is untouched.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
0123 appends steam_metadata to the generated facet chains, but every test
seeded its library through igdb_metadata, so nothing held the wiring in
place: a Steam-only game reaching roms_facets, and the builder indexing it,
were both untested. Both assertions fail when the blob is written to a
provider the chains do not list.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Merge 0123/0124/0125 into one migration. Each added STORED generated
columns to `roms`, and 0125 already dropped and re-added several, so
upgrading rewrote the widest table three times and restated the
`roms_metadata` view three times. One ALTER TABLE now carries the Steam
rebuild, the three IGDB tag columns and the rating count, and the view is
recreated once. Verified upgrade/downgrade/upgrade on MariaDB and Postgres.
Score each unordered pair once. Candidate generation is symmetric, so
every pair had its dot product computed twice. The sweep now runs in
ascending id order and scores only from the lower id, which also makes a
ROM's edges final the moment the sweep passes it, so the incremental
flush survives. Only the target's quality bonus differs by direction, so
one content score is blended twice. The per-ROM candidate ceiling moves
into `candidate_ids`, taking the rarest posting lists first, where it
bounds work instead of being applied after the cost was already paid.
Read identity off one list. `sibling_roms` decides "same title" from
seven provider ids; the suppression here used two, so a pair matched only
by MobyGames was a sibling everywhere else in RomM and a recommendation
for itself here. `IDENTITY_ID_FIELDS` on the model is now the one home,
consumed unscoped by the builder since a reissue on other hardware is no
more a suggestion than a second copy on the same platform.
Make the facet vocabulary a StrEnum. It was spelled out in five places,
two of them already stale, and `facet: str` kept it out of the API
contract, so an unmapped facet silently rendered a raw value. It reaches
OpenAPI as a closed union and the frontend maps are keyed by it, so
adding a facet now fails the typecheck until the UI handles it.
Give each surface one serving entry point. `similar_roms` and
`recommended_roms` own the over-fetch, hydration, visibility filter,
series cap and cache that the two endpoints and the inspection tool each
re-implemented with three different over-fetch constants; the cache moves
in with them so no caller can rank a feed without populating it.
Endpoints now do ORM-to-schema only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three tests reached the public internet on every CI run. `test_update_rom`
posts an igdb cover url and never mocked `get_cover`, so the fetch went out;
the two lock tests do the same with a manual url. The fix for the manual is
not just a decorator: `test_manual.py` patched `get_manual` on the
`fs_resource_handler` singleton with `monkeypatch.setattr`, and monkeypatch
restores by *setting* the bound method back as an instance attribute, which
then shadows a later class-level `patch.object` for the rest of the worker's
run. `mock.patch.object` deletes instead, so the patch in test_rom.py now
takes effect. Same change for the other singleton patches in that file, which
leak the same way.
The placeholder host moves to www.screenscraper.fr. `ss.fr` is a live
domain-parking host, unrelated to ScreenScraper, and the update path appends
`ssid` and `sspassword` to the url before fetching it.
The suite now makes no outbound request at all, bar the two ssrf tests that
exercise the rejection hook.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backend, wasted work:
- `_score_one` computed `content_similarity` twice per candidate on the
trim path and built `shared_reasons` for every candidate clearing the
score floor, discarding almost all of them. Compute content once and
build reasons only for the edges actually stored.
- `get_feature_rows` outer-joined `RomMetadata`, a view over the wide
`roms` table, defeating the point of reading the narrow facet mirror.
Read the generated columns off the `Rom` join already present.
- Feed cache invalidation ran a keyspace SCAN on every `rom_user` write.
Put graph and per-user version counters in the key so it is one INCR,
matching `invalidate_filter_values_cache`.
Backend, reuse:
- Route the five name comprehensions beside `_expanded_names` through it.
- `_recency_factor` reimplemented `to_utc`.
- `replace_similarity_edges` hand-rolled `itertools.batched`.
- Derive `TASTE_FACETS` from `FACET_WEIGHTS` instead of restating its keys.
Backend, dead code:
- `ScoredNeighbour`, `BuildStats.to_dict`, `delete_all_similarity_edges`,
the unread `difficulty`/`completion`/`backlogged` affinity fields,
`FACET_ORDER` and `RomInfo.rom_id`, and a no-op `column_type` ternary.
Frontend:
- Extract `RecommendationReason` from the two byte-identical copies in
`Home.vue` and `SimilarGamesGrid.vue`, dropping the repeated
`primaryReason` calls and their non-null assertions.
- Cap the caption with `--r-card-art-w` rather than a `158px` literal that
does not track the per-breakpoint card width.
- Key the similar-games fetch on the ROM id: `watchEffect` refetched on
every optimistic mutation of `currentRom`.
- One home for the similar-games limit.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The pytest job went from ~5 to ~21 minutes. Nineteen streaming tests take
60-66s each on a runner because they connect to a fake broker for real: a
workstation answers "unreachable" at once, a runner drops the packets and
the test burns the whole socket timeout (60s for a transfer, 120s for a
disc swap). One rom test fetches a manual from ss.fr the same way. Reading
the -vv timestamps out of the CI log, test_streaming.py alone accounted for
1250s of 1997s, and the job sat on a single worker for 1236s while the
other three finished in four minutes.
Refuse connections outside loopback, so a missed mock fails instantly with
the OSError the code already handles. Alongside that, three costs the fix
exposed: bcrypt runs 1670 times per suite for three constant fixture
passwords, the save-pull tests sleep out a retry backoff they don't assert
on, and the chunking test opens a thousand transactions to reach an id
count.
Under CI settings locally: 264.6s -> 61.8s, same 3977 passed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Resolve conflicts in the v2 Home view and its test: keep both the
recommendations row from this branch and the live multiplayer sessions
row from master.
Master added migrations 0119 through 0121 that forked the Alembic chain
against this branch's 0119 through 0122. Renumber this branch's
migrations to 0122 through 0125 so they chain after 0121_state_disc_file.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9EiQ8VWDJfzhEViDdj84d
HTTP 431 means a ROM did not match and the daily cap on proposing unknown
ROMs for review is reached; scraping is unaffected, so it becomes a
not-found with one informational line per scan instead of a refusal that
takes the provider out.
HTTP 431 is really two answers at once and only one of them concerns the
scan. The scrape allowance (430) still trips a breaker, since every
remaining ROM would otherwise cost a round trip to be told the same thing,
but it now arms only after repeated refusals, ignores the ones already in
flight when a refusal was counted, and re-checks the free account endpoint
so it recovers without a scan to reset it. The account check can no longer
arm it at all.
A recoverable breaker can clear itself while a rom is still gathering its
other providers, so a complete rescan read it as having answered and wiped
the rom's id. It is now sampled where ScreenScraper is consulted.
The manual-match search gathers every provider without return_exceptions,
so it now swallows an exhausted ScreenScraper the way the scan lookups do.
Fixes#4123
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Conflicts and how they were resolved:
- `useGameActions`: master renamed `useCanPlay`'s `canPlay` to `canPlayLocal`
and kept a local `canPlayStream`, while this branch moved `canPlayStream`
into `useCanPlay` and folded it into `canPlay`. Kept this branch's shape and
took master's `useScanTrigger()` call.
- `Player/Stream.vue`: kept this branch's force-release and session-poll block,
and re-placed master's `useUnloadGuard(sessionActive)` next to the
`sessionActive` watch.
- `locales/*/play.json`: kept both sides' keys, re-sorted.
- `__generated__/index.ts`: kept both sides' model exports, re-sorted.
- `test_config_loader.py`: kept both sides' tests.
Master took 0114 through 0118 while this branch was open, so its three
migrations are renumbered 0119-0121 and rechained after
`0118_rom_category_cheat_pg`, leaving alembic with a single head.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The same 503 was built inline at seven sites across the metadata handlers, and
the previous commits added two more copies of it as per-handler `_unavailable`
helpers. `base_handler.unavailable(provider)` now builds it for all of them.
Also renames the search endpoint's cover filter to say what it does and types
the scan test's lookup factory.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Every gathered provider already resolved through a single loop that logs the
failure, drops the source from the attempted set and falls back to an empty
match. SteamGridDB, which searches on the names the other providers produce and
so cannot join that gather, hand-wrote the same three steps again, and the
search endpoint hand-wrote a third copy. Extract the loop body into
`resolve_fetch` and route SteamGridDB through it.
In the search endpoint the cover gathers now tolerate exceptions instead, so a
failed lookup costs a thumbnail rather than the whole result set. That also
covers Libretro, whose lookup had no guard at all and could fail the request.
On the test side, the platform, rom and `fs_rom` scaffolding was written out
three times across the two scan tests; it now lives in `tests/handler/scan_stubs.py`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`_request` swallowed a non-404 HTTP error and a timeout into an empty dict,
which `lookup_rom` then reported as conclusive: Hasheous answered and knows
nothing about these hashes. A 500 or a timeout therefore de-verified a rom on
a rehash and cleared its id on a complete rescan.
Both paths now raise, so the conclusive flag already carried by `lookup_rom`
tells the two empty matches apart on its own.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Batocera, RetroBat and ES-DE all ship an `easyrpg` folder for RPG Maker
2000/2003 games, but RomM had no platform for them, so the folder fell
through as an unmatched platform that matched no metadata.
Add UniversalPlatformSlug.RPG_MAKER and wire it to the two providers that
carry the platform: ScreenScraper (system 231, "EasyRPG") for metadata and
libretro (system "RPG Maker") for thumbnails. IGDB, MobyGames and TheGamesDB
have no RPG Maker platform, so they stay unmapped, the same way DOOM is
wired.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A complete rescan clears the id of every source it consulted that came back
empty. That reads an outage as a conclusive miss for the providers that report
a failure as an empty match, so a rescan run while one was down wiped the id it
would otherwise have confirmed, hand-set ones included.
Each of those now reports the failure and leaves the tolerance to the caller,
which is what the gather loop's discard already assumed:
- Pouët, CSDb and Demozoo stop swallowing the 503 their own `_request` raises,
and Pouët's title search raises it rather than answering "no unique title".
- SteamGridDB and Flashpoint stop catching `Exception` around a whole lookup;
HLTB stops catching it around its search.
- ScreenScraper answers empty for every remaining ROM once its daily-quota or
credentials breaker trips, so the scan reads that state off the service and
drops it from the sources the rescan may clear.
SteamGridDB resolves outside the gather and so needs the discard at its call
site. Search keeps degrading to no thumbnail, since its cover art sits on top
of matches the other providers already produced.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A complete rescan is documented as wiping every external id and matching
again from scratch, but it only wrote NULL for deselected sources. Selected
ones were assumed to reset implicitly by staying out of rom_attrs, which
merge then skips rather than nulling, so a provider that searched and found
nothing left its old (wrong) id in place.
Track the sources whose lookup actually ran and clear those too. A source
skipped because the platform carries no id for it never enters the set, so
hand-set ids on unmapped platforms survive, and a provider that raised or
hit the ScreenScraper rate limit is discarded again since it ruled nothing
out. SteamGridDB resolves after the reset block, so it clears its own id.
Fixes#4346
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Nothing failed if the cache filename went back to ra_hashes_v2.json, which
would leave upgraded installs serving the unfiltered index until its mtime
aged past REFRESH_RETROACHIEVEMENTS_CACHE_DAYS.
Back the resources directory with a real temp directory so the freshness
check reads a real mtime, and assert a v2 index on disk is refetched rather
than reused.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The hash index was built with RA's f=0, so it mapped hashes of games that
exist on RetroAchievements but have no achievements. Those ROMs came out of
a scan with an ra_id set, which lit up every RA signal (achievements tab,
match chip, has_ra filter, smart collections) while answering the only
question those signals are asked: no, there is nothing to earn here.
Measured live against N64 (system 2), 45% of indexed hashes pointed at
set-less games; NES and PlayStation are above 60%.
Switch to f=1 and bump the cache filename, since the freshness check is an
mtime test and installs would otherwise keep the stale index for up to
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS.
Fixes#4343
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both CI failures came from one import cycle. RQ could no longer resolve
`endpoints.sockets.scan.scan_platforms`, and the e2e seed script failed the
same way, because `sigil` imports the platform slug enum, importing anything
under `handler.metadata` runs its `__init__`, that reaches `gamelist_handler`
which imports `handler.filesystem`, and `roms_handler` there imports `sigil`
back while it is still half-initialised.
The cycle predates this branch. It stayed hidden because `scan.py` reached
the enum through `utils.switch`, imported late enough that
`handler.filesystem` was already loaded; naming the adapter directly moved
that import to the top of the module and the ordering luck ran out.
So the enum moves to `utils/platform_slugs.py`, which imports nothing but
`enum`. Naming a platform no longer drags in httpx, redis and the titledb
task, and the 29 call sites point at the module that owns it rather than
picking it up from a 1000-line metadata handler that happens to re-export
it. `import adapters.services.sigil` now also works on its own, which it
did not before.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three problems the review pass turned up, all in the title id path.
A HASHES rescan re-reads every byte but `_should_extract_title_ids` only
exempted COMPLETE, so replacing a file in place left the previous binary's
title id and save target beside the new hashes. That row is
self-inconsistent, and the stale save target points saves at the wrong
game's folder. A scan that re-reads the bytes now re-reads the id too.
`refresh_rom_files` extracted title ids and then dropped `parsed.identity`
on the floor. Since only Switch populates `content_type`, the parse of every
changed file on PSP, PS2, PSX, Wii and the rest had no observable effect at
all, and a rom with no stored id never gained one from a quick scan or an
upload. The identity it reads is now persisted, guarded so a parse that read
nothing leaves the stored triple alone.
The Tinfoil feed keyed its titledb index on `str(index_entry.get("nsuId"))`
and then tested that for `None`, which `str()` had already turned into the
string "None". Entries without an nsuId were stored under that literal key,
each one overwriting the last, instead of being skipped.
Also revert the heartbeat to `cm.get_config()`. Reading the last-parsed
config avoided a YAML re-parse, but the same request already triggers
several through `get_platforms()`, so it bought nothing and left the
endpoint reporting a stale flag after a config edit.
`tests/endpoints/feeds.py` is renamed to `test_feeds.py`. It never matched
pytest's `test_*.py`, so all 15 feed tests, `test_tinfoil_feed` among them,
have been dormant since they were written.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The Tinfoil feed was left behind when `_switch_productid_format` changed
from taking a `re.Match` to taking a `str`, so `/feeds/tinfoil` raised a
TypeError for any Switch rom carrying a product id in its filename but no
titledb id. It went unnoticed because `feeds.py` sits outside the changed
files mypy sees.
That call site was reachable only because "prefer the id the scan read over
the one scraped from the filename" lived in a second helper above the lookup,
leaving each caller to remember it. The resolution now happens inside
`_switch_productid_format`, so the three providers and the feed all get it
without repeating a preamble.
Also:
- Move `SWITCH_PLATFORM_SLUGS` to the sigil adapter so `utils/switch.py`
stops importing the metadata base handler. The cycle that import created
was papered over with a function-local import, and `normalize_identity`
now takes the fact it needs rather than the whole slug set.
- Merge a partial identity update onto the stored identity before
normalizing it. Normalizing rewrites the whole triple, so a client sending
only a title id was getting the derived base id next to its old save
target.
- Add `RomIdentity.from_rom` so the triple has one home on the read side
too, and drop `asdict` from `as_rom_attrs`.
- Hold the `SigilExtractionResult` on `TitleIdEmbedCandidate` instead of
copying two of its fields.
- Drop a guard in `_rom_level_identity` that could not fire, derive once in
`normalize_identity`, and return only the parse from `_rebuild_rom_files`,
which already owns `fs_rom["fs_name"]`.
- Read the parsed config in the heartbeat rather than forcing a YAML
re-parse per request, and make `SigilService.is_enabled` a classmethod
like every other one.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The platform sync clears `missing_from_fs` before the batch loop runs, so
a rom being scanned can no longer tell that it was missing, and the fold
left the skip path (which could tell) unreachable for a quick scan. A rom
whose file came back byte for byte therefore emitted nothing and kept its
stale badge. Collect the restored roms from the snapshot the loop already
takes, for the ones it visits as well as the ones it skips.
Cleanups on the same paths:
- hoist the quick reconcile above the metadata prelude it never reads,
which was a config file parse and a tag parse per rom
- drop the unreachable quick clause from `_should_hash_incrementally`:
`refresh_rom_files` owns that policy
- drop `RomFilesRefresh.files`, which nothing reads
- take the refresh lock without a guard that had nothing to protect
- fold the single-caller upload destination helpers into one
- give "a quick scan needs no metadata source" one home, and read the
refresh title from the key rom.json already owns
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The refresh lists a rom folder and then deletes every row the listing
missed, so two uploads completing at once could let the slower listing
drop the file the faster one had just registered. Hold a per rom lock
across the listing and the sync.
Three smaller fixes on the same paths:
- honour SKIP_TITLE_ID_EXTRACTION, which the refresh read the hash flag
but not this one for
- emit a rom that just stopped being missing even when its files did not
change, so an open gallery drops the stale badge
- unlink the empty destination claim when the rename meant to replace it
fails, rather than leave a zero byte file for the next scan to ingest
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backend:
- Drop the HashPolicy enum: FULL had no caller and INCREMENTAL was the
default, so refresh_rom_files uses the existing_files knob directly.
- Narrow RomFilesRefresh to the counters callers read.
- Build ParsedRomFiles once so the incremental return stops dropping the
title id fields.
- Give the assembling suffix one home in config, read by both the
assembler and the scanner's excluded extensions.
- Fold the duplicated destination collision check into one helper, and
branch /start on the upload target itself.
- Load the lighter rom for the refresh emit and the upload endpoints,
keep the flat file stat off the event loop, and reuse the directory
listing for the RA hash lookup.
Frontend:
- Route the platform scan dialog and the scan view through
useScanTrigger, so a scan started while one runs is refused rather
than emitted and rejected by the backend.
- Rename the socket payload type to ScanRequest, away from the
useScanProviders type of the same name.
- Drop the dead uploading prop and folder icon, reuse singleRomTitle,
and resolve each file's relative path once per listing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The rebase put the branch's keyword-only `existing_files` alongside
master's title id flags, and mypy resolves a `**dict[str, bool]` against
every parameter, so the bag no longer type checks. Name the two flags the
cases actually vary.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
With SKIP_HASH_CALCULATION the listing carries no hashes, so a top-level
change would have blanked the ROM's CRC, MD5, SHA-1 and RA identity. The
stored values now outlive the refresh in that mode.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
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
Cuts the rationale that had grown past two lines, and drops the wording
that described the change rather than the behaviour: a scan on one of the
other queues is one an older release enqueued, not one from "before scans
had their own queue".
The result_ttl note moves onto the argument it explains, and in the
entrypoint the log line moves next to the call it announces rather than
sitting above the function definition.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Master replaced rq-scheduler with RQ's own cron and a task registry, so
the recommendations task moves from startup.py and the endpoint's task
list into tasks/registry.py, is surfaced through VISIBLE_SCHEDULED_TASKS,
and drops the func path and unschedule call the old base class needed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The dispatch job was hidden from the task list by a meta flag the endpoint
had to look for on every job in every queue and registry. RQ already has
the rule the flag was implementing: `result_ttl=0` deletes a job the moment
it succeeds, while a failed one still lands in the failed registry under
its own TTL. Registering the scan entry with it drops the marker, the
predicate, its four filter sites and the two Redis reads each one cost.
The concurrency guard is now one call. `get_blocking_library_scans()` says
which scans a second one has to wait for, so the socket handler no longer
assembles that rule out of two helpers in two shapes, and `ALL_QUEUES` sits
with the queues it lists rather than in the API layer.
Also merges the finished and failed registry sweeps, which were the same
loop, trims comments that explained the design rather than the code, and
drops two socket tests that duplicated their neighbours.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Master landed #4274 with the review changes that came out of it, and those
moved the code this branch was built on. Scan job bookkeeping now lives in
`handler/scan_jobs.py`, every enqueue goes through `enqueue_task`, cron
entries carry their own name and result TTL, and the watcher builds its two
rescans from one helper.
Resolved by putting this branch's changes where that code now lives:
- The scan queue, the scoped-scan check and the second scheduled registry
moved into `handler/scan_jobs.py`, keeping master's single-round-trip
reads (`get_job_ids` plus one `fetch_many`, and `get_jobs_to_schedule`
for the stale sweep) across both registries.
- `enqueue_scheduled_scan` sits next to `enqueue_task` in the registry and
is built from it, rather than hand-rolling the same enqueue in
`tasks/tasks.py`. Its tests moved with it.
- Cron keeps master's per-entry name and result TTL, and adds the scan
dispatch on top: `TASK_TIMEOUT` for the dispatch, the task's own timeout
(now `SCAN_TIMEOUT`) for the scan it enqueues.
- The watcher's `schedule_rescan` helper enqueues on the scan queue with
the abandoned-job callback.
- `PeriodicTask.func` is gone from master, so the scheduled rescan declares
only its timeout. `tasks.registry.enqueue_scheduled_scan` joins the func
paths an RQ worker has to be able to import.
- The job stubs shared by the discovery tests grew the scan queue and a
scoped-scan job; the duplicated stale-sweep tests are master's.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>