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).
Cleanup pass on save-sync addressing three independent failure modes
that interact in production data: content_hash drift between client
and server, null-slot archival saves leaking into sync flows, and
content-hash dedupe collapsing legitimately-distinct slots.
Bug fixes
- compute_content_hash dispatched on zipfile.is_zipfile(relative_path),
which silently returned False whenever the process's CWD wasn't
ASSETS_BASE_PATH. Every zip save fell through to the raw-MD5 branch,
persisting hashes that disagreed with clients computing the intended
per-entry zip-hash. Resolve to a full path before the dispatch.
- _build_negotiate_plan, sync_push_pull_task, and sync_watcher all
treated null-slot saves as sync-eligible. Null-slot saves represent
web-UI / archival uploads; including them in negotiate plans matched
them against device pushes by filename and overwrote archival data.
Filter null-slot saves at all three call sites.
- get_save_by_content_hash matched on (rom_id, user_id, content_hash)
only, so identical bytes uploaded to different slots collapsed into
one record. Scope the lookup by slot when provided so clone-save-
to-new-slot creates a distinct row per slot.
- get_save_by_filename matched on (rom_id, user_id, file_name) only.
When two uploads to different slots happened in the same wall-clock
second (the datetime tag is per-second), the second upload UPDATED
the first record's slot instead of creating a distinct row. Scope
the filename lookup by slot too.
One-shot recovery
- New recompute_save_content_hashes manual task walks every Save row,
recomputes via the fixed dispatch, and updates rows whose values
differ. Idempotent; safe to re-run.
- Backend startup runs a COUNT(content_hash IS NULL) query and, if
any rows exist, enqueues the recompute task on the low-priority
RQ queue. The API process moves on; the worker handles the
recompute out-of-band. Subsequent restarts find zero NULL hashes
and skip. Admins can also trigger the task manually.
Test infrastructure
- Added tests/_zipfile_shim.reload_zipfile() mirroring the pattern
from utils/zip_cache.py for the same zipfile-inflate64 + CPython
3.13.5 incompatibility. Test fixtures that build ZIPs call it
immediately before opening the archive.
Apply the same lazy-factory pattern to FSLaunchboxHandler and FSSyncHandler
that ssh_sync_handler now uses. With both opt-in features deferred to
first-use, the tolerate_missing_base escape hatch on FSHandler is no longer
needed — every handler now fails loudly on mkdir failure, which is the
right behavior for the always-on core paths (assets, library, resources).
Touched call sites:
- resources_handler._resolve_local_file_uri (launchbox)
- sync_watcher.py, endpoints/device.py, tasks/manual/sync_folder_scan.py
(fs_sync)
Net effect:
- Default installs never poke /romm/launchbox or /romm/sync at startup.
- Misconfigured opt-in users get a clear, actionable PermissionError at
the call site instead of a silent warning followed by mystery failures.
- tolerate_missing_base, its tests, and one stale log import are gone.
The module-level SSHSyncHandler() singleton ran filesystem side effects
(mkdir on SYNC_SSH_KEYS_PATH) at import time, which meant even default
installs with push-pull sync disabled would touch /romm/sync — and the
previous tolerate-and-warn fallback could leave users wondering why
sync silently does nothing.
Replace the eager singleton with a functools.cache'd factory. The
handler is now constructed on first use, so:
- Default-install users (ENABLE_SYNC_PUSH_PULL=false, no manual sync
triggered) never touch /romm/sync.
- Users opting in get a clear, actionable RuntimeError pointing at
the unwritable path and the env var to override, at the call site
rather than buried in a startup stack trace.
Also document in env.template that enabling either sync mode requires
a writable volume at $ROMM_BASE_PATH/sync.
- Bulk /download endpoint now caches ZIPs for Range requests (max 100 ROMs)
- LRU eviction frees space by removing oldest cached ZIPs (>1h old)
- Tiered TTL: 48h default, 12h for ZIPs over 8GB
- Generalize cache paths from rom_id to namespace (supports bulk-{ids})
- Restore NoResultFound behavior on update_session, complete_session,
fail_session when row is missing (scalar returns None, old .one()
raised -- silent None is a semantic regression)
- Remove redundant get_session call from _increment_session_counter;
the atomic SQL increment is already a no-op on missing rows
- Log warning when passed session_id is not found in _sync_device
instead of silently creating an orphan session
- Fix broken path construction in FSSyncHandler: build_* methods now
return relative paths; sync_watcher uses paths relative to sync base
instead of CWD (was completely non-functional in production)
- Fix SSH connection leak in push-pull task: conn.close() now in finally
- Add log.warning for disabled SSH host key verification
- Fix race condition in session operation counter: use atomic SQL
increment instead of read-then-write
- Extract _increment_session_counter helper, add exc_info to warnings
- Replace legacy session.query() with select() in sync_sessions_handler
- Fix orphaned session: trigger_push_pull now passes session_id to job
- Fix wasteful SSH download when no matched_save exists
- Fix BaseModel import collision in sync.py (pydantic -> project base)
- Fix ORM mutation in UserSchema.from_orm_with_request: set field on
schema instance instead of mutating live ORM object
- Mask ssh_password and ssh_key_path in DeviceSchema API response
- Fix migration PostgreSQL compatibility: condition ON UPDATE clause
on MySQL, drop enum in downgrade
- Rename copy-paste artifact rom_user_status_enum