29 Commits

Author SHA1 Message Date
Georges-Antoine Assi
20bff0830a fix(streaming): merge the webstation exit delta over the restored save archive (#5673)
* fix(streaming): merge the webstation exit delta over the restored save archive

A webstation exit export holds only the files changed since launch, but
RomM filed it as a standalone .saves.zip and the next launch restored only
the newest zip. A session that exited without an in-game save therefore
filed an archive with no save data, and the next Play booted without it.

The launch now records which native archive it restored on the session
record, and the exit pull lays the delta over that archive before filing
it, so every stored archive is a full snapshot.

Fixes #5544

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(streaming): type the stored exit archive as bytes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(streaming): skip the exit merge when the restored archive was replaced

PUT /saves/{id} rewrites a save in place under the same id, so the exit
merge could combine the session's delta with save data it never loaded.
Record the restored archive's content hash at launch next to its id, and
merge only while the base still has it; otherwise file the delta alone.

Addresses Greptile's review on #5673, including folding the
_over_restored_archive docstring into one sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(streaming): drop ensure_zipfile_writable from the archive overlay

#5678 applies the zipfile_inflate64 fix where it is imported, and removed the helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: review-polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose (code-review additions)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(streaming): keep imported states, folders and the entry cap in the exit merge

A launch that imported a state left the base archive's states off the
container, so the exit merge now leaves them out too. The merge keeps
both archives' folders and refuses past the archive entry limit, so a
merged archive always gets a content hash. The webstation hydrate now
uploads the save its caller resolved instead of looking it up again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(db): query a platform id no sequence can reach

Postgres keeps id sequences across tests, so a worker that has created
about a thousand platforms hands id 999 to the fixture's own platform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:40:47 -05:00
Georges-Antoine Assi
63faff8883 fix(misc): Rename paths, rescan artwork, scan lookups and streaming teardown fixes (#5396)
* fix(roms): rewrite only the moved part of a renamed rom's file paths

Renaming a rom rewrote each of its files with
`str.replace(old fs_name, new fs_name)` on both the name and the path. On
disk, rename_fs_rom moves only `fs_path/old` to `fs_path/new`, so:

- a folder rom's inner file named after the folder (`Game (Disc 1).bin`
  in `Game/`) was renamed in the database but not on disk;
- an fs_name that also appears in the platform path (a rom named `n64`
  under `n64/roms`) rewrote the platform path too.

_moved_file_location mirrors the move instead: a single-file rom's name
changes, a folder rom's files keep their names under the renamed folder,
and anything else is left alone.

_refetch_changed_matches now returns the ids it refetched, so the
RetroAchievements badge download keys off that rather than repeating the
comparison, and the shared-media rematch uses the same _match_changed
check as the refetch loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(scan): keep artwork a complete rescan has nothing to replace with

A complete rescan deleted the rom's cover, manual, screenshots and every
provider media folder before asking any provider, then reset the stored
paths. A provider that was down, rate limited or no longer had the art
left the rom with none.

The wipe is gone, and scan_rom no longer resets the path columns on a
complete rescan. The download step already replaces what changed:
covers, manuals and screenshots refetch when their URL differs, and
remove_stale_media drops provider media whose owner or URL changed. The
URLs and locks are still cleared, so whatever answers now can replace a
file; a file nothing replaces stays where it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(scan): move scan_rom's provider lookups onto a _RomLookups class

scan_rom defined 16 provider lookups as closures over its own locals
(scan type, platform, rom, rom_attrs, enabled sources, the attempted and
inconclusive sets), so none of them could be read or tested apart from
the 1,000-line function around them.

They are now methods of _RomLookups, a dataclass holding exactly what
they used to capture, along with the helpers they share (consults,
note_inconclusive, resolve_fetch and the cached match files). scan_rom
builds one instance and keeps its local names for the shared sets, so its
body is unchanged apart from the calls. SteamGridDB's lookup stays nested
because it reads the other providers' results.

scan_rom drops from 977 to 664 lines. Its own complexity is unchanged:
that comes from the merge after the lookups, not the lookups themselves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(streaming): one teardown order for every way a session ends

A session could be torn down three ways, each spelling out its steps:

- teardown_released_session (owner release and single admin release)
- teardown_abandoned_session (stale takeover and the reaper)
- force_release_all's inline _teardown

The first two ran the same stop/playtime/activity/state/saves sequence
in two copies. The sweep differed in ways that mattered: it held no drain
marker while it worked, recorded the termination after the stop (so a
polling tab could miss it), marked the exit save pull pending only after
the stop, and deleted the key unconditionally, even if a newer claim had
replaced the one it read.

_stop_and_collect now holds the shared sequence, and both lifecycle
teardowns call it after their own opening (a drain marker for a release,
a staleness-checked marker for an abandoned session). The sweep runs
teardown_released_session for each session, like a single admin release.
With no container config left, it still records the termination, then
frees the key through the guarded release_own_session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings (pr-ready step 2)

Record playtime and clear the activity entry when force-release-all frees
a session whose container config is gone, and let the PICO-8 cartridge
fallback see a cover a complete rescan keeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify findings (pr-ready step 3)

Let _RomLookups.attempts() record the attempt it gates, drop scan_rom's
local aliases for the lookups' state, read the platform slug off the
lookups in fetch_launchbox_rom, seed the kept artwork paths into
rom_attrs for every rescan so the PICO-8 fallback reads them directly,
return None from _moved_file_location when a file did not move, and
share the playtime and activity steps through close_session_record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on #5396

Drop a cover's other formats once a new one is stored, so a kept upload
in another extension can't shadow it, and move the rename path rule onto
FSRomsHandler next to rename_fs_rom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:06:52 -04:00
Georges-Antoine Assi
b5acfa4c44 refactor(streaming): type the session record as a StreamingSession TypedDict (#5395)
* refactor(streaming): type the session record as a StreamingSession TypedDict

The streaming session lived in the cache as a JSON object and moved
through the code as dict[str, Any], so its 18 keys were implied by the
two claim literals and a handful of mutate_session calls spread across
session_store, lifecycle, access, launch, memory_cards and the
endpoint. A misspelt key read as None without a warning.

StreamingSession (total=False, since drain markers and records from
older releases carry only some fields) now names every key and its type,
and every session and claim parameter, return and literal uses it. mypy
checks each .get() and write against it. The scope helpers that also
read a termination notice take a Mapping[str, object] instead.

No behaviour changes: the record's JSON is the same. Tests that built
sessions by hand now build StreamingSessions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(streaming): one-sentence StreamingSession docstring

Addresses Greptile's review on the comment rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:40:02 -04:00
Zach Clendenen
38dfb208f0 fix(streaming): file RetroArch streaming exits as raw saves (#5174)
* fix(streaming): keep foreign saves offered when the import-spec check fails

A broker that misses the 5 s import-spec deadline used to read as "imports
nothing": the Saves tab vanished and foreign picks were refused with
"Save is not a restorable archive". Keep the last good answer in Redis so
every worker can fall back on it, cache 404s for five minutes instead of
forever, answer a pick that can't be checked with a retryable 503, and
refetch the streaming config whenever the Stream page mounts.

* fix(streaming): code-review fixes for the import-spec fallback

Hold a fallback answer for 10 s so one claim's checks don't each wait out
the broker timeout, read the stored answer back through the broker
response parser, and warn about a pre-import broker once per worker
instead of at every cache expiry.

* refactor(streaming): simplify pass on the import-spec fallback

Make ImportSpecUnavailable the 503 itself so the save and state pickers
no longer convert it by hand, and store the broker's own response body
as the last answer instead of rebuilding its shape.

* chore(streaming): review-polish on the import-spec fallback

Trim the cache comments and the exception docstring, fit the 503 detail
within the line limit, and annotate the fresh-worker test dict for mypy.

* docs(streaming): humanizer pass on import-spec comments and test docstrings

* fix(streaming): tell lasting import-spec failures from passing ones

Only timeouts, connection errors, 5xx and 429 fall back to the broker's
last answer. A refused request (401, other 4xx) or a reply RomM can't read
caches no imports for 30 s and logs an error, so a pick gets a refusal
instead of an endless retry. A 404 from a broker that answered before
uses that answer, since it is likelier a restart behind a proxy than a
downgrade.

* fix(streaming): ask for a retry when a picked state can't be checked

An older save with the newest state resumes the pick only through an
import, so an unanswered import-spec check now returns the 503 instead of
launching from the older archive's own state.

* fix(streaming): share an in-flight config request

App load and the Stream page both fetch the config; two requests could land
out of order and leave the older answer in place. (Stability item 5.)

* fix(streaming): hold the resume picker until the fresh config lands

What the broker imports decides which saves and states are on offer, and the
app-load config can predate its answer. The panel shows a spinner until the
Stream page's own refetch settles, so a pick can't vanish under the player.
(Stability item 4.)

* fix(streaming): ask every platform's broker at once on /config

The checks ran on the default thread pool (cpu+4 threads), so a broker
serving more platforms than that cost one timeout per wave: 10.7 s for 14
platforms on a 6-CPU dev box with a silent broker. The Stream page's picker
now waits on /config, so the checks get a pool of their own.

* fix(streaming): address Greptile review on the import-spec fallback

- Play waits on the fresh config with the resume picker, so it can't send a
  preselected state the player can't see yet.
- The streaming store gets a reset() for logout, and a config reply asked for
  as the previous account is dropped instead of landing in the next one.
- The configFresh write after the refetch checks useIsAlive().
- Trimmed the require_import_spec docstring, the configFresh comment and the
  /config pool comment to the house length.
- Declined: a worker-wide pool for the /config checks. Each request's threads
  end within the broker timeout, and a shared bounded pool would bring back
  timeout waves under concurrent loads.

* fix(streaming): share /config broker checks across requests

Addresses Greptile's re-raised finding on #5174 that each /config request
opened its own pool of up to 64 threads, so overlapping page loads during
a silent broker multiplied the worker's threads.

- The checks run in one worker-wide pool, and a check already in flight
  for the same container and platform is joined rather than asked again,
  so concurrent page loads hold no more threads than one does, with no
  queued-timeout waves.
- Callers await the shared run through asyncio.shield, so a request that
  disconnects doesn't cancel the check others are waiting on.

* fix(streaming): file a RetroArch exit's save raw and boot the newest save

A RetroArch exit holding one .srm and its states is no longer stored as a
.saves.zip: the .srm is filed bare under the core's emulator name with a
timestamped name, and each state goes through the state store. Exits with
more than one save, a memory card, or unlabelled members still keep the zip.

A launch with no pick now boots the newest save, raw or zip. A newer bare
.srm goes through the broker's save import when the broker accepts one,
and the launch screen defaults to the same save.

* fix(streaming): keep the exit zip when a raw save can't be filed safely

pr-ready step 2 (code review).

- Keep the zip for a core that isn't one plain folder name, a malformed
  manifest kind, a member that fails to unpack, or a broker that doesn't
  import saves.
- Fall back to the newest archive when the default raw save fails to import.
- File exit states oldest first; one unreadable stored state no longer
  drops the rest.
- Rename locals that shadowed the archive module; fix a test return type
  and a stale comment.

* refactor(streaming): simplify the default save comparison

pr-ready step 3 (simplify): default_save reuses _newest's ordering, and newestSave takes the first match in the newest-first list.

* docs(streaming): trim the raw-save docstrings

pr-ready step 4 (review-polish).

* fix(streaming): rank saves by their last write and read .ZIP as an archive

The web player writes into its existing save row, which only moves
updated_at, so ranking by created_at let a stream with no pick boot an
older streaming zip over newer web-player progress. The backend default
and the launch screen now rank by updated_at, and the picker dates rows
by it. Upper-case .ZIP saves are now read as archives on both sides, to
match the web player's case-insensitive guard.

* feat(states): hash states so duplicate checks skip reading files

Adds states.content_hash (migration 0149), filled on every state write:
streaming capture, the states upload and update endpoints, the scan and
the RetroArch sync push. The streaming duplicate check compares hashes
and falls back to reading the file for rows stored before this, which
are not backfilled.

* fix(streaming): leave an untouched default off the claim and skip missing saves

Review items 1 and 2: a default sent as a pick bypassed the zip fallback, and a save marked missing could become the newest.

* fix(streaming): code-review fixes for raw exit filing and state hashing

pr-ready step 2: keep the zip when a state can't be filed, don't treat a missing state file as a duplicate, fall back to the native archive when a defaulted save fails, hash off the event loop, count filed states as new.

* docs(streaming): review-polish, trim the newest-save comment

* fix(streaming): bind the background exit pull's states to the swapped disc

Decision 1: the exit save job filed states without the session's disc id, so on a multi-disc game its copy could lose the disc binding. The second copy is still dropped by the hash dedupe.

* fix(streaming): keep the exit zip when one of its states fails to store

Decision 2: a state that threw on store was logged and lost, since the zip holding it was dropped. The zip holds the same .srm, so booting it as the default loses nothing.

* fix(sync): keep updated_at when RetroArch sync flags a vanished save or state

* fix(streaming): record a legacy state's hash when dedupe reads its bytes

* fix(streaming): file a RetroArch exit's auto state raw instead of keeping the zip

The auto state now goes into the state history under its own capture
stamp, so an exit carrying one files its .srm raw like any other. It is
never hydrated, and a resume pick of it is refused, since the broker
would file it into its numbered working slot.

* fix(streaming): hydrate the newest state still on disk

A newer row sync flagged as gone from disk made hydrate push nothing.
It now skips such rows the way the save picks already do.

* docs(streaming): note the auto-state refusal in resolve_resume_state

* fix(streaming): resume a RetroArch auto state like any other state

The broker files any pushed state into its working slot, so .state.auto
reads as slot 0 like a bare .state. Hydrate and the resume pick now push
it instead of skipping or refusing it.

* fix(streaming): address Greptile review on raw RetroArch exits

- A default .srm the broker refuses at activate now boots the newest
  native archive instead of failing the launch. Only a default save
  that rode the import alone falls back; a hand pick still fails.
- Exit states the history hasn't seen are filed just under the next
  state it already holds, so an older slot no longer heads the history
  over the exit capture teardown filed first.
- A raw exit save is skipped only when it matches the newest usable
  save, so returning to an older save records the play, and a match on
  a row whose file is gone no longer deletes the new copy.
- Stream.test.ts clicks the rendered play button instead of casting
  the view model to call onPlay.
- Trim the raw-exit docstrings to one sentence.

* fix(streaming): reserve a free version name for a raw RetroArch exit save

Addresses Greptile: the exit's .srm took a second-resolution tag without
checking whether another save held that name, so it could overwrite one.
Also compares updated_at naively in the mark-missing test, which failed on
PostgreSQL's UTC-aware column.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(streaming): file each RetroArch exit state on the disc it was saved on

Addresses Greptile: every state in the exit archive took the session's
final disc, so a hotkey slot saved before a swap resumed on the wrong one.
The session now keeps each swap with its time, and a session that ran more
than one disc files each state by its archive timestamp.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 20:44:14 -04:00
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

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

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

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

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

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

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00
Georges-Antoine Assi
aa80073d34 feat(streaming): run exit save pulls on the streaming worker
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:34:05 -04:00
Georges-Antoine Assi
29e6b8c1e9 fix(streaming): keep a claim fresh through its setup, log what spawned work raised, and notify a task's success only after that work ends (code-review)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 08:40:50 -04:00
Georges-Antoine Assi
2fc0460670 Merge remote-tracking branch 'origin/master' into streaming-reaper
# Conflicts:
#	backend/tasks/registry.py
#	backend/tasks/tasks.py
#	backend/tests/tasks/test_tasks.py
#	docs/BACKEND_ARCHITECTURE.md
2026-09-24 21:52:08 -04:00
Georges-Antoine Assi
2eb2b5973e refactor(streaming): share the claim query params, mark-and-start the exit save pull in one call, and drop no-op casts (simplify)
- Declare the container and claimed_at query params once, with named length limits.
- Add lifecycle.start_exit_save_pull for the two callers that mark and start back to back.
- Build every claim query on the frontend through one claimParams helper.
- Drop PlayerState casts that narrowed nothing in the launch socket handlers.
- Reuse _load_session in the _drain test helper.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:49:59 -04:00
Georges-Antoine Assi
ffdbe79032 Merge remote-tracking branch 'origin/master' into streaming-patches-5
Port the branch's emulator labels and live-state flag onto master's typed
streaming schemas, and carry the labelled state reason into
useSaveStateTabs now that the EmulatorJS view delegates to it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:37:10 -04:00
zurdi
a779fa41f7 fix(audit): apply the second pr-ready code review
- Re-measure the phone event rows whenever a web font finishes loading,
  and when a scrollbar narrows the rows, not only at mount.
- Log only the kind of an audit claim key when Redis fails, since a
  failed sign-in's key holds the text typed as the username.
- Make play-session ingest take the caller's permissions explicitly, so
  no caller skips the hidden-rom check by leaving them out.
- Read an empty collection cover URL as no cover, as the other fields do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 10:18:57 +02:00
zurdi
ff6b160117 feat: persistent notifications
Toasts disappear after a few seconds, and nothing reaches a user who has no
tab open. Notifications are now stored per user and kept until dismissed, so
what a background job or another user did is waiting the next time RomM is
opened.

Backend:
- `notifications` table (0130) with kind, level, data, actor and read_at, capped
  at the newest 200 per user.
- /api/notifications: list, mark read, dismiss one, dismiss all.
- notify()/notify_admins() store the row and push `notifications:new` to the
  user's socket room; read/dismiss push to the user's other tabs.
- Producers: a scan's end (to whoever started it; an unattended scan tells
  the admins when it failed or found new games), a manual task's end (to who
  ran it; a scheduled task's failure to the admins), an admin ending someone's
  stream, and an admin changing someone's role.

Frontend (v2):
- Unread count badge on the navbar avatar, and a Notifications entry in the
  user menu and settings sidebar.
- Notifications view: marks what it shows read, links each row to what it is
  about, dismiss one or all.
- Live toast for a new notification, except scans, which already toast.
- The text is rendered from the kind in the reader's language (18 locales).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 10:35:33 +02:00
Zach Clendenen
10c930112d fix(streaming): put an abandoned session back when its teardown fails before the stop, and give the reaper job room for the exit save pull (Greptile review) 2026-09-18 18:52:11 -05:00
Zach Clendenen
ca4ba4ee9a fix(streaming): keep a reap going past one failing container, give it the hold ceiling, keep no per-minute history, and share the abandoned-session read (code-review) 2026-09-18 16:28:02 -05:00
Zach Clendenen
9ee6bd4950 feat(streaming): reap abandoned streaming sessions every minute
A session whose heartbeat went stale was only torn down when a new claim
found every container of its platform held, so a player who left without
the pagehide release landing kept the emulator running. A scheduled task
now sweeps every configured container and hands stale sessions to the
existing abandoned-session teardown, which is made public for it.
2026-09-18 16:28:02 -05:00
Zach Clendenen
e4548b771c fix(streaming): keep retrying a webstation exit pull the exit never confirmed
A webstation exit that timed out or failed may still be writing its save dump, so taking its first answer as final could leave the archive uncollected. The stop now reports whether the broker answered, and only an answered exit or a confirmed save-and-exit takes one fetch. The claim test now makes a real claim while the pull runs.
2026-09-18 12:53:20 -05:00
Zach Clendenen
a62d1158ad fix(streaming): keep retrying a save pull the broker has not confirmed finished
A per-emulator broker acks DELETE /launch before the emulator has flushed its saves, and a blocking save-and-exit that timed out or failed may still be killing it, so one answer from those pulls could miss the session's saves. Only a webstation exit, which answers once its dump is written, and a confirmed blocking save-and-exit take the first answer as final.
2026-09-18 12:13:11 -05:00
Zach Clendenen
11eabe6431 docs(streaming): fit the branch's comments and docstrings in two lines
The repo caps a comment at two lines and a docstring at one sentence plus Args and Returns. Several comments and docstrings this branch wrote or edited ran to three lines or more, so they are tightened, with parameter notes moved under Args.
2026-09-18 12:03:10 -05:00
Zach Clendenen
36844e6c93 fix(streaming): take one answer from a save pull once the emulator has stopped
The pull retries to wait out an emulator still writing its saves, but every teardown stops the emulator first, so a pull after an exit with nothing new ran all five attempts and held the player's next claim for about twelve seconds. Only a background save-and-exit, where the broker may still be saving, keeps retrying.
2026-09-17 20:10:07 -05:00
Zach Clendenen
2512069345 fix(streaming): mark the exit save pull before the teardown stops the emulator
The release and abandoned teardowns only marked the pull after the stop, the card evacuation and the state pull. On a pool the player's next claim landed on a free sibling in that window, found nothing pending and hydrated from the archive before last. The mark now goes down as soon as the teardown owns the container, and a teardown that ends without starting the pull clears it.
2026-09-17 20:08:48 -05:00
Zach Clendenen
52893d301d fix(streaming): let a save pull clear only the mark it was given
The marker was one bare flag per user and ROM, so when two pulls overlapped the first to finish deleted the mark the second had set, and a claim behind the second stopped waiting for it. Each mark now carries a token and the clear is a compare-and-delete.
2026-09-17 20:06:55 -05:00
Zach Clendenen
8127fc11ae docs(streaming): fit the force-release note in two lines 2026-09-17 18:56:26 -05:00
Zach Clendenen
adf891b091 docs(streaming): place the force-release note before the quiesce
The note is written once the drain marker is held, so "before the drain"
pointed a reader at the wrong step.
2026-09-17 18:40:48 -05:00
Zach Clendenen
4f2d1198f2 docs(streaming): tighten the comments this branch grew
Several notes had run to four or more lines, a couple of them recounting
how the code was reordered rather than what it does now.
2026-09-17 16:59:38 -05:00
Zach Clendenen
e8c96f8aa8 refactor(streaming): drop arguments no caller varies
resolve_owned_session's include_desktop was never passed, and the two
teardown helpers and stamp_launched defaulted arguments every caller
supplies. The 409 builder's holder snapshot no longer reuses the name of
the container above it.
2026-09-17 16:53:46 -05:00
Zach Clendenen
f512bead7f fix(streaming): hold a claim until the last session's saves are filed
An exit pulls the in-game save archive off the container in a detached task,
so a claim landing right behind the release hydrated the container from the
archive before last and the player lost the session they just finished.

The teardown marks the pull pending in Redis before spawning it and clears the
marker when the task ends, and a claim waits the marker out before hydrating.
The wait is capped so a wedged pull costs one stale hydrate rather than a claim
that never answers.
2026-09-17 15:49:33 -05:00
Zach Clendenen
13e65ec375 fix(streaming): leave no ended notice when a player retakes their own session
A crashed tab leaves a stale session, and pressing Play again sweeps it.
The sweep left the same notice a force-release does, which went to the
user, whose only tab was the one that had just claimed the container: it
read the push as its own session ending and handed the claim straight
back.

The takeover now names the claimant, and the sweep skips the notice when
it is the owner coming back. A takeover by anyone else still leaves it.
2026-09-17 15:07:24 -05:00
Zach Clendenen
e3b529e214 fix(streaming): carry container and desktop on the session-ended notice
The termination notice named only the platform, so a tab could not tell
which of the account's claims had ended. One room carries them all: a
player holding two sessions from a pool, or an admin with a desktop open
alongside a game, tore down the wrong screen.

The notice now names the container it ended and whether that claim was a
desktop. Stream.vue ignores a desktop notice and one for a container it
did not claim; Desktop.vue gains the listener it never had, so a
force-released desktop says so at once instead of at the next heartbeat.

The tombstone also moves ahead of the drain in both teardown paths: the
session is over the moment the marker lands, and a poll during the
seconds of broker round trips that follow found no reason at all.
2026-09-17 15:04:27 -05:00
Georges-Antoine Assi
f78348da0f refactor(streaming): move the endpoint's domain layer into handler/streaming
endpoints/streaming.py had grown to 3778 lines, but only about a third of
that was routes. The rest was a second copy of the layer handler/streaming
already exists to hold: broker verbs, webstation protocol translation,
state and save and memory-card transfer, session teardown.

Split it along those seams rather than by route, and give claim_session
the same treatment: its 406 lines are now four named phases.

Cross-module calls go through the module (states.pull_state_to_library,
commands.stop) instead of imported names, so one definition site is what
tests patch and what every caller reads.

No route path, scope or response model changed, so the OpenAPI schema is
untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 18:47:18 -04:00