From 06f659d804754ef73657a17b39c5900dd107381f Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 07:05:04 -0800 Subject: [PATCH 1/6] Release reservations rejected during session validation --- CHANGELOG.md | 6 ++ src/livepeer_gateway/selection.py | 99 ++++++++++++++++++++++++------ tests/test_live_runner_payments.py | 5 ++ tests/test_reservation_cleanup.py | 91 +++++++++++++++++++++++++++ 4 files changed, 181 insertions(+), 20 deletions(-) create mode 100644 tests/test_reservation_cleanup.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e1added..d76a01a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- Release identifiable reservations when `reserve_session()` rejects a malformed + response. Cleanup retries transient failures and survives cancellation; an + exhausted cleanup preserves the validation error and retains its session handle. + ### Added - `LiveRunnerRegistration.stop_session()` to stop reserved sessions diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 0118198..044a4ca 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -1,8 +1,10 @@ from __future__ import annotations +import asyncio import logging from collections.abc import Sequence from typing import Any +from urllib.parse import quote, urlsplit, urlunsplit from .discovery import ( FilterValue, @@ -20,6 +22,7 @@ LiveRunnerSession, _live_runner_price_info_from_json, call_runner, + stop_runner_session, ) from .runner_payload import RunnerPayload, _ReplayUnavailableError, _StreamState, _stream_state @@ -207,27 +210,83 @@ async def reserve_session( timeout=timeout, ) result = await cursor.next() - session_id = result.data.get("session_id") - app_url = result.data.get("app_url") - control_url = _string_value(result.data.get("control_url")) - if not isinstance(session_id, str) or not session_id.strip(): - raise LivepeerGatewayError("runner session response missing session_id") - if not isinstance(app_url, str) or not app_url.strip(): - raise LivepeerGatewayError("runner session response missing app_url") - if not control_url: - raise LivepeerGatewayError("runner session response missing control_url") - session = LiveRunnerSession( - session_id=session_id.strip(), - app_url=app_url.strip(), - runner_url=result.runner_url, - control_url=control_url, - runner=result.runner, - ) + data = result.data if isinstance(result.data, dict) else {} + session_id = data.get("session_id") + app_url = data.get("app_url") + control_url = _string_value(data.get("control_url")) + cleanup = None + sid = _string_value(session_id) or _string_value(result.session_id) + if sid: + # Retain a fallback before validating the server's response fields. + fallback = "" + base = urlsplit(result.runner_url) + if base.path.rstrip("/").endswith("/session"): + fallback = urlunsplit(base._replace(path=base.path.rstrip("/") + "/" + quote(sid, safe=""), fragment="")) + for candidate in (fallback, control_url): + if not candidate: + continue + try: + cleanup = LiveRunnerSession( + session_id=sid, app_url="", runner_url=result.runner_url, + control_url=candidate, runner=result.runner, + ) + except LivepeerGatewayError: + continue + try: + if not isinstance(session_id, str) or not session_id.strip(): + raise LivepeerGatewayError("runner session response missing session_id") + if not isinstance(app_url, str) or not app_url.strip(): + raise LivepeerGatewayError("runner session response missing app_url") + if not control_url: + raise LivepeerGatewayError("runner session response missing control_url") + session = LiveRunnerSession( + session_id=session_id.strip(), + app_url=app_url.strip(), + runner_url=result.runner_url, + control_url=control_url, + runner=result.runner, + ) + cleanup = session + if result.payment_session is not None: + session._start_payments(result.payment_session) + return session + except BaseException as error: + if cleanup is not None: + await _release_invalid_reservation(cleanup, error) + raise - # No payment session means fixed price or offchain: nothing to fund. - if result.payment_session is not None: - session._start_payments(result.payment_session) - return session + +async def _release_invalid_reservation(session: LiveRunnerSession, original: BaseException) -> None: + async def release() -> None: + for attempt in range(3): + try: + await stop_runner_session(session, timeout=5.0) + return + except Exception as error: + status = getattr(error, "status_code", None) + if status in (404, 410): + return + if attempt == 2 or status is not None and status not in (408, 429) and not 500 <= status < 600: + raise + await asyncio.sleep(0.25 * 2**attempt) + + task = asyncio.create_task(release()) + cancellation = None + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError as error: + cancellation = error + except Exception: + break + try: + task.result() + except Exception as error: + original.add_note(f"Reservation cleanup failed for session {session.session_id}: {error}") + original.cleanup_session = session + _LOG.error("Invalid reservation cleanup failed for session %s", session.session_id, exc_info=True) + if cancellation is not None: + raise cancellation from original def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list[LiveRunnerInstance]: diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index c6fab96..331a79d 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -251,6 +251,11 @@ def _reservation( class TestReservationSelection: + @pytest.fixture(autouse=True) + def stop_invalid_reservation(self): + with mock.patch.object(selection, "stop_runner_session", new=mock.AsyncMock()): + yield + async def test_paid_reservation_starts_scoped_funding(self) -> None: payment_session = _FundingSession() cursor = _Cursor( diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py new file mode 100644 index 0000000..9607c87 --- /dev/null +++ b/tests/test_reservation_cleanup.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from unittest import mock + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer + +from livepeer_gateway import selection +from livepeer_gateway.errors import LivepeerGatewayError +from livepeer_gateway.live_runner import LiveRunnerCallResult + + +@pytest.fixture +async def reservation(): + state = SimpleNamespace(stops=0, statuses=[], started=asyncio.Event(), finish=None) + + async def stop(request: web.Request) -> web.Response: + state.stops += 1 + state.started.set() + if state.finish is not None: + await state.finish.wait() + return web.json_response({}, status=state.statuses.pop(0) if state.statuses else 200) + + app = web.Application() + app.router.add_post("/apps/a/session/sid/stop", stop) + async with TestServer(app) as server: + base = str(server.make_url("/apps/a/session")) + state.result = LiveRunnerCallResult( + {"session_id": "sid", "app_url": base + "/sid/app", "control_url": base + "/sid"}, + runner_url=base, + session_id="sid", + ) + cursor = SimpleNamespace(next=mock.AsyncMock(return_value=state.result)) + with mock.patch.object(selection, "runner_selector", new=mock.AsyncMock(return_value=cursor)): + yield state + + +@pytest.mark.parametrize("field,value", [ + ("app_url", None), ("app_url", 123), ("session_id", None), + ("control_url", None), ("control_url", "ftp://invalid/session"), +]) +async def test_malformed_response_releases_identifiable_reservation(reservation, field, value): + reservation.result.data[field] = value + with pytest.raises(LivepeerGatewayError): + await selection.reserve_session() + assert reservation.stops == 1 + + +@pytest.mark.parametrize("statuses", [[503, 200], [503, 404], [410]]) +async def test_validation_cleanup_retries_transient_errors(reservation, statuses): + reservation.result.data.pop("app_url") + reservation.statuses = list(statuses) + with pytest.raises(LivepeerGatewayError, match="missing app_url"): + await selection.reserve_session() + assert reservation.stops == len(statuses) + + +async def test_exhausted_cleanup_preserves_validation_error_and_handle(reservation): + reservation.result.data.pop("app_url") + reservation.statuses = [503, 503, 503] + with pytest.raises(LivepeerGatewayError, match="missing app_url") as raised: + await selection.reserve_session() + assert reservation.stops == 3 + assert raised.value.cleanup_session.session_id == "sid" + assert any("Reservation cleanup failed" in note for note in raised.value.__notes__) + + +async def test_cancellation_during_validation_cleanup_waits_for_release(reservation): + reservation.result.data.pop("app_url") + reservation.finish = asyncio.Event() + task = asyncio.create_task(selection.reserve_session()) + await reservation.started.wait() + task.cancel() + await asyncio.sleep(0) + task.cancel() + await asyncio.sleep(0) + assert not task.done() + reservation.finish.set() + with pytest.raises(asyncio.CancelledError): + await task + assert reservation.stops == 1 + + +async def test_success_transfers_reservation_without_stopping_it(reservation): + session = await selection.reserve_session() + assert session.session_id == "sid" and reservation.stops == 0 + await session.aclose() + assert reservation.stops == 1 From ef5e010b82b07a0bb0f77fde95fa3739b5f3302b Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 08:02:35 -0800 Subject: [PATCH 2/6] Verify the session route before releasing malformed reservations --- CHANGELOG.md | 6 +- src/livepeer_gateway/selection.py | 120 +++++++++++++++++++++-------- tests/test_live_runner_payments.py | 5 -- tests/test_reservation_cleanup.py | 89 ++++++++++++++++++++- 4 files changed, 177 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d76a01a..a6bf8e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed -- Release identifiable reservations when `reserve_session()` rejects a malformed - response. Cleanup retries transient failures and survives cancellation; an - exhausted cleanup preserves the validation error and retains its session handle. +- Release verified reservations when `reserve_session()` rejects a malformed response. + If cleanup fails, the validation error retains the session handle for retry. A missing + or conflicting identity may prevent cleanup; Node idle expiry can recover it when enabled. ### Added diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 044a4ca..a736b29 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -2,9 +2,10 @@ import asyncio import logging +import re from collections.abc import Sequence from typing import Any -from urllib.parse import quote, urlsplit, urlunsplit +from urllib.parse import SplitResult, quote, unquote, urlsplit from .discovery import ( FilterValue, @@ -20,6 +21,7 @@ LiveRunnerCallResult, LiveRunnerInstance, LiveRunnerSession, + _join_endpoint, _live_runner_price_info_from_json, call_runner, stop_runner_session, @@ -211,51 +213,101 @@ async def reserve_session( ) result = await cursor.next() data = result.data if isinstance(result.data, dict) else {} - session_id = data.get("session_id") - app_url = data.get("app_url") + session_id = _string_value(data.get("session_id")) + app_url = _string_value(data.get("app_url")) control_url = _string_value(data.get("control_url")) - cleanup = None - sid = _string_value(session_id) or _string_value(result.session_id) - if sid: - # Retain a fallback before validating the server's response fields. - fallback = "" - base = urlsplit(result.runner_url) - if base.path.rstrip("/").endswith("/session"): - fallback = urlunsplit(base._replace(path=base.path.rstrip("/") + "/" + quote(sid, safe=""), fragment="")) - for candidate in (fallback, control_url): - if not candidate: - continue - try: - cleanup = LiveRunnerSession( - session_id=sid, app_url="", runner_url=result.runner_url, - control_url=candidate, runner=result.runner, - ) - except LivepeerGatewayError: - continue + known_id = _string_value(result.session_id) + session = None try: - if not isinstance(session_id, str) or not session_id.strip(): + if not session_id: raise LivepeerGatewayError("runner session response missing session_id") - if not isinstance(app_url, str) or not app_url.strip(): + if known_id and session_id != known_id: + raise LivepeerGatewayError("runner session response session_id does not match payment manifest") + if not app_url: raise LivepeerGatewayError("runner session response missing app_url") if not control_url: raise LivepeerGatewayError("runner session response missing control_url") - session = LiveRunnerSession( - session_id=session_id.strip(), - app_url=app_url.strip(), - runner_url=result.runner_url, - control_url=control_url, - runner=result.runner, - ) - cleanup = session + try: + session = LiveRunnerSession(session_id, app_url, result.runner_url, control_url, result.runner) + except ValueError as error: + raise LivepeerGatewayError("runner session response has invalid control_url") from error if result.payment_session is not None: session._start_payments(result.payment_session) return session except BaseException as error: + cleanup = session or _invalid_reservation_handle(result, known_id or session_id, control_url, app_url) if cleanup is not None: await _release_invalid_reservation(cleanup, error) + elif known_id or session_id or control_url: + error.add_note("Reservation cleanup unresolved: no verified stop route") raise +def _invalid_reservation_handle( + result: LiveRunnerCallResult, session_id: str, control_url: str, app_url: str = "", +) -> LiveRunnerSession | None: + runner_url = result.runner_url + try: + base = urlsplit(runner_url) + except ValueError: + return None + path = base.path.rstrip("/") + canonical = re.search(r"/apps/[^/]+/session$", path) is not None + payment = result.payment_session + body_id = _string_value(result.data.get("session_id")) if isinstance(result.data, dict) else "" + # On offchain calls result.session_id just repeats the body field. + manifest = getattr(payment, "manifest_id", "") or (result.session_id if result.session_id != body_id else "") + + def verified(url: str) -> SplitResult | None: + try: + candidate = urlsplit(url) + if _origin(candidate) == _origin(base): + return candidate + except ValueError: + pass + return None + + def handle(sid: str, url: str) -> LiveRunnerSession: + return LiveRunnerSession(sid, "", runner_url, url, result.runner) + + try: + control = verified(control_url) + control_path = control.path.rstrip("/") if control is not None else "" + if not canonical and payment is not None and manifest and session_id == manifest: + payment_url = getattr(getattr(payment, "_challenge", None), "payment_url", "") + payment_route = verified(payment_url) + suffix = "/" + quote(manifest, safe="") + "/payment" + if payment_route and payment_route.path.endswith(suffix) and re.search( + r"/apps/[^/]+/session$", payment_route.path.removesuffix(suffix), + ): + path = payment_route.path.removesuffix("/payment") + stop_url = control_url if control_path == path else payment_route._replace(path=path).geturl() + return handle(manifest, stop_url) + match = re.search(r"(/apps/[^/]+/session)/([A-Za-z0-9_-]+)$", unquote(control_path)) + if match and (not canonical or control_path.rsplit("/", 1)[0] == path): + control_id = match[2] + app = verified(app_url) + if app is not None and app.path.rstrip("/") == control_path + "/app" and ( + not manifest or manifest == control_id + ): + return handle(control_id, control_url) + if session_id == control_id or (canonical and not session_id): + return handle(control_id, control_url) + if session_id and not manifest: + # The two offchain fields disagree without independent corroboration. + return None + if canonical and session_id: + return handle(session_id, _join_endpoint(runner_url, quote(session_id, safe=""))) + except (ValueError, LivepeerGatewayError): + pass # No usable stop identity in the response or request URL. + return None + + +def _origin(url: SplitResult) -> tuple[str, str | None, int]: + default_port = 443 if url.scheme == "https" else 80 + return url.scheme, url.hostname, url.port if url.port is not None else default_port + + async def _release_invalid_reservation(session: LiveRunnerSession, original: BaseException) -> None: async def release() -> None: for attempt in range(3): @@ -282,8 +334,12 @@ async def release() -> None: try: task.result() except Exception as error: - original.add_note(f"Reservation cleanup failed for session {session.session_id}: {error}") + note = f"Reservation cleanup failed for session {session.session_id}: {error}" + original.add_note(note) original.cleanup_session = session + if cancellation is not None: + cancellation.add_note(note) + cancellation.cleanup_session = session _LOG.error("Invalid reservation cleanup failed for session %s", session.session_id, exc_info=True) if cancellation is not None: raise cancellation from original diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index 331a79d..c6fab96 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -251,11 +251,6 @@ def _reservation( class TestReservationSelection: - @pytest.fixture(autouse=True) - def stop_invalid_reservation(self): - with mock.patch.object(selection, "stop_runner_session", new=mock.AsyncMock()): - yield - async def test_paid_reservation_starts_scoped_funding(self) -> None: payment_session = _FundingSession() cursor = _Cursor( diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py index 9607c87..a62d193 100644 --- a/tests/test_reservation_cleanup.py +++ b/tests/test_reservation_cleanup.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from dataclasses import replace from types import SimpleNamespace from unittest import mock @@ -19,6 +20,7 @@ async def reservation(): async def stop(request: web.Request) -> web.Response: state.stops += 1 + state.query = dict(request.query) state.started.set() if state.finish is not None: await state.finish.wait() @@ -33,7 +35,7 @@ async def stop(request: web.Request) -> web.Response: runner_url=base, session_id="sid", ) - cursor = SimpleNamespace(next=mock.AsyncMock(return_value=state.result)) + cursor = SimpleNamespace(next=mock.AsyncMock(side_effect=lambda: state.result)) with mock.patch.object(selection, "runner_selector", new=mock.AsyncMock(return_value=cursor)): yield state @@ -41,6 +43,7 @@ async def stop(request: web.Request) -> web.Response: @pytest.mark.parametrize("field,value", [ ("app_url", None), ("app_url", 123), ("session_id", None), ("control_url", None), ("control_url", "ftp://invalid/session"), + ("control_url", "http://["), ]) async def test_malformed_response_releases_identifiable_reservation(reservation, field, value): reservation.result.data[field] = value @@ -49,6 +52,82 @@ async def test_malformed_response_releases_identifiable_reservation(reservation, assert reservation.stops == 1 +@pytest.mark.parametrize("paid", [True, False]) +async def test_cleanup_recovers_canonical_reservation_identity(reservation, paid): + if paid: + reservation.result.data.update(session_id="wrong", control_url=None) + else: + reservation.result.data.pop("session_id") + reservation.result = replace(reservation.result, session_id="") + with pytest.raises(LivepeerGatewayError, match="session_id"): + await selection.reserve_session() + assert reservation.stops == 1 + + +async def test_cleanup_uses_canonical_route_when_control_url_targets_app(reservation): + reservation.result.data["control_url"] = reservation.result.data.pop("app_url") + with pytest.raises(LivepeerGatewayError, match="missing app_url"): + await selection.reserve_session() + assert reservation.stops == 1 + + +async def test_cleanup_preserves_verified_control_url_query(reservation): + reservation.result.data.pop("app_url") + reservation.result.data["control_url"] += "?lease=opaque" + with pytest.raises(LivepeerGatewayError, match="missing app_url"): + await selection.reserve_session() + assert reservation.query == {"lease": "opaque"} + + +def test_cleanup_recovers_session_across_equivalent_origins(): + result = LiveRunnerCallResult({}, runner_url="https://ORCH.test:443/apps/a/session") + control_url = "https://orch.test/apps/a/session/sid?lease=opaque" + session = selection._invalid_reservation_handle(result, "", control_url) + assert session is not None + assert session.session_id == "sid" and session.control_url == control_url + + +def test_aliased_reservation_cleanup_rejects_a_different_session_id(): + result = LiveRunnerCallResult({}, runner_url="https://orch.test/session", session_id="paid-id") + control_url = "https://orch.test/apps/a/session/paid-id" + session = selection._invalid_reservation_handle(result, result.session_id, control_url) + assert session is not None and session.control_url == control_url + assert selection._invalid_reservation_handle(result, result.session_id, control_url.replace("paid-id", "body-id")) is None + + +@pytest.mark.parametrize("reported_app", [None, "wrong", "a"]) +def test_metered_alias_recovers_control_route_from_payment_challenge(reported_app): + control_url = "https://orch.test/apps/a/session/paid-id" + payment = SimpleNamespace( + manifest_id="paid-id", _challenge=SimpleNamespace(payment_url=control_url + "/payment?lease=opaque"), + ) + result = LiveRunnerCallResult( + {"session_id": "paid-id"}, runner_url="https://orch.test/alias", session_id="paid-id", + payment_session=payment, + ) + reported_url = f"https://orch.test/apps/{reported_app}/session/paid-id?lease=returned" if reported_app else "" + session = selection._invalid_reservation_handle(result, "paid-id", reported_url) + expected = reported_url if reported_app == "a" else control_url + "?lease=opaque" + assert session is not None and session.control_url == expected + + +def test_offchain_alias_recovers_control_route_only_with_matching_app_url(): + control_url = "https://orch.test/apps/a/session/sid" + result = LiveRunnerCallResult({}, runner_url="https://orch.test/alias") + session = selection._invalid_reservation_handle(result, "", control_url, control_url + "/app") + assert session is not None and session.session_id == "sid" + assert selection._invalid_reservation_handle(result, "", control_url, control_url + "-other/app") is None + + +async def test_conflicting_offchain_ids_without_corroboration_do_not_stop_either(reservation): + data = {**reservation.result.data, "session_id": "body-id", "app_url": None} + reservation.result = replace(reservation.result, data=data, session_id="body-id") + with pytest.raises(LivepeerGatewayError, match="missing app_url") as raised: + await selection.reserve_session() + assert reservation.stops == 0 + assert any("cleanup unresolved" in note for note in raised.value.__notes__) + + @pytest.mark.parametrize("statuses", [[503, 200], [503, 404], [410]]) async def test_validation_cleanup_retries_transient_errors(reservation, statuses): reservation.result.data.pop("app_url") @@ -68,9 +147,11 @@ async def test_exhausted_cleanup_preserves_validation_error_and_handle(reservati assert any("Reservation cleanup failed" in note for note in raised.value.__notes__) -async def test_cancellation_during_validation_cleanup_waits_for_release(reservation): +@pytest.mark.parametrize("status", [200, 401]) +async def test_cancellation_during_validation_cleanup_waits_for_release(reservation, status): reservation.result.data.pop("app_url") reservation.finish = asyncio.Event() + reservation.statuses = [status] task = asyncio.create_task(selection.reserve_session()) await reservation.started.wait() task.cancel() @@ -79,9 +160,11 @@ async def test_cancellation_during_validation_cleanup_waits_for_release(reservat await asyncio.sleep(0) assert not task.done() reservation.finish.set() - with pytest.raises(asyncio.CancelledError): + with pytest.raises(asyncio.CancelledError) as raised: await task assert reservation.stops == 1 + if status == 401: + assert raised.value.cleanup_session.session_id == "sid" async def test_success_transfers_reservation_without_stopping_it(reservation): From f2b69b03f9c40a3bfdc30167c87de50333c61fef Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 09:41:37 -0800 Subject: [PATCH 3/6] Simplify malformed reservation cleanup --- CHANGELOG.md | 4 +- src/livepeer_gateway/live_runner.py | 15 +- src/livepeer_gateway/selection.py | 144 ++--------------- tests/test_reservation_cleanup.py | 234 +++++++++------------------- 4 files changed, 101 insertions(+), 296 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6bf8e6..61e84bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed -- Release verified reservations when `reserve_session()` rejects a malformed response. - If cleanup fails, the validation error retains the session handle for retry. A missing - or conflicting identity may prevent cleanup; Node idle expiry can recover it when enabled. +- Attempt to release sessions after malformed reservation responses when the route and ID are known. ### Added diff --git a/src/livepeer_gateway/live_runner.py b/src/livepeer_gateway/live_runner.py index 6e2afd0..516c68e 100644 --- a/src/livepeer_gateway/live_runner.py +++ b/src/livepeer_gateway/live_runner.py @@ -21,7 +21,7 @@ overload, ) from collections.abc import AsyncIterator, Awaitable, Callable, Mapping -from urllib.parse import quote, urlparse, urlunparse +from urllib.parse import quote, urlparse, urlsplit, urlunparse import aiohttp from aiohttp.helpers import parse_mimetype @@ -172,6 +172,7 @@ class LiveRunnerCallResult: # Non-JSON responses (an image, say) arrive unparsed in `content`; `data` stays empty. content: bytes | None = field(default=None, repr=False) content_type: str = "" + _payment_manifest_id: str = field(default="", repr=False, compare=False) @dataclass @@ -973,12 +974,14 @@ async def call_runner( if is_json: try: data = json.loads(body) - except (UnicodeDecodeError, json.JSONDecodeError) as e: + except (ValueError, RecursionError) as e: + await _release_reservation(runner_url, session_id, runner, method=method) raise LivepeerGatewayError( f"HTTP JSON error: endpoint did not return valid JSON: {e} " f"(url={runner_url}, content_type={response_content_type})" ) from e if not isinstance(data, dict): + await _release_reservation(runner_url, session_id, runner, method=method) raise LivepeerGatewayError( f"Live runner call expected JSON object, got {type(data).__name__}" ) @@ -993,6 +996,7 @@ async def call_runner( payment_session=None if payment_type == "fixed" else payment_session, content=None if is_json else body, content_type=response_content_type, + _payment_manifest_id=session_id, ) except LivepeerHTTPError as e: if e.status_code != 402: @@ -1122,6 +1126,13 @@ def _live_runner_price_info_from_json(value: object) -> LiveRunnerPriceInfo | No ) +async def _release_reservation(url: str, session_id: object, runner: LiveRunnerInstance | None, method: str = "POST") -> None: + with contextlib.suppress(Exception): + route = re.escape(urlsplit(runner.orchestrator_url if runner else "").path.rstrip("/")) + r"/apps/[\w-]+/session/?" + if method.upper() == "POST" and isinstance(session_id, str) and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII) and re.fullmatch(route, urlsplit(url).path, re.ASCII): + await _request_body(_join_endpoint(url, f"{session_id}/stop"), method="POST", allow_redirects=False) + + async def stop_runner_session( session: LiveRunnerSession | LiveRunnerSessionRequest, *, diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index a736b29..5dfca03 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -1,11 +1,8 @@ from __future__ import annotations -import asyncio import logging -import re from collections.abc import Sequence from typing import Any -from urllib.parse import SplitResult, quote, unquote, urlsplit from .discovery import ( FilterValue, @@ -21,10 +18,9 @@ LiveRunnerCallResult, LiveRunnerInstance, LiveRunnerSession, - _join_endpoint, _live_runner_price_info_from_json, + _release_reservation, call_runner, - stop_runner_session, ) from .runner_payload import RunnerPayload, _ReplayUnavailableError, _StreamState, _stream_state @@ -212,137 +208,21 @@ async def reserve_session( timeout=timeout, ) result = await cursor.next() - data = result.data if isinstance(result.data, dict) else {} - session_id = _string_value(data.get("session_id")) - app_url = _string_value(data.get("app_url")) - control_url = _string_value(data.get("control_url")) - known_id = _string_value(result.session_id) - session = None + fields = {key: _string_value(result.data.get(key)) for key in ("session_id", "app_url", "control_url")} try: - if not session_id: - raise LivepeerGatewayError("runner session response missing session_id") - if known_id and session_id != known_id: + if missing := next((key for key, value in fields.items() if not value), None): + raise LivepeerGatewayError(f"runner session response missing {missing}") + if result._payment_manifest_id and fields["session_id"] != result._payment_manifest_id: raise LivepeerGatewayError("runner session response session_id does not match payment manifest") - if not app_url: - raise LivepeerGatewayError("runner session response missing app_url") - if not control_url: - raise LivepeerGatewayError("runner session response missing control_url") - try: - session = LiveRunnerSession(session_id, app_url, result.runner_url, control_url, result.runner) - except ValueError as error: - raise LivepeerGatewayError("runner session response has invalid control_url") from error - if result.payment_session is not None: - session._start_payments(result.payment_session) - return session - except BaseException as error: - cleanup = session or _invalid_reservation_handle(result, known_id or session_id, control_url, app_url) - if cleanup is not None: - await _release_invalid_reservation(cleanup, error) - elif known_id or session_id or control_url: - error.add_note("Reservation cleanup unresolved: no verified stop route") + session = LiveRunnerSession(**fields, runner_url=result.runner_url, runner=result.runner) + except (LivepeerGatewayError, ValueError): + await _release_reservation(result.runner_url, result._payment_manifest_id or result.data.get("session_id"), result.runner) raise - -def _invalid_reservation_handle( - result: LiveRunnerCallResult, session_id: str, control_url: str, app_url: str = "", -) -> LiveRunnerSession | None: - runner_url = result.runner_url - try: - base = urlsplit(runner_url) - except ValueError: - return None - path = base.path.rstrip("/") - canonical = re.search(r"/apps/[^/]+/session$", path) is not None - payment = result.payment_session - body_id = _string_value(result.data.get("session_id")) if isinstance(result.data, dict) else "" - # On offchain calls result.session_id just repeats the body field. - manifest = getattr(payment, "manifest_id", "") or (result.session_id if result.session_id != body_id else "") - - def verified(url: str) -> SplitResult | None: - try: - candidate = urlsplit(url) - if _origin(candidate) == _origin(base): - return candidate - except ValueError: - pass - return None - - def handle(sid: str, url: str) -> LiveRunnerSession: - return LiveRunnerSession(sid, "", runner_url, url, result.runner) - - try: - control = verified(control_url) - control_path = control.path.rstrip("/") if control is not None else "" - if not canonical and payment is not None and manifest and session_id == manifest: - payment_url = getattr(getattr(payment, "_challenge", None), "payment_url", "") - payment_route = verified(payment_url) - suffix = "/" + quote(manifest, safe="") + "/payment" - if payment_route and payment_route.path.endswith(suffix) and re.search( - r"/apps/[^/]+/session$", payment_route.path.removesuffix(suffix), - ): - path = payment_route.path.removesuffix("/payment") - stop_url = control_url if control_path == path else payment_route._replace(path=path).geturl() - return handle(manifest, stop_url) - match = re.search(r"(/apps/[^/]+/session)/([A-Za-z0-9_-]+)$", unquote(control_path)) - if match and (not canonical or control_path.rsplit("/", 1)[0] == path): - control_id = match[2] - app = verified(app_url) - if app is not None and app.path.rstrip("/") == control_path + "/app" and ( - not manifest or manifest == control_id - ): - return handle(control_id, control_url) - if session_id == control_id or (canonical and not session_id): - return handle(control_id, control_url) - if session_id and not manifest: - # The two offchain fields disagree without independent corroboration. - return None - if canonical and session_id: - return handle(session_id, _join_endpoint(runner_url, quote(session_id, safe=""))) - except (ValueError, LivepeerGatewayError): - pass # No usable stop identity in the response or request URL. - return None - - -def _origin(url: SplitResult) -> tuple[str, str | None, int]: - default_port = 443 if url.scheme == "https" else 80 - return url.scheme, url.hostname, url.port if url.port is not None else default_port - - -async def _release_invalid_reservation(session: LiveRunnerSession, original: BaseException) -> None: - async def release() -> None: - for attempt in range(3): - try: - await stop_runner_session(session, timeout=5.0) - return - except Exception as error: - status = getattr(error, "status_code", None) - if status in (404, 410): - return - if attempt == 2 or status is not None and status not in (408, 429) and not 500 <= status < 600: - raise - await asyncio.sleep(0.25 * 2**attempt) - - task = asyncio.create_task(release()) - cancellation = None - while not task.done(): - try: - await asyncio.shield(task) - except asyncio.CancelledError as error: - cancellation = error - except Exception: - break - try: - task.result() - except Exception as error: - note = f"Reservation cleanup failed for session {session.session_id}: {error}" - original.add_note(note) - original.cleanup_session = session - if cancellation is not None: - cancellation.add_note(note) - cancellation.cleanup_session = session - _LOG.error("Invalid reservation cleanup failed for session %s", session.session_id, exc_info=True) - if cancellation is not None: - raise cancellation from original + # No payment session means fixed price or offchain: nothing to fund. + if result.payment_session is not None: + session._start_payments(result.payment_session) + return session def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list[LiveRunnerInstance]: diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py index a62d193..79842eb 100644 --- a/tests/test_reservation_cleanup.py +++ b/tests/test_reservation_cleanup.py @@ -1,7 +1,5 @@ from __future__ import annotations -import asyncio -from dataclasses import replace from types import SimpleNamespace from unittest import mock @@ -9,166 +7,84 @@ from aiohttp import web from aiohttp.test_utils import TestServer -from livepeer_gateway import selection -from livepeer_gateway.errors import LivepeerGatewayError -from livepeer_gateway.live_runner import LiveRunnerCallResult - - -@pytest.fixture -async def reservation(): - state = SimpleNamespace(stops=0, statuses=[], started=asyncio.Event(), finish=None) +from livepeer_gateway import live_runner, selection +from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError + + +@pytest.mark.parametrize( + "paid,body,error,expected_stops", + [ + (True, b"{", "did not return valid JSON", ["paid-id"]), + (True, [], "expected JSON object", ["paid-id"]), + (True, b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["paid-id"]), + (True, {}, "missing session_id", ["paid-id"]), + ( + True, + {"session_id": "wrong-id", "app_url": "https://orch.test/app", "control_url": "https://orch.test/control"}, + "does not match payment manifest", + ["paid-id"], + ), + (False, {"session_id": "free-id"}, "missing app_url", ["free-id"]), + (False, {}, "missing session_id", []), + (False, {"session_id": "../other"}, "missing app_url", []), + (False, {"session_id": " free-id "}, "missing app_url", []), + (True, {"session_id": " paid-id "}, "missing app_url", ["paid-id"]), + (False, b"{", "did not return valid JSON", []), + ], +) +async def test_malformed_reservation_cleanup(paid, body, error, expected_stops): + stops = [] + + async def reserve(request: web.Request) -> web.Response: + if paid and not request.headers.get("Livepeer-Payment"): + return web.json_response( + {"manifest_id": "paid-id", "payment_params": "test", "payment_url": f"{base}/paid-id/payment"}, + status=402, + ) + if isinstance(body, bytes): + return web.Response(body=body, content_type="application/json") + return web.json_response(body) async def stop(request: web.Request) -> web.Response: - state.stops += 1 - state.query = dict(request.query) - state.started.set() - if state.finish is not None: - await state.finish.wait() - return web.json_response({}, status=state.statuses.pop(0) if state.statuses else 200) + stops.append(request.match_info["session_id"]) + return web.Response(status=503) app = web.Application() - app.router.add_post("/apps/a/session/sid/stop", stop) + app.router.add_post("/apps/a/session", reserve) + app.router.add_post("/apps/a/session/{session_id}/stop", stop) async with TestServer(app) as server: base = str(server.make_url("/apps/a/session")) - state.result = LiveRunnerCallResult( - {"session_id": "sid", "app_url": base + "/sid/app", "control_url": base + "/sid"}, - runner_url=base, - session_id="sid", - ) - cursor = SimpleNamespace(next=mock.AsyncMock(side_effect=lambda: state.result)) - with mock.patch.object(selection, "runner_selector", new=mock.AsyncMock(return_value=cursor)): - yield state - - -@pytest.mark.parametrize("field,value", [ - ("app_url", None), ("app_url", 123), ("session_id", None), - ("control_url", None), ("control_url", "ftp://invalid/session"), - ("control_url", "http://["), -]) -async def test_malformed_response_releases_identifiable_reservation(reservation, field, value): - reservation.result.data[field] = value - with pytest.raises(LivepeerGatewayError): - await selection.reserve_session() - assert reservation.stops == 1 - - -@pytest.mark.parametrize("paid", [True, False]) -async def test_cleanup_recovers_canonical_reservation_identity(reservation, paid): - if paid: - reservation.result.data.update(session_id="wrong", control_url=None) - else: - reservation.result.data.pop("session_id") - reservation.result = replace(reservation.result, session_id="") - with pytest.raises(LivepeerGatewayError, match="session_id"): - await selection.reserve_session() - assert reservation.stops == 1 - - -async def test_cleanup_uses_canonical_route_when_control_url_targets_app(reservation): - reservation.result.data["control_url"] = reservation.result.data.pop("app_url") - with pytest.raises(LivepeerGatewayError, match="missing app_url"): - await selection.reserve_session() - assert reservation.stops == 1 - - -async def test_cleanup_preserves_verified_control_url_query(reservation): - reservation.result.data.pop("app_url") - reservation.result.data["control_url"] += "?lease=opaque" - with pytest.raises(LivepeerGatewayError, match="missing app_url"): - await selection.reserve_session() - assert reservation.query == {"lease": "opaque"} - - -def test_cleanup_recovers_session_across_equivalent_origins(): - result = LiveRunnerCallResult({}, runner_url="https://ORCH.test:443/apps/a/session") - control_url = "https://orch.test/apps/a/session/sid?lease=opaque" - session = selection._invalid_reservation_handle(result, "", control_url) - assert session is not None - assert session.session_id == "sid" and session.control_url == control_url - - -def test_aliased_reservation_cleanup_rejects_a_different_session_id(): - result = LiveRunnerCallResult({}, runner_url="https://orch.test/session", session_id="paid-id") - control_url = "https://orch.test/apps/a/session/paid-id" - session = selection._invalid_reservation_handle(result, result.session_id, control_url) - assert session is not None and session.control_url == control_url - assert selection._invalid_reservation_handle(result, result.session_id, control_url.replace("paid-id", "body-id")) is None - - -@pytest.mark.parametrize("reported_app", [None, "wrong", "a"]) -def test_metered_alias_recovers_control_route_from_payment_challenge(reported_app): - control_url = "https://orch.test/apps/a/session/paid-id" - payment = SimpleNamespace( - manifest_id="paid-id", _challenge=SimpleNamespace(payment_url=control_url + "/payment?lease=opaque"), - ) - result = LiveRunnerCallResult( - {"session_id": "paid-id"}, runner_url="https://orch.test/alias", session_id="paid-id", - payment_session=payment, - ) - reported_url = f"https://orch.test/apps/{reported_app}/session/paid-id?lease=returned" if reported_app else "" - session = selection._invalid_reservation_handle(result, "paid-id", reported_url) - expected = reported_url if reported_app == "a" else control_url + "?lease=opaque" - assert session is not None and session.control_url == expected - - -def test_offchain_alias_recovers_control_route_only_with_matching_app_url(): - control_url = "https://orch.test/apps/a/session/sid" - result = LiveRunnerCallResult({}, runner_url="https://orch.test/alias") - session = selection._invalid_reservation_handle(result, "", control_url, control_url + "/app") - assert session is not None and session.session_id == "sid" - assert selection._invalid_reservation_handle(result, "", control_url, control_url + "-other/app") is None - - -async def test_conflicting_offchain_ids_without_corroboration_do_not_stop_either(reservation): - data = {**reservation.result.data, "session_id": "body-id", "app_url": None} - reservation.result = replace(reservation.result, data=data, session_id="body-id") - with pytest.raises(LivepeerGatewayError, match="missing app_url") as raised: - await selection.reserve_session() - assert reservation.stops == 0 - assert any("cleanup unresolved" in note for note in raised.value.__notes__) - - -@pytest.mark.parametrize("statuses", [[503, 200], [503, 404], [410]]) -async def test_validation_cleanup_retries_transient_errors(reservation, statuses): - reservation.result.data.pop("app_url") - reservation.statuses = list(statuses) - with pytest.raises(LivepeerGatewayError, match="missing app_url"): - await selection.reserve_session() - assert reservation.stops == len(statuses) - - -async def test_exhausted_cleanup_preserves_validation_error_and_handle(reservation): - reservation.result.data.pop("app_url") - reservation.statuses = [503, 503, 503] - with pytest.raises(LivepeerGatewayError, match="missing app_url") as raised: - await selection.reserve_session() - assert reservation.stops == 3 - assert raised.value.cleanup_session.session_id == "sid" - assert any("Reservation cleanup failed" in note for note in raised.value.__notes__) - - -@pytest.mark.parametrize("status", [200, 401]) -async def test_cancellation_during_validation_cleanup_waits_for_release(reservation, status): - reservation.result.data.pop("app_url") - reservation.finish = asyncio.Event() - reservation.statuses = [status] - task = asyncio.create_task(selection.reserve_session()) - await reservation.started.wait() - task.cancel() - await asyncio.sleep(0) - task.cancel() - await asyncio.sleep(0) - assert not task.done() - reservation.finish.set() - with pytest.raises(asyncio.CancelledError) as raised: - await task - assert reservation.stops == 1 - if status == 401: - assert raised.value.cleanup_session.session_id == "sid" - - -async def test_success_transfers_reservation_without_stopping_it(reservation): - session = await selection.reserve_session() - assert session.session_id == "sid" and reservation.stops == 0 - await session.aclose() - assert reservation.stops == 1 + entries = [{"runners": [{"url": base, "app": "a", "price_info": {"price": "1", "unit": "fixed"}}]}] + with ( + mock.patch.object(selection, "discover_runners", return_value=entries), + mock.patch.object(live_runner, "get_signer_info", return_value=SimpleNamespace(address="payer")), + mock.patch.object( + live_runner.LivePaymentSession, "get_payment", + return_value=SimpleNamespace(payment="payment", seg_creds="segment"), + ), + pytest.raises(LivepeerGatewayError) as raised, + ): + await selection.reserve_session(signer_url="https://signer.test" if paid else None) + + failure = raised.value + reason = failure.rejections[0].reason if isinstance(failure, NoRunnerAvailableError) else str(failure) + assert error in reason + assert stops == expected_stops + + +@pytest.mark.parametrize( + "prefix,path,should_stop", + [ + ("", "/apps/a/app/apps/b/session", False), + ("/mount", "/apps/a/session", False), + ("", "/apps/a/session;other", False), + ("/mount", "/mount/apps/a/session", True), + ("/mount;v=2", "/mount/apps/a/session", False), + ("/mount;v=2", "/mount;v=2/apps/a/session", True), + ], +) +async def test_cleanup_only_targets_discovered_reservation_route(prefix, path, should_stop): + runner = SimpleNamespace(orchestrator_url="https://orch.test" + prefix) + with mock.patch.object(live_runner, "_request_body") as request: + await live_runner._release_reservation("https://orch.test" + path, "paid-id", runner) + assert request.await_count == int(should_stop) From a29d54e87acd7c0dbc0804db5b5ca549397e0063 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 10:38:16 -0800 Subject: [PATCH 4/6] Use the onchain session ID for reservation cleanup --- CHANGELOG.md | 2 +- src/livepeer_gateway/live_runner.py | 17 ++++++----- src/livepeer_gateway/selection.py | 14 ++++----- tests/test_live_runner_payments.py | 4 +-- tests/test_reservation_cleanup.py | 47 +++++++++++++++-------------- tests/test_selection.py | 5 ++- 6 files changed, 46 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61e84bd..3a5e927 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed -- Attempt to release sessions after malformed reservation responses when the route and ID are known. +- Attempt to release onchain sessions when reservation responses are malformed or have mismatched IDs, if the Node route is known. ### Added diff --git a/src/livepeer_gateway/live_runner.py b/src/livepeer_gateway/live_runner.py index 516c68e..7724ceb 100644 --- a/src/livepeer_gateway/live_runner.py +++ b/src/livepeer_gateway/live_runner.py @@ -172,7 +172,6 @@ class LiveRunnerCallResult: # Non-JSON responses (an image, say) arrive unparsed in `content`; `data` stays empty. content: bytes | None = field(default=None, repr=False) content_type: str = "" - _payment_manifest_id: str = field(default="", repr=False, compare=False) @dataclass @@ -786,6 +785,7 @@ async def call_runner( max_payment_challenge_retries: int = ..., on_payment_session: LivePaymentSessionCallback | None = ..., stream: Literal[False] = False, + _reservation: bool = False, ) -> LiveRunnerCallResult: pass @@ -823,6 +823,7 @@ async def call_runner( max_payment_challenge_retries: int = 3, on_payment_session: LivePaymentSessionCallback | None = None, stream: bool = False, + _reservation: bool = False, ) -> LiveRunnerCallResult | LiveRunnerCallStream: """Call a runner once and return its result (or a live stream if ``stream=True``). @@ -989,14 +990,10 @@ async def call_runner( data, runner_url=runner_url, runner=runner, - session_id=( - session_id - or (data["session_id"].strip() if isinstance(data.get("session_id"), str) else "") - ), + session_id=session_id or ("" if _reservation else _string_value(data.get("session_id"))), payment_session=None if payment_type == "fixed" else payment_session, content=None if is_json else body, content_type=response_content_type, - _payment_manifest_id=session_id, ) except LivepeerHTTPError as e: if e.status_code != 402: @@ -1126,10 +1123,10 @@ def _live_runner_price_info_from_json(value: object) -> LiveRunnerPriceInfo | No ) -async def _release_reservation(url: str, session_id: object, runner: LiveRunnerInstance | None, method: str = "POST") -> None: +async def _release_reservation(url: str, session_id: str, runner: LiveRunnerInstance | None, method: str = "POST") -> None: with contextlib.suppress(Exception): route = re.escape(urlsplit(runner.orchestrator_url if runner else "").path.rstrip("/")) + r"/apps/[\w-]+/session/?" - if method.upper() == "POST" and isinstance(session_id, str) and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII) and re.fullmatch(route, urlsplit(url).path, re.ASCII): + if method.upper() == "POST" and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII) and re.fullmatch(route, urlsplit(url).path, re.ASCII): await _request_body(_join_endpoint(url, f"{session_id}/stop"), method="POST", allow_redirects=False) @@ -1483,3 +1480,7 @@ def _decode_maybe_bytes(value: object) -> str: if isinstance(value, bytes): return value.decode("utf-8", errors="replace") return str(value or "") + + +def _string_value(value: object) -> str: + return value.strip() if isinstance(value, str) else "" diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 5dfca03..1e568de 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -20,6 +20,7 @@ LiveRunnerSession, _live_runner_price_info_from_json, _release_reservation, + _string_value, call_runner, ) from .runner_payload import RunnerPayload, _ReplayUnavailableError, _StreamState, _stream_state @@ -64,7 +65,7 @@ def __init__( def candidates(self) -> tuple[LiveRunnerInstance, ...]: return tuple(self._candidates) - async def next(self) -> LiveRunnerCallResult: + async def next(self, *, _reservation: bool = False) -> LiveRunnerCallResult: if self._closed: raise LivepeerGatewayError("Runner selection cursor is closed") if self._next_running: @@ -84,6 +85,7 @@ async def next(self) -> LiveRunnerCallResult: "payload": self._payload_state if self._payload_state is not None else self._body, "method": self._method, "timeout": self._timeout, + **({"_reservation": True} if _reservation else {}), } if self._content_type is not None: kwargs["content_type"] = self._content_type @@ -207,16 +209,16 @@ async def reserve_session( gpu=gpu, timeout=timeout, ) - result = await cursor.next() + result = await cursor.next(_reservation=True) fields = {key: _string_value(result.data.get(key)) for key in ("session_id", "app_url", "control_url")} try: if missing := next((key for key, value in fields.items() if not value), None): raise LivepeerGatewayError(f"runner session response missing {missing}") - if result._payment_manifest_id and fields["session_id"] != result._payment_manifest_id: + if result.session_id and not (result.session_id == fields["session_id"] == result.data["session_id"]): raise LivepeerGatewayError("runner session response session_id does not match payment manifest") session = LiveRunnerSession(**fields, runner_url=result.runner_url, runner=result.runner) except (LivepeerGatewayError, ValueError): - await _release_reservation(result.runner_url, result._payment_manifest_id or result.data.get("session_id"), result.runner) + await _release_reservation(result.runner_url, result.session_id, result.runner) raise # No payment session means fixed price or offchain: nothing to fund. @@ -252,7 +254,3 @@ def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list ) ) return candidates - - -def _string_value(value: object) -> str: - return value.strip() if isinstance(value, str) else "" diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index c6fab96..8744ee6 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -225,7 +225,7 @@ def __init__(self, *results: LiveRunnerCallResult) -> None: self.results = list(results) self.rejections = [] - async def next(self) -> LiveRunnerCallResult: + async def next(self, *, _reservation: bool = False) -> LiveRunnerCallResult: if self.results: return self.results.pop(0) raise AssertionError("unexpected extra runner selection") @@ -251,7 +251,7 @@ def _reservation( class TestReservationSelection: - async def test_paid_reservation_starts_scoped_funding(self) -> None: + async def test_onchain_reservation_starts_scoped_funding(self) -> None: payment_session = _FundingSession() cursor = _Cursor( _reservation( diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py index 79842eb..4f28a0e 100644 --- a/tests/test_reservation_cleanup.py +++ b/tests/test_reservation_cleanup.py @@ -10,35 +10,31 @@ from livepeer_gateway import live_runner, selection from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError +_SESSION_URLS = {"app_url": "https://orch.test/app", "control_url": "https://orch.test/control"} +_ID_MISMATCH = "does not match payment manifest" + @pytest.mark.parametrize( - "paid,body,error,expected_stops", + "manifest_id,body,error,expected_stops", [ - (True, b"{", "did not return valid JSON", ["paid-id"]), - (True, [], "expected JSON object", ["paid-id"]), - (True, b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["paid-id"]), - (True, {}, "missing session_id", ["paid-id"]), - ( - True, - {"session_id": "wrong-id", "app_url": "https://orch.test/app", "control_url": "https://orch.test/control"}, - "does not match payment manifest", - ["paid-id"], - ), - (False, {"session_id": "free-id"}, "missing app_url", ["free-id"]), - (False, {}, "missing session_id", []), - (False, {"session_id": "../other"}, "missing app_url", []), - (False, {"session_id": " free-id "}, "missing app_url", []), - (True, {"session_id": " paid-id "}, "missing app_url", ["paid-id"]), - (False, b"{", "did not return valid JSON", []), + ("onchain-id", b"{", "did not return valid JSON", ["onchain-id"]), + ("onchain-id", [], "expected JSON object", ["onchain-id"]), + ("onchain-id", b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["onchain-id"]), + ("onchain-id", {}, "missing session_id", ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": "wrong-id"}, _ID_MISMATCH, ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, ["onchain-id"]), + (" onchain-id ", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, []), + ("", {"session_id": "offchain-id"}, "missing app_url", []), + ("", b"{", "did not return valid JSON", []), ], ) -async def test_malformed_reservation_cleanup(paid, body, error, expected_stops): +async def test_malformed_reservation_cleanup(manifest_id, body, error, expected_stops): stops = [] async def reserve(request: web.Request) -> web.Response: - if paid and not request.headers.get("Livepeer-Payment"): + if manifest_id and not request.headers.get("Livepeer-Payment"): return web.json_response( - {"manifest_id": "paid-id", "payment_params": "test", "payment_url": f"{base}/paid-id/payment"}, + {"manifest_id": manifest_id, "payment_params": "test", "payment_url": f"{base}/onchain-id/payment"}, status=402, ) if isinstance(body, bytes): @@ -64,10 +60,15 @@ async def stop(request: web.Request) -> web.Response: ), pytest.raises(LivepeerGatewayError) as raised, ): - await selection.reserve_session(signer_url="https://signer.test" if paid else None) + await selection.reserve_session(signer_url="https://signer.test" if manifest_id else None) failure = raised.value - reason = failure.rejections[0].reason if isinstance(failure, NoRunnerAvailableError) else str(failure) + if isinstance(body, (bytes, list)): + assert isinstance(failure, NoRunnerAvailableError) + reason = failure.rejections[0].reason + else: + assert type(failure) is LivepeerGatewayError + reason = str(failure) assert error in reason assert stops == expected_stops @@ -86,5 +87,5 @@ async def stop(request: web.Request) -> web.Response: async def test_cleanup_only_targets_discovered_reservation_route(prefix, path, should_stop): runner = SimpleNamespace(orchestrator_url="https://orch.test" + prefix) with mock.patch.object(live_runner, "_request_body") as request: - await live_runner._release_reservation("https://orch.test" + path, "paid-id", runner) + await live_runner._release_reservation("https://orch.test" + path, "onchain-id", runner) assert request.await_count == int(should_stop) diff --git a/tests/test_selection.py b/tests/test_selection.py index 863bfd3..6dc2ec3 100644 --- a/tests/test_selection.py +++ b/tests/test_selection.py @@ -338,8 +338,10 @@ async def _call_runner( payload: dict[str, object], method: str, timeout: float, + _reservation: bool, ) -> LiveRunnerCallResult: del payload, method, timeout + assert _reservation return LiveRunnerCallResult( { "session_id": "session-1", @@ -348,7 +350,6 @@ async def _call_runner( }, runner_url=runner.url, runner=runner, - session_id="session-1", ) with ( @@ -378,8 +379,10 @@ async def _call_runner( payload: dict[str, object], method: str, timeout: float, + _reservation: bool, ) -> LiveRunnerCallResult: del runner, payload, method, timeout + assert _reservation return LiveRunnerCallResult( {"ok": True}, runner_url="https://orch-a/apps/a/app" ) From add77b7cd4313b8ae8777de76f191834f34c8313 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 10:47:30 -0800 Subject: [PATCH 5/6] Try the next runner after invalid reservation responses --- CHANGELOG.md | 1 + src/livepeer_gateway/selection.py | 33 +++++++++++++++--------------- tests/test_live_runner_payments.py | 18 ++++------------ tests/test_reservation_cleanup.py | 30 ++++++++++++++++----------- 4 files changed, 40 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a5e927..a50e943 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed - Attempt to release onchain sessions when reservation responses are malformed or have mismatched IDs, if the Node route is known. + Continue to the next runner after a malformed reservation response. ### Added diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 1e568de..96a6d8b 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -209,22 +209,23 @@ async def reserve_session( gpu=gpu, timeout=timeout, ) - result = await cursor.next(_reservation=True) - fields = {key: _string_value(result.data.get(key)) for key in ("session_id", "app_url", "control_url")} - try: - if missing := next((key for key, value in fields.items() if not value), None): - raise LivepeerGatewayError(f"runner session response missing {missing}") - if result.session_id and not (result.session_id == fields["session_id"] == result.data["session_id"]): - raise LivepeerGatewayError("runner session response session_id does not match payment manifest") - session = LiveRunnerSession(**fields, runner_url=result.runner_url, runner=result.runner) - except (LivepeerGatewayError, ValueError): - await _release_reservation(result.runner_url, result.session_id, result.runner) - raise - - # No payment session means fixed price or offchain: nothing to fund. - if result.payment_session is not None: - session._start_payments(result.payment_session) - return session + while True: + result = await cursor.next(_reservation=True) + fields = {key: _string_value(result.data.get(key)) for key in ("session_id", "app_url", "control_url")} + try: + if missing := next((key for key, value in fields.items() if not value), None): + raise LivepeerGatewayError(f"runner session response missing {missing}") + if result.session_id and not (result.session_id == fields["session_id"] == result.data["session_id"]): + raise LivepeerGatewayError("runner session response session_id does not match payment manifest") + session = LiveRunnerSession(**fields, runner_url=result.runner_url, runner=result.runner) + except (LivepeerGatewayError, ValueError) as error: + await _release_reservation(result.runner_url, result.session_id, result.runner) + cursor.rejections.append(RunnerRejection(url=result.runner_url, reason=str(error))) + else: + # No payment session means fixed price or offchain: nothing to fund. + if result.payment_session is not None: + session._start_payments(result.payment_session) + return session def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list[LiveRunnerInstance]: diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index 8744ee6..b0db0b0 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -273,7 +273,7 @@ async def test_onchain_reservation_starts_scoped_funding(self) -> None: "bad_control_url", [None, "ftp://orch.example.com/session/bad"], ) - async def test_invalid_control_url_fails_immediately( + async def test_invalid_control_url_tries_next_runner( self, bad_control_url: str | None ) -> None: cursor = _Cursor( @@ -286,17 +286,7 @@ async def test_invalid_control_url_fails_immediately( "runner_selector", new=mock.AsyncMock(return_value=cursor), ): - with pytest.raises(LivepeerGatewayError): - await selection.reserve_session() - - assert len(cursor.results) == 1 + session = await selection.reserve_session() - async def test_missing_control_url_is_contract_error(self) -> None: - cursor = _Cursor(_reservation("bad", control_url=None)) - with mock.patch.object( - selection, - "runner_selector", - new=mock.AsyncMock(return_value=cursor), - ): - with pytest.raises(LivepeerGatewayError, match="missing control_url"): - await selection.reserve_session() + assert session.session_id == "session-good" + assert len(cursor.rejections) == 1 diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py index 4f28a0e..74f3f70 100644 --- a/tests/test_reservation_cleanup.py +++ b/tests/test_reservation_cleanup.py @@ -8,7 +8,7 @@ from aiohttp.test_utils import TestServer from livepeer_gateway import live_runner, selection -from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError +from livepeer_gateway.errors import NoRunnerAvailableError _SESSION_URLS = {"app_url": "https://orch.test/app", "control_url": "https://orch.test/control"} _ID_MISMATCH = "does not match payment manifest" @@ -21,6 +21,7 @@ ("onchain-id", [], "expected JSON object", ["onchain-id"]), ("onchain-id", b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["onchain-id"]), ("onchain-id", {}, "missing session_id", ["onchain-id"]), + ("onchain-id", {}, None, ["onchain-id"]), ("onchain-id", {**_SESSION_URLS, "session_id": "wrong-id"}, _ID_MISMATCH, ["onchain-id"]), ("onchain-id", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, ["onchain-id"]), (" onchain-id ", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, []), @@ -45,12 +46,20 @@ async def stop(request: web.Request) -> web.Response: stops.append(request.match_info["session_id"]) return web.Response(status=503) + async def reserve_next(request: web.Request) -> web.Response: + assert stops == expected_stops + return web.json_response({**_SESSION_URLS, "session_id": "next-id"}) + app = web.Application() app.router.add_post("/apps/a/session", reserve) app.router.add_post("/apps/a/session/{session_id}/stop", stop) + app.router.add_post("/apps/next/session", reserve_next) async with TestServer(app) as server: base = str(server.make_url("/apps/a/session")) entries = [{"runners": [{"url": base, "app": "a", "price_info": {"price": "1", "unit": "fixed"}}]}] + if error is None: + entries[0]["runners"].append({"url": str(server.make_url("/apps/next/session")), "app": "a"}) + signer_url = "https://signer.test" if manifest_id else None with ( mock.patch.object(selection, "discover_runners", return_value=entries), mock.patch.object(live_runner, "get_signer_info", return_value=SimpleNamespace(address="payer")), @@ -58,18 +67,15 @@ async def stop(request: web.Request) -> web.Response: live_runner.LivePaymentSession, "get_payment", return_value=SimpleNamespace(payment="payment", seg_creds="segment"), ), - pytest.raises(LivepeerGatewayError) as raised, ): - await selection.reserve_session(signer_url="https://signer.test" if manifest_id else None) - - failure = raised.value - if isinstance(body, (bytes, list)): - assert isinstance(failure, NoRunnerAvailableError) - reason = failure.rejections[0].reason - else: - assert type(failure) is LivepeerGatewayError - reason = str(failure) - assert error in reason + if error is None: + session = await selection.reserve_session(signer_url=signer_url) + assert session.session_id == "next-id" + else: + with pytest.raises(NoRunnerAvailableError) as raised: + await selection.reserve_session(signer_url=signer_url) + assert len(raised.value.rejections) == 1 + assert error in raised.value.rejections[0].reason assert stops == expected_stops From 8efd801510f87339c8d61d75f7a1bf3a2de4eca3 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 20 Nov 2026 11:32:10 -0800 Subject: [PATCH 6/6] Validate session replies in call_runner --- CHANGELOG.md | 3 +- src/livepeer_gateway/discovery.py | 5 +- src/livepeer_gateway/http.py | 8 +-- src/livepeer_gateway/live_runner.py | 72 +++++++++++++--------- src/livepeer_gateway/selection.py | 34 ++++------- tests/test_live_runner.py | 34 +++++++---- tests/test_live_runner_payments.py | 79 ++++-------------------- tests/test_reservation_cleanup.py | 44 +++++++++++--- tests/test_selection.py | 94 +++++++++-------------------- 9 files changed, 162 insertions(+), 211 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a50e943..e766c2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed -- Attempt to release onchain sessions when reservation responses are malformed or have mismatched IDs, if the Node route is known. - Continue to the next runner after a malformed reservation response. +- Reject malformed or mismatched Node session replies, attempt to stop rejected onchain sessions when the challenge ID is known, and try the next runner. ### Added diff --git a/src/livepeer_gateway/discovery.py b/src/livepeer_gateway/discovery.py index 06da4b5..19b4ab0 100644 --- a/src/livepeer_gateway/discovery.py +++ b/src/livepeer_gateway/discovery.py @@ -3,7 +3,7 @@ import asyncio import logging from typing import Any -from collections.abc import Sequence +from collections.abc import Callable, Sequence from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse from .errors import LivepeerGatewayError @@ -189,6 +189,7 @@ async def discover_orchestrator_runners( app: FilterValue | None = None, gpu: FilterValue | None = None, batch_size: int = _RUNNER_DISCOVERY_BATCH_SIZE, + _has_runners: Callable[[list[dict[str, Any]]], bool] = bool, ) -> list[dict[str, Any]]: first_error: Exception | None = None urls = orchestrator_discovery_urls(orchestrators) @@ -204,7 +205,7 @@ async def discover_orchestrator_runners( first_error = result _LOG.debug("discover_orchestrator_runners failed: %s (%s)", discovery_url, result) continue - if result: + if _has_runners(result): return result if first_error is not None: diff --git a/src/livepeer_gateway/http.py b/src/livepeer_gateway/http.py index 9c15c74..31a3b12 100644 --- a/src/livepeer_gateway/http.py +++ b/src/livepeer_gateway/http.py @@ -323,14 +323,10 @@ async def _post_empty( *, headers: dict[str, str] | None = None, timeout: float = 5.0, + allow_redirects: bool = True, ) -> None: """POST an empty body to ``url`` and discard the response.""" - await _request_body( - url, - method="POST", - headers=headers, - timeout=timeout, - ) + await _request_body(url, method="POST", headers=headers, timeout=timeout, allow_redirects=allow_redirects) def _parse_http_url(url: str, *, context: str = "URL") -> ParseResult: diff --git a/src/livepeer_gateway/live_runner.py b/src/livepeer_gateway/live_runner.py index 7724ceb..3d88ef3 100644 --- a/src/livepeer_gateway/live_runner.py +++ b/src/livepeer_gateway/live_runner.py @@ -28,7 +28,7 @@ from .channel_reader import ChannelReader from .errors import LivepeerGatewayError, LivepeerHTTPError, SignerRefreshRequired -from .http import _close_response, _post_empty, _request_body, open_stream, post_json, request_json +from .http import _close_response, _parse_http_url, _post_empty, _request_body, open_stream, post_json, request_json from .remote_signer import ( LivePaymentChallenge, LivePaymentSession, @@ -785,7 +785,6 @@ async def call_runner( max_payment_challenge_retries: int = ..., on_payment_session: LivePaymentSessionCallback | None = ..., stream: Literal[False] = False, - _reservation: bool = False, ) -> LiveRunnerCallResult: pass @@ -823,7 +822,6 @@ async def call_runner( max_payment_challenge_retries: int = 3, on_payment_session: LivePaymentSessionCallback | None = None, stream: bool = False, - _reservation: bool = False, ) -> LiveRunnerCallResult | LiveRunnerCallStream: """Call a runner once and return its result (or a live stream if ``stream=True``). @@ -852,6 +850,7 @@ async def call_runner( state = _stream_state(payload) owned = state is not None and not isinstance(payload, _StreamState) payload = state if state is not None else payload + method = method or ("POST" if payload is not None else "GET") try: runner_url = runner_url.strip() or (runner.url.strip() if runner is not None else "") if not runner_url: @@ -971,26 +970,32 @@ async def call_runner( await _stop_funding(pay_task) # Non-JSON bodies (an image, ndjson) are handed back unparsed in `content`. is_json = _is_json_content_type(response_content_type) - data: dict[str, Any] = {} - if is_json: - try: - data = json.loads(body) - except (ValueError, RecursionError) as e: - await _release_reservation(runner_url, session_id, runner, method=method) - raise LivepeerGatewayError( - f"HTTP JSON error: endpoint did not return valid JSON: {e} " - f"(url={runner_url}, content_type={response_content_type})" - ) from e + is_session = method.upper() == "POST" and _is_session_endpoint(runner_url, runner) + try: + data = json.loads(body) if is_json else {} if not isinstance(data, dict): - await _release_reservation(runner_url, session_id, runner, method=method) - raise LivepeerGatewayError( - f"Live runner call expected JSON object, got {type(data).__name__}" - ) + raise LivepeerGatewayError(f"Live runner call expected JSON object, got {type(data).__name__}") + if is_session: + if missing := next((key for key in ("session_id", "app_url", "control_url") if not _string_value(data.get(key))), None): + raise LivepeerGatewayError(f"runner session response missing {missing}") + if session_id and not (session_id == data["session_id"] == data["session_id"].strip()): + raise LivepeerGatewayError("runner session response session_id does not match payment manifest") + _join_endpoint(data["control_url"], "stop") + except (LivepeerGatewayError, ValueError, RecursionError) as error: + if is_session and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII): + with contextlib.suppress(Exception): + await _post_empty(_join_endpoint(runner_url, f"{session_id}/stop"), allow_redirects=False) + if isinstance(error, LivepeerGatewayError): + raise + raise LivepeerGatewayError( + f"HTTP JSON error: endpoint did not return valid JSON: {error} " + f"(url={runner_url}, content_type={response_content_type})" + ) from error return LiveRunnerCallResult( data, runner_url=runner_url, runner=runner, - session_id=session_id or ("" if _reservation else _string_value(data.get("session_id"))), + session_id=session_id or _string_value(data.get("session_id")), payment_session=None if payment_type == "fixed" else payment_session, content=None if is_json else body, content_type=response_content_type, @@ -1123,11 +1128,18 @@ def _live_runner_price_info_from_json(value: object) -> LiveRunnerPriceInfo | No ) -async def _release_reservation(url: str, session_id: str, runner: LiveRunnerInstance | None, method: str = "POST") -> None: - with contextlib.suppress(Exception): - route = re.escape(urlsplit(runner.orchestrator_url if runner else "").path.rstrip("/")) + r"/apps/[\w-]+/session/?" - if method.upper() == "POST" and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII) and re.fullmatch(route, urlsplit(url).path, re.ASCII): - await _request_body(_join_endpoint(url, f"{session_id}/stop"), method="POST", allow_redirects=False) +def _is_session_endpoint(url: str, runner: LiveRunnerInstance | None) -> bool: + with contextlib.suppress(ValueError): + address = runner.orchestrator_url if runner else "" + base, target = urlsplit(address if "://" in address else f"https://{address}"), urlsplit(url) + default_port = 443 if target.scheme == "https" else 80 + origin = target.scheme, target.hostname, target.port if target.port is not None else default_port + single_shot = urlsplit(runner.url) if runner is not None and runner.mode == "single-shot" else None + same_orchestrator = not address or origin == (base.scheme, base.hostname, base.port if base.port is not None else default_port) + same_single_shot = single_shot and target.path.rstrip("/") == single_shot.path.rstrip("/") and origin == (single_shot.scheme, single_shot.hostname, single_shot.port if single_shot.port is not None else default_port) + has_http_origin = target.scheme in ("http", "https") and target.hostname is not None and target.port != 0 + return has_http_origin and same_orchestrator and not same_single_shot and re.fullmatch(re.escape(base.path.rstrip("/")) + r"/apps/[\w-]+/session/?", target.path, re.ASCII) is not None + return False async def stop_runner_session( @@ -1175,13 +1187,13 @@ def detect_process_gpu() -> LiveRunnerGPU | None: def _normalize_http_base(url: str) -> str: - url = url.strip() - normalized = url if "://" in url else f"https://{url}" - parsed = urlparse(normalized) - if parsed.scheme not in ("http", "https") or not parsed.netloc: - raise LivepeerGatewayError(f"Invalid orchestrator URL: {url!r}") - path = parsed.path.rstrip("/") - return urlunparse((parsed.scheme, parsed.netloc, path, "", parsed.query, "")) + try: + parsed = _parse_http_url(url) + if not parsed.hostname or parsed.port == 0: + raise ValueError("invalid hostname or port") + except ValueError as error: + raise LivepeerGatewayError(f"Invalid orchestrator URL: {url.strip()!r}") from error + return parsed._replace(path=parsed.path.rstrip("/"), params="", fragment="").geturl() def _join_endpoint(base_url: str, suffix: str) -> str: diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 96a6d8b..0e0a278 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from collections.abc import Sequence +from collections.abc import Callable, Sequence from typing import Any from .discovery import ( @@ -18,8 +18,8 @@ LiveRunnerCallResult, LiveRunnerInstance, LiveRunnerSession, + _is_session_endpoint, _live_runner_price_info_from_json, - _release_reservation, _string_value, call_runner, ) @@ -65,7 +65,7 @@ def __init__( def candidates(self) -> tuple[LiveRunnerInstance, ...]: return tuple(self._candidates) - async def next(self, *, _reservation: bool = False) -> LiveRunnerCallResult: + async def next(self) -> LiveRunnerCallResult: if self._closed: raise LivepeerGatewayError("Runner selection cursor is closed") if self._next_running: @@ -85,7 +85,6 @@ async def next(self, *, _reservation: bool = False) -> LiveRunnerCallResult: "payload": self._payload_state if self._payload_state is not None else self._body, "method": self._method, "timeout": self._timeout, - **({"_reservation": True} if _reservation else {}), } if self._content_type is not None: kwargs["content_type"] = self._content_type @@ -154,12 +153,14 @@ async def runner_selector( app: FilterValue | None = None, gpu: FilterValue | None = None, timeout: float = 5.0, + _matches: Callable[[LiveRunnerInstance], bool] = bool, ) -> RunnerSelectionCursor: if orchestrators is not None: entries = await discover_orchestrator_runners( orchestrators, app=app, gpu=gpu, + _has_runners=lambda entries: any(_matches(runner) for runner in _runner_candidates_from_discovery(entries)), ) else: entries = await discover_runners( @@ -171,7 +172,7 @@ async def runner_selector( gpu=gpu, ) - candidates = _runner_candidates_from_discovery(entries) + candidates = [runner for runner in _runner_candidates_from_discovery(entries) if _matches(runner)] if not candidates: _LOG.debug("select_runner failed: empty runner list") @@ -208,24 +209,13 @@ async def reserve_session( app=app, gpu=gpu, timeout=timeout, + _matches=lambda runner: _is_session_endpoint(runner.url, runner), ) - while True: - result = await cursor.next(_reservation=True) - fields = {key: _string_value(result.data.get(key)) for key in ("session_id", "app_url", "control_url")} - try: - if missing := next((key for key, value in fields.items() if not value), None): - raise LivepeerGatewayError(f"runner session response missing {missing}") - if result.session_id and not (result.session_id == fields["session_id"] == result.data["session_id"]): - raise LivepeerGatewayError("runner session response session_id does not match payment manifest") - session = LiveRunnerSession(**fields, runner_url=result.runner_url, runner=result.runner) - except (LivepeerGatewayError, ValueError) as error: - await _release_reservation(result.runner_url, result.session_id, result.runner) - cursor.rejections.append(RunnerRejection(url=result.runner_url, reason=str(error))) - else: - # No payment session means fixed price or offchain: nothing to fund. - if result.payment_session is not None: - session._start_payments(result.payment_session) - return session + result = await cursor.next() + session = LiveRunnerSession(result.session_id, result.data["app_url"].strip(), result.runner_url, result.data["control_url"], result.runner) + if result.payment_session is not None: + session._start_payments(result.payment_session) + return session def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list[LiveRunnerInstance]: diff --git a/tests/test_live_runner.py b/tests/test_live_runner.py index 32a58d6..1c714f8 100644 --- a/tests/test_live_runner.py +++ b/tests/test_live_runner.py @@ -247,16 +247,30 @@ async def test_stop_runner_session_request_requires_control_header(self) -> None with pytest.raises(LivepeerGatewayError): await stop_runner_session(request) - async def test_call_runner_can_attach_runner_instance(self) -> None: + @pytest.mark.parametrize( + "mode,override", + [ + ("persistent", ""), + ("single-shot", ""), + ("single-shot", "https://SERVICE.example.com:443/apps/runner-1/session/?format=json"), + ], + ) + async def test_call_runner_can_attach_runner_instance(self, mode: str, override: str) -> None: runner = LiveRunnerInstance( url="https://service.example.com/apps/runner-1/session", app="livepeer-sample/echo", runner_id="runner-1", - mode="persistent", + mode=mode, orchestrator_url="https://service.example.com", raw={"app": "livepeer-sample/echo"}, ) + data = { + "session_id": "session-1", + "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", + } if mode == "persistent" else {"ok": True} + def _request_body( url: str, *, @@ -267,17 +281,13 @@ def _request_body( ) -> tuple[bytes, str]: del method, payload, timeout assert headers == {"Accept": "*/*"} - return _json_data( - { - "session_id": "session-1", - "app_url": "https://service.example.com/app", - } - ) + return _json_data(data) with mock.patch.object(live_runner, "_request_body", side_effect=_request_body): - result = await call_runner(runner=runner) + result = await call_runner(override, runner=runner) assert result.runner is runner + assert result.data == data async def test_paid_call_retries_with_payment_headers(self) -> None: calls: list[ @@ -432,6 +442,7 @@ def _request_body( { "session_id": "fixed-manifest", "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", } ) @@ -503,8 +514,9 @@ def _request_body( if headers and "Livepeer-Payment" in headers: return _json_data( { - "session_id": "session-2", + "session_id": "manifest-2", "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", } ) unpaid_count += 1 @@ -532,7 +544,7 @@ def _request_body( signer_url="https://signer.example.com", ) - assert result.data["session_id"] == "session-2" + assert result.data["session_id"] == "manifest-2" assert result.session_id == "manifest-2" assert result.payment_session is payment_sessions[1] challenge_headers = { diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index b0db0b0..f16370b 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -220,73 +220,18 @@ async def test_already_released_session_only_stops_local_funding(self) -> None: post_empty.assert_not_awaited() -class _Cursor: - def __init__(self, *results: LiveRunnerCallResult) -> None: - self.results = list(results) - self.rejections = [] - - async def next(self, *, _reservation: bool = False) -> LiveRunnerCallResult: - if self.results: - return self.results.pop(0) - raise AssertionError("unexpected extra runner selection") - - -def _reservation( - name: str, - *, - control_url: str | None, - payment_session: object | None = None, -) -> LiveRunnerCallResult: - data = { - "session_id": f"session-{name}", - "app_url": f"https://orch.example.com/session-{name}/app", - } - if control_url is not None: - data["control_url"] = control_url - return LiveRunnerCallResult( - data, - runner_url=f"https://orch.example.com/runner-{name}/session", +async def test_onchain_reservation_starts_scoped_funding() -> None: + payment_session = _FundingSession() + expected = _session() + result = LiveRunnerCallResult( + {"app_url": expected.app_url, "control_url": expected.control_url}, + runner_url=expected.runner_url, + session_id=expected.session_id, payment_session=payment_session, # type: ignore[arg-type] ) + cursor = mock.Mock(next=mock.AsyncMock(return_value=result)) + with mock.patch.object(selection, "runner_selector", return_value=cursor): + session = await selection.reserve_session() - -class TestReservationSelection: - async def test_onchain_reservation_starts_scoped_funding(self) -> None: - payment_session = _FundingSession() - cursor = _Cursor( - _reservation( - "1", - control_url=_CONTROL_URL, - payment_session=payment_session, - ) - ) - - with mock.patch.object( - selection, "runner_selector", new=mock.AsyncMock(return_value=cursor) - ): - session = await selection.reserve_session() - - await asyncio.wait_for(payment_session.started.wait(), timeout=1.0) - await session.stop_payments() - - @pytest.mark.parametrize( - "bad_control_url", - [None, "ftp://orch.example.com/session/bad"], - ) - async def test_invalid_control_url_tries_next_runner( - self, bad_control_url: str | None - ) -> None: - cursor = _Cursor( - _reservation("bad", control_url=bad_control_url), - _reservation("good", control_url=_CONTROL_URL), - ) - - with mock.patch.object( - selection, - "runner_selector", - new=mock.AsyncMock(return_value=cursor), - ): - session = await selection.reserve_session() - - assert session.session_id == "session-good" - assert len(cursor.rejections) == 1 + await asyncio.wait_for(payment_session.started.wait(), timeout=1.0) + await session.stop_payments() diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py index 74f3f70..4788ce8 100644 --- a/tests/test_reservation_cleanup.py +++ b/tests/test_reservation_cleanup.py @@ -2,13 +2,14 @@ from types import SimpleNamespace from unittest import mock +from urllib.parse import urljoin import pytest from aiohttp import web from aiohttp.test_utils import TestServer from livepeer_gateway import live_runner, selection -from livepeer_gateway.errors import NoRunnerAvailableError +from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError _SESSION_URLS = {"app_url": "https://orch.test/app", "control_url": "https://orch.test/control"} _ID_MISMATCH = "does not match payment manifest" @@ -22,6 +23,7 @@ ("onchain-id", b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["onchain-id"]), ("onchain-id", {}, "missing session_id", ["onchain-id"]), ("onchain-id", {}, None, ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": "onchain-id", "control_url": "https://orch.test:bad/s1"}, None, ["onchain-id"]), ("onchain-id", {**_SESSION_URLS, "session_id": "wrong-id"}, _ID_MISMATCH, ["onchain-id"]), ("onchain-id", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, ["onchain-id"]), (" onchain-id ", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, []), @@ -80,18 +82,46 @@ async def reserve_next(request: web.Request) -> web.Response: @pytest.mark.parametrize( - "prefix,path,should_stop", + "prefix,path,is_session", [ ("", "/apps/a/app/apps/b/session", False), ("/mount", "/apps/a/session", False), ("", "/apps/a/session;other", False), + ("", "https://proxy.test/apps/a/session", False), + ("", "https://ORCH.test:443/apps/a/session", True), ("/mount", "/mount/apps/a/session", True), ("/mount;v=2", "/mount/apps/a/session", False), ("/mount;v=2", "/mount;v=2/apps/a/session", True), ], ) -async def test_cleanup_only_targets_discovered_reservation_route(prefix, path, should_stop): - runner = SimpleNamespace(orchestrator_url="https://orch.test" + prefix) - with mock.patch.object(live_runner, "_request_body") as request: - await live_runner._release_reservation("https://orch.test" + path, "onchain-id", runner) - assert request.await_count == int(should_stop) +def test_session_endpoint_matches_the_discovery_mount(prefix, path, is_session): + runner = SimpleNamespace(mode="persistent", orchestrator_url="https://orch.test" + prefix) + assert live_runner._is_session_endpoint(urljoin("https://orch.test", path), runner) is is_session + + +def test_session_endpoint_requires_http_origin(): + for url in ("/apps/a/session", "ftp://orch.test/apps/a/session", "https://orch.test:0/apps/a/session"): + assert not live_runner._is_session_endpoint(url, None) + + +@pytest.mark.parametrize( + "body,error", + [ + (b"{}", "missing session_id"), + (b'{"session_id":"s1","app_url":"https://orch.test/app","control_url":"https://orch.test:bad/s1"}', "Invalid orchestrator URL"), + ], +) +async def test_call_runner_validates_session_with_implicit_post(body, error): + runner = live_runner.LiveRunnerInstance( + url="https://orch.test/apps/proxy/session", + app="proxy", + runner_id="proxy", + mode="single-shot", + orchestrator_url="https://orch.test", + raw={}, + ) + with mock.patch.object(live_runner, "_request_body", return_value=(body, "application/json")) as request: + with pytest.raises(LivepeerGatewayError, match=error): + await live_runner.call_runner("https://orch.test/apps/a/session", runner=runner, method="", payload={}) + + assert request.call_args.kwargs["method"] == "POST" diff --git a/tests/test_selection.py b/tests/test_selection.py index 6dc2ec3..cab1554 100644 --- a/tests/test_selection.py +++ b/tests/test_selection.py @@ -1,11 +1,12 @@ from __future__ import annotations import asyncio +import json from unittest import mock import pytest -from livepeer_gateway import selection +from livepeer_gateway import discovery, live_runner, selection from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError from livepeer_gateway.live_runner import LiveRunnerCallResult, LiveRunnerInstance @@ -331,76 +332,41 @@ async def test_runner_selector_rejects_invalid_orchestrator_url(self) -> None: with pytest.raises(LivepeerGatewayError): await selection.runner_selector(orchestrators="ftp://orch.example.com") - async def test_reserve_session_returns_session_from_call_result(self) -> None: - async def _call_runner( - *, - runner: LiveRunnerInstance, - payload: dict[str, object], - method: str, - timeout: float, - _reservation: bool, - ) -> LiveRunnerCallResult: - del payload, method, timeout - assert _reservation - return LiveRunnerCallResult( - { - "session_id": "session-1", - "app_url": "https://orch-a/apps/a/app", - "control_url": "https://orch-a/apps/a/session/session-1", - }, - runner_url=runner.url, - runner=runner, - ) - + @pytest.mark.parametrize( + "first_address,first_mode,first_url", + [ + ("https://orch-a", "single-shot", "https://orch-a/apps/report/session"), + ("https:///mount", "persistent", "https://orch-a/mount/apps/report/session"), + ("https://orch-a:0", "persistent", "https://orch-a/apps/report/session"), + ], + ) + async def test_reserve_session_uses_first_eligible_orchestrator( + self, first_address: str, first_mode: str, first_url: str, + ) -> None: + second = "https://orch-b/mount/apps/a/session" + body = {"session_id": " s1 ", "app_url": second + "/s1/app", "control_url": second + "/s1"} with ( mock.patch.object( - selection, + discovery, "discover_runners", - return_value=[ - _entry([{"url": "https://orch-a/apps/a/session", "app": "app-a"}]) + side_effect=[ + [_entry([{"url": first_url, "app": "app-a", "mode": first_mode}], address=first_address)], + [_entry([{"url": second, "app": "app-a", "mode": "persistent"}], address="orch-b:443/mount")], ], ), - mock.patch.object(selection, "call_runner", side_effect=_call_runner), - ): - session = await selection.reserve_session( - discovery_url="https://example.com/discovery", app="app-a" - ) - - assert session.session_id == "session-1" - assert session.app_url == "https://orch-a/apps/a/app" - assert session.runner_url == "https://orch-a/apps/a/session" - assert session.runner is not None - assert session.runner.app == "app-a" - - async def test_reserve_session_rejects_non_session_json(self) -> None: - async def _call_runner( - *, - runner: LiveRunnerInstance, - payload: dict[str, object], - method: str, - timeout: float, - _reservation: bool, - ) -> LiveRunnerCallResult: - del runner, payload, method, timeout - assert _reservation - return LiveRunnerCallResult( - {"ok": True}, runner_url="https://orch-a/apps/a/app" - ) - - with ( mock.patch.object( - selection, - "discover_runners", - return_value=[ - _entry([{"url": "https://orch-a/apps/a/app", "app": "app-a"}]) - ], - ), - mock.patch.object(selection, "call_runner", side_effect=_call_runner), + live_runner, "_request_body", return_value=(json.dumps(body).encode(), "application/json") + ) as request, ): - with pytest.raises(LivepeerGatewayError): - await selection.reserve_session( - discovery_url="https://example.com/discovery", app="app-a" - ) + session = await selection.reserve_session(orchestrators=["https://orch-a", "https://orch-b"]) + + assert session.session_id == "s1" + assert session.app_url == body["app_url"] + assert session.control_url == body["control_url"] + assert session.runner_url == second + assert session.runner is not None and session.runner.app == "app-a" + request.assert_awaited_once() + assert request.call_args.args[0] == second async def test_runner_selector_supports_single_shot_url(self) -> None: async def _call_runner(