refactor(streaming): drain spawned tasks in the job runner for every task, build the abandoned read on the live one, and drop the reaper's extra config parse (simplify)

This commit is contained in:
Zach Clendenen
2026-09-18 16:37:05 -05:00
parent ca4ba4ee9a
commit 5ccafb361d
8 changed files with 115 additions and 82 deletions

View File

@@ -3,18 +3,8 @@
import asyncio
from typing import Any
_sync_tasks: set[asyncio.Task] = set()
from utils.background_tasks import fire_and_forget
def spawn_sync_task(coro: Any) -> asyncio.Task:
task = asyncio.get_running_loop().create_task(coro)
_sync_tasks.add(task)
task.add_done_callback(_sync_tasks.discard)
return task
async def wait_for_sync_tasks() -> None:
"""Await every task spawned on this loop, for a caller whose loop stops when it returns."""
loop = asyncio.get_running_loop()
while pending := [task for task in _sync_tasks if task.get_loop() is loop]:
await asyncio.gather(*pending, return_exceptions=True)
return fire_and_forget(coro)

View File

@@ -557,8 +557,8 @@ def session_is_stale(session: dict[str, Any]) -> bool:
async def get_abandoned_session(session_key: str) -> dict[str, Any] | None:
"""The claim on `session_key` when its heartbeat went stale, never a drain marker."""
session = await get_session(session_key)
if session is None or session.get("draining") or not session_is_stale(session):
session = await get_live_session(session_key)
if session is None or not session_is_stale(session):
return None
return session

View File

@@ -1,11 +1,9 @@
import asyncio
from handler.streaming import background
from handler.streaming.config import (
ResolvedContainer,
container_for_session,
containers_by_key,
streaming_enabled,
)
from handler.streaming.lifecycle import teardown_abandoned_session
from handler.streaming.session_store import HOLD_CEILING_SECONDS, get_abandoned_session
@@ -16,20 +14,23 @@ from tasks.tasks import PeriodicTask, TaskType
async def _reap(
grouped: dict[str, list[ResolvedContainer]], container_key: str
) -> None:
session = await get_abandoned_session(container_key)
if session is None:
return
record = container_for_session(grouped, container_key, session.get("platform"))
if record is None:
return
if await teardown_abandoned_session(
record, container_key, session, claimed_by=None
):
log.info(
"reaped abandoned streaming session, platform=%s user_id=%s",
record.platform,
session.get("user_id"),
)
try:
session = await get_abandoned_session(container_key)
if session is None:
return
record = container_for_session(grouped, container_key, session.get("platform"))
if record is None:
return
if await teardown_abandoned_session(
record, container_key, session, claimed_by=None
):
log.info(
"reaped abandoned streaming session, platform=%s user_id=%s",
record.platform,
session.get("user_id"),
)
except Exception:
log.exception("streaming session reap failed, key=%s", container_key)
class ReapStreamingSessionsTask(PeriodicTask):
@@ -48,20 +49,13 @@ class ReapStreamingSessionsTask(PeriodicTask):
)
async def run(self) -> None:
if not self.enabled or not streaming_enabled():
if not self.enabled:
return
# Concurrent, so one sick broker cannot hold up every other container.
# Empty while streaming is disabled, so a disabled install reaps nothing.
grouped = containers_by_key()
results = await asyncio.gather(
*(_reap(grouped, key) for key in grouped), return_exceptions=True
)
for key, result in zip(grouped, results, strict=True):
if isinstance(result, Exception):
log.error("streaming session reap failed, key=%s", key, exc_info=result)
# The worker's event loop stops with this job, which would strand the
# exit save pulls the teardowns spawned.
await background.wait_for_sync_tasks()
# Concurrent, so one sick broker cannot hold up every other container.
await asyncio.gather(*(_reap(grouped, key) for key in grouped))
reap_streaming_sessions_task = ReapStreamingSessionsTask()

View File

@@ -8,6 +8,7 @@ from rq import get_current_job
from config import TASK_RESULT_TTL, TASK_TIMEOUT
from exceptions.task_exceptions import TaskNotFoundException
from logger.logger import log
from utils.background_tasks import wait_for_background_tasks
from utils.context import ctx_httpx_client
@@ -34,7 +35,11 @@ async def run_task_by_name(name: str, task_kwargs: dict[str, Any] | None = None)
if task is None:
raise TaskNotFoundException(name)
return await task.run(**(task_kwargs or {}))
try:
return await task.run(**(task_kwargs or {}))
finally:
# RQ runs the job on a loop that never runs again once it returns.
await wait_for_background_tasks()
def update_job_meta(metadata: dict[str, Any]) -> None:

View File

@@ -1,7 +1,7 @@
import asyncio
import json
from collections.abc import Iterator
from contextlib import contextmanager, suppress
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
@@ -9,13 +9,14 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from handler.redis_handler import async_cache
from handler.streaming import background, commands, session_store
from handler.streaming import commands, session_store
from handler.streaming.config import ResolvedContainer, reset_cache, resolve_entry
from tasks.registry import SCHEDULED_TASKS
from tasks.scheduled.reap_streaming_sessions import (
ReapStreamingSessionsTask,
reap_streaming_sessions_task,
)
from tasks.tasks import run_task_by_name
N64 = {
"platform": "n64",
@@ -72,6 +73,13 @@ async def _hold(entry: dict, *, idle_seconds: int, **fields: Any) -> dict[str, A
return session
def _stub_teardown(teardown: Any = None) -> Any:
return patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=teardown or AsyncMock(return_value=True),
)
async def _stored(entry: dict) -> dict[str, Any] | None:
return await session_store.get_session(_resolved(entry).key)
@@ -99,10 +107,7 @@ def test_a_run_keeps_no_job_history():
async def test_a_stale_session_goes_through_the_abandoned_teardown():
with _streaming(N64):
session = await _hold(N64, idle_seconds=STALE)
with patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=AsyncMock(return_value=True),
) as teardown:
with _stub_teardown() as teardown:
await ReapStreamingSessionsTask().run()
teardown.assert_awaited_once_with(
@@ -117,10 +122,7 @@ async def test_fresh_sessions_and_drain_markers_are_left_alone():
session_store.session_redis_key(_resolved(PSX).key),
session_store.drain_marker("draining"),
)
with patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=AsyncMock(return_value=True),
) as teardown:
with _stub_teardown() as teardown:
await ReapStreamingSessionsTask().run()
teardown.assert_not_awaited()
@@ -136,10 +138,7 @@ async def test_a_shared_container_tears_down_under_the_sessions_own_platform():
}
with _streaming(shared):
await _hold(N64, idle_seconds=STALE, platform="psx")
with patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=AsyncMock(return_value=True),
) as teardown:
with _stub_teardown() as teardown:
await ReapStreamingSessionsTask().run()
teardown.assert_awaited_once()
@@ -162,10 +161,7 @@ async def test_one_failing_container_does_not_cut_the_others_short():
with _streaming(N64, PSX):
await _hold(N64, idle_seconds=STALE)
await _hold(PSX, idle_seconds=STALE)
with patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=teardown,
):
with _stub_teardown(teardown):
await ReapStreamingSessionsTask().run()
assert finished == ["psx"]
@@ -174,10 +170,7 @@ async def test_one_failing_container_does_not_cut_the_others_short():
async def test_nothing_runs_while_streaming_is_disabled():
with _streaming(N64, enabled=False):
await _hold(N64, idle_seconds=STALE)
with patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
new=AsyncMock(return_value=True),
) as teardown:
with _stub_teardown() as teardown:
await ReapStreamingSessionsTask().run()
teardown.assert_not_awaited()
@@ -202,7 +195,7 @@ async def test_a_reaped_session_frees_its_container_and_leaves_a_notice():
assert notice is not None and notice["reason"] == "abandoned"
async def test_the_run_waits_for_the_exit_save_pull_it_spawned():
async def test_the_job_waits_for_the_exit_save_pull_it_spawned():
"""A worker's event loop stops with the job, so a pull still spawned when
the run returns would never file the saves or clear its pending mark."""
pulled = asyncio.Event()
@@ -221,26 +214,11 @@ async def test_the_run_waits_for_the_exit_save_pull_it_spawned():
patch("handler.streaming.lifecycle.record_play_session"),
patch("handler.streaming.saves.pull_saves_to_library", new=pull),
):
await ReapStreamingSessionsTask().run()
await run_task_by_name("reap_streaming_sessions")
assert pulled.is_set()
async def test_waiting_for_spawned_tasks_skips_another_loops():
"""A task left on a loop that is not running can never finish."""
other_loop = asyncio.new_event_loop()
stranded = other_loop.create_task(asyncio.sleep(60))
background._sync_tasks.add(stranded)
try:
await asyncio.wait_for(background.wait_for_sync_tasks(), timeout=1)
finally:
background._sync_tasks.discard(stranded)
stranded.cancel()
with suppress(asyncio.CancelledError):
await asyncio.to_thread(other_loop.run_until_complete, stranded)
other_loop.close()
async def test_overlapping_runs_tear_a_session_down_once():
"""Two workers can both see the same stale session; the drain marker's
compare-and-set lets only one of them stop the emulator."""

View File

@@ -1,3 +1,4 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
@@ -5,6 +6,7 @@ import pytest
from exceptions.task_exceptions import TaskNotFoundException
from tasks.tasks import PeriodicTask, RemoteFilePullTask, TaskType, run_task_by_name
from utils.background_tasks import fire_and_forget
class ConcretePeriodicTask(PeriodicTask):
@@ -184,3 +186,23 @@ class TestRunTaskByName:
with pytest.raises(TaskNotFoundException, match="some_task"):
await run_task_by_name("some_task")
async def test_waits_for_what_the_task_spawned(self, mocker):
"""RQ runs each job on a loop that never runs again once the job returns,
so work the task spawned and left running would be frozen partway."""
finished = asyncio.Event()
async def later() -> None:
await asyncio.sleep(0.05)
finished.set()
async def run() -> None:
fire_and_forget(later())
task = MagicMock()
task.run = run
mocker.patch("tasks.registry.get_task", return_value=task)
await run_task_by_name("some_task")
assert finished.is_set()

View File

@@ -0,0 +1,36 @@
import asyncio
from contextlib import suppress
from utils import background_tasks
async def test_waiting_skips_another_loops_tasks():
"""A task left on a loop that is not running can never finish."""
other_loop = asyncio.new_event_loop()
stranded = other_loop.create_task(asyncio.sleep(60))
background_tasks._background_tasks.add(stranded)
try:
await asyncio.wait_for(background_tasks.wait_for_background_tasks(), timeout=1)
finally:
background_tasks._background_tasks.discard(stranded)
stranded.cancel()
with suppress(asyncio.CancelledError):
await asyncio.to_thread(other_loop.run_until_complete, stranded)
other_loop.close()
async def test_waiting_covers_tasks_spawned_while_waiting():
finished = asyncio.Event()
async def second() -> None:
await asyncio.sleep(0.01)
finished.set()
async def first() -> None:
await asyncio.sleep(0.01)
background_tasks.fire_and_forget(second())
background_tasks.fire_and_forget(first())
await background_tasks.wait_for_background_tasks()
assert finished.is_set()

View File

@@ -6,8 +6,16 @@ from typing import Any
_background_tasks: set[asyncio.Task[Any]] = set()
def fire_and_forget(coro: Coroutine[Any, Any, Any]) -> None:
def fire_and_forget(coro: Coroutine[Any, Any, Any]) -> asyncio.Task[Any]:
"""Schedule a coroutine without awaiting it."""
task = asyncio.create_task(coro)
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
return task
async def wait_for_background_tasks() -> None:
"""Await every task scheduled on this loop, for a caller whose loop stops when it returns."""
loop = asyncio.get_running_loop()
while pending := [task for task in _background_tasks if task.get_loop() is loop]:
await asyncio.gather(*pending, return_exceptions=True)