Skip to content

link_error is not executed when task fails in chord header #3317

Closed

Description

@tsudmi

I created a test case to reproduce the problem I suffer from in more complex workflow. I expect link_error of the chord callback to be executed every time an error occurs in chord header. In provided example chord header is a group, which consists of one chain. However, in my implementation group can contain multiple chains and/or tasks.

My celery version is 3.1.23.

test.py:

from celery import Celery, chain, group, chord

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

@app.task
def task1():
    print("Task 1 executed")

@app.task
def error_task():
    raise Exception("Mocked exception")

@app.task
def callback_task():
    print("Callback executed")


@app.task
def link_error_task(*args, **kwargs):
    print("Link error executed")


@app.task
def link_task():
    print("Link executed")


def main():
    c1 = chain(error_task.si(), task1.si())
    head = group([c1])
    callback = callback_task.si().set(link=[link_task], link_error=[link_error_task.s()])

    chord(head, callback).delay()

I expect following things to happen:

  1. Celery worker starts executing tasks in chain c1.

  2. After reaching exception in error_task celery stops executing chain c1.

  3. The error from chord header is propagated to the chord callback. As a result, callback execution will be marked as failed and finally link_error of the callback will be executed.

To execute this code I run following commands:

  • Terminal 1:

    $ celery -A test worker --app=test:app --loglevel=info
    
  • Terminal 2:

    $ python
    Python 2.7.12 (default, Jun 29 2016, 14:05:02)
    [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import test
    >>> test.main()
    

The celery output will be following:

[2016-07-14 21:39:36,186: INFO/MainProcess] Received task: test.error_task[b9e7d006-43f9-4e9d-8391-ada74fb3bc4e]
[2016-07-14 21:39:36,193: ERROR/MainProcess] Task test.error_task[b9e7d006-43f9-4e9d-8391-ada74fb3bc4e] raised unexpected: Exception('Mocked exception',)
Traceback (most recent call last):
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/private/tmp/test.py", line 11, in error_task
    raise Exception("Mocked exception")
Exception: Mocked exception

As we can see link_error was not executed. However, if we remove last task in c1, the program will work as expected:

    def main():
        c1 = chain(error_task.si()) # last task removed
        head = group([c1])
        callback = callback_task.si().set(link=[link_task], link_error=[link_error_task.s()])

        chord(head, callback).delay()

The output will be following:

[2016-07-14 21:42:47,177: INFO/MainProcess] Received task: test.error_task[96d5cb6c-b059-452a-b8cf-73e54f495976]
[2016-07-14 21:42:47,185: ERROR/Worker-4] Chord 'b3f57200-a52f-426f-9814-202576ae3538' raised: "Dependency 96d5cb6c-b059-452a-b8cf-73e54f495976 raised Exception('Mocked exception',)"
Traceback (most recent call last):
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/backends/base.py", line 580, in on_chord_part_return
    ret = j(timeout=3.0, propagate=propagate)
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/result.py", line 691, in join_native
    raise value
Exception: Mocked exception
[2016-07-14 21:42:47,207: INFO/MainProcess] Received task: test.link_error_task[c3c4408b-17fc-4efa-b502-c7cdf3862240]
[2016-07-14 21:42:47,209: WARNING/Worker-3] Link error executed
[2016-07-14 21:42:47,210: ERROR/MainProcess] Task test.error_task[96d5cb6c-b059-452a-b8cf-73e54f495976] raised unexpected: Exception('Mocked exception',)
Traceback (most recent call last):
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/private/tmp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/private/tmp/test.py", line 11, in error_task
    raise Exception("Mocked exception")
Exception: Mocked exception
[2016-07-14 21:42:47,214: INFO/MainProcess] Task test.link_error_task[c3c4408b-17fc-4efa-b502-c7cdf3862240] succeeded in 0.00591249897843s: None

To conclude, the problem seems to be with the chain c1. If there is at least one task after the task, which triggers an error, the link_error of the callback will not be executed.

Activity

  1. ask commented on Jul 19, 2016

    @ask
    Contributor

    Please try using the Celery development version (pip install -U --pre celery), I think most of these are fixed there

  2. AmbientLighter commented on Jul 20, 2016

    @AmbientLighter
    Contributor

    Hi, I can confirm this issue with latest Celery release (v4.0.0rc3)

    Case 1

    When I run this code without modifications, it fails with kombu.exceptions.EncodeError

    def main():
        c1 = chain(error_task.si(), task1.si())
        head = group([c1])
        callback = callback_task.si().set(link=[link_task], link_error=[link_error_task.s()])
    
        chord(head, callback).delay()
    

    Error:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "test.py", line 33, in main
        chord(head, callback).delay()
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 194, in delay
        return self.apply_async(partial_args, partial_kwargs)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 983, in apply_async
        return self.run(tasks, body, args, task_id=task_id, **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 1025, in run
        result=results)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/backends/redis.py", line 246, in apply_chord
        return header(*partial_args, **options or {})
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 847, in __call__
        return self.apply_async(partial_args, **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 805, in apply_async
        results = list(self._apply_tasks(tasks, producer, app, p, **options))
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 769, in _apply_tasks
        **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 447, in apply_async
        dict(self.options, **options) if options else self.options))
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 472, in run
        chain=tasks if not use_link else None, **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/canvas.py", line 278, in apply_async
        return _apply(args, kwargs, **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/task.py", line 521, in apply_async
        **options
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/base.py", line 678, in send_task
        amqp.send_task_message(P, name, message, **options)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/amqp.py", line 551, in send_task_message
        **properties
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 174, in publish
        compression, headers)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 256, in _prepare
        body) = dumps(body, serializer=serializer)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/serialization.py", line 165, in dumps
        payload = encoder(data)
      File "/usr/lib/python2.7/contextlib.py", line 35, in __exit__
        self.gen.throw(type, value, traceback)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/serialization.py", line 60, in _reraise_errors
        reraise(wrapper, wrapper(exc), sys.exc_info()[2])
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/serialization.py", line 56, in _reraise_errors
        yield
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/serialization.py", line 165, in dumps
        payload = encoder(data)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/utils/json.py", line 64, in dumps
        return _dumps(s, cls=cls, **dict(default_kwargs, **kwargs))
      File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
        sort_keys=sort_keys, **kw).encode(obj)
      File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
        return _iterencode(o, 0)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/utils/json.py", line 59, in default
        return super(JSONEncoder, self).default(o)
      File "/usr/lib/python2.7/json/encoder.py", line 184, in default
        raise TypeError(repr(o) + " is not JSON serializable")
    kombu.exceptions.EncodeError: <@task: test.link_task of test:0x7f02c71076d0> is not JSON serializable
    

    Case 2

    When I use subtask for callback link and link_error, it fails with initial exception, link_error is not called:
    Code:

    def main():
        c1 = chain(error_task.si(), task1.si())
        head = group([c1])
        callback = callback_task.si().set(link=link_task.s(), link_error=link_error_task.s())
    
        chord(head, callback).delay()
    

    Error:

    Task test.error_task[8baf1404-6d7a-40ca-8784-74f8047edec9] raised unexpected: ValueError('Mocked exception',)
    Traceback (most recent call last):
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/trace.py", line 358, in trace_task
        R = retval = fun(*args, **kwargs)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/trace.py", line 609, in __protected_call__
        return self.run(*args, **kwargs)
      File "/home/victor/nc/test.py", line 11, in error_task
        raise ValueError("Mocked exception")
    ValueError: Mocked exception
    

    Case 3

    And finally, when I skip task1.si(), it fails with ChordError and then Celery worker dies. It's strange, but when I try to restart Celery worker, it dies again and again. And the only way to restart worker is to purge queue.

    Code:

    def main():
        c1 = chain(error_task.si())
        head = group([c1])
        callback = callback_task.si().set(link=link_task.s(), link_error=link_error_task.s())
    
        chord(head, callback).delay()
    

    Error:

    [2016-07-20 10:33:54,260: ERROR/PoolWorker-4] Chord callback for u'29c63099-2375-407e-84be-df602278ddbb' raised: ChordError(u"Dependency 98bb66ba-2cc0-4098-a385-51a2a91ae26e raised ValueError(u'Mocked exception',)",)
    Traceback (most recent call last):
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/backends/redis.py", line 281, in on_chord_part_return
        callback.delay([unpack(tup, decode) for tup in resl])
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/backends/redis.py", line 239, in _unpack_chord_result
        raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
    ChordError: Dependency 98bb66ba-2cc0-4098-a385-51a2a91ae26e raised ValueError(u'Mocked exception',)
    [2016-07-20 10:33:54,276: ERROR/MainProcess] Received unregistered task of type u'chord_size'.
    The message has been ignored and discarded.
    
    Did you remember to import the module containing this task?
    Or maybe you are using relative imports?
    Please see http://bit.ly/gLye1c for more information.
    
    The full contents of the message body was:
    '{"expires": null, "utc": true, "args": ["62fcc31d-6a21-44e6-8712-ef95d04d7180"], "chord": null, "callbacks": null, "errbacks": null, "taskset": "b048a5a3-3c7e-4981-83d4-18e156ccd22d", "id": "6ffbcc89-93ef-4709-ace9-fa9a019baf22", "retries": 0, "task": "chord_size", "group": "b048a5a3-3c7e-4981-83d4-18e156ccd22d", "timelimit": [null, null], "eta": null, "kwargs": {}}' (368b)
    Traceback (most recent call last):
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 548, in on_task_received
        strategy = strategies[type_]
    KeyError: u'chord_size'
    [2016-07-20 10:33:54,277: CRITICAL/MainProcess] Unrecoverable error: TypeError("'NoneType' object has no attribute '__getitem__'",)
    Traceback (most recent call last):
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 201, in start
        self.blueprint.start(self)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/bootsteps.py", line 125, in start
        step.start(parent)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/bootsteps.py", line 376, in start
        return self.obj.start()
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 315, in start
        blueprint.start(self)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/bootsteps.py", line 125, in start
        step.start(parent)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 582, in start
        c.loop(*c.loop_args())
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/loops.py", line 90, in asynloop
        next(loop)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/async/hub.py", line 347, in create_loop
        cb(*cbargs)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/transport/redis.py", line 1042, in on_readable
        self._deliver(*item)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 967, in _deliver
        callback(message)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 623, in _callback
        return callback(message)
      File "/tmp/venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 630, in _receive_callback
        return on_m(message) if on_m else self.receive(decoded, message)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 550, in on_task_received
        return on_unknown_task(None, message, exc)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 489, in on_unknown_task
        id_, name = body['id'], body['task']
    TypeError: 'NoneType' object has no attribute '__getitem__'
    [2016-07-20 10:33:54,283: ERROR/PoolWorker-4] Task test.error_task[98bb66ba-2cc0-4098-a385-51a2a91ae26e] raised unexpected: ValueError('Mocked exception',)
    Traceback (most recent call last):
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/trace.py", line 358, in trace_task
        R = retval = fun(*args, **kwargs)
      File "/tmp/venv/local/lib/python2.7/site-packages/celery/app/trace.py", line 609, in __protected_call__
        return self.run(*args, **kwargs)
      File "/home/victor/nc/test.py", line 11, in error_task
        raise ValueError("Mocked exception")
    ValueError: Mocked exception
    [2016-07-20 10:33:55,287: WARNING/MainProcess] Restoring 1 unacknowledged message(s)
    
  3. rholloway commented on May 30, 2017

    @rholloway

    I seem to be having similar issue on 4.0.2. If I look at the header task request object I can see link_error mentions the chord error callback, but it's never executed no matter what I try.

    @task(bind=True)
    def my_on_error(self):
        print "In my error handler"
    
    @task(bind=True)
    def my_callback(self):
        print "my callback"
    
    @task(bind=True)
    def my_task(self):
        print self.request.link_error  # will mention my_on_error
        raise Exception("can raise whatever I want, the chord on_error will never be executed")
    
    c = chord([my_task.s(), my_task.s()])(my_callback.s().on_error(my_on_error.s()))
    
  4. Wesley-Li commented on Jul 10, 2017

    @Wesley-Li

    I hit the same problem, is this solved?

  5. AmbientLighter commented on Jul 10, 2017

    @AmbientLighter
    Contributor

    I hit the same problem, is this solved?

    Nope, it's still actual.

  6. Wesley-Li commented on Jul 10, 2017

    @Wesley-Li

    Chord/link_error is really terrible. Sometimes not run..., sometimes always run...sometimes run but still raises exception...

  7. AmbientLighter commented on Jul 10, 2017

    @AmbientLighter
    Contributor

    @Wesley-Li Yeah, that's true. You may find more info on related issue #3709, but I don't use chord until this feature is fixed.

  8. xeor commented on Nov 13, 2017

    @xeor

    @AmbientLighter This error is really annoying! Did you find a viable workaround not using chords? Or are you missing some functionality till this is solved?

  9. AmbientLighter commented on Nov 13, 2017

    @AmbientLighter
    Contributor

    I haven't found any viable workaround yet, I'm not using chords at all now :(

  10. AmbientLighter commented on Nov 13, 2017

    @AmbientLighter
    Contributor

    @xeor You may vote up for this issue so that it becomes more visible for the core developers.

  11. xeor commented on Nov 13, 2017

    @xeor

    I have subscribed to a bunch of related issues.. Is there a separate place to vote for then? Can't find any.

    I'm looking into a cheap workaround to this. Looks like a group don't have this problem. So just using them, and a side-task that checks and reports on the group-result might work till it is fixed.. Very ugly tho. Not even sure if that's going to work as I expect :(

  12. xeor commented on Nov 13, 2017

    @xeor

    naah... That didn't do it. Groups in a chain won't execute in order, and using link on a group raises an error telling me to use chords. Commenting out the part that tells me to use chords only results in the link not being executed at all.
    Executing a new task inside the first group using .join() blocks, so not something I want it to do (same as with .get()).

    So, basically, using time-limits (and probably other hooks that raises an exception), is broken if you use chords. I guess there will be no timelimits on my API for a while then... (don't tell them) :p

  13. AmbientLighter commented on Nov 13, 2017

    @AmbientLighter
    Contributor

    I have subscribed to a bunch of related issues.. Is there a separate place to vote for then? Can't find any.

    @xeor There's an issue which has got most comments so far:
    #3709

    There's some workaround provided:
    #3709 (comment)

    I haven't personally looked into it yet, but it may be useful too.

  14. auvipy commented on Dec 19, 2017

    @auvipy
    Member

    lets try the master and report issues on celery/kombu#817

  15. locked and limited conversation to collaborators on Dec 19, 2017
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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions