Repository navigation
fix: refresh dynamic auth credentials on dedicated connections - #1048
Conversation
…ground worker (#1050) ## Problem `pipe.Close` can block forever when another waiter is in flight at the same time. `Close` starts the background worker only when it is the only waiter, so that it does not race with a sync read (`8503b21`). Its graceful `PING` then relies on the other waiter, assumed to be a `syncDo`, to start the worker once the closed connection breaks its read. But the other waiter can also be: - a concurrent `Close`, for example the lifetime timer's `expired()` racing with `pool.Acquire`, `pool.Store` or the user; - a `Do` that sees the pipe already stopping and returns an error. Both leave without starting a worker: ``` Close A (e.g. lifetime timer) Close B (or a Do) ───────────────────────────── ───────────────── blcksig++ → 1 blcksig++ → 2 waits++ → 1 waits++ → 2 state 0→2 ✓, but waits != 1 └─► background worker NOT started state CAS fails → skips the PING path, waits-- and returns (a Do returns an error) PutOne(PING) <-ch ◄── never answered escape timer closes the conn after 1s, but no worker drains the queue ``` ``` ┌──────────────┐ PutOne(PING) ┌──────────────┐ drain / answer ┌─────────────────────┐ │ Close A │ ─────────────► │ queue │ ◄────────────── │ background worker │ │ waits <-ch │ │ │ │ NOT RUNNING │ └──────────────┘ └──────────────┘ └─────────────────────┘ ``` **Impact:** whichever `Close` loses never returns: - **The lifetime timer's `Close` (`expired()`):** one leaked goroutine. - **`pool.Acquire` / `pool.Store`:** they call `v.Close()` while holding the pool lock (`p.cond.L`). Every later `Dedicated()`/`Dedicate()` call and every blocking command on that pool then waits forever. - **`client.Close()`:** shutdown never returns. One realistic trigger: `ConnLifetime` is set, and an idle pooled connection that only ever took the sync path has never started its worker. Its lifetime timer fires at the same moment `pool.Acquire` takes it, `Acquire` sees `StopTimer()` return false, and both call `Close`. The window is nanoseconds wide, so it's rare. CI caught it on #1048 (https://github.com/redis/rueidis/actions/runs/40632881130), in `TestLifetimeTimerCrossTimerConstruction`: its tiny-lifetime case makes `expired()` and the test's own `Close` race 500 times per run. The leak detector fails with: ``` Expected not to leak 1 goroutines: goroutine … [chan receive, 1 minutes] github.com/redis/rueidis.(*pipe).Close at rueidis/pipe.go:… (<-ch) github.com/redis/rueidis.(*pipe).expired github.com/redis/rueidis._newPipe.func3 ``` ## Origin - **`8503b21`** ("fix: avoid racing with sync read when closing", v0.0.53) introduced the race. At that point the losing `Close` gave up waiting after one second and handed `<-ch` to a goroutine, so the race only leaked that goroutine. The caller returned. - **#1013** ("fix(pipe): don't let Close hang when the command ring is full", v1.0.77) replaced the give-up with an escape timer, and `Close` itself waits for the `PING`. The design assumes there is always a worker to drain the queue. This race breaks that assumption, so since v1.0.77 the losing caller hangs. ## Fix The escape timer calls `failSync(errClosing)` instead of only `p.conn.Close()`. `failSync` closes the connection and starts the **cleanup-only** background worker (`backgroundSkipReadWrite`). That worker answers every queued request with the pipe's error until no waiter is left, and it never reads or writes the connection. | Situation when the escape fires | Before | After | |---|---|---| | Worker already running (silent peer) | conn closed, worker drains | same: starting the worker is a no-op | | Sync read in flight | conn closed, `syncDo` fails and starts the worker | same: the cleanup worker does not read, so a late reply cannot be misread | | **No worker (this race)** | **`Close` blocks forever** | **cleanup worker drains, `Close` returns** | ## Why this fix | Alternative | Problem | |---|---| | Restore the pre-#1013 give-up after one second | Brings back the goroutine leaked in this race, and the hang #1013 fixed, where `PutOne` waits for a slot in a full ring. | | Always start the regular worker in `Close`, or from the waiter that leaves | That worker reads the connection while an in-flight `syncDo` may still be reading it: the race `8503b21` prevents. | | Count sync readers separately, so `Close` knows whether a `syncDo` is in flight | `Close` could return promptly, but `syncDo`, `syncDoMulti`, `DoStream` and `DoMultiStream` would all maintain the counter on the hot path, for a rare race. | | **Escape timer calls `failSync`** | Reuses the worker that exists for exactly this state: a failed pipe whose connection a sync path may still be reading. No new state, no hot-path cost, no change outside the race. | **Trade-off:** in this race, `Close` returns after the one-second escape rather than promptly. Avoiding that would require telling a departing waiter apart from an in-flight `syncDo`. Aborting a `syncDo` early would break the graceful `PING`, so the second is paid only in the race. ## Tests `TestCloseWithConcurrentWaiter` in `pipe_test.go` forces the losing state deterministically. It counts an extra waiter before `Close`, the way a concurrent `Close` or `Do` does, then checks that `Close` returns and that no goroutine leaks. - **Without the fix:** `Close hung without a background worker`, followed by the same leak-detector panic as CI. - **With the fix:** passes. The Close, ForceClose, lifetime-timer and late-reply tests pass 3× under `-race`. The full root package suite passes under `-race` against the docker-compose Redis setup. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes connection shutdown and pool/client close behavior, but the fix is confined to the existing escape timer and reuse of `failSync`/`backgroundSkipReadWrite`. > > **Overview** > Fixes **`pipe.Close`** blocking forever when a graceful shutdown **PING** sits on the queue and nothing drains it—typically when two **`Close`** calls (or a **`Close`** plus a **`Do`** that bails on “stopping”) race so neither starts the background worker. > > The one-second **escape timer** now calls **`failSync(errClosing)`** instead of only closing the socket. That marks the pipe failed and starts the **cleanup-only** background worker (**`backgroundSkipReadWrite`**), which answers queued work without reading the wire—the same path sync failures already use. > > Comments on **`failSync`** and the **`Close`** PING path document this case. **`TestCloseWithConcurrentWaiter`** simulates an extra waiter so **`Close`** must return without relying on another goroutine to start the worker. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e2b3d26. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
Hi @FZambia, thanks for the PR, but I think we should probably never pause the auth timer during checkout. We don't need to consider the Blocking commands are trickier, but what we can do are only two things:
We can start from 1. And 2 might be optional. |
db7a5ff to
03705cd
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 03705cd. Configure here.
|
Many thanks @rueian I reworked the PR:
One exception, which I think has to be addressed separately: the One more thing to know. Valkey 8.1.1 through the current 9.x releases have a server-side regression, valkey-io/valkey#4862: a module cannot block a RESP3 client that has subscriptions, so an Tried to reproduce using Valkey, loaded with Valkey's own
So on those servers, once the refresh runs on subscribed connections, users would see a reconnect per refresh interval instead of one every 12 hours. The fix is merged in Valkey (valkey-io/valkey#4863) and backported, but no release contains it yet, and ElastiCache will pick it up later still. Redis and Valkey up to 8.0 are not affected. |
|
Thanks, @FZambia. The Valkey server-side regression is unfortunate and might be huge. I wonder whether we should just always ignore the reply from the AUTH refreshes? |
StopTimer paused the auth refresh of a pipe checked out from a pool, and ResetTimer resumed it when the pipe was returned. A dedicated pub/sub pipe is held for as long as its subscriptions live, so its credentials were never refreshed and the server dropped the connection once they expired. The refresh now keeps running on a checked-out pipe. AUTH is an ordinary request, also on a subscribed RESP3 connection, and a transaction is sent in one DoMulti so AUTH cannot land inside it. Behind a blocking command the AUTH hits ConnWriteTimeout like the background PING does; that error is ignored when a blocking command is in flight, since the AUTH stays queued and is applied once the blocking command returns. Only nobg pipes, as used by the stream pool, still pause the refresh on checkout: DoStream owns its connection synchronously and cannot share it with a concurrent AUTH.
A blocking command ahead of the refresh AUTH can be answered right when the AUTH times out, so blcksig can already be zero when the timeout is handled and a healthy pipe would be closed. Sample it before sending the AUTH too, and keep the pipe open if either sample saw a blocking command. A pipe that really stopped replying is still closed by the background PING, which stalls behind the unanswered AUTH.
The refresh AUTH can fail while the connection is still fine: behind a blocking command it hits ConnWriteTimeout and is applied once the blocking command returns, a subscribed RESP2 connection rejects it, and Valkey 8.1 to 9.x reject module auth on a subscribed RESP3 connection (valkey-io/valkey#4862). Closing the connection on such a reply turned every refresh into a reconnect. The connection now keeps its current credentials and the server drops it when they expire, which is also what happens when the new credentials are really wrong. A connection that stopped replying is still closed by the background PING. This replaces the blcksig sampling around the AUTH.
599dc30 to
496bddd
Compare
Probably the best we can do here to not introduce more problems than improvements... Done in 496bddd: While verifying I found that this also fixes a pre-existing problem on RESP2. A subscribed RESP2 connection rejects every command but pub/sub ones, and the internal RESP2 pub/sub pipe has its own refresh timer that was never paused, so since #1008 it got Same setup as before, Valkey built from the tags with
On 8.1.11 the server still rejects the module I also rebased onto main to fix CI benchmark failure. |
|
Thanks @FZambia! |

TL;DR
A connection held by
Dedicate()/Dedicated()never refreshed itsAuthCredentials, so a long-lived pub/sub connection was dropped by the server once its credentials expired. The auth refresh now keeps running while a connection is checked out, and the reply of the refreshAUTHis ignored, so a refresh that cannot succeed no longer closes a working connection. No API change.Real-world report: centrifugal/centrifugo#1296 (AWS ElastiCache with IAM auth, connection dropped with
EOFevery 12 hours).Problem
AuthCredentials.RefreshAfter(#1008) makes every connection callAuthCredentialsFnagain and sendAUTHbefore its credentials expire.pool.AcquirecallsStopTimer()on checkout, which paused that refresh, andpool.Store→ResetTimer()resumed it. A pub/sub connection is never returned while its subscriptions live, so its refresh never ran. Centrifugo/centrifuge andrueidiscompat.PubSubboth subscribe on dedicated connections.Fix
Two changes, both following the maintainer's suggestions in the review.
The refresh is not paused on checkout anymore.
AUTHis an ordinary request, also on a subscribed RESP3 connection, and the backgroundPINGalready runs on dedicated pub/sub pipes. A transaction is sent in oneDoMulti(see the README's CAS section andrueidiscompat), which is written as a unit, soAUTHcannot land inside it.The reply of the refresh
AUTHis ignored. TheAUTHcan fail while the connection is still fine:ConnWriteTimeout, like the backgroundPING; it stays queued and is applied once the blocking command returns;Closing the connection on such a reply turned every refresh into a reconnect. The connection now keeps its current credentials and the server drops it when they expire, which is also what happens when the new credentials are really wrong; the next connect then fails on
HELLO. A connection that stopped replying is still closed by the backgroundPING. An error fromAuthCredentialsFnitself still closes the pipe, as before.Stream pool is out of scope
nobgpipes, used byspoolforDoStream/DoMultiStream, keep pausing the refresh on checkout. They have no queue and no background worker, andDoStreamowns the connection synchronously and panics on concurrent use, so an unpaused refresh during a stream would be a new failure there. A stream held longer than the credential lifetime is therefore still not refreshed. It needs a different mechanism and is left for a separate change.Verified against real servers
Valkey built from the release tags, loaded with Valkey's own
tests/modules/auth.so, which authenticates throughBlockClientOnAuthlike a provider module. This branch withRefreshAfterset to 2s, holding a dedicated pub/sub connection withReceivefor 8s, so three refreshes run on the subscribed connection.On 8.1.11 the module
AUTHon the subscribed RESP3 connection is still rejected by the server; the connection now simply keeps its credentials until they expire, as it did before this change.Tests
Auth Credentials Refresh Runs While Checked OutreplacesTimer Lifecycle: a regular pipe refreshes afterStopTimer().Auth Credentials Refresh Behind Blocking Command(new): theAUTHtimes out behindBLPOP, the pipe stays open and schedules the next refresh, and the queuedAUTHis applied after the blocking reply.Auth Credentials Refresh Timeout Keeps PipereplacesTimeout: on a pipelining pipe anAUTHthat hitsConnWriteTimeoutdoes not close the pipe and its late reply is consumed.Auth Credentials Refresh Rejected Keeps Pipe(new): anAUTHrejected by the server leaves the pipe open and schedules the next refresh.Auth Credentials Refresh NoBg Pool Lifecycle(unchanged) pins thatnobgpipes still pause.TestNewPipe,TestPool*,TestMux*,TestPipe*andTestClose*pass under-race.Note
Medium Risk
Changes long-lived connection lifecycle and when refresh AUTH failures close the pipe; behavior is security-adjacent (IAM/credentials) but scoped to error handling and timer scheduling with expanded tests.
Overview
Fixes long-lived dedicated/pub/sub connections (e.g.
Dedicate(), IAMRefreshAfter) losing credentials because pool checkout used to pause the auth refresh timer viaStopTimer()—those connections are rarely returned to the pool.Auth refresh now keeps running while a pipelined pipe is checked out:
StopTimer/ResetTimeronly stop the auth timer whenp.queue == nil(nobg stream pipes still pause, unchanged).Periodic refresh
AUTHno longer tears down the connection on a bad reply:refreshAuthfiresAUTHbut ignores the result instead of calling_exiton error. Failed or delayed refreshes (blocking commands +ConnWriteTimeout, RESP2 pub/sub rejection, Valkey module-auth on subscribed RESP3) leave the existing session credentials in place until the server expires them; dead connections are still detected via background PING. Errors fromAuthCredentialsFnstill close the pipe.Tests were flipped/extended to assert refresh during checkout, behind BLPOP, on write timeout, and on server AUTH rejection—all without closing the pipe.
Reviewed by Cursor Bugbot for commit 496bddd. Bugbot is set up for automated code reviews on this repo. Configure here.