Repository navigation
Conversation
…adlock Cyclic GC can finalize an AsyncResult mid-SUBSCRIBE/UNSUBSCRIBE via AsyncResult.__del__ -> backend.remove_pending_result -> cancel_for, which re-enters the same shared PubSub connection and wedges the Redis protocol waiting for interleaved responses. Production stacks show this on chain.apply_async() (outer SUBSCRIBE) and on task-body finalizers (outer UNSUBSCRIBE). Add a thread-local depth guard to ResultConsumer: nested cancel_for calls are queued and drained after the outer subscribe/unsubscribe completes. The drain loop holds depth=1 so finalizers fired during drain also queue rather than re-enter the connection. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
can you please refer to any relevant issues for more context? |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #10326 +/- ##
==========================================
- Coverage 89.28% 89.25% -0.04%
==========================================
Files 153 153
Lines 20397 20441 +44
Branches 2431 2436 +5
==========================================
+ Hits 18212 18245 +33
- Misses 1881 1891 +10
- Partials 304 305 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
There was a problem hiding this comment.
Pull request overview
Fixes a Redis result-backend deadlock caused by re-entrant pub/sub usage (e.g., AsyncResult.__del__ triggering cancel_for() while a SUBSCRIBE/UNSUBSCRIBE is in-flight) by deferring nested cancel_for() calls and draining them once the outer operation completes.
Changes:
- Add a re-entrancy guard to
celery.backends.redis.ResultConsumerusing a per-thread depth counter and a deferred-cancel queue. - Defer nested
cancel_for()calls during subscribe/unsubscribe and drain them safely after the outer operation finishes. - Add three unit regression tests covering re-entry during subscribe, unsubscribe, and during the deferred-drain loop itself.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
celery/backends/redis.py |
Adds depth-tracked deferral + drain mechanism to avoid re-entrant pub/sub deadlocks. |
t/unit/backends/test_redis.py |
Adds regression tests exercising re-entrant cancel_for() scenarios and drain behavior. |
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
auvipy
left a comment
There was a problem hiding this comment.
please check the test failures
The earlier Copilot autofix removed the ``finally`` clause while keeping an outer ``try`` with no handler, producing a SyntaxError and breaking unit-test collection across the suite. Restore the ``finally: self._reentry.depth = 0`` so depth is reset even when the inner ``raise RuntimeError`` propagates, and keep the RuntimeError re-raise so unrecoverable backend errors aren't swallowed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A single matrix cell (test_tasks.py / 3.12 / rabbitmq_redis) hit ``ValueError: bad marshal data (invalid reference)`` while pydantic loaded ``_internal/_generate_schema.py`` -- a corrupted .pyc on the runner, unrelated to the changes in this PR. All other ~24 matrix cells of the same module passed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Thanks for the review. We triaged this directly from production py-spy stacks, so there's no existing GitHub issue. Two angles worth distinguishing: The deadlock trigger is chain construction itself, independent of any timeout. The production blast radius is amplified by Full root-cause analysis, both production py-spy stacks (A: GC during |
|
Copilot's Only remaining red is Codecov flags 6 new lines (the drain's |
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Apply the same try/log/raise wrapper around `_drain_deferred_cancels` in both `_consume_from` and `cancel_for`. Logging gives a debug breadcrumb when the drain fails (addressing Copilot's masking concern); re-raising preserves `RuntimeError(E_RETRY_LIMIT_EXCEEDED)` as the unrecoverable-backend signal that prompts an operator restart. Python chains any outer exception via `__context__`. Drops the `exc = None` capture in `cancel_for` -- the inline `try/except` in the `finally:` block handles both the original-success and original-failure cases uniformly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
auvipy
left a comment
There was a problem hiding this comment.
it would be nice to improve test coverage, and possibly some integration/smoke tests for this
|
also the merge conflicts |
|
i tried to fix the merge conflicts |
| except RuntimeError: | ||
| # Unrecoverable backend state -- propagate so the | ||
| # caller can restart Celery. ``finally`` below | ||
| # still resets the depth counter. | ||
| raise |
Summary
Fixes a re-entrant Redis pub/sub deadlock in the result backend. CPython's cyclic GC can fire
AsyncResult.__del__mid-SUBSCRIBE/UNSUBSCRIBE, which calls back intocancel_foron the same sharedPubSubconnection and wedges the Redis protocol on interleaved responses. We've observed this in production aschain.apply_async()calls hanging indefinitely (tens of occurrences per day across our worker fleet, with workers stuck for hours).celery/backends/redis.py—ResultConsumernow uses athreading.localdepth counter. Nestedcancel_forcalls (the inner UNSUBSCRIBE in both stacks below) are queued and drained after the outer subscribe/unsubscribe returns. The drain loop holds depth=1 so finalizers fired during drain also queue rather than re-enter the connection.t/unit/backends/test_redis.py— three regression tests:test_cancel_for_reentry_during_subscribe(Stack A: GC insidechain.apply_async()→subscribe)test_cancel_for_reentry_during_unsubscribe(Stack B: GC inside task body → outerunsubscribe)test_drain_deferred_handles_nested_reentry(re-entries fired during the deferred drain are also queued)Bug detail
Two pieces of code are individually correct but mutually unsafe:
BaseAsynchronousBackend.add_pending_resultissuesSUBSCRIBEon a single sharedPubSubconnection.AsyncResult.__del__callsbackend.remove_pending_result→cancel_for→UNSUBSCRIBEon the samePubSub.When CPython's cyclic GC finalizes a lingering
AsyncResultcycle during the SUBSCRIBE/UNSUBSCRIBE response wait, the finalizer re-enters the same connection. The protocol is single-RPC-at-a-time; the connection deadlocks.Production py-spy stack A — GC during
chain.apply_async()Production py-spy stack B — GC inside task body (after deploying a downstream apply_async-only mitigation)
Both stacks share the same root cause — re-entrant pub/sub on a shared connection. A fix scoped to
apply_asyncalone (e.g. disabling cyclic GC around it) closes A but leaves B. The depth-guard at theResultConsumerlayer closes both.Reproduction
The script (linked + inlined below) supports two modes matching the two production stacks. Both deadlock within ~10 s on unpatched celery; both complete in milliseconds with this PR applied.
Reproduction script: https://gist.github.com/wckao/a292b29baceae14b911da2e54e3d2730
Inline copy for review convenience:
reproduce_celery_redis_gc_deadlock.pyAffected versions
Any setup that uses the Redis result backend and dispatches
chain/group/chordapply_async()under allocation pressure.Test plan
t/unit/backends/test_redis.py::test_RedisResultConsumer— all 14 tests pass (11 existing + 3 new regression tests)t/unit/backends/— full suite passes (1 unrelated msgpack-missing failure in my local env)