Repository navigation
fix(consumer): skip prefetch reduction when per-consumer QoS is in effect - #10253
Conversation
…fect When a worker reconnects after a broker outage with active tasks, Celery reduces the prefetch count and gradually restores it as in-flight tasks complete by calling basic.qos on each ack. With apply_global=False (the mode required by RabbitMQ quorum queues), basic.qos updates only apply to consumers created after the call and do not propagate to the running consumer. The restoration is therefore a no-op and the worker stays stuck at the reduced prefetch count after one reconnect, leaving most pool processes idle. Skip the reduction entirely when qos_global is False so the new consumer created on reconnect starts at the full prefetch count. This matches the existing worker_enable_prefetch_count_reduction=False workaround but auto-applies it only in the affected mode, preserving the original behavior for classic queues where channel-wide QoS still works. Fixes celery#9512
Add four tests around the prefetch reduction skip introduced in the previous commit: Unit: - Default qos_global=None must keep the legacy reduction behavior (guards against future tightening of the ``is False`` check). - Restoration callback must remain a clean no-op when qos_global=False so stale prefetch values are never pushed to the broker. Smoke (Docker, real RabbitMQ + quorum queue): - After broker restart, the new "Skipping prefetch count reduction" log appears and the legacy "Temporarily reducing the prefetch count" log does not. - A task submitted after broker restart still flows end-to-end, proving the consumer is not stranded at a reduced prefetch.
Address findings from a comprehensive code review of the previous two commits on this branch. Unit tests: - Delete test_restore_prefetch_count_after_connection_restart_qos_global_false: the test passed for the wrong reason. The early-exit in _restore_prefetch_count_after_connection_restart triggers on _maximum_prefetch_restored=True (the default after the fix skips the reduction), not on qos_global. Setting c.qos_global=False in the test was incidental, since the restoration code path never reads it. With the fix, the restoration callback is never even attached to messages for per-consumer QoS workers, so this code path is unreachable. - Collapse the three new qos_global unit tests (qos_global=False, qos_global=True, qos_global=None default) into one parametrized test. Removes ~85% of duplicated setup boilerplate. - Add caplog assertion to the parametrized test, verifying the Skipping prefetch count reduction log fires when qos_global is False and the legacy Temporarily reducing the prefetch count log fires otherwise. Closes the gap where a future refactor could silently delete the new info log without breaking unit tests. Smoke tests: - Replace the racy ``not in celery_setup.worker.logs()`` snapshot with ``assert_log_does_not_exist``, which polls with a short timeout and cannot pass spuriously if the legacy reduction log just has not been emitted yet at the moment the test reads the log buffer. - Add a wait_for_log barrier in test_skip_log_emitted_after_broker_restart so the in-flight tasks are guaranteed to be processing on the worker before the broker restart, ensuring the reduction code path is entered. - Strengthen test_worker_resumes_consuming_after_broker_restart so it actually exercises the bug. Previously it restarted the broker with no in-flight tasks and would have passed on a pre-fix build. Now it places two long-running tasks (less than worker_concurrency=4 so two pool slots remain free) before the restart. After reconnect a noop must still flow end-to-end through the free pool slots, which fails on a pre-fix build because the consumer is stranded at prefetch=2 with both slots taken by the redelivered long-running tasks. - Add a class-level comment explaining why no RedisTestBroker xfail guard is needed (the quorum_queues conftest forces a RabbitMQ broker).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #10253 +/- ##
=======================================
Coverage 88.28% 88.28%
=======================================
Files 153 153
Lines 19669 19676 +7
Branches 2268 2269 +1
=======================================
+ Hits 17364 17371 +7
Misses 2005 2005
Partials 300 300
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
This PR fixes a reconnection edge case for RabbitMQ quorum queues (per-consumer QoS / apply_global=False) where Celery’s prefetch-count reduction + gradual restoration logic becomes ineffective and can leave the worker stuck at a reduced prefetch after a broker outage (issue #9512).
Changes:
- Track the effective QoS mode (
qos_global) on theConsumerinstance (tri-state withNonepreserving legacy behavior). - Skip prefetch reduction on reconnect when per-consumer QoS is in effect (
qos_global is False) and emit an explanatory log. - Add unit + smoke regression tests to cover the quorum-queue reconnect behavior and logging.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
celery/worker/consumer/consumer.py |
Adds Consumer.qos_global and conditionally skips prefetch reduction when qos_global is False. |
celery/worker/consumer/tasks.py |
Records computed qos_global onto the Consumer during Tasks.start() so reconnect logic can make the right decision. |
t/unit/worker/test_consumer.py |
Adds unit regression coverage for tri-state qos_global and verifies Tasks.start() records the mode. |
t/smoke/tests/quorum_queues/test_qos.py |
Adds smoke regressions ensuring quorum-queue reconnect does not apply reduction and that post-restart tasks still flow. |
auvipy
left a comment
There was a problem hiding this comment.
can you please cross check the suggestions?
Two issues raised in review of celery#10253: 1. The ``qos_global is False`` skip branch left ``initial_prefetch_count`` and ``_maximum_prefetch_restored`` untouched. If a prior reconnect had taken the legacy reduction path (because ``qos_global`` was ``None`` or ``True`` at that time) the skip path would inherit that stale reduced state and the new consumer would be created with a reduced prefetch even though we claimed to "skip" reduction. Explicitly reset both to the maximum in the skip branch so the reconnect always comes up at full prefetch in per-consumer QoS mode. 2. ``len(tuple(active_requests))`` was called twice in the reduction branch, once for the reduction math and once for the log message. This allocated a new tuple on each call solely to call ``len()`` on a ``WeakSet`` (which already supports ``len()``) and could in principle give inconsistent counts between the two calls. Snapshot the count once with ``active_count = len(active_requests)`` and reuse it. Adds test_on_connection_error_skip_resets_prior_reduced_state which directly invokes ``on_connection_error_after_connected`` with a pre-reduced ``initial_prefetch_count`` and ``qos_global=False``, and verifies the state is reset to the maximum.
|
Both comments are addressed.
|
Copilot flagged a real race on top of my previous commit: ``wait_for_log`` only checks substring presence, so calling it once for ``"Starting long running task"`` returns as soon as the first task starts. The tests need N tasks to actually be in flight at the moment of the broker disconnect, so a single-occurrence barrier lets timing hide the bug: - ``test_worker_resumes_consuming_after_broker_restart`` needs both long-running tasks in flight so the reduction computes ``max(1, 4-2)=2``. With only one task started the reduction would compute ``max(1, 4-1)=3`` and leave enough prefetch slots free for the post-restart noop to succeed even on a buggy build. - ``test_skip_log_emitted_after_broker_restart`` similarly needs all four long-running tasks in flight for the reduction code path to be meaningfully exercised. Add a small ``_wait_for_log_count`` helper using ``wait_for_callable`` from ``pytest_docker_tools`` that polls until a log substring has appeared at least N times. Replace the single-occurrence barriers in both tests with counted versions.
Summary
Fixes #9512.
When a Celery worker reconnects after a broker outage with active tasks, Celery reduces the prefetch count and gradually restores it as in-flight tasks complete by calling
basic.qoson each ack. Withapply_global=False(the mode RabbitMQ requires for quorum queues),basic.qosupdates only apply to consumers created after the call and do not propagate to the already-running consumer. The restoration is therefore a no-op and the worker stays stuck at the reduced prefetch count after one reconnect, leaving most pool processes idle.The fix skips the reduction entirely when
qos_globalisFalseso the new consumer created on reconnect starts at the full prefetch count. This matches the existingworker_enable_prefetch_count_reduction=Falseworkaround but auto-applies it only in the affected mode, preserving the original behavior for classic queues where channel-wide QoS still works.Root cause
Per the RabbitMQ docs on consumer prefetch:
basic.qoswithglobal=false"applies to consumers created on the channel after the basic.qos method has been called." Once a consumer is running, its prefetch is fixed for that consumer's lifetime. The gradual restoration via_restore_prefetch_count_after_connection_restartupdates internal state and pushes a newbasic.qosframe to the broker, but the running consumer keeps its initial reduced prefetch forever.This is why the issue reporter's workaround (
worker_enable_prefetch_count_reduction=False) fixes the problem: with reduction disabled, the new consumer is created at the full prefetch count and there is nothing to restore.Changes
celery/worker/consumer/consumer.py:Consumer.__init__addsself.qos_global = None(tri-state default;Nonepreserves legacy behavior).on_connection_error_after_connectedskips the reduction whenself.qos_global is Falseand emits an info log explaining why. Theis Falseidentity check is deliberate so the unknown-state defaultNonefalls through to the legacy reduction path.celery/worker/consumer/tasks.py:Tasks.start()records the effectiveqos_globalon the consumer immediately after computing it, so the connection-error handler inConsumercan read it on the next reconnect.Test plan
t/unit/worker/test_consumer.py):test_prefetch_count_reduction_respects_qos_globalcovering all three states (False/True/None). Each parametrize ID assertsinitial_prefetch_count,_maximum_prefetch_restored, and the expected log message via caplog.test_start_records_qos_global_on_consumer_quorumandtest_start_records_qos_global_on_consumer_classicverifyTasks.start()writes the right value.test_restore_prefetch_count_on_restartparametrize cases continue to pass (no regression in classic-queue behavior).t/smoke/tests/quorum_queues/test_qos.py, real RabbitMQ via Docker):test_skip_log_emitted_after_broker_restart: floods the worker with in-flight tasks, restarts the broker, asserts the new "Skipping prefetch count reduction" log appears AND the legacy "Temporarily reducing the prefetch count" log does NOT (usingassert_log_does_not_existwhich polls).test_worker_resumes_consuming_after_broker_restart: places 2 long-running tasks (less thanworker_concurrency=4) before the restart so the bug path is actually exercised. After reconnect a noop must still flow end-to-end through a free pool slot, which fails on a pre-fix build because the consumer is stranded at the reduced prefetch with both slots taken by the redelivered long-running tasks.t/unit/worker/full suite: 596 passed, 1 skipped.test_reducing_prefetch_countstill passes, confirming the fix is surgical and does not affect channel-wide QoS users.NoChannelGlobalQoSbootstep + broker restart) on RabbitMQ 4.2.5: bug reproduced before fix (only 1 of 4 pool workers consuming after reconnect), all 4 workers active after reconnect with the fix.Backwards compatibility
The fix only takes effect when
worker_enable_prefetch_count_reduction = True(default) ANDqos_global = False(only for quorum queues, or custom bootsteps that force per-consumer QoS). All other code paths are unchanged:qos_global = True) keep the gradual reduction-and-restore behavior verbatim.worker_enable_prefetch_count_reduction = Falseare unaffected by the outer guard.Tasks.start()has not yet run (qos_global = None), the legacy reduction path runs as before.