Skip to content
1 change: 1 addition & 0 deletions docs/en/rl/advanced_tutorial/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ Reinforcement Learning
model.md
dataset.md
rl_trainer.md
../agent_loop_shutdown.md
loss.md
on_policy_distillation.md
38 changes: 38 additions & 0 deletions docs/en/rl/agent_loop_shutdown.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# AgentLoop lifecycle hooks

`AgentLoop` has three asynchronous lifecycle hooks. All of them are no-ops by
default, so loops without persistent resources or external clients need no
changes. Routers and Ray actors forward each hook to their workers.

Ray actors build the local loop on their first asynchronous call, so construction
errors surface on that call. All generation and lifecycle operations run
on that same asyncio loop. Control RPCs retain their separate Ray scheduling group
and can drain active tasks even when the generate group is full. Local loops are
unchanged.

## `close()`

Both RL trainers close their training and evaluation loop managers when `fit()`
exits, including after an error. A disaggregated trainer stops its background
producer first. A loop that owns sessions, background tasks or external clients
should override `close()` to stop admitting work, wait for active work to clean
up and close its clients. Bound any external I/O in the hook. All enabled managers
are given a chance to close. Close failures are logged; after otherwise successful
training, the first close failure is raised so the run cannot report success with
unreleased resources. If training already raised or was cancelled, that original
exception remains primary and the close failures remain in the logs.

The built-in sandbox loop rejects new runs, cancels active runners and waits
for their `finally` blocks to release their pools.

## `prepare_pause()` and `resume()`

Managers call `prepare_pause()` on every active loop before
`pause_generation()`, and `resume()` after `continue_generation()`. Loops whose
model calls come from an external harness use `prepare_pause()` to stop
admitting new calls and let accepted ones finish, so the abort that follows
does not cut a request the harness is still waiting on. If `prepare_pause()`
raises, the manager does not abort inference. The batch's
`group_gen_pause_time_s` measures the whole pause phase, from before
`prepare_pause()` through inference pause and producer cleanup, once at the
manager level.
3 changes: 3 additions & 0 deletions tests/rl/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

_RL_TEST_DIR = Path(__file__).resolve().parent
_LIGHTWEIGHT_TEST_FILES = {
"test_agent_loop_shutdown.py",
"test_cpu_pg.py",
"test_multi_task_agent_loop_manager.py",
"test_pending_tasks.py",
Expand All @@ -27,8 +28,10 @@
"test_rl_disaggregated_trainer.py",
"test_rollout_config_dist_port_base_patch.py",
"test_rollout_logic.py",
"test_sandbox_pool.py",
"test_single_turn_agent_loop.py",
"test_staleness_policy.py",
"test_trajectory_logging.py",
"test_utils.py",
}

Expand Down
82 changes: 82 additions & 0 deletions tests/rl/test_agent_loop_actor_lifecycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Control RPCs drain generation on its owning loop even when its Ray group is full."""

import asyncio
import threading
from typing import Any

import ray

from xtuner.v1.data_proto.rl_data import RolloutState
from xtuner.v1.rl.agent_loop.agent_loop import AGENT_LOOP_CONCURRENCY_GROUP_GENERATE, AgentLoopActor


class TestAgentLoopActorLifecycle:
def test_close_drains_saturated_generation_on_owner_loop(self) -> None:
# Local classes are serialized by value: workers need no test-module imports.
class Loop:
def __init__(self, started: threading.Event) -> None:
self.construct_loop = asyncio.get_event_loop()
self.started = started
self.cleaned = False

def _set_teacher_scorer(self, scorer: Any) -> None:
pass

async def generate_sample(self, state: RolloutState, **kwargs: Any) -> RolloutState:
self.generate_loop = asyncio.get_running_loop()
self.pending = asyncio.create_task(self._wait())
try:
await self.pending
except asyncio.CancelledError:
# A drained generation is allowed to return its interrupted state.
pass
return state

async def _wait(self) -> None:
try:
self.started.set()
await asyncio.Event().wait()
finally:
self.cleaned = True

async def close(self) -> None:
self.close_loop = asyncio.get_running_loop()
self.pending.cancel()
await asyncio.gather(self.pending, return_exceptions=True)

class Config:
def __init__(self, started: threading.Event) -> None:
self.started = started

def build_local(self, **kwargs: Any) -> Loop:
return Loop(self.started)

class Actor(AgentLoopActor):
def __init__(self) -> None:
self.started = threading.Event()
super().__init__(Config(self.started), None)

async def wait_started(self) -> bool:
return await asyncio.to_thread(self.started.wait, 20)

async def snapshot(self) -> tuple[bool, bool]:
loop = self.agent_loop
return loop.cleaned, loop.construct_loop is loop.generate_loop is loop.close_loop

ray.init(address="local", num_cpus=2, include_dashboard=False, object_store_memory=128 * 1024**2)
actor = None
try:
actor = ray.remote(
num_cpus=0,
concurrency_groups={AGENT_LOOP_CONCURRENCY_GROUP_GENERATE: 1},
)(Actor).remote()
generation = actor.generate_sample.remote(RolloutState(message=[]))
assert ray.get(actor.wait_started.remote(), timeout=30)
# The sole generate slot stays occupied until close drains the pending task.
ray.get(actor.close.remote(), timeout=30)
ray.get(generation, timeout=30)
assert ray.get(actor.snapshot.remote(), timeout=30) == (True, True)
finally:
if actor is not None:
ray.kill(actor)
ray.shutdown()
170 changes: 170 additions & 0 deletions tests/rl/test_agent_loop_shutdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""Shutdown reaches all loop owners without changing the sandbox Runner API."""

import asyncio
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch

import ray
import test_sandbox_pool as sandbox_fixtures

from xtuner.v1.rl.agent_loop.agent_loop import AgentLoop, AgentLoopActor, RouterAgentLoop
from xtuner.v1.rl.agent_loop.sandbox_agent_loop.agent_in_sandbox_loop import AgentInSandboxLoop
from xtuner.v1.rl.agent_loop.sandbox_agent_loop.judger import Judger
from xtuner.v1.rl.agent_loop.sandbox_agent_loop.runner import Runner
from xtuner.v1.rl.agent_loop.sandbox_agent_loop.sandbox import SandboxStage
from xtuner.v1.rl.agent_loop.sandbox_agent_loop.schemas import AgentRolloutItem
from xtuner.v1.rl.agent_loop_manager.agent_loop_manager import AgentLoopManager
from xtuner.v1.rl.agent_loop_manager.disagg_agent_loop_manager import DisaggAgentLoopManager
from xtuner.v1.train.rl_trainer import RLColocateTrainer, RLDisaggregatedTrainer


class TestLoopShutdown(unittest.IsolatedAsyncioTestCase):
async def test_base_close_is_optional_for_resource_free_loops(self):
class Loop(AgentLoop):
async def generate_sample(self, state, **kwargs):
return state

loop = Loop.__new__(Loop)
await loop.close()
await loop.close()

async def test_managers_close_local_actor_and_router_owners_despite_failure(self):
for manager_type in (AgentLoopManager, DisaggAgentLoopManager):
with self.subTest(manager_type=manager_type.__name__):
failure = RuntimeError("local cleanup failed")
local = SimpleNamespace(close=AsyncMock(side_effect=failure))
actor = MagicMock(spec=ray.actor.ActorHandle)
actor.close = SimpleNamespace(remote=AsyncMock())
worker = MagicMock(spec=ray.actor.ActorHandle)
worker.close = SimpleNamespace(remote=AsyncMock())
router = RouterAgentLoop([worker], MagicMock())
manager = manager_type.__new__(manager_type)
manager.task_runners = [SimpleNamespace(agent_loop=loop) for loop in (local, actor, router)]
with self.assertRaises(RuntimeError) as caught:
await manager.close()
self.assertIs(caught.exception, failure)
local.close.assert_awaited_once()
actor.close.remote.assert_awaited_once()
worker.close.remote.assert_awaited_once()

async def test_actor_forwards_close_to_its_local_loop(self):
loop = MagicMock(close=AsyncMock())
config = MagicMock()
config.build_local.return_value = loop
actor = AgentLoopActor(config, MagicMock())
await actor.close()
loop.close.assert_awaited_once()

@patch.dict("os.environ", {"SANDBOX_PROVIDER_USER": "test"})
async def test_sandbox_close_waits_for_original_runner_finally_once(self):
events = []
started, deleting, release = asyncio.Event(), asyncio.Event(), asyncio.Event()

class Provider(sandbox_fixtures.FakeProvider):
async def delete(self, env_id):
deleting.set()
await release.wait()
await super().delete(env_id)

class Block:
async def __call__(self, client, item, record):
started.set()
await asyncio.Event().wait()

pool = sandbox_fixtures.pool(Provider(events), sandbox_fixtures.spec())
runner = Runner(pool=pool, infer=SandboxStage(pre=[Block()]), validate=Judger("score", SandboxStage()))
item = AgentRolloutItem(
id="shutdown", data_source="test", instruction="task.md", task_root=Path("/tmp"), uid=1, pipeline=runner
)
loop = AgentInSandboxLoop.__new__(AgentInSandboxLoop)
loop._active_runs = set()
loop._closing = False
running = asyncio.create_task(loop._run_item(item))
await asyncio.wait_for(started.wait(), 2)
closing = asyncio.create_task(loop.close())
await asyncio.wait_for(deleting.wait(), 2)
self.assertFalse(closing.done())
with self.assertRaisesRegex(RuntimeError, "closing"):
await loop._run_item(item)
release.set()
await asyncio.wait_for(closing, 2)
with self.assertRaises(asyncio.CancelledError):
await running
await loop.close()
self.assertEqual(events.count("delete:env-1-agent"), 1)
self.assertEqual(events.count("close:env-1-agent"), 1)
self.assertFalse(loop._active_runs)


class TestTrainerShutdown(unittest.TestCase):
def test_fit_closes_train_and_eval_owners_for_every_exit(self):
for trainer_type in (RLColocateTrainer, RLDisaggregatedTrainer):
for outcome in (None, ValueError("training failed"), asyncio.CancelledError()):
for cleanup_fails in (False, True):
with self.subTest(trainer=trainer_type.__name__, outcome=outcome, cleanup_fails=cleanup_fails):
trainer = trainer_type.__new__(trainer_type)
trainer.logger = MagicMock()
trainer._enable_evaluate = True
trainer.agent_loop_manager = SimpleNamespace(
close=AsyncMock(side_effect=RuntimeError("cleanup failed") if cleanup_fails else None)
)
trainer.eval_agent_loop_manager = SimpleNamespace(close=AsyncMock())
trainer.rl_health_manager = MagicMock()
trainer._exp_tracker = MagicMock()
fit_mock = AsyncMock if trainer_type is RLDisaggregatedTrainer else MagicMock
trainer._fit = fit_mock(side_effect=outcome)
with patch("xtuner.v1.train.rl_trainer.close_trace") as close_trace:
if outcome is not None:
with self.assertRaises(type(outcome)) as caught:
trainer.fit()
self.assertIs(caught.exception, outcome)
elif cleanup_fails:
with self.assertRaisesRegex(RuntimeError, "cleanup failed"):
trainer.fit()
else:
trainer.fit()
close_trace.assert_called_once()
trainer.agent_loop_manager.close.assert_awaited_once()
trainer.eval_agent_loop_manager.close.assert_awaited_once()
self.assertEqual(trainer.logger.opt.called, cleanup_fails)
trainer._exp_tracker.close.assert_called_once()
if trainer_type is RLColocateTrainer:
trainer.rl_health_manager.stop.assert_called_once()

def test_fit_propagates_eval_close_error_or_cancellation(self) -> None:
for trainer_type in (RLColocateTrainer, RLDisaggregatedTrainer):
for failure in (RuntimeError("eval cleanup failed"), asyncio.CancelledError()):
with self.subTest(trainer=trainer_type.__name__, failure=type(failure).__name__):
trainer = trainer_type.__new__(trainer_type)
trainer.logger = MagicMock()
trainer._enable_evaluate = True
trainer.agent_loop_manager = SimpleNamespace(close=AsyncMock())
trainer.eval_agent_loop_manager = SimpleNamespace(close=AsyncMock(side_effect=failure))
trainer.rl_health_manager = MagicMock()
trainer._exp_tracker = MagicMock()
fit_mock = AsyncMock if trainer_type is RLDisaggregatedTrainer else MagicMock
trainer._fit = fit_mock()
with patch("xtuner.v1.train.rl_trainer.close_trace") as close_trace:
with self.assertRaises(type(failure)) as caught:
trainer.fit()
# gather materializes a new CancelledError for a cancelled child.
if not isinstance(failure, asyncio.CancelledError):
self.assertIs(caught.exception, failure)
close_trace.assert_called_once()
trainer.agent_loop_manager.close.assert_awaited_once()
trainer.eval_agent_loop_manager.close.assert_awaited_once()
trainer._exp_tracker.close.assert_called_once()
if trainer_type is RLColocateTrainer:
trainer.rl_health_manager.stop.assert_called_once()

def test_fit_skips_eval_manager_when_evaluation_is_disabled(self):
trainer = RLDisaggregatedTrainer.__new__(RLDisaggregatedTrainer)
trainer._fit = AsyncMock()
trainer._exp_tracker = MagicMock()
trainer._enable_evaluate = False
trainer.agent_loop_manager = SimpleNamespace(close=AsyncMock())
with patch("xtuner.v1.train.rl_trainer.close_trace"):
trainer.fit()
trainer.agent_loop_manager.close.assert_awaited_once()
Loading
Loading