Streaming credentials: background re-auth can miss the idle transition and never re-authenticate the connection (lost wake-up in ConnStateMachine.AwaitAndTransition)
Expected Behavior
After a StreamingCredentialsProvider delivers new credentials (OnNext), every pooled connection is re-authenticated in place by the background re-auth worker as soon as the connection is idle, and keeps serving afterwards.
Current Behavior
About one rotation in five (3/20, 4/20 and 5/20 in repeated runs), the connection marked for re-authentication is never re-authenticated. The worker spawned by ReAuthPoolHook.OnPut blocks in ConnStateMachine.AwaitAndTransition, waiting for the connection to become idle although it already is, until the PoolTimeout context expires. Then reAuthFn(context.DeadlineExceeded) reaches onAuthenticationErr, isBadConn treats the deadline error as a bad connection, the connection is closed with
redis: re-authentication failed: context deadline exceededand the next command dials a replacement. While the connection is marked, OnGet rejects it on every checkout, so it serves nothing and holds its pool slot; with the pool at PoolSize, every command in that window dials and then drops a replacement.
Goroutine captured from a stalled run on v9.22.0 (dumped ~5 s after the push, worker still waiting):
goroutine 44 [select]:
github.com/redis/go-redis/v9/internal/pool.(*ConnStateMachine).AwaitAndTransition(...)
internal/pool/conn_state.go:267
github.com/redis/go-redis/v9/internal/auth/streaming.(*ReAuthPoolHook).OnPut.func1()
internal/auth/streaming/pool_hook.go:194
created by github.com/redis/go-redis/v9/internal/auth/streaming.(*ReAuthPoolHook).OnPut
internal/auth/streaming/pool_hook.go:159Mechanism (found by instrumenting v9.22.0; the event trace of a stalled rotation is in the first comment): the worker waits for the connection's IN_USE → IDLE transition, but that transition is made by Conn.Release() (internal/pool/conn.go, Put's hot path) with a bare CAS on the state word, and Release() never calls notifyWaiters. Whenever the worker has enqueued itself before Put releases the connection, the waiter is never served; because the pool is LIFO, the connection then sits at the bottom of the idle stack and nothing transitions it again until the worker's context deadline. TryTransitionFast, which the comment on Release() points to, is a bare CAS as well. A second, narrower ordering also loses the wake-up: when Release() runs between the worker's failed fast path and its enqueue, there is no waiter to notify yet and the enqueue comes too late. Both orderings occur in the reproduction, and a change for either one alone leaves the other (measured below). Because the fast path is skipped whenever waiterCount > 0, a later OnNext for the same connection queues a second worker behind the stuck one and does not unstick it (verified: a second push of the same credentials fails at the same rate).
The code is unchanged on v9.23.0-beta.1 (reproduced, 5/20) and on master.
Possible Solution
Two hunks, verified together against the reproduction: 0 of 100 rotations stall, against 3 to 8 of 20 unpatched. Each alone still stalls (re-check after the enqueue only: 3, 0, 1, 1 of 20; Release() notifying only: 3, 4, 4, 3, 4 of 20). notifyWaiters begins with waiterCount.Load() == 0, so the cost on the Put hot path is one atomic load when nobody is waiting, the check TryTransition already makes.
--- a/internal/pool/conn.go
+++ b/internal/pool/conn.go
@@ -957,7 +957,14 @@
// on this transition, update this to use TryTransitionFast().
func (cn *Conn) Release() bool {
// Inline the hot path - single CAS operation
- return cn.stateMachine.state.CompareAndSwap(uint32(StateInUse), uint32(StateIdle))
+ if !cn.stateMachine.state.CompareAndSwap(uint32(StateInUse), uint32(StateIdle)) {
+ return false
+ }
+ // The connection just became IDLE: wake anyone waiting for that state (the
+ // re-auth worker parked in AwaitAndTransition). One atomic load when nobody
+ // is waiting.
+ cn.stateMachine.notifyWaiters()
+ return true
}
// ClearHandoffState clears the handoff state after successful handoff.
--- a/internal/pool/conn_state.go
+++ b/internal/pool/conn_state.go
@@ -263,6 +263,11 @@
sm.waiterCount.Add(1)
sm.mu.Unlock()
+ // Re-check now that the waiter is visible: a transition that happened
+ // between the fast path above and the enqueue (through Release, which
+ // found no waiter to notify) would otherwise never wake it.
+ sm.notifyWaiters()
+
// Wait for state change or timeout
select {
case <-ctx.Done():A regression test for the first hunk (package pool; fails on v9.22.0 after its 2 s deadline, passes with the change) is in the first comment. go test ./internal/pool/... ./internal/auth/... ./auth/... pass with both hunks applied.
Edited the same day: this section first proposed only the second hunk. The instrumented trace showed the un-notified Release() as the main path; see the first comment.
Steps to Reproduce
- Start a server with ACL support:
docker run --rm -d -p 127.0.0.1:63790:6379 valkey/valkey:8.1-alpine - Save the program below as
main.goin a module that requiresgithub.com/redis/go-redis/v9 v9.22.0. go run . 127.0.0.1:63790- Some of the 20 rotations report the original connection still listed as
rotuser1after 3 s, and go-redis logsre-authentication failed: context deadline exceededonce the pool timeout expires.
// Reproduces: a pooled connection marked for re-authentication after a
// StreamingCredentialsProvider push is sometimes never re-authenticated in place.
// The background re-auth worker blocks in ConnStateMachine.AwaitAndTransition
// waiting for the connection to become idle, although it already is, until the
// pool timeout expires and the connection is closed.
//
// Run against a Redis/Valkey with ACL support:
//
// docker run --rm -d -p 127.0.0.1:63790:6379 valkey/valkey:8.1-alpine
// go run . 127.0.0.1:63790
package main
import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/redis/go-redis/v9"
"github.com/redis/go-redis/v9/auth"
)
// provider is a minimal auth.StreamingCredentialsProvider: Subscribe hands out
// the current credentials and remembers the listener; Push delivers new ones.
type provider struct {
mu sync.Mutex
current basicCreds
listeners []auth.CredentialsListener
}
type basicCreds struct{ user, password string }
func (c basicCreds) BasicAuth() (string, string) { return c.user, c.password }
func (c basicCreds) RawCredentials() string { return c.user + ":" + c.password }
func (p *provider) Subscribe(l auth.CredentialsListener) (auth.Credentials, auth.UnsubscribeFunc, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.listeners = append(p.listeners, l)
return p.current, func() error { return nil }, nil
}
func (p *provider) Push(user, password string) {
p.mu.Lock()
p.current = basicCreds{user, password}
listeners := append([]auth.CredentialsListener(nil), p.listeners...)
p.mu.Unlock()
for _, l := range listeners {
l.OnNext(p.current)
}
}
func idsForUser(ctx context.Context, admin *redis.Client, user string) (map[string]bool, error) {
list, err := admin.Do(ctx, "CLIENT", "LIST").Text()
if err != nil {
return nil, err
}
ids := map[string]bool{}
for _, line := range strings.Split(list, "\n") {
if !strings.Contains(line, " user="+user+" ") {
continue
}
for _, f := range strings.Fields(line) {
if id, ok := strings.CutPrefix(f, "id="); ok {
ids[id] = true
}
}
}
return ids, nil
}
func main() {
if len(os.Args) < 2 {
fmt.Println("usage: go run . <redis-addr>")
os.Exit(2)
}
addr := os.Args[1]
ctx := context.Background()
admin := redis.NewClient(&redis.Options{Addr: addr})
for _, u := range []string{"rotuser1", "rotuser2"} {
if err := admin.Do(ctx, "ACL", "SETUSER", u, "on", ">"+u+"-pw", "~*", "+@all").Err(); err != nil {
panic(err)
}
}
defer admin.Do(ctx, "ACL", "DELUSER", "rotuser1", "rotuser2")
const runs = 20
stalled := 0
for i := 0; i < runs; i++ {
p := &provider{current: basicCreds{"rotuser1", "rotuser1-pw"}}
client := redis.NewClient(&redis.Options{Addr: addr, StreamingCredentialsProvider: p, PoolSize: 2})
if err := client.Set(ctx, "k", "v", time.Minute).Err(); err != nil {
panic(err)
}
before, _ := idsForUser(ctx, admin, "rotuser1") // the one pooled connection
p.Push("rotuser2", "rotuser2-pw") // credentials rotate; the connection is marked for re-auth
// Keep issuing commands, as an application would. Each checkout rejects
// the marked connection (OnGet), so a second connection serves them.
reauthed := false
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) && !reauthed {
_ = client.Set(ctx, "k", "v", time.Minute).Err()
after, _ := idsForUser(ctx, admin, "rotuser2")
reauthed = true
for id := range before {
if !after[id] {
reauthed = false
}
}
time.Sleep(50 * time.Millisecond)
}
if !reauthed {
stalled++
still, _ := idsForUser(ctx, admin, "rotuser1")
fmt.Printf("run %2d: original connection %v NOT re-authenticated after 3s (still listed as rotuser1: %v)\n", i, keys(before), keys(still))
}
client.Close()
}
fmt.Printf("%d of %d rotations left the original connection un-re-authenticated after 3s\n", stalled, runs)
}
func keys(m map[string]bool) []string {
out := []string{}
for k := range m {
out = append(out, k)
}
return out
}Context (Environment)
- go-redis
v9.22.0; also reproduced onv9.23.0-beta.1; the relevant code is unchanged onmaster. - Go 1.26.6, darwin/arm64; Valkey 8.1 (
valkey/valkey:8.1-alpine). - Use case: a
StreamingCredentialsProviderthat pushes rotated file-backed ACL credentials to a pool, relying on in-place re-authentication so that a rotation costs no reconnect. With this race, a rotation instead closes and replaces some connections after the pool timeout, and a saturated pool dials a replacement per command during that window.
Source: redis/go-redis