Skip to content

fix: don't let Close hang when another waiter skips starting the background worker - #1050

Merged
rueian merged 1 commit into
redis:mainfrom
FZambia:fix/pipe-close-concurrent-waiter
Oct 30, 2026
Merged

rueian merged 1 commit into
redis:mainfrom
FZambia:fix/pipe-close-concurrent-waiter

Conversation

@FZambia

@FZambia FZambia commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

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.
  • fix(pipe): don't let Close hang when the command ring is full #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.

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.

Reviewed by Cursor Bugbot for commit e2b3d26. Bugbot is set up for automated code reviews on this repo. Configure here.

…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.
@rueian

rueian commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

Thank you @FZambia!

@rueian
rueian merged commit 494ed3f into redis:main Oct 30, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants