Repository navigation
Requeue an acks_late task when storing STARTED fails with a retryable backend error - #11014
Conversation
… backend error With task_track_started and acks_late, a STARTED write that fails because the result backend is unreachable was treated as a task failure, so the message was acked and the task was lost without running. Raise Reject(requeue=True) instead, so the message is redelivered once the backend is back. Refs celery#8588
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #11014 +/- ##
==========================================
+ Coverage 91.79% 91.80% +0.01%
==========================================
Files 153 153
Lines 22243 22288 +45
Branches 2784 2792 +8
==========================================
+ Hits 20417 20462 +45
Misses 1530 1530
Partials 296 296
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.
Needs a couple changes before merge. I tested dc38d30, the same change as 613e2ff, with a prefork worker and a Redis result backend that I stopped for 15 s or 60 s. The brokers were Redis, a RabbitMQ classic queue and a RabbitMQ quorum queue.
On a Redis broker and a classic queue, the requeue fixes #8588: all 10 tasks ran once after the backend came back. On a quorum queue it doesn't, because the requeue loops until RabbitMQ drops each task, as the inline comment on line 565 shows.
Most of the waiting could happen in the Redis backend, which already retries writes. set() goes through ensure() with retry_policy, 20 tries about a second apart. But _store_result() reads the stored result first, and that read isn't retried. Each write fails at once on it.
With that read retried the same way on top of this PR, every task ran once on all three brokers, chords included. That was also true with early ack, and through a 60 s outage on a quorum queue. The worker used about 0.1% CPU, and clients reading results still fail at once. This requeue then only runs when an outage outlasts the retries, about once every 20 s per task.
The second change is a warning when the task goes back to the queue. For an error that waiting won't fix, such as a wrong password, the requeue loops forever and nothing in the log says why. The inline comment on line 564 has the numbers.
Documenting result_backend_always_retry=True, option 1 in the description, keeps the tasks but isn't enough on its own. The setting also covers backend writes in the worker's main process, and its retries are unlimited by default. When a pool process exited during the outage, the main process kept retrying mark_as_failure(). The worker then ran 0 of 5 unrelated tasks in 35 s and didn't answer ping.
For the open case, a write that fails after the body ran, the read retry also covers outages up to about 20 s, and the body runs once. Options 2 and 3 requeue there, which runs the body again, as your 1509 runs show.
Waiting in place has costs of its own:
- While a write waits, its pool process can't take other work. With one process, 0 of 10
ignore_resulttasks ran during the outage, against 3 with this PR alone. - After a lost pool process, the main process waits about 20 s before it records the failure.
Could the PR add tests for both changes? The new unit tests caught 5 of 5 mutations of the new code. They mock exception_safe_to_retry(), though, so none of them uses a backend's own errors, and none can show the loop. I ran these against main, this PR, and this PR with the read retry:
- A smoke test that stops the Redis backend container for 15 s while five tasks wait, on a classic and a quorum queue. Main loses all five on both. With this PR, the classic queue run received the tasks 416 times, and the quorum queue run lost all five. Both pass with the read retry.
- A
test_trace.pytest with aRedisBackendand a mock client, so thatConnectionError,TimeoutErrorandResponseErrorgo through the backend's ownexception_safe_to_retry(). - A sweep over the number of failed reads, from 0 to past
max_retries. With the read retry, the body runs once while the failures stay within the limit, and the message goes back once they pass it. - A check that the requeue logs a warning.
Suggested tests, with results on main, this PR and the read retry
| Test | main | This PR | This PR with the read retry |
|---|---|---|---|
| Smoke, classic queue | fails, 0 of 5 ran | fails, 416 receipts | passes, 3 runs |
| Smoke, quorum queue | fails, 0 of 5 ran | fails, 0 of 5 ran | passes, 3 runs |
Which errors requeue, with RedisBackend and 3 errors |
2 fail | pass | pass |
| Sweep, 0, 1, 3, 4 and 10 failed reads | 4 fail | 1 and 3 fail | pass |
| The requeue logs a warning | fails | fails | fails |
Read retry in RedisBackend, 4 tests |
3 fail | 3 fail | pass |
Stopping the container gives the fast connection errors of an outage. A paused Redis instead makes each try wait for the socket timeout, which slows the loop enough to stay under the quorum queue's delivery limit. A smoke test fits better than an integration test here, because the integration suite shares one worker and one result backend, and stopping the backend would fail the tests that run after it.
The log check passes with a warning like this one:
if (task.acks_late
and task.backend.exception_safe_to_retry(exc)):
+ logger.warning(
+ 'Task %s[%s] requeued: storing STARTED '
+ 'failed: %r',
+ get_task_name(task_request, name), uuid, exc)
raise Reject(exc, requeue=True) from exct/smoke/tests/test_backend_outage.py:
"""A short result backend outage doesn't lose tasks or spin the worker (#8588)."""
from __future__ import annotations
from time import monotonic, sleep
import pytest
from pytest_celery import (CeleryBackendCluster, CeleryBrokerCluster, CeleryTestSetup, RabbitMQTestBroker,
RedisTestBackend)
from celery import Celery, states, uuid
from t.integration.tasks import get_redis_connection, redis_echo
TASKS = 5
# Shorter than the Redis backend's retry_policy, about 20 s.
OUTAGE = 15
@pytest.fixture
def celery_broker_cluster(celery_rabbitmq_broker: RabbitMQTestBroker) -> CeleryBrokerCluster:
cluster = CeleryBrokerCluster(celery_rabbitmq_broker)
yield cluster
cluster.teardown()
@pytest.fixture
def celery_backend_cluster(celery_redis_backend: RedisTestBackend) -> CeleryBackendCluster:
cluster = CeleryBackendCluster(celery_redis_backend)
yield cluster
cluster.teardown()
@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
app = default_worker_app
app.conf.task_acks_late = True
app.conf.task_track_started = True
app.conf.worker_prefetch_multiplier = 1
app.conf.worker_concurrency = 1
return app
def run_tasks_through_backend_outage(celery_setup: CeleryTestSetup) -> None:
key = f'backend-outage-{uuid()}'
# Sending needs no result backend, so this client has none.
client = Celery('client', broker=celery_setup.app.conf.broker_url, set_as_current=False)
client.conf.task_default_queue_type = celery_setup.app.conf.task_default_queue_type
celery_setup.backend.kill()
try:
ids = [
client.send_task(redis_echo.name, (str(i),), {'redis_key': key},
queue=celery_setup.worker.worker_queue).id
for i in range(TASKS)
]
sleep(OUTAGE)
finally:
celery_setup.backend.restart()
redis = get_redis_connection()
deadline = monotonic() + 30
while redis.llen(key) < TASKS and monotonic() < deadline:
sleep(0.5)
ran = sorted(value.decode() for value in redis.lrange(key, 0, -1))
assert ran == [str(i) for i in range(TASKS)]
# The backend's host port changes when it restarts.
reader = Celery('reader', backend=celery_setup.backend.config()['host_url'], set_as_current=False)
assert [reader.AsyncResult(i).state for i in ids] == [states.SUCCESS] * TASKS
logs = celery_setup.worker.logs()
receipts = sum(logs.count(f'[{task_id}] received') for task_id in ids)
# Waiting out the outage shouldn't hand each task back hundreds of times.
assert receipts <= 3 * TASKS
class test_backend_outage:
def test_tasks_survive_a_short_backend_outage(self, celery_setup: CeleryTestSetup):
run_tasks_through_backend_outage(celery_setup)t/smoke/tests/quorum_queues/test_backend_outage.py:
"""A short result backend outage on a quorum queue (#8588).
RabbitMQ drops a message after its delivery limit, 20 by default, so a
requeue loop loses tasks here instead of only spinning.
"""
from __future__ import annotations
import pytest
from pytest_celery import CeleryBackendCluster, CeleryTestSetup, RedisTestBackend
from celery import Celery
from t.smoke.tests.test_backend_outage import run_tasks_through_backend_outage
@pytest.fixture
def celery_backend_cluster(celery_redis_backend: RedisTestBackend) -> CeleryBackendCluster:
cluster = CeleryBackendCluster(celery_redis_backend)
yield cluster
cluster.teardown()
@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
app = default_worker_app
app.conf.task_acks_late = True
app.conf.task_track_started = True
app.conf.worker_prefetch_multiplier = 1
app.conf.worker_concurrency = 1
return app
class test_backend_outage_on_quorum_queue:
def test_tasks_survive_a_short_backend_outage(self, celery_setup: CeleryTestSetup):
run_tasks_through_backend_outage(celery_setup)t/unit/tasks/test_trace_started_store.py, or a class in test_trace.py:
"""STARTED store failures with a Redis backend (#8588)."""
from unittest.mock import MagicMock, Mock, patch
import pytest
from redis import exceptions as redis_errors
from celery.backends.redis import RedisBackend
from celery.exceptions import Reject
from t.unit.tasks.test_trace import TraceCase
MAX_RETRIES = 3
class test_started_store_with_redis_backend(TraceCase):
def _task(self):
ran = Mock(name='body')
@self.app.task(shared=False, track_started=True, acks_late=True)
def add(x, y):
ran()
return x + y
self.app.conf.result_backend_transport_options = {'retry_policy': {
'max_retries': MAX_RETRIES, 'interval_start': 0,
'interval_step': 0, 'interval_max': 0,
}}
backend = RedisBackend(app=self.app, url='redis://localhost:1/0')
backend.client = MagicMock(name='client')
add.backend = backend
return add, ran, backend.client
def _run(self, add):
with patch('celery.app.trace.report_internal_error'):
return self.trace(add, (2, 2), {}, eager=False,
request={'id': 'id-1', 'delivery_info': {}})
# Which errors from the backend's own exception_safe_to_retry() send
# the message back.
@pytest.mark.parametrize('error, requeued', [
(redis_errors.ConnectionError('refused'), True),
(redis_errors.TimeoutError('timed out'), True),
(redis_errors.ResponseError('WRONGTYPE'), False),
])
def test_requeues_only_for_connection_errors(self, error, requeued):
add, ran, client = self._task()
client.get.side_effect = error
with patch.object(add.backend, 'mark_as_failure') as mark_as_failure:
if requeued:
with pytest.raises(Reject) as excinfo:
self._run(add)
assert excinfo.value.requeue is True
mark_as_failure.assert_not_called()
else:
self._run(add)
mark_as_failure.assert_called()
ran.assert_not_called()
# A requeue can repeat without end, so it should say why.
def test_requeue_is_logged(self):
add, ran, client = self._task()
client.get.side_effect = redis_errors.AuthenticationError('invalid password')
with patch('celery.app.trace.logger') as logger:
with pytest.raises(Reject):
self._run(add)
messages = [str(c) for c in logger.warning.call_args_list + logger.error.call_args_list]
assert any('id-1' in m for m in messages), messages
# Sweep the outage length across the retry window. While the backend
# comes back within retry_policy, the body runs once and nothing is
# requeued. Past it, the message goes back and the body doesn't run.
@pytest.mark.parametrize('failed_reads', [0, 1, MAX_RETRIES, MAX_RETRIES + 1, 10])
def test_outage_length_sweep(self, failed_reads):
add, ran, client = self._task()
client.get.side_effect = (
[redis_errors.ConnectionError('down')] * failed_reads + [None] * 5)
if failed_reads <= MAX_RETRIES:
self._run(add)
ran.assert_called_once()
assert client.get.call_count == failed_reads + 2 # STARTED, SUCCESS
else:
with pytest.raises(Reject) as excinfo:
self._run(add)
assert excinfo.value.requeue is True
ran.assert_not_called()With the read retry, in t/unit/backends/test_redis.py:
"""Tests that would go with retrying the read in RedisBackend._store_result."""
import json
from unittest.mock import MagicMock
import pytest
from redis import exceptions as redis_errors
from celery import states
from celery.backends.redis import RedisBackend
@pytest.fixture
def backend(app):
app.conf.result_backend_transport_options = {'retry_policy': {
'max_retries': 3, 'interval_start': 0, 'interval_step': 0, 'interval_max': 0,
}}
backend = RedisBackend(app=app, url='redis://localhost:1/0')
backend.client = MagicMock(name='client')
return backend
def test_store_retries_the_read(backend):
backend.client.get.side_effect = [redis_errors.ConnectionError('down')] * 2 + [None]
backend.store_result('id-1', None, states.STARTED)
assert backend.client.get.call_count == 3
backend.client.pipeline.return_value.__enter__.return_value.execute.assert_called_once()
def test_store_gives_up_after_retry_policy(backend):
backend.client.get.side_effect = redis_errors.ConnectionError('down')
with pytest.raises(redis_errors.ConnectionError):
backend.store_result('id-1', None, states.STARTED)
assert backend.client.get.call_count == 4
def test_store_after_retry_keeps_success(backend):
stored = json.dumps({'status': states.SUCCESS, 'result': 4, 'task_id': 'id-1'})
backend.client.get.side_effect = [redis_errors.ConnectionError('down'), stored]
backend.store_result('id-1', None, states.STARTED)
backend.client.pipeline.assert_not_called()
def test_client_reads_fail_fast(backend):
backend.client.get.side_effect = redis_errors.ConnectionError('down')
with pytest.raises(redis_errors.ConnectionError):
backend.get_task_meta('id-1')
assert backend.client.get.call_count == 1What I ran: each design under the same outage, CPU, self-heal time, chords, and the read retry
Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0, RabbitMQ 4.1.8, Redis 7.0.15. The worker ran -P prefork -c 1 with task_acks_late, task_reject_on_worker_lost and task_track_started. The result backend was a separate Redis that I stopped before the worker started and restarted after the outage, keeping its data. Ten tasks, or five chords of two tasks each.
15 s outage, ten tasks:
| Design | Redis broker | Classic queue | quorum queue | Early ack | Worker CPU | All done after the backend returned |
|---|---|---|---|---|---|---|
| main | 10 lost | 10 lost | 10 lost | 10 lost | 0.1% | never |
| This PR | all ran, 2,436 receipts | all ran, 2,971 receipts | 10 lost, 210 receipts | 10 lost | 94 to 106% | 0.2 s |
result_backend_always_retry=True |
all ran | all ran | all ran | all ran | 0.1% | 0.4 to 7.8 s |
| Read retry in the Redis backend, with this PR | all ran | all ran | all ran | all ran | 0.1% | 0.6 to 0.8 s |
Send the task again with a countdown, like task_retry_on_worker_lost |
all ran, 40 receipts | all ran | all ran | all ran | 1.2% | 0.6 s with a 5 s countdown |
| Run the task without storing STARTED | ran, no result stored | ran, no result stored | ran, no result stored | ran, no result stored | 0.1% | ran during the outage |
| This PR, waiting 1 s before each requeue | all ran, 25 receipts | all ran | all ran | not run | 0.9% | 0.8 s |
"All ran" means each task ran once with its result stored. The countdown design keeps unrelated tasks flowing, but it waits default_retry_delay (180 s by default) and gives up after max_retries.
60 s outage on a quorum queue, ten tasks:
| Design | Result | Receipts |
|---|---|---|
| This PR | 10 lost | 210 |
| Read retry alone | 9 ran, 1 lost | 10 |
| Read retry with this PR | all ran | 13 |
result_backend_always_retry=True |
all ran | 10 |
Five chords, 15 s outage: all five bodies ran with this PR, with result_backend_always_retry=True and with the read retry, on the Redis broker and the classic queue. The read retry with this PR also ran all five on a quorum queue through a 60 s outage. Running the task without storing STARTED didn't run any body, because the header results weren't stored.
Broker CPU during the outage was 4 to 6% with this PR, and 0.2 to 0.9% with the others. With one pool process, ten tasks that store results and ten ignore_result tasks on a classic queue:
| Design | ignore_result tasks run during the outage |
|---|---|
| This PR | 3 |
| The designs that wait in place | 0 |
| Send the task again with a countdown | 10 |
A pool process killed with os._exit() during the outage, then five ignore_result tasks, on a worker with two processes:
| Setting | Tasks run within 15 s | Within 35 s | ping reply |
|---|---|---|---|
| main | 5 | 5 | yes |
result_backend_always_retry=True |
0 | 0 | no |
| Read retry with this PR | 0 | 5 | yes |
The read retry I ran, on top of 613e2ff. test_redis.py, test_base.py and test_trace.py pass with it (506 tests). Reading a result while the backend is down still fails after 0.1 s, while a store retries for 19 s:
diff --git a/celery/backends/redis.py b/celery/backends/redis.py
index 2a6da4618..99eca125a 100644
--- a/celery/backends/redis.py
+++ b/celery/backends/redis.py
@@ -12,6 +12,7 @@ from urllib.parse import unquote
from uuid import uuid4
from kombu.utils import symbol_by_name
+from kombu.utils.encoding import bytes_to_str
from kombu.utils.functional import retry_over_time
from kombu.utils.objects import cached_property
from kombu.utils.url import _parse_url, maybe_sanitize_url
@@ -802,6 +803,26 @@ class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin):
retries, max_retries or 'Inf', humanize_seconds(tts, 'in '))
return tts
+ def _store_result(self, task_id, result, state,
+ traceback=None, request=None, **kwargs):
+ # The base class reads the stored result before it writes, so it
+ # doesn't replace a SUCCESS. set() retries the write with
+ # retry_policy; retry that read the same way, so that a short outage
+ # doesn't fail the store before the write is tried. Reads by clients
+ # (AsyncResult.state) still fail fast.
+ meta = self._get_result_meta(result=result, state=state,
+ traceback=traceback, request=request)
+ meta['task_id'] = bytes_to_str(task_id)
+ current_meta = self.ensure(self._get_task_meta_for, (task_id,))
+ if current_meta['status'] == states.SUCCESS:
+ return result
+ try:
+ self._set_with_state(self.get_key_for_task(task_id),
+ self.encode(meta), state)
+ except BackendStoreError as ex:
+ raise BackendStoreError(str(ex), state=state, task_id=task_id) from ex
+ return result
+
def _set_with_state(self, key, value, state):
if state == states.FAILURE:
return self.set(key, value, expires=self.failure_expires)RedisBackend.set() already retries with retry_policy, but the read that _store_result does first didn't, so a short outage failed the store at once and the STARTED requeue looped. Retry that read the same way through a _get_task_meta_for_store() hook. Reads by clients still fail fast. Also log a warning when a task is requeued because STARTED couldn't be stored, since errors like AuthenticationError are retryable for Redis and would otherwise loop silently.
|
Thanks @ChristianMurphy, this was really thorough. Pushed 3ec401c with both changes. Read retry. Same behavior as your diff, but through a small hook instead of copying _store_result into RedisBackend. BaseKeyValueStoreBackend._store_result now reads through _get_task_meta_for_store(), which defaults to _get_task_meta_for(). RedisBackend overrides it to call self.ensure(self._get_task_meta_for, (task_id,)), so it uses the same retry_policy as set(). Client reads (get_task_meta, AsyncResult.state) still fail fast. Happy to switch to your full override if you prefer it. Warning. Added before the Reject, with your wording: Task %s[%s] requeued: storing STARTED failed: %r. Measured with the same setup as before: Redis broker, Redis backend on 6380, prefork -c 1, 10 tasks, task_track_started=True. receipts in a 15 s outage after the backend returns at 8 s t/unit/tasks/test_trace_started_store.py: a real RedisBackend with a mock client, using your cases. Requeue for ConnectionError/TimeoutError and not for ResponseError; the requeue is logged (with AuthenticationError); and the outage-length sweep over 0, 1, 3, 4 and 10 failed reads, with max_retries=3. I couldn't run the smoke tests: there's no Docker daemon where I'm working. If you'd like t/smoke/tests/test_backend_outage.py and the quorum-queue variant in this PR, I can add them. Or, if you already have them written, would you be OK with me adding them with you as co-author? |
|
Looks good for Redis, with one question for @auvipy. Re-tested 3ec401c. @auvipy, this PR requeues an 3ec401c adds a wait before the requeue, in the Redis backend: each store retries its read of the stored result with Should the wait stay in each backend's store, or move into the tracer, around the stores a pool process makes?
I lean toward the tracer. On your questions: keep the hook. It's smaller than my override, and What I ran: the outage matrix, lost pool processes, the database backend, a wrong password, smoke tests and mutations, and a note on the open questionOn the open question in the description: the read retry leaves only outages longer than about 20 s on Redis. There the choice is between running the body again and losing the result. Celery at 3ec401c, Python 3.13, kombu 5.7.0rc1, Redis result backend stopped for 15 s, ten tasks or five chords:
With ten more Backend down the whole time,
Database backend (
The worker log shows Wrong Redis password for 45 s, five tasks: 6 receipts, 3 requeue warnings naming The container smoke tests from my last comment: 2 passed on 3ec401c. The whole unit suite has no new failures. The 11 that fail here also fail on main in my environment. Mutations of the new code, against
|
|
the tracer way seems better to me too |
Move the wait before a STARTED requeue from the Redis backend's store into the tracer, as discussed in the review. While a task runs, build_tracer sets store_retry_timeout, and Backend.store_result retries errors that are safe to retry, with the usual exponential backoff, until the new result_backend_store_retry_timeout setting (20 s by default) runs out. This covers the STARTED, result and failure stores of every backend, while stores from the worker's main process and reads by clients still fail fast. A BackendStoreError raised from an error that is safe to retry counts as safe to retry too, so the database backend, which wraps its errors after its own retries, now waits and requeues like Redis. The Redis-only read retry is removed.
|
Thanks both. Pushed 4083a45, which moves the wait into the tracer. How it works
Doing it in Database backend. It retries 3 times in under a second, then raises Hook. I removed the Redis read retry and the Measured with prefork
I didn't re-run the lost-pool-process case. A unit test checks that the context variable is cleared after the task, so a store outside the task fails at once. Tests
The read-retry tests in Smoke tests. I'll add yours next, with you as co-author. |
Stop the Redis backend container for 15 s while five acks_late tasks with track_started wait, on a classic and on a quorum queue. Each task must run once with a SUCCESS result, and the worker must not receive them more than three times each. Co-authored-by: Christian Murphy <[email protected]>
|
Added your smoke tests in 99c3d79, with you as co-author. The only change is the comment on |
ChristianMurphy
left a comment
There was a problem hiding this comment.
Needs a few changes before merge. I tested ae3db1a with a prefork worker against Redis, a RabbitMQ classic queue and a quorum queue, with Redis and Postgres result backends.
Moving the wait into the tracer fixed both problems from my last comment. After 3 lost pool processes, the worker ran the next task at 0.7 s, as on main. The database backend kept every task through a 15 s outage. Every task ran once on each broker, chords too, through 60 s on a quorum queue. The worker used 0.2% CPU or less, the broker 0.5% or less, and throughput without an outage matched main.
The changes, each in an inline comment:
- Recovery is slower. The wait sleeps up to
result_backend_max_sleep_between_retries_ms, 10 s by default, so a store can wake about 10 s after the backend is back. - The wait counts against the task's time limits. With a 5 s soft limit, tasks failed without running, or were lost.
- The wait also applies inside the task body, so
update_state()now blocks for 20 s during an outage. - The docs leave out that the pool process is blocked, that a task can wait twice, and that the requeue needs
task_track_started.
On the database backend the two retry loops nest, which floods the log. The inline comment on _ensure_retryable() suggests one loop.
The tests caught most of the mutations I tried on the new code. They missed these:
- The backoff never grows. A pool process then reads 3,980 times in 20 s instead of 15.
- Eager tasks wait too.
- The default changes to 0.
- The retry warning goes away.
A test that counts reads through a long outage would catch the first. Could the PR also add a changelog entry? Recent fixes such as #10945 and #10944 add one under "Unreleased".
What I ran: outages on each broker and backend, lost pool processes, time limits, large results, overhead and mutations
Celery at ae3db1a and at main 6b67b23, Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0, RabbitMQ 4.1.8, Redis 7.0.15, Postgres 17. The worker ran -P prefork -c 1 with task_acks_late and task_track_started, unless noted.
Redis result backend stopped for 15 s:
| Broker | Ten tasks | Five chords | Receipts | Worker CPU | Done after the backend returned | Same at 3ec401c |
|---|---|---|---|---|---|---|
| Redis | all ran once | 5 of 5 bodies | 10 | 0.1 to 0.2% | 0.6 and 1.8 s | 0.6 s |
| RabbitMQ classic queue | all ran once | 5 of 5 bodies | 10 | 0.0 to 0.1% | 2.6 and 5.6 s | 0.6 to 0.8 s |
| RabbitMQ quorum queue | all ran once | 5 of 5 bodies | 10 | 0.0 to 0.2% | 3.8 and 0.8 s | 0.6 s |
| RabbitMQ quorum queue, 60 s outage | all ran once | not run | 12 | 0.1% | 0.6 s | 0.6 s |
| Redis, early ack | all ran once | not run | 10 | 0.0% | 3.0 s | 0.6 s |
Broker CPU stayed at 0.5% or less. With ten more ignore_result tasks on one pool process, none ran during the outage and all ran after it, 5.0 s after the backend returned.
Backend down the whole time, -c 2, 3 tasks that call os._exit(), then 5 ignore_result tasks:
| Tree | First ignore_result task ran |
ping replies |
|---|---|---|
| main | 0.7 s | 1 of 1 |
| 3ec401c | 57.8 s | 1 of 5 |
| ae3db1a | 0.7 s | 1 of 1 |
Database backend, Postgres stopped for 15 s after the worker started, ten tasks:
| Tree | On a classic queue | On a quorum queue |
|---|---|---|
| main | 0 of 10 ran | 0 of 10 ran |
| ae3db1a | 10 of 10 ran once, SUCCESS | 10 of 10 ran once, SUCCESS |
Tasks with soft_time_limit=5 and time_limit=8, five of them, with the Redis backend down for 15 s:
| Tree | Ran | Stored |
|---|---|---|
| main | 0 | 5 PENDING |
| ae3db1a | 3 | 3 SUCCESS, 1 FAILURE from SoftTimeLimitExceeded before the body ran, 1 PENDING after the hard limit |
Tasks that sleep 3 s and return 20 MB, three of them, with task_track_started off and Redis stopped for 12 s during the first one:
| Tree | Stored | Worker CPU while waiting | Peak RSS | First result stored after Redis was back |
|---|---|---|---|---|
| main | 3 PENDING | 0.9% | 120 MB | never |
| ae3db1a | 3 SUCCESS | 0.2% | 71 MB | 9.3 s |
The retries before that store slept 0.02, 0.02, 0.00, 0.08, 0.18, 0.45, 0.81, 0.28, 0.78, 7.76 and 9.61 s.
With a fake clock and the Redis client always failing:
- One store in a 20 s window: 15 reads. With the backoff not growing: 3,980. With a 1 s cap: 46 on median over 200 runs, 57 at most.
update_state()in a task body: waited 20 s, then raised. Main raised at once.task_track_startedoff and the backend down throughout: the body ran once. The pool process then waited 20 s to store SUCCESS and 20 s more to store FAILURE.
Throughput with no outage, 3,000 tasks with a link each, -c 4, local Redis, two runs each: main 956 and 972 tasks/s, ae3db1a 932 and 988 tasks/s, both with 10 Redis commands per task.
Both smoke tests passed on ae3db1a.
The whole unit suite has no new failures. The 11 that fail here also fail on main in my environment.
Mutations of the new code, against test_trace_started_store.py, test_trace.py, backends/test_base.py, test_redis.py, test_database.py, test_request.py, test_app.py and test_defaults.py:
| Mutation | Result |
|---|---|
| Sleep not capped at the deadline | caught |
remaining <= 0 changed to < 0 |
caught, by hanging under the fake clock |
| Retry any error | caught |
| The backoff never grows | missed |
| No deadline, so no wait | caught |
No BackendStoreError unwrap |
caught |
| No retry warning | missed |
| Eager tasks wait too | missed |
ContextVar not reset |
caught |
| Wrapper never applied | caught |
| The requeue check skips the unwrap | caught |
| No requeue warning | caught |
A requeue without acks_late |
caught |
Reject(requeue=False) |
caught |
| Default changed to 0 | missed |
…d use one retry loop - Cap the sleep between store tries at 1 s, so a state is stored soon after the backend is back. - Stop waiting a second before the task's soft time limit, or its time limit, so the task is requeued rather than failed or killed. - Run the task body with the wait off, so update_state() and other stores the task makes fail fast as before. - Pass the deadline to _ensure_retryable(), so one loop applies both result_backend_max_retries and the timeout. It logs the backend's own error without a traceback and calls on_backend_retryable_error() before each try. - Rewrite the setting's docs, add a changelog entry, and add tests for the backoff, eager tasks, the default, the retry warning, the time limit and the task body.
Co-authored-by: Aman <[email protected]>
With result_backend_always_retry, max_retries can allow tries after the deadline has passed. Before bac962c they slept for 0 s and hit the backend in a tight loop. Co-authored-by: Aman <[email protected]>
|
Looks better. I reran everything on 34ae4ec and the points from my last review are covered. Two small things are left, and neither needs to block the merge.
What I checked against the last review:
The two things left: With the wait turned off, the requeue loops again. The docs say "Set to A quorum queue's delivery limit still ends it. With the default 20 s and a 450 s outage, two tasks were delivered 21 times and dropped, and the other 8 ran once. RabbitMQ puts a requeued message back at the head. The same messages come around every 20 s and reach the default limit of 20 after about 7 minutes. Main loses every task at once there, so this is an improvement. The docs could say that the delivery limit bounds how long an outage a quorum queue survives. One question for auvipy: the docs say Setup of the runs
|
|
Also can you look into CI? Several jobs are failing |
With result_backend_store_retry_timeout off, a task that can't store STARTED is requeued at once until the backend is back. On a quorum queue each requeue is a delivery, so the delivery limit bounds the outage a task survives. Also check that the store wait stops before the soft time limit, not at it.
Main released 5.7.0 and folded its Unreleased changelog entries into the 5.7.0 notes, so the celery#8588 entry moves to a new Unreleased section at the top.
|
Thanks @ChristianMurphy. b2d4419 adds both notes to the docs: with the wait off, a task that can't store STARTED goes straight back to the queue until the backend is back, and on a quorum queue the delivery limit bounds the outage a task survives. The time-limit test now checks that the wait stops before the limit, so it catches On CI: pre-commit.ci was failing its mergeable check on a merge conflict. Main released 5.7.0 and folded the Unreleased changelog section into the 5.7.0 notes. 7c8315a merges main and moves the #8588 entry to a new Unreleased section at the top. The unit tests and pre-commit pass locally after the merge. The other workflows still need approval to run. |
|
@auvipy could you approve the workflow runs when you have a moment? They've been waiting since the merge-conflict fix. @ChristianMurphy, if b2d4419 covers your last notes, would you mind updating your review? Thanks both. |
|
can we adjust the API surface changed so that we can include it in a bug fix release rather then waiting for a feature release? if not, we have to wait until the v5.8.x release cycle starts. will approve the CI later then |
…lease Remove result_backend_store_retry_timeout. The 20 s wait is now the private _STORE_RETRY_TIMEOUT in celery.app.trace, and _store_retry, _STORE_RETRY_MAX_SLEEP, _STORE_RETRY_LIMIT_MARGIN and Backend._store_error_safe_to_retry() are private too, so the change adds no public API. The behavior is unchanged.
|
@auvipy yes, c8fc1bd removes the new public API so this can go in a bug fix release:
The behavior is unchanged: with a real Redis backend down for 15 s, all 10 tasks ran once, 0.5 s after it came back. The open inline threads are all covered; I hadn't replied in them, sorry:
|
|
I guess I'm a bit late to the party with this 😅 One case is left after this merge, for whoever follows up. A worker started with
What I ran
|
|
@ChristianMurphy I think you can tackle that on a follow up |
Description
Refs #8588. This fixes the case where tasks are lost without running. It deliberately leaves one case open, explained below.
Problem. With
task_track_startedandacks_late, the worker writes STARTED before running the task body. If the result backend is unreachable, that write raises, and the tracer treats it as a task failure. With the defaulttask_acks_on_failure_or_timeout, the message is then acked. Storing the FAILURE also fails, so nothing records what happened. Every queued task is consumed without running.Change. In
build_tracer, when the STARTED write fails, the task'sacks_lateis set, andbackend.exception_safe_to_retry(exc)is true, raiseReject(exc, requeue=True).Request.on_failurealready turns that intoreject(requeue=True)without storing a result, so the message waits in the broker until the backend is back. Anything else keeps the current behavior: noacks_late, a backend that doesn't overrideexception_safe_to_retry(the base class returns False), or a non-retryable error.This is safe because the task body has not run yet, so redelivery cannot repeat any side effects.
Repro. Redis broker on 6379, separate Redis result backend on 6380. Settings:
task_acks_late=True,task_reject_on_worker_lost=True,task_track_started=True. Enqueue 10 tasks, stop the backend, and runcelery worker -P prefork -c 1. Each task appends a line to a file.Pool callback raised exceptionIn the last row, all 10 results are stored as
SUCCESS.Left open: a write failing after the task body ran. This is the
task_track_started=Falsecase from the issue, and FAILURE stores. I first tried the same requeue formark_as_doneandmark_as_failure. With the backend down for 15 seconds, the 10 tasks ran 1509 times: each run's store failed, the message was requeued, and the task ran again immediately. For tasks with side effects, that is worse than losing the result, so I kept it out of this PR.Options I can see for that case:
result_backend_always_retry=Truefor this setup. In @ChristianMurphy's tests, that setting avoided both problems.task_retry_on_worker_lost(feat(worker): add task_retry_on_worker_lost to limit requeues after worker loss #10843).@auvipy, which would you prefer? I'm happy to do it as a follow-up.
Tests. Three new tests in
t/unit/tasks/test_trace.py:acks_lateand a retryable error, without running the body or storing a failureacks_lateThe first test fails on main.
Checks.
t/unit/tasks,t/unit/workerand the base and Redis backend tests pass: 2486 passed. flake8 and isort are clean.