Skip to content

the chord function work not well with just one header task #3597

Closed

Description

@max1314

Steps to reproduce

@task
def add(x, y):
    return x + y
@task
def tsum(numbers):
    return sum(numbers)

ts = chord([add.s(1,1)])(tsum.s())

unexpected behavior

will raise error:  ValueError: AsyncResult requires valid id, not <type 'NoneType'>
## Actual behavior
File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 1200, in __call__
    return self.apply_async((), {'body': body} if body else {}, **options)
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 1246, in apply_async
    args, kwargs, **options)
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 567, in apply_async
    dict(self.options, **options) if options else self.options))
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 586, in run
    task_id, group_id, chord,
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 679, in prepare_steps
    res = task.freeze(root_id=root_id)
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/canvas.py", line 284, in freeze
    return self.AsyncResult(tid)
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/app/task.py", line 747, in AsyncResult
    task_name=self.name, **kwargs)
  File "/home/meron/workspace/xiaolusys/ve10/local/lib/python2.7/site-packages/celery/result.py", line 90, in __init__
    'AsyncResult requires valid id, not {0}'.format(type(id)))

Activity

  1. Zatte commented on Nov 17, 2016

    @Zatte

    I've also experienced this issues (or at least a similar one through implicit chord transformation).

    When only 1 element is added to a chord it doesn't wrap the single value in a list.

    from celery import Celery, group
    app = Celery('tasks', broker='redis://', backend='redis://')
    
    @app.task
    def add(x, y):
        return [x + y]
    
    @app.task
    def callback(*ags):
        print ags
    
    job_arr = group(
        [add.s(1,2), add.s(10,20 ), add.s(100, 200)]
    ) | callback.s("Arrary")
    
    job_single = group(
        [add.s(1,2)]
    ) | callback.s("Single")
    
    job_arr.apply()
    job_single.apply()
    

    =>

    # Printed by callback
    ([[3], [30], [300]], 'Arrary')
    ([3], 'Single')
    

    Note that the first element is [3] and not the expected [[3]]

    Verified with both Redis and RabbitMQ brooker but only Redis result backend.

    Environment
    Python 2.7.6
    Celery 4.0.0
    Redis 3.2.5

  2. ggstuart commented on Nov 23, 2016

    @ggstuart

    I get this a lot. Is there a work around? My solution is to check if there is only one element and in that case create a chain instead. The argument passed into the next task in the chain (or following the chord) is then converted to a list.

    # entry point
    @app.task
    def task1(arg):
        # schedule loads of tasks, or just one - depends on input
        mygroup = group(task2.s(a) for a in arg)
        if len(mygroup) == 1:
            return chain(mygroup, task3.s('there was only one')).delay()
        else:
            return chord(mygroup)(task3.s('there were more than one'))
    
    @app.task
    def task2(arg):
        # prepare data for processing
        return arg
    
    # this task expects a list
    @app.task
    def task3(arg1, arg2):
        print(arg2)
        if not isinstance(arg1, list):
            arg1 = [arg1]
        # process arg1 list
    
  3. Zatte commented on Nov 23, 2016

    @Zatte

    Did some quick digging; It seems the issues was introduced with
    867a3aa
    as a fix to
    #3323

    https://github.com/celery/celery/blob/master/celery/canvas.py#L388-L391

    Where single element chords are turned into a simple chain. I'm not sure the rationale for the patch still holds with this issue in mind but I would leave it for the author to answer: @ask any comments in regards to the added complexity with dynamic chord sizes?

  4. mattjegan commented on Feb 14, 2017

    @mattjegan

    Is there any progress on this?

  5. a-pertsev commented on Apr 9, 2017

    @a-pertsev

    +1 for fix, the current behaviour is totally broken, chord([A], B) is not equals to A | B
    =/

  6. canassa commented on Apr 14, 2017

    @canassa

    I must also add that this issue also affects the newly introduced add_to_chord method

  7. rholloway commented on May 30, 2017

    @rholloway

    Also affected here. My solution was to check in the chord callback if results is a list or not and make it one if needed, but again that only solves one of the issues this leads to.

  8. OndrejIT commented on Jun 3, 2017

    @OndrejIT

    +1 for fix.

    Hotfix:
    if len(tasks) == 1: tasks.append(blank_task.s())

  9. xeor commented on Nov 7, 2017

    @xeor

    This is very annoying indeed, and have been biting me randomly the last couple of days..
    Is everyone using the @OndrejIT hotfix? Is there a better way of doing this?

  10. calvinwyoung commented on Nov 7, 2017

    @calvinwyoung

    @xeor I've worked around this by implementing a custom chord helper. It's ugly and I'd prefer not to use it, but it's worked fine in production for almost a year now. Hope this helps someone else!

    import celery as _celery
    
    
    def chord(header, callback):
        """A smart wrapper around `celery.chord` that handles several edge cases.
    
        There are a two subtle gotchas that happen with the default implementation
        of `celery.chord`:
    
            - If the header is empty, the callback never gets executed. This wrapper
              ensures that the callback *does* get executed.
            - If the header has only one task, then celery throws a `ValueError`:
              https://github.com/celery/celery/issues/3597
    
        Args:
            header (List[Signature]): A list of task `Signature` objects.
            callback (Signature): The `Signature` of a task that should be executed
                after all the tasks in the header.
        """
        if not header:
            if callback:
                callback.delay()
        elif len(header) == 1:
            if callback:
                _celery.chain(header[0], callback).delay()
            else:
                header[0].delay()
        else:
            if callback:
                _celery.chord(header)(callback)
            else:
                _celery.group(header).delay()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions