Reinstate read-only lock on hooks access in dialHook to fix data race #3225
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Previously, in #3088, I removed the mutex guarding the implementation of
dialHook
in order to resolve an unbounded contention failure mode, that had the potential to backpressure commands indefinitely during periods of server downtime.However, this introduced a data race regression, which was the original motivation of introducing the lock, in #2814.
A minimal reproduction is as follows:
This race is caused by concurrent access to
hs.current
when the connection pool executesdialHook
in the background (whenMinIdleConns > 0
) whileAddHook
also mutateshs.current
. However, withindialHook
, only read access is required. This PR proposes fixing this by changing the mutex to async.RWMutex
and guarding only the access tohs.current
with the lock, which both solves the data race and does not regress the connection contention unit test introduced in #3088.With this patch, the example test above passes with the race detector enabled:
$ go test -v -race -count=1 ./cmd/... === RUN TestExec ping: PONG --- PASS: TestExec (0.00s) PASS ok github.com/redis/go-redis/v9/cmd 1.010s