Skip to content

[Serve] Import jinja2 lazily and declare it in the serve extra - #65542

Merged
elliot-barn merged 4 commits into
ray-project:masterfrom
lonexreb:fix/65507-serve-jinja2
Sep 2, 2026
Merged

elliot-barn merged 4 commits into
ray-project:masterfrom
lonexreb:fix/65507-serve-jinja2

Conversation

@lonexreb

Copy link
Copy Markdown
Contributor

Why are these changes needed?

As of 2.57.0, controller.py imports haproxy.py unconditionally, and haproxy.py imported jinja2 at module scope — but jinja2 was never declared in Ray's metadata (ray-haproxy is a binary distribution with requires_dist: None, so nothing pulls it in). On a slim base image:

docker run --rm python:3.13-slim bash -c \
  'pip install -q "ray[default,serve]==2.57.0" && python -c "from ray import serve"'
# ModuleNotFoundError: No module named 'jinja2'

This PR applies both fixes suggested in the issue:

  1. Lazy import: from jinja2 import Environment moves from module scope into _generate_config_file_internal() (its single use site), so a plain import ray.serve no longer requires jinja2 — it's only needed when HAProxy mode actually renders its config.
  2. Declare the dependency: jinja2 is added to the serve extra in setup.py (mirrored in python/requirements.txt), so it's present when HAProxy mode is used. The compiled lockfiles already pin jinja2==3.1.6, so no lock regeneration is needed.

Related issue number

Fixes #65507

Checks

  • I've signed off every commit (DCO).
  • Formatting checked with the repo-pinned black==22.10.0.
  • Testing strategy (run locally against master via Ray nightly wheel + setup-dev.py symlinks):
    • Added test_import_serve_does_not_require_jinja2: a subprocess blocks jinja2 via a meta-path finder, then imports ray.serve and ray.serve._private.controller. Fails on master (repro of the issue), passes with this change.
    • Verified the render path still works with jinja2 present: constructed HAProxyApi and called _generate_config_file_internal(); a full HAProxy config (~5 KB) renders through the now-lazy import.

Notes for reviewers / AI-assistance disclosure

As of 2.57.0, controller.py imports haproxy.py unconditionally, and
haproxy.py imported jinja2 at module scope — but jinja2 was never
declared in Ray's metadata (ray-haproxy is a binary distribution with no
requires_dist). On slim base images, pip install 'ray[serve]' produced
an install where a plain 'import ray.serve' fails with
ModuleNotFoundError: No module named 'jinja2'.

Move the jinja2 import into _generate_config_file_internal so it's only
required when HAProxy mode actually renders its config, and declare
jinja2 in the serve extra (mirrored in requirements.txt) so it's present
when HAProxy mode is used.

Fixes ray-project#65507

Signed-off-by: lonexreb <[email protected]>
@lonexreb
lonexreb requested review from a team, edoakes and richardliaw as code owners August 17, 2026 19:33

@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 refactors the HAProxy configuration generator to lazily import jinja2, preventing a plain import ray.serve from failing when jinja2 is not installed. It also adds a corresponding unit test to enforce this behavior and updates the dependency files to include jinja2. The reviewer suggested using textwrap.dedent with a multiline string in the unit test to improve the readability and maintainability of the subprocess code snippet.

Comment on lines +171 to +180
code = (
"import importlib.abc, sys\n"
"class BlockJinja(importlib.abc.MetaPathFinder):\n"
" def find_spec(self, fullname, path=None, target=None):\n"
" if fullname == 'jinja2' or fullname.startswith('jinja2.'):\n"
" raise ModuleNotFoundError(\"No module named 'jinja2'\")\n"
"sys.meta_path.insert(0, BlockJinja())\n"
"import ray.serve\n"
"import ray.serve._private.controller\n"
)

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 better readability and maintainability of the code snippet to be executed in the subprocess, consider using textwrap.dedent with a multiline string. This makes the code block easier to read and edit.

Suggested change
code = (
"import importlib.abc, sys\n"
"class BlockJinja(importlib.abc.MetaPathFinder):\n"
" def find_spec(self, fullname, path=None, target=None):\n"
" if fullname == 'jinja2' or fullname.startswith('jinja2.'):\n"
" raise ModuleNotFoundError(\"No module named 'jinja2'\")\n"
"sys.meta_path.insert(0, BlockJinja())\n"
"import ray.serve\n"
"import ray.serve._private.controller\n"
)
import textwrap
code = textwrap.dedent(
"""
import importlib.abc, sys
class BlockJinja(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path=None, target=None):
if fullname == 'jinja2' or fullname.startswith('jinja2.'):
raise ModuleNotFoundError("No module named 'jinja2'")
sys.meta_path.insert(0, BlockJinja())
import ray.serve
import ray.serve._private.controller
"""
)

Review feedback: a triple-quoted dedented snippet is easier to read and
edit than concatenated escaped string literals.

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

Copy link
Copy Markdown
Contributor Author

Applied the textwrap.dedent suggestion — the subprocess snippet is now a dedented triple-quoted string. Test re-run locally and passing.

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Aug 29, 2026
@elliot-barn
elliot-barn enabled auto-merge (squash) September 1, 2026 19:56
Signed-off-by: elliot-barn <[email protected]>
@elliot-barn
elliot-barn requested a review from a team as a code owner September 1, 2026 21:25
@github-actions
github-actions Bot disabled auto-merge September 1, 2026 21:25
@elliot-barn
elliot-barn enabled auto-merge (squash) September 2, 2026 00:11
@elliot-barn
elliot-barn merged commit e11fe03 into ray-project:master Sep 2, 2026
7 checks passed
elliot-barn added a commit that referenced this pull request Sep 9, 2026
This lock file was deleted on master before #65542 merged, so the
cherry-pick could not bring the regenerated version; the release
branch still compiles this depset and needs the via-ray entry now
that jinja2 is declared in the serve extra.

Signed-off-by: elliot-barn <[email protected]>
elliot-barn added a commit that referenced this pull request Sep 9, 2026
…he serve extra (#65542) (#65988)

Cherry-pick of #65542 (master commit
e11fe03) onto releases/2.59.0.

One conflict resolved: the original commit also updated
`python/deplocks/ray-torch/ray-torch-cu128_base_py3.11.lock`, which does
not exist on this branch (only the py3.14 ray-torch lock is present on
releases/2.59.0) — dropped that file from the pick; all other 82
lock/requirements updates applied cleanly.

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

---------

Signed-off-by: lonexreb <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Shubhankar Tripathy <[email protected]>
eicherseiji pushed a commit that referenced this pull request Sep 9, 2026
…eregistration window ends (#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently #63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (#65502 draining-node accessor on the
controller, #65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
qishengxhe added a commit to qishengxhe/ray that referenced this pull request Sep 11, 2026
…missing

The module-level import broke the Read the Docs build, which imports the
checkout's `ray.serve` in an environment without grpcio-reflection.
Follow the jinja2 precedent (ray-project#65542): import inside
`enable_server_reflection` so a plain `import ray.serve` doesn't require
the package.

Since reflection now defaults on, a missing package logs a warning and
skips reflection instead of failing proxy startup, so upgrading with a
core-only `pip install -U ray` cannot break an existing gRPC deployment.
`enable_server_reflection` returns whether reflection was enabled, with a
unit test for the skip path.

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Qisheng He <[email protected]>
qishengxhe added a commit to qishengxhe/ray that referenced this pull request Sep 11, 2026
Serve's gRPC proxy now serves the gRPC server reflection protocol, so
standard tools (grpcurl, grpcui, Postman) can discover and call the
registered user-defined gRPC services without local proto files, similar
to FastAPI's /docs page for HTTP.

- `enable_reflection` option in `gRPCOptions` (on by default), mirrored in
  the config schema and as `--grpc-enable-reflection/--grpc-disable-reflection`
  on `serve start` / `serve build`.
- The reflection service must execute on the proxy rather than being
  routed to a replica, so `gRPCGenericServer` gains a passthrough
  mechanism: handlers for registered passthrough services are added
  unmodified while all other handlers keep the replica-routing override.
  Advertised service names are derived from the registered method
  handlers, excluding Serve's built-in `RayServeAPIService`.
- `grpcio-reflection` (added to the `serve` extra in a separate PR) is
  imported lazily inside `enable_server_reflection`, following the jinja2
  precedent in ray-project#65542, so a plain `import ray.serve` doesn't require it.
  If it's missing, reflection is skipped with a warning instead of
  failing proxy startup.
- Guide section covering the flag, grpcurl/grpcui usage, and the HAProxy
  multi-app limitation (reflection requests need `application` metadata;
  routing the `/grpc.reflection.` prefix to the fallback proxy is a
  follow-up).

@MicroCheck //python/ray/serve/tests:test_grpc //python/ray/serve/tests/unit:test_grpc_util //python/ray/serve/tests/unit:test_schema

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Qisheng He <[email protected]>
qishengxhe added a commit to qishengxhe/ray that referenced this pull request Sep 11, 2026
Serve's gRPC proxy now serves the gRPC server reflection protocol, so
standard tools (grpcurl, grpcui, Postman) can discover and call the
registered user-defined gRPC services without local proto files, similar
to FastAPI's /docs page for HTTP.

- `enable_reflection` option in `gRPCOptions` (on by default), mirrored in
  the config schema and as `--grpc-enable-reflection/--grpc-disable-reflection`
  on `serve start` / `serve build`.
- The reflection service must execute on the proxy rather than being
  routed to a replica, so `gRPCGenericServer` gains a passthrough
  mechanism: handlers for registered passthrough services are added
  unmodified while all other handlers keep the replica-routing override.
  Advertised service names are derived from the registered method
  handlers, excluding Serve's built-in `RayServeAPIService`.
- `grpcio-reflection` (added to the `serve` extra in a separate PR) is
  imported lazily inside `enable_server_reflection`, following the jinja2
  precedent in ray-project#65542, so a plain `import ray.serve` doesn't require it.
  If it's missing, reflection is skipped with a warning instead of
  failing proxy startup.
- Guide section covering the flag, grpcurl/grpcui usage, and the HAProxy
  multi-app limitation (reflection requests need `application` metadata;
  routing the `/grpc.reflection.` prefix to the fallback proxy is a
  follow-up).

@MicroCheck //python/ray/serve/tests:test_grpc //python/ray/serve/tests/unit:test_grpc_util //python/ray/serve/tests/unit:test_schema

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Qisheng He <[email protected]>
NightWing1998 pushed a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
…eregistration window ends (ray-project#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently ray-project#63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (ray-project#65502 draining-node accessor on the
controller, ray-project#65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
richardliaw pushed a commit that referenced this pull request Sep 15, 2026
## Why

Prerequisite for #65854, which adds gRPC server reflection to Serve's
gRPC proxy. Reviewers there asked for `grpcio-reflection` to be a
default Serve dependency rather than an optional install, and for the
lock regeneration to be reviewed on its own, so the dependency change is
split out here.

## What

- `grpcio-reflection` added to the `serve` extra in `setup.py`, mirrored
in `python/requirements.txt` (same shape as the `jinja2` addition in
#65542).
- Pinned in `test-requirements.txt` next to `grpcio-tools` /
`grpcio-status`, with the same three-way split #66119 gave those two:
**1.71.2 on py<3.12**, 1.75.0 on py3.12–3.13, 1.76.0 on py3.14.
grpcio-reflection ≥ 1.72 requires protobuf ≥ 6.30, so 1.71.2 is the
newest release compatible with the protobuf 5.27.5 pin on the py<3.12
track. Mirrored into `requirements_compiled.txt` (py<3.12 branch, as
pip-compile emits it) and `requirements_compiled_py3.14.txt`.
- Lock files regenerated with `bazelisk run //ci/raydepsets:raydepsets
-- build --all-configs`; `--check` passes locally.

No code changes. The feature that uses the package lands in #65854.

**Rebased on 2026-09-14 after #66119 landed.** Master now pins protobuf
5.27.5 on py<3.12, which is exactly the constraint the earlier
`py310_protobuf_overrides.txt` / `--override` mechanism was working
around, so that mechanism is gone: no override file, no depset config
edits. The branch is a single commit again.

## Lock changes vs master

- 92 locks gain exactly one `grpcio-reflection` line, matched to the
grpcio already pinned in that lock (1.71.2, 1.75.0, 1.76.0, or
1.78.0/1.80.0/1.62.3 in the few locks on a different grpcio). **No lock
moves protobuf or grpcio.**
- **Two `expand` depsets with no constraints file**
(`tests/data/datatfds_py3.12`, `byod/audio_transcription_py3.10`)
resolve the newest grpcio-reflection (1.83.1) and follow it to grpcio
1.83.1, protobuf 7.36.1, and newer google-cloud/opentelemetry pins. Same
as before the rebase: a pre-existing gap in those depset definitions;
happy to add a constraints file to them if preferred.

## Tests

- `bazelisk run //ci/raydepsets:raydepsets -- build --all-configs` then
`--check`: "Lock files are up to date."
- `pre-commit run --files` on the edited source and compiled files:
passed.
- The `pip-compile dependencies` CI job validates the hand-added
`requirements_compiled*.txt` entries.

AI assistance was used for this PR; every changed line was reviewed and
all checks were run by the submitter.

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

---------

Signed-off-by: Qisheng He <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
qishengxhe added a commit to qishengxhe/ray that referenced this pull request Sep 15, 2026
Serve's gRPC proxy now serves the gRPC server reflection protocol, so
standard tools (grpcurl, grpcui, Postman) can discover and call the
registered user-defined gRPC services without local proto files, similar
to FastAPI's /docs page for HTTP.

- `enable_reflection` option in `gRPCOptions` (on by default), mirrored in
  the config schema and as `--grpc-enable-reflection/--grpc-disable-reflection`
  on `serve start` / `serve build`.
- The reflection service must execute on the proxy rather than being
  routed to a replica, so `gRPCGenericServer` gains a passthrough
  mechanism: handlers for registered passthrough services are added
  unmodified while all other handlers keep the replica-routing override.
  Advertised service names are derived from the registered method
  handlers, excluding Serve's built-in `RayServeAPIService`.
- `grpcio-reflection` (added to the `serve` extra in a separate PR) is
  imported lazily inside `enable_server_reflection`, following the jinja2
  precedent in ray-project#65542, so a plain `import ray.serve` doesn't require it.
  If it's missing, reflection is skipped with a warning instead of
  failing proxy startup.
- Guide section covering the flag, grpcurl/grpcui usage, and the HAProxy
  multi-app limitation (reflection requests need `application` metadata;
  routing the `/grpc.reflection.` prefix to the fallback proxy is a
  follow-up).

@MicroCheck //python/ray/serve/tests:test_grpc //python/ray/serve/tests/unit:test_grpc_util //python/ray/serve/tests/unit:test_schema

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Qisheng He <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…roject#65542)

## Why are these changes needed?

As of 2.57.0, `controller.py` imports `haproxy.py` unconditionally, and
`haproxy.py` imported jinja2 at module scope — but jinja2 was never
declared in Ray's metadata (`ray-haproxy` is a binary distribution with
`requires_dist: None`, so nothing pulls it in). On a slim base image:

```bash
docker run --rm python:3.13-slim bash -c \
  'pip install -q "ray[default,serve]==2.57.0" && python -c "from ray import serve"'
# ModuleNotFoundError: No module named 'jinja2'
```

This PR applies both fixes suggested in the issue:

1. **Lazy import**: `from jinja2 import Environment` moves from module
scope into `_generate_config_file_internal()` (its single use site), so
a plain `import ray.serve` no longer requires jinja2 — it's only needed
when HAProxy mode actually renders its config.
2. **Declare the dependency**: `jinja2` is added to the `serve` extra in
`setup.py` (mirrored in `python/requirements.txt`), so it's present when
HAProxy mode *is* used. The compiled lockfiles already pin
`jinja2==3.1.6`, so no lock regeneration is needed.

## Related issue number

Fixes ray-project#65507

## Checks

- [x] I've signed off every commit (DCO).
- [x] Formatting checked with the repo-pinned `black==22.10.0`.
- [x] Testing strategy (run locally against master via Ray nightly wheel
+ `setup-dev.py` symlinks):
- Added `test_import_serve_does_not_require_jinja2`: a subprocess blocks
jinja2 via a meta-path finder, then imports `ray.serve` and
`ray.serve._private.controller`. Fails on master (repro of the issue),
passes with this change.
- Verified the render path still works with jinja2 present: constructed
`HAProxyApi` and called `_generate_config_file_internal()`; a full
HAProxy config (~5 KB) renders through the now-lazy import.

### Notes for reviewers / AI-assistance disclosure

- This PR was prepared with AI assistance; I have reviewed every changed
line and run the checks above locally.
- Duplicate-work check: no open PR references ray-project#65507; the issue is
unassigned with no claims.

---------

Signed-off-by: lonexreb <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Elliot Barnwell <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…eregistration window ends (ray-project#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently ray-project#63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (ray-project#65502 draining-node accessor on the
controller, ray-project#65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Why

Prerequisite for ray-project#65854, which adds gRPC server reflection to Serve's
gRPC proxy. Reviewers there asked for `grpcio-reflection` to be a
default Serve dependency rather than an optional install, and for the
lock regeneration to be reviewed on its own, so the dependency change is
split out here.

## What

- `grpcio-reflection` added to the `serve` extra in `setup.py`, mirrored
in `python/requirements.txt` (same shape as the `jinja2` addition in
ray-project#65542).
- Pinned in `test-requirements.txt` next to `grpcio-tools` /
`grpcio-status`, with the same three-way split ray-project#66119 gave those two:
**1.71.2 on py<3.12**, 1.75.0 on py3.12–3.13, 1.76.0 on py3.14.
grpcio-reflection ≥ 1.72 requires protobuf ≥ 6.30, so 1.71.2 is the
newest release compatible with the protobuf 5.27.5 pin on the py<3.12
track. Mirrored into `requirements_compiled.txt` (py<3.12 branch, as
pip-compile emits it) and `requirements_compiled_py3.14.txt`.
- Lock files regenerated with `bazelisk run //ci/raydepsets:raydepsets
-- build --all-configs`; `--check` passes locally.

No code changes. The feature that uses the package lands in ray-project#65854.

**Rebased on 2026-09-14 after ray-project#66119 landed.** Master now pins protobuf
5.27.5 on py<3.12, which is exactly the constraint the earlier
`py310_protobuf_overrides.txt` / `--override` mechanism was working
around, so that mechanism is gone: no override file, no depset config
edits. The branch is a single commit again.

## Lock changes vs master

- 92 locks gain exactly one `grpcio-reflection` line, matched to the
grpcio already pinned in that lock (1.71.2, 1.75.0, 1.76.0, or
1.78.0/1.80.0/1.62.3 in the few locks on a different grpcio). **No lock
moves protobuf or grpcio.**
- **Two `expand` depsets with no constraints file**
(`tests/data/datatfds_py3.12`, `byod/audio_transcription_py3.10`)
resolve the newest grpcio-reflection (1.83.1) and follow it to grpcio
1.83.1, protobuf 7.36.1, and newer google-cloud/opentelemetry pins. Same
as before the rebase: a pre-existing gap in those depset definitions;
happy to add a constraints file to them if preferred.

## Tests

- `bazelisk run //ci/raydepsets:raydepsets -- build --all-configs` then
`--check`: "Lock files are up to date."
- `pre-commit run --files` on the edited source and compiled files:
passed.
- The `pip-compile dependencies` CI job validates the hand-added
`requirements_compiled*.txt` entries.

AI assistance was used for this PR; every changed line was reviewed and
all checks were run by the submitter.

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

---------

Signed-off-by: Qisheng He <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] jinja2 imported by haproxy.py but not declared by ray[serve] — slim installs can't import ray.serve

3 participants