Commit Graph

13 Commits

Author SHA1 Message Date
Sam Dornan
130ea73c23 perf(metadata): compress the cache-only metadata dump records (#4426)
* perf(metadata): compress the cache-only metadata dump records

The LaunchBox and Switch TitleDB stores are read by exact key and never
scanned, so each value can be compressed on its own. On a full import of
both real dumps into the bundled valkey, `used_memory` drops from 539.1MB
to 335.9MB and RSS from 553.3MB to 350.2MB, a 38% saving.

Values are zstd level 3, which costs 3-6us per record read, less than the
`json.loads` that follows it. A payload under 256 bytes is stored as plain
JSON: below that a frame header and a poor ratio on a short payload cost
more than they save, which is what leaves the id-valued title and product
id indexes untouched. `tools/measure_dump_cache.py --sweep` finds the real
records flat between 64 and 256 bytes.

Reads detect the zstd frame rather than trusting the key, so a store
written by an earlier import keeps answering until the next update
rewrites it. No re-import is required to upgrade.

A zstd frame is not UTF-8, so the dump keys move to a cache client that
leaves values as bytes. `async_cache` still serves everything else,
including the existence checks on these keys.

The new tool measures per-store size with `MEMORY USAGE ... SAMPLES 0`,
which walks every field. The default of five samples extrapolates, and on
a hash of this size it is wrong by enough that per-key figures stop
adding up to `used_memory`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* test(metadata): assert the writer stores through the dump codec

`test_values_are_json_encoded` pinned the exact string `json.dumps`
produced with default separators. The writer now hands the pipeline
compact bytes from `encode`, so the test asserts the contract that
matters instead: the value is bytes, and it decodes back to the record.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): stop the dump measurement wiping the whole cache server

`flushall` between passes would erase every database on whatever
`--redis-url` names, and RomM's sessions and RQ queues share that
database with the dump stores, so pointing the tool at a live instance
cost far more than the stores it meant to reset.

It now deletes only the ten keys it writes, and refuses a server holding
anything else unless forced, since a running RomM would have to
re-import what it drops. Each pass records what the server uses without
those stores and reports figures net of it, so a non-empty server still
measures what the dumps themselves cost.

Reported by Greptile on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): report field counts and bytes off the stores, not the writes

Two accounting errors in the measurement tool, both reported by Copilot
on #4426.

Field counts and byte totals were tallied while writing, so they counted
write attempts. `HSET` overwrites, and the dump repeats a title on one
platform and an alternate name across platforms, so 8,997 of the writes
landed on a field another record already held: the alternate name store
reported 70,297 fields against 62,384 actually stored. Both figures now
come from `HLEN` and a scan of each hash, which cannot drift from what
the store holds.

`used_memory_rss` was offset by a `used_memory` baseline, mixing two
metrics. Netting RSS turns out to be wrong however the baseline is
captured, because the pages a delete frees stay resident, which made the
encoded pass report -56.1MB. RSS is now reported absolute, and `--only`
loads a single encoding so it can be read off a server started fresh for
that pass: 555.8MB plain against 348.9MB encoded, measured that way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style(tools): cut the measurement tool's docstrings to the repo's limit

CLAUDE.md allows a docstring one sentence plus `Args:`/`Returns:`, and the
module docstring ran to four paragraphs. The non-obvious reasons move to
one-line comments at the code they explain, which is where a reader needs
them, and the operational detail was already carried by `--force` and
`--only`'s help text and by the refusal message itself.

Reported by Copilot on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): fold titles the way production does, and stop echoing the URL

Four more Copilot findings on #4426, three of them in the measurement tool
and one in the codec module.

The folded-title stand-in kept only ASCII alphanumerics, the exact thing
`fold_title`'s docstring warns against: it reduced `Astérix` to `astrix`
and `三國立志傳2` to `2`, and dropped titles that fold to nothing, so the
folded index measured smaller than it is. The tool now mirrors
`fold_title` character for character, verified against the real function
extracted from its module over 40,000 dump titles with no mismatch. The
store grows by 244 fields and 0.1MB, so the totals barely move.

The refusal path printed the target URL, which RomM builds with the
password inline, so it could have carried a credential into a CI log. It
now names the server generically and keeps the key count and the remedy.

`dump_cache`'s module docstring and its threshold comment both ran past
the one-to-two-line limit in CLAUDE.md. The benchmark numbers behind the
threshold live in the PR description, not the source.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* refactor(cache): give the dump store keys one home

The measurement tool carried its own copies of the ten store key strings,
against the single-source rule in CLAUDE.md. That matters more now the
tool deletes those keys: a production rename would have left it deleting
stale hashes, missing the new ones, and counting the real stores as
foreign data in its own safety guard.

The keys move to `handler/dump_cache.py`, which already holds the codec
that reads and writes them and depends on nothing but the cache client,
so the importers, the lookups and the tool all take them from there.
`DUMP_STORE_KEYS` is the list the tool measures and clears.

`base_handler` was reaching into `tasks/scheduled/update_switch_titledb`
for two constants, so a handler depended on a task module; that import is
gone. `launchbox_handler/types.py` keeps the initial-import flag, which
marks an import in progress rather than naming a store.

Measurement is unchanged: 538.0MB to 334.8MB, per-store figures identical.

Reported by Copilot on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tests): import the store keys from where the merge left them

Two test modules still took the keys from `handler.dump_cache`, which the
merge emptied of them, so collection failed with an ImportError on both
databases and mypy flagged nine missing attributes. They read them from
`launchbox_handler/types.py` and the TitleDB task now, as the code does.

Also reverts formatting the merge dragged into four files this change has
no business touching: running isort over everything the merge listed
reclassified `tests.*` and `startup` out of the block master keeps them
in, and black rewrote two `except (A, B)` clauses into the unparenthesized
form. Those files go back to master's copy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style(tests): restore both metadata test files to master's formatting

Running the formatters over everything the merge touched had reordered
imports trunk keeps in another block. Both files go back to master's copy,
with the compressed-store read test re-added by hand and its import placed
in the first-party block where the other `handler.*` imports sit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): report bad input rather than dividing by zero

A zip with none of the four XML files loads no records, and every ratio
the report prints then divides by a zero total.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* refactor(tools): match the yields to their siblings, type the serializer

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style: trim the comments and tighten the names review-polish flags

Cut the version notes to what version 2 is, drop the two comments that
repeated a neighbour, rename the tool's `measure` to `store_memory` beside
`store_stats`, and annotate the codec tests' parametrized arguments.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 16:09:32 -05:00
Georges-Antoine Assi
decd5c61c4 refactor(cache): make the versioned store a type rather than three constants
The schema key, its version and the keys they cover were three constants per
store, retyped at each of the six places that used them and interchangeable
enough that one store's version could be checked against another's keys. They
are a `VersionedCacheStore` now, so a store is declared once and the startup
drop is a loop over a table.

The two reader gates were the same four lines, and a third read path was
still checking the data key without the stamp, so the LaunchBox entry points
disagreed about what populated meant. All three call one helper.

The drop probed each key before deleting it, spending a round trip per key to
learn what `unlink` reports anyway, and `delete` freed the store on the main
thread. Both imports also merge into their hashes, so each now drops a stale
store itself rather than trusting the drop to have happened at startup.

The alternate name index holds the bare id its reader wants, like the two
title indexes beside it, and follows through the same helper.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 16:10:09 -04:00
Georges-Antoine Assi
721197476a perf(metadata): rebuild a metadata store an older release wrote
The readers tolerated both the old and the new shape of every index this
branch changed, which left two shapes supported forever and, on an install
whose scheduled update is off, meant the old store answered every lookup
and the saving never landed at all.

Each store now carries a schema stamp. A store whose stamp is missing or
stale reads as unpopulated, is dropped at startup, and has its import
queued the way the WebP backfill is, so the shape change causes the
rebuild instead of being worked around. The readers know one shape again.

The projection each store is written with moves next to its key, and the
three stores that had none get one: Mame.xml kept 24 fields per record to
serve `Name`, Files.xml kept the platform and filename its cache key
already carries, and an alternate name entry kept the name it is stored
under. Together with the image list that is ~135MB.

Measured against the real dump: the eight LaunchBox hashes hold 385MB, and
a store stamped by an earlier release is dropped at startup for 386MB of
`used_memory` reclaimed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 15:45:32 -04:00
Georges-Antoine Assi
13aaf54921 docs(metadata): trim the cache index comments to the fact each carries
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 13:19:30 -04:00
Georges-Antoine Assi
ea44dfd9cf refactor(metadata): fold the index follows into one lookup each
The title index reader now takes the key and field it reads, so the two
call sites lose their intermediate hit variable, and the alternate name
path follows its id through `get_by_id` like the other two. The Switch
titleID read is shared between the two lookups that do it.

The LaunchBox import reads the `Game` fields with `findtext`, and the
Switch import queues both indexes from one pass over the batches. The
image projection moves next to the `LaunchboxImage` type it fills.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 13:17:44 -04:00
Georges-Antoine Assi
d4f3d8be83 perf(metadata): stop storing the metadata dumps twice over in the cache
The LaunchBox import wrote the whole game record into three hashes: once
under its database id, and again under its title and folded title. The
Switch TitleDB import wrote every entry twice, once per id it is looked up
by. Both title indexes and the product id index now hold the id of the
record they point at, and the reader follows it.

Image lists also carried a `DatabaseID` repeating the field they are stored
under, plus a `CRC32` no lookup reads.

Measured on a full import of both dumps into the bundled valkey:
941MB -> 466MB of `used_memory`.

An index written by an earlier import still holds whole records, so a
lookup keeps answering off it until the next update rewrites the store.

Fixes #4395

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 20:25:42 -04:00
Sam Dornan
6ce0a2f528 fix(launchbox): match titles differing only by punctuation
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>
2026-08-17 16:51:42 -05:00
Sam Dornan
94f6b16ec1 fix(launchbox): match dump filenames against the metadata store
LaunchBox lookups are exact key reads, so a filename that doesn't already
read like a LaunchBox title misses. Three gaps closed:

- No-Intro inverts leading articles ("Legend of Zelda, The - Ocarina of
  Time"), LaunchBox keeps them in front, so the de-inverted form is now
  tried against the name and alternate-name indexes as well. Measured over
  the No-Intro sets: N64 unmatched 200 -> 171, SNES 461 -> 318, Genesis
  285 -> 191, GBA 683 -> 576.
- Files.xml, a filename-to-title index the dump already ships and the
  update task already caches, was never read by any lookup. It now runs
  ahead of the name search, which is the only route to titles whose files
  are named nothing like them (MS-DOS, Amiga, Arcade). Its cache key gains
  the platform, since the same dump filename exists on several systems.
- A local LaunchBox install was only reachable by an exact filename,
  extension included, or by a stem equal to the title. A library of `.zip`
  archives could never match an install pointing at `.z64`, and a No-Intro
  stem still carries region tags. Both sides now reduce to shared forms.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:50:24 -05:00
Georges-Antoine Assi
52940ea3d4 fix(launchbox): stop the cloud provider from silently matching nothing
LaunchBox cloud lookups read from a Redis store that only the metadata
update task fills, but nothing surfaced when that store was empty. The
provider reported healthy, every search returned zero results, and the
logs said nothing.

- heartbeat now reports unhealthy until the store is populated, and an
  empty store logs what to set to fix it
- the update task can be run manually whenever LAUNCHBOX_API_ENABLED is
  on, instead of also requiring the scheduled-update flag
- the ~600k entry dump was buffered into a single pipeline, peaking at
  1.7GB of RSS and writing nothing at all if the job was killed part way
  through. Writes now go out in batches and parsed elements are dropped
  as they are consumed, which caps the run at ~260MB. The task also gets
  its own timeout, since the default 5 minutes does not cover a 100MB
  download plus a 500MB parse
- alternate name lookups ignored the platform, so "Super Mario World" on
  PlayStation matched Super Mario Bros.
- Coleco ADAM was spelled wrong, and Famicom / Super Famicom pointed at
  platform names LaunchBox does not use

Fixes #3981

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 19:55:16 -04:00
Georges-Antoine Assi
90945685e4 Stuff 2026-05-17 12:43:33 -04:00
Georges-Antoine Assi
fad2e5c77d Use correct LaunchBox MameFile schema
The sample_metadata.zip test fixture used invented tag names
(<Description>, FileName ending in .zip). Real LaunchBox Mame.xml
(see backend/tasks/fixtures/launchbox/mame.xml) uses <Name> as the
full title and keys MameFile entries by the stem (e.g. wrlok_l3),
no extension. Read Name instead of Description, and fall back to
the stem when the raw fs_name lookup misses.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 14:31:16 -04:00
Georges-Antoine Assi
a83f3bdca7 Wire up LaunchBox MAME arcade lookups
The scheduled task populated LAUNCHBOX_MAME_KEY from Mame.xml but no
handler code ever read it, so arcade ROMs like pacman.zip never matched
against Metadata.xml (which keys on full titles like "Pac-Man"). Add
RemoteSource.get_mame_entry() and an ARCADE branch in get_rom() that
resolves the MAME filename to its Description before name lookup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:00:26 -04:00
Georges-Antoine Assi
eda88b70d1 get claude to refactor launchbox_handler 2026-03-07 16:02:39 -05:00