Skip to content

Chain-in-chord that fails before the last task in the chain doesn't trigger chord error handling #6220

Closed

Description

@msci-jordancrawford

Checklist

  • I have verified that the issue exists against the master branch of Celery.
  • This has already been asked to the discussion group first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the master branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the master branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.
    Confirmed to exist on at least celery 4.3.0 as well.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • There are several other issues that deal with chains-in-chords, e.g. Issue with chord group task exceptions and Redis backend #5229 seems similar, but nothing that addresses this exact problem. I don't think this duplicates them, but I haven't dug into the celery code enough to be sure that they aren't caused the the same underlying misbehavior in the redis backend.

Environment & Settings

Celery version: 4.4.6 (cliffs)

celery report Output:

software -> celery:4.4.6 (cliffs) kombu:4.6.11 py:3.6.9
            billiard:3.6.3.0 redis:3.5.3
platform -> system:Linux arch:64bit, ELF
            kernel version:4.4.0-17763-Microsoft imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:redis results:redis://localhost:6379/

broker_url: 'redis://localhost:6379//'
result_backend: 'redis://localhost:6379/'

Steps to Reproduce

Required Dependencies

Not sure that any of these are minimal, but I'll include what I can test locally:

  • Minimal Python Version: 3.6
  • Minimal Celery Version: 4.3
  • Minimal Kombu Version: N/A or Unknown
  • Minimal Broker Version: N/A or Unknown
  • Minimal Result Backend Version: 6.0.4
  • Minimal OS and/or Kernel Version: N/A or Unknown
  • Minimal Broker Client Version: N/A or Unknown
  • Minimal Result Backend Client Version: N/A or Unknown

Python Packages

pip freeze Output:

amqp==2.6.0
billiard==3.6.3.0
celery==4.4.6
future==0.18.2
importlib-metadata==1.7.0
kombu==4.6.11
pkg-resources==0.0.0
pytz==2020.1
redis==3.5.3
vine==1.3.0
zipp==3.1.0

Other Dependencies

Details

Output of redis-server --version, in case it's useful:

Redis server v=6.0.4 sha=00000000:0 malloc=jemalloc-5.1.0 bits=64 build=d5d470262d47f1a0

Minimally Reproducible Test Case

Details

Basic test case below. I'm still working on converting this to an integration test for your test suite.

from celery import Celery

app = Celery('task_fail', backend='redis://localhost:6379', broker='redis://localhost:6379')

@app.task
def simple_pass():
    print("Passing")
    pass

@app.task
def simple_fail():
    print("Failing!")
    raise Exception('Fail!')

@app.task
def record_failure(*args, **kwargs):
    print(f'Fail with args={args}, kwargs={kwargs}')

if __name__ == "__main__":
    from celery import chord

    # Test 1: Passes - When the chain fails at the end, the failure logic on
    # the chord is executed.
    try:
        chain = simple_pass.si() | simple_fail.si()
        ~chord([simple_pass.si(), chain],
                simple_pass.si().on_error(record_failure.s(test="test_1")))
    except Exception:
        print("Test 1 worked")

    # Test 2: Fails - When the chain has an intermediate exception, the failure
    # logic on the chord is not executed & the client simply hangs.
    try:
        chain = simple_pass.si() | simple_fail.si() | simple_pass.si()
        ~chord([simple_pass.si(), chain],
                simple_pass.si().on_error(record_failure.s(test="test_2")))
    except Exception:
        print("Test 2 worked")

Note that the only difference between test 1 and test 2 is that test 2 add the simple_pass.si() call to the end of the chain. That seems to be enough to trigger this error.

Expected Behavior

Test 2 should behave the same way that Test 1 does. Output of Test 1, with some simplification:

[2020-07-10 15:28:52,940: INFO/MainProcess] Received task: task_fail.simple_pass[65241973-d598-4bbe-a0c8-1f86694c9f33]
[2020-07-10 15:28:52,945: WARNING/ForkPoolWorker-8] Passing
[2020-07-10 15:28:52,954: INFO/ForkPoolWorker-8] Task task_fail.simple_pass[65241973-d598-4bbe-a0c8-1f86694c9f33] succeeded in 0.008173699956387281s: None
[2020-07-10 15:28:52,967: INFO/MainProcess] Received task: task_fail.simple_pass[fc15c163-0616-4b87-94c3-2c1b225f2e0e]
[2020-07-10 15:28:52,972: WARNING/ForkPoolWorker-8] Passing
[2020-07-10 15:28:52,985: INFO/ForkPoolWorker-8] Task task_fail.simple_pass[fc15c163-0616-4b87-94c3-2c1b225f2e0e] succeeded in 0.013192899990826845s: None
[2020-07-10 15:28:52,985: INFO/MainProcess] Received task: task_fail.simple_fail[0b0a3925-7ea8-4423-8e87-3a9f00d5c967]
[2020-07-10 15:28:52,992: WARNING/ForkPoolWorker-8] Failing!
[2020-07-10 15:28:53,010: ERROR/ForkPoolWorker-8] Chord callback for '76840678-80a3-4915-96b8-04c135ecb237' raised: ChordError("Dependency 0b0a3925-7ea8-4423-8e87-3a9f00d5c967 raised Exception('Fail!',)",)
Traceback (most recent call last):
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 412, in trace_task
    R = retval = fun(*args, **kwargs)
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 704, in __protected_call__
    return self.run(*args, **kwargs)
  File "~/celery/task_fail.py", line 13, in simple_fail
    raise Exception('Fail!')
Exception: Fail!

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/redis.py", line 449, in on_chord_part_return
    callback.delay([unpack(tup, decode) for tup in resl])
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/redis.py", line 449, in <listcomp>
    callback.delay([unpack(tup, decode) for tup in resl])
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/redis.py", line 402, in _unpack_chord_result
    raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
celery.exceptions.ChordError: Dependency 0b0a3925-7ea8-4423-8e87-3a9f00d5c967 raised Exception('Fail!',)
[2020-07-10 15:28:53,022: INFO/MainProcess] Received task: task_fail.record_failure[5f264f5d-a330-4f01-9274-662474d31a8f]
[2020-07-10 15:28:53,026: ERROR/ForkPoolWorker-8] Task task_fail.simple_fail[0b0a3925-7ea8-4423-8e87-3a9f00d5c967] raised unexpected: Exception('Fail!',)
Traceback (most recent call last):
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 412, in trace_task
    R = retval = fun(*args, **kwargs)
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 704, in __protected_call__
    return self.run(*args, **kwargs)
  File "~/celery/task_fail.py", line 13, in simple_fail
    raise Exception('Fail!')
Exception: Fail![2020-07-10 15:28:53,028: WARNING/ForkPoolWorker-1] Fail with args=('bc3aeb74-68c1-40e9-9c55-be9fb7860786',), kwargs={'test': 'test_1'}
[2020-07-10 15:28:53,036: INFO/ForkPoolWorker-1] Task task_fail.record_failure[5f264f5d-a330-4f01-9274-662474d31a8f] succeeded in 0.007674199994653463s: None

The most important thing to notice here is that the record_failure task is called & logs the failure, including the ID of the failing task. I expect this behavior to occur in both cases.

Actual Behavior

The output of the worker on Test 2 is:

[2020-07-10 15:28:55,039: INFO/MainProcess] Received task: task_fail.simple_pass[5779ce6a-64af-40ea-9b26-8ff3bdad348d]
[2020-07-10 15:28:55,050: INFO/MainProcess] Received task: task_fail.simple_pass[39469dfa-401c-45f0-9314-5849f6e7ca5f]
[2020-07-10 15:28:55,051: WARNING/ForkPoolWorker-8] Passing
[2020-07-10 15:28:55,051: WARNING/ForkPoolWorker-1] Passing
[2020-07-10 15:28:55,058: INFO/ForkPoolWorker-8] Task task_fail.simple_pass[5779ce6a-64af-40ea-9b26-8ff3bdad348d] succeeded in 0.007474799989722669s: None
[2020-07-10 15:28:55,062: INFO/ForkPoolWorker-1] Task task_fail.simple_pass[39469dfa-401c-45f0-9314-5849f6e7ca5f] succeeded in 0.010612400015816092s: None
[2020-07-10 15:28:55,069: INFO/MainProcess] Received task: task_fail.simple_fail[2fead196-cfe2-4ce5-896f-303c2f9970e2]
[2020-07-10 15:28:55,073: WARNING/ForkPoolWorker-8] Failing!
[2020-07-10 15:28:55,081: ERROR/ForkPoolWorker-8] Task task_fail.simple_fail[2fead196-cfe2-4ce5-896f-303c2f9970e2] raised unexpected: Exception('Fail!',)
Traceback (most recent call last):
  File "/home/crawjor/test/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 412, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/home/crawjor/test/celery/celery.venv/lib/python3.6/site-packages/celery/app/trace.py", line 704, in __protected_call__
    return self.run(*args, **kwargs)
  File "/home/crawjor/test/celery/task_fail.py", line 13, in simple_fail
    raise Exception('Fail!')
Exception: Fail!

Then no more progress is made. Note that neither the error handler nor the callback is ever invoked, despite the chain failing (which should trigger failure handlers in the chord).

The client side also hangs waiting on redis:

File "task_fail.py", line 40, in <module>
    simple_pass.si().on_error(record_failure.s(test="test_2")))
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/canvas.py", line 475, in __invert__
    return self.apply_async().get()
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/result.py", line 237, in get
    on_message=on_message,
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 200, in wait_for_pending
    for _ in self._wait_for_pending(result, **kwargs):
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 268, in _wait_for_pending
    on_interval=on_interval):
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 55, in drain_events_until
    yield self.wait_for(p, wait, timeout=interval)
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 64, in wait_for
    wait(timeout=timeout)
  File "~/celery/celery.venv/lib/python3.6/site-packages/celery/backends/redis.py", line 161, in drain_events
    message = self._pubsub.get_message(timeout=timeout)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/client.py", line 3617, in get_message
    response = self.parse_response(block=False, timeout=timeout)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/client.py", line 3503, in parse_response
    if not block and not conn.can_read(timeout=timeout):
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/connection.py", line 734, in can_read
    return self._parser.can_read(timeout)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/connection.py", line 321, in can_read
    return self._buffer and self._buffer.can_read(timeout)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/connection.py", line 231, in can_read
    raise_on_timeout=False)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/connection.py", line 198, in _read_from_socket
    data = recv(self._sock, socket_read_size)
  File "~/celery/celery.venv/lib/python3.6/site-packages/redis/_compat.py", line 72, in recv

There are no active, revoked, scheduled, or reserved tasks, and the queue is empty:

~/celery$ celery -A task_fail inspect active
-> celery: OK
    - empty -
~/celery$ celery -A task_fail inspect scheduled
-> celery: OK
    - empty -
~/celery$ celery -A task_fail inspect revoked
-> celery: OK
    - empty -
~/celery$ celery -A task_fail inspect reserved
-> celery: OK
    - empty -

Activity

  1. msci-jordancrawford commented on Jul 13, 2020

    @msci-jordancrawford
    ContributorAuthor

    Test case added in this PR: #6226

  2. added 2 commits that reference this issue on Apr 27, 2021
    f0d7ed6
    47c0ddd
  3. added a commit that references this issue on May 7, 2021
    3a76a45
  4. added a commit that references this issue on May 8, 2021
    6dd3852
  5. added this to the 5.1.0 milestone on May 8, 2021
  6. msci-jordancrawford commented on May 10, 2021

    @msci-jordancrawford
    ContributorAuthor

    Just want to give a shout out and thank you to everyone who worked on fixing this! I know how hard it is to find time to contribute to open source, and I just can't express how grateful I am for everyone who picked up this problem and put in the work I couldn't. Thank you 1000 times - you're all the best!!!

  7. added a commit that references this issue on Aug 25, 2021
    34b870f
  8. mwodonnell commented on Jun 17, 2023

    @mwodonnell

    This is still occurring - experiencing this issue right now on Python 3.11.2 with Celery 5.3

  9. auvipy commented on Jun 18, 2023

    @auvipy
    Member

    This is still occurring - experiencing this issue right now on Python 3.11.2 with Celery 5.3

    help us to reproduce that please

  10. mwodonnell commented on Jun 18, 2023

    @mwodonnell

    help us to reproduce that please

    @auvipy Good to see you guys are still keeping up with these old threads 😅

    I think my local issue is related - but potentially not the same exact problem.

    We have quite a complex workflow that nests tasks a few levels deep. We've discovered that the on_error handler for a chord is not called if within that chord, another chord is created, and a task within the inner chords header fails.

    We are running a normal celery app with a redis backend through Docker. Python 3.11.2 and Celery 5.3

    Note that the following examples are pulled from sample code within our application. If needed I can put a more well though example together - but the use case is so straightforward I don't feel it is necessary.

    Given these tasks:

    @celery_app.task
    def generic_good_task(*args, **kwargs):
        logger.info('Generic good task called')
    
    
    @celery_app.task
    def generic_error_task(*args, **kwargs):
        logger.info('Error task called')
        raise Exception('Error task called')
    
    
    @celery_app.task
    def generic_long_task(*args, **kwargs):
        logger.info('Long task called')
        time.sleep(5)
        logger.info('Long task finished')
    

    I've created this simplified example workflow:

    def sample_main_workflow(*args, **kwargs) -> Signature:
        from mods.workflows import tasks
    
        return (
            tasks.generic_good_task.si()
            | chord(
                [
                    tasks.generic_good_task.si()
                    | chord(
                        [
                            tasks.generic_good_task.si()
                            | tasks.generic_error_task.si()
                        ],
                        tasks.generic_good_task.si()
                    )
                ],
                tasks.generic_good_task.si()
            )
            | tasks.generic_good_task.si()
        )
    

    So we have a chord which we will call outer_chord that has a header which contains another chord that we'll call inner_chord.

    The inner_chord is setup to throw an exception.

    At the top most level, we have this workflow wrapper we use to execute all of our celery workflows:

    return (
        workflow_factory(*args, **kwargs).on_error(workflow_error_handler.s(workflow.id))
        | workflow_success_handler.si(workflow.id)
    ).delay()
    

    workflow_factory can be any number of similarly defined functions as I showed with sample_main_workflow - it is simple a function that returns a chain/group/chord, whatever a given workflow wants to execute - in this case it is our sample problematic workflow.

    Basically, the workflow_success_handler will just print a line indicating the success handler was called, similarly the workflow_error_handler will print a line indicating it was called.

    When I execute this workflow I expect the workflow_error_handler to be called, however instead I get two instances of the raised exception printed out to the celery logs.

    The first is the exception itself which I expect - the second is a ChordError. What I believe is happening is the inner_chord I defined earlier is capturing the error but has no error handler of its own to work with. And for some reason, when it throws it's error - the error handler I do have defined at the top level is not catching it as an error. Everything works as expected if we remove the outer_chord and only execute the inner_chord.

    Let me know if this is similar enough to this issue to consider re-opening. A senior dev and myself have been chasing this issue around our code base for a week now so if there's a known fix - we are very open to hearing it.

    It is worth noting we originally had our chords defined as chains and groups - however, this caused another/different issue where after each item of the group in question finished executing, it would kick off a new instance of the task that came after the group. We had 5 workflows in the group so we ended up with 5 instances of the workflow being executed. I tried to create a simple use case of this as well but have not been able to properly reproduce it outside of our app. All I can say for certain is that approach is not viable in our context.

  11. mwodonnell commented on Jun 18, 2023

    @mwodonnell

    here is a copy of the logs when I run the above example:

    [2023-06-18 20:17:06,033: ERROR/ForkPoolWorker-7] Chord '24e551a7-abd7-4967-9c66-2c9550e576a2' raised: ChordError("Dependency 8dd88f14-95d4-4d85-bc0b-9ea49ce2633c raised Exception('Error task called')")
    Traceback (most recent call last):
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 477, in trace_task
        R = retval = fun(*args, **kwargs)
                     ^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 760, in __protected_call__
        return self.run(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/git/hr-outcomes-service/mods/workflows/tasks.py", line 106, in generic_error_task
        raise Exception('Error task called')
    Exception: Error task called
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 528, in on_chord_part_return
        resl = [unpack(tup, decode) for tup in resl]
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 528, in <listcomp>
        resl = [unpack(tup, decode) for tup in resl]
                ^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 434, in _unpack_chord_result
        raise ChordError(f'Dependency {tid} raised {retval!r}')
    celery.exceptions.ChordError: Dependency 8dd88f14-95d4-4d85-bc0b-9ea49ce2633c raised Exception('Error task called')
    [2023-06-18 20:17:06,035: ERROR/ForkPoolWorker-7] Task mods.workflows.tasks.generic_error_task[8dd88f14-95d4-4d85-bc0b-9ea49ce2633c] raised unexpected: Exception('Error task called')
    Traceback (most recent call last):
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 477, in trace_task
        R = retval = fun(*args, **kwargs)
                     ^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 760, in __protected_call__
        return self.run(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/git/hr-outcomes-service/mods/workflows/tasks.py", line 106, in generic_error_task
        raise Exception('Error task called')
    Exception: Error task called
    

    And Here is what happens if I remove the outer_chord so the example workflow looks like such:

        return (
            tasks.generic_good_task.si()
            | chord(
                [
                    tasks.generic_good_task.si()
                    | tasks.generic_error_task.si()
                ],
                tasks.generic_good_task.si()
            )
            | tasks.generic_good_task.si()
        )
    

    These are those logs:

        2023-06-18 20:19:02,402: ERROR/ForkPoolWorker-7] Chord 'a03639a3-3ba1-49c5-b1cb-a644486c51bd' raised: ChordError("Dependency 6341b34f-7917-4cba-9f40-5c4d8fb22f7b raised Exception('Error task called')")
    Traceback (most recent call last):
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 477, in trace_task
        R = retval = fun(*args, **kwargs)
                     ^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/app/trace.py", line 760, in __protected_call__
        return self.run(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/git/hr-outcomes-service/mods/workflows/tasks.py", line 106, in generic_error_task
        raise Exception('Error task called')
    Exception: Error task called
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 528, in on_chord_part_return
        resl = [unpack(tup, decode) for tup in resl]
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 528, in <listcomp>
        resl = [unpack(tup, decode) for tup in resl]
                ^^^^^^^^^^^^^^^^^^^
      File "/Users/mjo/.virtualenvs/ff-hr/lib/python3.11/site-packages/celery/backends/redis.py", line 434, in _unpack_chord_result
        raise ChordError(f'Dependency {tid} raised {retval!r}')
    celery.exceptions.ChordError: Dependency 6341b34f-7917-4cba-9f40-5c4d8fb22f7b raised Exception('Error task called')
    [2023-06-18 20:19:02,403: WARNING/ForkPoolWorker-7] -----------------------------------------------------------------------------------> Error handler called
    ERROR: Workflow 212:sample failed with error
    [2023-06-18 20:19:02,417: ERROR/ForkPoolWorker-7] Workflow 212:sample failed with error
    ...
    

    There's a bunch more exception/traceback stuff showing in the logs - but the important piece is we see the line:
    [2023-06-18 20:19:02,403: WARNING/ForkPoolWorker-7] -----------------------------------------------------------------------------------> Error handler called

    Proving our error handler has been called as expected. This is the behavior I expect my original example to follow.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions