Skip to content

[Fix] Add AgentLoop shutdown and pause/resume lifecycle hooks - #2135

Closed
matrix72c wants to merge 8 commits into
InternLM:mainfrom
matrix72c:feat/sandbox-environment-design
Closed

matrix72c wants to merge 8 commits into
InternLM:mainfrom
matrix72c:feat/sandbox-environment-design

Conversation

@matrix72c

@matrix72c matrix72c commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Resource-owning AgentLoops need explicit shutdown and pause/resume hooks. Otherwise background work and external clients can survive trainer exit, and a disaggregated producer blocked on generation can prevent shutdown.

Ray async concurrency groups also run on different event loops. Directly forwarding control RPCs to a loop that created generation tasks elsewhere can raise Future attached to a different loop during cancellation/draining. Moving control RPCs into the generate group instead would let saturated generation starve shutdown.

Change

  • Add async AgentLoop.close(), a no-op by default. Both RL trainers close training and evaluation managers on normal, error and cancelled exits. Managers forward hooks to local loops, Ray actors and router workers, and attempt every owner even if one fails. Close failures are logged; after otherwise successful training, the first close failure is raised. An existing training failure remains primary.
  • Cancel a disaggregated producer that is blocked on generation before closing owners. An idle producer still exits through its shutdown flag.
  • The built-in sandbox loop rejects new runs, cancels active runners and waits for their existing finally blocks to release pools.
  • Add no-op-by-default prepare_pause() and resume(). Managers drain before pause_generation() and resume after continue_generation(). A failed drain prevents inference abort.
  • Construct a remote AgentLoop on the event loop of its first async RPC and execute all underlying operations on that owner loop. Cross-loop calls use run_coroutine_threadsafe / wrap_future; same-loop calls await directly. Construction failures surface on the first RPC. No extra event-loop thread or generation-wide shield is added; local loops are unchanged.
  • Measure the complete manager pause phase once, including drain, inference pause and producer cleanup; do not also sum strategy-reported durations. Preserve disaggregated consume-and-clear behavior.

Contract: docs/en/rl/agent_loop_shutdown.md.

ProduceBatchResult impact: group_gen_pause_time_s now covers the complete pause phase. Status, reward and produced-work accounting are unchanged by this follow-up.

RoutedExperts impact: no change to object-reference transfer or ownership.

Ray concurrency impact: generation retains the named generate group; control RPCs retain the default group and dispatch directly onto the owner event loop without queuing for a generate slot.

Test Plan

Latest follow-up (2026-11-13)

Six focused CPU tests passed on this PR branch:

  • Both manager drain/pause ordering tests, now with controlled-clock assertions.
  • Existing colocated cleanup/timing aggregation test, ensuring elapsed time is not double-counted.
  • One real Ray actor test: occupy the sole generate slot, close from the control group, and verify task cleanup and constructor/generation/close loop identity. The pre-fix implementation reproduced the different-loop RuntimeError.
  • Existing actor shutdown delegation and first-RPC validity-binding tests.

Required pre-commit run --all-files executed: mypy passed on 409 source files and pydantic checks passed. Overall failure is confined to pre-existing formatting/import-order issues in six untouched autotest/ files; those automatic edits were discarded. All applicable changed-file pre-commit hooks pass.

Earlier validation reported 86 passing lifecycle/trainer/producer tests; that broader set was not rerun for this follow-up. The latest test deliberately uses real Ray but no model server, live sandbox deletion or GPU training. No throughput benchmark was run: this follow-up corrects loop ownership and pause accounting, without adding model passes or per-token RPCs. Target-environment validation and clean upstream CI remain outstanding.

@matrix72c
matrix72c force-pushed the feat/sandbox-environment-design branch from b08a5d5 to 2db9f71 Compare October 15, 2026 03:04
@matrix72c matrix72c changed the title [Docs] Propose sandbox agent loop environment interfaces [Refactor] Separate sandbox environment ownership from Runner execution Oct 15, 2026
@matrix72c
matrix72c marked this pull request as ready for review October 15, 2026 03:04
@matrix72c
matrix72c force-pushed the feat/sandbox-environment-design branch from 3225eaa to eee2016 Compare October 21, 2026 06:11
@matrix72c matrix72c changed the title [Refactor] Separate sandbox environment ownership from Runner execution [Fix] Close agent loops on RL trainer shutdown Oct 21, 2026
Agent loops that serve an external harness need to stop admitting model
calls before the manager aborts inference, and reopen admission after it
resumes; otherwise the abort cuts requests the harness is still waiting on.

Add optional prepare_pause/resume hooks to AgentLoop, RouterAgentLoop and
AgentLoopActor, and call them around pause_generation/continue_generation in
both the colocated and disaggregated managers. A failed drain now prevents
the global abort. Generalize the close helper into call_agent_loop_hook.
@matrix72c matrix72c changed the title [Fix] Close agent loops on RL trainer shutdown [Fix] Add AgentLoop shutdown and pause/resume lifecycle hooks Oct 26, 2026
Drop the cancellation-proof cleanup helpers and the error-chaining
machinery. The trainer closes managers through asyncio_run, which never
cancels the cleanup, so await_cleanup, gather_cleanup and CleanupError
guarded a path that does not occur. Close failures are now logged and no
longer replace the training result.

Also remove id()-based owner dedup and the optional-hook getattr guard,
which cannot trigger, keep a single closing check in the sandbox loop,
shrink the lifecycle doc to the extension contract, and revert
formatting changes to untouched test lines.
@matrix72c

Copy link
Copy Markdown
Contributor Author

2026-11-09 new-main compatibility check

Validated this PR independently against fixed upstream main d841a3feeba4565054ad773fce5335a4734def88, using PR head c791a1e7c1ca3631b18d3cd1329aafae7b72174d. The PR head/history remains unchanged; the test-only local composition commit was 0f0199d9e051c0ab9d1378c4eacd1f149bdfed89 (not another topic or the final integration).

Focused targets:

  • tests/rl/test_agent_loop_shutdown.py
  • tests/rl/test_multi_task_agent_loop_manager.py

Result: 24 passed, pytest exit 0. Python 3.12.12, Torch 2.10.0, Ray 2.56.1, Transformers 5.17.0, existing LMDeploy 0.18.0 environment. This does not validate main's all-extra Ray 2.58.0 environment.

ProduceBatchResult impact: this validation checks shutdown and pause/resume lifecycle behavior; no new changes to status, reward totals, counters or timing aggregation in this refresh. Ray concurrency impact: lifecycle behavior is tested locally, not under saturated cluster dispatch.

These are targeted CPU/local-runtime checks, not a full-suite, GPU/PPO performance or CI-green claim. The unit-test check for this head was cancelled at the status inspection; cancellation is not a pass. Existing draft/readiness status is unchanged.

@matrix72c

Copy link
Copy Markdown
Contributor Author

Closing: trainer-exit cancellation and cleanup of running Agents are now covered on main by #2297 (manager.close() awaited via await_owned_operation, with produce strategies owning retained-Agent lifecycle). The cross-loop failure described here has no trigger path on current main, where AgentLoop.pause only forwards pause_generation. The remaining AgentLoop-level close/prepare_pause/resume hooks would be a new feature and should be discussed against the new strategy-owned lifecycle if needed.

@matrix72c matrix72c closed this Nov 23, 2026
@matrix72c
matrix72c deleted the feat/sandbox-environment-design branch November 23, 2026 03:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant