Skip to content

[12/N][HAProxy stability] - Close direct-ingress listeners once the deregistration window ends - #65698

Merged
eicherseiji merged 9 commits into
ray-project:masterfrom
harshit-anyscale:serve-close-ingress-listeners-after-deregistration-window
Sep 9, 2026
Merged

eicherseiji merged 9 commits into
ray-project:masterfrom
harshit-anyscale:serve-close-ingress-listeners-after-deregistration-window

Conversation

@harshit-anyscale

@harshit-anyscale harshit-anyscale commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

@harshit-anyscale
harshit-anyscale requested a review from a team as a code owner August 24, 2026 11:08

@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 two-phase draining mechanism for Ray Serve replicas running behind HAProxy. When HAProxy is enabled, the replica stays reachable during the deregistration window and then stops accepting new direct ingress HTTP connections before waiting for in-flight requests to complete. This prevents client-visible errors from late-arriving requests on a shutting-down replica. If HAProxy is not enabled, the replica continues to serve requests normally during the draining period. Unit tests have been added to verify these behaviors. I have no additional feedback to provide.

… ends

Behind HAProxy, a draining replica today keeps accepting new requests for
as long as they arrive. An HAProxy reload leaves the old process running
with a frozen backend list (it cannot be updated, only awaited), so a
stale worker can keep sending fresh requests to the draining replica for
minutes. When the node then goes away, those late requests are severed
mid-flight and the client sees an unretryable error.

Fix: behind HAProxy, drain in two phases -- serve the deregistration
window in full, then close the direct-ingress HTTP listener and wait for
in-flight requests. Late arrivals are refused at connect time, which
HAProxy retries on another replica (retry-on conn-failure + option
redispatch).

Without HAProxy nothing changes: there is no retrying party in front, so
a refusal would reach the client.

Signed-off-by: harshit-anyscale <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
@harshit-anyscale
harshit-anyscale force-pushed the serve-close-ingress-listeners-after-deregistration-window branch from 73ed903 to 4f969b7 Compare August 24, 2026 11:22
@harshit-anyscale harshit-anyscale self-assigned this Aug 24, 2026
@harshit-anyscale harshit-anyscale added the go add ONLY when ready to merge, run all tests label Aug 24, 2026
@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Aug 24, 2026
@harshit-anyscale harshit-anyscale changed the title [serve] Close direct-ingress listeners once the deregistration window ends [12/N][HAProxy stability] - Close direct-ingress listeners once the deregistration window ends Aug 26, 2026

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

This addresses the immediate spot-preemption case, but the underlying complexity comes from Ray manually managing HAProxy worker generations. A cleaner follow-up could be:

  1. Run HAProxy in master-worker mode and reload through the master CLI.
  2. Enumerate current and old workers and mark removed replicas maint in each before shutdown.
  3. Optionally use Runtime API membership updates later.

This would let HAProxy manage worker lifecycles, remove Ray’s manual PID/process handling, prevent stale-worker routing at the source, and return replicas to the normal drain path. It can be implemented incrementally while this PR remains a targeted mitigation.


