Skip to content

Redis result backend: don't hold the pubsub lock while waiting for messages - #10715

Merged
auvipy merged 3 commits into
celery:mainfrom
GangEunzzang:fix/redis-pubsub-gevent-starvation
Sep 27, 2026
Merged

auvipy merged 3 commits into
celery:mainfrom
GangEunzzang:fix/redis-pubsub-gevent-starvation

Conversation

@GangEunzzang

Copy link
Copy Markdown
Contributor

Note: Before submitting this pull request, please review our contributing
guidelines
.

Description

Since #10671, a gevent-patched client using the Redis result backend can hang in result.get(), and the timeout doesn't help. drain_events() holds _pubsub_lock while it blocks in get_message(timeout=1), and the greenlet drainer takes the lock again right after releasing it because gevent's lock doesn't hand off. consume_from() in the calling greenlet never gets it. I described this in #10671 (comment).

This keeps the lock around every pubsub call, so the race #10671 fixed stays fixed, but waits for the socket outside it:

  • drain_events() only takes the lock to read. It waits on the raw socket, or on subscribed_event when nothing is subscribed, without it. Only one thread waits on the socket at a time. The others wait on a condition that is notified after each read, because the message it reads may be theirs.
  • cancel_for() never blocks, since it runs from AsyncResult.__del__ where a greenlet can't switch. If the lock is busy, the key is queued and the holder unsubscribes it when it releases.

With a real Redis, a solo worker and a monkey-patched client, get(timeout=8) on 20 tasks went from 0/20 on main to 20/20 in about 0.1s. get(timeout=2) on a pending task now raises at 2s instead of hanging. Clients without gevent behave the same as before. A subscribe/unsubscribe stress with a drainer running under gevent gets through about 50k operations in 4s with every published message drained. On main it manages 4.

The new unit tests fail on main. This doesn't touch the same-thread GC re-entrancy case from #10326.

…ssages

Since celery#10671, drain_events() held _pubsub_lock while blocking in
get_message(timeout=1). Under gevent the drainer greenlet takes the
lock again right after releasing it (gevent's lock doesn't hand off),
so consume_from() and cancel_for() in other greenlets never get it:
result.get() on a monkey-patched client hangs and ignores its timeout.

Wait for the pubsub socket outside the lock and only take the lock to
read, so every redis-py pubsub call is still serialized. Only one
thread waits on the socket at a time; the others wait on a condition
it notifies after reading, since the message it reads may be theirs.

cancel_for() no longer blocks, because it runs from AsyncResult.__del__
where a greenlet can't switch. If the lock is busy the key is queued
and the holder unsubscribes it on release.
@codecov

codecov Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.87640% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.73%. Comparing base (0a24c06) to head (a3d7f23).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/redis.py 98.87% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10715      +/-   ##
==========================================
+ Coverage   89.52%   89.73%   +0.21%     
==========================================
  Files         153      153              
  Lines       20420    20496      +76     
  Branches     2434     2447      +13     
==========================================
+ Hits        18280    18392     +112     
+ Misses       1838     1803      -35     
+ Partials      302      301       -1     
Flag Coverage Δ
unittests 89.71% <98.87%> (+0.21%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@auvipy
auvipy self-requested a review September 27, 2026 08:14
@auvipy auvipy added this to the 5.7.0 milestone Sep 27, 2026
@auvipy

auvipy commented Sep 27, 2026

Copy link
Copy Markdown
Member

@ goingforstudying-ctrl this fix the regression your PR introduced

@auvipy auvipy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this changes covered by old smoke tests of redis?

@MehrazRumman MehrazRumman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @GangEunzzang, this is a careful fix for a nasty regression, and the numbers in the description (0/20 to 20/20 under gevent, ~4 to ~50k subscribe/unsubscribe operations) make the case clearly. I read through the new ResultConsumer closely. The overall design looks right to me. My notes are below; nothing here is blocking.

Design

  • Waiting on the socket outside the lock is the right fix. On main, get_message(timeout=...) blocked while holding _pubsub_lock, and gevent's RLock doesn't hand the lock to a waiting greenlet when it's released, so the drainer greenlet re-acquired it immediately and consume_from() / cancel_for() never got a turn.
  • Only one thread waits on the socket (_socket_waiter), and the others wait on _pubsub_read. Without this, several threads would sleep on the same socket and the one that reads a message might not be the one it's for. Notifying in the finally after the read means the other waiters come back and check the parser buffer through can_read(timeout=0), so buffered messages aren't missed.
  • can_read(timeout=0) before waiting on the raw socket also takes care of data that redis-py already holds (in its parser buffer, or decrypted but not yet read on a TLS socket). That data would otherwise be invisible to poll() on the raw file descriptor. It would be worth a short comment so nobody reorders these later.
  • When the connection is replaced while we wait, poll() reporting POLLNVAL / the OSError/ValueError fallback returns "readable", and the self._pubsub is pubsub check then skips the stale connection. That's handled correctly.
  • cancel_for() never blocks, which is right for AsyncResult.__del__. _flush_pending_unsubscribe() re-checks after every release, so an unsubscribe added while the lock was held isn't lost, and _consume_from() discarding the key handles cancel-then-resubscribe (with a test).

1. Same-thread re-entrancy still runs inline (related to #10326)

The description says #10326 is out of scope, which is fair. But with this design most of the fix is already in place. _flush_pending_unsubscribe() uses acquire(blocking=False) on an RLock, and that always succeeds when the current thread already holds the lock. So if garbage collection triggers AsyncResult.__del__ on the draining thread while it is inside _drain_one() (in the middle of get_message() / parsing), the unsubscribe still runs inline on the pubsub, in the middle of that read. The same happens when an inner _locked() exits during an outer one (for example _reconnect_pubsub() inside _drain_one()).

If you want to cover that here or in a follow-up: track the owner or nesting depth inside _locked() (e.g. self._lock_owner = threading.get_ident() plus a depth counter) and have cancel_for() / _flush_pending_unsubscribe() only add the key to the pending set when the current thread is already inside the lock. The outermost _locked() exit then runs the unsubscribes. This would keep pubsub operations strictly one at a time, including on the same thread.

2. The gevent test replaces the lock but not the condition

test_consume_from_is_not_starved_by_gevent_drainer sets consumer._pubsub_lock = RLock() (gevent), but consumer._pubsub_read is still a threading.Condition built on the original lock. The test passes only because it has a single drainer, so the follower path (_pubsub_read.wait()) never runs. If it did, it would raise RuntimeError: cannot wait on un-acquired lock.

Since __init__, on_after_fork() and this test all build the same group of objects (lock, condition, _socket_waiter, _pending_unsubscribe), a small _reset_sync() helper would keep them consistent. The test could then call it after patching in gevent's primitives, and it would be worth adding a second drainer greenlet so the follower path is also covered under gevent.

3. Smaller points

  • Stale socket and long timeouts. On Linux, poll() isn't woken when another thread closes the file descriptor, so if _reconnect_pubsub() replaces the connection during the wait, the waiter sleeps for the full timeout. It's capped at 1s when timeout is None, but a caller passing a larger timeout waits that long. Current callers use short intervals, so this is fine in practice, but capping the socket wait at e.g. min(timeout, 1.0) would make reconnects equally quick whatever the caller passes.
  • connection._sock is a private redis-py attribute. It's reasonable (it's been stable for a long time), but please add a comment pointing to it, and note the fallback. When _sock is None, each call returns immediately and relies on can_read() to reconnect, which is a brief busy loop, but fine.
  • eventlet. Looking up select.poll on each call handles gevent patching after import. Under eventlet, select.poll is removed by monkey-patching, so this falls back to selectors.DefaultSelector. That should use eventlet's version, but a quick check under eventlet (or a note that it was tested) would help, since the regression was specific to green threads.
  • Timing-based tests. elapsed < 1, done['other'] - start < 1 and the time.sleep(0.2) could flake on slow CI runners (PyPy, busy runners). Please consider more slack, or checking ordering with events instead of elapsed time where possible.
  • patch('celery.backends.redis._socket_readable', create=True, ...): create=True isn't needed, since the function exists.

4. Smoke / integration coverage (re @auvipy's question)

As far as I can tell, the unit tests cover the locking protocol well, but nothing runs this against a real Redis with gevent, which is where the regression appeared. Could you add the reproduction script you used for the numbers in the description as a smoke test (gevent-patched client, one worker, get(timeout=...) on N tasks)? At minimum, please include it in the PR description so it can be re-run. An eventlet variant would be good too.

Summary

The approach is sound and fixes the regression from #10671. I'd approve with (2) fixed and a reproduction script or smoke test added. (1) can be a follow-up if you'd rather keep this PR focused, but the deferral machinery here makes it a small change.

- Build the lock, condition and waiter state in one _reset_sync() helper,
  used by __init__ and on_after_fork().
- Cap every wait outside the lock at one second, whatever timeout the
  caller passes.
- Don't spin when the connection has no _sock attribute; fall back to
  checking once per interval.
- The gevent unit test installs a green lock and condition together and
  runs two drainers, so the follower path runs under gevent too.
- Thread tests check ordering with events instead of elapsed time.
- Add a smoke test running a gevent-patched client against a Redis
  result backend in a subprocess.
@GangEunzzang

GangEunzzang commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@auvipy No, none of the existing smoke tests patch the client with gevent, which is why this slipped through. Added one in a3d7f23, it hangs on main and passes here.

@MehrazRumman Thanks, addressed in a3d7f23: _reset_sync() now builds the lock and condition together and the gevent test runs two drainers so the follower path is covered; added the comments on can_read(timeout=0) and _sock; capped waits outside the lock at 1s; dropped create=True; the thread tests use events instead of timings. Under eventlet main didn't hang in my runs but was about a second slow, this branch returns in ~0.1s. I left No. 1 out since it overlaps #10326.

@auvipy
auvipy self-requested a review September 27, 2026 11:00
@auvipy
auvipy merged commit 3083864 into celery:main Sep 27, 2026
431 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants