Debian Codegraph @

docs/userguide/canvas.rst

raw
1 .. _guide-canvas:
2
3 ==============================
4 Canvas: Designing Work-flows
5 ==============================
6
7 .. contents::
8 :local:
9 :depth: 2
10
11 .. _canvas-subtasks:
12
13 .. _canvas-signatures:
14
15 Signatures
16 ==========
17
18 .. versionadded:: 2.0
19
20 You just learned how to call a task using the tasks ``delay`` method
21 in the :ref:`calling <guide-calling>` guide, and this is often all you need,
22 but sometimes you may want to pass the signature of a task invocation to
23 another process or as an argument to another function.
24
25 A :func:`~celery.signature` wraps the arguments, keyword arguments, and execution options
26 of a single task invocation in a way such that it can be passed to functions
27 or even serialized and sent across the wire.
28
29 - You can create a signature for the ``add`` task using its name like this:
30
31 .. code-block:: pycon
32
33 >>> from celery import signature
34 >>> signature('tasks.add', args=(2, 2), countdown=10)
35 tasks.add(2, 2)
36
37 This task has a signature of arity 2 (two arguments): ``(2, 2)``,
38 and sets the countdown execution option to 10.
39
40 - or you can create one using the task's ``signature`` method:
41
42 .. code-block:: pycon
43
44 >>> add.signature((2, 2), countdown=10)
45 tasks.add(2, 2)
46
47 - There's also a shortcut using star arguments:
48
49 .. code-block:: pycon
50
51 >>> add.s(2, 2)
52 tasks.add(2, 2)
53
54 - Keyword arguments are also supported:
55
56 .. code-block:: pycon
57
58 >>> add.s(2, 2, debug=True)
59 tasks.add(2, 2, debug=True)
60
61 - From any signature instance you can inspect the different fields:
62
63 .. code-block:: pycon
64
65 >>> s = add.signature((2, 2), {'debug': True}, countdown=10)
66 >>> s.args
67 (2, 2)
68 >>> s.kwargs
69 {'debug': True}
70 >>> s.options
71 {'countdown': 10}
72
73 - It supports the "Calling API" of ``delay``,
74 ``apply_async``, etc., including being called directly (``__call__``).
75
76 Calling the signature will execute the task inline in the current process:
77
78 .. code-block:: pycon
79
80 >>> add(2, 2)
81 4
82 >>> add.s(2, 2)()
83 4
84
85 ``delay`` is our beloved shortcut to ``apply_async`` taking star-arguments:
86
87 .. code-block:: pycon
88
89 >>> result = add.delay(2, 2)
90 >>> result.get()
91 4
92
93 ``apply_async`` takes the same arguments as the
94 :meth:`Task.apply_async <@Task.apply_async>` method:
95
96 .. code-block:: pycon
97
98 >>> add.apply_async(args, kwargs, **options)
99 >>> add.signature(args, kwargs, **options).apply_async()
100
101 >>> add.apply_async((2, 2), countdown=1)
102 >>> add.signature((2, 2), countdown=1).apply_async()
103
104 - You can't define options with :meth:`[email protected]`, but a chaining
105 ``set`` call takes care of that:
106
107 .. code-block:: pycon
108
109 >>> add.s(2, 2).set(countdown=1)
110 proj.tasks.add(2, 2)
111
112 Partials
113 --------
114
115 With a signature, you can execute the task in a worker:
116
117 .. code-block:: pycon
118
119 >>> add.s(2, 2).delay()
120 >>> add.s(2, 2).apply_async(countdown=1)
121
122 Or you can call it directly in the current process:
123
124 .. code-block:: pycon
125
126 >>> add.s(2, 2)()
127 4
128
129 Specifying additional args, kwargs, or options to ``apply_async``/``delay``
130 creates partials:
131
132 - Any arguments added will be prepended to the args in the signature:
133
134 .. code-block:: pycon
135
136 >>> partial = add.s(2) # incomplete signature
137 >>> partial.delay(4) # 4 + 2
138 >>> partial.apply_async((4,)) # same
139
140 .. note::
141
142 Additional args passed to ``delay``/``apply_async`` are **prepended**
143 to the signature args. Since ``add`` is commutative, the ordering may
144 not be obvious. A non-commutative task like
145 ``subtract(x, y) -> x - y`` makes this clear:
146
147 .. code-block:: python
148
149 @app.task
150 def subtract(x, y):
151 return x - y
152
153 partial = subtract.s(10) # incomplete: second arg only
154 partial.delay(30) # -> subtract(30, 10) = 20
155 Here ``delay(30)`` prepends ``30`` as the first argument, resulting
156 in ``subtract(30, 10)`` — not ``subtract(10, 30)``.
157
158 - Any keyword arguments added will be merged with the kwargs in the signature,
159 with the new keyword arguments taking precedence:
160
161 .. code-block:: pycon
162
163 >>> s = add.s(2, 2)
164 >>> s.delay(debug=True) # -> add(2, 2, debug=True)
165 >>> s.apply_async(kwargs={'debug': True}) # same
166
167 - Any options added will be merged with the options in the signature,
168 with the new options taking precedence:
169
170 .. code-block:: pycon
171
172 >>> s = add.signature((2, 2), countdown=10)
173 >>> s.apply_async(countdown=1) # countdown is now 1
174
175 You can also clone signatures to create derivatives:
176
177 .. code-block:: pycon
178
179 >>> s = add.s(2)
180 proj.tasks.add(2)
181
182 >>> s.clone(args=(4,), kwargs={'debug': True})
183 proj.tasks.add(4, 2, debug=True)
184
185 Immutability
186 ------------
187
188 .. versionadded:: 3.0
189
190 Partials are meant to be used with callbacks, any tasks linked, or chord
191 callbacks will be applied with the result of the parent task.
192 Sometimes you want to specify a callback that doesn't take
193 additional arguments, and in that case you can set the signature
194 to be immutable:
195
196 .. code-block:: pycon
197
198 >>> add.apply_async((2, 2), link=reset_buffers.signature(immutable=True))
199
200 The ``.si()`` shortcut can also be used to create immutable signatures:
201
202 .. code-block:: pycon
203
204 >>> add.apply_async((2, 2), link=reset_buffers.si())
205
206 Only the execution options can be set when a signature is immutable,
207 so it's not possible to call the signature with partial args/kwargs.
208
209 .. note::
210
211 In this tutorial I sometimes use the prefix operator `~` to signatures.
212 You probably shouldn't use it in your production code, but it's a handy shortcut
213 when experimenting in the Python shell:
214
215 .. code-block:: pycon
216
217 >>> ~sig
218
219 >>> # is the same as
220 >>> sig.delay().get()
221
222
223 .. _canvas-callbacks:
224
225 Callbacks
226 ---------
227
228 .. versionadded:: 3.0
229
230 Callbacks can be added to any task using the ``link`` argument
231 to ``apply_async``:
232
233 .. code-block:: pycon
234
235 add.apply_async((2, 2), link=other_task.s())
236
237 The callback will only be applied if the task exited successfully,
238 and it will be applied with the return value of the parent task as argument.
239
240 As I mentioned earlier, any arguments you add to a signature,
241 will be prepended to the arguments specified by the signature itself!
242
243 If you have the signature:
244
245 .. code-block:: pycon
246
247 >>> sig = add.s(10)
248
249 then `sig.delay(result)` becomes:
250
251 .. code-block:: pycon
252
253 >>> add.apply_async(args=(result, 10))
254
255 ...
256
257 Now let's call our ``add`` task with a callback using partial
258 arguments:
259
260 .. code-block:: pycon
261
262 >>> add.apply_async((2, 2), link=add.s(8))
263
264 As expected this will first launch one task calculating :math:`2 + 2`, then
265 another task calculating :math:`4 + 8`.
266
267 The Primitives
268 ==============
269
270 .. versionadded:: 3.0
271
272 .. topic:: Overview
273
274 - ``group``
275
276 The group primitive is a signature that takes a list of tasks that should
277 be applied in parallel.
278
279 - ``chain``
280
281 The chain primitive lets us link together signatures so that one is called
282 after the other, essentially forming a *chain* of callbacks.
283
284 - ``chord``
285
286 A chord is just like a group but with a callback. A chord consists
287 of a header group and a body, where the body is a task that should execute
288 after all of the tasks in the header are complete.
289
290 - ``map``
291
292 The map primitive works like the built-in ``map`` function, but creates
293 a temporary task where a list of arguments is applied to the task.
294 For example, ``task.map([1, 2])`` -- results in a single task
295 being called, applying the arguments in order to the task function so
296 that the result is:
297
298 .. code-block:: python
299
300 res = [task(1), task(2)]
301
302 - ``starmap``
303
304 Works exactly like map except the arguments are applied as ``*args``.
305 For example ``add.starmap([(2, 2), (4, 4)])`` results in a single
306 task calling:
307
308 .. code-block:: python
309
310 res = [add(2, 2), add(4, 4)]
311
312 - ``chunks``
313
314 Chunking splits a long list of arguments into parts, for example
315 the operation:
316
317 .. code-block:: pycon
318
319 >>> items = zip(range(1000), range(1000)) # 1000 items
320 >>> add.chunks(items, 10)
321
322 will split the list of items into chunks of 10, resulting in 100
323 tasks (each processing 10 items in sequence).
324
325
326 The primitives are also signature objects themselves, so that they can be combined
327 in any number of ways to compose complex work-flows.
328
329 Here're some examples:
330
331 - Simple chain
332
333 Here's a simple chain, the first task executes passing its return value
334 to the next task in the chain, and so on.
335
336 .. code-block:: pycon
337
338 >>> from celery import chain
339
340 >>> # 2 + 2 + 4 + 8
341 >>> res = chain(add.s(2, 2), add.s(4), add.s(8))()
342 >>> res.get()
343 16
344
345 This can also be written using pipes:
346
347 .. code-block:: pycon
348
349 >>> (add.s(2, 2) | add.s(4) | add.s(8))().get()
350 16
351
352 - Immutable signatures
353
354 Signatures can be partial so arguments can be
355 added to the existing arguments, but you may not always want that,
356 for example if you don't want the result of the previous task in a chain.
357
358 In that case you can mark the signature as immutable, so that the arguments
359 cannot be changed:
360
361 .. code-block:: pycon
362
363 >>> add.signature((2, 2), immutable=True)
364
365 There's also a ``.si()`` shortcut for this, and this is the preferred way of
366 creating signatures:
367
368 .. code-block:: pycon
369
370 >>> add.si(2, 2)
371
372 Now you can create a chain of independent tasks instead:
373
374 .. code-block:: pycon
375
376 >>> res = (add.si(2, 2) | add.si(4, 4) | add.si(8, 8))()
377 >>> res.get()
378 16
379
380 >>> res.parent.get()
381 8
382
383 >>> res.parent.parent.get()
384 4
385
386 - Simple group
387
388 You can easily create a group of tasks to execute in parallel:
389
390 .. code-block:: pycon
391
392 >>> from celery import group
393 >>> res = group(add.s(i, i) for i in range(10))()
394 >>> res.get(timeout=1)
395 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
396
397 - Simple chord
398
399 The chord primitive enables us to add a callback to be called when
400 all of the tasks in a group have finished executing. This is often
401 required for algorithms that aren't *embarrassingly parallel*:
402
403 .. code-block:: pycon
404
405 >>> from celery import chord
406 >>> res = chord((add.s(i, i) for i in range(10)), tsum.s())()
407 >>> res.get()
408 90
409
410 The above example creates 10 tasks that all start in parallel,
411 and when all of them are complete the return values are combined
412 into a list and sent to the ``tsum`` task.
413
414 The body of a chord can also be immutable, so that the return value
415 of the group isn't passed on to the callback:
416
417 .. code-block:: pycon
418
419 >>> chord((import_contact.s(c) for c in contacts),
420 ... notify_complete.si(import_id)).apply_async()
421
422 Note the use of ``.si`` above; this creates an immutable signature,
423 meaning any new arguments passed (including to return value of the
424 previous task) will be ignored.
425
426 - Blow your mind by combining
427
428 Chains can be partial too:
429
430 .. code-block:: pycon
431
432 >>> c1 = (add.s(4) | mul.s(8))
433
434 # (16 + 4) * 8
435 >>> res = c1(16)
436 >>> res.get()
437 160
438
439 this means that you can combine chains:
440
441 .. code-block:: pycon
442
443 # ((4 + 16) * 2 + 4) * 8
444 >>> c2 = (add.s(4, 16) | mul.s(2) | (add.s(4) | mul.s(8)))
445
446 >>> res = c2()
447 >>> res.get()
448 352
449
450 Chaining a group together with another task will automatically
451 upgrade it to be a chord:
452
453 .. code-block:: pycon
454
455 >>> c3 = (group(add.s(i, i) for i in range(10)) | tsum.s())
456 >>> res = c3()
457 >>> res.get()
458 90
459
460 Groups and chords accepts partial arguments too, so in a chain
461 the return value of the previous task is forwarded to all tasks in the group:
462
463 .. code-block:: pycon
464
465
466 >>> new_user_workflow = (create_user.s() | group(
467 ... import_contacts.s(),
468 ... send_welcome_email.s()))
469 ... new_user_workflow.delay(username='artv',
470 ... first='Art',
471 ... last='Vandelay',
472 ... email='[email protected]')
473
474
475 If you don't want to forward arguments to the group then
476 you can make the signatures in the group immutable:
477
478 .. code-block:: pycon
479
480 >>> res = (add.s(4, 4) | group(add.si(i, i) for i in range(10)))()
481 >>> res.get()
482 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
483
484 >>> res.parent.get()
485 8
486
487
488 .. warning::
489
490 With more complex workflows, the default JSON serializer has been observed to
491 drastically inflate message sizes due to recursive references, leading to
492 resource issues. The *pickle* serializer is not vulnerable to this and may
493 therefore be preferable in such cases.
494
495 .. _canvas-chain:
496
497 Chains
498 ------
499
500 .. versionadded:: 3.0
501
502 Tasks can be linked together: the linked task is called when the task
503 returns successfully:
504
505 .. code-block:: pycon
506
507 >>> res = add.apply_async((2, 2), link=mul.s(16))
508 >>> res.get()
509 4
510
511 The linked task will be applied with the result of its parent
512 task as the first argument. In the above case where the result was 4,
513 this will result in ``mul(4, 16)``.
514
515 The results will keep track of any subtasks called by the original task,
516 and this can be accessed from the result instance:
517
518 .. code-block:: pycon
519
520 >>> res.children
521 [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
522
523 >>> res.children[0].get()
524 64
525
526 The result instance also has a :meth:`[email protected]` method
527 that treats the result as a graph, enabling you to iterate over
528 the results:
529
530 .. code-block:: pycon
531
532 >>> list(res.collect())
533 [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
534 (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
535
536 By default :meth:`[email protected]` will raise an
537 :exc:`~@IncompleteStream` exception if the graph isn't fully
538 formed (one of the tasks hasn't completed yet),
539 but you can get an intermediate representation of the graph
540 too:
541
542 .. code-block:: pycon
543
544 >>> for result, value in res.collect(intermediate=True):
545 ....
546
547 You can link together as many tasks as you like,
548 and signatures can be linked too:
549
550 .. code-block:: pycon
551
552 >>> s = add.s(2, 2)
553 >>> s.link(mul.s(4))
554 >>> s.link(log_result.s())
555
556 You can also add *error callbacks* using the `on_error` method:
557
558 .. code-block:: pycon
559
560 >>> add.s(2, 2).on_error(log_error.s()).delay()
561
562 This will result in the following ``.apply_async`` call when the signature
563 is applied:
564
565 .. code-block:: pycon
566
567 >>> add.apply_async((2, 2), link_error=log_error.s())
568
569 The worker won't actually call the errback as a task, but will
570 instead call the errback function directly so that the raw request, exception
571 and traceback objects can be passed to it.
572
573 Here's an example errback:
574
575 .. code-block:: python
576
577
578 import os
579
580 from proj.celery import app
581
582 @app.task
583 def log_error(request, exc, traceback):
584 with open(os.path.join('/var/errors', request.id), 'a') as fh:
585 print('--\n\n{0} {1} {2}'.format(
586 request.id, exc, traceback), file=fh)
587
588 To make it even easier to link tasks together there's
589 a special signature called :class:`~celery.chain` that lets
590 you chain tasks together:
591
592 .. code-block:: pycon
593
594 >>> from celery import chain
595 >>> from proj.tasks import add, mul
596
597 >>> # (4 + 4) * 8 * 10
598 >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
599 proj.tasks.add(4, 4) | proj.tasks.mul(8) | proj.tasks.mul(10)
600
601
602 Calling the chain will call the tasks in the current process
603 and return the result of the last task in the chain:
604
605 .. code-block:: pycon
606
607 >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
608 >>> res.get()
609 640
610
611 It also sets ``parent`` attributes so that you can
612 work your way up the chain to get intermediate results:
613
614 .. code-block:: pycon
615
616 >>> res.parent.get()
617 64
618
619 >>> res.parent.parent.get()
620 8
621
622 >>> res.parent.parent
623 <AsyncResult: eeaad925-6778-4ad1-88c8-b2a63d017933>
624
625
626 Chains can also be made using the ``|`` (pipe) operator:
627
628 .. code-block:: pycon
629
630 >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async()
631
632 Task ID
633 ~~~~~~~
634
635 .. versionadded:: 5.4
636
637 A chain will inherit the task id of the last task in the chain.
638
639 Graphs
640 ~~~~~~
641
642 In addition you can work with the result graph as a
643 :class:`~celery.utils.graph.DependencyGraph`:
644
645 .. code-block:: pycon
646
647 >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
648
649 >>> res.parent.parent.graph
650 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
651 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
652 872c3995-6fa0-46ca-98c2-5a19155afcf0(2)
653 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
654 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
655
656 You can even convert these graphs to *dot* format:
657
658 .. code-block:: pycon
659
660 >>> with open('graph.dot', 'w') as fh:
661 ... res.parent.parent.graph.to_dot(fh)
662
663
664 and create images:
665
666 .. code-block:: console
667
668 $ dot -Tpng graph.dot -o graph.png
669
670 .. image:: ../images/result_graph.png
671
672 .. _canvas-group:
673
674 Groups
675 ------
676
677 .. versionadded:: 3.0
678
679 .. note::
680
681 Similarly to chords, tasks used in a group must *not* ignore their results.
682 See ":ref:`chord-important-notes`" for more information.
683
684
685 A group can be used to execute several tasks in parallel.
686
687 The :class:`~celery.group` function takes a list of signatures:
688
689 .. code-block:: pycon
690
691 >>> from celery import group
692 >>> from proj.tasks import add
693
694 >>> group(add.s(2, 2), add.s(4, 4))
695 (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
696
697 If you **call** the group, the tasks will be applied
698 one after another in the current process, and a :class:`~celery.result.GroupResult`
699 instance is returned that can be used to keep track of the results,
700 or tell how many tasks are ready and so on:
701
702 .. code-block:: pycon
703
704 >>> g = group(add.s(2, 2), add.s(4, 4))
705 >>> res = g()
706 >>> res.get()
707 [4, 8]
708
709 Group also supports iterators:
710
711 .. code-block:: pycon
712
713 >>> group(add.s(i, i) for i in range(100))()
714
715 A group is a signature object, so it can be used in combination
716 with other signatures.
717
718 .. _group-callbacks:
719
720 Group Callbacks and Error Handling
721 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
722
723 Groups can have callback and errback signatures linked to them as well, however
724 the behaviour can be somewhat surprising due to the fact that groups are not
725 real tasks and simply pass linked tasks down to their encapsulated signatures.
726 This means that the return values of a group are not collected to be passed to
727 a linked callback signature.
728 Additionally, linking the task will *not* guarantee that it will activate only
729 when all group tasks have finished.
730 As an example, the following snippet using a simple `add(a, b)` task is faulty
731 since the linked `add.s()` signature will not receive the finalised group
732 result as one might expect.
733
734 .. code-block:: pycon
735
736 >>> g = group(add.s(2, 2), add.s(4, 4))
737 >>> g.link(add.s())
738 >>> res = g()
739 [4, 8]
740
741 Note that the finalised results of the first two tasks are returned, but the
742 callback signature will have run in the background and raised an exception
743 since it did not receive the two arguments it expects.
744
745 Group errbacks are passed down to encapsulated signatures as well which opens
746 the possibility for an errback linked only once to be called more than once if
747 multiple tasks in a group were to fail.
748 As an example, the following snippet using a `fail()` task which raises an
749 exception can be expected to invoke the `log_error()` signature once for each
750 failing task which gets run in the group.
751
752 .. code-block:: pycon
753
754 >>> g = group(fail.s(), fail.s())
755 >>> g.link_error(log_error.s())
756 >>> res = g()
757
758 With this in mind, it's generally advisable to create idempotent or counting
759 tasks which are tolerant to being called repeatedly for use as errbacks.
760
761 These use cases are better addressed by the :class:`~celery.chord` class which
762 is supported on certain backend implementations.
763
764 .. _group-results:
765
766 Group Results
767 ~~~~~~~~~~~~~
768
769 The group task returns a special result too,
770 this result works just like normal task results, except
771 that it works on the group as a whole:
772
773 .. code-block:: pycon
774
775 >>> from celery import group
776 >>> from tasks import add
777
778 >>> job = group([
779 ... add.s(2, 2),
780 ... add.s(4, 4),
781 ... add.s(8, 8),
782 ... add.s(16, 16),
783 ... add.s(32, 32),
784 ... ])
785
786 >>> result = job.apply_async()
787
788 >>> result.ready() # have all subtasks completed?
789 True
790 >>> result.successful() # were all subtasks successful?
791 True
792 >>> result.get()
793 [4, 8, 16, 32, 64]
794
795 The :class:`~celery.result.GroupResult` takes a list of
796 :class:`~celery.result.AsyncResult` instances and operates on them as
797 if it was a single task.
798
799 It supports the following operations:
800
801 * :meth:`~celery.result.GroupResult.successful`
802
803 Return :const:`True` if all of the subtasks finished
804 successfully (e.g., didn't raise an exception).
805
806 * :meth:`~celery.result.GroupResult.failed`
807
808 Return :const:`True` if any of the subtasks failed.
809
810 * :meth:`~celery.result.GroupResult.waiting`
811
812 Return :const:`True` if any of the subtasks
813 isn't ready yet.
814
815 * :meth:`~celery.result.GroupResult.ready`
816
817 Return :const:`True` if all of the subtasks
818 are ready.
819
820 * :meth:`~celery.result.GroupResult.completed_count`
821
822 Return the number of completed subtasks. Note that `complete` means `successful` in
823 this context. In other words, the return value of this method is the number of
824 ``successful`` tasks.
825
826 * :meth:`~celery.result.GroupResult.revoke`
827
828 Revoke all of the subtasks.
829
830 * :meth:`~celery.result.GroupResult.join`
831
832 Gather the results of all subtasks
833 and return them in the same order as they were called (as a list).
834
835 .. _group-unrolling:
836
837 Group Unrolling
838 ~~~~~~~~~~~~~~~
839
840 A group with a single signature will be unrolled to a single signature when chained.
841 This means that the following group may pass either a list of results or a single result to the chain
842 depending on the number of items in the group.
843
844 .. code-block:: pycon
845
846 >>> from celery import chain, group
847 >>> from tasks import add
848 >>> chain(add.s(2, 2), group(add.s(1)), add.s(1))
849 add(2, 2) | add(1) | add(1)
850 >>> chain(add.s(2, 2), group(add.s(1), add.s(2)), add.s(1))
851 add(2, 2) | %add((add(1), add(2)), 1)
852
853 This means that you should be careful and make sure the ``add`` task can accept either a list or a single item as input
854 if you plan to use it as part of a larger canvas.
855
856 .. warning::
857
858 In Celery 4.x the following group below would not unroll into a chain due to a bug but instead the canvas would be
859 upgraded into a chord.
860
861 .. code-block:: pycon
862
863 >>> from celery import chain, group
864 >>> from tasks import add
865 >>> chain(group(add.s(1, 1)), add.s(2))
866 %add([add(1, 1)], 2)
867
868 In Celery 5.x this bug was fixed and the group is correctly unrolled into a single signature.
869
870 .. code-block:: pycon
871
872 >>> from celery import chain, group
873 >>> from tasks import add
874 >>> chain(group(add.s(1, 1)), add.s(2))
875 add(1, 1) | add(2)
876
877 .. _canvas-chord:
878
879 Chords
880 ------
881
882 .. versionadded:: 2.3
883
884 .. note::
885
886 Tasks used within a chord must *not* ignore their results. If the result
887 backend is disabled for *any* task (header or body) in your chord you
888 should read ":ref:`chord-important-notes`". Chords are not currently
889 supported with the RPC result backend.
890
891
892 A chord is a task that only executes after all of the tasks in a group have
893 finished executing.
894
895
896 Let's calculate the sum of the expression
897 :math:`1 + 1 + 2 + 2 + 3 + 3 ... n + n` up to a hundred digits.
898
899 First you need two tasks, :func:`add` and :func:`tsum` (:func:`sum` is
900 already a standard function):
901
902 .. code-block:: python
903
904 @app.task
905 def add(x, y):
906 return x + y
907
908 @app.task
909 def tsum(numbers):
910 return sum(numbers)
911
912
913 Now you can use a chord to calculate each addition step in parallel, and then
914 get the sum of the resulting numbers:
915
916 .. code-block:: pycon
917
918 >>> from celery import chord
919 >>> from tasks import add, tsum
920
921 >>> chord(add.s(i, i)
922 ... for i in range(100))(tsum.s()).get()
923 9900
924
925
926 This is obviously a very contrived example, the overhead of messaging and
927 synchronization makes this a lot slower than its Python counterpart:
928
929 .. code-block:: pycon
930
931 >>> sum(i + i for i in range(100))
932
933 The synchronization step is costly, so you should avoid using chords as much
934 as possible. Still, the chord is a powerful primitive to have in your toolbox
935 as synchronization is a required step for many parallel algorithms.
936
937 Let's break the chord expression down:
938
939 .. code-block:: pycon
940
941 >>> callback = tsum.s()
942 >>> header = [add.s(i, i) for i in range(100)]
943 >>> result = chord(header)(callback)
944 >>> result.get()
945 9900
946
947 Remember, the callback can only be executed after all of the tasks in the
948 header have returned. Each step in the header is executed as a task, in
949 parallel, possibly on different nodes. The callback is then applied with
950 the return value of each task in the header. The task id returned by
951 :meth:`chord` is the id of the callback, so you can wait for it to complete
952 and get the final return value (but remember to :ref:`never have a task wait
953 for other tasks <task-synchronous-subtasks>`)
954
955 .. _chord-errors:
956
957 Error handling
958 ~~~~~~~~~~~~~~
959
960 So what happens if one of the tasks raises an exception?
961
962 The chord callback result will transition to the failure state, and the error is set
963 to the :exc:`~@ChordError` exception:
964
965 .. code-block:: pycon
966
967 >>> c = chord([add.s(4, 4), raising_task.s(), add.s(8, 8)])
968 >>> result = c()
969 >>> result.get()
970
971 .. code-block:: pytb
972
973 Traceback (most recent call last):
974 File "<stdin>", line 1, in <module>
975 File "*/celery/result.py", line 120, in get
976 interval=interval)
977 File "*/celery/backends/amqp.py", line 150, in wait_for
978 raise meta['result']
979 celery.exceptions.ChordError: Dependency 97de6f3f-ea67-4517-a21c-d867c61fcb47
980 raised ValueError('something something',)
981
982 While the traceback may be different depending on the result backend used,
983 you can see that the error description includes the id of the task that failed
984 and a string representation of the original exception. You can also
985 find the original traceback in ``result.traceback``.
986
987 Note that the rest of the tasks will still execute, so the third task
988 (``add.s(8, 8)``) is still executed even though the middle task failed.
989 Also the :exc:`~@ChordError` only shows the task that failed
990 first (in time): it doesn't respect the ordering of the header group.
991
992 To perform an action when a chord fails you can therefore attach
993 an errback to the chord callback:
994
995 .. code-block:: python
996
997 @app.task
998 def on_chord_error(request, exc, traceback):
999 print('Task {0!r} raised error: {1!r}'.format(request.id, exc))
1000
1001 .. code-block:: pycon
1002
1003 >>> c = (group(add.s(i, i) for i in range(10)) |
1004 ... tsum.s().on_error(on_chord_error.s())).delay()
1005
1006 Chords may have callback and errback signatures linked to them, which addresses
1007 some of the issues with linking signatures to groups.
1008 Doing so will link the provided signature to the chord's body which can be
1009 expected to gracefully invoke callbacks just once upon completion of the body,
1010 or errbacks just once if any task in the chord header or body fails.
1011
1012 This behavior can be manipulated to allow error handling of the chord header using the :ref:`task_allow_error_cb_on_chord_header <task_allow_error_cb_on_chord_header>` flag.
1013 Enabling this flag will cause the chord header to invoke the errback for the body (default behavior) *and* any task in the chord's header that fails.
1014
1015 .. _chord-important-notes:
1016
1017 Important Notes
1018 ~~~~~~~~~~~~~~~
1019
1020 Tasks used within a chord must *not* ignore their results. In practice this
1021 means that you must enable a :const:`result_backend` in order to use
1022 chords. Additionally, if :const:`task_ignore_result` is set to :const:`True`
1023 in your configuration, be sure that the individual tasks to be used within
1024 the chord are defined with :const:`ignore_result=False`. This applies to both
1025 Task subclasses and decorated tasks.
1026
1027 Example Task subclass:
1028
1029 .. code-block:: python
1030
1031 class MyTask(Task):
1032 ignore_result = False
1033
1034
1035 Example decorated task:
1036
1037 .. code-block:: python
1038
1039 @app.task(ignore_result=False)
1040 def another_task(project):
1041 do_something()
1042
1043 By default the synchronization step is implemented by having a recurring task
1044 poll the completion of the group every second, calling the signature when
1045 ready.
1046
1047 Example implementation:
1048
1049 .. code-block:: python
1050
1051 from celery import maybe_signature
1052
1053 @app.task(bind=True)
1054 def unlock_chord(self, group, callback, interval=1, max_retries=None):
1055 if group.ready():
1056 return maybe_signature(callback).delay(group.join())
1057 raise self.retry(countdown=interval, max_retries=max_retries)
1058
1059
1060 This is used by all result backends except Redis, Memcached and DynamoDB: they
1061 increment a counter after each task in the header, then applies the callback
1062 when the counter exceeds the number of tasks in the set.
1063
1064 The Redis, Memcached and DynamoDB approach is a much better solution, but not easily
1065 implemented in other backends (suggestions welcome!).
1066
1067 .. note::
1068
1069 Chords don't properly work with Redis before version 2.2; you'll need to
1070 upgrade to at least redis-server 2.2 to use them.
1071
1072 .. note::
1073
1074 If you're using chords with the Redis result backend and also overriding
1075 the :meth:`Task.after_return` method, you need to make sure to call the
1076 super method or else the chord callback won't be applied.
1077
1078 .. code-block:: python
1079
1080 def after_return(self, *args, **kwargs):
1081 do_something()
1082 super().after_return(*args, **kwargs)
1083
1084 .. _canvas-map:
1085
1086 Map & Starmap
1087 -------------
1088
1089 :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
1090 that call the provided calling task for every element in a sequence.
1091
1092 They differ from :class:`~celery.group` in that:
1093
1094 - only one task message is sent.
1095
1096 - the operation is sequential.
1097
1098 For example using ``map``:
1099
1100 .. code-block:: pycon
1101
1102 >>> from proj.tasks import add
1103
1104 >>> ~tsum.map([list(range(10)), list(range(100))])
1105 [45, 4950]
1106
1107 is the same as having a task doing:
1108
1109 .. code-block:: python
1110
1111 @app.task
1112 def temp():
1113 return [tsum(range(10)), tsum(range(100))]
1114
1115 and using ``starmap``:
1116
1117 .. code-block:: pycon
1118
1119 >>> ~add.starmap(zip(range(10), range(10)))
1120 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
1121
1122 is the same as having a task doing:
1123
1124 .. code-block:: python
1125
1126 @app.task
1127 def temp():
1128 return [add(i, i) for i in range(10)]
1129
1130 Both ``map`` and ``starmap`` are signature objects, so they can be used as
1131 other signatures and combined in groups etc., for example
1132 to call the starmap after 10 seconds:
1133
1134 .. code-block:: pycon
1135
1136 >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
1137
1138 .. _canvas-chunks:
1139
1140 Chunks
1141 ------
1142
1143 Chunking lets you divide an iterable of work into pieces, so that if
1144 you have one million objects, you can create 10 tasks with a hundred
1145 thousand objects each.
1146
1147 Some may worry that chunking your tasks results in a degradation
1148 of parallelism, but this is rarely true for a busy cluster
1149 and in practice since you're avoiding the overhead of messaging
1150 it may considerably increase performance.
1151
1152 To create a chunks' signature you can use :meth:`@Task.chunks`:
1153
1154 .. code-block:: pycon
1155
1156 >>> add.chunks(zip(range(100), range(100)), 10)
1157
1158 As with :class:`~celery.group` the act of sending the messages for
1159 the chunks will happen in the current process when called:
1160
1161 .. code-block:: pycon
1162
1163 >>> from proj.tasks import add
1164
1165 >>> res = add.chunks(zip(range(100), range(100)), 10)()
1166 >>> res.get()
1167 [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
1168 [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
1169 [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
1170 [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
1171 [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
1172 [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
1173 [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
1174 [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
1175 [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
1176 [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
1177
1178 while calling ``.apply_async`` will create a dedicated
1179 task so that the individual tasks are applied in a worker
1180 instead:
1181
1182 .. code-block:: pycon
1183
1184 >>> add.chunks(zip(range(100), range(100)), 10).apply_async()
1185
1186 You can also convert chunks to a group:
1187
1188 .. code-block:: pycon
1189
1190 >>> group = add.chunks(zip(range(100), range(100)), 10).group()
1191
1192 and with the group skew the countdown of each task by increments
1193 of one:
1194
1195 .. code-block:: pycon
1196
1197 >>> group.skew(start=1, stop=10)()
1198
1199 This means that the first task will have a countdown of one second, the second
1200 task a countdown of two seconds, and so on.
1201
1202 .. _canvas-stamping:
1203
1204 Stamping
1205 ========
1206
1207 .. versionadded:: 5.3
1208
1209 The goal of the Stamping API is to give an ability to label
1210 the signature and its components for debugging information purposes.
1211 For example, when the canvas is a complex structure, it may be necessary to
1212 label some or all elements of the formed structure. The complexity
1213 increases even more when nested groups are rolled-out or chain
1214 elements are replaced. In such cases, it may be necessary to
1215 understand which group an element is a part of or on what nested
1216 level it is. This requires a mechanism that traverses the canvas
1217 elements and marks them with specific metadata. The stamping API
1218 allows doing that based on the Visitor pattern.
1219
1220 For example,
1221
1222 .. code-block:: pycon
1223
1224 >>> sig1 = add.si(2, 2)
1225 >>> sig1_res = sig1.freeze()
1226 >>> g = group(sig1, add.si(3, 3))
1227 >>> g.stamp(stamp='your_custom_stamp')
1228 >>> res = g.apply_async()
1229 >>> res.get(timeout=TIMEOUT)
1230 [4, 6]
1231 >>> sig1_res._get_task_meta()['stamp']
1232 ['your_custom_stamp']
1233
1234 will initialize a group ``g`` and mark its components with stamp ``your_custom_stamp``.
1235
1236 For this feature to be useful, you need to set the :setting:`result_extended`
1237 configuration option to ``True`` or directive ``result_extended = True``.
1238
1239 Canvas stamping
1240 ----------------
1241
1242 We can also stamp the canvas with custom stamping logic, using the visitor class ``StampingVisitor``
1243 as the base class for the custom stamping visitor.
1244
1245 Custom stamping
1246 ----------------
1247
1248 If more complex stamping logic is required, it is possible
1249 to implement custom stamping behavior based on the Visitor
1250 pattern. The class that implements this custom logic must
1251 inherit ``StampingVisitor`` and implement appropriate methods.
1252
1253 For example, the following example ``InGroupVisitor`` will label
1254 tasks that are in side of some group by label ``in_group``.
1255
1256 .. code-block:: python
1257
1258 class InGroupVisitor(StampingVisitor):
1259 def __init__(self):
1260 self.in_group = False
1261
1262 def on_group_start(self, group, **headers) -> dict:
1263 self.in_group = True
1264 return {"in_group": [self.in_group], "stamped_headers": ["in_group"]}
1265
1266 def on_group_end(self, group, **headers) -> None:
1267 self.in_group = False
1268
1269 def on_chain_start(self, chain, **headers) -> dict:
1270 return {"in_group": [self.in_group], "stamped_headers": ["in_group"]}
1271
1272 def on_signature(self, sig, **headers) -> dict:
1273 return {"in_group": [self.in_group], "stamped_headers": ["in_group"]}
1274
1275 The following example shows another custom stamping visitor, which labels all
1276 tasks with a custom ``monitoring_id`` which can represent a UUID value of an external monitoring system,
1277 that can be used to track the task execution by including the id with such a visitor implementation.
1278 This ``monitoring_id`` can be a randomly generated UUID, or a unique identifier of the span id used by
1279 the external monitoring system, etc.
1280
1281 .. code-block:: python
1282
1283 class MonitoringIdStampingVisitor(StampingVisitor):
1284 def on_signature(self, sig, **headers) -> dict:
1285 return {'monitoring_id': uuid4().hex}
1286
1287 .. important::
1288
1289 The ``stamped_headers`` key in the dictionary returned by ``on_signature()`` (or any other visitor method) is **optional**:
1290
1291 .. code-block:: python
1292
1293 # Approach 1: Without stamped_headers - ALL keys are treated as stamps
1294 def on_signature(self, sig, **headers) -> dict:
1295 return {'monitoring_id': uuid4().hex} # monitoring_id becomes a stamp
1296
1297 # Approach 2: With stamped_headers - ONLY listed keys are stamps
1298 def on_signature(self, sig, **headers) -> dict:
1299 return {
1300 'monitoring_id': uuid4().hex, # This will be a stamp
1301 'other_data': 'value', # This will NOT be a stamp
1302 'stamped_headers': ['monitoring_id'] # Only monitoring_id is stamped
1303 }
1304
1305 If the ``stamped_headers`` key is not specified, the stamping visitor will assume all keys in the returned dictionary are stamped headers.
1306
1307 Next, let's see how to use the ``MonitoringIdStampingVisitor`` example stamping visitor.
1308
1309 .. code-block:: python
1310
1311 sig_example = signature('t1')
1312 sig_example.stamp(visitor=MonitoringIdStampingVisitor())
1313
1314 group_example = group([signature('t1'), signature('t2')])
1315 group_example.stamp(visitor=MonitoringIdStampingVisitor())
1316
1317 chord_example = chord([signature('t1'), signature('t2')], signature('t3'))
1318 chord_example.stamp(visitor=MonitoringIdStampingVisitor())
1319
1320 chain_example = chain(signature('t1'), group(signature('t2'), signature('t3')), signature('t4'))
1321 chain_example.stamp(visitor=MonitoringIdStampingVisitor())
1322
1323 Lastly, it's important to mention that each monitoring id stamp in the example above would be different from each other between tasks.
1324
1325 Callbacks stamping
1326 ------------------
1327
1328 The stamping API also supports stamping callbacks implicitly.
1329 This means that when a callback is added to a task, the stamping
1330 visitor will be applied to the callback as well.
1331
1332 .. warning::
1333
1334 The callback must be linked to the signature before stamping.
1335
1336 For example, let's examine the following custom stamping visitor that uses the
1337 implicit approach where all returned dictionary keys are automatically treated as
1338 stamped headers without explicitly specifying `stamped_headers`.
1339
1340 .. code-block:: python
1341
1342 class CustomStampingVisitor(StampingVisitor):
1343 def on_signature(self, sig, **headers) -> dict:
1344 # 'header' will automatically be treated as a stamped header
1345 # without needing to specify 'stamped_headers': ['header']
1346 return {'header': 'value'}
1347
1348 def on_callback(self, callback, **header) -> dict:
1349 # 'on_callback' will automatically be treated as a stamped header
1350 return {'on_callback': True}
1351
1352 def on_errback(self, errback, **header) -> dict:
1353 # 'on_errback' will automatically be treated as a stamped header
1354 return {'on_errback': True}
1355
1356 This custom stamping visitor will stamp the signature, callbacks, and errbacks with ``{'header': 'value'}``
1357 and stamp the callbacks and errbacks with ``{'on_callback': True}`` and ``{'on_errback': True}`` respectively as shown below.
1358
1359 .. code-block:: python
1360
1361 c = chord([add.s(1, 1), add.s(2, 2)], xsum.s())
1362 callback = signature('sig_link')
1363 errback = signature('sig_link_error')
1364 c.link(callback)
1365 c.link_error(errback)
1366 c.stamp(visitor=CustomStampingVisitor())
1367
1368 This example will result in the following stamps:
1369
1370 .. code-block:: python
1371
1372 >>> c.options
1373 {'header': 'value', 'stamped_headers': ['header']}
1374 >>> c.tasks.tasks[0].options
1375 {'header': 'value', 'stamped_headers': ['header']}
1376 >>> c.tasks.tasks[1].options
1377 {'header': 'value', 'stamped_headers': ['header']}
1378 >>> c.body.options
1379 {'header': 'value', 'stamped_headers': ['header']}
1380 >>> c.body.options['link'][0].options
1381 {'header': 'value', 'on_callback': True, 'stamped_headers': ['header', 'on_callback']}
1382 >>> c.body.options['link_error'][0].options
1383 {'header': 'value', 'on_errback': True, 'stamped_headers': ['header', 'on_errback']}