Skip to content

Redis result backend: serialize pubsub access between the drainer and result cleanup - #10671

Merged
auvipy merged 9 commits into
celery:mainfrom
goingforstudying-ctrl:fix/redis-pubsub-race
Sep 21, 2026
Merged

auvipy merged 9 commits into
celery:mainfrom
goingforstudying-ctrl:fix/redis-pubsub-race

Conversation

@goingforstudying-ctrl

Copy link
Copy Markdown
Contributor

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 into remove_pending_result -> cancel_for -> pubsub.unsubscribe() while the result drainer is sitting in get_message() on the very same pubsub object. redis-py pubsub isn't safe for concurrent use, and with gevent this blows up as ConcurrentObjectUseError: 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 ResultConsumer an RLock and took it around every touch of the shared pubsub — start/stop, subscribe, unsubscribe, the get_message poll in drain_events, reconnect, and the fork cleanup. RLock because the drainer itself calls cancel_for from on_state_change when 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 so apply_async isn'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_fork swaps 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 that on_after_fork replaces the lock. t/unit/backends/test_redis.py + test_asynchronous.py pass locally (167 passed, 9 skipped), flake8 clean.

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

codecov Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.82609% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.27%. Comparing base (6ed1ec1) to head (ef09917).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/redis.py 97.82% 0 Missing and 1 partial ⚠️
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     
Flag Coverage Δ
unittests 89.25% <97.82%> (+0.04%) ⬆️

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 added this to the 5.7.0 milestone Sep 19, 2026
@auvipy
auvipy self-requested a review September 19, 2026 06:36
@auvipy

auvipy commented Sep 19, 2026

Copy link
Copy Markdown
Member

can you also check this pr #10326 ? and is it related? or fixing a different problem?

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

it would be great to have additional smoke or integration tests for this change

auvipy and others added 4 commits September 19, 2026 15:55
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.
@goingforstudying-ctrl

Copy link
Copy Markdown
Contributor Author

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.

@auvipy

auvipy commented Sep 20, 2026

Copy link
Copy Markdown
Member

@GangEunzzang @MehrazRumman can you try and verify this please?

@GangEunzzang GangEunzzang 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.

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.

@auvipy
auvipy merged commit cd3b42e into celery:main Sep 21, 2026
17 of 19 checks passed
@phanky1

phanky1 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Hi @goingforstudying-ctrl @auvipy @GangEunzzang, I run an AI to review this, and it shows me a quite serious regression issue, that is:

When using gevent with Redis as the result backend, the new lock in drain_events() might keep getting reacquired by the drainer, so other greenlets can’t get a turn. This could make result.get(timeout=...) hang even after the result is received, without respecting the timeout.

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?

@auvipy

auvipy commented Sep 21, 2026

Copy link
Copy Markdown
Member

@goingforstudying-ctrl can you please cross check the above comment?

@GangEunzzang

Copy link
Copy Markdown
Contributor

@phanky1 It's real, and it's worse than a delay. With a real worker and Redis, a gevent-patched client calling result.get() on a task that already finished never returns on main (waited 25s+, six runs), while the same call takes 0.07s on the commit before this PR and 0.1s on main without gevent. The greenlet dump shows the caller stuck in consume_from waiting for _pubsub_lock, and the drainer holding it inside pubsub.get_message(timeout=1); gevent's semaphore doesn't hand off on release, so the drainer re-takes the lock every loop before the waiter runs.

Yielding after the release only moves the problem: AsyncResult.__del__ → cancel_for then blocks on the lock inside a finalizer and gevent raises RuntimeError: greenlet is being finalized. So the blocking get_message() can't sit under the same lock that cancel_for takes from __del__. My LGTM here was wrong: the stress test I ran counted errors, and the starved threads simply did nothing.

@auvipy this is on main now, so probably worth a look before the alpha. Happy to open a PR for it (keep the lock for the pubsub calls, but wait for messages outside it, and make cancel_for non-blocking from __del__) if you'd rather not wait for the author.

auvipy added a commit that referenced this pull request Sep 27, 2026
…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]>
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.

4 participants