Repository navigation
fix: don't let Close hang when another waiter skips starting the background worker - #1050
Merged
Merged
Conversation
…ground worker Close starts the background worker only when it is the only waiter, so that it does not race with a sync read. Its graceful PING then relies on the other waiter, assumed to be a syncDo, to start the worker. But the other waiter can be a concurrent Close, or a Do that sees the pipe already stopping, and both leave without starting one. The PING is then never answered and Close blocks forever. When the caller holds a lock, as pool.Acquire and pool.Store do, the whole pool deadlocks. The race dates back to 8503b21, where it only parked a goroutine after Close gave up waiting for a second. Since redis#1013, Close itself waits for the PING, so the race hangs the caller. Make the escape timer call failSync, which also starts the cleanup worker: it drains the queue without reading or writing the connection, and is a no-op when a worker is already running. Why not the alternatives: - Restoring the pre-redis#1013 give-up after one second would bring back both the goroutine leaked in this race and the hang redis#1013 fixed, where PutOne waits for a slot in a full ring. - Starting the regular worker unconditionally in Close, or from the waiter that leaves, would read the connection concurrently with an in-flight syncDo, the race 8503b21 prevents. - Counting sync readers separately would let Close return promptly, but every sync path would have to maintain the counter on the hot path, for a race that is rare. The cleanup worker exists for exactly this state, a failed pipe whose connection may still be read by a sync path, so the fix adds no new state and changes nothing outside the race. In this race, Close now returns after the one-second escape rather than promptly. Avoiding that would require telling a departing waiter apart from an in-flight syncDo, and aborting a syncDo early would break the graceful PING, so the second is paid only in the race.
Collaborator
|
Thank you @FZambia! |
rueian
approved these changes
Oct 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
pipe.Closecan block forever when another waiter is in flight at the same time.Closestarts the background worker only when it is the only waiter, so that it does not race with a sync read (8503b21). Its gracefulPINGthen relies on the other waiter, assumed to be asyncDo, to start the worker once the closed connection breaks its read. But the other waiter can also be:Close, for example the lifetime timer'sexpired()racing withpool.Acquire,pool.Storeor the user;Dothat sees the pipe already stopping and returns an error.Both leave without starting a worker:
Impact: whichever
Closeloses never returns:Close(expired()): one leaked goroutine.pool.Acquire/pool.Store: they callv.Close()while holding the pool lock (p.cond.L). Every laterDedicated()/Dedicate()call and every blocking command on that pool then waits forever.client.Close(): shutdown never returns.One realistic trigger:
ConnLifetimeis 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 momentpool.Acquiretakes it,AcquireseesStopTimer()return false, and both callClose. 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 makesexpired()and the test's ownCloserace 500 times per run. The leak detector fails with:Origin
8503b21("fix: avoid racing with sync read when closing", v0.0.53) introduced the race. At that point the losingClosegave up waiting after one second and handed<-chto a goroutine, so the race only leaked that goroutine. The caller returned.Closeitself waits for thePING. 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 onlyp.conn.Close().failSynccloses 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.syncDofails and starts the workerCloseblocks foreverClosereturnsWhy this fix
PutOnewaits for a slot in a full ring.Close, or from the waiter that leavessyncDomay still be reading it: the race8503b21prevents.Closeknows whether asyncDois in flightClosecould return promptly, butsyncDo,syncDoMulti,DoStreamandDoMultiStreamwould all maintain the counter on the hot path, for a rare race.failSyncTrade-off: in this race,
Closereturns after the one-second escape rather than promptly. Avoiding that would require telling a departing waiter apart from an in-flightsyncDo. Aborting asyncDoearly would break the gracefulPING, so the second is paid only in the race.Tests
TestCloseWithConcurrentWaiterinpipe_test.goforces the losing state deterministically. It counts an extra waiter beforeClose, the way a concurrentCloseorDodoes, then checks thatClosereturns and that no goroutine leaks.Close hung without a background worker, followed by the same leak-detector panic as CI.-race. The full root package suite passes under-raceagainst the docker-compose Redis setup.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.Closeblocking forever when a graceful shutdown PING sits on the queue and nothing drains it—typically when twoClosecalls (or aCloseplus aDothat 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
failSyncand theClosePING path document this case.TestCloseWithConcurrentWaitersimulates an extra waiter soClosemust return without relying on another goroutine to start the worker.Reviewed by Cursor Bugbot for commit e2b3d26. Bugbot is set up for automated code reviews on this repo. Configure here.