Repository navigation
Conversation
There was a problem hiding this comment.
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.
| 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") | ||
| ) |
There was a problem hiding this comment.
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(...)).
| 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 | |
| ) |
There was a problem hiding this comment.
Done in 63ff7f3 — both now use get_env_int("...", 0) to match the rest of the file.
| 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)) |
There was a problem hiding this comment.
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))There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
Done in 63ff7f3 — switched the bind to ("::", 0).
fe0b57d to
63ff7f3
Compare
|
This pull request has been automatically marked as stale because it has not had 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. |
|
|
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 TLSNot something you raised, but it's the most important item here. # 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 2. Dropping "backward compatible" — agreedYou're right that the dual path isn't earning its keep. I'll delete the 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 gapThe replica-side half is already there and I'd just be following it. The gap is on the controller side. if self._direct_ingress_enabled:
...
NodePortManager.update_ports(...)
NodePortManager.prune(self._get_node_id_to_alive_replica_ids())and its input,
Closing both is not hard — 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. |
|
542df67 to
e2be534
Compare
|
Done — rebased onto master and reimplemented on The branch is now a single commit against current master. The old What it tookReplica — mirrors the direct-ingress pattern: ask the controller, try to bind, and on failure release with NodePortManager — a third Controller — this is the part that isn't free, and it's the one you should look at hardest.
The unconditional part is required, not incidental: 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 Two things that changed beyond your two pointsTLS, as flagged above — binding now goes through SO_REUSEPORT, which I hadn't mentioned and which turned out to matter more than I expected. Defaults42000–43000, 1000 wide per your "1000 is fine", not overlapping the direct-ingress ranges. Complexity assessment+462 / −43 across 7 files, of which 175 lines are tests. Roughly: ~50 lines of real logic in the replica, ~30 in 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 statusI have not been able to run these tests. 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. |
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]>
e2be534 to
2c4642a
Compare
|
Bugbot's finding is correct and it's a regression I introduced — fixed and pushed.
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 Dropped it; the gate is now just the membership version. Expired quarantines still return to the pool, on demand rather than eagerly: One loose end I did not clean up, since it's your file and reasonable people differ: Now +504/−46. Still unrun locally, same reason as above. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
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}") |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 2c4642a. Configure here.
| self._replica_id.unique_id, | ||
| port, | ||
| block_port=True, | ||
| ) |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 2c4642a. Configure here.
|
@abrarsheikh, should we pick this back up? It fixes #64544 and has been waiting since 8 Aug. |
## 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]>


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 byRAY_SERVE_THROUGHPUT_OPTIMIZED). It binds an OS-assigned ephemeral port viaadd_insecure_port("[::]:0")inreplica.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_PORTandRAY_SERVE_INTERNAL_GRPC_MAX_PORT, so the server can bind within a bounded, mesh-declarable range — mirroring the existingRAY_SERVE_DIRECT_INGRESS_*_PORTknobs already used by the direct-ingress servers.0, which keeps the current ephemeral behavior unchanged.SO_REUSEPORTdisabled (integer0) so an already-used port is rejected and each replica on a node gets a distinct port. Note the integer0is required — the string"0"does not disableSO_REUSEPORT.bind_grpc_port_in_rangeingrpc_util.py.Related issue number
Checks
-s) with the DCO.pre-commit(ruff v0.8.4, black 22.10.0) passes on the changed files.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 theSO_REUSEPORT-off occupancy detection — was validated against real gRPC sync andgrpc.aioservers.🤖 Generated with Claude Code