Repository navigation
[core][2/N] Reconnect to Redis in place when the connection drops - #65298
Conversation
When the async connection to Redis drops, hiredis frees the raw
redisAsyncContext and RedisAsyncContext is left holding nothing. Nothing
puts it back, so every subsequent GCS command fails with
Status::Disconnected until num_redis_request_retries runs out and
gcs_server aborts with "Failed to run redis cmds". A Redis restart, an
idle timeout or a proxy dropping the backend is enough to take the head
node down.
Reconnect in place instead. RedisContext keeps the connection parameters
from the last successful Connect() and, on a disconnect, dials again with
exponential backoff until redis_db_connect_retries is exhausted.
The reconnect has to preserve object identity: in-flight
RedisRequestContexts hold a raw RedisAsyncContext*, so a fresh
RedisAsyncContext would leave them pointing at freed memory.
RedisAsyncContext::Reset() therefore swaps the raw handle and re-attaches
the asio socket while the wrapper object stays put.
Two hiredis details drive the rest:
- redisAsyncConnect is non-blocking and returns a healthy-looking
context even when nothing is listening. Success is declared from the
connect callback, never from the return value.
- hiredis does not run the disconnect callback for a connect that never
reached REDIS_CONNECTED; __redisAsyncFree only runs it once that flag
is set. The connect callback releases the raw pointer itself on
failure, otherwise the next command dereferences freed memory.
Teardown is guarded by disconnect_requested_. Disconnect() runs hiredis'
teardown, which calls back into us, and it may be running from
~RedisContext where the io_service is already gone; a reconnect must not
be scheduled from there.
Registering a connect callback has one more consequence worth calling out.
redisAsyncSetConnectCallback arms a write wait immediately, because that is
how hiredis detects an established connection. Connect() against a Sentinel
then destroys the RedisAsyncContext as soon as it learns where the primary
is, so a request queued by that write wait would run against a freed object
— reproducibly, as a SIGSEGV in ray start. AddRead/AddWrite and the socket
handlers now carry a weak sentinel that the destructor expires first, and a
generation counter keeps a handler from an old socket from clearing the
in-progress flags of the one that replaced it.
The same review pass closed four smaller holes. The destructor frees the
raw context in its body: left to member destruction order it outlives the
handlers, and the disconnect callback hiredis runs from redisAsyncFree
would read a destroyed std::function. Disconnect() forgets the retained
connection parameters, so reusing the object against a different server
cannot reconnect to the old one with the old credentials. A retry timer
carries the episode it was armed in and dies with it, rather than joining
the next episode as a second driver and spending the budget twice as
fast. And the submission-failure path hands the response callback a null
context instead of an unsynchronized raw pointer read.
Also fixes two latent issues found along the way: errstr was read outside
the mutex in RedisAsyncCommand/RedisAsyncCommandArgv, and HandleIo could
run against a null raw context.
Signed-off-by: Dongjun Na <[email protected]>
The in-place reconnect dials the address recorded at connect time. That is correct behind a proxy or a Kubernetes Service, where the address outlives the backend, but not for Sentinel: Connect() asks Sentinel for the primary and then connects to that node directly, so the recorded address is the old primary's. After a failover it points at a node that is down or demoted, and the reconnect loop retries it forever. Remember how the connection was reached, not just where it landed. A Sentinel setup keeps origin_address_/origin_port_ (the Sentinel, the only address that survives a failover) alongside the primary it is currently talking to. Each reconnect attempt re-queries Sentinel through a short-lived synchronous connection and follows the promotion: Redis Sentinel now reports the primary at 127.0.0.1:7002, was 127.0.0.1:7001 Reconnected to Redis at 127.0.0.1:7002 For every other setup the address is re-resolved through DNS, so a name that now points elsewhere is followed too. The Sentinel probe runs on the io_service thread, so every step of it is bounded: the connect by redisConnectWithTimeout, the query by the probe timeout (AuthenticateRedis restores the socket to no-timeout after AUTH, and never sets one when there is no password, so the query bounds it itself). It also initiates TLS when the context is encrypted — the startup path does, and a Sentinel behind rediss:// would otherwise refuse the plaintext re-query on every attempt. This aims the reconnect at the right node, but a Sentinel failover is still not survivable on its own: promoting a replica takes about four seconds and a command exhausts its retries after three and a half, so gcs_server aborts moments before the reconnect it is waiting for lands. The next commit closes that gap. Redis Cluster addressed directly is out of scope and stays broken: there is no equivalent lookup point, so GCS keeps dialling the node it was given. Put a Service or a proxy in front of it. Signed-off-by: Dongjun Na <[email protected]>
…Redis A command gets num_redis_request_retries+1 attempts on the shared exponential backoff, which is 6 attempts over roughly 3.5 seconds of wall clock. That budget is meant for a Redis that answers and fails, but it is also consumed by attempts made while the connection is down — attempts that never reach Redis at all and say nothing about the command. A Sentinel failover takes about 3.5 seconds to promote a replica, measured against the default down-after-milliseconds. The reconnect lands at 3.51s. The command budget runs out at 3.50s. gcs_server aborts ten milliseconds before the connection it is waiting for comes back. Refund the retry when the reply is a null pointer: no reply at all means the command never made it to Redis, so the attempt should not count against it. An error reply is different — the command reached Redis and was refused, retrying will not fix it, and the budget drains as before. That keeps -READONLY and friends behaving exactly as they did. Wall clock bounds the refund. redis_reconnect_grace_period_ms (60s by default) caps how long a command can keep waiting out a reconnect before its retries start counting again, so a permanently unreachable Redis still fails instead of hanging. Setting it to 0 restores the previous behaviour. The updated Sentinel test passes wait_for_condition an explicit timeout: ray.init blocks on GCS internal KV until the reconnect lands, and the default 10s would fail the test on its first slow attempt. Signed-off-by: Dongjun Na <[email protected]>
The KubeRay GCS fault tolerance guide told users to keep Redis reachable but not what Ray does when it is not. Now that gcs_server reconnects in place, describe the behaviour, the knobs that shape it, and the one topology it cannot follow (Redis Cluster addressed directly, which has no Sentinel to re-resolve through). Signed-off-by: Dongjun Na <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements in-place GCS reconnection when the Redis connection drops, allowing GCS to survive Redis Sentinel failovers and temporary network drops without restarting. The changes include adding reconnect configuration parameters, handling asynchronous reconnects and DNS re-resolution in RedisContext, and updating fault tolerance tests. The review feedback highlights two important improvement opportunities: first, optimizing the reconnect logic in RedisContext to avoid busy-waiting/polling when a connection attempt is pending; second, adding a retry_interval_ms to wait_for_condition in the test suite to prevent CPU exhaustion from rapid Python process spawning.
…events Round of fixes from the first CI run (microcheck ray-project#51781) and the bot reviews on ray-project#65298. Teardown crash (CI: gcs_client_test SIGSEGV, 2 out of 2). When an io_context is destroyed with redis work still queued, boost::asio destroys the pending handlers without running them. One of those handlers held the last owner of the RedisStoreClient, so its destruction tore down the RedisContext, whose raw hiredis context was still REDIS_CONNECTED because the loop never got to process the drop. redisAsyncFree then flushed the pending command callbacks, and the retry path scheduled a timer on the io_context that was mid- destruction. RedisRequestContext now carries a token that expires with its RedisAsyncContext; a flushed callback that finds it expired drops the request instead of scheduling anything. AUTH verified before a reconnect is declared (Cursor review, and it made a row in the PR's verification table wrong). Startup proves credentials on a synchronous probe before anything async happens; the reconnect path had no probe and sent AUTH fire-and-forget, so a promoted primary that rejects the credentials still logged "Reconnected" and then bled the command budget on -NOAUTH replies. The reconnect's AUTH now carries a reply callback: an error reply tears the fresh connection down (redisAsyncDisconnect, the teardown that is legal from inside a hiredis callback) and the disconnect path retries; only a clean reply completes the episode. The TCP connect callback defers to it through auth_pending_. Retries driven by failure events instead of a poll (Gemini review). The retry timer used to re-arm unconditionally, so while a connect was in flight it woke up, saw the pending flag, and re-armed: a poll. Now a sync connect failure schedules the retry on the spot, an async failure schedules it from the disconnect callback, and a success arms nothing. The epoch guard still kills timers orphaned by an episode that ended in success. Log flood (CI: 26,244 identical ERROR lines in one test). During an outage every in-flight command fails once per backoff step, and with the grace period holding their budgets nothing is even being spent. Refunded failures now log at WARNING, rate-limited to one line per second; failures that do spend budget keep the per-command ERROR. test_redis_failureover asserts that gcs_server exits promptly when the Redis Cluster node it is pointed at goes away, which is exactly the documented-unsupported topology, so the test now pins redis_reconnect_grace_period_ms=0 to keep the old exit semantics it is built around. test_redis_with_sentinel_failureover polls with a 2s interval so the 120s wait does not spawn a driver process per 100ms (Gemini review). The gcs_client_test thread_checker failure in CI attempt 2 reproduces locally only under parallel test load and its stack has no redis frames (TearDown polls the io_context on the main thread and a queued GcsActorManager callback trips its thread checker); it predates this stack. Signed-off-by: Dongjun Na <[email protected]>
|
Ref #65424 |
@nadongjun were you able to test this manually end to end or was this comment based on |
…ded exit The reconnect behavior for the most common topology, a single external Redis, was verified manually but had no automated regression test; only the Sentinel path did. Two tests close that: - test_redis_in_place_reconnect: kill the external Redis and bring a fresh one up on the same port. The same gcs_server process must serve internal-KV writes again (that path goes GCS -> Redis, so it only succeeds once the reconnect lands) and keep scheduling tasks. The new Redis is empty, which is fine for a live cluster: GCS keeps its runtime state in memory and Redis contents only matter for a GCS restart. - test_redis_permanently_down_bounded_exit: Redis never comes back. The grace period must hold first (the process outlives the old ~3.5s budget), and the exit must still come, bounded by grace + retry drain or the reconnect budget, whichever runs out first. Signed-off-by: Dongjun Na <[email protected]>
|
@andrewsykim Yes, manual E2E — the tables come from a local harness that boots each topology for real (single Redis, Sentinel, HAProxy, Cluster, TLS), kills/restarts the actual servers, and asserts that ray.get round trips succeed before and after. That pytest only covers the Sentinel path. I also just added pytest coverage for the plain Redis case: |
…e grace path Both from Cursor's review of the previous commit. test_redis_in_place_reconnect bound the replacement Redis while the SIGKILLed one could still hold the listen socket, and never checked the replacement was serving. Now it waits for the old pid to exit before binding and pings the new server before asserting anything against it. test_redis_permanently_down_bounded_exit treated surviving 4s as proof the grace period held, but that is only conclusive if something is draining a retry budget during those seconds. A helper thread now puts a Redis-bound internal-KV write in flight the moment Redis dies: without the grace period that command exhausts its ~3.5s budget and kills the process before the check; with it, the process outlives the check and then exits bounded as before. Signed-off-by: Dongjun Na <[email protected]>
From Cursor's review: Future.cancel() cannot stop a running call and the discarded executor left the probe thread inside internal_kv_put while the fixture tore the cluster down. The put now carries a 15s client timeout and the executor is shut down (joined) after the exit assertion, so the thread is gone before teardown. The probe only needs to be in flight for the first few seconds; the server-side command it created drains on its own schedule either way. Signed-off-by: Dongjun Na <[email protected]>
Signed-off-by: Dongjun Na <[email protected]>
…nds resume Signed-off-by: Dongjun Na <[email protected]>
…cking the pause Signed-off-by: Dongjun Na <[email protected]>
|
@rueian CI is green now. Could you take another look when you have time? |
… handshake Signed-off-by: Dongjun Na <[email protected]>
|
Hi @nadongjun, want to clarify what would happen if someone upgrades their ray cluster with FT from a version without the watermark to a version with the watermark? Will it keep restarting? |
…mark is off Signed-off-by: Dongjun Na <[email protected]>
|
No, upgrading from a version without the watermark won't cause restarts.
|
Signed-off-by: Dongjun Na <[email protected]>
| // reconnect AUTH that the server rejected, on a connection that rejection | ||
| // is already tearing down. The command never ran, so count it like a reply | ||
| // that never came. | ||
| const bool reached_redis = |
There was a problem hiding this comment.
A null reply here doesn't mean the command never reached Redis. Run reports a rejected submission straight to HandleFailure (line 489), so a null reply on this line comes from hiredis failing every pending callback when a context goes away, including commands it had already written to the socket. Redis may have run those. HandleFailure then refunds the attempt (line 350) and Run sends the command again on the new connection (line 378). The data stays right, since HSET, HSETNX and HDEL are idempotent, but the retry's reply describes the state the first run left behind:
HSETNXreturns 0 on the retry.RedisStoreClient::AsyncPutsends it for every internal KV put withoverwrite=false(redis_store_client.cc:162) and turns the 0 intoadded=false(redis_store_client.cc:169), whichHandleInternalKVPutreturns to the caller (gcs_kv_manager.cc:83). Job submission acts on it:JobManager.submit_jobraises "Job with submission_id ... already exists" (job_manager.py:559) for the job its own call created, and the record it wrote staysPENDINGwith no supervisor. Only_recover_running_jobs(job_manager.py:112), which runs when the dashboard starts, picks it up again.HSETandHDELunder-report what they added or deleted, andINCRBYonJobCounter, which isn't idempotent, skips a job ID. As far as I can tell nothing in Ray acts on those.
Today the GCS exits instead: the dead context stays null, every retry is rejected, and Run hits the RAY_LOG(FATAL) after num_redis_request_retries. put_info then times out after its 30 s default, and _recover_running_jobs settles the record after the head Pod restarts.
Could the retried HSETNX check its reply? The check can't live in AsyncPut's reply callback: SendRedisCmdWithKeys frees the key and sends the next queued request for it before calling that callback (redis_store_client.cc:324-330), so a queued delete or overwrite could land before the check. It fits in RedisRequestContext, which holds the key until it posts the callback (line 417):
- In
RedisResponseFn, whenredis_replyis null, mark the request as having lost a reply. - In the success branch, before the post: if the request lost a reply,
redis_cmds_[0]isHSETNX, and the reply is 0, sendHGET redis_cmds_[1] redis_cmds_[2]first. If it returnsredis_cmds_[3], hand the callback 1 instead of 0. TheHGETis a read, so it can be retried like any other command.
AsyncPut then needs no change, and only a put that lost a reply pays for the extra read. The check can't tell this request's write from an earlier put of the same bytes, but Ray's own callers either write unique values (job info, cluster ID) or accept an existing equal value (session name, node.py:1667).
For a test, ClosingProxy (redis_async_context_test.cc:375) could close the connection after forwarding an HSETNX but before forwarding its reply, and the test checks that AsyncPut reports added=true.
There was a problem hiding this comment.
Thanks. Fixed in 845b823 as you suggested: after a lost reply, a retried HSETNX that gets 0 checks the field with HGET and reports 1 if it holds its value.
Added TestPutReportsAddedWhenItsReplyIsLost, it fails without the fix.
I also checked the other writes (HSET, HDEL, INCRBY). Nothing else acts on their replies, so job submission was the only affected path.
Signed-off-by: Dongjun Na <[email protected]>
…elpers Signed-off-by: Dongjun Na <[email protected]>
|
Nice work @nadongjun! I will merge this once the rest tests pass. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit 4a3a5d7. Configure here.
| return; | ||
| } | ||
| } | ||
| redis_context->OnReconnectConfirmed(); |
There was a problem hiding this comment.
Reconnect check accepts read-only replicas
High Severity
The reconnect readiness check only issues HGET or PING, both of which succeed on a replica. A demoted primary or a proxy still routing to the old node is treated as a completed reconnect, commands are unpaused, and subsequent writes get -READONLY. Those error replies are not refunded, so the command budget drains in a few seconds and gcs_server exits even though a writable primary may appear moments later. Sentinel FAILOVER (demote, not kill) and a Service that still has the old endpoint both hit this path.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 4a3a5d7. Configure here.
| } | ||
| done(results.begin()->endpoint().address().to_string()); | ||
| }); | ||
| } |
There was a problem hiding this comment.
Hung DNS stalls all reconnect attempts
Medium Severity
Reconnect DNS uses async_resolve with no timeout, and reconnect_pending_ stays true until that lookup finishes. A hung or blackholed resolver (CoreDNS overload, missing nameservers) blocks every later attempt, so GCS never retries the connect even if Redis is already up. TCP connect and the Sentinel query both have dedicated timeouts; DNS does not. The command grace period then expires and gcs_server exits.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 4a3a5d7. Configure here.
… test Signed-off-by: Dongjun Na <[email protected]>
|
Hi @nadongjun, I think the Windows test keeps failing. Would you mind checking it? https://buildkite.com/ray-project/premerge/builds/77399#01a1f0f8-24c2-4f29-88a8-deb7455ae550 Full logs: |
|
@rueian Thanks for checking, Fixed in ca142ff. Redis 5.0.9 (Windows) drops auth on open connections when Windows tests on #77525 are waiting for approval. Could you unblock them? |



