Skip to content

[serve][in-place-updates][4/n] Add max_surge_percent for start-before-stop rolling updates - #66267

Merged
abrarsheikh merged 18 commits into
masterfrom
serve/inplace-4-max-surge-percent
Oct 15, 2026
Merged

abrarsheikh merged 18 commits into
masterfrom
serve/inplace-4-max-surge-percent

Conversation

@qishengxhe

@qishengxhe qishengxhe commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Draft for discussion of the rollout behavior raised in #63016.

Rolling updates currently stop old replicas before starting replacements, temporarily reducing capacity.

This adds max_surge_percent to start replacements first. Old replicas stop in batches once enough replacements are running to maintain the target count. If capacity is unavailable, replacements wait while old replicas keep serving.

The default is 0, preserving existing behavior. Gang deployments round the allowance up to whole gangs. During a terminally failed surge update, reducing the replica count is deferred until a deploy changes the target.
image

Example usage:
in YAML

name: surge-demo
image_uri: anyscale/ray:nightly-py311   # needs a Ray with #66267
working_dir: .
applications:
  - name: app
    import_path: serve_app:app
    deployments:
      - name: Model
        num_replicas: 4
        max_surge_percent: 50          # up to 2 extra replicas during a restart
        graceful_shutdown_timeout_s: 60

or via decorator:

from ray import serve
from starlette.requests import Request


@serve.deployment(num_replicas=4, max_surge_percent=50)
class Model:
    def __init__(self, version: str = "v1"):
        self.version = version

    async def __call__(self, request: Request) -> str:
        return f"hello from {self.version}"


app = Model.bind()

Tests

Added end-to-end tests covering surge rolling updates:

  • Startup failures, rollback reusing original replicas, and successful surge replacement while preserving capacity and serving traffic, with and without a controller restart.
  • Independent surge rollouts and rollbacks across multiple applications.
  • Surge with autoscaling, graceful request draining, scale-to-zero, and recovery after a failed deployment.
  • Whole-gang surge replacement, failure handling, and rollback.
  • Replica-count increases and decreases during surge rollouts.
  • Health-check failures stopping a surge rollout, followed by rollback preserving surviving old replicas.
  • Insufficient capacity leaving surge replacements pending while old replicas keep serving.
python -m pytest python/ray/serve/tests/unit/test_deployment_state.py python/ray/serve/tests/unit/test_config.py python/ray/serve/tests/unit/test_deployment_class.py
python -m pytest python/ray/serve/tests/test_deploy_app_2.py -k surge_rolling_update

Duplicate checks found no overlapping implementation. Claude Code assisted with implementation.

@qishengxhe qishengxhe changed the title [serve] Add max_surge_percent for start-before-stop rolling updates [serve][in-place-updates][4/n] Add max_surge_percent for start-before-stop rolling updates Sep 18, 2026
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from 87743e3 to b9e8b36 Compare September 18, 2026 04:38
@qishengxhe
qishengxhe force-pushed the serve/inplace-3-config-overrides-from-build branch from 0614b71 to 4d0b129 Compare September 18, 2026 04:38
@qishengxhe qishengxhe added serve Ray Serve Related Issue go add ONLY when ready to merge, run all tests labels Sep 18, 2026
@qishengxhe
qishengxhe force-pushed the serve/inplace-3-config-overrides-from-build branch from 4d0b129 to b7ede56 Compare September 18, 2026 18:25
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from b9e8b36 to 850a1f6 Compare September 18, 2026 18:25
@qishengxhe
qishengxhe force-pushed the serve/inplace-3-config-overrides-from-build branch from b7ede56 to d8d7a30 Compare September 18, 2026 19:25
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from 850a1f6 to bfbe574 Compare September 18, 2026 19:25
@qishengxhe
qishengxhe added this pull request to stack #66293 September 18, 2026 19:51
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from bfbe574 to a68eed4 Compare September 18, 2026 20:31
Comment on lines -268 to +269
Refer to the `@serve.deployment` decorator docs for available arguments.
See the `@serve.deployment` decorator docs for details on each option.

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.

The missing Args: section is an existing documentation gap. Adding max_surge_percent triggers validation, so I had to backfill all argument descriptions for the checks to pass.

@qishengxhe
qishengxhe marked this pull request as ready for review September 18, 2026 21:16
@qishengxhe
qishengxhe requested a review from a team as a code owner September 18, 2026 21:16

@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 max_surge_percent configuration for Ray Serve deployments, enabling rolling updates that start replacement replicas before stopping old ones. The implementation includes updates to the DeploymentConfig schema, new surge rollout logic in deployment_state.py, and comprehensive tests. The review feedback identified three actionable improvements: ensuring gang deployments stop only complete gangs to maintain scheduling invariants, adding defensive checks for potential AttributeError cases with legacy versions, and correcting a potential NameError in the test suite by using the built-in dictionary copy() method.

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/protobuf/serve.proto Resolved
@qishengxhe
qishengxhe force-pushed the serve/inplace-3-config-overrides-from-build branch from 97418a5 to 28fe00c Compare September 21, 2026 18:54
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from a21888c to b92f9fc Compare September 21, 2026 18:54

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

Stale Bugbot comment from a previous run.

@qishengxhe
qishengxhe removed this pull request from stack #66293 September 21, 2026 19:13
abrarsheikh pushed a commit that referenced this pull request Sep 23, 2026
…g updates (#66290)

## Summary

A failing rolling update can keep replacing healthy old replicas until
none remain. This change stops the update at the existing startup
failure threshold, including failures from new replicas that start but
then fail health checks. Gang health failures count once per affected
gang; healthy siblings stopped for a gang restart do not consume
retries.

The deployment stays `DEPLOY_FAILED` until a deploy changes the target.
This state survives a controller restart, including when actor or
placement-group creation reaches the failure threshold during
scheduling. The terminal flag is set when the threshold is reached, and
checkpoint changes are collected after scheduling failures are
processed.

Surviving replicas keep serving, but a small deployment can still lose
all old replicas before reaching the threshold. Set
`RAY_SERVE_STOP_FAILED_ROLLING_UPDATES=0` to disable this behavior.

## Tests

Coverage includes startup and health failures, gang failure accounting,
controller recovery, autoscaling, the environment setting, stale
constructor-error cleanup, and successful recovery after a changed
deploy. Actor-creation and placement-group-creation regression cases
both failed before the checkpoint fix and pass afterward; they recover
directly from the threshold-reaching tick's checkpoint and verify the
rollout remains stopped.

Ran locally in the Python 3.11 environment:

```text
python -m pytest python/ray/serve/tests/unit/test_deployment_state.py python/ray/serve/tests/unit/test_application_state.py -q
400 passed

python -m pytest python/ray/serve/tests/test_deploy_app_2.py -q -k 'keeps_serving_from_old_replicas or flapping_rolling_update or survives_controller_restart'
4 passed, 24 deselected

pre-commit run --files python/ray/serve/_private/deployment_state.py python/ray/serve/tests/unit/test_deployment_state.py python/ray/serve/tests/test_deploy_app_2.py python/ray/serve/tests/BUILD.bazel
Passed
```

Duplicate checks found no overlapping fix; #66267 adds complementary
surge support. Claude Code assisted with implementation.

---------

Signed-off-by: Qisheng He <[email protected]>
@qishengxhe
qishengxhe force-pushed the serve/inplace-3-config-overrides-from-build branch from 28fe00c to ec1aeea Compare September 23, 2026 18:48
Base automatically changed from serve/inplace-3-config-overrides-from-build to master September 24, 2026 05:12
Rolling updates stop a batch of old replicas and start their replacements in
the same tick, so every update dips capacity by one batch until the
replacements are RUNNING. A new per-deployment `max_surge_percent`
(default 0, lightweight) lets `ceil(max_surge_percent / 100 * target)` extra
replicas run during a rolling update that restarts replicas:

- replacements are started first, filling the room below `target + surge`
  left by every live replica (old, RECOVERING, new RUNNING or starting) and
  never exceeding the target on the new version;
- old replicas are stopped by version, one rollout batch per tick, only once
  enough new-version replicas are RUNNING to keep `target` running, so the
  running count never dips below the target and a new version that never
  starts leaves every old replica in place; replacements that cannot be
  placed wait;
- the same start budget feeds gang placement group reservation, which
  otherwise uses the ordinary deficit (zero at target, so a replacement gang
  would never be reserved); the surge is rounded up to a whole gang and
  replicas are started in whole gangs;
- old RECOVERING replicas count against the room but are never stopped, and
  while replicas are recovering (their versions unknown) no downscale is
  issued so a controller restart mid-surge keeps the old replicas;
- with 0 or for reconfigure-only updates the existing stop-before-start path
  runs unchanged; `rolling_update_percentage` still bounds the batch.

The field is plumbed through `DeploymentConfig`, the proto (new
`max_surge_percent` field; older controllers fall back to 0), the
deployment schema, `@serve.deployment` and the schema conversions.

Tests: unit tests for start-before-stop, a failed version keeping every old
replica, unplaceable replacements waiting, autoscale-down mid-surge stopping
old replicas first, gang reservation at target, recovery during a surge,
zero surge and reconfigure keeping the existing path, and the proto round
trip. Integration test with traffic: a surge update whose new version never
starts keeps all three old replicas serving, and re-deploying the previous
config reuses them without a restart.

Signed-off-by: Qisheng He <[email protected]>
@qishengxhe
qishengxhe force-pushed the serve/inplace-4-max-surge-percent branch from b92f9fc to d9366c1 Compare September 24, 2026 06:42
@qishengxhe
qishengxhe marked this pull request as draft September 24, 2026 07:18
Only RUNNING replicas justify stopping an old replica during a surge
rollout; old replicas that never started stop for free. Fold the surge
branch into the regular scale path and add end-to-end coverage for
start-before-stop, failure with rollback, multi-app, autoscaling, gang and
capacity-starved rollouts with traffic running throughout.

Signed-off-by: qishengxhe <[email protected]>
@abrarsheikh

Copy link
Copy Markdown
Contributor

That's right. the new replica initializes with rank=1, world_size=1, as the old replica still holds rank 0. after the rollout completes, the new replica is reassigned rank 0. I updated the documentation and covered it in a test.

The surge rank limitation is now documented and tested. Please also update the replica-ranks guide, which still describes global ranks as 0 through N−1. Applications using rank to index a world-size-sized structure need this exception documented there.

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

could you also add a test for how deployment-scoped actor should behave with surge.

reserved = ray.util.placement_group([{"CPU": 1}] * 16)
ray.get(reserved.ready())

def running_max_ongoing_requests() -> Dict[int, int]:

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.

This checks the controller’s recorded configuration. Please also exercise user_config through a replica’s reconfigure() method and read the applied value from that replica after rollout completion, retaining the PID assertion.

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.

added unit and e2e coverage for deployment-scoped actor during surge: replacements wait for the new actors, old actors stay alive until their replicas stop, and actor startup failure preserves the serving version. rollback checks both replica id and actor id for reuse.

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.

also updated the test for reconfigure() behaviour

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 10, 2026
…gure

- Replica-ranks guide: ranks are contiguous once the deployment is
  HEALTHY; with max_surge_percent a replacement can initialize with a
  rank at or above world_size until the rollout converges.
- Capacity-blocked rollout test: carry a user_config in the lightweight
  change and read it back through the replica's reconfigure(), keeping
  the pid assertion.
- Deployment-scoped actors: e2e and unit tests cover replacements
  waiting for the new version's actors, old actors living until their
  last replica stops, a failing actor version changing no replica, and
  rollback reusing the same replicas and actor.
- Test helpers wait out the app rebuild window before reading details.

Signed-off-by: qishengxhe <[email protected]>
@qishengxhe
qishengxhe requested review from a team as code owners October 13, 2026 17:45
@qishengxhe

Copy link
Copy Markdown
Contributor Author

The surge rank limitation is now documented and tested. Please also update the replica-ranks guide, which still describes global ranks as 0 through N−1. Applications using rank to index a world-size-sized structure need this exception documented there.

updated the guide to document this exception for in-place updates with max_surge_percent > 0. Service rollout behaviour remains unchanged.

@abrarsheikh
abrarsheikh enabled auto-merge (squash) October 13, 2026 19:30
@github-actions
github-actions Bot disabled auto-merge October 14, 2026 23:23
@qishengxhe

Copy link
Copy Markdown
Contributor Author

split surge related e2e test cases into test_deploy_app_3.py to fix bazel test target timeout on test_deploy_app_2.py

The capacity-blocked surge test read the applied user_config by sending
handle requests until one landed on a specific replica. In the gRPC test
job the router's cached queue length for the replacement replica can stay
at 1 while the others read 0, so power-of-two never picks it within the
attempt budget. Record (pid, user_config) in an accumulator actor from
reconfigure() and read it back directly.

Signed-off-by: qishengxhe <[email protected]>
The autoscaler can overshoot from four to five replicas on noisy metrics
while requests move from the handle to the replicas. Capturing the old
pids while a fifth replica is still starting made the HAProxy job fail
when it became RUNNING. Wait for the target and running count to both
reach four first.

Signed-off-by: qishengxhe <[email protected]>
@abrarsheikh
abrarsheikh merged commit 9491664 into master Oct 15, 2026
6 checks passed
@abrarsheikh
abrarsheikh deleted the serve/inplace-4-max-surge-percent branch October 15, 2026 21:08
sai-miduthuri pushed a commit that referenced this pull request Oct 16, 2026
…rcent` for start-before-stop rolling updates (#66267) (#67094)

Cherry-pick of #66267 (master commit
9491664) onto `releases/2.60.0`.

## Why

The first three PRs of the in-place-updates series (#66252, #66290,
#66266) are already on `releases/2.60.0`. This picks the fourth, which
adds `max_surge_percent` for start-before-stop rolling updates, so
2.60.0 ships the complete series.

## Cherry-pick details

`git cherry-pick -x` conflicted in one file,
`python/ray/serve/tests/unit/test_deployment_state.py`. The conflict was
positional only: on master, #66243 (push-based replica health) had
appended `TestPushedHealthEndToEnd` and related tests to the end of that
file, and #66267 inserts `TestMaxSurge` right before them. This branch
doesn't have #66243, so git couldn't anchor the hunk and offered the
#66243 tests as part of the incoming side. Resolved by inserting only
the PR's `TestMaxSurge` block (plus its `defaultdict` import) before the
`__main__` guard. The added and removed lines in each of the 17 files
are identical to the master commit's diff.

After the pick, 11 of the 17 files are byte-identical to master at
9491664. The other 6 differ only by master commits that aren't on
this branch and that #66267 doesn't depend on:

- `_private/deployment_state.py`, `tests/unit/test_deployment_state.py`:
#66243.
- `schema.py`, `tests/BUILD.bazel`, `tests/test_controller.py`,
`tests/test_direct_ingress.py`: #66339 and #66940.

No commit on `releases/2.60.0` after the branch cut touched any of these
files.

Not a duplicate: no PR against `releases/2.60.0` references #66267.

## Testing

Run on this branch with the Serve protobuf regenerated from the branch's
`serve.proto` (the pick adds the `max_surge_percent` field).

```
python -m pytest python/ray/serve/tests/unit/test_deployment_state.py python/ray/serve/tests/unit/test_config.py python/ray/serve/tests/unit/test_deployment_class.py python/ray/serve/tests/unit/test_schema.py
3530 passed, 12 skipped
```

```
python -m pytest python/ray/serve/tests/test_deploy_app_3.py python/ray/serve/tests/test_deploy_app_2.py -k surge
13 passed, 41 deselected in 282s
```

`pre-commit run --files <changed files>` passed.

AI assistance was used to prepare this cherry-pick.

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

Signed-off-by: Qisheng He <[email protected]>
Signed-off-by: qishengxhe <[email protected]>
wanadzhar913 added a commit to wanadzhar913/ray that referenced this pull request Oct 19, 2026
Add Args entries for prefer_local_node_routing and
prefer_local_az_routing so public API param coverage and pydoclint
match the existing options() parameters. In response to ray-project#66267

Signed-off-by: wanadzhar913 <[email protected]>
jeffreywang88 pushed a commit that referenced this pull request Oct 20, 2026
`test_deploy_app_3` (added in #66267) flakes on the HAProxy, gRPC and
flaky-tests shards. One commit per cause:

- Two waits read replica counts and pids in separate calls, so a replica
changing state in between could pass for the state they wait for. They
now read one snapshot, as #67163 does for the same race in
`test_deploy_app_2`.
- The HAProxy shard's 0.01s drain lets a stopping replica close
connections HAProxy still uses. The traffic tests whose replicas stop
during a rollout now use the 5s drain `test_deploy_app_2` already uses;
the gang test is left out, since gang replicas are force-stopped.
- Under direct ingress, a request moving from the handle to a replica
can briefly count twice, which raised the autoscaling target in
`test_surge_rolling_update_follows_autoscaling_mid_rollout`. A 2s
upscale delay filters it.
- Two waits that ran close to their limit under load get more room.

Tested with `pytest python/ray/serve/tests/test_deploy_app_3.py` under
the default and HAProxy shard environments with CPU stressors: 13 of 13
in each at the final commit.

---------

Signed-off-by: john.taylor <[email protected]>
Co-authored-by: Claude <[email protected]>
wanadzhar913 added a commit to wanadzhar913/ray that referenced this pull request Oct 26, 2026
Add Args entries for prefer_local_node_routing and
prefer_local_az_routing so public API param coverage and pydoclint
match the existing options() parameters. In response to ray-project#66267

Signed-off-by: wanadzhar913 <[email protected]>
qishengxhe pushed a commit to qishengxhe/ray that referenced this pull request Oct 26, 2026
…7165)

`test_deploy_app_3` (added in ray-project#66267) flakes on the HAProxy, gRPC and
flaky-tests shards. One commit per cause:

- Two waits read replica counts and pids in separate calls, so a replica
changing state in between could pass for the state they wait for. They
now read one snapshot, as ray-project#67163 does for the same race in
`test_deploy_app_2`.
- The HAProxy shard's 0.01s drain lets a stopping replica close
connections HAProxy still uses. The traffic tests whose replicas stop
during a rollout now use the 5s drain `test_deploy_app_2` already uses;
the gang test is left out, since gang replicas are force-stopped.
- Under direct ingress, a request moving from the handle to a replica
can briefly count twice, which raised the autoscaling target in
`test_surge_rolling_update_follows_autoscaling_mid_rollout`. A 2s
upscale delay filters it.
- Two waits that ran close to their limit under load get more room.

Tested with `pytest python/ray/serve/tests/test_deploy_app_3.py` under
the default and HAProxy shard environments with CPU stressors: 13 of 13
in each at the final commit.

---------

Signed-off-by: john.taylor <[email protected]>
Co-authored-by: Claude <[email protected]>
(cherry picked from commit b2ca380)
Signed-off-by: qishengxhe <[email protected]>
wanadzhar913 added a commit to wanadzhar913/ray that referenced this pull request Oct 26, 2026
Add Args entries for prefer_local_node_routing and
prefer_local_az_routing so public API param coverage and pydoclint
match the existing options() parameters. In response to ray-project#66267

Signed-off-by: wanadzhar913 <[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 serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants