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

582 lines
21 KiB
Python

"""What every teardown path does, and in what order.
Stopping the emulator, evacuating and wiping the card, crediting the playtime,
filing the exit state and saves, and only then giving the container back. The
order is load-bearing and lives here once rather than in each route that ends
a session.
"""
import asyncio
import secrets
from collections.abc import Coroutine
from datetime import datetime, timezone
from typing import Any
from handler.activity_handler import activity_handler
from handler.database import db_user_handler
from handler.play_session_handler import ingest_play_sessions
from handler.redis_handler import streaming_queue
from handler.streaming import background, commands, memory_cards, saves, states
from handler.streaming.config import (
ResolvedContainer,
container_for_session,
containers_by_key,
)
from handler.streaming.session_store import (
DRAIN_MARKER_TTL,
DiscSwap,
StreamingSessionContended,
broker_session_id,
claim_drain_marker,
drain_marker,
drop_drain_marker,
hold_drain_marker,
hold_session_claim,
record_termination,
release_own_session,
replace_session_if,
restore_drained_session,
same_claim,
session_disc_id,
session_disc_swaps,
session_is_stale,
)
from logger.logger import log
async def abort_claim(
session_key: str,
claim: dict[str, Any],
blank_card_id: int | None = None,
) -> None:
"""Undo a claim that will not become a session.
Every exit from `claim_session` that is not a started session goes through
here: leaving the key behind wedges the container until the TTL lapses, and
leaving an auto-created blank card behind orphans a row nobody asked for.
Guarded like every other release: a card probe or an activate blocks for
minutes, and an unguarded delete would free a container an admin release
and a fresh claim had already handed to somebody else.
"""
if not await release_own_session(session_key, claim):
log.warning("aborted claim on %s was no longer ours", session_key)
if blank_card_id is not None:
await memory_cards.discard_blank_card(blank_card_id)
def _hold_reservation(
session_key: str, token: str | None, claim: dict[str, Any]
) -> asyncio.Future[None]:
"""Keep a container reserved while a teardown runs.
The drain marker holds it where one landed; where it did not, nothing took
the container over and the claim itself still reserves it. Either way the
stamp is kept current, since the player who owned it has left and an
unrefreshed reservation reads as abandoned to the next claimant.
"""
return asyncio.ensure_future(
hold_drain_marker(session_key, token)
if token is not None
else hold_session_claim(session_key, claim)
)
async def _drop_reservation(
session_key: str, token: str | None, claim: dict[str, Any]
) -> None:
"""Free whatever `_hold_reservation` was holding. `token` keeps the release
aimed at this drain, so an overrun that outlived its own marker cannot free
whoever took the container afterwards."""
if token is not None:
await drop_drain_marker(session_key, token)
elif not await release_own_session(session_key, claim):
log.error("session %s survived its own exit", session_key)
async def release_after_state_pull(
session_key: str,
pull: Coroutine[Any, Any, Any],
token: str | None,
claim: dict[str, Any],
) -> None:
"""Run the exit state pull, then free the container it was holding.
The reservation goes even when the pull raised: the state is recoverable
from the container on the next claim, a container nothing releases is not.
"""
keepalive = _hold_reservation(session_key, token, claim)
try:
await pull
finally:
keepalive.cancel()
await _drop_reservation(session_key, token, claim)
async def quiesce_container(
container: ResolvedContainer, session: dict[str, Any], *, save: bool = True
) -> commands.StopOutcome:
"""Stop the emulator, then evacuate and wipe its memory card.
Every teardown path opens this way, and the order is load-bearing: stopping
first is what makes the card quiescent, and the wipe runs only where the
evacuation captured the card. Returns what the stop left to collect.
"""
stopped = await asyncio.to_thread(commands.stop, container, save)
if await memory_cards.evacuate_session_card(session, container):
await memory_cards.wipe_session_card(container)
return stopped
async def pull_exit_saves(
*,
user_id: int,
rom_id: int,
token: str,
container_key: str,
platform: str,
broker_session: str | None,
settled: bool,
disc_file_id: int | None = None,
disc_swaps: list[DiscSwap] | None = None,
) -> None:
"""The RQ job behind `collect_exit_saves`, which lets the next claim through
however the pull ended."""
try:
container = container_for_session(containers_by_key(), container_key, platform)
if container is None:
log.warning("skipping the exit save pull, %s is gone", container_key)
return
await saves.pull_saves_to_library(
user_id,
rom_id,
container,
broker_session,
settled=settled,
disc_file_id=disc_file_id,
disc_swaps=disc_swaps or [],
)
finally:
await saves.clear_save_pull_pending(saves.SavePullMark(user_id, rom_id, token))
async def mark_exit_saves_pending(
container: ResolvedContainer, session: dict[str, Any]
) -> saves.SavePullMark | None:
"""Hold the owner's next claim on this ROM until the exit pull has filed.
Returns:
The mark for `collect_exit_saves`, or None when no pull will run: a
whole-card sync container evacuates the card instead, and a desktop ran
no ROM to file one under.
"""
rom_id = session.get("rom_id")
user_id = session.get("user_id")
if (
container.memory_card_sync
or not isinstance(rom_id, int)
or not isinstance(user_id, int)
):
return None
return await saves.mark_save_pull_pending(user_id, rom_id)
async def collect_exit_saves(
container: ResolvedContainer,
session: dict[str, Any],
mark: saves.SavePullMark | None,
*,
settled: bool,
) -> None:
"""Queue the pull of a stopped session's save archive, since the broker keeps
it after the emulator dies, filing it under the owner whoever ended it.
Args:
mark: cleared by the pull however it ends.
settled: the broker confirmed the emulator is done writing, so the first
answer is final.
"""
if mark is None:
return
try:
# On the streaming worker, so a web restart cannot cut a pull short.
streaming_queue.enqueue(
pull_exit_saves,
kwargs={
"user_id": mark.user_id,
"rom_id": mark.rom_id,
"token": mark.token,
"container_key": container.key,
"platform": container.platform,
"broker_session": broker_session_id(session),
"settled": settled,
"disc_file_id": session_disc_id(session),
"disc_swaps": session_disc_swaps(session),
},
job_timeout=saves.SAVE_PULL_TTL_SECONDS,
result_ttl=0,
meta={"task_name": "Streaming exit save pull"},
)
except Exception:
log.exception("could not queue the exit save pull for %s", container.key)
await saves.clear_save_pull_pending(mark)
async def start_exit_save_pull(
container: ResolvedContainer, session: dict[str, Any], *, settled: bool
) -> None:
"""Mark the exit pull pending, then start it, for a stop that is already done."""
mark = await mark_exit_saves_pending(container, session)
await collect_exit_saves(container, session, mark, settled=settled)
async def collect_exit_state(
container: ResolvedContainer, session: dict[str, Any], state_slot: int | None
) -> None:
"""File the state the stop wrote, while the claim still guards the container.
The broker keeps an exited session's state only until the next activate, and
dropping the claim is what lets that activate happen.
"""
rom_id = session.get("rom_id")
user_id = session.get("user_id")
if (
state_slot is None
or not isinstance(rom_id, int)
or not isinstance(user_id, int)
):
return
await states.pull_state_to_library(
user_id,
rom_id,
container,
state_slot,
disc_file_id=session_disc_id(session),
)
# Streaming sessions shorter than this are treated as accidental (a claim that
# was released almost immediately) and not recorded as playtime.
_MIN_PLAY_SESSION_MS = 5_000
# A streaming session is a play session like any other, so it goes on the
# activity board next to the devices. The container key stands in for a device
# id: a user holds at most one session per container, which is what
# clear_active needs to find the entry again.
_DEVICE_TYPE = "streaming"
async def publish_session_activity(session_key: str, session: dict[str, Any]) -> None:
"""Put a live streaming session on the activity board.
Best-effort: the board is a view, never a reason to fail a launch.
"""
user_id = session.get("user_id")
rom_id = session.get("rom_id")
if not isinstance(user_id, int) or not isinstance(rom_id, int):
return
try:
entry = await activity_handler.build_entry(
user_id=user_id,
device_id=session_key,
rom_id=rom_id,
preserve_started_at=True,
device_type=_DEVICE_TYPE,
)
if entry is not None:
await activity_handler.publish_active(entry)
except Exception:
log.exception("failed to publish streaming session activity")
async def refresh_session_activity(session_key: str, session: dict[str, Any]) -> None:
"""Keep the activity entry alive on the player's heartbeat.
Re-stores what is already there instead of rebuilding it: nothing on the
entry changes for the length of a session, and a beat every 30s per session
would otherwise cost two queries and a broadcast each time. An entry that
has gone (expired while the backend was down) is rebuilt.
"""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
try:
existing = await activity_handler.get_active(user_id, session_key)
except Exception:
log.exception("failed to read streaming session activity")
return
if existing is None:
await publish_session_activity(session_key, session)
return
try:
await activity_handler.set_active(existing)
except Exception:
log.exception("failed to refresh streaming session activity")
async def clear_session_activity(session_key: str, session: dict[str, Any]) -> None:
"""Take a finished streaming session off the activity board.
Every teardown path calls this: the board is socket-driven, so an entry left
behind sits on an open board until its TTL runs out.
"""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
try:
await activity_handler.publish_clear(user_id, session_key)
except Exception:
log.exception("failed to clear streaming session activity")
async def record_play_session(session: dict[str, Any]) -> None:
"""Record a finished streaming session as RomM playtime.
Reuses the same ingest path as device sync (dedup on user+rom+start_time,
updates the ROM's last_played). The session's stored claimed_at is the
start and now is the end. Best-effort: any failure is logged, never fatal,
so playtime accounting cannot block or fail a teardown.
"""
user_id = session.get("user_id")
rom_id = session.get("rom_id")
claimed_at = session.get("claimed_at")
if (
not isinstance(user_id, int)
or not isinstance(rom_id, int)
or not isinstance(claimed_at, str)
):
return
try:
start = datetime.fromisoformat(claimed_at)
except ValueError:
return
if start.tzinfo is None:
start = start.replace(tzinfo=timezone.utc)
end = datetime.now(timezone.utc)
duration_ms = int((end - start).total_seconds() * 1000)
if duration_ms < _MIN_PLAY_SESSION_MS:
return
try:
user = db_user_handler.get_user(user_id)
ingest_play_sessions(
user_id=user_id,
username=user.username if user else str(user_id),
entries=[
{
"rom_id": rom_id,
"save_slot": None,
"start_time": start,
"end_time": end,
"duration_ms": duration_ms,
}
],
# The rom was checked against the user when the stream was claimed.
perms=None,
)
except Exception:
log.exception("failed to record play session")
async def teardown_released_session(
container: ResolvedContainer,
session: dict[str, Any],
session_key: str,
platform: str,
*,
acting_user_id: int,
acting_username: str,
reason: str | None,
save: bool = True,
) -> None:
"""Stop the emulator, evacuate the card, then release the claim.
Ordering is load-bearing (see the inline notes). Runs detached from the
release request; every step is best-effort so a teardown hiccup cannot wedge
the claim, which the stale-session takeover reclaims if this never finishes.
"""
# Take the claim into a drain marker first. Everything below runs detached
# and blocks on the broker for as long as the emulator takes to die, so a
# takeover landing in that window would otherwise have its emulator stopped
# and its claim deleted along with the session it replaced.
try:
token = await claim_drain_marker(session_key, session)
except StreamingSessionContended:
# The claim is still ours, it just could not be marked: it is what
# reserves the container below, and the delete at the end is guarded on
# it anyway.
log.error("could not drain released session %s", session_key)
token = None
else:
if token is None:
log.warning("skipping teardown, session %s was taken over", session_key)
return
keepalive = _hold_reservation(session_key, token, session)
pull_mark: saves.SavePullMark | None = None
try:
# Before anything slow: on a pool the player's next claim can land on a
# free sibling while this container drains.
pull_mark = await mark_exit_saves_pending(container, session)
# A force-release rather than the player quitting: another user, or a reason,
# which only the admin panel sends. Before the quiesce, so a poll finds it.
if session.get("user_id") != acting_user_id or reason is not None:
await record_termination(
session,
session_key,
ended_by=acting_username,
reason=reason,
ended_by_user_id=acting_user_id,
)
log.info(
"session force-released, platform=%s by=%s user_id=%s reason=%s",
platform,
acting_username,
session.get("user_id"),
reason or "-",
)
# The marker, or the claim it could not replace, holds the container
# throughout, so no concurrent claim can interleave.
stopped = await quiesce_container(container, session, save=save)
await record_play_session(session)
await clear_session_activity(session_key, session)
# Awaited, not spawned: the claim is released below.
await collect_exit_state(container, session, stopped.state_slot)
await collect_exit_saves(container, session, pull_mark, settled=stopped.settled)
# The pull clears it from here.
pull_mark = None
log.info("session released, platform=%s", platform)
except Exception:
log.exception("session teardown failed, platform=%s", platform)
finally:
# The claim goes even when a step above raised. The API already told the
# caller the session was released, so a key left behind blocks every
# later claim until stale takeover or the TTL expires. A card left
# un-evacuated is recoverable, since the next claim prompts to adopt
# whatever is still on the container; a phantom claim is not.
keepalive.cancel()
await _drop_reservation(session_key, token, session)
if pull_mark is not None:
# No pull is coming, so a claim has nothing to wait for.
await saves.clear_save_pull_pending(pull_mark)
async def teardown_abandoned_session(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
*,
claimed_by: int | None,
) -> bool:
"""Free a container whose owner vanished without releasing (heartbeat went
stale). Same order as an owner release: stop the emulator so the card is
quiescent, evacuate and wipe it, credit the owner's playtime, then drop
the claim.
Args:
claimed_by: the user whose claim found the session, None for the reaper.
Returns:
Whether the emulator was stopped: False when the session stopped looking
abandoned first, or a step before the stop failed and it was put back.
"""
# Claim the teardown before touching the broker. The work below runs for
# seconds, and the staleness check that led here is older still, so without
# the marker a heartbeat landing in that window would refresh a claim whose
# container is already being wiped. Re-checking staleness under the same
# watch is what makes the decision current rather than the caller's, and the
# marker's own token is what keeps a second claim from running all of this
# a second time over the same container.
token = secrets.token_hex(8)
try:
marked = await replace_session_if(
session_key,
lambda current: session_is_stale(current) and same_claim(current, session),
drain_marker(token),
DRAIN_MARKER_TTL,
)
except StreamingSessionContended:
# Somebody is writing to this key, so it is not the derelict session
# this path exists to clean up.
return False
if not marked:
return False
keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token))
pull_mark: saves.SavePullMark | None = None
stopping = False
try:
# Before anything slow, as a release does.
pull_mark = await mark_exit_saves_pending(container, session)
# That tab may still be showing the stream, so leave a force-release's note,
# but not for the owner coming back, whose new tab it would end.
if session.get("user_id") != claimed_by:
await record_termination(
session, session_key, ended_by=None, reason="abandoned"
)
stopping = True
stopped = await quiesce_container(container, session)
await record_play_session(session)
await clear_session_activity(session_key, session)
await collect_exit_state(container, session, stopped.state_slot)
await collect_exit_saves(container, session, pull_mark, settled=stopped.settled)
pull_mark = None
except Exception:
log.exception("abandoned session teardown failed, key=%s", session_key)
finally:
keepalive.cancel()
# Past the stop, free the container rather than park it until the marker
# lapses. Before it, a claim would launch over the running emulator.
if stopping:
await drop_drain_marker(session_key, token)
else:
await restore_drained_session(session_key, token, session)
if pull_mark is not None:
await saves.clear_save_pull_pending(pull_mark)
return stopping
# How long a claim waits for stale sessions to be torn down before it gives up.
# The teardown stops a broker, evacuates and wipes a card and pulls the exit
# state, each with its own timeout and retries, so on a sick container it can
# run for minutes. A claim is an interactive request and must not, so this is
# the budget for the whole sweep rather than for each container in it.
ABANDONED_TEARDOWN_WAIT = 30.0
async def await_teardown_within_budget(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
budget: float,
*,
claimed_by: int,
) -> bool:
"""Tear down an abandoned session, but only wait `budget` seconds for it.
A teardown that overruns keeps running, shielded, and frees the container
when it lands. It is never cancelled part-way: the card evacuation and the
state pull are the abandoned player's only copies, and the drain marker
this leaves behind blocks a claim until the teardown drops it.
"""
task = background.spawn_sync_task(
teardown_abandoned_session(
container, session_key, session, claimed_by=claimed_by
)
)
try:
return await asyncio.wait_for(asyncio.shield(task), timeout=budget)
except asyncio.TimeoutError:
log.warning(
"stale session teardown is taking too long, leaving it to finish, key=%s",
session_key,
)
return False