Skip to content

[train][Preemption handling 1/n] Add preemption watcher for node-drain observability - #63807

Merged
matthewdeng merged 16 commits into
ray-project:masterfrom
liulehui:preempt-stage1-watcher
Jun 12, 2026
Merged

matthewdeng merged 16 commits into
ray-project:masterfrom
liulehui:preempt-stage1-watcher

Conversation

@liulehui

@liulehui liulehui commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Description

  1. first step for ray train v2 preemption handling.
  2. This PR adds:
  • PreemptionWatcher: a num_cpus=0 actor whose background thread polls Ray Core's get_draining_nodes(), maps drained node IDs to affected worker ranks via a failure-domain map, and logs detected events.
  • PreemptionCallback : manages one watcher per worker group (fresh watcher + failure-domain map per restart/resize), and stops/kills it on shutdown. Not registered in TorchFT (replica-group) mode.
  • Controller wiring, gated behind RAY_TRAIN_ENABLE_PREEMPTION_WATCHER (default on) for a quick rollback path. Poll interval via RAY_TRAIN_PREEMPTION_POLL_INTERVAL_S (default 5s).

Additional information

tested with this script and corresponding logs:
https://gist.github.com/liulehui/fc9bd4a6fe58b72a85363c0cda619f7e

see logs:

(RayTrainWorker pid=79326) [rank 1] checkpoint at step 0
(RayTrainWorker pid=79326) Reporting training result 2: TrainingReport(checkpoint=None, metrics={'step': 1}, validation=False) from rank 1
[22:48:55.753 PDT] [drain] node=b157c93d... drained via GCS, deadline=+15s (22:49:10.749 PDT)
(PreemptionWatcher pid=79362) PreemptionWatcher: drain detected — preempted_node_ids=['b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45'], preempted_ranks=[1], deadline=1780379350.749
(RayTrainWorker pid=79327) [W601 22:48:50.712818000 ProcessGroupGloo.cpp:547] Warning: Unable to resolve hostname to a (local) address. Using the loopback address as fallback. Manually set the network interface to bind to with GLOO_SOCKET_IFNAME. (function operator())
(raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer). [repeated 2x across cluster]
(raylet)   warnings.warn( [repeated 2x across cluster]
(RayTrainWorker pid=79327) [rank 0] starting fresh
(RayTrainWorker pid=79327) Checkpoint successfully created at: Checkpoint(filesystem=local, path=/var/folders/xv/0ps50qx155xd08dr1kk37t7m0000gp/T/ray_train_preempt_demo_s0sn2wy1/preempt_stage1_demo/checkpoint_2026-06-01_22-48-50.556954)
(RayTrainWorker pid=79327) Reporting training result 1: TrainingReport(checkpoint=Checkpoint(filesystem=local, path=/var/folders/xv/0ps50qx155xd08dr1kk37t7m0000gp/T/ray_train_preempt_demo_s0sn2wy1/preempt_stage1_demo/checkpoint_2026-06-01_22-48-50.556954), metrics={'step': 0}, validation=False) from rank 0
(RayTrainWorker pid=79327) [rank 0] checkpoint at step 0
(RayTrainWorker pid=79327) Reporting training result 4: TrainingReport(checkpoint=None, metrics={'step': 3}, validation=False) from rank 0 [repeated 5x across cluster]
(RayTrainWorker pid=79326) Reporting training result 8: TrainingReport(checkpoint=None, metrics={'step': 7}, validation=False) from rank 1 [repeated 7x across cluster]
(RayTrainWorker pid=79326) Reporting training result 11: TrainingReport(checkpoint=None, metrics={'step': 10}, validation=False) from rank 1 [repeated 6x across cluster]
[22:49:10.754 PDT] [evict] deadline reached → removing node b157c93d... (reclaim)
(TrainController pid=79312) [FailurePolicy] RETRY
(TrainController pid=79312)   Source: worker group
(TrainController pid=79312)   Error count: 1 (max allowed: 1)
(TrainController pid=79312) Error: Training failed due to worker errors:
(TrainController pid=79312) [Rank 1 Error Snippet]:
(TrainController pid=79312) A worker health check failed.
(TrainController pid=79312) Worker info: Worker(
(TrainController pid=79312)   actor=Actor(RayTrainWorker, c221047dc0a4e2b3ea0bbcc501000000),
(TrainController pid=79312)   metadata=ActorMetadata(
(TrainController pid=79312)     hostname='Lehuis-MacBook-Pro.local',
(TrainController pid=79312)     node_id='b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45',
(TrainController pid=79312)     node_ip='127.0.0.1',
(TrainController pid=79312)     pid=79326,
(TrainController pid=79312)   ),
(TrainController pid=79312)   distributed_context=DistributedContext(world_rank=1, world_size=2, local_rank=1, local_world_size=2, node_rank=0),
(TrainController pid=79312)   log_file_path='/tmp/ray/session_2026-06-01_22-48-34_224594_13456/logs/train/ray-train-app-worker-e6b351b6cfced688270c769672b65d23cb0190c3ab92160fbaa39bd6.log',
(TrainController pid=79312) )
(TrainController pid=79312) The actor died unexpectedly before finishing this task.
(TrainController pid=79312) 	class_name: RayTrainWorker
(TrainController pid=79312) 	actor_id: c221047dc0a4e2b3ea0bbcc501000000
(TrainController pid=79312) 	pid: 79326
(TrainController pid=79312) 	namespace: b37ae402-a08c-4afd-abc6-dd97b4c09dca
(TrainController pid=79312) 	ip: 127.0.0.1
(TrainController pid=79312) The actor died because its node has died. Node Id: b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45
(TrainController pid=79312) 	the actor's node was preempted: preemption_integration_demo: simulating node drain
(TrainController pid=79312) ray.train.WorkerGroupError: Training failed due to worker errors:
(TrainController pid=79312) [Rank 1 Error Snippet]:
(TrainController pid=79312) A worker health check failed.
(TrainController pid=79312) Worker info: Worker(
(TrainController pid=79312)   actor=Actor(RayTrainWorker, c221047dc0a4e2b3ea0bbcc501000000),
(TrainController pid=79312)   metadata=ActorMetadata(
(TrainController pid=79312)     hostname='Lehuis-MacBook-Pro.local',
(TrainController pid=79312)     node_id='b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45',
(TrainController pid=79312)     node_ip='127.0.0.1',
(TrainController pid=79312)     pid=79326,
(TrainController pid=79312)   ),
(TrainController pid=79312)   distributed_context=DistributedContext(world_rank=1, world_size=2, local_rank=1, local_world_size=2, node_rank=0),
(TrainController pid=79312)   log_file_path='/tmp/ray/session_2026-06-01_22-48-34_224594_13456/logs/train/ray-train-app-worker-e6b351b6cfced688270c769672b65d23cb0190c3ab92160fbaa39bd6.log',
(TrainController pid=79312) )
(TrainController pid=79312) The actor died unexpectedly before finishing this task.
(TrainController pid=79312) 	class_name: RayTrainWorker
(TrainController pid=79312) 	actor_id: c221047dc0a4e2b3ea0bbcc501000000
(TrainController pid=79312) 	pid: 79326
(TrainController pid=79312) 	namespace: b37ae402-a08c-4afd-abc6-dd97b4c09dca
(TrainController pid=79312) 	ip: 127.0.0.1
(TrainController pid=79312) The actor died because its node has died. Node Id: b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45
(TrainController pid=79312) 	the actor's node was preempted: preemption_integration_demo: simulating node drain
(TrainController pid=79312) Graceful shutdown of backend failed. This is expected if one of the workers has crashed.
(TrainController pid=79312) Traceback (most recent call last):
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/train/v2/_internal/callbacks/backend_setup.py", line 27, in before_execution_group_shutdown
(TrainController pid=79312)     self._backend.on_shutdown(execution_group, self._backend_config)
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/train/torch/config.py", line 247, in on_shutdown
(TrainController pid=79312)     ray.get(futures, timeout=timeout_s)
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper
(TrainController pid=79312)     return fn(*args, **kwargs)
(TrainController pid=79312)            ^^^^^^^^^^^^^^^^^^^
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/_private/client_mode_hook.py", line 107, in wrapper
(TrainController pid=79312)     return func(*args, **kwargs)
(TrainController pid=79312)            ^^^^^^^^^^^^^^^^^^^^^
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/_private/worker.py", line 2984, in get
(TrainController pid=79312)     values, debugger_breakpoint = worker.get_objects(
(TrainController pid=79312)                                   ^^^^^^^^^^^^^^^^^^^
(TrainController pid=79312)   File "/Users/lehui/Desktop/ray/python/ray/_private/worker.py", line 1052, in get_objects
(TrainController pid=79312)     raise value
(TrainController pid=79312) ray.exceptions.ActorDiedError: The actor died unexpectedly before finishing this task.
(TrainController pid=79312) 	class_name: RayTrainWorker
(TrainController pid=79312) 	actor_id: c221047dc0a4e2b3ea0bbcc501000000
(TrainController pid=79312) 	pid: 79326
(TrainController pid=79312) 	namespace: b37ae402-a08c-4afd-abc6-dd97b4c09dca
(TrainController pid=79312) 	ip: 127.0.0.1
(TrainController pid=79312) The actor died because its node has died. Node Id: b157c93de9603b1458ae4bd22668b46a4f0ae249bf9467072ba6fd45
(TrainController pid=79312) 	the actor's node was preempted: preemption_integration_demo: simulating node drain
(TrainController pid=79312) Attempting to start training worker group of size 2 with the following resources: [{'worker_node': 1}] * 2
(raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).
(raylet)   warnings.warn(
(RayTrainWorker pid=79327) Reporting training result 12: TrainingReport(checkpoint=None, metrics={'step': 11}, validation=False) from rank 0 [repeated 3x across cluster]

@liulehui
liulehui requested a review from a team as a code owner June 2, 2026 22:18
@liulehui liulehui added the go add ONLY when ready to merge, run all tests label Jun 2, 2026

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces a preemption observability mechanism for Ray Train v2, adding a PreemptionCallback and a PreemptionWatcher actor to poll Ray Core for node drains and handle failure-domain mapping (including TPU slices). The review feedback highlights several important robustness and performance issues: a synchronous ray.get call that blocks the controller's asyncio event loop, potential initialization failures in the failure-domain mapping logic if exceptions are raised outside the current try-except block, and potential runtime errors (AttributeError and TypeError) if the drain source returns None or invalid values.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@ray-gardener ray-gardener Bot added train Ray Train Related Issue observability Issues related to the Ray Dashboard, Logging, Metrics, Tracing, and/or Profiling labels Jun 3, 2026

@TimothySeah TimothySeah 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.

Looks great! I have some high level questions:

  1. Would it be worth filing a bug to have event signaling so we don't need to poll get_draining_nodes? Not sure if they have rate limits that we need to be aware of
  2. Should we create the preemption watcher by default? I would imagine only setups with spot instances have that signal. Would it make sense to detect whether the setup has get_draining_nodes, and if not, not create the preemption watcher?

liulehui and others added 9 commits June 5, 2026 10:41
Stage 1 of preemption handling for Ray Train V2: observability only.

- PreemptionWatcher (execution/preemption.py): a num_cpus=0 actor whose
  background thread polls Ray Core's get_draining_nodes, maps drained node
  IDs to affected ranks via a failure-domain map, and logs detected drains.
  TPU-slice-aware: ranks fate-shared across a slice (including slice-mates we
  don't host) are expanded together; non-TPU clusters collapse to per-node.
  The thread starts in __init__ so it resumes on actor restart (max_restarts=-1).
  Deadline follows Ray Core's convention: earliest non-zero deadline_ms, or
  0.0 when unknown.

- PreemptionCallback (callbacks/preemption_callback.py): spawns one watcher
  per worker group and stops/kills it on shutdown. Not registered in TorchFT
  (replica-group) mode.

- Controller registers the callback, gated behind RAY_TRAIN_ENABLE_PREEMPTION_WATCHER
  (default on); poll interval via RAY_TRAIN_PREEMPTION_POLL_INTERVAL_S.

No worker fan-out, no controller state change, and no user-facing API yet —
those land in later stages (mark_preempt + preemption_status, PreemptingState,
PreemptionError + max_preemption_failures).

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
- Don't block the controller's event loop on shutdown: force-kill the watcher
  actor (non-blocking) instead of a synchronous ray.get(stop.remote()).
- Make watcher startup idempotent: tear down any existing watcher before
  spawning a new one, so a failed start that skips the shutdown hook can't
  leak an orphaned watcher across a reschedule.
- Wrap the entire failure-domain build in try/except so a malformed node entry
  or TPU-label lookup error falls back to per-node domains instead of failing
  __init__ (which under max_restarts=-1 would restart-loop).
- Guard against a drain source returning None and against None/missing
  deadline values.
- Tests for the slice-lookup-error fallback and the None drain source.

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
The callback force-kills the watcher (kill-only), so stop() is no longer
called in production. Drop it along with PREEMPTION_WATCHER_STOP_TIMEOUT_S;
the test helper halts the poll thread inline.

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Drop the unreachable distributed_context-None guard in the callback
  (it's assigned to every worker before after_worker_group_start runs).
- Log when the watcher is explicitly enabled but skipped due to replica
  groups (TorchFT), instead of silently ignoring it.
- Document the keys-are-job-nodes invariant in _poll_once: complete for TPU
  (SPMD jobs fully occupy their slice) and correct for GPU.
- Hoist `import ray` to module scope in the tests.

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
@liulehui
liulehui force-pushed the preempt-stage1-watcher branch from 083cf58 to 7b1c161 Compare June 5, 2026 17:41
@liulehui

liulehui commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Looks great! I have some high level questions:

  1. Would it be worth filing a bug to have event signaling so we don't need to poll get_draining_nodes? Not sure if they have rate limits that we need to be aware of
  2. Should we create the preemption watcher by default? I would imagine only setups with spot instances have that signal. Would it make sense to detect whether the setup has get_draining_nodes, and if not, not create the preemption watcher?
  1. created a bug for us to track
  2. Right now I am hiding it under the env var

liulehui and others added 3 commits June 10, 2026 23:20
…nups

- deadline_ms is now Optional[int] (None = no deadline) instead of 0, and the
  docstring clarifies it's the earliest reclaim deadline across draining nodes.
- Remove the drain_source injection seam; the watcher calls _get_draining_nodes
  directly and tests mock that. Drops the DrainSource type / param.
- Rename get_latest_info -> get_latest_preemption_info.
- Elaborate the failure-domain-map docstring; clarify the drain-filtering
  comment; reword the stage-1 TODOs to not reference not-yet-existing APIs.

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Per review: keep deadline_ms as the single earliest preemption deadline for
now (documented), but store preempted nodes as a node_id -> ranks map and
expose preempted_node_ids / preempted_ranks as derived getters. This keeps the
ergonomic flat views while retaining the per-node association, so per-rank
deadlines can be layered on when the report() barrier is relaxed in a later
stage.

Signed-off-by: Lehui Liu <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 1abf5a5. Configure here.

Signed-off-by: Lehui Liu <[email protected]>
Comment thread ISSUE_DRAFT.md Resolved
@matthewdeng
matthewdeng merged commit 2f0866c into ray-project:master Jun 12, 2026
3 checks passed
justinvyu pushed a commit that referenced this pull request Jun 24, 2026
…#64099)

1. Builds on top of the Stage 1 preemption watcher (#63807): when the
watcher detects a preemption, it now fans the signal out to the worker
actors and stores in `PreemptionContext` in the TrainContext
2. added a rpc for mark_preempt in Train worker
3. watcher fans out preemptionInfo through every worker handle.
4. follow up PR will add public apis and controller state.

---------

Signed-off-by: Lehui Liu <[email protected]>
limarkdcunha pushed a commit to limarkdcunha/ray that referenced this pull request Jun 30, 2026
limarkdcunha pushed a commit to limarkdcunha/ray that referenced this pull request Jun 30, 2026
…ray-project#64099)

1. Builds on top of the Stage 1 preemption watcher (ray-project#63807): when the
watcher detects a preemption, it now fans the signal out to the worker
actors and stores in `PreemptionContext` in the TrainContext
2. added a rpc for mark_preempt in Train worker
3. watcher fans out preemptionInfo through every worker handle.
4. follow up PR will add public apis and controller state.

---------

Signed-off-by: Lehui Liu <[email protected]>
matthewdeng pushed a commit that referenced this pull request Jul 24, 2026
…ller PreemptingState (#64360)

## Description
This is stage 3 of preemption handling for Ray Train V2, stacked on top
of stage 1 (#63807, watcher + observability) and stage 2 (#64099,
worker-side fan-out). Stage 2 fans the preemption signal out to all
workers; this stage
exposes it to user code and add the controller state to react to it.

1. add the public api: `ray.train.get_preemption_info()`, which returns
the current `PreemptionInfo`
2. add `PreemptingState`, when an worker echoes a preemption signal in
its poll status, controller transitions from `RunningState` ->
`PreemptingState`.
3. in PreemptingState, controller will wait until (a) all workers gone
(b) reclaim deadline elapsed (`drain_timed_out`=True, force restart),
(c) clean finish (run finish before the reclaim -> `Finished`.)
4. add `max_preemption_failures` in FailureConfig and `PreemptionError`.

### User behavior coverage
Note that currently, the deadline for preempting exit is the same as
premption signal deadline or 120s if None.

| # | Situation | UDF behavior | preemption budget >= 0 | preemption
budget < 0 |
|---|---|---|---|---|
| 1a | Ray Core draining signal arrives, then the reclaim kills **all**
training workers (before or at the warned deadline) | Save a JIT
checkpoint on the signal, keep training until killed | Enters
`PreemptingState`; once every worker has exited →
`PreemptionError(drain_timed_out=False)` → **restart + resume** |
transfer into ShuttingDown and `ErroredState`; `fit()` raises
`PreemptionError` |
| 1b | Ray Core draining signal arrives, Save a JIT checkpoint on the
signal, keep training until killed **some** workers — others are still
healthy | Healthy workers keep training and stuck at the next report
barrier, util timeout | **Stays in `PreemptingState`** — the partial
kill does *not* trigger an immediate restart; healthy workers get the
rest of the grace window, until every worker exits (→ 1a) or the
deadline passes (→ 2) | same as 1a / 2 |
| 2 | Draining signal arrives but the reclaim is **late** — workers
still alive at the warned deadline (or after 120s if the cloud gave no
deadline) | Keep training | Enters `PreemptingState`; at the deadline
Ray Train stops waiting → `PreemptionError(drain_timed_out=True)` →
tears down the live workers itself → **restart + resume** | Run shuts
down into `ErroredState`; `fit()` raises `PreemptionError` |
| 3 | Worker killed by a reclaim with **no warning ever observed** (no
signal from Ray Core) | Nothing — there was no window to react | Skips
`PreemptingState`; Ray Core tags the death (`RayActorError.preempted`),
so the failure policy still charges it to the **preemption** budget →
**restart + resume** | Run shuts down into `ErroredState`; raises
`WorkerGroupError` carrying the preemption-tagged death |
| 4 | Training **finishes** | Just `return`, as normal | The run
**finishes** (`FinishedState`); **no budget consumed** (works even with
`max_preemption_failures=0`);| — |
| 5 | A **bug in the training code** (e.g. the JIT-checkpoint part
raises) while a warning is active or during the drain | e.g. user write
a bug in jit checkpoint function | Fails fast: no `preempted` tag on the
error → `WorkerGroupError` → charged to **`max_failures`**; the drain is
not prolonged and the preemption budget never hides real bugs |
retried/raised per `max_failures` |
| 6 | A **second node is warned** while the first is still draining
(staggered preemption) | Nothing new — keep checkpointing | The signals
are **merged** in `PreemptingState` (union of nodes/ranks, earliest
deadline); exits via 1a/2 with the merged info in the error | same as 1a
/ 2 |


### Controller State transition graph for PreemptingState:
<img width="1340" height="1290" alt="3e915f722c3f4389dfa9e9d28fdcd207"
src="https://github.com/user-attachments/assets/dfa5a19b-770c-42a4-b132-a41a75294781"
/>

## Related issues
part of #63968

## Additional information
tested with this script:
https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b
this is the log:
```
RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] PREEMPT signal: this=False preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84119) [rank 1] starting fresh
(RayTrainWorker pid=84119) [rank 1] periodic checkpoint at step 0
(RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84119) Reporting training result 10: TrainingReport(checkpoint=None, metrics={'step': 9}, validation=False) from rank 1 [repeated 4x across cluster]
(TrainController pid=84105) [FailurePolicy] RETRY
(TrainController pid=84105)   Source: preemption
(TrainController pid=84105)   Error count: 1 (max allowed: 3)
(TrainController pid=84105) Error: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) ray.train.v2.api.exceptions.PreemptionError: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) Attempting to start training worker group of size 2 with the following resources: [{'worker_node': 1}] * 2
(raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).
(raylet)   warnings.warn(
(RayTrainWorker pid=84184) Setting up process group for: env:// [rank=0, world_size=2]
(RayTrainWorker pid=84184) [W625 15:57:53.256638000 ProcessGroupGloo.cpp:547] Warning: Unable to resolve hostname to a (local) address. Using the loopback address as fallback. Manually set the network interface to bind to with GLOO_SOCKET_IFNAME. (function operator())
(TrainController pid=84105) Started training worker group of size 2: 
(TrainController pid=84105) - (ip=127.0.0.1, pid=84184) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=84105) - (ip=127.0.0.1, pid=84183) world_rank=1, local_rank=1, node_rank=0
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
```

---------

Signed-off-by: Lehui Liu <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ray-project#64099)

1. Builds on top of the Stage 1 preemption watcher (ray-project#63807): when the
watcher detects a preemption, it now fans the signal out to the worker
actors and stores in `PreemptionContext` in the TrainContext
2. added a rpc for mark_preempt in Train worker
3. watcher fans out preemptionInfo through every worker handle.
4. follow up PR will add public apis and controller state.

---------

Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ller PreemptingState (ray-project#64360)

## Description
This is stage 3 of preemption handling for Ray Train V2, stacked on top
of stage 1 (ray-project#63807, watcher + observability) and stage 2 (ray-project#64099,
worker-side fan-out). Stage 2 fans the preemption signal out to all
workers; this stage
exposes it to user code and add the controller state to react to it.

1. add the public api: `ray.train.get_preemption_info()`, which returns
the current `PreemptionInfo`
2. add `PreemptingState`, when an worker echoes a preemption signal in
its poll status, controller transitions from `RunningState` ->
`PreemptingState`.
3. in PreemptingState, controller will wait until (a) all workers gone
(b) reclaim deadline elapsed (`drain_timed_out`=True, force restart),
(c) clean finish (run finish before the reclaim -> `Finished`.)
4. add `max_preemption_failures` in FailureConfig and `PreemptionError`.

### User behavior coverage
Note that currently, the deadline for preempting exit is the same as
premption signal deadline or 120s if None.

| # | Situation | UDF behavior | preemption budget >= 0 | preemption
budget < 0 |
|---|---|---|---|---|
| 1a | Ray Core draining signal arrives, then the reclaim kills **all**
training workers (before or at the warned deadline) | Save a JIT
checkpoint on the signal, keep training until killed | Enters
`PreemptingState`; once every worker has exited →
`PreemptionError(drain_timed_out=False)` → **restart + resume** |
transfer into ShuttingDown and `ErroredState`; `fit()` raises
`PreemptionError` |
| 1b | Ray Core draining signal arrives, Save a JIT checkpoint on the
signal, keep training until killed **some** workers — others are still
healthy | Healthy workers keep training and stuck at the next report
barrier, util timeout | **Stays in `PreemptingState`** — the partial
kill does *not* trigger an immediate restart; healthy workers get the
rest of the grace window, until every worker exits (→ 1a) or the
deadline passes (→ 2) | same as 1a / 2 |
| 2 | Draining signal arrives but the reclaim is **late** — workers
still alive at the warned deadline (or after 120s if the cloud gave no
deadline) | Keep training | Enters `PreemptingState`; at the deadline
Ray Train stops waiting → `PreemptionError(drain_timed_out=True)` →
tears down the live workers itself → **restart + resume** | Run shuts
down into `ErroredState`; `fit()` raises `PreemptionError` |
| 3 | Worker killed by a reclaim with **no warning ever observed** (no
signal from Ray Core) | Nothing — there was no window to react | Skips
`PreemptingState`; Ray Core tags the death (`RayActorError.preempted`),
so the failure policy still charges it to the **preemption** budget →
**restart + resume** | Run shuts down into `ErroredState`; raises
`WorkerGroupError` carrying the preemption-tagged death |
| 4 | Training **finishes** | Just `return`, as normal | The run
**finishes** (`FinishedState`); **no budget consumed** (works even with
`max_preemption_failures=0`);| — |
| 5 | A **bug in the training code** (e.g. the JIT-checkpoint part
raises) while a warning is active or during the drain | e.g. user write
a bug in jit checkpoint function | Fails fast: no `preempted` tag on the
error → `WorkerGroupError` → charged to **`max_failures`**; the drain is
not prolonged and the preemption budget never hides real bugs |
retried/raised per `max_failures` |
| 6 | A **second node is warned** while the first is still draining
(staggered preemption) | Nothing new — keep checkpointing | The signals
are **merged** in `PreemptingState` (union of nodes/ranks, earliest
deadline); exits via 1a/2 with the merged info in the error | same as 1a
/ 2 |

### Controller State transition graph for PreemptingState:
<img width="1340" height="1290" alt="3e915f722c3f4389dfa9e9d28fdcd207"
src="https://github.com/user-attachments/assets/dfa5a19b-770c-42a4-b132-a41a75294781"
/>

## Related issues
part of ray-project#63968

## Additional information
tested with this script:
https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b
this is the log:
```
RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] PREEMPT signal: this=False preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84119) [rank 1] starting fresh
(RayTrainWorker pid=84119) [rank 1] periodic checkpoint at step 0
(RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84119) Reporting training result 10: TrainingReport(checkpoint=None, metrics={'step': 9}, validation=False) from rank 1 [repeated 4x across cluster]
(TrainController pid=84105) [FailurePolicy] RETRY
(TrainController pid=84105)   Source: preemption
(TrainController pid=84105)   Error count: 1 (max allowed: 3)
(TrainController pid=84105) Error: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) ray.train.v2.api.exceptions.PreemptionError: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) Attempting to start training worker group of size 2 with the following resources: [{'worker_node': 1}] * 2
(raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).
(raylet)   warnings.warn(
(RayTrainWorker pid=84184) Setting up process group for: env:// [rank=0, world_size=2]
(RayTrainWorker pid=84184) [W625 15:57:53.256638000 ProcessGroupGloo.cpp:547] Warning: Unable to resolve hostname to a (local) address. Using the loopback address as fallback. Manually set the network interface to bind to with GLOO_SOCKET_IFNAME. (function operator())
(TrainController pid=84105) Started training worker group of size 2:
(TrainController pid=84105) - (ip=127.0.0.1, pid=84184) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=84105) - (ip=127.0.0.1, pid=84183) world_rank=1, local_rank=1, node_rank=0
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
```

---------

Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: 400Ping <[email protected]>
matthewdeng pushed a commit that referenced this pull request Oct 6, 2026
## Description
Ray Train added a preemption-handling API
(`ray.train.get_preemption_info()`, `PreemptionInfo`, `PreemptionError`,
and the `FailureConfig` options `max_preemption_failures`,
`relax_collectives_on_preemption`, and `preemption_grace_s`). None of it
has a user guide. This PR adds a "Just-in-time checkpointing on node
preemption" section to the Train fault tolerance guide
(`train/user-guides/fault-tolerance.rst`). The section covers:

- **How Ray Train handles a preemption**: detection through Ray Core
draining nodes (including TPU slice fate-sharing), the `PreemptionInfo`
every rank receives, the drain window (120s fallback when there's no
deadline), and the restart. The restart counts against
`max_preemption_failures`, which is separate from `max_failures`.
- **Save a just-in-time checkpoint**: a runnable `TorchTrainer` example
with the preemption-specific lines highlighted. It comes with the usage
rules: call `get_preemption_info()` the same number of times on every
rank because it's a barrier, save once, fit the upload in the drain
window, and don't `return` after saving, because a clean return finishes
the run.
- **Finish slow checkpoints without the preempted workers**: when to use
`relax_collectives_on_preemption` and `preemption_grace_s`. A warning
lists the limits: rank 0 must survive, sharded checkpoints (FSDP or
ZeRO) can be committed without the preempted ranks' shards, and
collectives in user code aren't relaxed.
- **Make preemptions visible to Ray**: Briefly introduce how to
integrates with Ray core draining code api

## Related issues
1. #63807, #64099, #64360, #66225 
2. #63968


## Additional information
Test locally with `make local`, see screenshot below:
<img width="2704" height="1588" alt="image"
src="https://github.com/user-attachments/assets/e541aa79-5ec1-44d7-a44b-26f9f44f48b3"
/>
<img width="2682" height="842" alt="image"
src="https://github.com/user-attachments/assets/8d32a6c6-06f6-425c-9dbc-b490a225bfee"
/>
<img width="2674" height="1754" alt="image"
src="https://github.com/user-attachments/assets/637d3eff-2980-4bf6-b0f1-4179a756c8ec"
/>
<img width="2654" height="1586" alt="image"
src="https://github.com/user-attachments/assets/18e40213-6c28-41de-b989-5a725c0cc01a"
/>
<img width="2632" height="1780" alt="image"
src="https://github.com/user-attachments/assets/03663ff9-ed65-411e-82a4-54fba7985aa0"
/>

---------

Signed-off-by: Lehui Liu <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests observability Issues related to the Ray Dashboard, Logging, Metrics, Tracing, and/or Profiling train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants