Skip to content

[Serve] Support a configurable port range for the inter-deployment gRPC server - #64623

Open
tobby168 wants to merge 1 commit into
ray-project:masterfrom
tobby168:serve-internal-grpc-port-range
Open

tobby168 wants to merge 1 commit into
ray-project:masterfrom
tobby168:serve-internal-grpc-port-range

Conversation

@tobby168

@tobby168 tobby168 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Each replica runs an inter-deployment gRPC server used for the handle path (proxy->replica and replica->replica calls) when gRPC is enabled by default (RAY_SERVE_USE_GRPC_BY_DEFAULT, auto-enabled by RAY_SERVE_THROUGHPUT_OPTIMIZED). It binds an OS-assigned ephemeral port via add_insecure_port("[::]:0") in replica.py.

Service meshes such as Istio only route ports that are declared on the pod, so calls to this undeclared ephemeral port are dropped / have their HTTP/2 stream reset. The result is that cross-node handle calls hang or time out when Serve runs behind a mesh.

This PR adds two env vars, RAY_SERVE_INTERNAL_GRPC_MIN_PORT and RAY_SERVE_INTERNAL_GRPC_MAX_PORT, so the server can bind within a bounded, mesh-declarable range — mirroring the existing RAY_SERVE_DIRECT_INGRESS_*_PORT knobs already used by the direct-ingress servers.

  • Backward compatible / opt-in: both default to 0, which keeps the current ephemeral behavior unchanged.
  • Distinct ports per replica: when a range is configured, the server is created with SO_REUSEPORT disabled (integer 0) so an already-used port is rejected and each replica on a node gets a distinct port. Note the integer 0 is required — the string "0" does not disable SO_REUSEPORT.
  • Binding logic is a small, unit-tested helper bind_grpc_port_in_range in grpc_util.py.

Related issue number

Checks

  • I've signed off every commit (-s) with the DCO.
  • pre-commit (ruff v0.8.4, black 22.10.0) passes on the changed files.
  • Added unit tests in python/ray/serve/tests/unit/test_bind_grpc_port.py (binds within range, skips occupied ports, raises when the range is exhausted, preserves the ephemeral default). The binding behavior — including the SO_REUSEPORT-off occupancy detection — was validated against real gRPC sync and grpc.aio servers.

🤖 Generated with Claude Code

@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 configurable port range for the inter-deployment gRPC server of Ray Serve replicas, enabling compatibility with service meshes like Istio. It adds a utility function to bind ports within a specified range, disables SO_REUSEPORT to prevent port conflicts, and includes comprehensive unit tests. The review feedback suggests using the get_env_int helper for environment variable parsing, validating the port range early during replica initialization to fail fast, and using "::" instead of "" for IPv6 socket binding in tests to improve portability.

Comment thread python/ray/serve/_private/constants.py Outdated
Comment on lines +977 to +982
RAY_SERVE_INTERNAL_GRPC_MIN_PORT = int(
os.environ.get("RAY_SERVE_INTERNAL_GRPC_MIN_PORT", "0")
)
RAY_SERVE_INTERNAL_GRPC_MAX_PORT = int(
os.environ.get("RAY_SERVE_INTERNAL_GRPC_MAX_PORT", "0")
)

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

For consistency with other environment variables in this file, use the get_env_int helper function instead of manually parsing with int(os.environ.get(...)).

Suggested change
RAY_SERVE_INTERNAL_GRPC_MIN_PORT = int(
os.environ.get("RAY_SERVE_INTERNAL_GRPC_MIN_PORT", "0")
)
RAY_SERVE_INTERNAL_GRPC_MAX_PORT = int(
os.environ.get("RAY_SERVE_INTERNAL_GRPC_MAX_PORT", "0")
)
RAY_SERVE_INTERNAL_GRPC_MIN_PORT = get_env_int(
"RAY_SERVE_INTERNAL_GRPC_MIN_PORT", 0
)
RAY_SERVE_INTERNAL_GRPC_MAX_PORT = get_env_int(
"RAY_SERVE_INTERNAL_GRPC_MAX_PORT", 0
)

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.

Done in 63ff7f3 — both now use get_env_int("...", 0) to match the rest of the file.

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines +1140 to +1145
if RAY_SERVE_INTERNAL_GRPC_MIN_PORT > 0:
# When binding within a fixed port range, disable SO_REUSEPORT so that a
# port already taken by another replica on this node is rejected, ensuring
# each replica gets a distinct, mesh-declarable port. Must be the integer
# 0 (the string "0" does not disable SO_REUSEPORT).
_internal_grpc_server_options.append(("grpc.so_reuseport", 0))

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

If RAY_SERVE_INTERNAL_GRPC_MIN_PORT is set to a positive value but RAY_SERVE_INTERNAL_GRPC_MAX_PORT is less than it, the configuration is invalid. It is better to validate this range and fail fast during replica initialization (__init__) rather than waiting until _on_initialized is called asynchronously.

        if RAY_SERVE_INTERNAL_GRPC_MIN_PORT > 0:
            if RAY_SERVE_INTERNAL_GRPC_MAX_PORT < RAY_SERVE_INTERNAL_GRPC_MIN_PORT:
                raise ValueError(
                    "Invalid inter-deployment gRPC port range: "
                    f"RAY_SERVE_INTERNAL_GRPC_MAX_PORT ({RAY_SERVE_INTERNAL_GRPC_MAX_PORT}) "
                    f"cannot be less than RAY_SERVE_INTERNAL_GRPC_MIN_PORT ({RAY_SERVE_INTERNAL_GRPC_MIN_PORT})."
                )
            # When binding within a fixed port range, disable SO_REUSEPORT so that a
            # port already taken by another replica on this node is rejected, ensuring
            # each replica gets a distinct, mesh-declarable port. Must be the integer
            # 0 (the string "0" does not disable SO_REUSEPORT).
            _internal_grpc_server_options.append(("grpc.so_reuseport", 0))

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.

Done in 63ff7f3 — added a fail-fast check in __init__ that raises when RAY_SERVE_INTERNAL_GRPC_MAX_PORT < RAY_SERVE_INTERNAL_GRPC_MIN_PORT. I kept the ValueError inside bind_grpc_port_in_range as well: that helper is a reusable, independently unit-tested util, so it validates its own contract; the __init__ check is the fail-fast guard.

Comment on lines +21 to +27
def _find_free_port() -> int:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
try:
s.bind(("", 0))
return s.getsockname()[1]
finally:
s.close()

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

Using "" as the bind address on an AF_INET6 socket can be non-portable or fail on some platforms. It is safer and more explicit to use "::" as the IPv6 wildcard address.

Suggested change
def _find_free_port() -> int:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
try:
s.bind(("", 0))
return s.getsockname()[1]
finally:
s.close()
def _find_free_port() -> int:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
try:
s.bind(("::", 0))
return s.getsockname()[1]
finally:
s.close()

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.

Done in 63ff7f3 — switched the bind to ("::", 0).

@tobby168
tobby168 force-pushed the serve-internal-grpc-port-range branch from fe0b57d to 63ff7f3 Compare July 9, 2026 03:54
@tobby168
tobby168 marked this pull request as ready for review July 15, 2026 19:56
@tobby168
tobby168 requested a review from a team as a code owner July 15, 2026 19:56
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Jul 16, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jul 30, 2026
@abrarsheikh

Copy link
Copy Markdown
Contributor
  1. can we leverage the node port manager for consistency.
  2. i dont think Backward compatible is necessary here since user facing behavior is not changing, best to use sane default here and have a single way of assigning ports.

@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 Jul 31, 2026
@tobby168

tobby168 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @abrarsheikh, and sorry for the slow turnaround. Both points are fair; I dug into what each would take and there's one design question I'd rather settle with you than guess at. There's also a third thing I found while looking, which needs fixing regardless of how you answer.

First: this PR currently regresses TLS

Not something you raised, but it's the most important item here. _on_initialized on master now binds via the shared helper:

# Use the shared helper so RAY_USE_TLS is honored; binding the port
# directly would leave this server plaintext in a TLS-enabled cluster.
self._internal_grpc_port = add_port_to_grpc_server(self._server, "[::]:0")

My bind_grpc_port_in_range calls server.add_insecure_port(...) directly, so with a port range configured the inter-deployment gRPC server would come up plaintext even with RAY_USE_TLS=1 — exactly what that comment is guarding against. That's a security regression, and it's mine; the helper landed after I opened this. Whatever shape the rest takes, the range bind has to go through add_port_to_grpc_server.

2. Dropping "backward compatible" — agreed

You're right that the dual path isn't earning its keep. I'll delete the min <= 0 → ephemeral branch and give the range a real default, matching how RAY_SERVE_DIRECT_INGRESS_* already works.

One consequence worth stating out loud before I pick numbers: an ephemeral bind has no practical ceiling on replicas per node, a bounded range does. Direct ingress already accepts that with 1000-port defaults (30000–31000, 40000–41000), and this server is per-replica just like those, so the same bound seems fine — but note this one exists on every replica, not just ingress ones, so it's the first place that ceiling would actually bind. I'd propose a third non-overlapping 1000-port window unless you want it sized differently.

1. Leveraging NodePortManager — yes, and here's the gap

The replica-side half is already there and I'd just be following it. _maybe_start_direct_ingress_servers does exactly the right thing at replica.py:2182: ask the controller for a port, try to bind, and on EADDRINUSE release it with block_port=True and retry. Reusing that for the internal server is straightforward, and it buys the same deterministic min-heap assignment — which for this PR isn't just consistency, it's the feature. The whole point is a mesh-declarable port, and NodePortManager's low-fragmentation determinism is precisely what makes a declared range predictable.

The gap is on the controller side. _maybe_update_ingress_ports is gated:

if self._direct_ingress_enabled:
    ...
    NodePortManager.update_ports(...)
    NodePortManager.prune(self._get_node_id_to_alive_replica_ids())

and its input, get_ingress_replicas_info(), filters on owns_direct_ingress_ports(). The internal gRPC server has neither property — _on_initialized starts it unconditionally for every replica, ingress or not. So allocating internal ports from NodePortManager without touching that loop leaves two holes:

  • Controller restart: recovering replicas' internal ports are never fed back via update_port_if_missing, so the allocator re-hands-out ports that are live.
  • Crashed replicas: prune never sees them, so their ports leak for the lifetime of the cluster.

Closing both is not hard — _internal_grpc_port already round-trips to the controller through _ready_obj_ref (deployment_state.py:1479) and is already stored per replica, so a sibling of get_ingress_replicas_info() without the owns_direct_ingress_ports() filter has the data. But it means the reconcile now runs for clusters that have direct ingress off, i.e. an O(replicas) scan per tick where today there is none. That's your loop and your perf budget, so:

The question: do you want the internal gRPC port managed by NodePortManager with the reconcile un-gated to cover all replicas (correct, consistent, costs the reconcile pass everywhere), or kept as a replica-local bind-scan (self-contained, no controller changes, but a second way of assigning ports — the thing you're trying to avoid)?

I'll implement whichever you prefer. My read is that you want the first, and I agree it's the better end state; I just don't want to un-gate a control-loop pass in your subsystem on my own judgment. If it helps, a middle option is gating the reconcile on "direct ingress enabled or a non-default internal range configured" — but that reintroduces conditional behavior, which is what point 2 was about, so I'd rather not unless you like it.

Also flagging: this branch has drifted (the TLS helper above, among other things), so I'll rebase as part of whichever direction we take rather than push a rebase now and make you re-read it twice.

For transparency: AI assistance was used in preparing this analysis and the patch.

@abrarsheikh

Copy link
Copy Markdown
Contributor
  1. rebase with master
  2. 1000 is fine, i have never seen a node host those many replicas
  3. let's try to implement the NodePort manager solution, then assess the complexity of the implementation.

@tobby168
tobby168 force-pushed the serve-internal-grpc-port-range branch from 542df67 to e2be534 Compare August 8, 2026 07:25
@tobby168

tobby168 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Done — rebased onto master and reimplemented on NodePortManager. Since you asked to assess the complexity afterwards, that's at the bottom.

The branch is now a single commit against current master. The old bind_grpc_port_in_range range-scan helper is gone entirely; the replica asks the controller for a port and binds that one, following _maybe_start_direct_ingress_servers exactly.

What it took

Replica — mirrors the direct-ingress pattern: ask the controller, try to bind, and on failure release with block_port=True and retry against a fresh port.

NodePortManager — a third PortAllocator alongside the HTTP and gRPC ones, reached through explicit allocate_internal_grpc_port / release_internal_grpc_port / update_internal_grpc_port_if_missing rather than the RequestProtocol dispatch. That enum is also a metrics tag dimension and this server carries no ingress traffic, so widening it seemed worse than three small methods; it also keeps the existing direct-ingress surface and its tests untouched.

Controller — this is the part that isn't free, and it's the one you should look at hardest.

_maybe_update_ingress_ports split into _reconcile_direct_ingress_ports (still gated on _direct_ingress_enabled, membership-version shortcut intact) and _reconcile_internal_grpc_ports (unconditional). prune moved out of the direct-ingress branch and now runs once per tick for both pools, since it covers every allocator on a node anyway.

The unconditional part is required, not incidental: _on_initialized starts this server on every replica, so without recovery a controller restart re-hands-out ports that live replicas hold, and without prune a crashed replica leaks its port for the life of the cluster.

On the cost you were implicitly asking about — there is no membership-version shortcut for this pool, because that counter tracks ingress membership only. Instead the per-tick work is bounded by a set difference against the previous tick, which is what the version check was buying in the first place, and prune already skips its scan per node while the alive set is unchanged. So a steady-state tick with no membership change does one set construction over the replicas and nothing else. If you'd rather have a real all-replica membership version, that's a deployment_state change I'm happy to make instead — it just seemed like more machinery than the set diff justified.

Two things that changed beyond your two points

TLS, as flagged above — binding now goes through add_port_to_grpc_server, so RAY_USE_TLS is honored.

SO_REUSEPORT, which I hadn't mentioned and which turned out to matter more than I expected. create_grpc_server_with_interceptors doesn't set it, so it's at gRPC's default, which is on for Linux. With it on, binding an already-occupied port succeeds silently — the retry loop can't tell a collision from a success, and two replicas would share a port while both believe they own it. Now disabled explicitly with the integer 0; the string "0" does not disable it (it parses as a non-empty value, which is worth knowing since grpc_util.start_grpc_server passes str(int(...))).

Defaults

42000–43000, 1000 wide per your "1000 is fine", not overlapping the direct-ingress ranges. RAY_SERVE_INTERNAL_GRPC_PORT_RETRY_COUNT mirrors the direct-ingress retry count. No opt-out and no ephemeral fallback — single path, as you asked.

Complexity assessment

+462 / −43 across 7 files, of which 175 lines are tests. Roughly: ~50 lines of real logic in the replica, ~30 in NodePortManager, ~45 in the controller (mostly the split, which is a wash), ~20 in deployment_state.

My read: the replica and allocator halves are cheap and clearly better than a self-managed range scan. The controller half is where the judgment call sits — it makes a reconcile pass that was previously direct-ingress-only into something every cluster runs. I think that's correct rather than merely acceptable, because the port it manages now exists on every replica in every cluster. But if you'd rather not take that, the honest alternative is not "a smaller NodePortManager change" — it's going back to a replica-local bind, with the second port-assignment path you were trying to avoid. Those are the two real options, and I'd take this one.

Testing status

I have not been able to run these tests. pre-commit passes on every changed file (including the Serve mypy/pyrefly hooks) and the commit is DCO signed, but I have no Ray build available here — the wheel in my environment predates get_all_interfaces_ip in _raylet, so master's Python can't import against it. The new tests are written but unexecuted, and I'd rather say so than let CI be the first to find out:

pytest python/ray/serve/tests/unit/test_node_port_manager.py
pytest python/ray/serve/tests/unit/test_controller_direct_ingress.py

New coverage: allocation/release, disjointness from the direct-ingress pools, blocked ports not returning to the pool, recovered ports not being re-handed-out, reclaim of a crashed replica's port, pool exhaustion, and two controller tests — that recovery happens with direct ingress disabled, and that only the per-tick delta reaches the allocator.

I'll report results once I've built. Happy to hold review until then if you'd rather.

AI assistance was used for this implementation.

Comment thread python/ray/serve/_private/controller.py Resolved
The per-replica inter-deployment gRPC server (proxy->replica and
replica->replica handle calls, used when gRPC is enabled by default via
RAY_SERVE_USE_GRPC_BY_DEFAULT / RAY_SERVE_THROUGHPUT_OPTIMIZED) bound an
OS-assigned ephemeral port. Service meshes such as Istio do not route
undeclared ephemeral ports, so cross-node handle calls to it were
dropped or reset.

Allocate it from the controller's ``NodePortManager`` instead, the same
mechanism direct ingress already uses, so there is one way of assigning
replica ports rather than two. Its deterministic min-heap assignment is
not just consistency here: a mesh-declarable range is only useful if the
ports drawn from it are predictable.

The replica follows the existing direct-ingress pattern -- ask the
controller for a port, try to bind, and on failure release it with
``block_port=True`` and retry against a fresh one.

Two things the direct-ingress path gets for free had to be extended,
because this server runs on *every* replica rather than only ingress
ones:

- ``_maybe_update_ingress_ports`` reconciled only when direct ingress was
  enabled, and its input filtered on ``owns_direct_ingress_ports()``.
  Internal ports are now reconciled unconditionally via a sibling
  accessor with no such filter. Without it, a controller restart would
  forget the ports of running replicas and hand them out again, and a
  crashed replica would leak its port for the life of the cluster.
- ``prune`` covers every allocator on a node, so it moves out of the
  direct-ingress branch and runs once per tick for both pools. It is
  cheap when nothing changed: the scan is skipped per node while the
  alive set is unchanged.

Two correctness details worth calling out:

- Binding goes through ``add_port_to_grpc_server`` so ``RAY_USE_TLS`` is
  honored. Calling ``add_insecure_port`` directly would have left this
  server plaintext in a TLS-enabled cluster.
- SO_REUSEPORT is disabled explicitly with the **integer** 0. It is on by
  default on Linux, and with it enabled a bind to an already-occupied
  port succeeds silently -- the retry loop could not tell a collision
  from a success, and two servers would share a port. The string "0" does
  not disable it.

There is no opt-out and no ephemeral fallback: user-facing behavior is
unchanged, so a single default range is all that is needed. The range is
1000 ports wide, matching the direct-ingress defaults, and does not
overlap them.

Signed-off-by: tobby168 <[email protected]>
@tobby168
tobby168 force-pushed the serve-internal-grpc-port-range branch from e2be534 to 2c4642a Compare August 8, 2026 08:35
@tobby168

tobby168 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Bugbot's finding is correct and it's a regression I introduced — fixed and pushed.

has_pending_quarantine() now aggregates all three allocators, and _reconcile_direct_ingress_ports was still consulting it through any_pending_quarantine(). Since every replica holds an internal gRPC port, every replica stop anywhere in the cluster puts one in quarantine, so the ingress skip gate would be defeated for the whole quarantine window (default hard_stop_after + 30s) even with ingress membership untouched. That's a straight perf regression on the direct-ingress path, caused by a pool that has nothing to do with it.

The second half of Bugbot's reasoning is the important one: that check no longer serves its original purpose either. It existed so the reclaim pass wasn't skipped along with the reconcile — but prune was hoisted out to the caller and now runs unconditionally, so the check was pure cost.

Dropped it; the gate is now just the membership version. Expired quarantines still return to the pool, on demand rather than eagerly: PortAllocator.allocate drains them before handing anything out, which is exactly when it matters. Added test_ingress_skip_survives_an_internal_grpc_quarantine to pin it, with an assertion that the quarantine is genuinely pending so the test can't go vacuous if that default ever becomes 0.

One loose end I did not clean up, since it's your file and reasonable people differ: NodePortManager.any_pending_quarantine() is now dead — that was its only caller. Worth deleting, or worth keeping as a helper? Happy to drop it in this PR if you prefer; I left it rather than widen the diff on my own judgment.

Now +504/−46. Still unrun locally, same reason as above.

@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 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 2c4642a. Configure here.

# replica is still on its old port, which is now outside the
# pool. Recovering it anyway is right -- the port is genuinely
# in use -- but it will not be handed out again once released.
logger.warning(f"Internal gRPC port out of range: {port}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Out-of-range ports reallocated

High Severity

update_port_if_missing claims out-of-range recovered ports will not be handed out again, but release still quarantines or pushes them into _available_ports, and allocate will return them. On upgrade, live replicas still hold ephemeral ports; after they stop, those ports re-enter the pool and new replicas bind outside the mesh-declarable range.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2c4642a. Configure here.

self._replica_id.unique_id,
port,
block_port=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bind errors block ports

Medium Severity

_bind_internal_grpc_port treats every RuntimeError from add_port_to_grpc_server as a port collision and releases with block_port=True. Non-bind failures such as TLS misconfiguration are also swallowed, permanently blocking up to RAY_SERVE_INTERNAL_GRPC_PORT_RETRY_COUNT ports and masking the real error behind a port-range message.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2c4642a. Configure here.

@johntaylor-cell

Copy link
Copy Markdown
Contributor

@abrarsheikh, should we pick this back up? It fixes #64544 and has been waiting since 8 Aug.

abrarsheikh pushed a commit that referenced this pull request Nov 16, 2026
## Description

`start_grpc_server(..., enable_so_reuseport=False)` did not turn
SO_REUSEPORT off. It passed the option as the string `"0"`, and gRPC
reads `grpc.so_reuseport` as an integer and ignores a string, which
leaves its default (on). Direct ingress replicas ask for `False` so that
a port another process listens on fails to bind and Serve allocates
another. Instead they could share a port with another process, and the
kernel split the port's connections between them. In #66815 about 8% of
a deployment's requests failed with `UNIMPLEMENTED` this way.

This PR passes the option as an integer and adds a test: a second server
binds a port in use only with `enable_so_reuseport=True`.

Behavior changes only where `enable_so_reuseport=False` is passed:
direct ingress replica servers, and Serve's proxies when
`SERVE_SOCKET_REUSE_PORT_ENABLED=0`. Proxies keep SO_REUSEPORT on by
default, as before.

## Related issues

Fixes #66815

## Additional information

- Not a duplicate: I searched open and closed issues and PRs for
`so_reuseport` and direct ingress ports. #64216 (HAProxy drain test
without SO_REUSEPORT), #64623 and #64544 deal with other port behavior.
- Tests, on Linux with Ray 3.0.0.dev0 (6703877, whose `grpc_util.py`
and test file match master) and grpcio 1.75.0, loading this PR's
`grpc_util.py` in place of the installed one:
- `python -m pytest -v python/ray/serve/tests/unit/test_grpc_util.py -k
so_reuseport`: 2 passed. Without the fix,
`test_start_grpc_server_so_reuseport[False]` fails with `DID NOT RAISE
RuntimeError`.
- `python -m pytest -q python/ray/serve/tests/unit/test_grpc_util.py`:
18 passed.
- black 22.10.0 and ruff 0.8.4 (the pre-commit versions) pass on both
files.
- The test is skipped off Linux, where SO_REUSEPORT semantics differ.
- AI assistance (Claude Code) was used to find the cause and prepare
this change.

Signed-off-by: xyuzh <[email protected]>

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