Skip to content

[rl] Cancel a rollout group on its worker - #5507

Draft
felipemello1 wants to merge 1 commit into
felipemello1/parked-rollout-worker-basefrom
felipemello1/http/4-cancel-group
Draft

felipemello1 wants to merge 1 commit into
felipemello1/parked-rollout-worker-basefrom
felipemello1/http/4-cancel-group

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Tabled until Monarch issue 5301 is fixed and a cancel is needed (outside shutdown, or a measured slowdown of the validation after training). Out of the stack; its base is felipemello1/parked-rollout-worker-base, a frozen copy of the stack up to "Rollouter: keep one handle per rollout worker" in its earlier order (Verifiers 0.4.0, with the row-0 router copy). Don't merge it: port it onto main when it is unparked. Delete that branch once #5507 and #5512 are both ported or closed. TODO for that port: past Verifiers 0.4.1, the test's fake _GeneratingWorker needs an async def close(). Without it, mesh.stop() fails that actor, Monarch sends SIGINT, and pytest stops after about 500 tests with no failure line.

TLDR: When training ends, the controller cancels the rollout groups still running. Monarch never passes that cancel to the rollout worker, so today the group keeps running turns until Controller.close. This PR stops a cancelled group on its worker, then releases it. Key fact: main's Rollouter.close is safe only because run_group ends after its generators answered all its generate calls. A cancel breaks that, so each worker now keeps its unanswered calls, and close waits for them.

end of training; group 7 is mid-turn on worker B
main                                      this PR
the loop's await raises CancelledError    cancel_group(7) to B, wait <= 30 s: B stops group 7
  at once; release_groups([7]) skipped      (sessions released, envs closed), then release_groups([7])
B keeps going: env step, generate, ...    no new turns; a call already sent decodes to its end
Controller.close: ~40-line traceback      Controller.close: that call fails fast; Rollouter.close
  per leftover rollout                      waits for its answer, then stops the workers

Problem

  1. Rollouter.run_group_rollouts sends each group to one rollout worker (run_group.call_one on a random worker's handle). The cancel from Controller.run stays local, so the remote run_group keeps going.
  2. Multi-turn recipes that validate after training (alphabet_sort, search_r1) run leftover turns during it. At Controller.close, each leftover rollout logs a ~40-line traceback.
  3. The cancel also skips release_groups: one cache-salt entry per group, plus held KV only with session_kv_holder, which no recipe sets.

Solution

cancel_group returned              the group's work and cleanup ended
wait_for_generate_calls returned   the worker got every generate answer owed to it
  1. RolloutWorkerActor.cancel_group(group_id) cancels the group's task and returns once its cleanup ran.
  2. A cancelled run_group_rollouts sends it only to the worker that runs the group. It waits at most 30 s, logs an error instead of raising it, then re-raises the cancel.
  3. release_groups and each rollout's session release move into finally blocks.
  4. Each worker keeps its generate calls until answered. Rollouter.close waits for them on every worker, then stops the workers. An answer that reaches a stopped worker fails the actor that sends it, a generator with look-aside routing: the job exits 130 (an open Monarch issue). A dead worker's error is logged with its traceback.

Results

Numerics: unchanged by construction (only shutdown cancels). Not run on GPU.
Shutdown probe, Monarch 0.7.0, CPU: real Rollouter and worker, a stand-in router holding 200 calls;
cancel the group, close the router, then Rollouter.close:
  without wait_for_generate_calls   2 of 2 runs crash: "undeliverable message for router.generate()"
  this PR                           2 of 2 runs end cleanly; the router answered 200 of 200

The probe predates look-aside routing (row 0 of the stack): its stand-in router plays the part a generator plays now. The race is the same; only the actor that fails changes.

The shutdown probe (save as probe_shutdown.py in the repo root)
setsid --wait python probe_shutdown.py untracked 10   # without the wait: exit 130
setsid --wait python probe_shutdown.py tracked 10     # this PR: exit 0
"""Shutdown probe: does Rollouter.close crash the job when a cancelled group left generate calls unanswered?

A stand-in router holds 200 generate calls from one group on a real RolloutWorkerActor. The group is
cancelled, the router is closed (its calls fail fast), then Rollouter.close runs (Controller.close's order).
    tracked     Rollouter.close as in this PR
    untracked   the same, but the worker's wait_for_generate_calls returns at once
Exit 130: Monarch failed the router ("undeliverable message"). Exit 0: clean.

Run from the repo root. Start it with setsid: the crash kills its process group.
    setsid --wait python probe_shutdown.py tracked 10    # or untracked; 10 = seconds to wait after close
"""
import asyncio, functools, sys, time
from types import SimpleNamespace
import cloudpickle
from monarch.actor import Actor, concurrent_endpoint, this_host
from torchtitan.rl.actors.monarch.rollout_worker import RolloutWorkerActor
from torchtitan.rl.rollout import rollouter as rollouter_module
from torchtitan.rl.rollout.rollouter import Rollouter
from torchtitan.rl.rollout.types import RolloutGroup

NUM_CALLS = 200

class FakeRouter(Actor):
    def __init__(self):
        self.received = 0
        self.answered = 0
        self.closed = asyncio.Event()
    @concurrent_endpoint
    async def generate(self, i: int) -> int:
        self.received += 1
        await asyncio.wait_for(self.closed.wait(), timeout=30)
        self.answered += 1
        raise RuntimeError("generator closed")
    @concurrent_endpoint
    async def close_generators(self) -> None:
        self.closed.set()
    @concurrent_endpoint
    async def received_count(self) -> int:
        return self.received
    @concurrent_endpoint
    async def answered_count(self) -> int:
        return self.answered

async def _generate(router, i):
    try:
        return await router.generate.call_one(i)
    except BaseException as error:
        if i == 0:
            print(f"worker: generate 0 raised {type(error).__name__}: {str(error)[:300]}", flush=True)
        raise

class FakeWorker:
    async def run_group(self, *, generate_fn, group_id, **kwargs):
        print("worker: run_group started", flush=True)
        await asyncio.gather(*(generate_fn(i) for i in range(NUM_CALLS)))
        return RolloutGroup(group_id=group_id, rollouts=[])

class FakeWorkerConfig:
    def build(self):
        return FakeWorker()

async def main(mode):
    cloudpickle.register_pickle_by_value(sys.modules[__name__])
    router_mesh = this_host().spawn_procs(per_host={"cpus": 1})
    router = router_mesh.spawn("router", FakeRouter)
    worker_mesh = this_host().spawn_procs(per_host={"cpus": 1})
    workers = worker_mesh.spawn("rollout_worker", RolloutWorkerActor, worker_config=FakeWorkerConfig(),
                                num_threads=1, structured_logger_init_fn=None)
    worker = workers.flatten("rank").slice(rank=0)
    rollouter = object.__new__(Rollouter)
    rollouter._workers = [worker]
    rollouter._inflight_run_group_calls = set()
    async def stop_rollout_workers():
        await worker_mesh.stop()
    rollouter._actor_system = SimpleNamespace(stop_rollout_workers=stop_rollout_workers)
    if mode == "untracked":
        async def no_wait():
            return None
        worker_proxy = SimpleNamespace(cancel_group=worker.cancel_group,
                                       wait_for_generate_calls=SimpleNamespace(call_one=no_wait))
    dispatch = asyncio.ensure_future(rollouter.run_group_rollouts(
        generate_fn=functools.partial(_generate, router), release_session_fn=None, sample=None,
        group_id=7, group_size=1, sampling=None))
    while await router.received_count.call_one() < NUM_CALLS:
        await asyncio.sleep(0.05)
    print(f'router answered {await router.answered_count.call_one()} before the cancel', flush=True)
    t0 = time.monotonic()
    dispatch.cancel()
    await asyncio.gather(dispatch, return_exceptions=True)
    print(f"{mode}: group cancelled in {time.monotonic() - t0:.2f} s", flush=True)
    if mode == "untracked":
        rollouter._workers = [worker_proxy]
    # Controller.close's order: close the generators (pending calls fail fast), then Rollouter.close.
    await router.close_generators.call_one()
    t0 = time.monotonic()
    await rollouter.close()
    print(f"{mode}: Rollouter.close took {time.monotonic() - t0:.2f} s", flush=True)
    await asyncio.sleep(float(sys.argv[2]))
    print(f"{mode}: router answered {await router.answered_count.call_one()} of {NUM_CALLS}", flush=True)
    await router_mesh.stop()
    print(f"{mode}: done", flush=True)

asyncio.run(main(sys.argv[1]))

You may ask:

  • Why wait for cancel_group? The caller releases the group next; a rollout still running could pin it again.
  • Why not let the groups finish? Their results are dropped, and the validation after training would wait for the slowest.

NOTE:

  • Verifiers groups run in rollout workers here ("Run Verifiers groups in rollout workers" is below), so a cancel stops them on their worker too. The worker's GenerationServer calls go through the tracked generate_fn, so close also waits for a call the agent gave up on. VerifiersRollouter.close then stops the env server first: every group is done or cancelled by then, so none waits on it. A call the GenerationServer starts after wait_for_generate_calls began isn't awaited (TODO there).
  • Look-aside's TODO in _make_generate_fn (a cancelled caller releases its router reservation while the generator still runs the call) doesn't apply: the worker shields each tracked call, so the call, and its release, end only when the generator answers.
  • A call sent before the cancel can pin its group's cache salt again. TODO in rollout_worker.py: abort the request on the generator.
  • engine_loop.py gets only a TODO: a release can now run before its own queued call is admitted.

Test plan

pytest tests/rl/unit_tests/cpu   # Verifiers 0.4.0: 711 passed, 1 skipped

Each new test fails when its piece is removed. One uses real Monarch CPU processes.

@felipemello1
felipemello1 added this pull request to stack #5508 October 18, 2026 22:49
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 18, 2026
@felipemello1
felipemello1 removed this pull request from stack #5508 October 18, 2026 23:25
@felipemello1
felipemello1 force-pushed the felipemello1/http/3-generate-over-http branch from 66f7d01 to 15817d3 Compare October 18, 2026 23:31
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 5d54c9e to 2461a1e Compare October 18, 2026 23:31
@felipemello1
felipemello1 changed the base branch from felipemello1/http/3-generate-over-http to felipemello1/http/5-abort-when-caller-left October 18, 2026 23:31
@felipemello1
felipemello1 added this pull request to stack #5513 October 18, 2026 23:32
@felipemello1
felipemello1 force-pushed the felipemello1/http/5-abort-when-caller-left branch from e1ce3b5 to 18f4e80 Compare October 19, 2026 00:38
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 2461a1e to 3a790cd Compare October 19, 2026 00:38
@felipemello1
felipemello1 force-pushed the felipemello1/http/5-abort-when-caller-left branch from 18f4e80 to 3cd6910 Compare October 19, 2026 01:16
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 3a790cd to 3fb646d Compare October 19, 2026 01:16
@felipemello1 felipemello1 changed the title [rl] Cancel a rollout group on its worker [rl] Cancel a rollout group on its worker (11/14) Oct 19, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 3fb646d to 8659d82 Compare October 22, 2026 23:31
@felipemello1
felipemello1 force-pushed the felipemello1/http/5-abort-when-caller-left branch from feaee20 to 115c064 Compare October 23, 2026 07:34
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 8659d82 to addb7b0 Compare October 23, 2026 07:34
@felipemello1
felipemello1 removed this pull request from stack #5513 October 27, 2026 14:27
@felipemello1
felipemello1 force-pushed the felipemello1/http/5-abort-when-caller-left branch from 115c064 to 6c784be Compare October 27, 2026 14:31
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from addb7b0 to f2a0101 Compare October 27, 2026 14:31
@felipemello1 felipemello1 changed the title [rl] Cancel a rollout group on its worker (11/14) [rl] Cancel a rollout group on its worker (12/14) Oct 27, 2026
@felipemello1
felipemello1 added this pull request to stack #5639 October 27, 2026 14:33
@felipemello1
felipemello1 force-pushed the felipemello1/http/5-abort-when-caller-left branch from 6c784be to 4d94d82 Compare November 5, 2026 00:38
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from f2a0101 to 3983136 Compare November 5, 2026 00:38
@felipemello1
felipemello1 removed this pull request from stack #5639 November 5, 2026 07:53
@felipemello1
felipemello1 changed the base branch from felipemello1/http/5-abort-when-caller-left to felipemello1/rollout-error-system November 5, 2026 07:53
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 285df2e to dec98f6 Compare November 5, 2026 07:53
@felipemello1
felipemello1 added this pull request to stack #5857 November 5, 2026 07:54
@felipemello1 felipemello1 changed the title [rl] Cancel a rollout group on its worker (12/14) [rl] Cancel a rollout group on its worker (8/10) Nov 5, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review. This PR was re-cut onto PR 7: it no longer depends on the HTTP generation PRs, so the code and the body changed.

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 15s —— View job


Approve -- please address the items below before merging (empty human-written summary, upstream issue links for the two TODO(monarch) workarounds): review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. At this head I found no new problems, and every review thread from the last round is handled in code or answered. The same two small items are still open. This PR touches controller.py and engine_loop.py, so a maintainer still needs to review it.

What this PR does. When the controller cancels a _rollout_loop or a validation at shutdown, Rollouter.run_group_rollouts sends cancel_group(group_id) to every rollout worker. It waits at most _SHUTDOWN_DRAIN_TIMEOUT_S, then re-raises the cancel. The worker that owns the group cancels its run_group task. Each rollout releases its routing session in a finally, and the controller calls release_groups in a finally. Each worker tracks the generate calls the router hasn't answered yet. Rollouter.close waits for them under the same deadline, then stops the workers in a finally.

Example.

shutdown, multi-turn recipe, group 3 mid-turn on worker B
before: the controller's await returns; B keeps running env steps and generate calls
        through post-training validation; release_groups([3]) is skipped, so the salts stay
after:  cancel_group(3) goes to A, B and C. A and C return at once. B cancels the task,
        each rollout releases its session, the env closes.
        The controller's finally runs release_groups([3]); the CancelledError propagates.
        B's generate call is still tracked; Rollouter.close waits for its reply, then stops B.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.
  2. torchtitan/rl/rollout/rollouter.py:288 and torchtitan/rl/actors/monarch/rollout_worker.py:74: neither TODO(monarch) has an upstream issue link yet. File the two drafted Monarch issues and link them, the way rdma_microbatch.py links monarch#5049. The cancel issue should also cover what cancel_group relies on: Monarch starts one sender's concurrent-endpoint calls in the order they were sent.
Details
  • Last round's threads, checked at HEAD:
    • Shutdown constant: kept, with a shorter comment. It is the only shutdown or drain timeout in torchtitan/rl, so it already is the one central place.
    • close docstring: now written as numbered steps.
    • worker_actors is None: a one-line comment now says why (setup failed before it spawned the pool).
    • The broad except in close: narrowed to TimeoutError, and the stop moved into a finally. A dead worker's error now reaches Controller.close. The new parametrized test covers both cases.
    • The broad except around cancel_group (rollouter.py:687): now has a comment that says why it stays broad.
    • The gather comment and the release try/except comment: both rewritten. The "Also on a cancel" line is gone.
  • Verifiers rollouter (examples/verifiers/rollouter.py:241): it doesn't override close's worker path, and its groups run in the controller. A cancel reaches its gather directly, and the controller's finally releases the group. Nothing to change here.
  • Stale references: none. No _RUN_GROUP_DRAIN_TIMEOUT_S is left in the repo.
  • Deadline in close: if the run_group drain uses the whole 30 s, timeout_at(deadline) times out at once. That is logged, and the workers still stop. This is intended.

Not verified: that Monarch starts one sender's concurrent-endpoint calls in order (only the CPU real-process test covers it). No GPU run at this head.

@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 55d19be to 6fb7960 Compare November 10, 2026 22:41
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. The 3 shutdown blocks (cancel path, routing-session release, close) are rewritten at 6fb7960: one helper, _best_effort, for the first two, and one shared timeout in close.

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 7s —— View job


Approve -- please address the items below before merging. I found no correctness problems in the rewritten shutdown blocks; the empty human-written summary and the TODO(monarch) issue links are still open: review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. I found no correctness problems in the three rewritten shutdown blocks at 6fb7960. The two items from earlier reviews are still open. This PR touches controller.py and engine_loop.py, so a maintainer still needs to review it.

What changed at this head. Two paths now share one module-private context manager, _best_effort: the cancel path in run_group_rollouts, and the routing-session release in _run_single_rollout's finally. It logs any Exception, including a timeout, with its traceback, and lets a CancelledError propagate. close now puts both drains under one asyncio.timeout. When the deadline passes, the gather cancels the run_group calls still running. The workers stop in the finally, also when close is cancelled.

Example.

close(), deadline 30 s, group 3's run_group still running on worker B
  t=0    gather(call_3) ......................... still waiting at 30 s
  t=30   the timeout cancels the gather -> call_3 cancelled -> TimeoutError
         -> warning "(1 run_group calls cancelled)" -> finally: stop_rollout_workers()
same, but call_3 ends at t=1 and B's last generate call never gets a reply
  t=1    wait_for_generate_calls.call() ......... still waiting at 30 s
  t=30   TimeoutError -> warning "(0 run_group calls cancelled)" -> stop_rollout_workers()
B died:  wait_for_generate_calls raises ActorError -> finally stops the pool -> Controller.close logs it

Must fix (still open)

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.
  2. torchtitan/rl/rollout/rollouter.py:284 and torchtitan/rl/actors/monarch/rollout_worker.py:74: neither TODO(monarch) has an upstream issue link yet. Link the two drafted Monarch issues once they are filed. The cancel issue should also cover what cancel_group relies on: Monarch starts one sender's concurrent-endpoint calls in the order they were sent.

Should consider

  • torchtitan/rl/rollout/rollouter.py:634 -- _best_effort(timeout_s=...) has a single consumer. Stacking asyncio.timeout at that call site would drop the parameter (inline comment).
Details
  • _best_effort inside except CancelledError: the task has cancelling() == 1 when it enters. When the timeout fires, asyncio.timeout cancels the task (count 2) and calls uncancel() on exit (back to 1). That is <= the count it recorded on entry, so it raises TimeoutError. That error is an Exception, so it is logged, and the bare raise then re-raises the original cancel. A second external cancel is a BaseException, so it skips the except and propagates. Both cases are correct.
  • _best_effort in the rollout finally: asyncio.timeout(None) never expires, as token_env.py:217 already relies on. The release still awaits correctly after the task's cancel was delivered, and the CancelledError re-raises after the block. A finished rollout whose release fails stays a finished rollout.
  • The single deadline in close: with return_exceptions=True, a cancelled gather cancels its children and finishes only once they are done. So sum(call.cancelled() ...) in the warning is read after every call has settled. This matches the earlier behavior: cancel the calls still pending, then gather them. A timeout that fires during the run_group drain skips wait_for_generate_calls, which is correct because the deadline has already passed.
  • A late caller of a call that close cancelled: its shield raises CancelledError, so it goes into the cancel path and calls cancel_group on a pool that is stopping. _best_effort logs that error. At this point Controller.run has already cancelled and gathered its loops and validations, so this only produces log noise.
  • Helper placement: the helper is private, it lives in the module of both its callers, and net LoC barely changes. This answers the maintainer's "should this be a util?" without adding a shared module.

Not verified: that Monarch starts one sender's concurrent-endpoint calls in order (only the CPU real-process test covers it). No GPU run at this head.

Comment thread torchtitan/rl/rollout/rollouter.py Outdated
Comment on lines +634 to +649
async def _best_effort(
failure_message: str, *message_args: object, timeout_s: float | None = None
) -> AsyncIterator[None]:
"""Run the block. Log any `Exception` with its traceback, also a timeout after `timeout_s`, and go on.

async with _best_effort("cancel_group(%d) failed", 7, timeout_s=30):
await cancel_group(7) # raises, or hangs past 30 s -> logged, not raised
# timeout_s=None (the default): no time limit

A cancel of the caller still propagates.
"""
try:
async with asyncio.timeout(timeout_s):
yield
except Exception:
logger.exception(failure_message, *message_args)

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.

Should consider: timeout_s has one consumer (the cancel_group call at line 285). The helper could just log and swallow Exception, and that call site could stack the timeout on top:

async with _best_effort("cancel_group(%d) failed; the group may keep running", group_id), \
        asyncio.timeout(_SHUTDOWN_DRAIN_TIMEOUT_S):
    await worker_actors.cancel_group.call(group_id)

asyncio.timeout is the inner manager, so its TimeoutError reaches _best_effort's except Exception and gets logged, which is what happens now. This drops the keyword and the third line of the docstring example, and _best_effort then does one thing. The behavior is the same either way, so this is optional.

@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from 6fb7960 to f5e1684 Compare November 11, 2026 01:38
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review (f5e1684: _best_effort renamed _suppress_and_log, comments cut to 3 lines or fewer, the cancel TODO replaced by a note that Monarch never forwards a cancel by design, the tracking TODO links the Monarch issue).

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 39s —— View job


Approve -- please address the item below before merging. The TODO(monarch) links are now resolved; the human-written summary is still empty: review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the item below before merging. At f5e1684, one of the two open items is resolved, and I found no new problems in this push. This PR touches controller.py and engine_loop.py, so a maintainer still needs to review it.

What this PR does. When the controller cancels a _rollout_loop or a validation at shutdown, Rollouter.run_group_rollouts sends cancel_group(group_id) to every rollout worker. It waits at most _SHUTDOWN_DRAIN_TIMEOUT_S (errors and timeouts go to the log through _suppress_and_log), then re-raises the cancel. The worker that owns the group cancels its run_group task. Each rollout releases its routing session in a finally, and the controller calls release_groups in a finally. Each worker tracks the generate calls the router hasn't answered yet. Rollouter.close waits for them under the same deadline, then stops the workers in a finally.

Example.

shutdown, multi-turn recipe, group 3 mid-turn on worker B
before: the controller's await returns; B keeps running env steps and generate calls
        through post-training validation; release_groups([3]) is skipped, so the salts stay
after:  cancel_group(3) goes to A, B and C. A and C return at once. B cancels the task,
        each rollout releases its session, the env closes.
        The controller's finally runs release_groups([3]); the CancelledError propagates.
        B's generate call is still tracked; Rollouter.close waits for its reply, then stops B.

Must fix (still open)

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.

Resolved since the last review:

  • TODO(monarch) links. rollout_worker.py now links meta-pytorch/monarch#5249, which is open and matches the comment: an InvalidReference reply skips _handle_undeliverable_message and fails the sender. The cancel path no longer has a TODO. Instead it cites Monarch's actor docs, which say that dropping a call's Future doesn't cancel the request. That is intended behavior, not an upstream gap, so a note is the right form and no issue link is needed.
Details
  • Re-checked at HEAD:
    • _suppress_and_log at both call sites. Inside except CancelledError, a timeout becomes TimeoutError, which is logged, and the bare raise re-raises the original cancel. In the rollout finally, timeout_s=None means no limit.
    • The close deadline, its finally stop, and its single read of _worker_actors.
    • The controller finally blocks in _rollout_loop and _collect_validation_rollouts.
  • Comment accuracy:
    • The release comment says a raised error "would turn this rollout into ERROR_INFRA". That is correct: the error would leave _run_single_rollout, and make_scored_group turns a sibling that raised into ERROR_INFRA (rollouter.py:482).
    • Deleting main's shutdown-traceback TODO is justified. Controller.run cancels the loops before close, so at shutdown a rollout still generating now ends with CancelledError, which skips except Exception. It no longer ends as ERROR_INFRA with a remote traceback.
  • Earlier should-consider (timeout_s has one consumer): kept by the author. The docstring is now two lines, so it's not worth another round.
  • In-order start of concurrent endpoints: cancel_group relies on Monarch starting one sender's concurrent-endpoint calls in the order they were sent. Monarch doesn't document this and no issue tracks it. The real-process CPU test test_cancel_group_and_wait_for_generate_calls_on_real_worker_processes would fail if it changed, so a CI guard exists.

Not verified: that Monarch starts one sender's concurrent-endpoint calls in order (only the CPU real-process test covers it). No GPU run at this head.

@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch 2 times, most recently from 21f6ee2 to c67edf2 Compare November 11, 2026 02:03
@felipemello1
felipemello1 force-pushed the felipemello1/rollout-error-system branch from 5fa84c6 to 198d9eb Compare November 11, 2026 03:31
@felipemello1
felipemello1 force-pushed the felipemello1/http/4-cancel-group branch from c67edf2 to 74a1555 Compare November 11, 2026 03:31
@felipemello1
felipemello1 marked this pull request as ready for review November 11, 2026 03:32
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. This push rebuilds the PR on "Rollouter: keep one handle per rollout worker", which now sits below it:

  • A cancelled run_group_rollouts sends cancel_group only to the worker that runs the group (call_one on its handle), waits at most _SHUTDOWN_DRAIN_TIMEOUT_S, then re-raises the cancel.
  • Each worker keeps its unanswered generate calls. Rollouter.close waits for them on every worker (wait_for_generate_calls), then stops the workers. A dead worker's error is logged with its traceback, and the others still wait.
  • The shutdown probe is in the body, under a collapsed block. Without the wait, 2 of 2 runs exit 130. With it, 2 of 2 end cleanly.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 5s —— View job


Approve -- please address the item below before merging. The human-written summary is still empty; one should-consider on close's handling of a worker whose call fails when sent: review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the item below before merging. The rebuild on PR 2's per-worker handles makes the cancel path smaller and correct: cancel_group now goes only to the worker that runs the group. I found no correctness problems in this push. This PR touches controller.py and engine_loop.py, so a maintainer still needs to review it.

What this PR does. run_group_rollouts keeps the worker handle it picked. When its caller is cancelled, it sends worker.cancel_group.call_one(group_id), waits up to _SHUTDOWN_DRAIN_TIMEOUT_S (an error or a timeout is only logged), then re-raises the cancel. On the worker, every generate call is shielded and stays in _generate_calls until the router answers it. Rollouter.close waits under one deadline for the in-flight run_group calls, then for wait_for_generate_calls on every worker, and stops the pool in a finally. The controller's release_groups and each rollout's session release now run in finally blocks.

Example.

shutdown; group 7 runs on worker B (of A, B, C), mid-turn with generate call c in flight
base:  the loop's await raises CancelledError; B keeps running turns; release_groups([7]) skipped
now:   cancel_group(7) -> B only; B cancels the task, rollouts release sessions, env closes
       controller finally: release_groups([7]); CancelledError propagates
       Controller.close: generators close -> c fails fast -> B reads its answer
       Rollouter.close: run_group calls done -> wait_for_generate_calls on A, B, C -> stop

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.

Should consider

  • torchtitan/rl/rollout/rollouter.py:217 -- if a worker's call_one() raises on send, that error skips return_exceptions. Then the other workers aren't waited on, which contradicts the close docstring, and a test locks that behavior in (inline comment).
Details
  • Checked at HEAD against the new base:
    • The cancel path uses the local worker, not self._workers, so it doesn't race close clearing the list.
    • The examples/verifiers/rollouter.py close override doesn't touch the worker pool. Its groups run in the controller, so only the controller finally applies there, as the body says.
    • No _RUN_GROUP_DRAIN_TIMEOUT_S is left anywhere.
  • Shield on the worker's generate calls: in normal training nothing cancels a rollout while it is generating. TokenEnv.step_timeout_s only wraps MessageEnv.step, so the shield adds only a future and a callback per call on the main path.
  • _group_tasks keyed by group id: each group now runs on exactly one worker, and training and validation ids don't overlap (training ids are >= 0, validation ids are negative). So a del in one group's finally can't remove another group's entry.
  • Timeout inside close: if the run_group drain uses up the deadline, the gather cancels the shielded calls that are still running, and wait_for_generate_calls is skipped. The warning is logged and the finally stops the pool. This is intended.
  • Earlier threads: the maintainer threads on the constant, the close docstring, the None guard, the broad excepts, the gather comment, and the per-rollout release are all handled at HEAD or answered in the replies. Monarch issue 5249 is linked.

Not verified: whether Monarch's call_one can raise on send for a dead or stopped mesh. Also that Monarch starts one sender's concurrent-endpoint calls in order; only the CPU real-process test covers that. No GPU run at this head.

# return_exceptions: a failed group or a dead worker must not end the wait for the others.
await asyncio.gather(*calls, return_exceptions=True)
results = await asyncio.gather(
*(worker.wait_for_generate_calls.call_one() for worker in workers),

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.

Should consider: return_exceptions=True only catches errors raised while a call is awaited. If one worker's call_one() raises when it is sent, the generator expression raises before gather starts. Then no other worker is waited on, nothing is logged here, and the error leaves close. The docstring says the opposite: "A dead worker's error is logged with its traceback; the other workers still wait." test_close_stops_the_workers_when_wait_for_generate_calls_raises_when_sent locks in that mismatch (it expects close to raise).

I couldn't check whether Monarch's call_one raises on send for a dead or stopped mesh. If it can, one small fix is to send each call from inside a coroutine, so both kinds of failure go through return_exceptions:

async def _wait_for_generate_calls(worker) -> None:
    await worker.wait_for_generate_calls.call_one()
...
results = await asyncio.gather(
    *(_wait_for_generate_calls(worker) for worker in workers),
    return_exceptions=True,
)

After that, the "raises when sent" test is covered by test_close_waits_for_the_live_workers_when_one_worker_is_dead and can be deleted. If Monarch never raises on send, delete the test anyway: it guards a path that can't happen.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Deleted the test in 7423b81, and kept the code as is.

On Monarch 0.7.0, a call_one to a dead worker doesn't raise when sent. We ran two worker processes and stopped one. The dead worker's future failed at once with Monarch's SupervisionError (a RuntimeError), and the live worker still answered. So return_exceptions=True catches it, close logs it, and the other workers still wait. test_close_waits_for_the_live_workers_when_one_worker_is_dead covers that branch.

With the test gone, no test checked that close stops the workers in its finally. I added test_close_stops_the_workers_when_close_is_cancelled. It fails when the stop moves out of the finally.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. This push replays the PR onto main. It deletes the send-time-raise test (see the inline reply) and adds test_close_stops_the_workers_when_close_is_cancelled.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 5s —— View job


Approve -- please address the item below before merging. The last should-consider is resolved and I found no new problems at 7423b81; the human-written summary is still empty: review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the item below before merging. At 7423b81 the last should-consider is resolved and I found no new problems. This PR touches controller.py and engine_loop.py, so a maintainer still needs to review it.

What changed since the last review.

  • test_close_stops_the_workers_when_wait_for_generate_calls_raises_when_sent is deleted. The author checked on Monarch 0.7.0 that a call_one to a dead worker doesn't raise when it is sent: its future fails with SupervisionError, and return_exceptions=True catches that. So the path the test guarded can't happen, and test_close_waits_for_the_live_workers_when_one_worker_is_dead covers the branch that can.
  • test_close_stops_the_workers_when_close_is_cancelled is new. It is the only guard that the stop in close stays in the finally. If the stop moved after the try, a cancel of close would skip it and the test would fail.

Example.

shutdown; group 7 runs on worker B (of A, B, C), mid-turn, with generate call c in flight
base:  the loop's await raises CancelledError; B keeps running turns; release_groups([7]) is skipped
now:   cancel_group(7) goes to B only; B cancels the task, the rollouts release their sessions, the env closes
       controller finally: release_groups([7]); CancelledError propagates
       Controller.close: generators close -> c fails fast -> B reads its answer
       Rollouter.close: run_group calls done -> wait_for_generate_calls on A, B, C -> stop (in finally)

Must fix (still open)

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.
Details
  • close cancelled mid-wait: the CancelledError isn't a TimeoutError (the deadline didn't fire), so it skips the except and reaches the finally, which stops the pool. results is read only when the async with exits normally, so a timeout or a cancel never reads it unbound.
  • The cancel path at HEAD (rollouter.py:299-310): it uses the local worker, so it doesn't race close clearing self._workers. asyncio.timeout is the inner manager, so its TimeoutError reaches _suppress_and_log, gets logged, and the bare raise re-raises the original cancel.
  • wait_for_generate_calls: asyncio.wait copies its input, so _on_generate_call_done can remove entries while it waits.
  • Earlier threads: every maintainer thread is handled at HEAD or answered, with no pushback. No _RUN_GROUP_DRAIN_TIMEOUT_S is left anywhere.

Not verified: that Monarch starts one sender's concurrent-endpoint calls in order (only the CPU real-process test covers it). No GPU run at this head.

@pzhan9

pzhan9 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

I think this PR is trying to solve 2 different things:

Work around the error caused by Monarch's undeliverable-message mechanism

The proper fix is for Monarch to provide the right semantics: as this PR shows, working around it on the user side is quite messy. I filed a Monarch issue for it: meta-pytorch/monarch#5301

Until then, main's drain-before-stop in Rollouter.close already avoids the crash, so nothing is broken in the meantime.

Bridge the asyncio cancel between the controller and the RolloutWorker actor

Not propagating cancellation is a common design decision in actor frameworks, and Monarch calls it out explicitly in its docs. So I think Monarch's design is reasonable, and the question becomes whether titan should add a cancellation endpoint so the application can cancel ongoing rollouts.

I don't see visible value in it today. The only cross-process cancel is at shutdown, and the job tears everything down shortly after, so letting those rollouts run for that short period seems harmless. The one cost I can see is that leftover rollouts overlap with the validation after training. If that turns out to be noticeable, a measurement on a multi-turn recipe would make the case. Also note that adding the cancel today isn't free: it breaks the invariant the current drain relies on, which is why half of this PR has to work around #5249. It only becomes cheap once #5301 is fixed. (Releasing the group in a finally without actually stopping it doesn't help either: the group's next turn re-creates its pin.)

So my recommendation is to table this PR for now, and:

  • wait for the Monarch issue to be resolved;
  • only add the rollout cancellation logic to RolloutWorker when we have a real need (e.g. a cancel outside shutdown, or a measured slowdown of the final validation).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Agreed, thanks. This PR is out of the stack and back to a draft, parked on "Rollouter: keep one handle per rollout worker". It waits for the Monarch issue you filed and a real need for a cancel (outside shutdown, or a measured slowdown of the validation after training).

The native rollout timeout PR is parked with it. Without this PR's call tracking, a timeout cut can leave the router owing a stopped worker an answer at shutdown. In a CPU probe, 200 cut calls exited 130 and 1 cut call exited 0. No recipe sets that timeout today.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants