Skip to content

fix(consumer): skip prefetch reduction when per-consumer QoS is in effect - #10253

Merged
auvipy merged 6 commits into
celery:mainfrom
aurangzaib048:fix/9512-prefetch-restore-qos-disabled
Apr 20, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
aurangzaib048:fix/9512-prefetch-restore-qos-disabled

Conversation

@aurangzaib048

@aurangzaib048 aurangzaib048 commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

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.qos on each ack. With apply_global=False (the mode RabbitMQ requires for quorum queues), basic.qos updates 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_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.

Root cause

Per the RabbitMQ docs on consumer prefetch: basic.qos with global=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_restart updates internal state and pushes a new basic.qos frame 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__ adds self.qos_global = None (tri-state default; None preserves legacy behavior). on_connection_error_after_connected skips the reduction when self.qos_global is False and emits an info log explaining why. The is False identity check is deliberate so the unknown-state default None falls through to the legacy reduction path.
  • celery/worker/consumer/tasks.py: Tasks.start() records the effective qos_global on the consumer immediately after computing it, so the connection-error handler in Consumer can read it on the next reconnect.

Test plan

  • Unit tests (t/unit/worker/test_consumer.py):
    • Parametrized regression test test_prefetch_count_reduction_respects_qos_global covering all three states (False / True / None). Each parametrize ID asserts initial_prefetch_count, _maximum_prefetch_restored, and the expected log message via caplog.
    • test_start_records_qos_global_on_consumer_quorum and test_start_records_qos_global_on_consumer_classic verify Tasks.start() writes the right value.
    • All existing test_restore_prefetch_count_on_restart parametrize cases continue to pass (no regression in classic-queue behavior).
  • Smoke tests (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 (using assert_log_does_not_exist which polls).
    • test_worker_resumes_consuming_after_broker_restart: places 2 long-running tasks (less than worker_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.
  • Existing classic-queue smoke test test_reducing_prefetch_count still passes, confirming the fix is surgical and does not affect channel-wide QoS users.
  • Manual reproduction with the issue reporter's setup (quorum queue + custom NoChannelGlobalQoS bootstep + 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) AND qos_global = False (only for quorum queues, or custom bootsteps that force per-consumer QoS). All other code paths are unchanged:

  • Classic queues (qos_global = True) keep the gradual reduction-and-restore behavior verbatim.
  • Users with worker_enable_prefetch_count_reduction = False are unaffected by the outer guard.
  • If Tasks.start() has not yet run (qos_global = None), the legacy reduction path runs as before.

…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

codecov Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.28%. Comparing base (d8ec9e0) to head (cc047f6).
⚠️ Report is 66 commits behind head on main.

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           
Flag Coverage Δ
unittests 88.25% <100.00%> (+<0.01%) ⬆️

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.

Copilot AI 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.

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 the Consumer instance (tri-state with None preserving 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.

Comment thread celery/worker/consumer/consumer.py Resolved
Comment thread celery/worker/consumer/consumer.py Resolved

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

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

aurangzaib048 commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Both comments are addressed.

  1. Reset prefetch state on skip path, the qos_global is False branch now explicitly resets initial_prefetch_count = self.max_prefetch_count and _maximum_prefetch_restored = True, so a prior legacy-reduction reconnect cannot leave stale reduced state that carries into the skip branch. Added test_on_connection_error_skip_resets_prior_reduced_state to lock this in.

  2. Snapshot active_count once, replaced two separate len(tuple(active_requests)) calls with a single active_count = len(active_requests) reused in both the reduction math and the log message. active_requests is a WeakSet so len() is already O(1), and this also prevents the two values from drifting.

@auvipy auvipy added this to the 5.7.0 milestone Apr 8, 2026
@auvipy
auvipy requested a review from Copilot April 8, 2026 12:40

Copilot AI 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.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

Comment thread t/smoke/tests/quorum_queues/test_qos.py Resolved
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.

Copilot AI 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.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

@auvipy
auvipy merged commit b313b64 into celery:main Apr 20, 2026
336 checks passed
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.

Worker loss on reconnection with RabbitMQ with QoS disabled

3 participants