Repository navigation
Register rate-limited tasks as reserved and migrate pending tasks on rate limit reset - #11168
meat-daemon-404 wants to merge 1 commit into
Conversation
…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
ChristianMurphy
left a comment
There was a problem hiding this comment.
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, becauseautoscale.pyreadsreserved_requests. With--autoscale=6,1and twelve waiting tasks the pool grows to six processes, and main stays at one. - The edits to
UNKNOWN_FORMAT,INVALID_TASK_ERRORandCANCEL_TASKS_BY_DEFAULTlook 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
12ef86d19and main atbffee14b2, each with kombu main (9cd1cef8), Python 3.13, prefork with 2 processes, late ack, Valkey 8.1. Theworker_disable_prefetchand countdown runs gave the same result twice on each tree. t/unit/workerin the3.13-unittox 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 inreset_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.
Summary
Previously, tasks waiting inside a rate-limit
TokenBuckethad two issues:task_reserved(request)was only called in_limit_move_to_pool()when a task left the bucket, so waiting tasks were invisible toinspect reservedandinspect query_task.Consumer.reset_rate_limits()replaced entries inself.task_bucketswithout cancelling old bucket timers or migrating pending requests, so updating or clearing a rate limit viacontrol.rate_limit()left already-queued tasks running on the old bucket's rate.Changes
task_reserved(request)when enqueuing in_limit_task()and_limit_post_eta()(removing the duplicate call from_limit_move_to_pool()) incelery/worker/consumer/consumer.py.Consumer.reset_rate_limits(), cancel any armed timer for replaced buckets viaself.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
Consumer's bucket/timer lifecycle:task_reservedimmediately on arrival.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