From dd6b949b6a47fcd10c169bd60a2a9e57c8b2fa8e Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 14:50:32 -0500 Subject: [PATCH] fix(streaming): bind release and heartbeat to the caller's claim A claim is the holder plus the moment they took it, so a tab that missed its own takeover could still act on the claim that replaced it: its unload release ended the new session and its beat kept it alive. Both routes now take the claimed_at the claim answered with, and a mismatch reads as a session the caller no longer holds: the release is a no-op and the heartbeat reports ended, with the termination notice the displaced tab needs. Admin releases from the settings and activity panels end whatever is running and send no stamp. --- backend/endpoints/streaming.py | 40 +++++++++++-- backend/handler/streaming/access.py | 18 ++++-- backend/tests/endpoints/test_streaming.py | 69 +++++++++++++++++++++++ 3 files changed, 117 insertions(+), 10 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 9d07e5c17..2e30bae39 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -198,6 +198,7 @@ async def _session_status( candidates: list[ResolvedContainer] | None = None, *, include_desktop: bool = False, + claimed_at: str | None = None, ) -> dict[str, Any]: """Whether the caller holds a session for this platform among `candidates` (its first pool by default), and if not, why it ended. Read-only, so it is @@ -214,6 +215,7 @@ async def _session_status( request.user.id, platform=platform, include_desktop=include_desktop, + claimed_at=claimed_at, ) if found is not None: container, _, session = found @@ -962,6 +964,7 @@ async def heartbeat_session( request: Request, platform: str, container_key: str | None = Query(default=None, alias="container", max_length=300), + claimed_at: str | None = Query(default=None, max_length=64), ) -> SessionStatusSchema: """Refresh the session's liveness stamp and report whether it still exists. @@ -974,7 +977,9 @@ async def heartbeat_session( making rather than watching a dead stream. `container` names the claim to refresh, needed for a desktop on a container - outside the platform's first pool. + outside the platform's first pool. `claimed_at` is the stamp the claim + answered with: a tab that missed its own takeover reports ended rather than + keeping the claim that replaced it alive. """ user_id = request.user.id # A named claim answers for itself: another session the caller holds on the @@ -987,12 +992,20 @@ async def heartbeat_session( else containers_for_platform(platform) ) found = await access.find_session_for_user( - candidates, user_id, platform=platform, include_desktop=named + candidates, + user_id, + platform=platform, + include_desktop=named, + claimed_at=claimed_at, ) if found is None: return SessionStatusSchema( **await _session_status( - platform, request, candidates, include_desktop=named + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) ) _, session_key, _ = found @@ -1003,7 +1016,9 @@ async def heartbeat_session( refreshed = await mutate_session( session_key, {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining") and s.get("user_id") == user_id, + require=lambda s: not s.get("draining") + and s.get("user_id") == user_id + and (claimed_at is None or s.get("claimed_at") == claimed_at), ) except StreamingSessionContended: # A key too busy to write is a key that exists, so the session is live @@ -1013,7 +1028,11 @@ async def heartbeat_session( if refreshed is None: return SessionStatusSchema( **await _session_status( - platform, request, candidates, include_desktop=named + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) ) await lifecycle.refresh_session_activity(session_key, refreshed) @@ -1232,6 +1251,7 @@ async def release_session( background_tasks: BackgroundTasks, reason: str | None = Query(default=None, max_length=200), container_key: str | None = Query(default=None, alias="container", max_length=300), + claimed_at: str | None = Query(default=None, max_length=64), save: bool = Query(default=True), ) -> ReleaseSessionResponse: """Release a session and tell the broker to stop the emulator. @@ -1244,6 +1264,9 @@ async def release_session( `save=false` is a player leaving deliberately without saving. It defaults on because the other way in here is a tab closing, where nobody chose anything and the last minutes of play would otherwise be gone. + + `claimed_at` is the stamp the claim answered with, which binds this release + to that claim. Admin panels end whatever is running and send none. """ if container_key is not None: container, session_key, session = await access.resolve_named_container( @@ -1264,6 +1287,13 @@ async def release_session( raise return ReleaseSessionResponse(status="not_found", platform=platform) + # A tab whose claim was replaced (taken over, or the player pressing Play + # again elsewhere) still releases on unload, and must not end the claim + # that took its place. + if claimed_at is not None and session.get("claimed_at") != claimed_at: + log.info("release ignored, the claim was replaced, platform=%s", platform) + return ReleaseSessionResponse(status="not_found", platform=platform) + # Teardown pulls the whole card off the broker and pushes a blank one back, # several seconds of broker round-trips. The player who quit does not need # the claim released to get their UI back, so it runs after the response is diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 7eb8ace43..8fbe2c55d 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -94,13 +94,19 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool: def _session_in_scope( - session: dict[str, Any], platform: str | None, include_desktop: bool + session: dict[str, Any], + platform: str | None, + include_desktop: bool, + claimed_at: str | None = None, ) -> bool: """Whether a stored session is one the route asked about. A container serves several platforms and holds one session, so the owner alone does not - identify it, and a desktop only answers to the caller that named it.""" + identify it, a desktop only answers to the caller that named it, and a claim + is the holder plus the moment they took it.""" if not include_desktop and session_is_desktop(session): return False + if claimed_at is not None and session.get("claimed_at") != claimed_at: + return False return platform is None or session_platform_matches(session, platform) @@ -110,19 +116,21 @@ async def find_session_for_user( *, platform: str | None = None, include_desktop: bool = False, + claimed_at: str | None = None, ) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: """The candidate holding this user's session, as (container, key, session). With a pool the platform no longer identifies the container, the session - does. `platform` scopes the match to sessions claimed for it, and a desktop - is only reachable when the caller named its container. + does. `platform` scopes the match to sessions claimed for it, `claimed_at` + to the one claim the caller was given, and a desktop is only reachable when + the caller named its container. """ for candidate in candidates: session_key = candidate.key session = await get_live_session(session_key) if session is None: continue - if not _session_in_scope(session, platform, include_desktop): + if not _session_in_scope(session, platform, include_desktop, claimed_at): continue if session.get("user_id") == user_id: return candidate, session_key, session diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index ebfdfa44d..0c561eb82 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2368,6 +2368,40 @@ def test_heartbeat_refreshes_last_seen(client, access_token, rom: Rom): assert not session_store.session_is_stale(session) +def test_a_heartbeat_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A tab that missed its takeover must not keep the claim that replaced it + alive: the stamp it was given is what identifies the claim it holds.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(_container_for(rom)))["last_seen"] + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(_container_for(rom)))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_a_heartbeat_naming_its_own_claim_still_refreshes_it( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(_container_for(rom))) + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Rom): """The refresh finds nothing when the claim was released between the lookup and the write; answering "active" there would leave the client beating a @@ -2762,6 +2796,41 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) assert r.json()["status"] == "released" +def test_a_release_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A tab whose claim was taken over still releases on unload, and it must + not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("handler.streaming.commands.stop", return_value=None) as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + assert session is not None + + +def test_a_release_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with patch("handler.streaming.commands.stop", return_value=None) as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "released" + stop.assert_called_once() + + def test_release_by_other_user_is_forbidden( client, access_token, viewer_access_token, rom: Rom ):