Skip to content

group and chord: subtasks are not executed until entire generator is consumed #3021

Closed

Description

@chadrik

When passing a generator to group or chord, sub-tasks are not submitted to the broker for execution until the entire generator is consumed. The expected result is that subtasks are submitted during iteration, as soon as they are visited.

Here is the test code I'm using:

from celery import Celery, group
from celery.utils.log import get_task_logger

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

logger = get_task_logger(__name__)

def longyield():
    import time
    for i in xrange(5):
        time.sleep(2)
        print "yielding", i
        yield add.s(i, i)

@app.task
def add(x, y):
    logger.info("adding {} + {}".format(x, y))
    return x + y

def itertest():
    it = longyield()
    g = group(it)
    result = g.delay()
    print result.get()

I'm testing with 4.0rc1.

Activity

  1. sysradium commented on Jan 24, 2016

    @sysradium

    @chadrik Your example is really strange. Why do you need a group when you expect synchronous behaviour?

    Anyway, I think you are wrong. First you create a signature of a task which you call later which in fact is a group which consists of add subtasks. It is created yielding from a logyield in a for loop.

    Later after the group is created and saved to g you call it and add subtasks are executed in parallel.

    What would work as you want is this:

    result = [add.delay(i, i).get() for i in longyield()]
    print result
    

    But looks pointless.

  2. chadrik commented on Jan 24, 2016

    @chadrik
    Author

    @syradium Hopefully my example is not pointless because it is taken almost directly from the celery docs:

    from celery import group
    res = group(add.s(i, i) for i in xrange(10))()
    res.get(timeout=1)

    I used group.delay() but that doesn't make a difference. By extending the time it takes to yield results (e.g. longyield vs xrange) I'm trying to make apparent that group is consuming the entire generator before submitting subtasks for execution.

    Why do you need a group when you expect synchronous behaviour?

    I don't understand your question. I want all sub-tasks executed in parallel. I thought that was the point of the group primitive.

    I'm also not the only person who has had this problem. I found this old reference from the celery-users google group, but the suggestions from Ask seemed out of date for the 3.1.x codebase, and the ones that I tried did not help. I was surprised to find this issue has not been address in 4.x.

    result = [add.delay(i, i).get() for i in longyield()]
    print result

    Yes, that's the workaround I'm using for now, but the point is that I want to use the canvas primitives so that I can combine them into complex topologies.

  3. sysradium commented on Jan 24, 2016

    @sysradium

    @chadrik

    @syradium Hopefully my example is not pointless because it is taken almost directly from the celery docs.

    Yes and docs are correct. Your example is a little bit different.

    Look, this:

    group(add.s(i, i) for i in xrange(10)
    

    Is equivalent of:

    group(add.s(0, 0), add.s(1, 1), ...)
    

    Right? add.s(0, 0) does not start/execute a task. It only creates a subtask. You can later call it with .delay()/apply_async():

    foo = add.s(0, 0)
    result = foo.delay().get()
    

    .. or by running a group. This is why your tasks start running only after your generator stops.

  4. chadrik commented on Jan 25, 2016

    @chadrik
    Author

    @syradium I got so annoyed trying to prove to you that you don't know what you're talking about that I just went ahead and fixed the problem.

    The issue is that there's a test for empty tasks which forces the entire generator to be consumed before it's really needed (note the line if not self.tasks):

      File "/Users/chad/python/celery_walk_task.py", line 79, in itertest
        result = g()
      File "/Users/chad/dev/celery4.venv/lib/python2.7/site-packages/celery/canvas.py", line 807, in __call__
        return self.apply_async(partial_args, **options)
      File "/Users/chad/dev/celery4.venv/lib/python2.7/site-packages/celery/canvas.py", line 760, in apply_async
        if not self.tasks:
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserList.py", line 30, in __len__
        def __len__(self): return len(self.data)
      File "/Users/chad/dev/celery4.venv/lib/python2.7/site-packages/celery/utils/functional.py", line 353, in data
        self.__consumed.extend(list(self.__it))
      File "/Users/chad/python/celery_walk_task.py", line 77, in <genexpr>
        g = group(add.s(i, i) for i in longyield())
      File "/Users/chad/python/celery_walk_task.py", line 68, in longyield
        raise
    

    The tasks are held in a _regen class, which caches the generator so that it can be consumed more than once, like a list (it is in fact a sublcass of UserList and list). So, to get around the expansion of the generator just for this nonzero test, I added an optimized __nonzero__ method:

        def __nonzero__(self):
            if len(self.__consumed):
                return True
            try:
                # consume just one item
                self.__consumed.append(next(self.__it))
            except StopIteration:
                return False
            else:
                return True

    By adding this, I was able to get past the nonzero test without consuming the entire generator, and the rest of the code handled the generator appropriately, submitting each task for async execution as it was yielded from the generator.

    I'm going to test this out a bit and submit a pull request. Thanks for the motivation.

  5. sysradium commented on Jan 25, 2016

    @sysradium

    @chadrik wow, take it easy.

    I understand what are you talking about but wasn't sure we are on the same page. To me these two lines were identical (in celery terms):

    group(add.s(i, i) for i in range(10))
    group([add.s(i, i) for i in range(10)])
    

    Be default I assumed that celery builds a list of whatever you give to it. Because in order to properly schedule a group of tasks it needs the whole group signature and not a generator which in fact can be infinite have side-effects and so on.

    I do not see a use case for what you want to introduce. If each generator iteration is a long task and you want to start task in group as soon as possible, then why not to move this out to another task, make chain/chord, etc ... I am not sure if this is absolutely safe. Will it correctly work with get(propagate=...) if an exception is raised during yielding.

    Anyway, that's just my opinion. If community agree on that then ok.

  6. detzgk commented on Jan 29, 2016

    @detzgk

    I think I understand the issue because I think it's one I've encountered. I'm a celery newbie so hopefully I won't mangle any terms too badly.

    Let's say you have task A that generates chord B with callback C. A retrieves a few million rows from a database, does something to chunks of them in B and then merges the results in C. You're expecting the results from A to be very large but the results from B should be much smaller.

    It would be ideal not to force A to keep its data around until B has been created. If there were a way for group/chord to start executing its tasks immediately, task A would only need to remember the GID of its subtasks (which could each be working on large chunks of data) instead of its entire data set. If A takes a long time to run, you could be losing the possibility of having a large amount of the work done by the time you finish generating B.

    This would require some kind of call to mark B as "fully submitted for processing". From what I've seen of Redis as a broker (the only one I've used so far), it's using the native increment/decrement functions to check when the task is done. In this case you'd need to use those functions but also check that there wasn't potentially new work incoming for that chord. Just because I've completed 5/5 subtasks doesn't meant that A is done submitting tasks unless it says so.

    It's certainly not trivial to implement.

  7. chadrik commented on Jan 31, 2016

    @chadrik
    Author

    Yep, you've nailed it.

    I've explored this a bit more deeply and I've modified the celery code to work as desired for simple groups and it's almost there for chords.

    The way that chords in celery+redis work under the hood is this:

    1. the number of sub-tasks in the group is computed and stored on the chord
    2. the chord is stored on each group subtask
    3. in the redis backend, when each subtask in the group completes, the number of completed subtasks is checked. if the number complete equals the computed group size, then the chord callback is executed (except not quite. there's a little wrinkle which I'll explain later).

    To put it another way, each group subtask carries a copy of the callback subtask forward, but only one -- the last to complete -- will execute it.

    And, of course, the first step described above, computing the number of tasks, necessarily means consuming the complete generator of subtasks, which is what I'm hoping to avoid.

    The relevant backend code is here:

        def on_chord_part_return(self, request, state, result, propagate=None):
            app = self.app
            tid, gid = request.id, request.group
            if not gid or not tid:
                return
    
            client = self.client
            jkey = self.get_key_for_group(gid, '.j')
            tkey = self.get_key_for_group(gid, '.t')
            result = self.encode_result(result, state)
            with client.pipeline() as pipe:
                _, readycount, totaldiff, _, _ = pipe                           \
                    .rpush(jkey, self.encode([1, tid, state, result]))          \
                    .llen(jkey)                                                 \
                    .get(tkey)                                                  \
                    .expire(jkey, 86400)                                        \
                    .expire(tkey, 86400)                                        \
                    .execute()
    
            totaldiff = int(totaldiff or 0)
    
            try:
                callback = maybe_signature(request.chord, app=app)
                total = callback['chord_size'] + totaldiff
                if readycount == total:
                    decode, unpack = self.decode, self._unpack_chord_result
                    with client.pipeline() as pipe:
                        resl, _, _ = pipe               \
                            .lrange(jkey, 0, total)     \
                            .delete(jkey)               \
                            .delete(tkey)               \
                            .execute()
                    try:
                        callback.delay([unpack(tup, decode) for tup in resl])
                    except Exception as exc:
                        error('Chord callback for %r raised: %r',
                              request.group, exc, exc_info=1)
                        return self.chord_error_from_stack(
                            callback,
                            ChordError('Callback error: {0!r}'.format(exc)),
                        )
            except ChordError as exc:
                error('Chord %r raised: %r', request.group, exc, exc_info=1)
                return self.chord_error_from_stack(callback, exc)
            except Exception as exc:
                error('Chord %r raised: %r', request.group, exc, exc_info=1)
                return self.chord_error_from_stack(
                    callback,
                    ChordError('Join error: {0!r}'.format(exc)),
                )

    Looking at this, it doesn't seem that it would be that difficult to add a new group key along the lines of .t or .j which holds the total number of tasks, which is null (-1) until set by A when it submits the final task from group B.

    The only thing I don't understand yet is the totaldiff offset, e.g.

                total = callback['chord_size'] + totaldiff
                if readycount == total:
                    ...

    Why can't we compare readycount directly to callback['chord_size']? Why the need for the offset? I'll have to do some more digging.

  8. chadrik commented on Jan 31, 2016

    @chadrik
    Author

    Got it working without too much hassle. I'll post a pull request soon.

  9. prydie commented on May 27, 2016

    @prydie

    This issue is currently causing me a lot of problems also.

    I see that @chadrik's PR (#3043) has unfortunately not landed as of yet and he is no longer working on it at this point. I don't suppose any of the maintainers are able to pick up @chadrik's PR and get it ready for merging? I'm happy to help out with any testing, however, I'm not in a position to complete his work myself, unfortunately.

    My use-case

    I have three tasks:

    • A: Periodic task for the sending of weekly messages to customers
    • B: Task which does all the data crunching to generate each message and calls out to an external API to deliver the message
    • C: Callback for chord of task Bs to report on sending job

    To me this seems like an obvious use-case for chord, however, the amount of memory used by task A in generating the chord header is in the order of gigabytes.

  10. added this to the v4.0 milestone on Jun 29, 2016
  11. modified the milestones: v4.1, v4.0 on Jul 8, 2016
  12. thedrow commented on Jul 11, 2017

    @thedrow
    Contributor

    We'll try to get this on 4.1.

  13. RyanNaughton commented on Sep 15, 2017

    @RyanNaughton

    Hi, any update on this issue?

  14. thedrow commented on Sep 16, 2017

    @thedrow
    Contributor

    No unfortunately none of us had time to work on this so far.

  15. 4 remaining items

  16. added this to the v4.3 milestone on May 27, 2018
  17. modified the milestones: v4.3, v5.0.0 on Jan 8, 2019
  18. modified the milestones: v5.0.0, 4.7 on Jun 26, 2019
  19. modified the milestones: 4.7, 4.6 on Aug 23, 2019
  20. modified the milestones: 4.6, 4.4.x on Dec 16, 2019
  21. modified the milestones: 4.4.x, 5.0.5 on Dec 9, 2020
  22. thedrow commented on Mar 4, 2021

    @thedrow
    Contributor

    This is finally fixed and will appear in 5.1.

  23. chadrik commented on Mar 4, 2021

    @chadrik
    Author
  24. RyanNaughton commented on Mar 4, 2021

    @RyanNaughton

    Awesome!

    @pigrabbit87 Remember how this always used mess up our jobs! Flash from the past!

  25. thedrow commented on Mar 10, 2021

    @thedrow
    Contributor

    I'm sorry to hear that it happened :) It must have been frustrating.

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