Skip to content

[Serve][1/2] Add per-deployment prefer_local_node_routing and prefer_local_az_routing options (wiring only) - #63629

Open
wanadzhar913 wants to merge 16 commits into
ray-project:masterfrom
wanadzhar913:bugfix/replace-locality-routing-59929
Open

wanadzhar913 wants to merge 16 commits into
ray-project:masterfrom
wanadzhar913:bugfix/replace-locality-routing-59929

Conversation

@wanadzhar913

@wanadzhar913 wanadzhar913 commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR is part of a migration from env-var-only control to per-deployment control without breaking current users. We mainly focus on the wiring aspects in this PR.

*NOTE: The added fields have no routing effect until #66580 lands.

What this changes:

  • Adds deployment-level configs for:
    • prefer_local_node_routing
    • prefer_local_az_routing
  • Precedence is:
    • Explicit deployment config value > env var fallback > existing default behavior
  • Adds protobuf schema fields for these deployment config options so config serialization/deserialization remains consistent
  • Adds unit tests

Related issues

Additional information

Testing:

python3 -m pytest python/ray/serve/tests/unit/test_application_state.py \
    python/ray/serve/tests/unit/test_schema.py \
    python/ray/serve/tests/test_controller.py::test_get_serve_instance_details_json_serializable \
    python/ray/serve/tests/test_direct_ingress.py::test_get_serve_instance_details_json_serializable \
    python/ray/serve/tests/test_cli.py -k locality \
    python/ray/serve/tests/unit/test_deployment_version.py::test_prefer_local_routing_flags_are_lightweight \
    python/ray/serve/tests/unit/test_deployment_state.py -k locality \
    python/ray/serve/tests/unit/test_deployment_class.py::TestDeploymentOptions::test_options_locality_routing \
    python/ray/serve/tests/unit/test_deployment_class.py::TestDeploymentOptions::test_decorator_locality_routing \
    python/ray/serve/tests/unit/test_deployment_class.py::TestDeploymentOptions::test_typed_options_match_deployment_signature -v

AI Assistance

  • Used Cursor + Opus 5 + Grok 4.6

@wanadzhar913
wanadzhar913 requested a review from a team as a code owner May 25, 2026 15:15
@wanadzhar913 wanadzhar913 changed the title fix: initial commit for https://github.com/ray-project/ray/issues/59929 [Serve] (cont.) add locality routing vars to deploy options and prioritize them over env May 25, 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 prefer_local_node_routing and prefer_local_az_routing as per-deployment configuration options, allowing for more granular control over locality-aware routing in Ray Serve. The changes span the public API, configuration schemas, and internal routing logic, including support for runtime updates. Review feedback suggests making the deprecation warnings for the legacy environment variables conditional to avoid unnecessary noise for migrated users. Additionally, it was noted that AsyncioRouter should consistently receive both locality parameters as constructor arguments rather than relying on global constants for initialization.

Comment thread python/ray/serve/api.py Outdated
Comment on lines +665 to +672
if "RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING" in os.environ:
warnings.warn(
"The environment variable 'RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING' "
"is deprecated and will be removed in a future release. "
"Please use 'prefer_local_node_routing' in @serve.deployment instead.",
DeprecationWarning,
stacklevel=2,
)

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.

medium

The deprecation warning for RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING is issued whenever @serve.deployment is called, even if the user has explicitly provided the new prefer_local_node_routing parameter. This can be noisy and misleading. The warning should only be triggered if the environment variable is set and the user has NOT provided the explicit parameter.

    # check for deprecated environment variable usage
    if (
        prefer_local_node_routing is DEFAULT.VALUE
        and "RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING" in os.environ
    ):
        warnings.warn(
            "The environment variable 'RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING' "
            "is deprecated and will be removed in a future release. "
            "Please use 'prefer_local_node_routing' in @serve.deployment instead.",
            DeprecationWarning,
            stacklevel=2,
        )

Comment thread python/ray/serve/api.py Outdated
Comment on lines +675 to +682
if "RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING" in os.environ:
warnings.warn(
"The environment variable 'RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING' "
"is deprecated and will be removed in a future release. "
"Please use 'prefer_local_az_routing' in @serve.deployment instead.",
DeprecationWarning,
stacklevel=2,
)

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.

medium

Similar to the node routing warning, this deprecation warning for RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING should be conditional on the prefer_local_az_routing parameter being unset to avoid unnecessary warnings for users who have already migrated.

Suggested change
if "RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING" in os.environ:
warnings.warn(
"The environment variable 'RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING' "
"is deprecated and will be removed in a future release. "
"Please use 'prefer_local_az_routing' in @serve.deployment instead.",
DeprecationWarning,
stacklevel=2,
)
# check for deprecated environment variable usage
if (
prefer_local_az_routing is DEFAULT.VALUE
and "RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING" in os.environ
):
warnings.warn(
"The environment variable 'RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING' "
"is deprecated and will be removed in a future release. "
"Please use 'prefer_local_az_routing' in @serve.deployment instead.",
DeprecationWarning,
stacklevel=2,
)

Comment thread python/ray/serve/_private/router.py Outdated
@@ -648,6 +649,7 @@ def __init__(
self._node_id = node_id
self._availability_zone = availability_zone
self._prefer_local_node_routing = prefer_local_node_routing
self._prefer_local_az_routing = RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING

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.

medium

There is an inconsistency in how locality routing parameters are initialized in AsyncioRouter.__init__. While _prefer_local_node_routing is passed as an argument (presumably from the deployment configuration), _prefer_local_az_routing is initialized directly from the environment variable constant. For consistency and to ensure the router starts with the correct per-deployment configuration, prefer_local_az_routing should also be passed as a constructor argument.

Comment thread src/ray/protobuf/serve.proto Resolved
Comment thread python/ray/serve/_private/router.py Outdated
@@ -648,6 +649,7 @@ def __init__(
self._node_id = node_id
self._availability_zone = availability_zone
self._prefer_local_node_routing = prefer_local_node_routing
self._prefer_local_az_routing = RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AZ routing parameter ignored at AsyncioRouter init

Medium Severity

self._prefer_local_az_routing is hardcoded to the env var RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING in AsyncioRouter.__init__, while self._prefer_local_node_routing is set from a constructor parameter. This asymmetry means there's no way to control prefer_local_az_routing at init time. If the request router is lazily created before update_deployment_config fires (e.g., triggered by update_deployment_targets arriving first via LongPoll), it will always use the env var value for AZ routing, ignoring any per-deployment intent. Adding a prefer_local_az_routing parameter — matching the pattern for prefer_local_node_routing — would close this gap.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e5040d48390a4ee075dc0e98b7def0b2fd88a5a2. Configure here.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels May 25, 2026
@wanadzhar913
wanadzhar913 marked this pull request as draft May 26, 2026 13:50
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch 3 times, most recently from 26261ea to 8e1d923 Compare May 27, 2026 05:55
@wanadzhar913
wanadzhar913 marked this pull request as ready for review May 27, 2026 06:02
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 8e1d923 to c473f1f Compare May 28, 2026 13:39
@wanadzhar913

Copy link
Copy Markdown
Contributor Author

Hi @harshit-anyscale, appreciate if you could review this. Thanks so much!

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from c473f1f to 116dcb8 Compare June 4, 2026 15:29

@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 python/ray/serve/api.py Resolved
Comment thread python/ray/serve/api.py Outdated
)

# check for deprecated environment variable usage
if "RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING" in os.environ:

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.

i dont think we need to deprecate it necessarily, there is still a use case for this. Env vars can be used as a default that globally applies to all deployments, if a deployment level config is specified, then we honor that instead.

Comment thread python/ray/serve/api.py Outdated
)

# check for deprecated environment variable usage
if "RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING" in os.environ:

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.

same comment here, we dont need to deprecate the env var

from ray.serve.context import _get_global_client
from ray.tests.conftest import * # noqa
from ray.util.placement_group import get_current_placement_group, placement_group_table
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy

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.

the code refactors in this file are a nice touch, but those are independent of the primary changes proposed in this PR. I recommend taking these up in a separate PR.


# Scale up to 3 replicas (1 head + 2 worker), then back down to 1.
self._wait_for_upscale(
self._wait_until_running_replicas(

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.

same comment: prefer to make code refactor in a separate PR.

Comment thread python/ray/serve/_private/config.py Resolved
Comment thread python/ray/serve/_private/config.py Outdated
)

prefer_local_az_routing: bool = Field(
default=True,

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.

use the env var as default

pull Bot pushed a commit to Stars1233/fairchem that referenced this pull request Jun 17, 2026
Three small changes to the ray serve deployment. 

This PR
1. By default local node routing is used for ingress via the http proxy,
but not when using deployment handles. This PR tells the handle to
prefer local routing so that inference stays within nodes when possible
2. The atoms info validation requires a roundtrip to the model inference
server. We can instead cache the validated atoms info objects.
3. Add timeouts (default 10min, controlled by environment variable
`FAIRCHEM_BATCH_SERVER_TIMEOUT_S`) to all of the .request() calls so
that an indefinite hang (eg inference request when a server doesn't have
enough resources to start inference service) eventually throws an error

Related to ray-project/ray#63629
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch 2 times, most recently from 92c8d34 to 5c2551d Compare June 24, 2026 00:25
@wanadzhar913

wanadzhar913 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @abrarsheikh! I've addressed the comments you've made.

However, as expected, there's several CI failures. I'm not too sure if the core: dashboard tests failures are due to this PR, but the likely cause of the serve: tests failures are due to locality routing being enabled causing regressions in:

  • test_gang_scheduling.py* (handle.remote() only routes to local replicas, so you see 1 instead of 2–3); &
  • test_deployment_scheduler_downscale.py (locality routing keeps hitting the same local replica, so it never reaches 3 and times out.).

*From buildkite CI, all failures are only due to test_gang_scheduling.py. Will investigate.

Here's some logs from my local run:

Partial logs from local PyTest run

Tests I ran:

pytest python/ray/serve/tests/test_gang_scheduling.py \
    python/ray/serve/tests/unit/test_pow_2_request_router.py \
    python/ray/serve/tests/unit/test_router.py \
    python/ray/serve/tests/test_deployment_scheduler_downscale.py -q

Output:

================================= short test summary info =================================
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangScheduling::test_incomplete_deployment - AssertionError: assert 1 == 3
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangScheduling::test_gang_scheduling_spread_strategy - AssertionError: assert 1 == 2
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangScaling::test_scale_gang_boundary[4-2] - AssertionError: assert 1 == 2
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangScaling::test_scale_gang_boundary[8-4] - AssertionError: assert 2 == 4
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangScaling::test_scale_gang_boundary[4-8] - AssertionError: assert 1 == 2
FAILED python/ray/serve/tests/test_gang_scheduling.py::TestGangMigration::test_gang_migration - AssertionError: assert 1 == 2
FAILED python/ray/serve/tests/test_deployment_scheduler_downscale.py::TestScaleDownReplicaSelection::test_downscale_prefers_not_head_node - RuntimeError: The condition wasn't met before the timeout expired.

Results (802.74s):
     256 passed
       7 failed
         - python/ray/serve/tests/test_gang_scheduling.py:96 TestGangScheduling.test_incomplete_deployment
         - python/ray/serve/tests/test_gang_scheduling.py:279 TestGangScheduling.test_gang_scheduling_spread_strategy
         - python/ray/serve/tests/test_gang_scheduling.py:1437 TestGangScaling.test_scale_gang_boundary[4-2]
         - python/ray/serve/tests/test_gang_scheduling.py:1437 TestGangScaling.test_scale_gang_boundary[8-4]
         - python/ray/serve/tests/test_gang_scheduling.py:1437 TestGangScaling.test_scale_gang_boundary[4-8]
         - python/ray/serve/tests/test_gang_scheduling.py:1899 TestGangMigration.test_gang_migration
         - python/ray/serve/tests/test_deployment_scheduler_downscale.py:222 TestScaleDownReplicaSelection.test_downscale_prefers_not_head_node
Task was destroyed but it is pending!
task: <Task pending name='Task-40449' coro=<RouterMetricsManager._report_cached_metrics_forever() running at /home/faiq0913/open_source/ray/python/ray/serve/_private/router.py:359>>
sys:1: RuntimeWarning: coroutine 'RouterMetricsManager._report_cached_metrics_forever' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

As per your comments, the next step should be to:

  1. Create another issue/PR regarding the above regressions
  2. Get that approved
  3. Work on getting this PR approved?

Let me know if that works!

@wanadzhar913
wanadzhar913 requested a review from abrarsheikh June 24, 2026 05:12
abrarsheikh added a commit to wanadzhar913/ray that referenced this pull request Jul 5, 2026
test_gang_context inferred gang membership by looping up to 100
handle.remote() calls until it observed all 4 replicas. Under
locality-aware routing (parameterized in ray-project#63629) this loop only hits
local replicas and never sees all gangs, so it would undercount like the
other handle-based placement checks this PR converts.

Read the GangContext from controller replica state instead. The
controller stores the exact GangContext each replica reports from its
own ReplicaContext (round-tripped via initialize_and_get_metadata), so
this verifies the same values deterministically without depending on
request routing.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
abrarsheikh added a commit to wanadzhar913/ray that referenced this pull request Jul 6, 2026
test_gang_context inferred gang membership by looping up to 100
handle.remote() calls until it observed all 4 replicas. Under
locality-aware routing (parameterized in ray-project#63629) this loop only hits
local replicas and never sees all gangs, so it would undercount like the
other handle-based placement checks this PR converts.

Read the GangContext from controller replica state instead. The
controller stores the exact GangContext each replica reports from its
own ReplicaContext (round-tripped via initialize_and_get_metadata), so
this verifies the same values deterministically without depending on
request routing.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: abrar <[email protected]>
abrarsheikh added a commit that referenced this pull request Jul 9, 2026
#64345)

## Summary

Several gang scheduling tests inferred replica placement by issuing
repeated
`DeploymentHandle` calls and counting the distinct nodes / gangs /
replicas
observed in the responses. Request routing is not a scheduler-state API:
with
locality-aware routing (added per-deployment and parameterized in
#63629),
repeated calls may legitimately prefer local replicas, so these tests
can
undercount nodes, gangs, or replicas even when scheduler state is
correct.

This PR makes the tests read placement directly from controller replica
state
instead of inferring it from handle responses.

## Changes

In `test_gang_scheduling.py`:
- Add helpers to read RUNNING replicas (and their node / gang IDs) from
  controller state.
- Verify placement via controller state in `test_incomplete_deployment`,
  `test_gang_scheduling_spread_strategy`, `test_gang_context`,
  `test_scale_gang_boundary`, and `test_gang_migration`.
- Keep handle calls where the test checks request serving or
zero-downtime, and
add comments documenting the remaining handle-based loops that are safe
under
  locality routing (PACK / placement-group invariant checks, single-node
  discovery).

Note: the originally-planned `test_deployment_scheduler_downscale.py`
change was
dropped — #64325 already converted that test to controller-state waiting
on
master.

## Related issues
- Related to #59929
- Depends on / unblocks #63629

## Tests

```bash
pytest python/ray/serve/tests/test_gang_scheduling.py -q
```

---------

Signed-off-by: wanadzhar913 <[email protected]>
Signed-off-by: abrar <[email protected]>
Co-authored-by: abrar <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 3ce21f3 to 3098893 Compare July 13, 2026 04:39
@wanadzhar913

wanadzhar913 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @abrarsheikh & @jeffreywang88, appreciate if you could review this when you have time. Tysm!

Now that, #64345 has landed, all the previous failed tests in test_gang_scheduling.py (impacted by locality routing enablement) pass. Have also fixed some merge conflicts.

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from be9e95d to eaae5ac Compare August 12, 2026 09:57
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
ray-project#64345)

## Summary

Several gang scheduling tests inferred replica placement by issuing
repeated
`DeploymentHandle` calls and counting the distinct nodes / gangs /
replicas
observed in the responses. Request routing is not a scheduler-state API:
with
locality-aware routing (added per-deployment and parameterized in
ray-project#63629),
repeated calls may legitimately prefer local replicas, so these tests
can
undercount nodes, gangs, or replicas even when scheduler state is
correct.

This PR makes the tests read placement directly from controller replica
state
instead of inferring it from handle responses.

## Changes

In `test_gang_scheduling.py`:
- Add helpers to read RUNNING replicas (and their node / gang IDs) from
  controller state.
- Verify placement via controller state in `test_incomplete_deployment`,
  `test_gang_scheduling_spread_strategy`, `test_gang_context`,
  `test_scale_gang_boundary`, and `test_gang_migration`.
- Keep handle calls where the test checks request serving or
zero-downtime, and
add comments documenting the remaining handle-based loops that are safe
under
  locality routing (PACK / placement-group invariant checks, single-node
  discovery).

Note: the originally-planned `test_deployment_scheduler_downscale.py`
change was
dropped — ray-project#64325 already converted that test to controller-state waiting
on
master.

## Related issues
- Related to ray-project#59929
- Depends on / unblocks ray-project#63629

## Tests

```bash
pytest python/ray/serve/tests/test_gang_scheduling.py -q
```

---------

Signed-off-by: wanadzhar913 <[email protected]>
Signed-off-by: abrar <[email protected]>
Co-authored-by: abrar <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>

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

please add this test and ignore if it already exists or will be added in a follow-up:

  • setting prefer_local_node_routing / prefer_local_az_routing in @serve.deployment

Comment thread python/ray/serve/_private/config.py Outdated
Comment on lines +168 to +172
prefer_local_node_routing: Feature flag to turn on node locality
routing. Applies to both proxy-to-replica and replica-to-replica
routing. Defaults to the value of
``RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING`` (on by default).
Explicit deployment config overrides the env var.

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.

Suggested change
prefer_local_node_routing: Feature flag to turn on node locality
routing. Applies to both proxy-to-replica and replica-to-replica
routing. Defaults to the value of
``RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING`` (on by default).
Explicit deployment config overrides the env var.
prefer_local_node_routing: Prefer routing requests to replicas on
the same node as the caller. Applies to both proxy-to-replica and
replica-to-replica routing. Defaults to the value of
``RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING`` (on by default).
Explicit deployment config overrides the env var.

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.

similarly for prefer_local_az_routing below

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.

it isn't on by default for inter-deployment handle:

_prefer_local_routing: bool = False

only proxy handles override it with the env var:

_prefer_local_routing=RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING,

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.

Aah okay, thank you for pointing this out. I've replaced with this:

-        prefer_local_node_routing: Feature flag to turn on node locality
-            routing. Applies to both proxy-to-replica and replica-to-replica
-            routing. Defaults to the value of
-            ``RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING`` (on by default).
-            Explicit deployment config overrides the env var.
+        prefer_local_node_routing: Prefer routing requests to replicas on
+            the same node as the caller. Applies to both proxy-to-replica and
+            replica-to-replica routing. The default differs by caller: proxy
+            handles default to ``RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING``
+            (on by default), while inter-deployment handles default to off.
+            An explicit value overrides both defaults.

f = f.options(**options)
assert f._deployment_config.user_configured_option_names == set(options.keys())

def test_options_prefer_local_node_routing_false(self):

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.

let's parametrize this test to validate (prefer_local_node_routing, prefer_local_az_routing) x (True, False)

Comment thread python/ray/serve/api.py Outdated
rolling_update_percentage: The fraction of replicas to update at a
time during a rolling update. Must be in ``(0.0, 1.0]``.
Defaults to ``0.2`` (20%).
prefer_local_node_routing: Feature flag to turn on node locality routing.

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.

same here: describe what this does instead of calling it a feature flag

config_key = (LongPollNamespace.DEPLOYMENT_CONFIG, TEST_DEPLOYMENT_ID)
assert config_key in notified
assert getattr(notified[config_key], field_name) == new_value

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.

proceed the state machine dsm until it reaches a healthy state to verify there's no regression in the reconciliation loop

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from a170207 to 7a029b2 Compare October 2, 2026 11:16
@wanadzhar913

wanadzhar913 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

please add this test and ignore if it already exists or will be added in a follow-up:

  • setting prefer_local_node_routing / prefer_local_az_routing in @serve.deployment

Hi @jeffreywang88, yeahp, I've implemented this here: python/ray/serve/tests/unit/test_deployment_class.py::TestDeploymentOptions::test_decorator_locality_routing. I've also addressed your feedback. Thanks so much!

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 7a029b2 to 2fb4036 Compare October 2, 2026 18:44
@wanadzhar913

Copy link
Copy Markdown
Contributor Author

Hi @jeffreywang88, gentle bump on the wiring PR. Tysm for your time. 🙏🏻

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 2fb4036 to 13b7582 Compare October 19, 2026 12:22
@wanadzhar913 wanadzhar913 changed the title [Serve][1/2] Wiring: Add locality routing vars to deploy deployment config, protobuf, YAML, etc. [Serve][1/2] Add per-deployment prefer_local_node_routing and prefer_local_az_routing options (wiring only) Oct 25, 2026
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 5d6ac23 to 25714df Compare October 26, 2026 13:29
@wanadzhar913

wanadzhar913 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @jeffreywang88 / @abrarsheikh gentle bump on the wiring PR. Tysm for your time. 🙏🏻*

@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch 2 times, most recently from dff18a7 to 86e595f Compare October 27, 2026 16:16
@wanadzhar913

Copy link
Copy Markdown
Contributor Author

Hi @jeffreywang88 / @abrarsheikh gentle bump on the wiring PR. Tysm for your time. 🙏🏻

wanadzhar913 and others added 16 commits November 19, 2026 23:30
Two premerge failures from 7af4332 ("Add locality routing options to
DeploymentSchema/Deployment").

1. lint-api-param-coverage requires an Args: entry for every new
   parameter on a @publicapi callable. Adding one to
   Deployment.options() ends that docstring's pydoclint "short
   docstring" exemption, which then demands all 26 parameters plus a
   Returns section -- duplicating the @serve.deployment docs the
   docstring deliberately delegates to. The repo has an empty pydoclint
   baseline and no "# noqa: DOC" suppressions, so neither escape hatch
   is available without adding new lint debt. Drop the two options from
   Deployment.options() instead, matching rolling_update_percentage,
   which is likewise in DeploymentConfig and DeploymentSchema but
   intentionally absent from options().

2. test_get_serve_instance_details_json_serializable compares the whole
   details response against a golden dict that enumerates every
   deployment_config key. _deployment_info_to_schema now reports both
   options, so add them to the golden dicts in test_controller.py and
   test_direct_ingress.py. Both default to True via
   RAY_SERVE_PROXY_PREFER_LOCAL_{NODE,AZ}_ROUTING.

The DeploymentSchema fields and converters are unchanged: config files,
the REST API, and RayService serveConfigV2 can still set both options.

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
AsyncioRouter took prefer_local_node_routing as a constructor argument
but hardcoded self._prefer_local_az_routing to the
RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING env var. Because the request
router is created lazily, it can be constructed before the
DEPLOYMENT_CONFIG long poll fires (for example when
update_deployment_targets arrives first), in which case the AZ flag was
never controllable at init while the node flag was.

Make prefer_local_az_routing a required AsyncioRouter parameter,
sourced from a new InitHandleOptions._prefer_local_az_routing field
that defaults to the env var. create_router forwards it, and
get_proxy_handle passes it explicitly alongside the node flag.

Also drop the user_configured_option_names branching in
update_deployment_config. DeploymentConfig.prefer_local_node_routing
and prefer_local_az_routing already default to their respective env
vars, so both arms of each if/else assigned the same value. Read the
config fields directly, matching how the backoff params in the same
method are handled.

Tests:
- test_router.py: pass the new argument at every router construction
  site; cover a default DeploymentConfig (no user-configured names)
  still applying its field values, and a lazily created request router
  picking up the constructor AZ flag.
- test_handle_options.py: cover the new field's default and override.

Signed-off-by: wanadzhar913 <[email protected]>
…default and the router live in different processes. DeploymentConfig.prefer_local_*_routing defaults to the env var, but that default is evaluated once at import time in the process that builds the config (the driver), while the router runs in a proxy or replica process that imported the env var independently. Without the guard, the config's copy wins, which makes RAY_SERVE_PROXY_PREFER_LOCAL_*_ROUTING a no-op on every node except the one that built the config — that's what broke test_cluster.py::test_proxy_prefers_replicas_on_same_node[False], which sets the env var to 0 after the driver has already imported Serve so the proxy and driver legitimately disagree. The else keeps the intended precedence: explicit deployment config beats the env var, and an unconfigured deployment defers to the env var of the process actually doing the routing.

Signed-off-by: wanadzhar913 <[email protected]>
Two-node cluster with d1->d2, one replica of each per node. Asserts that
prefer_local_node_routing pins replica-to-replica traffic on-node, and
that flipping the flag off via a lightweight config update restores
spread routing.

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Drop router runtime wiring and related tests from this branch so PR 1
covers deployment config, schema, and protobuf only. Router behavior
lands in a stacked follow-up branch.

Signed-off-by: wanadzhar913 <[email protected]>
Add prefer_local_node_routing and prefer_local_az_routing to Deployment.options(), as requested in review. Previously the flags could be set through @serve.deployment and the config schema, but calling .options(prefer_local_node_routing=...) raised a TypeError.

This reverses the options() part of 1062bad, which removed the flags to satisfy the API param coverage lint.

Tests:
- Add both flags to TestDeploymentOptions.deployment_options. This covers the decorator, .options(), and user_configured_option_names after proto serialization.
- Add test_options_prefer_local_node_routing_false.

Signed-off-by: wanadzhar913 <[email protected]>
…zed over all four (prefer_local_node_routing, prefer_local_az_routing) combinations. - Builds a DeploymentConfig with both flags and user_configured_option_names set. - After to_proto(), asserts HasField on both optional bool fields and that values match (including explicit False). - Round-trips via to_proto_bytes() / from_proto_bytes() and checks flags and user_configured_option_names. test_prefer_local_routing_proto_unset_fields_use_defaults - Starts from a valid proto, ClearFields both locality fields (simulating an older sender). - Deserializes from bytes and asserts values equal RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING and RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, not proto3’s implicit False.

Signed-off-by: wanadzhar913 <[email protected]>
Deploy ray.serve.tests.test_config_files.pid.node through serve deploy
with prefer_local_node_routing=false and prefer_local_az_routing=true,
and check that serve details reports both in deployment_config. Then
redeploy with the values swapped and check that the details update
while the replica PID stays the same.

Giving the two flags different values, and flipping both, catches any
mix-up between the fields. It also confirms that changing them is a
lightweight update that doesn't restart the replica.

Signed-off-by: wanadzhar913 <[email protected]>
Add unit tests that flipping prefer_local_node_routing or
prefer_local_az_routing does not change DeploymentVersion equality or
trigger replica restart/reconfigure, while still broadcasting the updated
deployment config over long poll for routers.

Signed-off-by: wanadzhar913 <[email protected]>
… healthy state to verify there's no regression in the reconciliation loop

Signed-off-by: wanadzhar913 <[email protected]>
…test_options_locality_routing & test_decorator_locality_routing

Signed-off-by: wanadzhar913 <[email protected]>
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]>
ray-project#66513 typed the @serve.deployment overloads with a _DeploymentOptions
TypedDict and added test_typed_options_match_deployment_signature,
which checks that the TypedDict lists every keyword deployment()
takes. This branch added prefer_local_node_routing and
prefer_local_az_routing to deployment() but not to the TypedDict, so
the test fails after merging master. Type checkers would also reject
both options when passed to @serve.deployment(...).

Add both as Default[bool] fields, matching deployment()'s signature.
Also move the two options after max_surge_percent in DeploymentConfig
and Deployment.options() so they follow the same order as deployment().
In response to ray-project#66513

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
@wanadzhar913
wanadzhar913 force-pushed the bugfix/replace-locality-routing-59929 branch from 86e595f to e8e340d Compare November 19, 2026 15:42

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

community-contribution Contributed by the community 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.

3 participants