Skip to content

Do not run failure handling twice for a hard time limit - #11105

Merged
auvipy merged 7 commits into
celery:mainfrom
tony1233200:fix/11090-hard-time-limit-double-failure
Nov 24, 2026
Merged

auvipy merged 7 commits into
celery:mainfrom
tony1233200:fix/11090-hard-time-limit-double-failure

Conversation

@tony1233200

Copy link
Copy Markdown
Contributor

Closes #11090

What changed

For a hard time limit, the pool first sets the job's result to TimeLimitExceeded, which calls Request.on_failure(), and then calls Request.on_timeout() for the same limit. Both ran the full failure handling, so the backend stored the failure twice (firing the errbacks twice) and, since #10226, the task_failure signal and the task-failed event were also sent twice.

  • Request.on_failure() now records _time_limit_failure_handled = True when its failure block (backend mark_as_failure + task_failure signal) has run for a TimeLimitExceeded.
  • Request.on_timeout() (hard limit) skips its duplicate failure block when that flag is set. Its acknowledge/reject handling at the end is unchanged.

The flag is only set when on_failure() actually stored the failure: when acks_on_failure_or_timeout = False makes on_failure() requeue instead of storing, the flag stays unset and on_timeout() still stores the FAILURE and fires the errback, as #11090 requires for that configuration. Calling on_timeout() alone (the path the existing hard-timeout tests exercise) is unchanged.

Verification

  • New regression test test_hard_time_limit_failure_not_handled_twice drives the pool's exact sequence -- on_failure(ExceptionInfo(TimeLimitExceeded)) followed by on_timeout(soft=False) -- and asserts mark_as_failure, the task_failure signal and the task-failed event each fire exactly once. It fails without this change and passes with it.
  • Full t/unit/worker/test_request.py: 181 passed.
  • flake8 clean on the touched files.

Disclosure: this change was prepared with AI assistance (Muse). All test results above are from actual runs on this branch.

Comment thread celery/worker/request.py Resolved
@auvipy
auvipy self-requested a review November 16, 2026 15:24
@auvipy auvipy added this to the 5.7.x milestone Nov 16, 2026
@tony1233200

This comment was marked as abuse.

@auvipy

auvipy commented Nov 23, 2026

Copy link
Copy Markdown
Member

@tony1233200 can you please stop this kind of attention seeking drama? this is last warning

@auvipy auvipy reopened this Nov 23, 2026
@tony1233200

This comment was marked as abuse.

@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy please check

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.36%. Comparing base (c7d74ff) to head (b6fb48d).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11105   +/-   ##
=======================================
  Coverage   91.35%   91.36%           
=======================================
  Files         153      153           
  Lines       21896    21902    +6     
  Branches     2722     2725    +3     
=======================================
+ Hits        20004    20010    +6     
  Misses       1590     1590           
  Partials      302      302           
Flag Coverage Δ
unittests 91.34% <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.

@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 two tests before merge. The fix itself works: I ran 34d222c8a against main (c0b177ede) and it does what I asked for in #11090.

A prefork worker on Redis, a task killed by its hard time limit:

main This PR
Errback (link_error) 2 calls 1
task_failure signal 2 1
task-failed event 2 1
Task.on_failure and after_return 1 each 1 each

The same holds with ignore_result, with acks_late, after a caught soft limit, for two tasks at once, and for 40 tasks over their limit on 8 processes: every task has each count at 1 here and at 2 on main. A chain and a chord around the task end the same as on main. The gevent pool calls only on_timeout() and was at 1 already. The change is small, and I would not make it smaller: on_timeout() has to keep its own handling for the pools that call nothing else.

The path where on_failure() requeues has no test. With acks_late and acks_on_timeout off, on_failure() requeues the message and stores nothing, so on_timeout() must still do its own handling. If the flag is set there too, all 186 tests in test_request.py pass. The test below passes here and on main, and fails with that bug.

A smoke test. The unit tests call the two handlers by hand, in the order the pool calls them today. A smoke test checks the pool itself. The one below fails on main (assert 2 == 1) and passes here, on the RabbitMQ and the Redis broker.

Unit test

For t/unit/worker/test_request.py:

    def test_hard_time_limit_requeued_by_on_failure_is_handled_by_on_timeout(self, patching):
        """With acks_late and acks_on_timeout off, on_failure()
        requeues the message and stores nothing, so on_timeout() must not
        skip its own failure handling.
        """
        patching('celery.worker.request.error')

        handler = Mock(name='signal_handler')
        task_failure.connect(handler)
        original_mark = self.mytask.backend.mark_as_failure
        self.mytask.acks_late = True
        self.mytask.acks_on_timeout = False
        try:
            job = self.xRequest()
            job.send_event = Mock(name='send_event')
            mark_mock = Mock(name='mark_as_failure')
            job.task.backend.mark_as_failure = mark_mock
            try:
                raise TimeLimitExceeded(30)
            except TimeLimitExceeded:
                job.on_failure(ExceptionInfo())
            mark_mock.assert_not_called()
            handler.assert_not_called()
            job.on_timeout(soft=False, timeout=30)
        finally:
            task_failure.disconnect(handler)
            self.mytask.backend.mark_as_failure = original_mark

        mark_mock.assert_called_once()
        handler.assert_called_once()
Smoke test

In test_time_limit in t/smoke/tests/test_tasks.py. It needs from time import sleep, get_redis_connection from t.integration.conftest and errback_new_style from t.integration.tasks:

    def test_hard_timeout_calls_the_errback_once(self, celery_setup: CeleryTestSetup):
        """A hard time limit runs the failure handling once (#11090)."""
        queue = celery_setup.worker.worker_queue
        sig = self_termination_delay_timeout.s().set(queue=queue)
        sig.link_error(errback_new_style.s().set(queue=queue))
        task_id = sig.freeze().id
        redis_connection = get_redis_connection()
        redis_connection.delete(task_id)

        with pytest.raises(TimeLimitExceeded):
            sig.apply_async().get(timeout=RESULT_TIMEOUT)

        # The errback counts its calls under the id of the failed task.
        # Give a second call time to arrive before counting.
        sleep(5)
        assert int(redis_connection.get(task_id)) == 1
        redis_connection.delete(task_id)

For my run I removed the apt-get step from the worker image, since my sandbox could not reach the package mirror.

One thing this PR leaves as it is, which is fine. The second point in #11090 is unchanged: with acks_late and no ack on timeout, the task is requeued, and it is still stored as FAILURE with its errback called before the next run ends in SUCCESS. I'll track that separately. Whether #11090 closes with this PR is your call, @auvipy.

What I did not run
  • RabbitMQ as the broker outside the smoke test, and eventlet.
  • Python versions other than 3.13.

@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Member

if you can handle the remaining part, i will leave that

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Sure, I'll take the requeue case in a follow-up PR once this merges.

- Unit test: on_failure() requeue path still handled by on_timeout()
- Smoke test: hard timeout calls the errback once (celery#11090)
@tony1233200

This comment was marked as abuse.

@auvipy
auvipy merged commit d463388 into celery:main Nov 24, 2026
22 of 23 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.

A hard time limit runs the failure handling twice: errbacks, task_failure and task-failed

4 participants