Description
When the async connection to Redis drops, hiredis frees the raw
redisAsyncContextand nothing puts it back. Every subsequent GCS command fails withStatus::Disconnecteduntilnum_redis_request_retriesruns out (~3.5s), and gcs_server aborts withFailed 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 (1/N) made the connection-failure paths return
Statusinstead 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
RedisRequestContexts hold a rawRedisAsyncContext*, 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, sinceredisAsyncConnectreports 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;0restores the old behaviour exactly). Error replies (-READONLY, …) drain the budget as before.test_redis_with_sentinel_failureoverasserted 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):
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 succeedsBefore this PR the timeline ends at t=3.5s with
Failed to run redis cmds: [PING] for 5 times.Behaviour matrix
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.Plain Redis (single node) — 9 scenarios
-LOADINGreply leaksHAProxy / Kubernetes Service + Sentinel-managed failover — 2 scenarios
Sentinel addressed directly — 8 scenarios
Sentinel now reports the primary at :7002, was :7001, reconnects to the promoted nodeRedis Cluster / TLS — 4 scenarios
CLUSTER FAILOVER, GCS pointed at a node directlyrediss://drop + reconnectConfig knobs — 6 scenarios
redis_reconnect_grace_period_ms=0redis_reconnect_grace_period_ms=5000redis_db_connect_retries=0/=1redis_retry_base_ms=1, max_ms=10num_redis_request_retries=0retries=3+grace=60sUnit tests: 4 new cases in
redis_async_context_test(in-placeReset, 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)
redis_db_connect_retriesbudget in wall-clock terms.Related issues
Closes #48781. Related: #53475, #64204 (SIGSEGV on failover, fixed earlier), #64299 (1/N prerequisite).
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.kuberay-gcs-ft.md: new section on what happens when the Redis connection drops, plus the tuning knobs.)RAY_redis_reconnect_grace_period_ms).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.
gcs_rpc_server_reconnect_timeout_sfrom_system_config#62462 touch gRPC reconnect settings, not the Redis connection). The adjacent fixes [core] Avoid GCS crash on Redis connection loss in RedisResponseFn #64204 and [core][1/N] Make RedisContext::Connect non-fatal on connection failure #64299 landed separately and this PR stacks on them.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 stackpytest python/ray/tests/test_gcs_fault_tolerance.py::test_redis_with_sentinel_failureover— passed (16.4s), withTEST_EXTERNAL_REDIS=1