Skip to content

Complete chord part return when pool child is lost after storing SUCCESS - #11170

Open
meat-daemon-404 wants to merge 1 commit into
celery:mainfrom
meat-daemon-404:fix/chord-part-return-worker-lost
Open

meat-daemon-404 wants to merge 1 commit into
celery:mainfrom
meat-daemon-404:fix/chord-part-return-worker-lost

Conversation

@meat-daemon-404

Copy link
Copy Markdown

Summary

When a prefork worker child stores SUCCESS for a chord header task and is killed before on_chord_part_return() completes, Request.on_failure() previously acknowledged the message without invoking on_chord_part_return(), leaving the chord stuck in PENDING forever.

This change calls self.task.backend.on_chord_part_return(self._context, states.SUCCESS, result) from the main process in the if success_meta: branch whenever self._context.chord is set, before acknowledging the task.

Testing

  • Added t/unit/worker/test_request_chord_worker_lost.py verifying that on_chord_part_return() is called for chord headers when WorkerLostError arrives after SUCCESS was stored, and skipped for non-chord tasks.
  • Ran pytest -q t/unit/worker/test_request_chord_worker_lost.py (2 passed) and pytest -q t/unit/worker/test_request.py -k "after_success_was_stored or worker_lost" (18 passed).

Fixes #11038

When a prefork child stores SUCCESS for a chord header and is killed
before on_chord_part_return() runs, Request.on_failure() previously
acknowledged the message without calling on_chord_part_return(), leaving
the chord stuck in PENDING forever. Invoke on_chord_part_return() from
the main process when self._context.chord is present.

Fixes celery#11038
@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy is this PR a duplicate one?

@ChristianMurphy

Copy link
Copy Markdown
Contributor

No, it's not a duplicate. It's the first PR for #11038, and it takes the direction I suggested in the issue. My #11072 only mentions #11038 and doesn't touch this code.

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

OK great

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

@gyanu2507 @MehrazRumman check this please

@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.43%. Comparing base (14115f0) to head (a142c04).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11170      +/-   ##
==========================================
- Coverage   91.43%   91.43%   -0.01%     
==========================================
  Files         153      153              
  Lines       22061    22063       +2     
  Branches     2749     2750       +1     
==========================================
+ Hits        20172    20173       +1     
  Misses       1588     1588              
- Partials      301      302       +1     
Flag Coverage Δ
unittests 91.41% <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 changes before merge. It fixes the case I reported in #11038, but on the memcached backend it breaks chords that work on main.

I ran a142c04b3 against main (14115f05e) with Redis 7, memcached 1.6 and PostgreSQL 16 as result backends, prefork, chords of four headers. A hook in a backend subclass kills the pool process of one header at a chosen step.

The reported case is fixed. Process killed after SUCCESS is stored and before the header is counted:

main This PR
Redis, first or last header, late and early ack PENDING, 12 of 12 body ran once, 12 of 12
memcached, first or last header PENDING, 6 of 6 body ran once, 6 of 6

1. On memcached a header is now counted twice when its process is killed after the count. The child counted the header, and the main process counts it again. Two cases, three chords each:

Process killed main This PR This PR with #11072
After an early header was counted, while another header runs for 10 s body ran once chord fails with TimeoutError, errback runs body ran once
After the last header finished its part return (the body is already sent) body ran once body ran once, and the errback runs too body ran once

In the first case the counter equals the chord size one header early, the join waits 3 s for a result that is not there, and the chord fails. In the second the chord's keys are already deleted, so the second part return fails the chord with GroupResult ... no longer exists. The second case is the usual way a process is lost after SUCCESS: in on_success or a task_postrun receiver. DynamoDB and GCS count the same way. I did not run them.

Either of these would settle it. #11072 (mine) makes a repeated part return harmless on the cache, DynamoDB and GCS backends, and with both PRs merged all the cases above come out right. Or this PR can call the part return from the main process only on backends where a repeat is safe. Redis is: it counts each header once, and the same kills gave the same result on main and here. PostgreSQL does not count parts and is not affected.

2. A test with a backend. Both new tests mock the backend, so they could not see point 1. An integration test for Redis is below: it fails on main with a timeout and passed 5 of 5 here. The unit tests also miss one of five bugs I planted: with the ack moved before the part return, they all pass. A test for the order is below too.

3. Please change "Fixes #11038" to "Refs". One case from the issue stays open, on main and here: when the process is killed after the last header was counted and before the body is sent, the chord is PENDING (3 of 3 on Redis, 3 of 3 on memcached, still after 45 s). On Redis the dead process holds the chord's claim. That can be a follow-up, with the issue left open for it.

Integration test

A new file, t/integration/test_chord_worker_lost.py:

from unittest.mock import Mock

import pytest
from billiard.einfo import ExceptionInfo

from celery import states, uuid
from celery.app.task import Context
from celery.exceptions import WorkerLostError
from celery.result import AsyncResult
from celery.worker.request import Request

from .conftest import TEST_BACKEND
from .tasks import identity, tsum

TIMEOUT = 20


def test_chord_completes_when_a_header_is_lost_after_it_stored_success(manager):
    """The pool process of a chord header is lost after SUCCESS is stored
    and before the header is counted (#11038): the body must still run."""
    if not TEST_BACKEND.startswith('redis'):
        raise pytest.skip('Requires redis result backend.')
    app = manager.app
    backend = app.backend
    gid, first, lost, body_id = uuid(), uuid(), uuid(), uuid()
    body = tsum.s().set(task_id=body_id)
    backend.set_chord_size(gid, 2)

    # The first header returns as usual: stored and counted.
    backend.mark_as_done(first, 1, request=Context(
        id=first, group=gid, group_index=0, chord=body))
    # The second header stored its result, and its process died there.
    backend.store_result(lost, 2, states.SUCCESS)

    message = Mock(name='message')
    message.headers = {'id': lost, 'task': identity.name,
                       'group': gid, 'group_index': 1}
    message.properties = {'correlation_id': lost, 'reply_to': ''}
    message.delivery_info = {'routing_key': 'celery'}
    request = Request(
        message, on_ack=Mock(), on_reject=Mock(), app=app,
        task=app.tasks[identity.name], decoded=True,
        body=((2,), {}, {'callbacks': None, 'errbacks': None,
                         'chain': None, 'chord': body}),
    )
    try:
        raise WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL)')
    except WorkerLostError:
        einfo = ExceptionInfo(internal=True)
    request.on_failure(einfo)

    assert AsyncResult(body_id, app=app).get(timeout=TIMEOUT) == 3
Unit test for the order of the part return and the ack

In t/unit/worker/test_request_chord_worker_lost.py:

def test_on_failure_worker_lost_counts_the_header_before_the_ack(app):
    # If the part return raised after the ack, nothing would redeliver the
    # header and the chord would stay PENDING.
    @app.task(shared=False, acks_late=True)
    def header_task():
        return 42

    chord_callback = {'task': 'proj.body', 'args': (), 'kwargs': {}}
    message = Mock()
    message.headers = {'id': 'chord-header-2', 'task': header_task.name,
                       'group': 'chord-group-2', 'group_index': 0}
    message.properties = {'correlation_id': 'chord-header-2', 'reply_to': ''}
    message.delivery_info = {'routing_key': 'celery'}
    calls = Mock()
    req = Request(
        message, on_ack=calls.ack, on_reject=Mock(), app=app,
        task=header_task, decoded=True,
        body=((), {}, {'callbacks': None, 'errbacks': None, 'chain': None,
                       'chord': chord_callback}),
    )
    req.task.backend = Mock()
    req.task.backend.max_retries = 3
    req.task.backend._ensure_retryable.return_value = {
        'status': states.SUCCESS, 'result': 42,
    }
    req.task.backend.on_chord_part_return = calls.part_return

    req.on_failure(_make_worker_lost_einfo())

    assert [call[0] for call in calls.mock_calls] == ['part_return', 'ack']
Other checks
  • Redis, process killed after an early header was counted, or after any header finished its part return: body ran once on main and here, no errback, no second body.
  • PostgreSQL, process killed after the header was stored: body ran once on main and here.
  • A backend error raised by the part return in the main process: the worker logs it and keeps running, and a late-ack message stays unacknowledged for redelivery.
  • t/unit/worker as tox runs it (python -bb): 847 passed. flake8 and isort are clean on the touched files.
What I did not run
  • DynamoDB and GCS, and memcached with early ack.
  • Pools other than prefork, and Python versions other than 3.13.
  • Random kills or an out-of-memory kill. The hook placed the kills in these runs.

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

@meat-daemon-404 check the last review from murphy

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

Thanks for this. The direction is right, and I agree with @ChristianMurphy's review. Some notes from reading it against main:

  • The double count (point 1) should block. The Redis Lua script counts each header once, keyed on the task id, so a repeated part return is harmless there. The cache, DynamoDB and GCS backends just increment a counter, so the main process can't tell whether the child already counted. Of the two options, I'd prefer landing #11072 first and keeping this PR backend-agnostic. A list of backends where a repeat is safe would leave memcached, DynamoDB and GCS stuck exactly as on main, and it would need updating every time a backend changes.
  • The part return now runs in the consumer process. For the last header on Redis, on_chord_part_return joins the header results (up to result_chord_join_timeout) and then publishes the body, all inside the worker's main loop. This only happens on the worker-lost path, so it's probably acceptable, but a code comment saying so would help the next reader. If the join raises, the late-ack message stays unacknowledged and gets redelivered, which is what we want.
  • Tests (nit): the existing after_success_was_stored tests are in t/unit/worker/test_request.py. I'd put the new ones next to them, using the get_request() helper there, rather than in a new file. Murphy's ordering test (part return before ack) is worth adding as well.
  • Agree on changing "Fixes" to "Refs #11038" in the description and the commit message, since the case where the process is killed after the last header is counted but before the body is sent is still open.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Chord stays PENDING forever when a pool process is lost after a header stored SUCCESS

4 participants