Repository navigation
[Core] Fix double-free in redis_async_context_test - #65246
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves Redis startup reliability in tests by replacing a hardcoded sleep with a polling mechanism that waits for the port to accept connections. It also addresses potential double-free crashes in redis_async_context_test.cc by releasing the raw context in the connect and disconnect callbacks. The review feedback suggests using boost::asio::ip::address_v4::loopback() instead of parsing the loopback IP string at runtime, and recommends adding defensive null checks and using static_cast instead of reinterpret_cast when casting c->data from void*.
Problem
1. Double free. TestRedisCommands gives a raw redisAsyncContext to a
RedisAsyncContext, which owns it, but neither of its callbacks
releases it. hiredis frees that context itself once the connection
ends, so the destructor frees it a second time. The test process dies
instead of reporting what went wrong.
Two paths reach it, and hiredis handles them differently:
- The connection is established and later drops. hiredis runs
__redisAsyncDisconnect -> __redisAsyncFree, which invokes the
disconnect callback and then frees.
- The connection never completes. __redisAsyncHandleConnectFailure
runs the connect callback with REDIS_ERR and then frees, but the
disconnect callback is skipped: __redisAsyncFree only runs it when
REDIS_CONNECTED was set.
Both reproduce on master. Killing the server after a successful
connect dies on every run (9/10 SIGSEGV in redisFree, 1/10 caught by
the allocator); connecting to a port with no listener dies in
redisFree as well.
2. Startup race, which is how the second path is reached in CI.
StartUpRedisServer sleeps a flat 200ms after Process::Spawn, and
Process::Spawn only reports that the binary launched. If the server
has not bound yet, the caller connects to a closed port. Eight test
files share this helper; two of them have been flagged flaky before
(ray-project#55773, ray-project#55772) and closed without a root cause.
Fix
1. Release the raw context from both callbacks, the same way the
production callback in redis_context.cc does it, and only on the
connect path when the status is an error, since a successful connect
frees nothing. Both releases come before the assertion so an early
return cannot skip them. redisAsyncContext::data is a user field
("Not used by hiredis"), distinct from the ev.data that
RedisAsyncContext uses. Both probes now end in an ordinary gtest
failure.
2. Poll until the port accepts a TCP connection instead of sleeping,
bounded by 30s. That is also faster when Redis starts quickly:
redis_async_context_test goes from ~1.2s to ~0.4s.
Signed-off-by: Dongjun Na <[email protected]>
d4a8623 to
34185ed
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 34185ed. Configure here.
Review feedback: the helper had a prose comment but no parameter or return documentation. Add them in the style the rest of src/ray uses (\param and \return in /// comments) rather than the @PARAM form, which appears about five times less often in this tree. Signed-off-by: Dongjun Na <[email protected]>
The probe called the throwing overload of socket.close(). Connect failures are the normal case while the server is still coming up, and close() on a socket left in that state can fail, which would raise system_error out of a helper that has no handler above it and take the test process down. Use the error_code overload and ignore the result: the socket is being discarded either way, and the connect result is what the caller cares about. 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]>
## Description ### Problem 1. Double free. `TestRedisCommands` gives a raw redisAsyncContext to a `RedisAsyncContext`, which owns it, but neither of its callbacks releases it. hiredis frees that context itself once the connection ends, so the destructor frees it a second time. The test process dies instead of reporting what went wrong. - Two paths reach it, and hiredis handles them differently: - The connection is established and later drops. hiredis runs __redisAsyncDisconnect -> __redisAsyncFree, which invokes the disconnect callback and then frees. - The connection never completes. __redisAsyncHandleConnectFailure runs the connect callback with REDIS_ERR and then frees, but the disconnect callback is skipped: __redisAsyncFree only runs it when REDIS_CONNECTED was set. Both reproduce. Killing the server after a successful connect dies on every run (9/10 SIGSEGV in redisFree, 1/10 caught by the allocator); connecting to a port with no listener dies in redisFree as well. 2. Startup race, which is how the second path is reached in CI. `StartUpRedisServer` sleeps a flat 200ms after Process::Spawn, and Process::Spawn only reports that the binary launched. If the server has not bound yet, the caller connects to a closed port. Eight test files share this helper; two of them have been flagged flaky before (ray-project#55773, ray-project#55772) and closed without a root cause. ### Fix 1. Release the raw context from both callbacks, the same way the production callback in redis_context.cc does it, and only on the connect path when the status is an error, since a successful connect frees nothing. Both releases come before the assertion so an early return cannot skip them. redisAsyncContext::data is a user field ("Not used by hiredis"), distinct from the ev.data that RedisAsyncContext uses. Both probes now end in an ordinary gtest failure. 2. Poll until the port accepts a TCP connection instead of sleeping, bounded by 30s. That is also faster when Redis starts quickly: redis_async_context_test goes from ~1.2s to ~0.4s. ## Related issues Related to ray-project#55773, ray-project#55772 ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]>
## Description ### Problem 1. Double free. `TestRedisCommands` gives a raw redisAsyncContext to a `RedisAsyncContext`, which owns it, but neither of its callbacks releases it. hiredis frees that context itself once the connection ends, so the destructor frees it a second time. The test process dies instead of reporting what went wrong. - Two paths reach it, and hiredis handles them differently: - The connection is established and later drops. hiredis runs __redisAsyncDisconnect -> __redisAsyncFree, which invokes the disconnect callback and then frees. - The connection never completes. __redisAsyncHandleConnectFailure runs the connect callback with REDIS_ERR and then frees, but the disconnect callback is skipped: __redisAsyncFree only runs it when REDIS_CONNECTED was set. Both reproduce. Killing the server after a successful connect dies on every run (9/10 SIGSEGV in redisFree, 1/10 caught by the allocator); connecting to a port with no listener dies in redisFree as well. 2. Startup race, which is how the second path is reached in CI. `StartUpRedisServer` sleeps a flat 200ms after Process::Spawn, and Process::Spawn only reports that the binary launched. If the server has not bound yet, the caller connects to a closed port. Eight test files share this helper; two of them have been flagged flaky before (ray-project#55773, ray-project#55772) and closed without a root cause. ### Fix 1. Release the raw context from both callbacks, the same way the production callback in redis_context.cc does it, and only on the connect path when the status is an error, since a successful connect frees nothing. Both releases come before the assertion so an early return cannot skip them. redisAsyncContext::data is a user field ("Not used by hiredis"), distinct from the ev.data that RedisAsyncContext uses. Both probes now end in an ordinary gtest failure. 2. Poll until the port accepts a TCP connection instead of sleeping, bounded by 30s. That is also faster when Redis starts quickly: redis_async_context_test goes from ~1.2s to ~0.4s. ## Related issues Related to ray-project#55773, ray-project#55772 ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]> Signed-off-by: 400Ping <[email protected]>
## Description ### Problem 1. Double free. `TestRedisCommands` gives a raw redisAsyncContext to a `RedisAsyncContext`, which owns it, but neither of its callbacks releases it. hiredis frees that context itself once the connection ends, so the destructor frees it a second time. The test process dies instead of reporting what went wrong. - Two paths reach it, and hiredis handles them differently: - The connection is established and later drops. hiredis runs __redisAsyncDisconnect -> __redisAsyncFree, which invokes the disconnect callback and then frees. - The connection never completes. __redisAsyncHandleConnectFailure runs the connect callback with REDIS_ERR and then frees, but the disconnect callback is skipped: __redisAsyncFree only runs it when REDIS_CONNECTED was set. Both reproduce. Killing the server after a successful connect dies on every run (9/10 SIGSEGV in redisFree, 1/10 caught by the allocator); connecting to a port with no listener dies in redisFree as well. 2. Startup race, which is how the second path is reached in CI. `StartUpRedisServer` sleeps a flat 200ms after Process::Spawn, and Process::Spawn only reports that the binary launched. If the server has not bound yet, the caller connects to a closed port. Eight test files share this helper; two of them have been flagged flaky before (ray-project#55773, ray-project#55772) and closed without a root cause. ### Fix 1. Release the raw context from both callbacks, the same way the production callback in redis_context.cc does it, and only on the connect path when the status is an error, since a successful connect frees nothing. Both releases come before the assertion so an early return cannot skip them. redisAsyncContext::data is a user field ("Not used by hiredis"), distinct from the ev.data that RedisAsyncContext uses. Both probes now end in an ordinary gtest failure. 2. Poll until the port accepts a TCP connection instead of sleeping, bounded by 30s. That is also faster when Redis starts quickly: redis_async_context_test goes from ~1.2s to ~0.4s. ## Related issues Related to ray-project#55773, ray-project#55772 ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Dongjun Na <[email protected]>

Description
Problem
TestRedisCommandsgives a raw redisAsyncContext to aRedisAsyncContext, which owns it, but neither of its callbacks releases it. hiredis frees that context itself once the connection ends, so the destructor frees it a second time. The test process dies instead of reporting what went wrong.Both reproduce. Killing the server after a successful connect dies on every run (9/10 SIGSEGV in redisFree, 1/10 caught by the allocator); connecting to a port with no listener dies in redisFree as well.
StartUpRedisServersleeps a flat 200ms after Process::Spawn, and Process::Spawn only reports that the binary launched. If the server has not bound yet, the caller connects to a closed port. Eight test files share this helper; two of them have been flagged flaky before (CI test linux://src/ray/gcs/store_client/tests:redis_store_client_test is flaky #55773, CI test linux://src/ray/gcs/store_client/tests:chaos_redis_store_client_test is flaky #55772) and closed without a root cause.Fix
Release the raw context from both callbacks, the same way the production callback in redis_context.cc does it, and only on the connect path when the status is an error, since a successful connect frees nothing. Both releases come before the assertion so an early return cannot skip them. redisAsyncContext::data is a user field ("Not used by hiredis"), distinct from the ev.data that RedisAsyncContext uses. Both probes now end in an ordinary gtest failure.
Poll until the port accepts a TCP connection instead of sleeping, bounded by 30s. That is also faster when Redis starts quickly: redis_async_context_test goes from ~1.2s to ~0.4s.
Related issues
Related to #55773, #55772
Additional information