Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4910bea
fix(rollout): retry proxy admin connection timeouts
Nov 11, 2026
0d468e6
fix(rl): preserve global sampler identity and epoch on resume
Nov 11, 2026
17f33ad
fix(rl): release training batch references when fit fails
Nov 11, 2026
fb5c03f
feat(rl): preserve request provenance and shared routed-expert refere…
Nov 11, 2026
ff2ad68
feat(rollout): settle complete requests behind version publication ba…
Nov 11, 2026
edab2ea
feat(rollout): pin and retire external HTTP sessions with owned probes
Nov 11, 2026
e226e97
feat(rl): retain Agent tasks across colocated and disaggregated windows
Nov 11, 2026
f5ee2be
feat(rl): wire quiescent checkpoints and sealed cold publication
Nov 11, 2026
42bf4ca
feat(rl): reuse rollout and training debug phases for disaggregated runs
Nov 11, 2026
9b33e53
feat(rl): expose optional valid-attempt filtering and sandbox metadata
Nov 11, 2026
e42ad7b
test(rl): retain existing Agent lifecycle regressions and documentation
Nov 11, 2026
7e3bde2
[Fix] Recover run-owned sandboxes across task and training exits
Wuyh11 Nov 13, 2026
d6a0677
fix(rl): finalize run-owned sandboxes with bounded recovery
Wuyh11 Nov 15, 2026
5e91217
[Fix] Isolate sandbox trials and harden cleanup ownership
Wuyh11 Nov 17, 2026
e6d902e
fix(rl): preserve global sampler identity and epoch on resume
Nov 11, 2026
589fd88
fix(rl): release training batch references when fit fails
Nov 11, 2026
8aecc7c
feat(rl): preserve request provenance and shared routed-expert refere…
Nov 11, 2026
19a75fd
feat(rollout): settle complete requests behind version publication ba…
Nov 11, 2026
0e35a53
feat(rollout): pin and retire external HTTP sessions with owned probes
Nov 11, 2026
6444827
feat(rl): retain Agent tasks across colocated and disaggregated windows
Nov 11, 2026
6b6439f
feat(rl): wire quiescent checkpoints and sealed cold publication
Nov 11, 2026
42bd8b1
feat(rl): reuse rollout and training debug phases for disaggregated runs
Nov 11, 2026
af71c15
feat(rl): expose optional valid-attempt filtering and sandbox metadata
Nov 11, 2026
2c9ccbf
test(rl): retain existing Agent lifecycle regressions and documentation
Nov 11, 2026
9735a33
[Fix] Harden sandbox finalization and trial budget validation
Wuyh11 Nov 17, 2026
f755457
[Chore] Exclude sandbox cleanup test scripts from delivery
Wuyh11 Nov 17, 2026
912987f
[Fix] Align sandbox cleanup with the updated Agent RL stack
Wuyh11 Nov 17, 2026
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
52 changes: 52 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Sandbox cleanup domain

- **Isolated trial** keeps an entire infer/verify pipeline in one disposable
CPU process. Ray owns scheduling, model services and training trace objects.
The public `run_trial_process` interface takes declarative configuration,
confirms process exit and recovers only pre-allocation registered journals.
A private manifest atomically publishes one entry per journal; a partially
published entry cannot have allocated resources. Run shutdown still owns the
complete shared ledger scope if the parent disappears.
- **Creation permit channel** retains the actor's existing shared token bucket
across isolated processes. Request identities separate concurrent/cancelled
waiters; child disconnect settles actor-side permit requests. Model traffic
continues through the HTTP proxy and never crosses this channel.
- **Kernel ownership** uses protocol-marked Linux OFD record locks. Fresh
descriptors, fork closure and explicit guardian transfer preserve ownership.
Unknown historical lock namespaces fail closed. Local capability observation
and deployment-level cross-node exclusion are separate validation obligations.

- **SandboxPool** plans a trial's named dependency groups, checks health and runs
provisioners. Public phase release keeps the management transport available
for a later verifier; final close ends the trial's ownership.
- **Trial preparation** belongs to Runner: input validation and isolated Pool
overrides precede execution. Recipes may observe the prepared Pool, then use
Runner's standard execution without changing the task's overrides or copying
its merge and cancellation rules. Setup scopes close a prepared Pool when
execution has not started.
- **Trial execution** keeps stage orchestration in Runner and cleanup result
policy in its module's `_run_sandbox_trial` operation. The latter owns scope
entry/exit, cancellation, cleanup failures and the final receipt, preserving
the Runner's existing failure callback. Runner calls it once and logs only
after the receipt is published; timings are a per-call data record.
- **SandboxLifecycle** owns one Pool's resource-release obligations. It tracks
allocated IDs and clients, confirms deletion, seals the journal and hands off
unfinished cleanup. It also owns acquisition attempts, partial rollback and
the decision to retry. Pool supplies dependency/readiness work through a
per-attempt create capability. Release stops admission and drains acquisition
completion before sealing ownership or closing transport; a resistant create
retains the journal lease and transport for a later close attempt. Persistent
and in-process-only operation share this module.
A phase shares fixed deletion deadlines across its groups and drain-triggered
rollback; the phase deadline expires with that release operation. Independent
acquisition rollback uses its own existing budget, never an earlier phase's.
- **CleanupJournal** persists exact resource ownership and unresolved creation
intents under a kernel lease. A DELETE response alone is not deletion evidence.
Each concurrent request has an internal intent token; allocation/end resolve
only that request. Their aggregate retains the existing persistent `creating`
boolean, so older recovery readers still see an unresolved request.
- **Run cleanup** stops admission before task drain, then performs bounded exit
recovery. `run_control` owns configuration propagation and exit integration;
`recycler` freezes requests and ancestor budget ownership after an explicit
handoff. An exit batch seals its resource scope once, after stopping admission;
retries then use that immutable scope without renewing ancestor work.
48 changes: 48 additions & 0 deletions docs/en/rl/advanced_tutorial/agent_turn_lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Retaining Agents across weight updates (experimental)

Ordinary rollout pauses can cancel pending Agent executions. The opt-in complete-turn path keeps the native pending tasks, sessions and sandboxes alive between model requests. Training and weight transfer still wait for every admitted model request to settle. This is an experimental fixed-topology, non-streaming path, not a guarantee that an arbitrary external Agent can resume from a checkpoint.

## Ownership and publication

The producer's existing `_PendingTasks` owns each live Agent task. The replay buffer owns training admission and consumption. Disaggregated sampling uses the native persistent loop. Colocated sampling uses a dedicated `LoopThread` to keep tools and HTTP clients progressing while the trainer performs synchronous GPU work; it does not run GPU inference during training and does not introduce a second pending queue.

Publication order is: freeze worker recovery, seal every entrypoint, drain admitted model requests, pause inference, train/synchronize, install the new version at every sealed entrypoint, clear backend pause flags, then reopen. Forwarding must certify both backend completion and terminal trace recording. Unknown backend/trace outcomes prevent publication; HTTP cancellation alone is insufficient. Only recognized pre-generation context-limit rejection can settle without a generated training trace.

Version install, backend resume and reopen share one monotonic control deadline, using the configured freeze timeout. This budget does not include training or weight transfer. Multi-entrypoint reopen is not atomic; a partial or late RPC may open a ready entrypoint while the controller fails and retains the barrier. Gate, HTTP and Trial waiting budgets remain finite and must cover the intended training pause.

## Required configuration

Start from a working native trainer/runner configuration; these fields are additions, not a standalone runnable recipe.

| Scope | Configuration |
| --- | --- |
| Rollout | `turn_resume_wait_timeout` positive; `health_check_failure_threshold=0` (fixed topology) |
| Sandbox loop | `require_turn_provenance=True`; preserve real session/request IDs from the Agent client |
| Disaggregated manager | `turn_resume_drain_timeout` positive; `turn_resume_freeze_timeout` and `turn_resume_quiesce_timeout` explicit |
| Colocated manager | `turn_keepalive=True`; set `turn_keepalive_drain_timeout`, `turn_keepalive_freeze_timeout`, `turn_keepalive_quiesce_timeout` |
| Evaluation/partial rollout | All online evaluation entrypoints disabled; token partial rollout disabled |
| Optional affinity | `rollout_config.session_affinity=True` and sandbox `retire_route_on_completion=True` |

Gates and the corresponding manager must be enabled together. Unsupported custom disaggregated strategies are rejected at manager construction unless they implement the declared turn-resume/quiesce capability. Colocated keepalive requires the native asynchronous producer. Ordinary configurations leave these fields disabled and preserve the native failed-attempt filter: discard failed members of mixed training groups and retain successful members. `min_valid_attempts` is a separate explicit recipe policy, default `None`; it does not change evaluation.

A client must return the server's real request ID and session ID with each recorded model response. A locally invented request ID or model-step counter cannot certify provenance. The Lagent client integration targets `v1.0.0` (baseline `46e07b9f`) with the minimal request-ID and Mini-SWE adapter patch in [Lagent Draft #385](https://github.com/InternLM/lagent/pull/385). It does not require migrating Lagent main. Complete end-to-end validation remains pending. The XT request-gate and controlled forwarding interfaces can be reviewed independently of that cross-repository integration.

## Trace, routing and cleanup

Each admitted request fixes its model version. Trace export retains historical per-segment logprobs and routed experts, plus complete token versions including tool tokens. Sandbox conversion maps the complete response suffix into the native training fields. Supervised labels and generated-token accounting remain separate from complete-history provenance.

Affinity binds a session to one concrete DP entrypoint, not merely an EP group. The binding survives training pauses and fails closed if that backend disappears. Terminal success, failure or cancellation retires the binding; tombstones reject late requests and have a finite router capacity. There is no automatic POST retry or reassignment. Affinity does not make old-weight KV valid after a weight update. Trace references retire according to training ownership separately from session routing; completion must not free R3 storage still borrowed by training.

Checkpoint quiescence stops new groups and lets existing Agents finish while gates are still open, then seals/drains and saves. A checkpoint does not serialize live tools, sandboxes or client coroutine stacks. Cold restore starts with closed admission until restored weights and the actual saved version are ready. HF warm-start and DCP optimizer/sampler restore are distinct operations. For diagnostics, collect actual `debug_rollout_N.pt` files before using train-only replay; ordinary rollout JSONL is not replay PT data.

## Verification and remaining work

The tests cover request leases and unsafe settlement, real localhost forwarding, trace provenance/R3 ownership, sampler restore, retained task identity, persistent-loop startup/cleanup, concrete backend affinity and terminal retirement. Some tests stub model/backend/teacher imports and RPCs; they do not demonstrate full-model GPU execution, distributed recovery or learning.

The main-adapted path still needs real Agent tool progress through synchronous training, online publication across an optimizer update, HF/DCP loading and resource-cleanup checks. Historical experiment success and the historical context-limit failure are version-specific, not verification of this main adaptation. Keep the feature experimental until those checks and the remaining lifecycle design review are closed.

## Sources and scope

The admission-accounting concept references [matrix72c/sandbox_rl](https://github.com/matrix72c/sandbox_rl), `src/sandbox_rl/agents/request_gate.py` before commit `fd76fba`. The native implementation here uses condition-protected leases and explicit settlement/version publication rather than copying that HTTP gate's forwarding implementation. The inspected reference snapshot contains third-party Apache notices for listed XTuner-derived files, but no root license declaration for unrelated files; this is not presented as a blanket license grant for the reference repository. Maintainers should retain this provenance and resolve any further source-permission requirements before merging.

External frozen MTP configuration and transport are a separate change, [PR #2289](https://github.com/InternLM/xtuner/pull/2289); this lifecycle patch contains no frozen-source hook or LMDeploy modification. Generation-cancellation/resume, online MTP training, new sampling policy and performance claims are outside this change.
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 @@ -9,3 +9,4 @@ Reinforcement Learning
rl_trainer.md
loss.md
on_policy_distillation.md
agent_turn_lifecycle.md
1 change: 1 addition & 0 deletions docs/zh_cn/rl/advanced_tutorial/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@
loss.md
ppo.md
on_policy_distillation.md
sandbox_cleanup
Loading
Loading