Repository navigation
Redis result backend: serialize pubsub access between the drainer and result cleanup - #10671
Conversation
The shared pubsub object is not safe for concurrent use, but subscribe/unsubscribe can be called from any thread or greenlet (apply_async, AsyncResult.__del__) while the drainer is polling get_message on the same socket. Guard every pubsub operation with a lock so the calls cannot interleave. The lock is recreated after fork since the inherited one may be held by a dead thread.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #10671 +/- ##
==========================================
+ Coverage 89.23% 89.27% +0.04%
==========================================
Files 153 153
Lines 20374 20385 +11
Branches 2430 2430
==========================================
+ Hits 18180 18198 +18
+ Misses 1888 1882 -6
+ Partials 306 305 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
|
can you also check this pr #10326 ? and is it related? or fixing a different problem? |
auvipy
left a comment
There was a problem hiding this comment.
it would be great to have additional smoke or integration tests for this change
Two tests against a real server: concurrent AsyncResult.get() calls through a worker round-trip, and direct subscribe/unsubscribe churn on the ResultConsumer while a drainer polls. Both would have wedged or desynced the shared pubsub before the lock.
|
Checked #10326. Same root cause (the shared pubsub from #4670), different interleaving. That one is same-thread: cyclic GC fires AsyncResult.del mid-subscribe and the nested cancel_for re-enters the same connection. This one is cross-thread: del runs on the GC thread and calls unsubscribe while the drainer is blocked in get_message on the same pubsub. The RLock here can't fix theirs (a re-entrant acquire succeeds and the writes still interleave), and their depth counter can't fix this one, so both are needed. Added integration tests in c2e107a (t/integration/test_redis_backend.py): concurrent AsyncResult.get() round-trips through a worker on the shared pubsub, plus subscribe/unsubscribe churn on the ResultConsumer while the drainer polls. Asserts no errors and no leaked channels. |
|
@GangEunzzang @MehrazRumman can you try and verify this please? |
GangEunzzang
left a comment
There was a problem hiding this comment.
Tried it against a real Redis with a drainer thread and four threads subscribing/unsubscribing: under plain threads neither tree errors, but under gevent main throws ConcurrentObjectUseError and redis protocol ValueErrors within seconds (11 to 392 per 4s run) and this branch stays at zero. The unit race test fails on main and passes here. LGTM.
|
Hi @goingforstudying-ctrl @auvipy @GangEunzzang, I run an AI to review this, and it shows me a quite serious regression issue, that is:
I haven't spent time to look into that, so I don't really know if this is real or not. Can you take a quick look? |
|
@goingforstudying-ctrl can you please cross check the above comment? |
|
@phanky1 It's real, and it's worse than a delay. With a real worker and Redis, a gevent-patched client calling Yielding after the release only moves the problem: @auvipy this is on |
…ssages (#10715) * Redis result backend: don't hold the pubsub lock while waiting for messages Since #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. * Redis result backend: address review on the pubsub lock 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. --------- Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
Description
Got bitten by the #4670 race again on 5.5.x:
AsyncResult.__del__runs on whatever thread the GC happens to pick, and it walks intoremove_pending_result->cancel_for->pubsub.unsubscribe()while the result drainer is sitting inget_message()on the very same pubsub object. redis-py pubsub isn't safe for concurrent use, and with gevent this blows up asConcurrentObjectUseError: This socket is already used by another greenlet(AssertionError on older versions). The #4666 / #6416 fixes added the unsubscribe but never serialized it against the reader, so the race just moved around.What I did: gave
ResultConsumeran RLock and took it around every touch of the shared pubsub — start/stop, subscribe, unsubscribe, theget_messagepoll indrain_events, reconnect, and the fork cleanup. RLock because the drainer itself callscancel_forfromon_state_changewhen a ready meta comes in, and the reconnect path re-enters from the error handler. The idle sleep when there's no pubsub yet stays outside the lock soapply_asyncisn't stalled by nothing.One thing I wasn't 100% sure about: fork safety. The child inherits the lock possibly still held by a thread that didn't survive the fork, so
on_after_forkswaps in a fresh one before closing the old pubsub.There's a real trade-off here worth spelling out: while the drainer is mid-poll (up to its 1s timeout), a subscribe/unsubscribe from another thread has to wait. I think that's strictly better than crashing, and in the pure fire-and-forget producer case the drainer isn't running so there's no contention at all. If maintainers would rather have the drainer own the pubsub exclusively via a command queue, that's a bigger redesign — figured I'd start here.
Tests: the main one is a race test that hammers subscribe/unsubscribe from 4 threads while a drainer thread polls; the fake pubsub records any overlapping calls. It fails immediately on main (
assert not ['subscribe', 'subscribe', 'get_message', 'unsubscribe', ...]) and is clean with the lock. Plus deterministic checks that each pubsub op holds the lock, that the idle sleep doesn't, and thaton_after_forkreplaces the lock.t/unit/backends/test_redis.py+test_asynchronous.pypass locally (167 passed, 9 skipped), flake8 clean.