Files
romm/backend/handler/redis_handler.py
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

164 lines
4.7 KiB
Python

import os
import sys
from enum import Enum
from typing import Any, Final
from redis import Redis
from redis.asyncio import Redis as AsyncRedis
from rq import Queue, Worker
from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError
from rq.job import Job, JobStatus
from config import IS_PYTEST_RUN, REDIS_URL
from logger.logger import log
class QueuePrio(Enum):
HIGH = "high"
DEFAULT = "default"
LOW = "low"
# Scans have a queue and a worker of their own: a library scan runs for hours,
# and one worker on one queue keeps two of them from ever running at once.
SCAN_QUEUE_NAME: Final = "scans"
redis_client = Redis.from_url(REDIS_URL)
high_prio_queue = Queue(name=QueuePrio.HIGH.value, connection=redis_client)
default_queue = Queue(name=QueuePrio.DEFAULT.value, connection=redis_client)
low_prio_queue = Queue(name=QueuePrio.LOW.value, connection=redis_client)
scan_queue = Queue(name=SCAN_QUEUE_NAME, connection=redis_client)
ALL_QUEUES: Final = (scan_queue, high_prio_queue, default_queue, low_prio_queue)
def __get_sync_cache() -> Redis:
if IS_PYTEST_RUN:
# Only import fakeredis when running tests, as it is a test dependency.
from fakeredis import FakeRedis
return FakeRedis(version=7)
# A separate client that auto-decodes responses is needed
client = Redis.from_url(REDIS_URL, decode_responses=True)
log.debug(
f"Sync redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}"
)
return client
def __get_async_cache() -> AsyncRedis:
if IS_PYTEST_RUN:
# Only import fakeredis when running tests, as it is a test dependency.
from fakeredis import FakeAsyncRedis
return FakeAsyncRedis(version=7)
# A separate client that auto-decodes responses is needed
client = AsyncRedis.from_url(REDIS_URL, decode_responses=True)
log.debug(
f"Async redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}"
)
return client
sync_cache = __get_sync_cache()
async_cache = __get_async_cache()
def __get_async_binary_cache() -> AsyncRedis:
"""A client that leaves values as bytes, since `async_cache` decodes every
response as UTF-8 and a zstd frame is not."""
if IS_PYTEST_RUN:
# Two fakeredis clients get two keyspaces, so the fake is shared. It
# does not decode responses, which is what this client wants anyway.
return async_cache
return AsyncRedis.from_url(REDIS_URL)
async_binary_cache = __get_async_binary_cache()
def get_job_func_name(job: Job, fallback: str = "") -> str:
"""Safely get the function name from an RQ job, handling DeserializationError.
Args:
job: The RQ Job object to get the function name from
fallback: The value to return if deserialization fails
Returns:
The function name if available, otherwise the fallback value
"""
try:
return job.func_name or fallback
except DeserializationError:
# Job data cannot be deserialized (e.g., function no longer exists)
return fallback
def get_job_status(job: Job, refresh: bool = True) -> JobStatus | None:
"""Safely get the status of an RQ job, which is gone once its hash expires.
Args:
job: The RQ Job object to get the status of
refresh: Whether to re-read the status, rather than trust the one the
job was fetched with
Returns:
The job status, or None if the job no longer has one
"""
try:
return job.get_status(refresh=refresh)
except InvalidJobOperation:
return None
def get_job_kwargs(job: Job) -> dict[str, Any] | None:
"""Safely get the keyword arguments an RQ job was enqueued with.
Args:
job: The RQ Job object to read
Returns:
The keyword arguments, or None if the payload cannot be deserialized
"""
try:
return job.kwargs
except DeserializationError:
return None
def cancel_job(job: Job) -> bool:
"""Cancel an RQ job, tolerating one that is already cancelled.
Args:
job: The RQ Job object to cancel
Returns:
Whether this call was the one that cancelled it
"""
try:
job.cancel()
except InvalidJobOperation:
return False
return True
def get_worker_current_job(worker: Worker) -> Job | None:
"""Safely get the job a worker is holding, which can be gone before the
worker's own registration expires.
Args:
worker: The RQ Worker to read
Returns:
The job the worker is running, or None if it has none or it is gone
"""
try:
return worker.get_current_job()
except NoSuchJobError:
return None