Skip to content

[Core] Drain node on SIGTERM before shutting down ray start --block - #64454

Merged
edoakes merged 1 commit into
ray-project:masterfrom
johntaylor-cell:serve-drain-on-sigterm
Jul 18, 2026
Merged

edoakes merged 1 commit into
ray-project:masterfrom
johntaylor-cell:serve-drain-on-sigterm

Conversation

@johntaylor-cell

@johntaylor-cell johntaylor-cell commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Fixes a regression between Ray 2.32 and 2.33 that causes bursts of HTTP 500s
during RayService zero-downtime upgrades.

Root cause

KubeRay launches the container as bash -c "...; ray start ... --block".

  • 2.32: bash stays PID 1. A non-interactive bash does not forward SIGTERM,
    and the kernel suppresses PID-1 default signal actions, so the SIGTERM that
    Kubernetes sends on pod deletion is effectively swallowed. Ray keeps running
    until the grace-period SIGKILL, and traffic drains off the node naturally.
  • 2.33+: bash's last-command exec optimization replaces the shell, making
    ray start (Python) PID 1. SIGTERM now reaches ray start's handler, which
    calls kill_all_processes → SIGTERMs the raylet with a 1s grace before
    SIGKILL. Local Serve replicas are torn down immediately while old proxies
    still route to them → HTTP 500s.

Fix

Add an opt-in graceful drain on SIGTERM for ray start --block, gated by
RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S (seconds; default 0 = disabled,
shutdown behavior unchanged
). KubeRay sets it on RayService nodes.

When enabled, before kill_all_processes the SIGTERM handler:

  1. Marks the local node draining in the GCS via drain_node (reason
    PREEMPTION, with a deadline). This reuses the exact mechanism autoscaler v2
    already uses to terminate nodes — no new raylet- or GCS-side behavior.
  2. Drain-aware components (Ray Serve) observe the draining node and quiesce the
    local proxy + migrate replicas. As leases are returned the node becomes
    draining and idle, at which point the raylet self-terminates.
  3. Polls for the raylet process to exit (dead_processes()), capped by the
    timeout, then proceeds with teardown.

Safety / correctness

  • Best-effort, never blocks shutdown: the drain is wrapped in try/except,
    and the drain_node RPC is given a bounded timeout so a hung or unreachable
    GCS cannot stall the handler. It is skipped entirely when there is no local
    node id yet or no raylet in all_processes (SIGTERM can arrive mid
    Node.__init__, before the id is set or the raylet is started).
  • Hex node id: drain_node is passed the node id as a hex string — it
    decodes via FromHex; a binary id yields a nil id that the GCS silently
    accepts as an "unknown node" without actually draining.
  • Scope: only ray start --block is affected. ray.init() uses
    shutdown_at_exit=False (the handler is never installed) and ray stop
    kills the raylet directly.
  • Double-bounded: worst case is the drain timeout, itself bounded by the
    pod's termination grace period (Kubernetes SIGKILLs at the deadline anyway).

Testing

  • test_draining.py: mock-based unit tests (fake clock) — marks draining then
    polls to the cap, early-exits when the raylet self-terminates, disabled when
    timeout ≤ 0, drain failure/rejection do not block shutdown, the RPC is
    bounded, and the no-node-id / no-raylet guards are covered.
  • test_multi_node_3.py::test_graceful_shutdown_drains_node_on_sigterm:
    integration test of the drain-enabled path (ray start --head --block,
    SIGTERM, assert the drain and finished-draining log lines).
  • The fast-teardown tests that SIGTERM a ray start --block supervisor
    (test_calling_start_ray_head, test_ray_init, test_ray_init_2) pin
    RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S=0 to keep asserting immediate teardown.

Related issue number

Fixes #64181

@johntaylor-cell
johntaylor-cell requested a review from a team as a code owner June 30, 2026 20:00
@johntaylor-cell johntaylor-cell added the go add ONLY when ready to merge, run all tests label Jun 30, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@ray-gardener ray-gardener Bot added the core Issues that should be addressed in Ray Core label Jul 1, 2026
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from 0a2ae2a to e064e87 Compare July 1, 2026 16:51
Comment thread python/ray/_private/node.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from e064e87 to 7a0cd19 Compare July 1, 2026 17:15
Comment thread python/ray/_private/node.py Resolved
@karticam karticam self-assigned this Jul 1, 2026
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from 7a0cd19 to 3a13018 Compare July 2, 2026 14:59
Comment thread python/ray/_private/node.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch 2 times, most recently from bceda73 to 9c63ab4 Compare July 2, 2026 19:09
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/ray_constants.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch 2 times, most recently from 2be5632 to 57fad3e Compare July 3, 2026 16:15
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from 57fad3e to df8ddb2 Compare July 7, 2026 17:37
Comment thread python/ray/_private/node.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from df8ddb2 to d820a05 Compare July 7, 2026 17:48

@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 d820a05. Configure here.

Comment thread python/ray/_private/node.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch 3 times, most recently from 6c5d321 to e8cdc3e Compare July 9, 2026 03:06
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/ray_constants.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch 4 times, most recently from bf58714 to 274a3e4 Compare July 12, 2026 20:31
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/ray_constants.py Resolved
Comment thread python/ray/_private/ray_constants.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from 274a3e4 to a43ff67 Compare July 17, 2026 18:38
Comment thread python/ray/_private/node.py Resolved
@karticam

Copy link
Copy Markdown
Contributor

Thanks for addressing the comments. LGTM. The only thing left is to decide the default value of the config variable RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S. Tagging @edoakes for that

…rt --block`

Regression between Ray 2.32 and 2.33. KubeRay launches the container as
`bash -c "...; ray start ... --block"`. In 2.32 bash was PID 1, so the SIGTERM
on pod deletion was swallowed (non-interactive bash does not forward it, and the
kernel suppresses PID-1 default actions); Ray kept running until the grace-period
SIGKILL and traffic drained off the old node naturally. In 2.33 bash s
last-command exec makes `ray start` PID 1, so SIGTERM reaches its handler ->
kill_all_processes SIGTERMs the raylet (1s grace, then SIGKILL) -> local Serve
replicas are torn down immediately while old proxies still route to them ->
bursts of HTTP 500s during RayService zero-downtime upgrades.

This adds an opt-in graceful drain on SIGTERM for `ray start --block`: when
RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S > 0, the handler marks the local node
draining in the GCS (PREEMPTION, with a deadline) so drain-aware components
(Ray Serve) can quiesce the local proxy and migrate replicas, then waits for the
node to finish draining before tearing down. Once the node is draining AND idle
(all worker leases returned), the raylet self-terminates, so we poll for the
raylet process exiting, capped by the timeout. Default 0 (disabled) leaves
shutdown behavior unchanged; KubeRay sets it on RayService nodes.

Draining is best-effort and cannot block kill_all_processes: it is wrapped in
try/except and skipped when there is no local node id yet or no raylet in
all_processes (SIGTERM can arrive mid-Node.__init__, before the id is set or the
raylet is started). The node id is passed to drain_node as a hex string (it
decodes via FromHex; a binary id yields a nil id the GCS accepts as an unknown
node without draining). Only `ray start --block` is affected; `ray.init()` uses
shutdown_at_exit=False and `ray stop` kills the raylet directly.

The fast-teardown tests that SIGTERM a `ray start --block` supervisor
(test_calling_start_ray_head, test_ray_init, test_ray_init_2) pin
RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S=0 to explicitly assert immediate teardown;
test_graceful_shutdown_drains_node_on_sigterm covers the drain-enabled path.

Fixes ray-project#64181.

Signed-off-by: john.taylor <[email protected]>
@johntaylor-cell
johntaylor-cell force-pushed the serve-drain-on-sigterm branch from a43ff67 to 61c92a9 Compare July 17, 2026 20:26
@edoakes
edoakes merged commit f77bdb3 into ray-project:master Jul 18, 2026
3 checks passed
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ray-project#64454)

## Why are these changes needed?

Fixes a regression between Ray 2.32 and 2.33 that causes bursts of HTTP
500s
during RayService zero-downtime upgrades.

### Root cause

KubeRay launches the container as `bash -c "...; ray start ...
--block"`.

- **2.32:** bash stays PID 1. A non-interactive bash does not forward
SIGTERM,
and the kernel suppresses PID-1 default signal actions, so the SIGTERM
that
Kubernetes sends on pod deletion is effectively swallowed. Ray keeps
running
until the grace-period SIGKILL, and traffic drains off the node
naturally.
- **2.33+:** bash's last-command `exec` optimization replaces the shell,
making
`ray start` (Python) PID 1. SIGTERM now reaches `ray start`'s handler,
which
calls `kill_all_processes` → SIGTERMs the raylet with a 1s grace before
SIGKILL. Local Serve replicas are torn down immediately while old
proxies
  still route to them → HTTP 500s.

### Fix

Add an **opt-in** graceful drain on SIGTERM for `ray start --block`,
gated by
`RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S` (seconds; **default `0` =
disabled,
shutdown behavior unchanged**). KubeRay sets it on RayService nodes.

When enabled, before `kill_all_processes` the SIGTERM handler:

1. Marks the local node draining in the GCS via `drain_node` (reason
`PREEMPTION`, with a deadline). This reuses the exact mechanism
autoscaler v2
already uses to terminate nodes — no new raylet- or GCS-side behavior.
2. Drain-aware components (Ray Serve) observe the draining node and
quiesce the
local proxy + migrate replicas. As leases are returned the node becomes
   draining **and** idle, at which point the raylet self-terminates.
3. Polls for the raylet process to exit (`dead_processes()`), capped by
the
   timeout, then proceeds with teardown.

### Safety / correctness

- **Best-effort, never blocks shutdown:** the drain is wrapped in
`try/except`,
and the `drain_node` RPC is given a bounded timeout so a hung or
unreachable
GCS cannot stall the handler. It is skipped entirely when there is no
local
  node id yet or no raylet in `all_processes` (SIGTERM can arrive mid
  `Node.__init__`, before the id is set or the raylet is started).
- **Hex node id:** `drain_node` is passed the node id as a hex string —
it
decodes via `FromHex`; a binary id yields a nil id that the GCS silently
  accepts as an "unknown node" without actually draining.
- **Scope:** only `ray start --block` is affected. `ray.init()` uses
`shutdown_at_exit=False` (the handler is never installed) and `ray stop`
  kills the raylet directly.
- **Double-bounded:** worst case is the drain timeout, itself bounded by
the
pod's termination grace period (Kubernetes SIGKILLs at the deadline
anyway).

### Testing

- `test_draining.py`: mock-based unit tests (fake clock) — marks
draining then
polls to the cap, early-exits when the raylet self-terminates, disabled
when
  timeout ≤ 0, drain failure/rejection do not block shutdown, the RPC is
  bounded, and the no-node-id / no-raylet guards are covered.
- `test_multi_node_3.py::test_graceful_shutdown_drains_node_on_sigterm`:
integration test of the drain-enabled path (`ray start --head --block`,
  SIGTERM, assert the drain and finished-draining log lines).
- The fast-teardown tests that SIGTERM a `ray start --block` supervisor
(`test_calling_start_ray_head`, `test_ray_init`, `test_ray_init_2`) pin
`RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S=0` to keep asserting immediate
teardown.

## Related issue number

Fixes ray-project#64181

Signed-off-by: john.taylor <[email protected]>
Signed-off-by: 400Ping <[email protected]>
abrarsheikh pushed a commit that referenced this pull request Sep 11, 2026
## Description

- Ray Serve doesn't perform replicas graceful shutdown during node
preemption (in-flight requests will fail immediately)
- [PR #64454](#64454) marks a Ray
node as draining when `ray start
--block` receives SIGTERM. This allows time for Controller to draining
and graceful shutdown replicas running on the nodes.
- There is already logic for draining and migrating replicas on draining
nodes
- However, the default Ray Serve controller node cache always returned
an empty draining-node map. As a result, Serve’s existing proxy and
replica draining logic could not observe nodes marked as draining in
GCS.
- This change allow the serve controller to query draining nodes from
GCS to enable draining of running replicas during node preemption

---------

Signed-off-by: Le Duc Manh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Description

- Ray Serve doesn't perform replicas graceful shutdown during node
preemption (in-flight requests will fail immediately)
- [PR ray-project#64454](ray-project#64454) marks a Ray
node as draining when `ray start
--block` receives SIGTERM. This allows time for Controller to draining
and graceful shutdown replicas running on the nodes.
- There is already logic for draining and migrating replicas on draining
nodes
- However, the default Ray Serve controller node cache always returned
an empty draining-node map. As a result, Serve’s existing proxy and
replica draining logic could not observe nodes marked as draining in
GCS.
- This change allow the serve controller to query draining nodes from
GCS to enable draining of running replicas during node preemption

---------

Signed-off-by: Le Duc Manh <[email protected]>
rueian pushed a commit that referenced this pull request Nov 25, 2026
… passed (#68457)

## Why are these changes needed?

Closes #68304.

On SIGTERM, `ray start --block` drains the local node with
`DRAIN_NODE_REASON_PREEMPTION` and a deadline of `now +
RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S` (#64454). If the node is still
busy when that time is up, `_drain_node_before_shutdown` returns and
`kill_all_processes()` sends SIGTERM to the raylet right away.

The raylet records the node as preempted only if the drain deadline is
strictly in the past when it receives SIGTERM (`deadline_timestamp_ms <
now`, `src/ray/raylet/main.cc`). The poll loop ends on the monotonic
clock at about the same instant as the wall-clock deadline, so the
raylet often sees `deadline == now` and records `EXPECTED_TERMINATION`.
Owners then count the failed tasks against `max_retries` (`TaskManager`
only skips the count for `AUTOSCALER_DRAIN_PREEMPTED`), so #54182 does
not take effect for busy nodes.

This PR keeps the raylet's rule as it is and fixes the caller: after the
poll loop times out, it sleeps until wall-clock time is 10 ms past the
deadline it sent, then kills local processes. The extra wait is capped
at 1 s so that a backwards wall-clock jump cannot stall teardown.
Nothing changes when the raylet exits on its own after draining, because
in that case it takes the death reason from the drain request.

## Related issue number

Closes #68304

## Testing

Unit tests (`python/ray/tests/test_draining.py`):

- `_run_drain` now fakes the wall clock in lockstep with the monotonic
clock.
- `test_drain_timeout_kills_only_after_deadline` (16 cases over timeout
and poll interval) checks that a timed-out drain ends strictly after the
deadline sent to the GCS, by at most the margin. Without the fix in
`node.py`, all 16 cases fail.
- `test_drain_early_exit_does_not_wait_for_deadline` checks that an
early exit does not wait.
- `test_wait_until_past_drain_deadline` covers the helper: before, at
and after the deadline, and a backwards clock jump.

```
python -m pytest python/ray/tests/test_draining.py -k "drain_ or sigterm or wait_until"
35 passed, 10 deselected
```

End to end on Kubernetes (minikube, KubeRay v1.6.2,
`rayproject/ray:2.60.0`, `RAY_GRACEFUL_SHUTDOWN_DRAIN_TIMEOUT_S=3`,
grace period 10 s). A task pinned to each worker keeps the node busy,
the worker pods are deleted, and the head reads each node's death reason
from the GCS. Both runs mount `node.py` from a ConfigMap: the stock
2.60.0 file (same sha256 as the image) or the same file with this patch
applied (the hunk applies to 2.60.0 unchanged).

Each run deletes 2 busy workers per round, for 15 rounds (30 nodes):

| `node.py` | `AUTOSCALER_DRAIN_PREEMPTED` | `EXPECTED_TERMINATION` |
|---|---|---|
| stock 2.60.0 | 24 | 6 |
| with this PR | 30 | 0 |

With the stock file, 6 of 30 busy nodes are recorded as
`EXPECTED_TERMINATION` ("received SIGTERM"). With the patch, all 30 are
recorded as preempted.

## Duplicate check

- No open or closed PR references #68304 or touches
`_drain_node_before_shutdown` apart from #64454, which introduced it.
- @MaiAditya offered to work on this in the issue. I replied there
before opening this PR, and the PR follows the approach they outlined
(option 1).
- Option 3 from the issue (treating any `PREEMPTION` drain as preempted
in the raylet) is intentionally left out; it overlaps with #66901.

## AI assistance

I used an AI coding assistant (Claude Code) to draft the change, the
tests and this description. I reviewed every changed line and ran the
tests and the Kubernetes check above myself.

## Checks

- [x] I've signed off every commit (by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've run `black` and `ruff` (pre-commit versions) on the changed
files.
- [x] Unit tests
- [ ] Release tests
- [ ] This PR is not tested :(

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

Labels

core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve][Core] RayService upgrade can return HTTP 500 when ray start receives SIGTERM before Serve proxy drains

5 participants