perf(rq): Save 67MB RAM; keep the database and API out of streaming worker's parent (#5755)

* perf(streaming) lazy loading in streaming worker

* perf(rq): push _resolved to test container

* pr-ready: code-review

Move the reaper import guard into test_task_func_paths.py, reusing
BACKEND_ROOT and JOB_ONLY_MODULES, watch socket_handler and lifecycle too,
check the deferred imports still load, and surface stderr on failure.
Explain the lazy socket_handler import.

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

* pr-ready: simplify

Defer the lifecycle import inside _reap instead of wrapping its teardown,
share one subprocess helper between the import guards, and check every
streaming-queue task the PreloadingWorker parent would load.

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

* pr-ready: review-polish

Keep the import-guard helper's docstring to one sentence.

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

* pr-ready: prose

Write the lazy-import and guard comments as full sentences.

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

* refactor(streaming): move session notices out of session_store

record_termination and push_to_user deliver over the socket and as
notifications, so they now live in handler/streaming/notices.py with
top-level imports. session_store keeps only the Redis tombstone write
(save_termination) and loads neither the database nor socketio.

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

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stu Anderson
2026-11-28 19:30:04 -06:00
committed by GitHub
parent 355ce188a4
commit 39ed3a05b6
9 changed files with 150 additions and 88 deletions

View File

@@ -100,6 +100,7 @@ from handler.streaming.config import (
first_claim_targets,
streaming_enabled,
)
from handler.streaming.notices import record_termination
from handler.streaming.protocol import room_url_on
from handler.streaming.session_store import (
STREAMING_SESSION_DRAIN_SECONDS,
@@ -117,7 +118,6 @@ from handler.streaming.session_store import (
iter_live_sessions,
iter_session_keys,
mutate_session,
record_termination,
refresh_session,
release_own_session,
same_claim,

View File

@@ -25,10 +25,10 @@ from handler.streaming import (
webstation,
)
from handler.streaming.config import ResolvedContainer
from handler.streaming.notices import push_to_user
from handler.streaming.session_store import (
StreamingSession,
hold_session_claim,
push_to_user,
set_session_disc,
stamp_launched,
)

View File

@@ -22,6 +22,7 @@ from handler.streaming.config import (
container_for_session,
containers_by_key,
)
from handler.streaming.notices import record_termination
from handler.streaming.session_store import (
DRAIN_MARKER_TTL,
DiscSwap,
@@ -33,7 +34,6 @@ from handler.streaming.session_store import (
drop_drain_marker,
hold_drain_marker,
hold_session_claim,
record_termination,
release_own_session,
replace_session_if,
restore_drained_session,

View File

@@ -0,0 +1,73 @@
"""Telling a player what happened to their streaming session.
Kept apart from session_store because delivery loads the socket server and the
database, which the streaming worker's parent must not hold.
"""
from datetime import datetime, timezone
from typing import Any
from handler.notification_handler import notify
from handler.socket_handler import socket_handler
from handler.streaming.session_store import (
StreamingSession,
save_termination,
session_is_desktop,
)
from models.notification import NotificationKind, NotificationLevel
async def record_termination(
session: StreamingSession,
session_key: str,
*,
ended_by: str | None,
reason: str | None,
ended_by_user_id: int | None = None,
) -> None:
"""Leave a note for the player whose session was taken away, and push it
over the socket so the poll isn't the only way that tab finds out. No-op
when the session records no owner, since there is nobody to notify."""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
notice = {
"ended_by": ended_by,
"reason": reason or None,
"ended_at": datetime.now(timezone.utc).isoformat(),
"platform": session.get("platform"),
"rom_id": session.get("rom_id"),
"rom_name": session.get("rom_name"),
# Which claim ended: a user can hold one per container, plus a desktop,
# and only the tab that holds this one should act on the notice.
"container": session_key,
# A re-claim of the container keeps its key, so the stamp names the claim.
"claimed_at": session.get("claimed_at"),
"desktop": session_is_desktop(session),
}
await save_termination(session_key, user_id, notice)
await push_to_user(user_id, "streaming:session-ended", notice)
if ended_by_user_id is not None and ended_by_user_id != user_id:
await notify(
user_id,
NotificationKind.STREAMING_SESSION_ENDED,
NotificationLevel.WARNING,
{
"rom_id": notice["rom_id"],
"rom_name": notice["rom_name"],
"platform": notice["platform"],
"reason": notice["reason"],
},
actor_id=ended_by_user_id,
)
async def push_to_user(user_id: Any, event: str, payload: dict[str, Any]) -> None:
"""Tell one user's open tabs something happened to their session.
Best-effort by design: every event pushed here also has a poll behind it,
so a dropped socket costs latency rather than correctness.
"""
if isinstance(user_id, int):
await socket_handler.emit_to_user(user_id, event, payload)

View File

@@ -24,12 +24,9 @@ from typing import Any, NamedTuple, TypedDict, cast
from redis.exceptions import WatchError
from handler.notification_handler import notify
from handler.redis_handler import as_text, async_cache
from handler.socket_handler import socket_handler
from handler.streaming.config import HOLD_CEILING_SECONDS
from logger.logger import log
from models.notification import NotificationKind, NotificationLevel
# Sessions are stored in Redis so they are shared across uvicorn workers and
# survive backend restarts (the emulator container keeps running either way).
@@ -695,64 +692,14 @@ def _termination_redis_key(session_key: str, user_id: int) -> str:
return f"{_TERMINATION_KEY_PREFIX}{session_key}:{user_id}"
async def record_termination(
session: StreamingSession,
session_key: str,
*,
ended_by: str | None,
reason: str | None,
ended_by_user_id: int | None = None,
async def save_termination(
session_key: str, user_id: int, notice: dict[str, Any]
) -> None:
"""Leave a note for the player whose session was taken away, and push it
over the socket so the poll isn't the only way that tab finds out. No-op
when the session records no owner, since there is nobody to notify."""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
notice = {
"ended_by": ended_by,
"reason": reason or None,
"ended_at": datetime.now(timezone.utc).isoformat(),
"platform": session.get("platform"),
"rom_id": session.get("rom_id"),
"rom_name": session.get("rom_name"),
# Which claim ended: a user can hold one per container, plus a desktop,
# and only the tab that holds this one should act on the notice.
"container": session_key,
# A re-claim of the container keeps its key, so the stamp names the claim.
"claimed_at": session.get("claimed_at"),
"desktop": session_is_desktop(session),
}
await async_cache.set(
_termination_redis_key(session_key, user_id),
json.dumps(notice),
ex=_TERMINATION_TTL_SECONDS,
)
await push_to_user(user_id, "streaming:session-ended", notice)
if ended_by_user_id is not None and ended_by_user_id != user_id:
await notify(
user_id,
NotificationKind.STREAMING_SESSION_ENDED,
NotificationLevel.WARNING,
{
"rom_id": notice["rom_id"],
"rom_name": notice["rom_name"],
"platform": notice["platform"],
"reason": notice["reason"],
},
actor_id=ended_by_user_id,
)
async def push_to_user(user_id: Any, event: str, payload: dict[str, Any]) -> None:
"""Tell one user's open tabs something happened to their session.
Best-effort by design: every event pushed here also has a poll behind it,
so a dropped socket costs latency rather than correctness.
"""
if isinstance(user_id, int):
await socket_handler.emit_to_user(user_id, event, payload)
async def get_termination(session_key: str, user_id: int) -> dict[str, Any] | None:

View File

@@ -6,7 +6,6 @@ from handler.streaming.config import (
containers_by_key,
streaming_enabled,
)
from handler.streaming.lifecycle import teardown_abandoned_session
from handler.streaming.session_store import (
get_abandoned_session,
in_restart_grace,
@@ -26,6 +25,9 @@ async def _reap(
record = container_for_session(grouped, container_key, session.get("platform"))
if record is None:
return
# Imported here so the streaming worker's parent never loads the database.
from handler.streaming.lifecycle import teardown_abandoned_session
if await teardown_abandoned_session(
record, container_key, session, claimed_by=None
):

View File

@@ -3480,7 +3480,7 @@ def test_taking_over_ones_own_stale_session_pushes_no_notice(
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
with (
_stub_stop(),
patch("handler.streaming.session_store.push_to_user", new=_capture),
patch("handler.streaming.notices.push_to_user", new=_capture),
):
_claim_ok(client, access_token, rom.id)

View File

@@ -90,7 +90,7 @@ async def _hold(
def _stub_teardown(teardown: Any = None) -> Any:
return patch(
"tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session",
"handler.streaming.lifecycle.teardown_abandoned_session",
new=teardown or AsyncMock(return_value=True),
)

View File

@@ -40,10 +40,42 @@ def test_task_func_resolves_in_a_fresh_interpreter(func):
assert result.returncode == 0, f"{func} is not importable by RQ:\n{result.stderr}"
def _loaded_after(
setup: str, watched: tuple[str, ...], base_path: Path, then: str = ""
) -> str:
"""List the `watched` modules a fresh interpreter loads for `setup`, then run `then`."""
result = subprocess.run(
[
sys.executable,
"-c",
"import sys\n"
f"{setup}\n"
"watched = sys.argv[1:]\n"
"loaded = ','.join(m for m in sys.modules\n"
" if any(m == w or m.startswith(w + '.') for w in watched))\n"
f"{then}\n"
"print('LOADED:' + loaded)\n",
*watched,
],
cwd=BACKEND_ROOT,
env={
**os.environ,
"PYTHONPATH": str(BACKEND_ROOT),
"ROMM_BASE_PATH": str(base_path),
# A developer's .env could otherwise turn telemetry on.
"OTEL_SDK_DISABLED": "true",
},
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
return result.stdout.rpartition("LOADED:")[2].strip()
# Loaded only by the jobs that need them, so the long-lived scheduler and
# worker parents stay small. Each name covers its submodules too.
JOB_ONLY_MODULES = (
"tasks.scheduled",
HEAVY_MODULES = (
"tasks.manual",
"tasks.sync_push_pull_task",
"handler.database",
@@ -52,6 +84,7 @@ JOB_ONLY_MODULES = (
"httpx2",
"sqlalchemy",
)
JOB_ONLY_MODULES = ("tasks.scheduled", *HEAVY_MODULES)
@pytest.mark.parametrize("module", ["tasks.cron_config", "handler.rq_worker"])
@@ -64,30 +97,37 @@ def test_the_scheduler_and_worker_load_no_task_code(
) -> None:
(tmp_path / "config").mkdir()
(tmp_path / "config" / "config.yml").write_text(config_yml)
result = subprocess.run(
[
sys.executable,
"-c",
"import importlib, sys\n"
"importlib.import_module(sys.argv[1])\n"
"watched = sys.argv[2:]\n"
"print('LOADED:' + ','.join(m for m in sys.modules\n"
" if any(m == w or m.startswith(w + '.') for w in watched)))\n",
module,
*JOB_ONLY_MODULES,
],
cwd=BACKEND_ROOT,
env={
**os.environ,
"PYTHONPATH": str(BACKEND_ROOT),
"ROMM_BASE_PATH": str(tmp_path),
# A developer's .env could otherwise turn telemetry on.
"OTEL_SDK_DISABLED": "true",
},
capture_output=True,
text=True,
loaded = _loaded_after(f"import {module}", JOB_ONLY_MODULES, tmp_path)
assert loaded == "", f"{module} loads {loaded}"
# The streaming work horse loads these only when it tears down a session or sends a notice.
PRELOAD_DEFERRED_MODULES = (
*HEAVY_MODULES,
"handler.scan",
"handler.metadata",
"handler.streaming.lifecycle",
"handler.socket_handler",
"endpoints",
)
def test_the_streaming_worker_preloads_its_tasks_without_their_teardown(
tmp_path: Path,
) -> None:
"""The parent keeps what it preloads, and a work horse can still import the rest."""
# PreloadingWorker loads only the enabled tasks, and this loads all of them.
loaded = _loaded_after(
"import handler.rq_worker\n"
"from handler.redis_handler import STREAMING_QUEUE_NAME\n"
"from tasks.registry import SCHEDULED_TASKS, get_task\n"
"for name, spec in SCHEDULED_TASKS.items():\n"
" if spec.queue_name == STREAMING_QUEUE_NAME:\n"
" get_task(name)",
PRELOAD_DEFERRED_MODULES,
tmp_path,
then="import handler.streaming.lifecycle, handler.notification_handler",
)
assert result.returncode == 0, result.stderr
loaded = result.stdout.rpartition("LOADED:")[2].strip()
assert loaded == "", f"{module} loads {loaded}"
assert loaded == "", f"the streaming preload loads {loaded}"