Skip to content

[core] Add per-call RetryOnTimeoutPolicy to RetryableGrpcClient; opt in GetClusterId - #64847

Closed
xyuzh wants to merge 1 commit into
ray-project:masterfrom
xyuzh:gcs-getclusterid-connect-retry
Closed

xyuzh wants to merge 1 commit into
ray-project:masterfrom
xyuzh:gcs-getclusterid-connect-retry

Conversation

@xyuzh

@xyuzh xyuzh commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Why are these changes needed?

A DEADLINE_EXCEEDED on the cluster-ID fetch maps to TimedOut, which IsGrpcRetryableStatus deliberately never retries (that predicate feeds an unbounded retry queue). The fetch was a single all-or-nothing RPC with the whole connect budget as its deadline (30s on the Python standalone client path), so one deadline spent queueing on a GCS busy with a node registration storm was fatal to the connecting process — observed as fleet-wide bring-up deaths at 400 nodes on Ray 2.56.

Fix: generalize the existing retry infrastructure instead of adding a bespoke loop. RetryableGrpcClient::CallMethod gains an opt-in per-call RetryOnTimeoutPolicy:

  • Each attempt gets a bounded per-attempt deadline, clamped to an absolute overall deadline derived from the call's timeout_ms — so retries can never exceed the caller's budget.
  • A timed-out attempt is re-sent after a full-jitter exponential backoff delay (uniform in [0, min(100ms·2^attempt, 2s)]). Jitter is the point: hundreds of clients that timed out on the same overloaded server at the same moment must not re-fire in lockstep.
  • Non-timeout errors keep the existing semantics (UNAVAILABLE/UNKNOWN → reconnect queue; everything else fails fast). Calls without the policy are unchanged.

GcsRpcClient::GetClusterId is the only opt-in (hand-written instead of the VOID_GCS_RPC_CLIENT_METHOD macro to attach the policy), with per-attempt deadline gcs_rpc_server_connect_timeout_s. GcsClient::FetchClusterId shrinks back to a single sync call; it now RAY_CHECKs a non-positive budget instead of silently normalizing it (an invalid budget is an operator error and should fail loudly), and its final-failure Disconnect() behavior is unchanged. With the C++ default 5s budget this stays effectively a single attempt; the Python 30s budget becomes ~6 chances to land in a queue gap.

An earlier revision implemented this as a hand-rolled attempt-counting loop inside FetchClusterId with a test-only virtual seam; this revision replaces that with the per-call policy in RetryableGrpcClient so there is one retry mechanism, it is reusable, and it adds jitter.

Companion PR (server-side half of the same incident, independently mergeable/revertable): #64845.

Related issue number

None found — searched open PRs/issues for GetClusterId / connect retry before opening. Not a duplicate of in-flight work.

Checks

  • I've signed off every commit (DCO).
  • I've run pre-commit on the changed files.
  • Testing strategy — new //src/ray/rpc/tests:retryable_grpc_client_test exercises the policy against a real gRPC server with a freezable handler: RetriesTimedOutAttemptsUntilSuccess (attempts time out while frozen; a later attempt succeeds after unfreeze; ≥2 requests observed server-side) and DeliversTimedOutWhenBudgetExhausted (handler stays frozen; final status is TimedOut, delivered no earlier than the overall budget). Ran locally (macOS, --dynamic_mode=off): passes, along with //src/ray/gcs_rpc_client/tests:gcs_client_test, gcs_client_reconnection_test, gcs_client_injectable_test, accessor_test. (global_state_accessor_test fails on my machine because it hardcodes port 6379, which a local redis service occupies — pre-existing, unrelated.)

Per the repo's AI contribution policy: AI assistance was used to develop this change; every changed line was reviewed and the tests above were run locally.

@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 bounded per-attempt retry loop in GcsClient::FetchClusterId to split the overall timeout budget into bounded per-attempt deadlines, retrying specifically on TimedOut errors. It also adds comprehensive unit tests to verify this retry logic under various configurations. The review feedback highlights two important improvements: addressing a potential integer overflow when calculating the number of attempts with extremely large timeouts, and resolving undefined behavior in the test's fake context caused by strict aliasing violations with reinterpret_cast.

Comment thread src/ray/gcs_rpc_client/gcs_client.cc Outdated
Comment on lines +239 to +240
const int64_t num_attempts =
std::max<int64_t>(1, (timeout_ms + per_attempt_ms - 1) / per_attempt_ms);

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

Calculating num_attempts using (timeout_ms + per_attempt_ms - 1) / per_attempt_ms can result in integer overflow if timeout_ms is extremely large (e.g., close to INT64_MAX). Since timeout_ms and per_attempt_ms are guaranteed to be positive here, we can safely calculate this without overflow using division and the modulo operator.

Suggested change
const int64_t num_attempts =
std::max<int64_t>(1, (timeout_ms + per_attempt_ms - 1) / per_attempt_ms);
const int64_t num_attempts =
(timeout_ms / per_attempt_ms) + ((timeout_ms % per_attempt_ms > 0) ? 1 : 0);

Comment on lines +43 to +56
pubsub::GcsSubscriber &GetGcsSubscriber() override {
RAY_LOG(FATAL) << "Unexpected GetGcsSubscriber call";
return *reinterpret_cast<pubsub::GcsSubscriber *>(this);
}

rpc::GcsRpcClient &GetGcsRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetGcsRpcClient call";
return *reinterpret_cast<rpc::GcsRpcClient *>(this);
}

rpc::ObservabilityPubSubRpcClient &GetObservabilityPubSubRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetObservabilityPubSubRpcClient call";
return *reinterpret_cast<rpc::ObservabilityPubSubRpcClient *>(this);
}

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 reinterpret_cast to cast this (a FakeGcsClientContext*) to unrelated types like pubsub::GcsSubscriber*, rpc::GcsRpcClient*, or rpc::ObservabilityPubSubRpcClient* and then dereferencing them violates strict aliasing rules and is undefined behavior in C++. Even though these methods abort via RAY_LOG(FATAL), compilers can still optimize or emit warnings based on strict aliasing assumptions. A safer approach to satisfy the compiler's return requirement is to return a dereferenced static null pointer of the respective type.

Suggested change
pubsub::GcsSubscriber &GetGcsSubscriber() override {
RAY_LOG(FATAL) << "Unexpected GetGcsSubscriber call";
return *reinterpret_cast<pubsub::GcsSubscriber *>(this);
}
rpc::GcsRpcClient &GetGcsRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetGcsRpcClient call";
return *reinterpret_cast<rpc::GcsRpcClient *>(this);
}
rpc::ObservabilityPubSubRpcClient &GetObservabilityPubSubRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetObservabilityPubSubRpcClient call";
return *reinterpret_cast<rpc::ObservabilityPubSubRpcClient *>(this);
}
pubsub::GcsSubscriber &GetGcsSubscriber() override {
RAY_LOG(FATAL) << "Unexpected GetGcsSubscriber call";
static pubsub::GcsSubscriber *dummy = nullptr;
return *dummy;
}
rpc::GcsRpcClient &GetGcsRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetGcsRpcClient call";
static rpc::GcsRpcClient *dummy = nullptr;
return *dummy;
}
rpc::ObservabilityPubSubRpcClient &GetObservabilityPubSubRpcClient() override {
RAY_LOG(FATAL) << "Unexpected GetObservabilityPubSubRpcClient call";
static rpc::ObservabilityPubSubRpcClient *dummy = nullptr;
return *dummy;
}

@ray-gardener ray-gardener Bot added the core Issues that should be addressed in Ray Core label Jul 17, 2026
Comment thread src/ray/gcs_rpc_client/gcs_client.cc Outdated
// The last attempt gets the remainder of the budget.
const int64_t this_attempt_ms =
std::min(per_attempt_ms, timeout_ms - attempt * per_attempt_ms);
s = SyncGetClusterIdOnce(&reply, this_attempt_ms);

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.

Doesn’t splitting the connect budget into more GetClusterId attempts make the storm even stronger?

…in GetClusterId

A DEADLINE_EXCEEDED on the cluster-ID fetch maps to TimedOut, which
IsGrpcRetryableStatus deliberately never retries (that predicate feeds an
unbounded retry queue). The fetch was a single all-or-nothing RPC with the
whole connect budget as its deadline (30s on the Python standalone client
path), so one deadline spent queueing on a GCS busy with a node
registration storm was fatal to the connecting process — observed as
fleet-wide bring-up deaths at 400 nodes on Ray 2.56.

Instead of a bespoke retry loop in GcsClient::FetchClusterId, generalize
the existing retry infrastructure: RetryableGrpcClient::CallMethod gains an
opt-in per-call RetryOnTimeoutPolicy. Attempts get bounded per-attempt
deadlines clamped to an absolute overall deadline (the call's timeout_ms),
and a timed-out attempt is re-sent after a full-jitter exponential backoff
delay — jitter decorrelates retries from many clients that timed out on the
same overloaded server at the same moment. Non-timeout errors keep the
existing semantics, and nothing changes for calls without the policy.

GcsRpcClient::GetClusterId is the only opt-in (hand-written instead of the
macro to attach the policy), with per-attempt deadline
gcs_rpc_server_connect_timeout_s. FetchClusterId now RAY_CHECKs a
non-positive budget instead of silently normalizing it, and its
final-failure Disconnect() behavior is unchanged. With the C++ default 5s
budget this stays a single attempt; the Python 30s budget becomes ~6
chances to land in a queue gap.

Tests: new //src/ray/rpc/tests:retryable_grpc_client_test exercises the
policy against a real server with a freezable handler — retries until
success once unfrozen, and delivers TimedOut only after the overall budget
is exhausted.

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh force-pushed the gcs-getclusterid-connect-retry branch from ef9f6fc to d0d6f7a Compare July 31, 2026 21:01
@xyuzh xyuzh changed the title [core] Retry GetClusterId with bounded per-attempt deadlines in GcsClient::Connect [core] Add per-call RetryOnTimeoutPolicy to RetryableGrpcClient; opt in GetClusterId Jul 31, 2026

@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 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit d0d6f7a. Configure here.

io_context_,
[request = std::move(request)]() { request->CallMethod(); },
std::chrono::milliseconds(delay_ms));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timeout budget not fully enforced

Medium Severity

RetryOnTimeoutPolicy claims retries stay within timeout_ms, but RetryAfterJitteredBackoff schedules an unclamped delay (up to 2s) whenever any budget remains, so SyncGetClusterId / Connect can overrun the caller budget by the backoff plus a final attempt. Separately, if a later attempt fails with Unavailable, Retry requeues using the full original GetTimeoutMs() from now and ignores overall_deadline_, which can roughly double the wait after timeout retries have already consumed most of the budget.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d0d6f7a. Configure here.

@xyuzh

xyuzh commented Jul 31, 2026

Copy link
Copy Markdown
Member Author

Reworked per design review: the bespoke retry loop in FetchClusterId is replaced by an opt-in per-call RetryOnTimeoutPolicy in RetryableGrpcClient with jittered backoff — see the updated PR description. Strategic companion that removes most of the fetch load altogether: #65156.

@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 Aug 15, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

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

Thanks again for your contribution!

@github-actions github-actions Bot closed this Aug 29, 2026
rueian pushed a commit that referenced this pull request Nov 24, 2026
…5298)

## Description

When the async connection to Redis drops, hiredis frees the raw
`redisAsyncContext` and nothing puts it back. Every subsequent GCS
command fails with `Status::Disconnected` until
`num_redis_request_retries` runs out (~3.5s), and gcs_server aborts with
`Failed to run redis cmds`. A Redis restart, an idle timeout, a proxy
dropping its backend, or a Sentinel failover is enough to take the head
node down, which defeats the purpose of GCS fault tolerance.

