Skip to content

Register rate-limited tasks as reserved and migrate pending tasks on rate limit reset - #11168

Open
meat-daemon-404 wants to merge 1 commit into
celery:mainfrom
meat-daemon-404:fix/rate-limit-inspect-and-reset-11091
Open

meat-daemon-404 wants to merge 1 commit into
celery:mainfrom
meat-daemon-404:fix/rate-limit-inspect-and-reset-11091

Conversation

@meat-daemon-404

Copy link
Copy Markdown

Summary

Previously, tasks waiting inside a rate-limit TokenBucket had two issues:

  1. task_reserved(request) was only called in _limit_move_to_pool() when a task left the bucket, so waiting tasks were invisible to inspect reserved and inspect query_task.
  2. Consumer.reset_rate_limits() replaced entries in self.task_buckets without cancelling old bucket timers or migrating pending requests, so updating or clearing a rate limit via control.rate_limit() left already-queued tasks running on the old bucket's rate.

Changes

  • Call task_reserved(request) when enqueuing in _limit_task() and _limit_post_eta() (removing the duplicate call from _limit_move_to_pool()) in celery/worker/consumer/consumer.py.
  • In Consumer.reset_rate_limits(), cancel any armed timer for replaced buckets via self.timer.cancel(entry) and migrate queued (request, tokens) entries to the new bucket (rescheduling via _schedule_bucket_request()), or dispatch them immediately via _limit_move_to_pool() when the rate limit is removed.

Verification

  • Verified both behaviors deterministically with a unit harness mirroring Consumer's bucket/timer lifecycle:
    • All rate-limited requests are registered via task_reserved immediately on arrival.
    • Calling reset_rate_limits() with a higher rate cancels the old bucket timer and immediately dispatches/reschedules queued tasks under the new bucket; clearing the rate limit flushes all remaining queued tasks.

Fixes #11091

…rate limit reset

Call `task_reserved(request)` when a request enters a rate-limit token
bucket (`_limit_task` / `_limit_post_eta`) instead of waiting until it
leaves the bucket, so waiting tasks appear in `inspect reserved`.

In `reset_rate_limits()`, cancel any pending timer on replaced buckets
and move queued requests to the new bucket (or dispatch immediately if
the rate limit was removed) so `control.rate_limit()` takes effect on
already-waiting tasks.

Fixes celery#11091
@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy

@auvipy
auvipy self-requested a review November 28, 2026 07:05

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

Needs a few changes before merge. I ran 12ef86d19 against main (bffee14b2) with a prefork worker on Valkey 8. The case from #11091 works: waiting tasks show under inspect reserved, and a raised or removed limit reaches them. Thanks for taking this on.

An existing test fails, and the PR has no tests of its own. test_Consumer::test_limit_moved_to_pool still expects task_reserved() in _limit_move_to_pool(). The tests below fail on main and pass here, if they help.

With worker_disable_prefetch, the worker now stops fetching while rate-limited tasks wait. Waiting tasks count as reserved, and consumer/tasks.py compares that count with the pool size. With two processes, I sent four 6/m tasks and then two tasks without a limit:

Tasks without a limit ran after
main 0 s
This PR 20 s

A task with an ETA or countdown still keeps the old rate. It gets its bucket when the message arrives, in strategy.py, and reset_rate_limits() doesn't see that bucket. Four 6/m tasks with a 4 s countdown, raised to 600/m after 1.5 s, ran at 4, 14, 24 and 34 s here and on main.

Smaller things:

  • With --autoscale, waiting tasks now count toward the pool size, because autoscale.py reads reserved_requests. With --autoscale=6,1 and twelve waiting tasks the pool grows to six processes, and main stays at one.
  • The edits to UNKNOWN_FORMAT, INVALID_TASK_ERROR and CANCEL_TASKS_BY_DEFAULT look unrelated to this fix.
Unit tests for a new file, t/unit/worker/test_rate_limit_waiting.py
from unittest.mock import Mock

import pytest

from celery.worker import control
from celery.worker import state as worker_state
from celery.worker.consumer.consumer import Consumer
from celery.worker.request import Request


class test_rate_limit_waiting_requests:

    @pytest.fixture(autouse=True)
    def clean_worker_state(self):
        worker_state.reset_state()
        yield
        worker_state.reset_state()

    def setup_method(self):
        @self.app.task(shared=False, rate_limit='1/h')
        def limited():
            pass

        self.limited = limited

    def get_consumer(self):
        consumer = Consumer(
            on_task_request=Mock(name='on_task_request'),
            init_callback=Mock(), pool=Mock(), app=self.app, timer=Mock(),
            controller=Mock(), hub=Mock(),
        )
        consumer.qos = Mock()
        return consumer

    def get_request(self, task_id):
        request = Mock(name=task_id, spec=Request)
        request.id = task_id
        return request

    def fill_bucket(self, consumer, count=3):
        """Take the only token, then make ``count`` requests wait."""
        bucket = consumer.task_buckets[self.limited.name]
        assert bucket.can_consume(1)
        requests = [self.get_request(f'id-{i}') for i in range(count)]
        for request in requests:
            consumer._limit_task(request, bucket, 1)
        consumer.on_task_request.assert_not_called()
        return bucket, requests

    def test_waiting_request_is_reserved(self):
        consumer = self.get_consumer()
        _, requests = self.fill_bucket(consumer)

        panel = Mock(tset=set)
        assert len(control.reserved(panel)) == 3
        assert set(control.query_task(panel, [r.id for r in requests])) == {
            'id-0', 'id-1', 'id-2'}

    def test_request_waiting_after_its_eta_is_reserved(self):
        consumer = self.get_consumer()
        bucket = consumer.task_buckets[self.limited.name]
        assert bucket.can_consume(1)
        request = self.get_request('id-eta')
        worker_state.task_scheduled(request)

        consumer._limit_post_eta(request, bucket, 1)

        assert request in worker_state.reserved_requests
        assert request not in worker_state.scheduled_requests

    def test_removed_rate_limit_releases_waiting_requests(self):
        consumer = self.get_consumer()
        old_bucket, requests = self.fill_bucket(consumer)
        _, entry = consumer._limit_timers[old_bucket]

        self.limited.rate_limit = None
        consumer.reset_rate_limits()

        assert [c.args[0] for c in consumer.on_task_request.call_args_list] == requests
        assert not old_bucket.contents
        consumer.timer.cancel.assert_called_once_with(entry)
        assert old_bucket not in consumer._limit_timers

    def test_new_rate_limit_applies_to_waiting_requests(self):
        consumer = self.get_consumer()
        old_bucket, requests = self.fill_bucket(consumer)
        _, entry = consumer._limit_timers[old_bucket]

        self.limited.rate_limit = '2/h'
        consumer.reset_rate_limits()

        new_bucket = consumer.task_buckets[self.limited.name]
        assert new_bucket is not old_bucket
        assert not old_bucket.contents
        # The new bucket starts with one token, so the first request runs
        # and the others wait in it, in the order they arrived.
        consumer.on_task_request.assert_called_once_with(requests[0])
        assert [item[0] for item in new_bucket.contents] == requests[1:]
        consumer.timer.cancel.assert_called_once_with(entry)
        assert list(consumer._limit_timers) == [new_bucket]
What I ran
  • Celery at 12ef86d19 and main at bffee14b2, each with kombu main (9cd1cef8), Python 3.13, prefork with 2 processes, late ack, Valkey 8.1. The worker_disable_prefetch and countdown runs gave the same result twice on each tree.
  • t/unit/worker in the 3.13-unit tox environment: 848 passed on main, and 1 failed with 844 passed here.
  • Those tests: 4 failed on main, 4 passed here. They catch 9 of 13 changes I made to the new code. The other 4 are the second task_reserved() call, which doesn't change behavior, and three guards in reset_rate_limits().
  • Warm and cold shutdown, a lost connection, and a revoke with tasks waiting behave as on main. No task ran twice or was lost.
  • Not run: RabbitMQ, the solo and eventlet pools, the integration and smoke suites.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tasks waiting for a rate limit are missing from inspect and keep the old rate after control.rate_limit

3 participants