diff --git a/examples/fully_async/fully_async_rollout.py b/examples/fully_async/fully_async_rollout.py index e4c23cc1206..4bf385c0b0b 100644 --- a/examples/fully_async/fully_async_rollout.py +++ b/examples/fully_async/fully_async_rollout.py @@ -4,6 +4,7 @@ import queue import threading import time +from collections.abc import Awaitable import aiohttp @@ -49,6 +50,59 @@ async def get(self, args) -> int | None: _cached_version = _CachedWeightVersion() +async def _run_group_with_timeout( + coro: Awaitable[list[Sample]], + group: list[Sample], + timeout_s: float | None, +) -> list[Sample]: + """Run a group-generation coroutine with a hard timeout and exception safety. + + Contract: always returns the group list and NEVER raises. On timeout or any + exception, every sample in ``group`` is marked ``Sample.Status.ABORTED`` so + the outer collector's aborted-requeue path in ``generate_rollout_async`` + re-adds the group to the data buffer for retry. + + This is the single choke point that fixes two historical bugs in the + continuous worker loop: + 1. Hung group-tasks (e.g. an agent stuck in an infinite tool-call loop) + that would otherwise own a concurrency slot forever. + 2. Silent group-loss when ``generate_and_rm_group``'s ``asyncio.gather`` + propagates a sub-task exception — previously swallowed by a bare + ``except Exception: print`` in the worker loop, dropping the group + without requeueing it. + + A ``timeout_s`` of None or a non-positive value disables the time bound; + exception safety still applies. + """ + use_timeout = timeout_s is not None and timeout_s > 0 + try: + if use_timeout: + return await asyncio.wait_for(coro, timeout=timeout_s) + return await coro + except asyncio.TimeoutError: + logger.warning( + "Group task exceeded timeout of %.1fs; marking %d samples ABORTED for requeue", + timeout_s, + len(group), + ) + except asyncio.CancelledError: + # Propagate cancellation (e.g. worker shutdown) without silencing it, + # but first mark samples so any caller that catches can requeue. + for s in group: + s.status = Sample.Status.ABORTED + raise + except Exception as e: + logger.warning( + "Group task raised %s: %s; marking %d samples ABORTED for requeue", + type(e).__name__, + e, + len(group), + ) + for s in group: + s.status = Sample.Status.ABORTED + return group + + # Global worker manager _global_worker = None _worker_lock = threading.Lock() @@ -88,6 +142,10 @@ def __init__(self, args, data_buffer: DataSource, concurrency=10): self.output_queue = queue.Queue(maxsize=1000) # Continuous output queue self.worker_thread = None self.state = GenerateState(args) + # Per-task timeout bounds how long a single group-generation task may run + # before its samples are marked ABORTED and requeued. See + # _run_group_with_timeout for the full contract. + self.group_task_timeout_s: float | None = getattr(args, "rollout_group_timeout_s", 1800.0) async def continuous_worker_loop(self): """Continuous work loop - constantly get data from data_buffer and process""" @@ -99,14 +157,18 @@ async def continuous_worker_loop(self): while self.running: try: - # Clean up completed tasks + # Clean up completed tasks. The timeout/exception wrapper used at + # dispatch time guarantees the wrapped coroutine never raises + # (see _run_group_with_timeout) so task.result() here is a + # defensive safety net; any raised exception is logged and the + # slot is reclaimed without dropping a group silently. if active_tasks: done_tasks = {task for task in active_tasks if task.done()} for task in done_tasks: try: - task.result() # Results are already handled in callbacks + task.result() except Exception as e: - print(f"Task failed with exception: {e}") + logger.exception("Unexpected error from wrapped group task: %s", e) active_tasks -= done_tasks # If active task count hasn't reached limit, try to get new data and start tasks @@ -117,13 +179,20 @@ async def continuous_worker_loop(self): group_id = group_id_counter group_id_counter += 1 - # Create new async task + # Create new async task wrapped with a per-task timeout + # and exception safety net so a single stuck trial cannot + # own a concurrency slot forever, and transport errors + # never silently drop a group (see _run_group_with_timeout). task = asyncio.create_task( - generate_and_rm_group( - self.args, + _run_group_with_timeout( + generate_and_rm_group( + self.args, + group, + sampling_params=self.state.sampling_params.copy(), + evaluation=False, + ), group, - sampling_params=self.state.sampling_params.copy(), - evaluation=False, + timeout_s=self.group_task_timeout_s, ) ) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 375cd6c2c27..641ff5cf46b 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -396,6 +396,18 @@ def add_rollout_arguments(parser): "async mode. None (default) disables staleness filtering." ), ) + parser.add_argument( + "--rollout-group-timeout-s", + type=float, + default=1800.0, + help=( + "Hard upper bound (seconds) on a single group-generation task in the fully " + "async worker. A group that exceeds this deadline has its samples marked " + "Sample.Status.ABORTED and is returned to the data buffer for retry via the " + "existing aborted-requeue path, preventing stuck trials from owning a " + "concurrency slot forever. Set to None (or <= 0) to disable." + ), + ) parser.add_argument( "--custom-generate-function-path", type=str, diff --git a/tests/fast/rollout/test_fully_async_rollout_timeout.py b/tests/fast/rollout/test_fully_async_rollout_timeout.py new file mode 100644 index 00000000000..8c67b76e95d --- /dev/null +++ b/tests/fast/rollout/test_fully_async_rollout_timeout.py @@ -0,0 +1,153 @@ +"""Tests for the per-task timeout + exception-safe requeue contract in +``examples/fully_async/fully_async_rollout.py``. + +Covers: + (a) Normal completion — samples flow through unchanged. + (b) Timeout exceeded — samples are marked ``Sample.Status.ABORTED`` so the + outer collector's aborted-requeue path re-adds them to the data buffer. + (c) Coroutine raises — samples are also marked ``ABORTED`` instead of the + group being silently dropped (regression test for the previous bare + ``except Exception: print`` in ``continuous_worker_loop``). +""" + +import asyncio +import importlib.util +from pathlib import Path + +import pytest + +from miles.utils.types import Sample + +_MODULE_PATH = ( + Path(__file__).resolve().parents[3] + / "examples" + / "fully_async" + / "fully_async_rollout.py" +) + + +def _load_module(): + spec = importlib.util.spec_from_file_location("fully_async_rollout_under_test", _MODULE_PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_fa = _load_module() +_run_group_with_timeout = _fa._run_group_with_timeout + + +def _group(n: int = 2) -> list[Sample]: + return [Sample(index=i, prompt="p") for i in range(n)] + + +async def test_normal_completion_returns_samples_unchanged(): + group = _group(3) + + async def ok() -> list[Sample]: + for s in group: + s.status = Sample.Status.COMPLETED + s.response = "done" + return group + + out = await _run_group_with_timeout(ok(), group, timeout_s=5.0) + + assert out is group + assert [s.status for s in out] == [Sample.Status.COMPLETED] * 3 + assert all(s.response == "done" for s in out) + + +async def test_timeout_marks_samples_aborted(): + group = _group(4) + + async def slow() -> list[Sample]: + await asyncio.sleep(10) + return group + + out = await _run_group_with_timeout(slow(), group, timeout_s=0.05) + + assert out is group + assert len(out) == 4 + assert all(s.status == Sample.Status.ABORTED for s in out) + + +async def test_exception_does_not_drop_group(): + group = _group(2) + + async def boom() -> list[Sample]: + raise RuntimeError("simulated transport failure") + + out = await _run_group_with_timeout(boom(), group, timeout_s=5.0) + + assert out is group + assert all(s.status == Sample.Status.ABORTED for s in out) + + +async def test_subtask_exception_via_gather_does_not_drop_group(): + """Mirrors production bug: ``generate_and_rm_group`` uses ``asyncio.gather`` + without ``return_exceptions=True`` so a single sub-task raise propagates. + The wrapper must still return the group (with ABORTED status) rather than + letting the exception escape and silently drop the group. + """ + group = _group(3) + + async def good() -> Sample: + await asyncio.sleep(0) + return Sample(index=0, prompt="p") + + async def bad() -> Sample: + raise ConnectionResetError("peer hung up") + + async def gather_like(): + # One failing sub-task must propagate out of gather, which is the exact + # production failure mode this wrapper is designed to contain. + return await asyncio.gather(good(), bad(), good()) + + out = await _run_group_with_timeout(gather_like(), group, timeout_s=5.0) + + assert out is group + assert all(s.status == Sample.Status.ABORTED for s in out) + + +async def test_none_timeout_disables_time_bound_but_keeps_exception_safety(): + group = _group(2) + + async def boom() -> list[Sample]: + raise ValueError("still caught") + + out = await _run_group_with_timeout(boom(), group, timeout_s=None) + + assert out is group + assert all(s.status == Sample.Status.ABORTED for s in out) + + +async def test_non_positive_timeout_disables_time_bound(): + group = _group(1) + + async def quick() -> list[Sample]: + group[0].status = Sample.Status.COMPLETED + return group + + out = await _run_group_with_timeout(quick(), group, timeout_s=0.0) + + assert out is group + assert out[0].status == Sample.Status.COMPLETED + + +async def test_cancellation_propagates_after_marking(): + group = _group(2) + + async def long_running() -> list[Sample]: + await asyncio.sleep(10) + return group + + task = asyncio.create_task(_run_group_with_timeout(long_running(), group, timeout_s=5.0)) + await asyncio.sleep(0.01) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + # Samples should have been marked before the cancellation propagated so a + # caller that catches CancelledError can still requeue. + assert all(s.status == Sample.Status.ABORTED for s in group)