[#64299](#64299) (1/N) made the
connection-failure paths return `Status` instead of crashing. This PR
adds the reconnect itself, as a stack of three commits that each build
and fix something on their own. The commit messages carry the design
details; in short:

**1/3: Rebind the async context in place.** In-flight
`RedisRequestContext`s hold a raw `RedisAsyncContext*`, so the reconnect
preserves object identity: `Reset()` swaps the raw hiredis handle while
the wrapper stays put. Success is only declared from the hiredis connect
callback, since `redisAsyncConnect` reports a healthy context even when
nothing is listening.

**2/3: Re-resolve the address on every reconnect attempt.** The recorded
address survives a failover behind a proxy or Service, but for Sentinel
it is the old primary's. Sentinel setups now re-query the Sentinel on
each attempt and follow the promotion; everything else re-resolves
through DNS. Redis Cluster addressed directly has no lookup point and
stays out of scope (documented: front it with a Service or proxy).

**3/3: Don't spend a command's retries on attempts that never reached
Redis.** A Sentinel promotion takes ~4s, the command retry budget ~3.5s,
so gcs_server aborted moments before the reconnect landed. Null replies
(never reached Redis) are refunded within the new
`redis_reconnect_grace_period_ms` (default 60s; `0` restores the old
behaviour exactly). Error replies (`-READONLY`, …) drain the budget as
before.

`test_redis_with_sentinel_failureover` asserted the old behaviour and
carried the TODO for this work in its docstring. It now asserts the same
process survives the failover and that the old cold-restart coverage
still holds.

How the three commits interact, on the case that needs all of them
(Sentinel direct, measured timings):

```mermaid
sequenceDiagram
    participant REQ as RedisRequestContext
    participant RC as RedisContext
    participant S as Sentinel
    participant P1 as primary :7001
    participant P2 as replica :7002

    Note over REQ,P1: connected. command budget: 6 tries in ~3.5s
    P1--xRC: connection drops (t=0)
    Note over REQ: 3/3: null replies are refunded within the 60s grace,<br/>so the command is not spending its 6 tries yet
    loop backoff 100ms..1s, up to redis_db_connect_retries=120
        RC->>S: 2/3: SENTINEL MASTERS
        S-->>RC: primary is :7001
        RC->>P1: async connect
        P1--xRC: refused
    end
    RC->>S: SENTINEL MASTERS
    S-->>RC: primary is :7002 (promoted at t=4s)
    RC->>P2: async connect
    P2-->>RC: connect callback OK
    Note over RC: 1/3: Reset() rebinds the same RedisAsyncContext,<br/>so in-flight requests keep their raw pointer valid
    REQ->>P2: retry succeeds
```

Before this PR the timeline ends at t=3.5s with `Failed to run redis
cmds: [PING] for 5 times`.

### Behaviour matrix

| Topology | Before | After |
|---|---|---|
| Plain Redis, drop/restart | FATAL in ~3.5s / SIGSEGV | survives,
reconnects in ~0ms |
| Proxy / K8s Service, backend failover | dies before proxy recovers |
survives (~1ms, same VIP) |
| Sentinel direct, primary failover | dies ~0.5s before promotion |
survives, follows the promotion |
| Redis Cluster direct, failover | dies | still unsupported; documented,
use a Service/proxy in front |
| Redis permanently unreachable | FATAL ~3.5s | still exits (bounded by
grace + retry drain), deliberately |

### Verification

Everything below ran against real Redis processes and containers
(killed, restarted, demoted; no mocks). Each scenario runs a task
(`ray.get`) before and after the failure, so "survives" means the
cluster still schedules work, not just that the process exists.

<details>
<summary><b>Plain Redis (single node) — 9 scenarios</b></summary>

| Scenario | Before | After |
|---|---|---|
| Connection drop | FATAL in ~3.5s | survives, 0ms reconnect, tasks run
|
| Process restart (no persistence) | SIGSEGV | survives |
| Restart while loading a 400k-key AOF | dies | survives, no `-LOADING`
reply leaks |
| Never comes back | FATAL ~3.5s | bounded FATAL after grace + drain, no
hang |
| Rapid flapping (drop every 200ms for 10s) | dies on first drop |
survives, 88 reconnects, 0 crash markers |
| Concurrent load across a drop | dies | 160,140 tasks, 0 errors |
| Soak: 60 drops | — | RSS +0.7MB, fd +2, 120 reconnects |
| Worker node attached across a drop | — | both nodes stay alive, tasks
on both |
| Detached actor across a drop | — | callable after reconnect |

</details>

<details>
<summary><b>HAProxy / Kubernetes Service + Sentinel-managed failover — 2
scenarios</b></summary>

| Scenario | Before | After |
|---|---|---|
| Kill primary container → Sentinel promotes → proxy repoints | dies |
survives, reconnects through the same VIP, tasks run |
| Second backend churn 10s later | — | same recovery path |

</details>

<details>
<summary><b>Sentinel addressed directly — 8 scenarios</b></summary>

| Scenario | Before | After |
|---|---|---|
| Primary killed → replica promoted (~4s) | dies at ~3.5s | survives,
logs `Sentinel now reports the primary at :7002, was :7001`, reconnects
to the promoted node |
| Two failovers in a row | — | follows both promotions, both directions
|
| Old primary rejoins as replica | — | stays on the new primary |
| Sentinel dies while the primary is down | — | keeps retrying, no
crash, no false "Reconnected" |
| Sentinel reports a dead address, then a live one | — | adopts the good
address once offered |
| Password auth across the failover | — | 0 auth errors |
| Promoted node rejects AUTH | — | keeps retrying, no false success |
| GCS cold restart after the failover | covered by the old test | still
covered; detached actor recovered from the promoted primary |

</details>

<details>
<summary><b>Redis Cluster / TLS — 4 scenarios</b></summary>

| Scenario | Result |
|---|---|
| Single-shard cluster, drop | survives, reconnects, tasks run |
| `CLUSTER FAILOVER`, GCS pointed at a node directly | does not recover;
measured, documented with the workaround |
| `rediss://` drop + reconnect | survives, reconnect re-initiates TLS |
| TLS + Sentinel re-query | re-query initiates TLS like the startup path
|

</details>

<details>
<summary><b>Config knobs — 6 scenarios</b></summary>

| Knob | Verified |
|---|---|
| `redis_reconnect_grace_period_ms=0` | restores pre-change behaviour
exactly (~3.5s FATAL) |
| `redis_reconnect_grace_period_ms=5000` | bounded exit at grace + drain
|
| `redis_db_connect_retries=0` / `=1` | exits after exactly 0 / 1
attempts |
| `redis_retry_base_ms=1, max_ms=10` | no hot spin, CPU flat |
| `num_redis_request_retries=0` | idle drop survives, 0 wasted connects
|
| `retries=3` + `grace=60s` | the smaller bound wins |

</details>

Unit tests: 4 new cases in `redis_async_context_test` (in-place `Reset`,
never-connected release, teardown during reconnect). All store-client
tests pass at each commit of the stack independently. Not verified
locally: Linux CI (this PR is its first run), ASAN/TSAN (macOS
toolchain), IPv6.

### Known limitations (deliberately out of scope)

- The reconnect handshake (Sentinel re-query, DNS resolve) runs
synchronously on the io_service thread. Each step is bounded by the
probe timeout, but a fully async handshake is follow-up work.
- Error replies are not refunded: a Service that keeps routing writes to
a demoted (read-only) primary for longer than the command budget still
brings GCS down, exactly as before this PR.
- Against a SYN-blackholed address, each async connect attempt settles
only after the kernel TCP timeout, which stretches the
`redis_db_connect_retries` budget in wall-clock terms.

## Related issues

Closes #48781. Related: #53475, #64204 (SIGSEGV on failover, fixed
earlier), #64299 (1/N prerequisite).

## Checks

- [x] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've run `scripts/format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed for
https://docs.ray.io/en/master/. (`kuberay-gcs-ft.md`: new section on
what happens when the Redis connection drops, plus the tuning knobs.)
- [ ] I've added any new APIs to the API Reference. N/A: no public API
change; one new internal config (`RAY_redis_reconnect_grace_period_ms`).
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
  - [x] Unit tests
  - [ ] Release tests
  - [ ] This PR is not tested :(

## AI assistance disclosure

AI assistance (Claude) was used for the implementation, the verification
harnesses, and this description. I (the human submitter) have reviewed
every changed line and understand the change end-to-end.

- **Not duplicating existing work:** the previous attempt (#48781) was
auto-closed as stale in July 2025, and a search of open PRs on
2026-08-08 found none implementing Redis reconnection (#64847 and #62462
touch gRPC reconnect settings, not the Redis connection). The adjacent
fixes #64204 and #64299 landed separately and this PR stacks on them.
- **Test commands run locally** (macOS source build; results in the
Verification section above):
- `bazel test //src/ray/gcs/store_client/tests:redis_async_context_test
//src/ray/gcs/store_client/tests:redis_store_client_test` — pass at each
commit of the stack
- `pytest
python/ray/tests/test_gcs_fault_tolerance.py::test_redis_with_sentinel_failureover`
— passed (16.4s), with `TEST_EXTERNAL_REDIS=1`
- a 29-scenario topology harness against real Redis/Sentinel/HAProxy
processes and containers, run before and after the change

---------

Signed-off-by: Dongjun Na <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants