Repository navigation
Redis result backend: don't hold the pubsub lock while waiting for messages - #10715
Conversation
…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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
|
@ goingforstudying-ctrl this fix the regression your PR introduced |
auvipy
left a comment
There was a problem hiding this comment.
is this changes covered by old smoke tests of redis?
MehrazRumman
left a comment
There was a problem hiding this comment.
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'sRLockdoesn't hand the lock to a waiting greenlet when it's released, so the drainer greenlet re-acquired it immediately andconsume_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 thefinallyafter the read means the other waiters come back and check the parser buffer throughcan_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 topoll()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()reportingPOLLNVAL/ theOSError/ValueErrorfallback returns "readable", and theself._pubsub is pubsubcheck then skips the stale connection. That's handled correctly. cancel_for()never blocks, which is right forAsyncResult.__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 fulltimeout. It's capped at 1s whentimeout 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._sockis 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_sockisNone, each call returns immediately and relies oncan_read()to reconnect, which is a brief busy loop, but fine.- eventlet. Looking up
select.pollon each call handles gevent patching after import. Under eventlet,select.pollis removed by monkey-patching, so this falls back toselectors.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 < 1and thetime.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=Trueisn'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.
|
@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: |
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_lockwhile it blocks inget_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 onsubscribed_eventwhen 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 fromAsyncResult.__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.