Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
- `LivePaymentSession.manifest_id` for payment attribution
- Flexible request body types on call_runner and selectors.

### Fixed

- Live runners replace their reservation-event reader when re-registration
returns a new channel. An ended or failed reader triggers registration on the
next heartbeat, including after an orchestrator restart.
- Trickle subscriber transport cleanup survives callback cancellation, including
cancellation during natural end-of-stream cleanup. Caller cancellation has a
bounded cleanup grace period; repeated close calls reuse the same teardown.

### Changed

- `discover_orchestrators` is now asynchronous and must be awaited, including
Expand Down
72 changes: 66 additions & 6 deletions src/livepeer_gateway/live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ def __init__(
self._closed = False
self._task: asyncio.Task[None] | None = None
self._o2r_task: asyncio.Task[None] | None = None
self._heartbeat_lock = asyncio.Lock()
self._o2r_needs_registration = False
self._o2r_closing_reader: ChannelReader | None = None
self._o2r_close_task: asyncio.Task[None] | None = None

async def start(self) -> LiveRunnerRegistration:
await self._send_heartbeat()
Expand All @@ -339,9 +343,9 @@ async def close(self) -> None:
o2r_reader = self._o2r_reader
self._o2r_reader = None
self._o2r_task = None
if o2r_reader is not None:
if o2r_reader is not None or self._o2r_close_task is not None:
try:
await o2r_reader.close(wait_callback=False)
await self._close_o2r_reader(o2r_reader)
except asyncio.CancelledError:
raise
except Exception:
Expand Down Expand Up @@ -495,6 +499,19 @@ async def _heartbeat_loop(self) -> None:
_LOG.warning("Live runner heartbeat failed; retrying on next interval", exc_info=True)

async def _send_heartbeat(self) -> None:
# A re-registration and its reader replacement must be one operation.
async with self._heartbeat_lock:
if self._closed:
return
await self._send_heartbeat_locked()

async def _send_heartbeat_locked(self) -> None:
# A 404/EOF ends ChannelReader normally; errors also finish its callback
# task. Re-register on the next heartbeat instead of advertising a runner
# whose reservation events can no longer arrive.
if self._o2r_needs_registration or (self._o2r_task is not None and self._o2r_task.done()):
_LOG.warning("Live runner O2R reader ended; registering a fresh channel")
self._heartbeat_secret = None
is_initial_heartbeat = self._heartbeat_secret is None
auth = self._heartbeat_secret or self._bootstrap_secret
request_orchestrator_url = self.orchestrator_url
Expand Down Expand Up @@ -547,8 +564,9 @@ async def _send_heartbeat(self) -> None:
elif is_initial_heartbeat:
raise LivepeerGatewayError("Live runner heartbeat response missing heartbeat_secret")

if is_initial_heartbeat:
self._start_o2r(data.get("o2r"))
if self._closed:
return
await self._start_o2r(data.get("o2r"))

async def _post_heartbeat(self, auth: str) -> dict[str, Any]:
return await post_json(
Expand All @@ -558,8 +576,23 @@ async def _post_heartbeat(self, auth: str) -> dict[str, Any]:
timeout=self._timeout,
)

def _start_o2r(self, value: object) -> None:
if self._closed or self._o2r_reader is not None:
async def _close_o2r_reader(self, reader: ChannelReader | None) -> None:
# Closing cancels the callback once. Keep that cleanup task alive if a
# replacement or shutdown waiter is cancelled, and reuse it on retry.
if reader is not None and reader is not self._o2r_closing_reader:
async def finish() -> None:
try:
await reader.close(wait_callback=False)
except Exception:
_LOG.exception("Live runner O2R reader failed during cleanup")

self._o2r_closing_reader = reader
self._o2r_close_task = asyncio.create_task(finish())
if self._o2r_close_task is not None:
await asyncio.shield(self._o2r_close_task)

async def _start_o2r(self, value: object) -> None:
if self._closed:
return
if not _is_trickle_channel_response(value):
if value is not None:
Expand All @@ -569,10 +602,37 @@ def _start_o2r(self, value: object) -> None:
url = channel.get("url", "").strip()
if not url:
return
if (
not self._o2r_needs_registration
and self._o2r_reader is not None
and self.o2r_channel is not None
and self.o2r_channel.get("url", "").strip() == url
and self._o2r_task is not None
and not self._o2r_task.done()
):
return
old_reader = self._o2r_reader
# Keep ownership until close completes. If this operation is cancelled,
# shutdown or the next heartbeat must still be able to close the reader.
if old_reader is not None:
try:
await self._close_o2r_reader(old_reader)
except asyncio.CancelledError:
# The new heartbeat secret may already be installed, while the
# old reader is still alive. A retry must request the channel
# again even if ordinary heartbeat responses omit it.
self._o2r_needs_registration = True
raise
except Exception:
# An already-failed reader must not block its replacement.
_LOG.exception("Live runner old O2R reader failed during replacement")
if self._closed:
return
self.o2r_channel = channel
reader = ChannelReader(url, start_seq=0, on_event=self._handle_o2r_message)
self._o2r_reader = reader
self._o2r_task = reader.callback_task()
self._o2r_needs_registration = False

async def _handle_o2r_message(self, message: dict[str, Any]) -> None:
if message.get("keep") == "alive":
Expand Down
38 changes: 37 additions & 1 deletion src/livepeer_gateway/trickle_subscriber.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@


_LOG = logging.getLogger(__name__)
_CLOSE_CANCEL_GRACE_S = 10.0

@dataclass(frozen=True)
class TrickleSubscriberStats:
Expand Down Expand Up @@ -76,6 +77,7 @@ def __init__(
self._errored = False
self._closing = False
self._closed = False
self._close_task: asyncio.Task[None] | None = None
self._prefetch_task: asyncio.Task[None] | None = None
self._started_at = time.time()
self._stats: dict[str, int] = {
Expand Down Expand Up @@ -290,7 +292,41 @@ async def _preconnect_next_segment(self) -> None:
self._pending_get = next_conn

async def close(self) -> None:
"""Close the session when done."""
"""Keep transport cleanup owned when callers are cancelled.

Natural EOF cleanup can overlap reader shutdown. Both await the same
teardown, so cancelling the callback cannot abandon its HTTP session.
Cancellation waits at most ten seconds; cleanup continues if it needs
longer, and a later close can await the same task.
"""
if self._close_task is None:
self._closing = True
self._close_task = asyncio.create_task(self._close_transport())
cancel_deadline: float | None = None
loop = asyncio.get_running_loop()
while True:
if cancel_deadline is not None and loop.time() >= cancel_deadline:
raise asyncio.CancelledError
try:
cleanup = asyncio.shield(self._close_task)
if cancel_deadline is None:
await cleanup
else:
await asyncio.wait_for(cleanup, max(0.0, cancel_deadline - loop.time()))
break
except asyncio.CancelledError:
if self._close_task.cancelled():
raise
if cancel_deadline is None:
cancel_deadline = loop.time() + _CLOSE_CANCEL_GRACE_S
except TimeoutError:
# Propagate cancellation without abandoning the owned cleanup.
# A later close() can still await the same task.
raise asyncio.CancelledError from None
if cancel_deadline is not None:
raise asyncio.CancelledError

async def _close_transport(self) -> None:
if self._closed:
return

Expand Down
Loading