@pytest.mark.asyncio
async def test_without_haproxy_keeps_serving_until_drained(self):
"""Without a retrying party in front, the replica keeps accepting for

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we do a manual rewrite on these comments

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.

have re-written them, ptal again, TIA :)

Comment thread python/ray/serve/_private/replica.py Outdated
self._stop_accepting_direct_ingress()

# Phase 3: wait for in-flight requests (window already served).
await self._drain_ongoing_requests()

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.

_drain_ongoing_requests() begins by sleeping for graceful_shutdown_wait_loop_s before checking the request count. That delay is redundant here because this path has already waited for deregistration and closed HTTP ingress.

With graceful_shutdown_wait_loop_s=10:

  1. t=0–30: Wait for deregistration.
  2. t=30: Close HTTP ingress and call this method.
  3. t=30–40: Sleep before checking the request count.
  4. t=35: The controller force-kills the replica before cleanup.

Could we pass check_immediately=True here so the request count is checked before entering the polling loop?

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.

thanks for pointing this out @eicherseiji , pushed the changes.

Review follow-up. `_drain_ongoing_requests` sleeps
`graceful_shutdown_wait_loop_s` before it first counts ongoing requests.
That is fine when it also owns the draining period, but in the two-phase
drain the window is already spent, so an idle replica waits one more loop
for nothing.

With `graceful_shutdown_wait_loop_s=10` that overruns the shutdown
budget: the deregistration window ends at t=30, the drain then sleeps
until t=40, and the controller force-kills at t=35 (the ingress floor of
`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S` +
`RAY_SERVE_DIRECT_INGRESS_SHUTDOWN_BUFFER_S`), so the quiesce and the
graceful server shutdown never run.

Add `check_immediately` to count before the first sleep, and pass it from
the two-phase drain. The default path is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: harshit-anyscale <[email protected]>
harshit-anyscale and others added 2 commits September 1, 2026 23:50
…intermediate_downscaling

The test used `check_num_replicas_lte(target=1)` as its cue that the
downscale had settled, then cleared the signal and sent 50 more requests.
But 1 includes the replica the autoscaler is about to remove, and a
replica stays in the router's target list until the controller's stop
actually reaches it.

That leaves a window (~130ms in CI) where the deployment's target is
already 0 but the last replica is still routable. Requests sent in that
window are admitted -- `max_ongoing_requests=1000`, so one replica takes
all 50 -- and then block forever on the signal the test just cleared. The
replica is force-killed at the end of its grace period and the requests
die with it.

Nothing then reports that demand: replica metrics are filtered to running
replicas, and the requests were assigned rather than queued, so the
autoscaler reads 0 ongoing requests and never scales back up. The test
waits out its 30s timeout.

Waiting for the replicas to actually be gone removes the window. This is
the same condition the test already uses for its final downscale check,
and it is strictly stronger than `<= 1`.

Previously this was masked by shutdown latency: idle replicas spent one
`graceful_shutdown_wait_loop_s` before their first drain check, so by the
time the count dropped the last replica had finished dying.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: harshit-anyscale <[email protected]>
@harshit-anyscale

Copy link
Copy Markdown
Contributor Author

This addresses the immediate spot-preemption case, but the underlying complexity comes from Ray manually managing HAProxy worker generations. A cleaner follow-up could be:

  • Run HAProxy in master-worker mode and reload through the master CLI.
  • Enumerate current and old workers and mark removed replicas maint in each before shutdown.
  • Optionally use Runtime API membership updates later.

This would let HAProxy manage worker lifecycles, remove Ray’s manual PID/process handling, prevent stale-worker routing at the source, and return replicas to the normal drain path. It can be implemented incrementally while this PR remains a targeted mitigation.

Agreed, i have parked it for later, here's one more reason to implement it: https://claude.ai/code/artifact/6f26de03-7bb6-42f3-929e-743d149cc2b1?open_in_browser=1&via=user_open&org=cab79e62-097e-4f6d-a45d-18248cadf428

The controller re-issues the stop when it restarts, so a replica can get
a second `perform_graceful_shutdown` while the first is still running.
Nothing prevented re-entry, and `call_destructor` deliberately runs the
user's `__del__` only once -- so the second pass skipped the destructor,
returned promptly, and the controller recorded a clean shutdown while the
first pass was still blocked inside `__del__`.

The replica is then reported stopped and the application deletes with
user cleanup still pending, which is exactly what
test_recover_deleting_application checks.

Run the shutdown once and have later calls await that same run, shielded
so a cancelled caller can't abort it. The controller now keeps seeing the
replica as stopping until the grace period expires and force-kills it.

Previously the second pass spent one `graceful_shutdown_wait_loop_s` in
the drain before reaching the destructor, which was long enough to hide
this.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: harshit-anyscale <[email protected]>
@harshit-anyscale
harshit-anyscale force-pushed the serve-close-ingress-listeners-after-deregistration-window branch from a349d1a to 43eb101 Compare September 3, 2026 07:29
abrarsheikh pushed a commit that referenced this pull request Sep 9, 2026
…ica detection (#65729)

## Why this change

Two HAProxy defaults that are reasonable for a single-node dev cluster
but poor once replicas come and go under autoscaling. Each is a default
change only; both stay overridable through their existing environment
variables.

| Constant | Before | After |
|---|---|---|
| `RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` | unset | `5` |
| `RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED` | `0` | `1` |

### `timeout connect`: unset → `5s`

Replicas are in-cluster, so a connect that takes seconds means the node
is gone rather than busy. Bounding it lets `retry-on conn-failure` +
`option redispatch` reach another replica while the request still has
budget. This is connection-establishment time only — it does not bound
request duration.

`timeout server` is deliberately **not** set here; see *Deliberately not
included*.

### `observe layer4 ... on-error mark-down`: off → on

Live traffic marks a dead replica DOWN without waiting for a health
checker, and `redispatch` plus the `backup` fallback take over. A false
positive revives in ~0.5s via the existing health check. Backup/fallback
servers are never observed.

## Not a duplicate

Checked before opening, no overlapping work found:

```
gh pr list --repo ray-project/ray --state open --search "haproxy default"
```

The only open PR touching this area is #65698 (mine, direct-ingress
listener close), which does not change any of these constants.

## Tests

Two environments. **(A)** nightly `ray-3.0.0.dev0` wheel with
`python/ray/serve` and `python/ray/tests` symlinked in, `pytest==7.4.4`
per `python/requirements/test-requirements.txt` — used for the rendering
and unit runs. **(B)** the same, plus a real HAProxy binary (`brew`
3.4.4) via `RAY_SERVE_HAPROXY_BINARY_PATH`, running the CI job's env
(`RAY_SERVE_ENABLE_HA_PROXY=1`,
`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S=0.01`,
`SERVE_SOCKET_REUSE_PORT_ENABLED=1`) — used for the integration runs.

**End-to-end with a real HAProxy (B)** — the tests premerge flagged on
earlier revisions of this PR, re-run at this revision's defaults with no
env overrides:

```
test_autoscaling_policy.py::test_e2e_preserve_prev_replicas_rest_api   => passed (x2)
test_streaming_response.py                                             => 23 passed
```

Both were failing on earlier revisions and pass here. Caveats on this
environment: it is HAProxy **3.4.4**, while CI ships **2.8** via
`ray-haproxy`; and macOS has no `splice(2)`, so `option splice-request`
/ `option splice-response` had to be dropped from the rendered config
for HAProxy to start locally. Those options affect data forwarding, not
routing or timing. CI remains the authority.

**HAProxy config rendering (A)**:

```
RAY_SERVE_ENABLE_HA_PROXY=1 pytest --pyargs ray.serve.tests.test_haproxy_api \
  -k "generate_config_file_internal or escapes_special_characters or close_spread_time
      or generate_backends_in_order or routers_and_targets or ingress_request_router_lua
      or router_servers_without_replica_ids or does_not_leak_into_other_backends
      or router_failure_503 or inherits_global_retry_policy or global_retry_knobs
      or default_data_plane_tuning"
=> 13 passed, 26 deselected
```

**New test** `test_default_data_plane_tuning_renders` pins the shipped
values. Every other test in that file passes explicit overrides, so
nothing previously caught a silent change to these defaults. It is
`skipif`-guarded on the env vars it asserts about, so overriding any of
them skips rather than fails:

```
RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED=0      => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_SERVER_S=3600            => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S=9              => 1 skipped
```

The skip does not neuter it — changing a shipped default in *source*
still fails the test.

**Serve unit suite (A)** — `pytest python/ray/serve/tests/unit`:

```
this branch:            195 failed, 4564 passed, 18 skipped, 2 errors
clean origin/master:    195 failed, 4564 passed, 18 skipped, 2 errors
```

Identical, so failure-neutral. The 195 are an artifact of running repo
Serve code against a slightly older nightly core wheel on macOS; they
are in `test_deployment_state.py` / `test_handle_options.py` and touch
nothing this PR changes. Measured on the six-default revision of this
PR; the diff has only shrunk since, so this is a ceiling rather than a
current reading.

**Lint** at the versions pinned in `.pre-commit-config.yaml`, re-run at
this revision:

```
ruff 0.8.4 check                => All checks passed
ruff 0.8.4 check --select I     => All checks passed
black 22.10.0 --check           => unchanged
```

`mypy 1.7.0` and `pyrefly 1.1.1` (both of which have `constants.py` on
their allowlists) were clean on an earlier revision that already
contained both remaining changes; they were not re-run at this exact
commit, since everything removed since was a revert to master's own
text.

One shape change worth calling out:
`RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` moves from the hand-rolled
`int(os.environ.get(...)) if os.environ.get(...) else ...` conditional
to the file's existing `get_env_int_non_negative` helper, which drops a
`# type: ignore[arg-type]`. Its default is changing anyway, so the line
is touched regardless, and the helper handles `=0` correctly — the
truthiness form would silently turn an explicit `0` into the default. It
does mean an empty-string value now raises instead of being ignored,
matching every other `get_env_*` constant in the file. Say the word if
you would rather keep the original shape and just swap the `else`
branch.

## AI assistance

This change was drafted with AI assistance (Claude), including the code,
the tests, and this description.

Opened as a **draft** on purpose: per `AGENTS.md` a human submitter has
to review every changed line and run the relevant tests locally before
review is requested. I have not finished that pass yet. Marking ready
for review is the signal that it is done — please don't spend review
time on it before then.

The binary-dependent HAProxy tests (26 deselected above) also still need
a run on a machine that has `haproxy` installed.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@eicherseiji
eicherseiji merged commit 776ce48 into ray-project:master Sep 9, 2026
6 checks passed
NightWing1998 pushed a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
…ica detection (ray-project#65729)

## Why this change

Two HAProxy defaults that are reasonable for a single-node dev cluster
but poor once replicas come and go under autoscaling. Each is a default
change only; both stay overridable through their existing environment
variables.

| Constant | Before | After |
|---|---|---|
| `RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` | unset | `5` |
| `RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED` | `0` | `1` |

### `timeout connect`: unset → `5s`

Replicas are in-cluster, so a connect that takes seconds means the node
is gone rather than busy. Bounding it lets `retry-on conn-failure` +
`option redispatch` reach another replica while the request still has
budget. This is connection-establishment time only — it does not bound
request duration.

`timeout server` is deliberately **not** set here; see *Deliberately not
included*.

### `observe layer4 ... on-error mark-down`: off → on

Live traffic marks a dead replica DOWN without waiting for a health
checker, and `redispatch` plus the `backup` fallback take over. A false
positive revives in ~0.5s via the existing health check. Backup/fallback
servers are never observed.

## Not a duplicate

Checked before opening, no overlapping work found:

```
gh pr list --repo ray-project/ray --state open --search "haproxy default"
```

The only open PR touching this area is ray-project#65698 (mine, direct-ingress
listener close), which does not change any of these constants.

## Tests

Two environments. **(A)** nightly `ray-3.0.0.dev0` wheel with
`python/ray/serve` and `python/ray/tests` symlinked in, `pytest==7.4.4`
per `python/requirements/test-requirements.txt` — used for the rendering
and unit runs. **(B)** the same, plus a real HAProxy binary (`brew`
3.4.4) via `RAY_SERVE_HAPROXY_BINARY_PATH`, running the CI job's env
(`RAY_SERVE_ENABLE_HA_PROXY=1`,
`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S=0.01`,
`SERVE_SOCKET_REUSE_PORT_ENABLED=1`) — used for the integration runs.

**End-to-end with a real HAProxy (B)** — the tests premerge flagged on
earlier revisions of this PR, re-run at this revision's defaults with no
env overrides:

```
test_autoscaling_policy.py::test_e2e_preserve_prev_replicas_rest_api   => passed (x2)
test_streaming_response.py                                             => 23 passed
```

Both were failing on earlier revisions and pass here. Caveats on this
environment: it is HAProxy **3.4.4**, while CI ships **2.8** via
`ray-haproxy`; and macOS has no `splice(2)`, so `option splice-request`
/ `option splice-response` had to be dropped from the rendered config
for HAProxy to start locally. Those options affect data forwarding, not
routing or timing. CI remains the authority.

**HAProxy config rendering (A)**:

```
RAY_SERVE_ENABLE_HA_PROXY=1 pytest --pyargs ray.serve.tests.test_haproxy_api \
  -k "generate_config_file_internal or escapes_special_characters or close_spread_time
      or generate_backends_in_order or routers_and_targets or ingress_request_router_lua
      or router_servers_without_replica_ids or does_not_leak_into_other_backends
      or router_failure_503 or inherits_global_retry_policy or global_retry_knobs
      or default_data_plane_tuning"
=> 13 passed, 26 deselected
```

**New test** `test_default_data_plane_tuning_renders` pins the shipped
values. Every other test in that file passes explicit overrides, so
nothing previously caught a silent change to these defaults. It is
`skipif`-guarded on the env vars it asserts about, so overriding any of
them skips rather than fails:

```
RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED=0      => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_SERVER_S=3600            => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S=9              => 1 skipped
```

The skip does not neuter it — changing a shipped default in *source*
still fails the test.

**Serve unit suite (A)** — `pytest python/ray/serve/tests/unit`:

```
this branch:            195 failed, 4564 passed, 18 skipped, 2 errors
clean origin/master:    195 failed, 4564 passed, 18 skipped, 2 errors
```

Identical, so failure-neutral. The 195 are an artifact of running repo
Serve code against a slightly older nightly core wheel on macOS; they
are in `test_deployment_state.py` / `test_handle_options.py` and touch
nothing this PR changes. Measured on the six-default revision of this
PR; the diff has only shrunk since, so this is a ceiling rather than a
current reading.

**Lint** at the versions pinned in `.pre-commit-config.yaml`, re-run at
this revision:

```
ruff 0.8.4 check                => All checks passed
ruff 0.8.4 check --select I     => All checks passed
black 22.10.0 --check           => unchanged
```

`mypy 1.7.0` and `pyrefly 1.1.1` (both of which have `constants.py` on
their allowlists) were clean on an earlier revision that already
contained both remaining changes; they were not re-run at this exact
commit, since everything removed since was a revert to master's own
text.

One shape change worth calling out:
`RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` moves from the hand-rolled
`int(os.environ.get(...)) if os.environ.get(...) else ...` conditional
to the file's existing `get_env_int_non_negative` helper, which drops a
`# type: ignore[arg-type]`. Its default is changing anyway, so the line
is touched regardless, and the helper handles `=0` correctly — the
truthiness form would silently turn an explicit `0` into the default. It
does mean an empty-string value now raises instead of being ignored,
matching every other `get_env_*` constant in the file. Say the word if
you would rather keep the original shape and just swap the `else`
branch.

## AI assistance

This change was drafted with AI assistance (Claude), including the code,
the tests, and this description.

Opened as a **draft** on purpose: per `AGENTS.md` a human submitter has
to review every changed line and run the relevant tests locally before
review is requested. I have not finished that pass yet. Marking ready
for review is the signal that it is done — please don't spend review
time on it before then.

The binary-dependent HAProxy tests (26 deselected above) also still need
a run on a machine that has `haproxy` installed.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ica detection (ray-project#65729)

## Why this change

Two HAProxy defaults that are reasonable for a single-node dev cluster
but poor once replicas come and go under autoscaling. Each is a default
change only; both stay overridable through their existing environment
variables.

| Constant | Before | After |
|---|---|---|
| `RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` | unset | `5` |
| `RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED` | `0` | `1` |

### `timeout connect`: unset → `5s`

Replicas are in-cluster, so a connect that takes seconds means the node
is gone rather than busy. Bounding it lets `retry-on conn-failure` +
`option redispatch` reach another replica while the request still has
budget. This is connection-establishment time only — it does not bound
request duration.

`timeout server` is deliberately **not** set here; see *Deliberately not
included*.

### `observe layer4 ... on-error mark-down`: off → on

Live traffic marks a dead replica DOWN without waiting for a health
checker, and `redispatch` plus the `backup` fallback take over. A false
positive revives in ~0.5s via the existing health check. Backup/fallback
servers are never observed.

## Not a duplicate

Checked before opening, no overlapping work found:

```
gh pr list --repo ray-project/ray --state open --search "haproxy default"
```

The only open PR touching this area is ray-project#65698 (mine, direct-ingress
listener close), which does not change any of these constants.

## Tests

Two environments. **(A)** nightly `ray-3.0.0.dev0` wheel with
`python/ray/serve` and `python/ray/tests` symlinked in, `pytest==7.4.4`
per `python/requirements/test-requirements.txt` — used for the rendering
and unit runs. **(B)** the same, plus a real HAProxy binary (`brew`
3.4.4) via `RAY_SERVE_HAPROXY_BINARY_PATH`, running the CI job's env
(`RAY_SERVE_ENABLE_HA_PROXY=1`,
`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S=0.01`,
`SERVE_SOCKET_REUSE_PORT_ENABLED=1`) — used for the integration runs.

**End-to-end with a real HAProxy (B)** — the tests premerge flagged on
earlier revisions of this PR, re-run at this revision's defaults with no
env overrides:

```
test_autoscaling_policy.py::test_e2e_preserve_prev_replicas_rest_api   => passed (x2)
test_streaming_response.py                                             => 23 passed
```

Both were failing on earlier revisions and pass here. Caveats on this
environment: it is HAProxy **3.4.4**, while CI ships **2.8** via
`ray-haproxy`; and macOS has no `splice(2)`, so `option splice-request`
/ `option splice-response` had to be dropped from the rendered config
for HAProxy to start locally. Those options affect data forwarding, not
routing or timing. CI remains the authority.

**HAProxy config rendering (A)**:

```
RAY_SERVE_ENABLE_HA_PROXY=1 pytest --pyargs ray.serve.tests.test_haproxy_api \
  -k "generate_config_file_internal or escapes_special_characters or close_spread_time
      or generate_backends_in_order or routers_and_targets or ingress_request_router_lua
      or router_servers_without_replica_ids or does_not_leak_into_other_backends
      or router_failure_503 or inherits_global_retry_policy or global_retry_knobs
      or default_data_plane_tuning"
=> 13 passed, 26 deselected
```

**New test** `test_default_data_plane_tuning_renders` pins the shipped
values. Every other test in that file passes explicit overrides, so
nothing previously caught a silent change to these defaults. It is
`skipif`-guarded on the env vars it asserts about, so overriding any of
them skips rather than fails:

```
RAY_SERVE_HAPROXY_OBSERVE_MARK_DOWN_ENABLED=0      => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_SERVER_S=3600            => 1 skipped
RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S=9              => 1 skipped
```

The skip does not neuter it — changing a shipped default in *source*
still fails the test.

**Serve unit suite (A)** — `pytest python/ray/serve/tests/unit`:

```
this branch:            195 failed, 4564 passed, 18 skipped, 2 errors
clean origin/master:    195 failed, 4564 passed, 18 skipped, 2 errors
```

Identical, so failure-neutral. The 195 are an artifact of running repo
Serve code against a slightly older nightly core wheel on macOS; they
are in `test_deployment_state.py` / `test_handle_options.py` and touch
nothing this PR changes. Measured on the six-default revision of this
PR; the diff has only shrunk since, so this is a ceiling rather than a
current reading.

**Lint** at the versions pinned in `.pre-commit-config.yaml`, re-run at
this revision:

```
ruff 0.8.4 check                => All checks passed
ruff 0.8.4 check --select I     => All checks passed
black 22.10.0 --check           => unchanged
```

`mypy 1.7.0` and `pyrefly 1.1.1` (both of which have `constants.py` on
their allowlists) were clean on an earlier revision that already
contained both remaining changes; they were not re-run at this exact
commit, since everything removed since was a revert to master's own
text.

One shape change worth calling out:
`RAY_SERVE_HAPROXY_TIMEOUT_CONNECT_S` moves from the hand-rolled
`int(os.environ.get(...)) if os.environ.get(...) else ...` conditional
to the file's existing `get_env_int_non_negative` helper, which drops a
`# type: ignore[arg-type]`. Its default is changing anyway, so the line
is touched regardless, and the helper handles `=0` correctly — the
truthiness form would silently turn an explicit `0` into the default. It
does mean an empty-string value now raises instead of being ignored,
matching every other `get_env_*` constant in the file. Say the word if
you would rather keep the original shape and just swap the `else`
branch.

## AI assistance

This change was drafted with AI assistance (Claude), including the code,
the tests, and this description.

Opened as a **draft** on purpose: per `AGENTS.md` a human submitter has
to review every changed line and run the relevant tests locally before
review is requested. I have not finished that pass yet. Marking ready
for review is the signal that it is done — please don't spend review
time on it before then.

The binary-dependent HAProxy tests (26 deselected above) also still need
a run on a machine that has `haproxy` installed.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants