Repository navigation
[core] Avoid GCS crash on Redis connection loss in RedisResponseFn - #64204
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a reconnection mechanism (Reconnect()) to RedisContext to recover from lost Redis connections (e.g., during failovers) instead of crashing. It stores connection parameters on initial connection and updates RedisRequestContext to reference RedisContext directly. The reviewer identified several critical issues with this implementation, including thread-safety and lifetime issues in async_context() that could lead to data races or use-after-free bugs, a bug where bootstrap addresses are overwritten in Sentinel/Cluster setups, and a potential crash in RunArgvAsync during active reconnections.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
Reviewed by Cursor Bugbot for commit 28f4384. Configure here.
Signed-off-by: Dongjun Na <[email protected]>
28f4384 to
bafecfc
Compare
|
@rueian PTAL |
…ay-project#64204) ## Description While testing, `gcs_server` crashed with a SIGSEGV during a Redis connection error (failover). Looking for a fix I found ray-project#48781, which solves it by reconnecting to Redis, but it was closed as stale without being merged. Its main blocker at the time (a dependency cycle in the GCS Redis client) has since been resolved by ray-project#49000 and ray-project#55655, so this PR ports that reconnect approach onto the current version. When the Redis connection is lost, an in-flight request retries against the released connection and dereferences a null pointer, crashing the GCS. This PR reconnects to Redis when the connection is dead so requests retry on a healthy connection instead of crashing. ## Related issues - Fixes ray-project#53475 - Based on ray-project#48781 by @MortalHappiness (closed without merge); credit for the original design. ## Additional information Reproduction: 1. Run a cluster with GCS fault tolerance backed by an HA Redis. 2. While the cluster is up, trigger a Redis primary failover e.g. kill/replace the Redis primary so a replica is promoted. 3. Before this PR, `gcs_server` exits with signal 11 and the head pod restarts; after this PR it reconnects to the new primary and continues. The exact crash we observed: ``` 2026-06-18 04:54:00,110 ERROR scripts.py:1219 -- Some Ray subprocesses exited unexpectedly: gcs_server [exit code=-11 (signal 11)] [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: *** SIGSEGV received at time=1781726136 on cpu 0 *** [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: PC: @ 0x55719802efb8 (unknown) ray::gcs::RedisRequestContext::RedisResponseFn() [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x7f6c34fb6520 (unknown) (unknown) [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x55719802f1f9 1168 ray::gcs::RedisRequestContext::Run() [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x55719801a748 224 ray::gcs::RedisStoreClient::AsyncCheckHealth() ``` --- ## Update: I first took the reconnect approach above, but a robust in-place reconnect needs `Connect()` to be non-fatal (it `RAY_CHECK`s today, so a transient failover still aborts `gcs_server`) - the larger refactor that stalled ray-project#48781. So this PR instead takes the minimal fix: null-guard the dereference so the request fails gracefully instead of crashing, and GCS fault tolerance recovers as today. Full reconnect is left as a follow-up (ray-project#48781). Signed-off-by: Dongjun Na <[email protected]>
#64299) ## Description RedisContext::Connect and its helpers RAY_CHECK / RAY_LOG(FATAL) on any connection failure, which aborts gcs_server. This blocks an in-place Redis reconnect: a reconnect attempt during a transient failover would just move the crash into Connect() instead of recovering. This PR converts the connection-failure paths to return Status instead of crashing. It is a prerequisite refactor, so behavior is unchanged: no caller consumes the new failure path yet, startup still aborts on a connection failure because RedisClient::Connect keeps its RAY_CHECK_OK, and the retry budget (redis_db_connect_retries) is preserved. ## Related issues Related to #48781 (in-place reconnect, stalled because it needs Connect() to be non-fatal) Related to #53475, #64204 (gcs_server SIGSEGV on Redis failover) ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]> Co-authored-by: Rueian <[email protected]>
Problem RedisContext has no reconnect path. When the connection drops, hiredis' disconnect callback releases the raw async context and nothing ever refills it, so every retry re-observes the same null and RedisRequestContext::Run() eventually hits RAY_LOG(FATAL). ray-project#64204 stopped the null dereference and 1/N (ray-project#64299) made Connect() non-fatal. Even so, gcs_server still dies on a dropped Redis connection. It just aborts now instead of taking SIGSEGV. A lifetime cycle is what stalled ray-project#48781. Connect() ends with `redis_async_context_.reset(new RedisAsyncContext(...))`, and in-flight RedisRequestContexts hold a raw pointer to that object. Calling Connect() again to reconnect would dangle all of them. Fix Keep the RedisAsyncContext object and swap only what is stale. RedisAsyncContext::Reset() closes the old asio socket and adopts a freshly connected raw context, reusing the constructor body (now AttachLocked). The object's address does not move, so in-flight requests stay valid and recover on their next retry. RedisContext retains the connect parameters, registers a disconnect handler, and drives a backoff loop on the io_service thread. It never reconnects synchronously inside hiredis' teardown. A weak_ptr sentinel keeps a delayed reconnect from touching a destroyed RedisContext. Two related fixes in the same paths: - RedisAsyncCommand{,Argv} read `redis_async_context_->errstr` after dropping the lock, where a concurrent disconnect can null it. Copy the string under the lock. - HandleIo RAY_CHECKed the context is non-null, but a socket operation queued before the drop can complete after hiredis freed it. Return instead; the reconnect path re-arms the socket. ResetRawRedisAsyncContext deliberately stays lock-free. hiredis reaches it from redisAsyncHandleRead/Write while HandleIo already holds the mutex, and std::mutex is not recursive. Scope This covers a dropped connection to a live server, the ray-project#48781 idle timeout shape. A request's retry budget spans ~3.5s, so a failover that takes longer still exhausts it. Converting that budget to a wall-clock deadline is left to 3/N. Verified with an integration repro that drops only the client connections (`CLIENT KILL TYPE normal`). Before, gcs_server dies 5s later and the cluster is unusable. After, it reconnects in 0ms and tasks keep running. Related to ray-project#48781, ray-project#53475, ray-project#64204 Signed-off-by: Dongjun Na <[email protected]>
Problem RedisContext has no reconnect path. When the connection drops, hiredis' disconnect callback releases the raw async context and nothing refills it, so every retry re-observes the same null and RedisRequestContext::Run() ends in RAY_LOG(FATAL). ray-project#64204 stopped the null dereference and 1/N (ray-project#64299) made Connect() non-fatal, but gcs_server still dies on a dropped Redis connection. It just aborts instead of taking SIGSEGV. Four things stood in the way: 1. A lifetime cycle, which is what stalled ray-project#48781. Connect() ends with `redis_async_context_.reset(new RedisAsyncContext(...))`, and in-flight RedisRequestContexts hold a raw pointer to that object. Calling Connect() again to reconnect dangles all of them. 2. redisAsyncConnect is non-blocking and reports a healthy context even when nothing is listening. On a failed connect hiredis then frees the context without running the disconnect callback, since __redisAsyncFree only runs that one once REDIS_CONNECTED was set. A reconnect that trusts the return value declares success against a dead server and the next command dereferences freed memory. 3. The address recorded at startup stops being right. Sentinel hands out the primary's own address, and a failover moves it; a name resolved once can stop pointing anywhere. Ray documents both Sentinel and a single-shard Redis Cluster as supported GCS FT backing stores. 4. A command's retry budget is a count (num_redis_request_retries) whose wall-clock span happens to be ~3.5s. A Sentinel failover takes longer, so the budget ran out moments before the reconnect landed. Fix Keep the RedisAsyncContext object and swap only what is stale. RedisAsyncContext::Reset() closes the old asio socket and adopts a freshly connected raw context, reusing the constructor body (now AttachLocked). The object's address does not move, so in-flight requests stay valid and recover on their next retry. Register a connect callback, not just a disconnect one. Only that callback declares the reconnect successful; a failed connect releases the raw pointer and lets the backoff loop try again. Re-resolve before each attempt. Connect() records the Sentinel address it was originally given, and each reconnect asks it who the primary is now. The lookup ConnectRedisSentinel already did is split out as QuerySentinelForPrimary so both paths share it. DNS is resolved again too, for the case where the name outlives the address behind it. A literal IP resolves to itself, so that case is unaffected. Stop spending the command retry budget on attempts that never reached Redis. A missing reply, rather than an error reply, is the signal: either the context was gone, or it was still mid-connect when hiredis took the command and then freed it. Both say nothing about the command itself, so the retry is given back and bounded by wall clock instead, via a new redis_reconnect_grace_period_ms (60s, mirroring gcs_rpc_server_reconnect_timeout_s). Setting it to 0 restores the old behaviour. Disconnect() now parks the reconnect logic until the next Connect(). Resetting the async context runs hiredis' teardown, which calls back into us, and that can happen from ~RedisContext where the io_context is already gone; scheduling a reconnect there crashed four GCS test binaries. Two more fixes in the same paths: - RedisAsyncCommand{,Argv} read `redis_async_context_->errstr` after dropping the lock, where a concurrent disconnect can null it. Copy the string under the lock. - HandleIo RAY_CHECKed the context is non-null, but a socket operation queued before the drop can complete after hiredis freed it. Return instead; the reconnect path re-arms the socket. ResetRawRedisAsyncContext deliberately stays lock-free. hiredis reaches it from redisAsyncHandleRead/Write while HandleIo already holds the mutex, and std::mutex is not recursive. Verified Single Redis: connection drop, five drops in a row, process restart with and without persistence, load across a drop, shutdown mid-outage, and a 45s outage under continuous load, where gcs_server now survives and reconnects instead of exhausting a command's retries partway through (RSS grows ~1.3MB over the outage and settles). HAProxy in front of a Sentinel-managed pair, and Sentinel with no proxy: killing the primary takes gcs_server down before this change; after it, the reconnect follows the promotion and tasks keep running. Also over TLS, against a single-shard Redis Cluster, with password auth, by hostname rather than IP, and with a worker node attached. Edge cases: Redis never returns (exits inside the grace period rather than hanging), two failovers in a row, old primary rejoining as a replica (stays on the new primary), Sentinel dying mid-reconnect or answering with no primary at all (no crash, no false "Reconnected"), quorum lost so nothing is promoted, shutdown landing inside the backoff window, Redis busy loading a 400k-key AOF, a grace period of 0, 60 drops back to back (no descriptor or RSS drift), and plain non-Sentinel Redis (unaffected, zero re-resolutions). test_redis_with_sentinel_failureover asserted the old behaviour, down to a TODO in its docstring asking for exactly this ("GCS should automatically try re-connect to sentinel"). It waited for gcs_server to exit, then restarted it by hand. It now asserts the process survives the promotion and that the cluster, including a detached actor made before the failover, still works. The updated test passes with this change and cannot pass without it: on master the driver dies along with GCS. test_redis_failureover carries the same TODO for Redis Cluster, where there is no Sentinel to ask. Its gcs_server should still exit, just after the grace period rather than the retry budget, so the test's 1000s wait still covers it. That path is untested here -- the fixture's Redis Cluster does not form on macOS (cluster_state:fail) -- so CI is the first place it runs. Ordering note: `fix/redis-test-server-readiness` fixes a startup race in StartUpRedisServer where the helper sleeps a flat 200ms instead of waiting for the port. That race is unchanged in frequency here, but its symptom moves: on master a caught request exhausts its budget and fails fast, while with this change it retries out the grace period and the test times out instead. Landing that PR first keeps the race from mattering. Related to ray-project#48781, ray-project#53475, ray-project#64204 Signed-off-by: Dongjun Na <[email protected]>
Problem RedisContext has no reconnect path. When the connection drops, hiredis' disconnect callback releases the raw async context and nothing refills it, so every retry re-observes the same null and RedisRequestContext::Run() ends in RAY_LOG(FATAL). ray-project#64204 stopped the null dereference and 1/N (ray-project#64299) made Connect() non-fatal, but gcs_server still dies on a dropped Redis connection. It just aborts instead of taking SIGSEGV. Four things stood in the way: 1. A lifetime cycle, which is what stalled ray-project#48781. Connect() ends with `redis_async_context_.reset(new RedisAsyncContext(...))`, and in-flight RedisRequestContexts hold a raw pointer to that object. Calling Connect() again to reconnect dangles all of them. 2. redisAsyncConnect is non-blocking and reports a healthy context even when nothing is listening. On a failed connect hiredis then frees the context without running the disconnect callback, since __redisAsyncFree only runs that one once REDIS_CONNECTED was set. A reconnect that trusts the return value declares success against a dead server and the next command dereferences freed memory. 3. The address recorded at startup stops being right. Sentinel hands out the primary's own address, and a failover moves it; a name resolved once can stop pointing anywhere. Ray documents both Sentinel and a single-shard Redis Cluster as supported GCS FT backing stores. 4. A command's retry budget is a count (num_redis_request_retries) whose wall-clock span happens to be ~3.5s. A Sentinel failover takes longer, so the budget ran out moments before the reconnect landed. Fix Keep the RedisAsyncContext object and swap only what is stale. RedisAsyncContext::Reset() closes the old asio socket and adopts a freshly connected raw context, reusing the constructor body (now AttachLocked). The object's address does not move, so in-flight requests stay valid and recover on their next retry. Register a connect callback, not just a disconnect one. Only that callback declares the reconnect successful; a failed connect releases the raw pointer and lets the backoff loop try again. Re-resolve before each attempt. Connect() records the Sentinel address it was originally given, and each reconnect asks it who the primary is now. The lookup ConnectRedisSentinel already did is split out as QuerySentinelForPrimary so both paths share it. DNS is resolved again too, for the case where the name outlives the address behind it. A literal IP resolves to itself, so that case is unaffected. Stop spending the command retry budget on attempts that never reached Redis. A missing reply, rather than an error reply, is the signal: either the context was gone, or it was still mid-connect when hiredis took the command and then freed it. Both say nothing about the command itself, so the retry is given back and bounded by wall clock instead, via a new redis_reconnect_grace_period_ms (60s, mirroring gcs_rpc_server_reconnect_timeout_s). Setting it to 0 restores the old behaviour. Disconnect() now parks the reconnect logic until the next Connect(). Resetting the async context runs hiredis' teardown, which calls back into us, and that can happen from ~RedisContext where the io_context is already gone; scheduling a reconnect there crashed four GCS test binaries. Two more fixes in the same paths: - RedisAsyncCommand{,Argv} read `redis_async_context_->errstr` after dropping the lock, where a concurrent disconnect can null it. Copy the string under the lock. - HandleIo RAY_CHECKed the context is non-null, but a socket operation queued before the drop can complete after hiredis freed it. Return instead; the reconnect path re-arms the socket. ResetRawRedisAsyncContext deliberately stays lock-free. hiredis reaches it from redisAsyncHandleRead/Write while HandleIo already holds the mutex, and std::mutex is not recursive. Verified Single Redis: connection drop, five drops in a row, process restart with and without persistence, load across a drop, shutdown mid-outage, and a 45s outage under continuous load, where gcs_server now survives and reconnects instead of exhausting a command's retries partway through (RSS grows ~1.3MB over the outage and settles). HAProxy in front of a Sentinel-managed pair, and Sentinel with no proxy: killing the primary takes gcs_server down before this change; after it, the reconnect follows the promotion and tasks keep running. Also over TLS, against a single-shard Redis Cluster, with password auth, by hostname rather than IP, and with a worker node attached. Edge cases: Redis never returns (exits inside the grace period rather than hanging), two failovers in a row, old primary rejoining as a replica (stays on the new primary), Sentinel dying mid-reconnect or answering with no primary at all (no crash, no false "Reconnected"), quorum lost so nothing is promoted, shutdown landing inside the backoff window, Redis busy loading a 400k-key AOF, a grace period of 0, 60 drops back to back (no descriptor or RSS drift), and plain non-Sentinel Redis (unaffected, zero re-resolutions). test_redis_with_sentinel_failureover asserted the old behaviour, down to a TODO in its docstring asking for exactly this ("GCS should automatically try re-connect to sentinel"). It waited for gcs_server to exit, then restarted it by hand. It now asserts the process survives the promotion and that the cluster, including a detached actor made before the failover, still works. The updated test passes with this change and cannot pass without it: on master the driver dies along with GCS. test_redis_failureover carries the same TODO for Redis Cluster, where there is no Sentinel to ask. Its gcs_server should still exit, just after the grace period rather than the retry budget, so the test's 1000s wait still covers it. That path is untested here -- the fixture's Redis Cluster does not form on macOS (cluster_state:fail) -- so CI is the first place it runs. Rebased on ray-project#65246, which replaced StartUpRedisServer's flat 200ms sleep with a readiness probe. That mattered here: while the sleep was in place, a test that caught the startup race would exhaust a request's budget and fail fast on master, but retry out the grace period and time out with this change. Related to ray-project#48781, ray-project#53475, ray-project#64204 Signed-off-by: Dongjun Na <[email protected]>
Problem RedisContext has no reconnect path. When the connection drops, hiredis' disconnect callback releases the raw async context and nothing refills it, so every retry re-observes the same null and RedisRequestContext::Run() ends in RAY_LOG(FATAL). ray-project#64204 stopped the null dereference and 1/N (ray-project#64299) made Connect() non-fatal, but gcs_server still dies on a dropped Redis connection. It just aborts instead of taking SIGSEGV. Four things stood in the way: 1. A lifetime cycle, which is what stalled ray-project#48781. Connect() ends with `redis_async_context_.reset(new RedisAsyncContext(...))`, and in-flight RedisRequestContexts hold a raw pointer to that object. Calling Connect() again to reconnect dangles all of them. 2. redisAsyncConnect is non-blocking and reports a healthy context even when nothing is listening. On a failed connect hiredis then frees the context without running the disconnect callback, since __redisAsyncFree only runs that one once REDIS_CONNECTED was set. A reconnect that trusts the return value declares success against a dead server and the next command dereferences freed memory. 3. The address recorded at startup stops being right. Sentinel hands out the primary's own address, and a failover moves it; a name resolved once can stop pointing anywhere. Ray documents both Sentinel and a single-shard Redis Cluster as supported GCS FT backing stores. 4. A command's retry budget is a count (num_redis_request_retries) whose wall-clock span happens to be ~3.5s. A Sentinel failover takes longer, so the budget ran out moments before the reconnect landed. Fix Keep the RedisAsyncContext object and swap only what is stale. RedisAsyncContext::Reset() closes the old asio socket and adopts a freshly connected raw context, reusing the constructor body (now AttachLocked). The object's address does not move, so in-flight requests stay valid and recover on their next retry. Register a connect callback, not just a disconnect one. Only that callback declares the reconnect successful; a failed connect releases the raw pointer and lets the backoff loop try again. Re-resolve before each attempt. Connect() records the Sentinel address it was originally given, and each reconnect asks it who the primary is now. The lookup ConnectRedisSentinel already did is split out as QuerySentinelForPrimary so both paths share it. DNS is resolved again too, for the case where the name outlives the address behind it. A literal IP resolves to itself, so that case is unaffected. Stop spending the command retry budget on attempts that never reached Redis. A missing reply, rather than an error reply, is the signal: either the context was gone, or it was still mid-connect when hiredis took the command and then freed it. Both say nothing about the command itself, so the retry is given back and bounded by wall clock instead, via a new redis_reconnect_grace_period_ms (60s, mirroring gcs_rpc_server_reconnect_timeout_s). Setting it to 0 restores the old behaviour. Disconnect() now parks the reconnect logic until the next Connect(). Resetting the async context runs hiredis' teardown, which calls back into us, and that can happen from ~RedisContext where the io_context is already gone; scheduling a reconnect there crashed four GCS test binaries. Two more fixes in the same paths: - RedisAsyncCommand{,Argv} read `redis_async_context_->errstr` after dropping the lock, where a concurrent disconnect can null it. Copy the string under the lock. - HandleIo RAY_CHECKed the context is non-null, but a socket operation queued before the drop can complete after hiredis freed it. Return instead; the reconnect path re-arms the socket. ResetRawRedisAsyncContext deliberately stays lock-free. hiredis reaches it from redisAsyncHandleRead/Write while HandleIo already holds the mutex, and std::mutex is not recursive. Verified Single Redis: connection drop, five drops in a row, process restart with and without persistence, load across a drop, shutdown mid-outage, and a 45s outage under continuous load, where gcs_server now survives and reconnects instead of exhausting a command's retries partway through (RSS grows ~1.3MB over the outage and settles). HAProxy in front of a Sentinel-managed pair, and Sentinel with no proxy: killing the primary takes gcs_server down before this change; after it, the reconnect follows the promotion and tasks keep running. Also over TLS, against a single-shard Redis Cluster, with password auth, by hostname rather than IP, and with a worker node attached. Edge cases: Redis never returns (exits inside the grace period rather than hanging), two failovers in a row, old primary rejoining as a replica (stays on the new primary), Sentinel dying mid-reconnect or answering with no primary at all (no crash, no false "Reconnected"), quorum lost so nothing is promoted, shutdown landing inside the backoff window, Redis busy loading a 400k-key AOF, a grace period of 0, 60 drops back to back (no descriptor or RSS drift), and plain non-Sentinel Redis (unaffected, zero re-resolutions). test_redis_with_sentinel_failureover asserted the old behaviour, down to a TODO in its docstring asking for exactly this ("GCS should automatically try re-connect to sentinel"). It waited for gcs_server to exit, then restarted it by hand. It now asserts the process survives the promotion and that the cluster, including a detached actor made before the failover, still works. The updated test passes with this change and cannot pass without it: on master the driver dies along with GCS. test_redis_failureover carries the same TODO for Redis Cluster, where there is no Sentinel to ask. Its gcs_server should still exit, just after the grace period rather than the retry budget, so the test's 1000s wait still covers it. That path is untested here -- the fixture's Redis Cluster does not form on macOS (cluster_state:fail) -- so CI is the first place it runs. The reconnect loop reuses knobs that already existed: redis_db_connect_retries bounds the attempts, and redis_retry_{base_ms,multiplier,max_ms} shape the backoff, the same ones the command retry path uses. Only redis_reconnect_grace_period_ms is new. Verified at non-default values, including the boundaries: 0 attempts, 1 attempt, a 1-10ms backoff (no hot spin), num_redis_request_retries=0, and a small attempt budget against a large grace period, where the smaller bound is the one that ends it. Rebased on ray-project#65246, which replaced StartUpRedisServer's flat 200ms sleep with a readiness probe. That mattered here: while the sleep was in place, a test that caught the startup race would exhaust a request's budget and fail fast on master, but retry out the grace period and time out with this change. Related to ray-project#48781, ray-project#53475, ray-project#64204 Signed-off-by: Dongjun Na <[email protected]>
ray-project#64299) ## Description RedisContext::Connect and its helpers RAY_CHECK / RAY_LOG(FATAL) on any connection failure, which aborts gcs_server. This blocks an in-place Redis reconnect: a reconnect attempt during a transient failover would just move the crash into Connect() instead of recovering. This PR converts the connection-failure paths to return Status instead of crashing. It is a prerequisite refactor, so behavior is unchanged: no caller consumes the new failure path yet, startup still aborts on a connection failure because RedisClient::Connect keeps its RAY_CHECK_OK, and the retry budget (redis_db_connect_retries) is preserved. ## Related issues Related to ray-project#48781 (in-place reconnect, stalled because it needs Connect() to be non-fatal) Related to ray-project#53475, ray-project#64204 (gcs_server SIGSEGV on Redis failover) ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]> Co-authored-by: Rueian <[email protected]>
…ay-project#64204) ## Description While testing, `gcs_server` crashed with a SIGSEGV during a Redis connection error (failover). Looking for a fix I found ray-project#48781, which solves it by reconnecting to Redis, but it was closed as stale without being merged. Its main blocker at the time (a dependency cycle in the GCS Redis client) has since been resolved by ray-project#49000 and ray-project#55655, so this PR ports that reconnect approach onto the current version. When the Redis connection is lost, an in-flight request retries against the released connection and dereferences a null pointer, crashing the GCS. This PR reconnects to Redis when the connection is dead so requests retry on a healthy connection instead of crashing. ## Related issues - Fixes ray-project#53475 - Based on ray-project#48781 by @MortalHappiness (closed without merge); credit for the original design. ## Additional information Reproduction: 1. Run a cluster with GCS fault tolerance backed by an HA Redis. 2. While the cluster is up, trigger a Redis primary failover e.g. kill/replace the Redis primary so a replica is promoted. 3. Before this PR, `gcs_server` exits with signal 11 and the head pod restarts; after this PR it reconnects to the new primary and continues. The exact crash we observed: ``` 2026-06-18 04:54:00,110 ERROR scripts.py:1219 -- Some Ray subprocesses exited unexpectedly: gcs_server [exit code=-11 (signal 11)] [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: *** SIGSEGV received at time=1781726136 on cpu 0 *** [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: PC: @ 0x55719802efb8 (unknown) ray::gcs::RedisRequestContext::RedisResponseFn() [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x7f6c34fb6520 (unknown) (unknown) [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x55719802f1f9 1168 ray::gcs::RedisRequestContext::Run() [2026-06-18 04:55:36,551 E 42 42] (gcs_server) logging.cc:474: @ 0x55719801a748 224 ray::gcs::RedisStoreClient::AsyncCheckHealth() ``` --- ## Update: I first took the reconnect approach above, but a robust in-place reconnect needs `Connect()` to be non-fatal (it `RAY_CHECK`s today, so a transient failover still aborts `gcs_server`) - the larger refactor that stalled ray-project#48781. So this PR instead takes the minimal fix: null-guard the dereference so the request fails gracefully instead of crashing, and GCS fault tolerance recovers as today. Full reconnect is left as a follow-up (ray-project#48781). Signed-off-by: Dongjun Na <[email protected]> Signed-off-by: 400Ping <[email protected]>
ray-project#64299) ## Description RedisContext::Connect and its helpers RAY_CHECK / RAY_LOG(FATAL) on any connection failure, which aborts gcs_server. This blocks an in-place Redis reconnect: a reconnect attempt during a transient failover would just move the crash into Connect() instead of recovering. This PR converts the connection-failure paths to return Status instead of crashing. It is a prerequisite refactor, so behavior is unchanged: no caller consumes the new failure path yet, startup still aborts on a connection failure because RedisClient::Connect keeps its RAY_CHECK_OK, and the retry budget (redis_db_connect_retries) is preserved. ## Related issues Related to ray-project#48781 (in-place reconnect, stalled because it needs Connect() to be non-fatal) Related to ray-project#53475, ray-project#64204 (gcs_server SIGSEGV on Redis failover) ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]> Co-authored-by: Rueian <[email protected]> Signed-off-by: 400Ping <[email protected]>
ray-project#64299) ## Description RedisContext::Connect and its helpers RAY_CHECK / RAY_LOG(FATAL) on any connection failure, which aborts gcs_server. This blocks an in-place Redis reconnect: a reconnect attempt during a transient failover would just move the crash into Connect() instead of recovering. This PR converts the connection-failure paths to return Status instead of crashing. It is a prerequisite refactor, so behavior is unchanged: no caller consumes the new failure path yet, startup still aborts on a connection failure because RedisClient::Connect keeps its RAY_CHECK_OK, and the retry budget (redis_db_connect_retries) is preserved. ## Related issues Related to ray-project#48781 (in-place reconnect, stalled because it needs Connect() to be non-fatal) Related to ray-project#53475, ray-project#64204 (gcs_server SIGSEGV on Redis failover) ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]> Co-authored-by: Rueian <[email protected]>
…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]>

Description
While testing,
gcs_servercrashed with a SIGSEGV during a Redis connection error (failover). Looking for a fix I found #48781, which solves it by reconnecting to Redis, but it was closed as stale without being merged. Its main blocker at the time (a dependency cycle in the GCS Redis client) has since been resolved by #49000 and #55655, so this PR ports that reconnect approach onto the current version.When the Redis connection is lost, an in-flight request retries against the released connection and dereferences a null pointer, crashing the GCS. This PR reconnects to Redis when the connection is dead so requests retry on a healthy connection instead of crashing.
Related issues
Additional information
Reproduction:
gcs_serverexits with signal 11 and the head pod restarts; after this PR it reconnects to the new primary and continues.The exact crash we observed:
Update:
I first took the reconnect approach above, but a robust in-place reconnect needs
Connect()to be non-fatal (itRAY_CHECKs today, so a transient failover still abortsgcs_server) - the larger refactor that stalled #48781. So this PR instead takes the minimal fix: null-guard the dereference so the request fails gracefully instead of crashing, and GCS fault tolerance recovers as today. Full reconnect is left as a follow-up (#48781).