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
85 changes: 77 additions & 8 deletions examples/fully_async/fully_async_rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import queue
import threading
import time
from collections.abc import Awaitable

import aiohttp

Expand Down Expand Up @@ -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
Comment on lines +88 to +93

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Re-raising asyncio.CancelledError here will cause the task.result() call in the continuous_worker_loop (line 169) and the task_done_callback (line 202) to raise the exception. Since CancelledError inherits from BaseException in Python 3.8+, it is not caught by the except Exception block (line 170), which will lead to the unexpected termination of the worker loop. Furthermore, if the exception propagates, the group is never put into the output_queue, causing the collector to lose those samples and potentially hang while waiting for the target batch size. To maintain the "exception-safe" contract and prevent group loss, it is recommended to catch the cancellation, mark the samples as ABORTED, and return the group normally. When resetting these samples for retry, ensure all metadata fields (e.g., remove_sample, train_metadata) are cleared to their default state to prevent carrying over stale data. Note that you should also update the corresponding test case test_cancellation_propagates_after_marking in tests/fast/rollout/test_fully_async_rollout_timeout.py to reflect this change.

    except asyncio.CancelledError:
        logger.warning(
            "Group task was cancelled; marking %d samples ABORTED for requeue",
            len(group),
        )
        for s in group:
            s.status = Sample.Status.ABORTED
            s.remove_sample = False
            s.train_metadata = {}
        return group
References
  1. When implementing a function to reset Sample objects for retry, ensure all generated outputs and metadata fields (e.g., remove_sample, train_metadata) are cleared to their default state to prevent carrying over stale data from previous attempts.

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()
Expand Down Expand Up @@ -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"""
Expand All @@ -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
Expand All @@ -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,
)
)

Expand Down
12 changes: 12 additions & 0 deletions miles/utils/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The help text suggests setting the value to None to disable the timeout. However, because the argument type is set to float, argparse will raise a ValueError if a user attempts to pass the string "None" via the command line. It is clearer to instruct users to use a non-positive value (e.g., 0) to disable the time bound.

Suggested change
"concurrency slot forever. Set to None (or <= 0) to disable."
"concurrency slot forever. Set to <= 0 to disable."

),
)
parser.add_argument(
"--custom-generate-function-path",
type=str,
Expand Down
153 changes: 153 additions & 0 deletions tests/fast/rollout/test_fully_async_rollout_timeout.py
Original file line number Diff line number Diff line change
@@ -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)
Loading