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>
rq.cron names an entry after its function unless told otherwise, and
every entry here runs the task runner, so all of them shared one cron
identity and one job history zset. It also always passes a result_ttl,
so leaving it out meant its 500s default rather than the worker's
setting: a scheduled run vanished from the task list eight minutes after
finishing while a manual run of the same task was kept for a day.
Stopping a scan twice raised out of the socket handler. The first Stop
marks the job cancelled but the worker holds it until it unwinds, so the
second reaches it again and RQ refuses to cancel a cancelled job.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Also stops the scan job test stubs keeping their own copy of the func
name the handler already declares.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Scheduling moved onto RQ, which left the task catalog with two identity
schemes: the registry key a job payload now carries, and the dotted func
path each PeriodicTask still declared. Nothing read the latter, so it is
gone, along with the test that guarded paths no payload names.
Four sites built the same enqueue by hand and had already drifted: the
startup backfills passed the global timeout and no result_ttl, so an
auto-enqueued conversion fell out of the task list after RQ's default
500s while the same task triggered by an admin lived for TASK_RESULT_TTL.
They now go through enqueue_task, which derives timeout, ttl and meta
from the task itself.
Scan discovery paid a Redis round trip per queued job to re-read a status
the fetch already carried, and the stale sweep read every delayed job to
find the few past due. Both now ask Redis once.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`on_failure=report_scan_failure` is attached where a scan is enqueued by
the socket handler and the watcher, but a scan cron enqueues carried
nothing: `CronScheduler.register()` takes no `on_failure` and `CronJob`
has no equivalent, so the one scan nobody is watching is also the one
whose worker can die without a `scan:done_ko` reaching the clients. RQ
reaps the job correctly and moves it to the failed registry, but no
callback runs, so the client keeps showing a scan that no longer exists
and `/tasks/status` cannot recover it either.
Cron now registers a dispatch job for a scan instead. It enqueues the
real scan onto the scan queue with the callback attached, mirroring what
the socket handler does. The dispatch sits on the low priority queue
rather than the scan queue so it fires on the tick instead of waiting
behind a scan that is already running, and because it only enqueues, it
takes the ordinary task timeout and hands the scan timeout to the scan
itself. That last part is a behaviour change: the cron job's own timeout
drops from `SCAN_TIMEOUT` to `TASK_TIMEOUT`.
The dispatch is left out of the task history, because it carries the
scan's own name and finishes in milliseconds, so listing it would show
one scheduled rescan as two runs. A dispatch that failed is still listed,
since then no scan ran at all.
Cron jobs also get an explicit result TTL. `register()` defaults it to
RQ's 500 seconds and writes that onto the job, so `job.get_result_ttl()`
never fell back to the worker's own 86400 and the Task History panel
emptied about eight minutes after each run. Passing `TASK_RESULT_TTL`
restores what rq-scheduler gave for free, since it passed no TTL at all.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`ScanLibraryTask` never set a timeout, so it inherited `TASK_TIMEOUT` and
the nightly pass over the whole library was killed after five minutes.
That predates the scan queue, which only made it visible: the timeout is
now read straight off the task when its cron entry is registered.
Delayed scans are also looked for in the low priority queue's registry as
well as the scan queue's. A scan delayed before scans had their own queue
waits in the old one, where a worker will still release it, so the stale
sweep has to be able to see and drop it.
The queue table in the architecture doc still described the low priority
queue as the home of long-running scans.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A library scan runs for hours on the same worker as everything else, so
every cleanup, conversion and metadata refresh waited behind it. Scans go
on a queue of their own, consumed by a second worker, and the queues that
serve the rest of the app keep moving while a scan runs.
One worker on one queue also makes "one scan at a time" structural rather
than something the socket handler has to enforce, and it leaves another
worker running to notice when the scan worker dies.
Which is what the second half of this does. A worker killed mid-scan
never reaches the handler that reports the scan ended, so clients kept
showing a scan that no longer existed. RQ hands an abandoned job to its
failure callback when a surviving worker reaps it, so scans carry one
that emits `scan:done_ko`. Only for AbandonedJobError: every other
failure is already reported by the scan as it unwinds, and emitting here
too would report it twice. The scheduled rescan is not covered, because
rq cron cannot attach callbacks.
Scan discovery still reads the other queues, so a scan enqueued before
this change is still found and still runs.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Spreading the caller's arguments alongside the task name let a body set
`name` and redirect the run, so an authorized caller could reach a task
the route had just refused: one the API does not surface, or one whose
`manual_run` is off. The endpoint checked the name from the path, and the
worker then resolved whatever name the payload ended up holding.
Nest the caller's arguments under `task_kwargs` instead of spreading
them. Ordering the spread so the trusted name wins would also close the
hole, but nesting makes the collision impossible rather than
order-dependent, and leaves a task free to take an argument called name.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
rq-scheduler has one release since 2023, 109 open issues, and RomM ran a
fork of it for Redis username and SSL options that upstream never took.
Everything it was here for now ships with RQ.
Its two failure modes were the reason for the workarounds in 9e9f59c04.
It reads a job's function name before taking the job out of its registry,
so one unreadable job stalls it for good; RQ's scheduler removes every id
it looked at whether or not the job could be read. And cancelling a
delayed job needed both `Scheduler.cancel` and `Job.cancel`, because the
first left the status alone and the second left the registry entry, which
the scheduler then queued anyway; `Job.cancel` on its own now clears the
scheduled registry.
Delayed jobs, which is how the watcher defers a rescan, go onto the queue
with `Queue.enqueue_in` and are released by the worker running with
`--with-scheduler`. Periodic tasks are declared in `tasks/cron_config.py`
and loaded by an `rq cron` process, replacing `rqscheduler`. A task is
registered only when it is enabled and has a cron string, so the
schedule-then-unschedule dance around the env toggles is gone, and with
it `PeriodicTask.init/schedule/unschedule`.
Jobs are enqueued by task name through `run_task_by_name`, resolved
against a catalog in `tasks/registry.py`. Nothing pickles a task instance
into Redis any more, which is what made a payload unreadable across
upgrades in the first place. The catalog also gives the tasks endpoint
one home for what a task is, rather than a list of its own.
Scan discovery keys off the type a job carries rather than the scheduled
rescan's function name, since every task now shares one entry point. That
also drops SCAN_LIBRARY_TASK_FUNC, which only existed to name a function
across an import cycle.
The watcher's dedupe worked on `job.args[0]` while scans are enqueued with
keyword arguments, so it never matched and every filesystem change
scheduled another scan. It reads `platform_ids` from the payload now, and
deliberately ignores a scan already running: that one may have walked past
the folder that just changed.
Startup clears what the old scheduler left in Redis, once.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Every scan request has been refused with "A scan is already in progress"
on instances whose rq-scheduler cannot make progress, and waiting does
not help because nothing is running to wait for.
The scheduler reads a job's function name before it takes the job out of
its registry, so one job left behind by an older version, holding an
argument that no longer deserializes, crashes it on every poll and stays
there for the next one to trip on. Nothing scheduled runs again, and the
watcher's delayed rescans pile up behind it. `_get_queued_scan_jobs`
counted those as scans waiting to start, so the guard added in 99e214a8b
refused every manual scan for as long as the scheduler stayed broken.
Clear jobs the scheduler cannot read at startup, before it polls them
again, and split scan discovery so the guard consults only what sits on
a worker queue. Delayed scans still block nothing: the scheduler is the
only thing that releases them, so one that is down must not be able to
refuse scans. A recovered scheduler would release its whole backlog at
once and run the same library scan over and over, so delayed scans more
than an hour past due go too.
Stopping a scan now drops delayed scans out of the scheduler's registry
rather than only cancelling the job, which left the id in the registry
for the scheduler to queue anyway once the delay was up.
A worker killed mid-scan points at a job that can already be gone, which
raised NoSuchJobError out of the socket handler with no reply to the
client, and out of GET /tasks/status as a 500. Reading a job's status has
the same problem once its hash expires, so it goes through a wrapper.
Finally, name the scan in the way when refusing, and say when it is
stopping rather than running, so the message is actionable.
Fixes#4186
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Renumber the two migrations onto master's head: 0108/0109 collided with
0108_roms_primary_region and 0109_rom_files_category_index, leaving the
chain with two heads. They are now 0114 and 0115 behind 0113.
Both rebuild the roms_facets sync triggers from a hardcoded column list,
so add the publishers and developers columns 0112 introduced. Without
them the rebuilt triggers would have silently stopped mirroring the two.
Adopt master's provider taxonomy. METADATA_PROVIDER_GROUPS now carries
demozoo, pouet, and csdb as catalogs, which replaces the branch's own
GENERAL_PROVIDER_KEYS set and feeds the setup wizard, the scan dialog,
and Settings from one registry. CSDb reaches the scan explainer for the
first time; it was already selectable there.
Regenerate the frontend types: DetailedRomSchema was missing the three
metadata blobs the backend has always declared on RomSchema, and the
blobs are now typed rather than Record<string, unknown>.
Correct the setup strings that still called the three sources enabled by
default, and sort the locale keys.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Security review follow-ups on the Demozoo, Pouet, and CSDb handlers.
Default the three sources to off, matching every other provider. They
were the only ones defaulting to on, so an upgrade began contacting
demozoo.org, pouet.net, and csdb.dk on the next scan with no operator
opt-in, reachable through the unauthenticated metadata heartbeat.
Guard the bare id conversion in scene_id_or_none. str.isdigit() accepts
superscripts and other digits int() rejects, so a pasted "²" raised out
of the Edit ROM endpoint as a 500.
Filter the remote demozoo_url through http_url(). It was the only one of
the three URL fields taking a string from the API rather than building
one from a hardcoded template and an integer id.
Match a YouTube id against an explicit ASCII class. isalnum() is
Unicode-aware, so it accepted ids the embed URL never can.
Stream the CSDb response against a byte budget. The cap ran after the
whole body was already buffered, so it bounded the parse but not memory.
Catch defusedxml's refusals. EntitiesForbidden derives from ValueError
and ParseError from SyntaxError, so the existing handler caught neither
and an entity-declaring document raised out of production_from_xml.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Resolves the additive conflicts against master:
- config, handler registry and the roms endpoint imports keep both the
Steam and the new UPC-lookup entries.
- Renumbers the Steam migration to 0113 (master took 0109) and rebases it
onto 0112_publisher_developer_split.
- Syncs the migration's pre-Steam facet mirror list with 0112, which added
publishers/developers to the roms_facets triggers.
- Groups SteamMetadata's publishers/developers with the shared provider
keys, now that master has made them a shared field.
The cleanup tasks took a single platform_id while both Missing tabs
offer a multi-select, so picking two platforms ran the unscoped
cleanup over the whole library. The confirmation dialog still named
the selection, so the tab deleted more than it said it would.
Take platform_ids on both cleanup tasks and filter firmware by the
whole list, so what runs matches what the dialog names.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Steam covers the PC platforms RomM otherwise has thin metadata for, and
its store payload is provider-grade on its own: title, description,
portrait capsule art, screenshots, genres, developers, publishers,
release date and Metacritic score, with no API key.
Valve documents no storefront API, so this reads the two endpoints that
back the store's own search box and app pages, paced well under the ~200
requests per 5 minutes they tolerate. Every failure path degrades to "no
match" rather than aborting a scan, and the provider is opt-in behind
STEAM_API_ENABLED, matching HowLongToBeat and Flashpoint.
Matching is gated on the platform slug so the three PC platforms are the
only ones that spend a request. The storefront's search index carries
DLC, soundtracks and tools alongside games, so hits are filtered by type
and then confirmed against the app page, which is the only place a demo
or a video is distinguishable from a game. A (steam-12345) filename tag
pins a match by hand when the title is ambiguous.
SteamMetadata reuses the key names the other providers already use for
the values they share, so wiring Steam into the generated facet columns
later is a SQL change with no stored-row reshaping.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three text conflicts and one alembic head collision that git merged clean.
Master added a Ports section to the overview tab and i18n-ified the related
headings; this branch replaced the IGDB "Similar games" section with the
recommendations index. Both survive: Ports keeps its RelatedGamesGrid, and
Similar games keeps SimilarGamesGrid behind the recommendations toggle.
`rom.related-similar-games` was master's key for the section this branch
replaces, so it goes with it; `recommendations.similar-games` is its home now.
Both sides added OverviewTab.test.ts. The two suites now share one mount
helper.
Master's 0108_roms_primary_region and this branch's 0108_rom_similarity both
revised 0107, which alembic reads as two heads. This branch's four migrations
move to 0109 to 0112 behind master's. Verified up, down and up again on
MariaDB, including down past master's 0108: the generated region column, the
five new facet columns, rom_similarity and the widened sibling-cover index all
survive the round trip.
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>
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>
Identify demoscene productions as ROMs via filename tags, Edit-ROM
id/URL paste, Demozoo ?title= + rank, unique Pouët search.php 302,
and CSDb XML by id (no HTML scrape). Scene ids lock name/summary/cover
so game catalogs cannot attach a similarly titled box.
CSDb XML is parsed with defusedxml and capped; screenshot and extra
links are stored only when they are http(s).
Fixesrommapp/romm#1796 (Phase 0–2).
Every cached ranking is computed against the edges that existed when it was
built, so the nightly rebuild left users reading the previous graph until
their cache expired. The same argument that moved per-user invalidation into
`update_rom_user` applies to the largest input of all.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Recommendations came straight from IGDB's `similar_games`, which mostly
names titles the server does not hold and is absent entirely for anything
IGDB never matched.
`rom_similarity` holds a precomputed item-item graph blending four signals:
IDF-weighted metadata overlap, the IGDB prior resolved against the library,
collection co-membership and co-play. Scores are library-relative, so a
shelf full of arcade games learns on its own that "Action" says nothing
while "Metroidvania" says a great deal, with no tuning.
Each edge stores the facets that produced it, so the UI can explain a
recommendation rather than showing an unattributed row of covers.
Candidate generation runs off an inverted index with a document-frequency
cap, avoiding the all-pairs comparison. The graph is rebuilt wholesale by a
scheduled task because the IDF weighting shifts as the library grows, and
writes commit in batches so a task that dies leaves stale edges rather than
an empty table.
The personalised feed is ranked on demand from those edges plus live play
history, since a nightly feed would ignore the game played an hour ago.
Ratings below the scale midpoint act as negative seeds, results are
diversified per franchise and platform, and owned-but-unplayed games are
boosted.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both blocks ended on a counterfactual about what storing raw text would
do, which explains the change rather than the behaviour. State what the
code does instead.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Lookups strip the term they search for (and lowercase it where the index
is lowercased), but the import task keyed entries off raw XML text. The
dump has no padded values today, so nothing is broken, but if LaunchBox
ever pretty-printed one of these files the affected index would go dark
with no way to tell from the outside.
The fixture now pads one entry per index the way a pretty-printed dump
would, and the assertions check key text rather than just call counts, so
a regression here fails the test instead of quietly shipping.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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>
A scan flags firmware whose file vanished, but nothing could act on the
flag: stale BIOS entries could only be found by opening each platform's
Firmware tab one at a time, the player still offered them (auto-selecting
the sole entry, so the game failed to boot with nothing pointing at the
BIOS), and platform firmware counts included them.
Adds a `missing` filter to the firmware list endpoint, a
`cleanup_missing_firmware` manual task alongside the ROM one, and a
Missing firmware tab in Library management that lists every flagged entry
library-wide with a bulk cleanup. The player now asks for present
firmware only, and firmware selection moved to a `playerFirmware` util
that never picks a missing entry. `firmware_count` counts only firmware
present on disk; the rows themselves still ship so the Firmware tab can
strike them through.
`FirmwareSchema` gains `platform_id` so the library-wide list can group
by platform.
Fixes#4075
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Restrict ROM file deletion to the ROMS/DELETE grant. The new
DELETE /roms/{rom_id}/files/{file_id} route gated on ROMS_WRITE alone and,
unlike its manual/soundtrack/screenshot siblings, carried no category guard,
so a group holding write-but-not-delete could remove game files from disk
while whole-ROM deletion still required ROMS/DELETE.
Gate mutating streaming routes on ROMS_USER_WRITE instead of ROMS_READ,
matching the play-session routes. ROMS_USER_WRITE is always-on for
authenticated users, but absent from READ_SCOPES, which is all KIOSK_MODE
grants an anonymous visitor. Kiosk visitors all share user_id=-1, so session
ownership could not separate them and any visitor could claim sessions and
overwrite another's save states.
Restore the ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES gate on the cleanup
task's cron_string. It was dropped in 06cafd4b1, whose message refers to
update_switch_titledb, leaving the documented opt-out inert and scheduling a
destructive task nightly. That commit also broke two of the task's own tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The store is written in batches, so an initial import answers for the
names committed so far long before it holds the whole dump. Checking
that the name index exists reported the provider healthy off a fraction
of the entries, and a run that died partway left it that way for good.
Flag the initial import and clear it once a run completes, so only a
finished import counts as healthy. A refresh keeps serving the previous
dump, so it is not flagged.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
Importing the task module first, as the worker does when it resolves the job,
pulled endpoints.roms in and closed an import cycle through decorators.database.
RQ hides the ImportError behind "Invalid attribute name: run", so the cleanup
never ran and orphaned chunked-upload directories piled up.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Scan job discovery only looked at the high priority queue and only
recognised scan_platforms, so two kinds of in-flight scan went unseen.
Watcher scans are delayed through the scheduler and land in the low
priority queue, so the concurrency guard let a manual scan start
alongside one and the stop handler left it queued to run afterwards.
The scheduled rescan enqueues its own task and calls scan_platforms in
process, so the worker reports the task's name. That made stopping it a
silent no-op: with no running job matched, the stop flag it polls was
never set.
Discovery now spans both queues plus the scheduler and matches either
function name. The scheduler registry also holds the standing cron entry
for the scheduled rescan, which is a schedule rather than a pending
scan, so only delayed scan_platforms jobs count as queued.
Clearing the stop flag at scan start is now scoped to the scan that owns
it, so a scan starting next to one that has not yet polled the flag
cannot drop a stop request meant for it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The orphaned resource cleanup listed the resource tree through
`anyio.Path`, which dispatches to a worker thread for every entry it
yields and again for every `is_dir()` call. On a library with ~30k ROM
resource directories that is ~60k thread round trips to read data the
directory listing already contains.
Measured on a 30,262-directory library (Raspberry Pi 4, ext4):
anyio iterdir + is_dir() 50.3s
os.scandir 0.15s
`os.scandir` reports the entry type from the directory read itself, so
no per-entry stat is needed. The walk moves into a helper run once via
`asyncio.to_thread`, keeping the event loop free while doing the whole
traversal in a single thread hop rather than tens of thousands.
Cold and warm runs of the old code were within 1% of each other, so this
was thread-dispatch overhead rather than disk I/O.
A directory that cannot be listed now logs and yields an empty set
instead of aborting the walk, so one unreadable platform cannot strand
every other platform's orphans.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`cleanup_orphaned_resources` decides what to delete purely by asking whether
a resource directory's id is absent from the database, with no sanity floor.
If `get_platforms()` ever comes back empty while artwork is still on disk
(database unavailable, mid-migration, half-restored backup), every platform
directory is treated as orphaned and removed in a single pass.
That was tolerable when the task only ran on an admin's click. Now that it
can run unattended at 5 AM via `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES`,
nobody is watching when it happens.
Bail out when the database reports zero platforms but platform directories
exist on disk, and log a warning saying so. A genuinely emptied library can
still be cleaned by running the task manually with `{"force": true}`, which
the run-task endpoint already forwards to `run()`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Orphaned covers and screenshots left behind by deleted ROMs accumulate
indefinitely, because the only way to reclaim them is to trigger the
cleanup task by hand. On a long-lived instance the resources directory
grows without bound, which is a problem when it shares a filesystem with
the database.
Move the task to `tasks/scheduled/` and turn it into a `PeriodicTask`
with an opt-in cron schedule, defaulting to 5:00 AM so it runs after the
nightly scan and metadata tasks have settled.
`enabled` stays `True` rather than tracking the new env var, because the
run-task endpoint requires both `enabled` and `manual_run`. Gating it
would have silently removed the ability to run the cleanup by hand,
which is how it works today. The cron string is what is opt-in, and
`init()` unschedules when it is unset.
Add the new flag to the init script's scheduler condition, so enabling
only this schedule still starts `rqscheduler`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three sync callsites (endpoints/sync.py, sync_watcher.py, and both
branches of tasks/sync_push_pull_task.py) ran get_saves(...) and then
discarded archival null-slot rows in a Python list comprehension. On
libraries with many archival/web-UI uploads that's a strict waste:
those rows are pulled from MariaDB, hydrated into Save model instances,
and then immediately filtered out.
Add a slot_not_null bool kwarg to DBSavesHandler.get_saves and apply
the filter in the SQL query. Update all four callsites to use it and
drop the Python-side comprehension. Default stays False so unrelated
callers keep the current behavior.
get_all_saves() materialized every Save row across all users into a
single .all() list. On instances with very large libraries that's a
real RAM ceiling and pins every row for the lifetime of the recompute
run.
Replace it with get_saves_after_id(after_id, limit) and have the
recompute task drive keyset pagination in PAGE_SIZE-row chunks. SQLAlchemy
streaming via .execution_options(yield_per=...) is incompatible with the
per-call session lifetime that @begin_session enforces (the session
exits before the consumer iterates), so keyset paging from the caller is
the cleanest fit.
Behavior is unchanged: same row coverage, same idempotency, same
counters. Memory usage drops from O(all saves) to O(PAGE_SIZE).