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
18 changes: 18 additions & 0 deletions docs/serverless/worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ The `config` parameter is a dictionary containing the following keys:
|-------------------|------------|--------------------------------------------------------------------|
| `handler` | `function` | The handler function called with each job input. |
| `prestart_timeout`| `number` | Optional deadline in seconds for all registered prestart hooks. |
| `take_ahead` | `int` | Optional number of extra jobs to request after a full batch. Defaults to `RUNPOD_TAKE_AHEAD`, or `0` (off). |

### handler

Expand Down Expand Up @@ -64,6 +65,23 @@ Support depends on the runtime mode:
If shutdown begins while a claimed request waits for prestart, that request
fails with `prestart_cancelled`.

## Take-ahead

When a job take returns a full batch, a busy worker can request up to
`take_ahead` extra jobs while its current jobs run. This overlaps the next
job-take round trip with work. It is disabled by default:

```python
runpod.serverless.start({"handler": handler, "take_ahead": 8})
```

Set `RUNPOD_TAKE_AHEAD` instead to configure it through the endpoint
environment. A worker keeps held jobs even if another worker becomes free,
so enable take-ahead when throughput matters more than spreading a deep queue
across workers. Stop signals still apply to held jobs. Take-ahead is disabled
when `refresh_worker` is set; don't combine it with handlers that return
`refresh_worker`.

## Failure logs

When a prestart hook fails, the SDK can attach its `stdout`/`stderr` to the
Expand Down
82 changes: 76 additions & 6 deletions runpod/serverless/modules/rp_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
import inspect
import json
import os
import signal
import sys
import traceback
Expand Down Expand Up @@ -36,6 +37,7 @@
# wait so one long job can't hold the other slots idle, and so set_scale still
# runs as often as it did under the old fixed sleep.
FULL_WAIT_SECONDS = 1
TAKE_AHEAD_ENV = "RUNPOD_TAKE_AHEAD"
# Cap the result uploads that may overlap new work. The shared HTTP client sets
# no connection limit (TCPConnector(limit=0)) and a 600 s timeout, so without a
# ceiling a stalled result endpoint would let a worker retain unbounded results
Expand All @@ -50,6 +52,33 @@ def _handle_uncaught_exception(exc_type, exc_value, exc_traceback):
log.error(f"Uncaught exception | {exc}")


def _take_ahead_from(config: dict[str, Any]) -> int:
"""Read the optional number of extra jobs a busy worker may hold."""
value = config.get("take_ahead")
if value is None:
value = os.environ.get(TAKE_AHEAD_ENV, "0")

try:
if isinstance(value, bool) or not isinstance(value, (int, str)):
raise TypeError
take_ahead = int(value)
except (TypeError, ValueError):
log.warn(
f"JobScaler | Ignoring invalid take_ahead {value!r}; expected an integer >= 0."
)
return 0

if take_ahead < 0:
log.warn(f"JobScaler | Ignoring negative take_ahead {take_ahead}.")
return 0

if take_ahead and config.get("refresh_worker", False):
log.warn("JobScaler | take_ahead is disabled when refresh_worker is set.")
return 0

return take_ahead


def _default_concurrency_modifier(current_concurrency: int) -> int:
"""
Default concurrency modifier.
Expand All @@ -76,6 +105,9 @@ def __init__(self, config: dict[str, Any]):
self._jobs_available = asyncio.Event()
# Set when a job leaves the worker so a full get_jobs re-checks for room.
self._slot_freed = asyncio.Event()
# Set when run_jobs dequeues a held job, so intake can refill the buffer
# only after its previous batch has been dispatched.
self._job_dequeued = asyncio.Event()
self._prestart_ready = asyncio.Event()
self._prestart_succeeded = False
self._prestart_error: dict[str, Any] | None = None
Expand All @@ -102,7 +134,10 @@ def __init__(self, config: dict[str, Any]):
self.stop_signals_fetcher = get_stop_signals
self.stop_signals_fetcher_timeout = 90

self.jobs_queue = asyncio.Queue(maxsize=self.current_concurrency)
self.take_ahead = _take_ahead_from(config)
self._queue_is_deep = False
self._queued_job_ids: set[str] = set()
self.jobs_queue = asyncio.Queue(maxsize=self._queue_size())

self.concurrency_modifier = _default_concurrency_modifier
self.jobs_fetcher = get_job
Expand Down Expand Up @@ -138,7 +173,7 @@ def __init__(self, config: dict[str, Any]):
async def set_scale(self):
self.current_concurrency = self.concurrency_modifier(self.current_concurrency)

if self.jobs_queue and (self.current_concurrency == self.jobs_queue.maxsize):
if self.jobs_queue and (self._queue_size() == self.jobs_queue.maxsize):
# no need to resize
return

Expand All @@ -148,11 +183,14 @@ async def set_scale(self):
await asyncio.sleep(1)
continue

self.jobs_queue = asyncio.Queue(maxsize=self.current_concurrency)
self.jobs_queue = asyncio.Queue(maxsize=self._queue_size())
log.debug(
f"JobScaler.set_scale | New concurrency set to: {self.current_concurrency}"
)

def _queue_size(self) -> int:
return self.current_concurrency + self.take_ahead

def start(self):
"""
This is required for the worker to be able to shut down gracefully
Expand Down Expand Up @@ -339,7 +377,14 @@ async def get_jobs(self, session: ClientSession):
break
await self.set_scale()

if self.take_ahead and self._queue_is_deep and not self.jobs_queue.empty():
log.debug("JobScaler.get_jobs | Holding jobs. Waiting for a slot.")
await self._wait_until_queue_drained()
continue

jobs_needed = self.current_concurrency - self.current_occupancy()
if self.take_ahead and self._queue_is_deep and self.current_concurrency > 0:
jobs_needed += self.take_ahead
if jobs_needed <= 0:
log.debug("JobScaler.get_jobs | Queue is full. Waiting to drain.")
await self._wait_until_drained()
Expand All @@ -354,6 +399,8 @@ async def get_jobs(self, session: ClientSession):
timeout=self.jobs_fetcher_timeout,
)

self._queue_is_deep = len(acquired_jobs or []) >= jobs_needed

if not acquired_jobs:
log.debug("JobScaler.get_jobs | No jobs acquired.")
continue
Expand All @@ -371,6 +418,8 @@ async def get_jobs(self, session: ClientSession):

for job in acquired_jobs:
await self.jobs_queue.put(job)
if self.take_ahead:
self._queued_job_ids.add(job["id"])
self.job_progress.add(job)
log.debug("Job Queued", job["id"])
self._jobs_available.set()
Expand All @@ -397,6 +446,22 @@ async def get_jobs(self, session: ClientSession):
# Yield control back to the event loop
await asyncio.sleep(0)

async def _wait_until_queue_drained(self) -> None:
"""Wait for held jobs to leave the buffer or for worker shutdown."""
while self.is_alive() and not self.jobs_queue.empty():
self._job_dequeued.clear()
if self.jobs_queue.empty():
return
dequeued = asyncio.create_task(self._job_dequeued.wait())
stopping = asyncio.create_task(self._shutdown_event.wait())
try:
await asyncio.wait(
{dequeued, stopping}, return_when=asyncio.FIRST_COMPLETED
)
finally:
dequeued.cancel()
stopping.cancel()

async def _wait_until_drained(self) -> None:
"""Block until no job is in progress, shutdown begins, or FULL_WAIT_SECONDS pass."""
loop = asyncio.get_running_loop()
Expand Down Expand Up @@ -445,6 +510,8 @@ async def run_jobs(self, session: ClientSession):
and not self.jobs_queue.empty()
):
job = await self.jobs_queue.get()
self._queued_job_ids.discard(job["id"])
self._job_dequeued.set()
# Create a new task for each job and track it by job id
task = asyncio.create_task(self.handle_job(session, job))
tasks.add(task)
Expand Down Expand Up @@ -550,17 +617,20 @@ async def monitor_stop_signals(self, session: ClientSession):

async def stop_job(self, job_id: str) -> bool:
"""
Stop a single in-progress job by cancelling its running task.
Stop a running job or mark a held job to be skipped before it starts.

Args:
job_id: The id of the job to stop.

Returns:
True if a matching in-progress job was found and stopped,
False otherwise.
True if a matching job was found and stopped, False otherwise.
"""
task = self.jobs_tasks.get(job_id)
if task is None:
if self.take_ahead and job_id in self._queued_job_ids:
log.info("Stopping queued job.", job_id)
self._stopped_jobs.add(job_id)
return True
log.debug(f"JobScaler.stop_job | No in-progress job for {job_id}.")
return False
if job_id in self._sending_stop_pod:
Expand Down
178 changes: 178 additions & 0 deletions tests/test_serverless/test_take_ahead.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
"""Tests for opt-in job take-ahead in JobScaler."""

import asyncio
from unittest.mock import AsyncMock

import pytest

from runpod.serverless.modules import rp_scale


class Progress:
def __init__(self):
self.jobs = set()

def add(self, job):
self.jobs.add(job["id"])

def remove(self, job):
self.jobs.discard(job["id"])

def get_job_count(self):
return len(self.jobs)


class Platform:
"""Return scripted batches and block after the script is exhausted."""

def __init__(self, batches):
self.batches = list(batches)
self.asked = []
self.changed = asyncio.Event()

async def take(self, _session, count):
self.asked.append(count)
self.changed.set()
if not self.batches:
await asyncio.sleep(60)
return []
return [{"id": job_id, "input": {}} for job_id in self.batches.pop(0)[:count]]

async def wait_for_takes(self, count):
while len(self.asked) < count:
self.changed.clear()
if len(self.asked) >= count:
return
await asyncio.wait_for(self.changed.wait(), timeout=3)


class Worker:
def __init__(self, platform, concurrency, take_ahead):
self.started = []
self.finished = []
self.release = {}
self.started_changed = asyncio.Event()
self.stopping = False
self.scaler = rp_scale.JobScaler(
{"handler": lambda _: None, "take_ahead": take_ahead}
)
self.scaler.jobs_fetcher = platform.take
self.scaler.jobs_handler = self.handle
self.scaler.current_concurrency = concurrency
self.tasks = (
asyncio.create_task(self.scaler.get_jobs(AsyncMock())),
asyncio.create_task(self.scaler.run_jobs(None)),
)

async def handle(self, _session, _config, job):
job_id = job["id"]
self.started.append(job_id)
self.started_changed.set()
if not self.stopping:
await self.release.setdefault(job_id, asyncio.Event()).wait()
self.finished.append(job_id)

async def wait_for_started(self, count):
while len(self.started) < count:
self.started_changed.clear()
if len(self.started) >= count:
return
await asyncio.wait_for(self.started_changed.wait(), timeout=3)

def finish(self, *job_ids):
for job_id in job_ids:
self.release.setdefault(job_id, asyncio.Event()).set()

async def stop(self):
self.stopping = True
self.scaler.kill_worker()
self.finish(*self.release)
self.tasks[0].cancel()
await asyncio.gather(*self.tasks, return_exceptions=True)


@pytest.fixture(autouse=True)
def clean_take_ahead(monkeypatch):
monkeypatch.setattr(rp_scale, "JobsProgress", Progress)
monkeypatch.delenv(rp_scale.TAKE_AHEAD_ENV, raising=False)


def test_take_ahead_is_disabled_by_default():
assert rp_scale._take_ahead_from({}) == 0
assert rp_scale.JobScaler({"handler": lambda _: None}).take_ahead == 0


def test_take_ahead_config_and_environment(monkeypatch):
monkeypatch.setenv(rp_scale.TAKE_AHEAD_ENV, "16")
assert rp_scale._take_ahead_from({}) == 16
assert rp_scale._take_ahead_from({"take_ahead": 4}) == 4
assert rp_scale._take_ahead_from({"take_ahead": 0}) == 0


@pytest.mark.parametrize("value", [True, 1.5, "1.5", "many", -1, "-1"])
def test_invalid_take_ahead_is_ignored(value):
assert rp_scale._take_ahead_from({"take_ahead": value}) == 0


def test_take_ahead_is_disabled_with_refresh_worker():
assert rp_scale._take_ahead_from(
{"take_ahead": 8, "refresh_worker": True}
) == 0


@pytest.mark.asyncio
async def test_queue_capacity_includes_take_ahead():
scaler = rp_scale.JobScaler({"handler": lambda _: None, "take_ahead": 3})
scaler.concurrency_modifier = lambda _: 4
await scaler.set_scale()
assert scaler.jobs_queue.maxsize == 7


@pytest.mark.asyncio
async def test_deep_queue_takes_ahead_while_jobs_are_running():
platform = Platform([["a", "b"], ["c", "d"]])
worker = Worker(platform, concurrency=2, take_ahead=2)
try:
await platform.wait_for_takes(2)
await worker.wait_for_started(2)

assert platform.asked[:2] == [2, 2]
assert worker.started == ["a", "b"]
assert worker.scaler.jobs_queue.qsize() == 2

worker.finish("a")
await worker.wait_for_started(3)
assert "c" in worker.started
finally:
await worker.stop()


@pytest.mark.asyncio
async def test_short_take_does_not_request_extra_jobs():
platform = Platform([["a"], []])
worker = Worker(platform, concurrency=2, take_ahead=2)
try:
await platform.wait_for_takes(1)
await worker.wait_for_started(1)
worker.finish("a")
await platform.wait_for_takes(2)
assert platform.asked[:2] == [2, 1]
finally:
await worker.stop()


@pytest.mark.asyncio
async def test_stop_signal_applies_to_a_held_job():
platform = Platform([["a", "b"], ["c", "d"]])
worker = Worker(platform, concurrency=2, take_ahead=2)
try:
await platform.wait_for_takes(2)
await worker.wait_for_started(2)
assert await worker.scaler.stop_job("c") is True

worker.finish("a")
await worker.wait_for_started(3)
assert "c" not in worker.started
assert "d" in worker.started
finally:
await worker.stop()