-
Notifications
You must be signed in to change notification settings - Fork 752
/
runtime.py
1703 lines (1541 loc) · 67.3 KB
/
runtime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Local backend
Execute the flow with a native runtime
using local / remote processes
"""
from __future__ import print_function
import os
import sys
import fcntl
import time
import subprocess
from datetime import datetime
from io import BytesIO
from functools import partial
from concurrent import futures
from metaflow.datastore.exceptions import DataException
from contextlib import contextmanager
from . import get_namespace
from .metadata import MetaDatum
from .metaflow_config import MAX_ATTEMPTS, UI_URL
from .exception import (
MetaflowException,
MetaflowInternalError,
METAFLOW_EXIT_DISALLOW_RETRY,
)
from . import procpoll
from .datastore import TaskDataStoreSet
from .debug import debug
from .decorators import flow_decorators
from .mflog import mflog, RUNTIME_LOG_SOURCE
from .util import to_unicode, compress_list, unicode_type
from .clone_util import clone_task_helper
from .unbounded_foreach import (
CONTROL_TASK_TAG,
UBF_CONTROL,
UBF_TASK,
)
import metaflow.tracing as tracing
MAX_WORKERS = 16
MAX_NUM_SPLITS = 100
MAX_LOG_SIZE = 1024 * 1024
POLL_TIMEOUT = 1000 # ms
PROGRESS_INTERVAL = 300 # s
# The following is a list of the (data) artifacts used by the runtime while
# executing a flow. These are prefetched during the resume operation by
# leveraging the TaskDataStoreSet.
PREFETCH_DATA_ARTIFACTS = ["_foreach_stack", "_task_ok", "_transition"]
RESUME_POLL_SECONDS = 60
# Runtime must use logsource=RUNTIME_LOG_SOURCE for all loglines that it
# formats according to mflog. See a comment in mflog.__init__
mflog_msg = partial(mflog.decorate, RUNTIME_LOG_SOURCE)
# TODO option: output dot graph periodically about execution
class NativeRuntime(object):
def __init__(
self,
flow,
graph,
flow_datastore,
metadata,
environment,
package,
logger,
entrypoint,
event_logger,
monitor,
run_id=None,
clone_run_id=None,
clone_only=False,
reentrant=False,
steps_to_rerun=None,
max_workers=MAX_WORKERS,
max_num_splits=MAX_NUM_SPLITS,
max_log_size=MAX_LOG_SIZE,
resume_identifier=None,
):
if run_id is None:
self._run_id = metadata.new_run_id()
else:
self._run_id = run_id
metadata.register_run_id(run_id)
self._flow = flow
self._graph = graph
self._flow_datastore = flow_datastore
self._metadata = metadata
self._environment = environment
self._logger = logger
self._max_workers = max_workers
self._active_tasks = dict() # Key: step name;
# value: [number of running tasks, number of done tasks]
# Special key 0 is total number of running tasks
self._active_tasks[0] = 0
self._unprocessed_steps = set([n.name for n in self._graph])
self._max_num_splits = max_num_splits
self._max_log_size = max_log_size
self._params_task = None
self._entrypoint = entrypoint
self.event_logger = event_logger
self._monitor = monitor
self._resume_identifier = resume_identifier
self._clone_run_id = clone_run_id
self._clone_only = clone_only
self._cloned_tasks = []
self._cloned_task_index = set()
self._reentrant = reentrant
self._run_url = None
# If steps_to_rerun is specified, we will not clone them in resume mode.
self._steps_to_rerun = steps_to_rerun or {}
# sorted_nodes are in topological order already, so we only need to
# iterate through the nodes once to get a stable set of rerun steps.
for step_name in self._graph.sorted_nodes:
if step_name in self._steps_to_rerun:
out_funcs = self._graph[step_name].out_funcs or []
for next_step in out_funcs:
self._steps_to_rerun.add(next_step)
self._origin_ds_set = None
if clone_run_id:
# resume logic
# 0. If clone_run_id is specified, attempt to clone all the
# successful tasks from the flow with `clone_run_id`. And run the
# unsuccessful or not-run steps in the regular fashion.
# 1. With _find_origin_task, for every task in the current run, we
# find the equivalent task in `clone_run_id` using
# pathspec_index=run/step:[index] and verify if this task can be
# cloned.
# 2. If yes, we fire off a clone-only task which copies the
# metadata from the `clone_origin` to pathspec=run/step/task to
# mimmick that the resumed run looks like an actual run.
# 3. All steps that couldn't be cloned (either unsuccessful or not
# run) are run as regular tasks.
# Lastly, to improve the performance of the cloning process, we
# leverage the TaskDataStoreSet abstraction to prefetch the
# entire DAG of `clone_run_id` and relevant data artifacts
# (see PREFETCH_DATA_ARTIFACTS) so that the entire runtime can
# access the relevant data from cache (instead of going to the datastore
# after the first prefetch).
logger(
"Gathering required information to resume run (this may take a bit of time)..."
)
self._origin_ds_set = TaskDataStoreSet(
flow_datastore,
clone_run_id,
prefetch_data_artifacts=PREFETCH_DATA_ARTIFACTS,
)
self._run_queue = []
self._poll = procpoll.make_poll()
self._workers = {} # fd -> subprocess mapping
self._finished = {}
self._is_cloned = {}
# NOTE: In case of unbounded foreach, we need the following to schedule
# the (sibling) mapper tasks of the control task (in case of resume);
# and ensure that the join tasks runs only if all dependent tasks have
# finished.
self._control_num_splits = {} # control_task -> num_splits mapping
for step in flow:
for deco in step.decorators:
deco.runtime_init(flow, graph, package, self._run_id)
def _new_task(self, step, input_paths=None, **kwargs):
if input_paths is None:
may_clone = True
else:
may_clone = all(self._is_cloned[path] for path in input_paths)
if step in self._steps_to_rerun:
may_clone = False
if step == "_parameters":
decos = []
else:
decos = getattr(self._flow, step).decorators
return Task(
self._flow_datastore,
self._flow,
step,
self._run_id,
self._metadata,
self._environment,
self._entrypoint,
self.event_logger,
self._monitor,
input_paths=input_paths,
may_clone=may_clone,
clone_run_id=self._clone_run_id,
clone_only=self._clone_only,
reentrant=self._reentrant,
origin_ds_set=self._origin_ds_set,
decos=decos,
logger=self._logger,
resume_identifier=self._resume_identifier,
**kwargs,
)
@property
def run_id(self):
return self._run_id
def persist_constants(self, task_id=None):
self._params_task = self._new_task("_parameters", task_id=task_id)
if not self._params_task.is_cloned:
self._params_task.persist(self._flow)
self._is_cloned[self._params_task.path] = self._params_task.is_cloned
def should_skip_clone_only_execution(self):
(
should_skip_clone_only_execution,
skip_reason,
) = self._should_skip_clone_only_execution()
if should_skip_clone_only_execution:
self._logger(skip_reason, system_msg=True)
return True
return False
@contextmanager
def run_heartbeat(self):
self._metadata.start_run_heartbeat(self._flow.name, self._run_id)
yield
self._metadata.stop_heartbeat()
def print_workflow_info(self):
self._run_url = (
"%s/%s/%s" % (UI_URL.rstrip("/"), self._flow.name, self._run_id)
if UI_URL
else None
)
if self._run_url:
self._logger(
"Workflow starting (run-id %s), see it in the UI at %s"
% (
self._run_id,
self._run_url,
),
system_msg=True,
)
else:
self._logger(
"Workflow starting (run-id %s):" % self._run_id, system_msg=True
)
def _should_skip_clone_only_execution(self):
if self._clone_only and self._params_task:
if self._params_task.resume_done():
return True, "Resume already complete. Skip clone-only execution."
if not self._params_task.is_resume_leader():
return (
True,
"Not resume leader under resume execution. Skip clone-only execution.",
)
return False, None
def clone_task(
self,
step_name,
task_id,
pathspec_index,
ubf_context,
generate_task_obj,
verbose=False,
):
try:
new_task_id = task_id
if generate_task_obj:
task = self._new_task(step_name, pathspec_index=pathspec_index)
if ubf_context:
task.ubf_context = ubf_context
new_task_id = task.task_id
self._cloned_tasks.append(task)
self._cloned_task_index.add(task.task_index)
if verbose:
self._logger(
"Cloning task from {}/{}/{}/{} to {}/{}/{}/{}".format(
self._flow.name,
self._clone_run_id,
step_name,
task_id,
self._flow.name,
self._run_id,
step_name,
new_task_id,
),
system_msg=True,
)
clone_task_helper(
self._flow.name,
self._clone_run_id,
self._run_id,
step_name,
task_id, # origin_task_id
new_task_id,
self._flow_datastore,
self._metadata,
origin_ds_set=self._origin_ds_set,
)
except Exception as e:
self._logger(
"Cloning {}/{}/{}/{} failed with error: {}".format(
self._flow.name, self._clone_run_id, step_name, task_id, str(e)
)
)
def clone_original_run(self, generate_task_obj=False, verbose=True):
self._logger(
"Cloning {}/{}".format(self._flow.name, self._clone_run_id),
system_msg=True,
)
inputs = []
ubf_mapper_tasks_to_clone = []
# We only clone ubf mapper tasks if the control task is complete.
# Here we need to check which control tasks are complete, and then get the corresponding
# mapper tasks.
for task_ds in self._origin_ds_set:
_, step_name, task_id = task_ds.pathspec.split("/")
pathspec_index = task_ds.pathspec_index
if task_ds["_task_ok"] and step_name != "_parameters":
# Only control task can have _control_mapper_tasks. We then store the corresponding mapepr task pathspecs.
control_mapper_tasks = (
[]
if "_control_mapper_tasks" not in task_ds
else task_ds["_control_mapper_tasks"]
)
ubf_mapper_tasks_to_clone.extend(control_mapper_tasks)
for task_ds in self._origin_ds_set:
_, step_name, task_id = task_ds.pathspec.split("/")
pathspec_index = task_ds.pathspec_index
if (
task_ds["_task_ok"]
and step_name != "_parameters"
and (step_name not in self._steps_to_rerun)
):
# "_unbounded_foreach" is a special flag to indicate that the transition is an unbounded foreach.
# Both parent and splitted children tasks will have this flag set. The splitted control/mapper tasks
# have no "foreach_param" because UBF is always followed by a join step.
is_ubf_task = (
"_unbounded_foreach" in task_ds and task_ds["_unbounded_foreach"]
) and (self._graph[step_name].foreach_param is None)
# Only the control task has "_control_mapper_tasks" artifact.
is_ubf_control_task = (
is_ubf_task
and ("_control_mapper_tasks" in task_ds)
and task_ds["_control_mapper_tasks"]
)
is_ubf_mapper_tasks = is_ubf_task and (not is_ubf_control_task)
if is_ubf_mapper_tasks and (
task_ds.pathspec not in ubf_mapper_tasks_to_clone
):
# Skip copying UBF mapper tasks if control tasks is incomplete.
continue
ubf_context = None
if is_ubf_task:
ubf_context = "ubf_test" if is_ubf_mapper_tasks else "ubf_control"
inputs.append(
(
step_name,
task_id,
pathspec_index,
is_ubf_mapper_tasks,
ubf_context,
)
)
with futures.ThreadPoolExecutor(max_workers=self._max_workers) as executor:
all_tasks = [
executor.submit(
self.clone_task,
step_name,
task_id,
pathspec_index,
ubf_context=ubf_context,
generate_task_obj=generate_task_obj and (not is_ubf_mapper_tasks),
verbose=verbose,
)
for (
step_name,
task_id,
pathspec_index,
is_ubf_mapper_tasks,
ubf_context,
) in inputs
]
_, _ = futures.wait(all_tasks)
self._logger(
"{}/{} cloned!".format(self._flow.name, self._clone_run_id), system_msg=True
)
self._params_task.mark_resume_done()
def execute(self):
if len(self._cloned_tasks) > 0:
# mutable list storing the cloned tasks.
self._run_queue = []
self._active_tasks[0] = 0
else:
if self._params_task:
self._queue_push("start", {"input_paths": [self._params_task.path]})
else:
self._queue_push("start", {})
progress_tstamp = time.time()
try:
# main scheduling loop
exception = None
while self._run_queue or self._active_tasks[0] > 0 or self._cloned_tasks:
# 1. are any of the current workers finished?
if self._cloned_tasks:
finished_tasks = self._cloned_tasks
# reset the list of cloned tasks and let poll_workers handle
# the remaining transition
self._cloned_tasks = []
else:
finished_tasks = list(self._poll_workers())
# 2. push new tasks triggered by the finished tasks to the queue
self._queue_tasks(finished_tasks)
# 3. if there are available worker slots, pop and start tasks
# from the queue.
self._launch_workers()
if time.time() - progress_tstamp > PROGRESS_INTERVAL:
progress_tstamp = time.time()
tasks_print = ", ".join(
[
"%s (%d running; %d done)" % (k, v[0], v[1])
for k, v in self._active_tasks.items()
if k != 0 and v[0] > 0
]
)
if self._active_tasks[0] == 0:
msg = "No tasks are running."
else:
if self._active_tasks[0] == 1:
msg = "1 task is running: "
else:
msg = "%d tasks are running: " % self._active_tasks[0]
msg += "%s." % tasks_print
self._logger(msg, system_msg=True)
if len(self._run_queue) == 0:
msg = "No tasks are waiting in the queue."
else:
if len(self._run_queue) == 1:
msg = "1 task is waiting in the queue: "
else:
msg = "%d tasks are waiting in the queue." % len(
self._run_queue
)
self._logger(msg, system_msg=True)
if len(self._unprocessed_steps) > 0:
if len(self._unprocessed_steps) == 1:
msg = "%s step has not started" % (
next(iter(self._unprocessed_steps)),
)
else:
msg = "%d steps have not started: " % len(
self._unprocessed_steps
)
msg += "%s." % ", ".join(self._unprocessed_steps)
self._logger(msg, system_msg=True)
except KeyboardInterrupt as ex:
self._logger("Workflow interrupted.", system_msg=True, bad=True)
self._killall()
exception = ex
raise
except Exception as ex:
self._logger("Workflow failed.", system_msg=True, bad=True)
self._killall()
exception = ex
raise
finally:
# on finish clean tasks
for step in self._flow:
for deco in step.decorators:
deco.runtime_finished(exception)
# assert that end was executed and it was successful
if ("end", ()) in self._finished:
if self._run_url:
self._logger(
"Done! See the run in the UI at %s" % self._run_url,
system_msg=True,
)
else:
self._logger("Done!", system_msg=True)
elif self._clone_only:
self._logger(
"Clone-only resume complete -- only previously successful steps were "
"cloned; no new tasks executed!",
system_msg=True,
)
self._params_task.mark_resume_done()
else:
raise MetaflowInternalError(
"The *end* step was not successful by the end of flow."
)
def _killall(self):
# If we are here, all children have received a signal and are shutting down.
# We want to give them an opportunity to do so and then kill
live_workers = set(self._workers.values())
now = int(time.time())
self._logger(
"Terminating %d active tasks..." % len(live_workers),
system_msg=True,
bad=True,
)
while live_workers and int(time.time()) - now < 5:
# While not all workers are dead and we have waited less than 5 seconds
live_workers = [worker for worker in live_workers if not worker.clean()]
if live_workers:
self._logger(
"Killing %d remaining tasks after having waited for %d seconds -- "
"some tasks may not exit cleanly"
% (len(live_workers), int(time.time()) - now),
system_msg=True,
bad=True,
)
for worker in live_workers:
worker.kill()
self._logger("Flushing logs...", system_msg=True, bad=True)
# give killed workers a chance to flush their logs to datastore
for _ in range(3):
list(self._poll_workers())
# Given the current task information (task_index), the type of transition,
# and the split index, return the new task index.
def _translate_index(self, task, next_step, type, split_index=None):
import re
match = re.match(r"^(.+)\[(.*)\]$", task.task_index)
if match:
_, foreach_index = match.groups()
# Convert foreach_index to a list of integers
if len(foreach_index) > 0:
foreach_index = foreach_index.split(",")
else:
foreach_index = []
else:
raise ValueError(
"Index not in the format of {run_id}/{step_name}[{foreach_index}]"
)
if type == "linear":
return "%s[%s]" % (next_step, ",".join(foreach_index))
elif type == "join":
indices = []
if len(foreach_index) > 0:
indices = foreach_index[:-1]
return "%s[%s]" % (next_step, ",".join(indices))
elif type == "split":
foreach_index.append(str(split_index))
return "%s[%s]" % (next_step, ",".join(foreach_index))
# Store the parameters needed for task creation, so that pushing on items
# onto the run_queue is an inexpensive operation.
def _queue_push(self, step, task_kwargs, index=None):
# If the to-be-pushed task is already cloned before, we don't need
# to re-run it.
if index and index in self._cloned_task_index:
return
self._run_queue.insert(0, (step, task_kwargs))
# For foreaches, this will happen multiple time but is ok, becomes a no-op
self._unprocessed_steps.discard(step)
def _queue_pop(self):
return self._run_queue.pop() if self._run_queue else (None, {})
def _queue_task_join(self, task, next_steps):
# if the next step is a join, we need to check that
# all input tasks for the join have finished before queuing it.
# CHECK: this condition should be enforced by the linter but
# let's assert that the assumption holds
if len(next_steps) > 1:
msg = (
"Step *{step}* transitions to a join and another "
"step. The join must be the only transition."
)
raise MetaflowInternalError(task, msg.format(step=task.step))
else:
next_step = next_steps[0]
unbounded_foreach = not task.results.is_none("_unbounded_foreach")
if unbounded_foreach:
# Before we queue the join, do some post-processing of runtime state
# (_finished, _is_cloned) for the (sibling) mapper tasks.
# Update state of (sibling) mapper tasks for control task.
if task.ubf_context == UBF_CONTROL:
mapper_tasks = task.results.get("_control_mapper_tasks")
if not mapper_tasks:
msg = (
"Step *{step}* has a control task which didn't "
"specify the artifact *_control_mapper_tasks* for "
"the subsequent *{join}* step."
)
raise MetaflowInternalError(
msg.format(step=task.step, join=next_steps[0])
)
elif not (
isinstance(mapper_tasks, list)
and isinstance(mapper_tasks[0], unicode_type)
):
msg = (
"Step *{step}* has a control task which didn't "
"specify the artifact *_control_mapper_tasks* as a "
"list of strings but instead specified it as {typ} "
"with elements of {elem_typ}."
)
raise MetaflowInternalError(
msg.format(
step=task.step,
typ=type(mapper_tasks),
elem_type=type(mapper_tasks[0]),
)
)
num_splits = len(mapper_tasks)
self._control_num_splits[task.path] = num_splits
# If the control task is cloned, all mapper tasks should have been cloned
# as well, so we no longer need to handle cloning of mapper tasks in runtime.
# Update _finished since these tasks were successfully
# run elsewhere so that join will be unblocked.
_, foreach_stack = task.finished_id
top = foreach_stack[-1]
bottom = list(foreach_stack[:-1])
for i in range(num_splits):
s = tuple(bottom + [top._replace(index=i)])
self._finished[(task.step, s)] = mapper_tasks[i]
self._is_cloned[mapper_tasks[i]] = False
# Find and check status of control task and retrieve its pathspec
# for retrieving unbounded foreach cardinality.
_, foreach_stack = task.finished_id
top = foreach_stack[-1]
bottom = list(foreach_stack[:-1])
s = tuple(bottom + [top._replace(index=None)])
# UBF control can also be the first task of the list. Then
# it will have index=0 instead of index=None.
if task.results.get("_control_task_is_mapper_zero", False):
s = tuple(bottom + [top._replace(index=0)])
control_path = self._finished.get((task.step, s))
if control_path:
# Control task was successful.
# Additionally check the state of (sibling) mapper tasks as well
# (for the sake of resume) before queueing join task.
num_splits = self._control_num_splits[control_path]
required_tasks = []
for i in range(num_splits):
s = tuple(bottom + [top._replace(index=i)])
required_tasks.append(self._finished.get((task.step, s)))
if all(required_tasks):
index = self._translate_index(task, next_step, "join")
# all tasks to be joined are ready. Schedule the next join step.
self._queue_push(
next_step,
{"input_paths": required_tasks, "join_type": "foreach"},
index,
)
else:
# matching_split is the split-parent of the finished task
matching_split = self._graph[self._graph[next_step].split_parents[-1]]
_, foreach_stack = task.finished_id
index = ""
if matching_split.type == "foreach":
# next step is a foreach join
def siblings(foreach_stack):
top = foreach_stack[-1]
bottom = list(foreach_stack[:-1])
for index in range(top.num_splits):
yield tuple(bottom + [top._replace(index=index)])
# required tasks are all split-siblings of the finished task
required_tasks = [
self._finished.get((task.step, s)) for s in siblings(foreach_stack)
]
join_type = "foreach"
index = self._translate_index(task, next_step, "join")
else:
# next step is a split
# required tasks are all branches joined by the next step
required_tasks = [
self._finished.get((step, foreach_stack))
for step in self._graph[next_step].in_funcs
]
join_type = "linear"
index = self._translate_index(task, next_step, "linear")
if all(required_tasks):
# all tasks to be joined are ready. Schedule the next join step.
self._queue_push(
next_step,
{"input_paths": required_tasks, "join_type": join_type},
index,
)
def _queue_task_foreach(self, task, next_steps):
# CHECK: this condition should be enforced by the linter but
# let's assert that the assumption holds
if len(next_steps) > 1:
msg = (
"Step *{step}* makes a foreach split but it defines "
"multiple transitions. Specify only one transition "
"for foreach."
)
raise MetaflowInternalError(msg.format(step=task.step))
else:
next_step = next_steps[0]
unbounded_foreach = not task.results.is_none("_unbounded_foreach")
if unbounded_foreach:
# Need to push control process related task.
ubf_iter_name = task.results.get("_foreach_var")
ubf_iter = task.results.get(ubf_iter_name)
# UBF control task has no split index, hence "None" as place holder.
if task.results.get("_control_task_is_mapper_zero", False):
index = self._translate_index(task, next_step, "split", 0)
else:
index = self._translate_index(task, next_step, "split", None)
self._queue_push(
next_step,
{
"input_paths": [task.path],
"ubf_context": UBF_CONTROL,
"ubf_iter": ubf_iter,
},
index,
)
else:
num_splits = task.results["_foreach_num_splits"]
if num_splits > self._max_num_splits:
msg = (
"Foreach in step *{step}* yielded {num} child steps "
"which is more than the current maximum of {max} "
"children. You can raise the maximum with the "
"--max-num-splits option. "
)
raise TaskFailed(
task,
msg.format(
step=task.step, num=num_splits, max=self._max_num_splits
),
)
# schedule all splits
for i in range(num_splits):
index = self._translate_index(task, next_step, "split", i)
self._queue_push(
next_step,
{"split_index": str(i), "input_paths": [task.path]},
index,
)
def _queue_tasks(self, finished_tasks):
# finished tasks include only successful tasks
for task in finished_tasks:
self._finished[task.finished_id] = task.path
self._is_cloned[task.path] = task.is_cloned
# CHECK: ensure that runtime transitions match with
# statically inferred transitions. Make an exception for control
# tasks, where we just rely on static analysis since we don't
# execute user code.
trans = task.results.get("_transition")
if trans:
next_steps = trans[0]
foreach = trans[1]
else:
next_steps = []
foreach = None
expected = self._graph[task.step].out_funcs
if next_steps != expected:
msg = (
"Based on static analysis of the code, step *{step}* "
"was expected to transition to step(s) *{expected}*. "
"However, when the code was executed, self.next() was "
"called with *{actual}*. Make sure there is only one "
"unconditional self.next() call in the end of your "
"step. "
)
raise MetaflowInternalError(
msg.format(
step=task.step,
expected=", ".join(expected),
actual=", ".join(next_steps),
)
)
# Different transition types require different treatment
if any(self._graph[f].type == "join" for f in next_steps):
# Next step is a join
self._queue_task_join(task, next_steps)
elif foreach:
# Next step is a foreach child
self._queue_task_foreach(task, next_steps)
else:
# Next steps are normal linear steps
for step in next_steps:
index = self._translate_index(task, step, "linear")
self._queue_push(step, {"input_paths": [task.path]}, index)
def _poll_workers(self):
if self._workers:
for event in self._poll.poll(POLL_TIMEOUT):
worker = self._workers.get(event.fd)
if worker:
if event.can_read:
worker.read_logline(event.fd)
if event.is_terminated:
returncode = worker.terminate()
for fd in worker.fds():
self._poll.remove(fd)
del self._workers[fd]
step_counts = self._active_tasks[worker.task.step]
step_counts[0] -= 1 # One less task for this step is running
step_counts[1] += 1 # ... and one more completed.
# We never remove from self._active_tasks because it is possible
# for all currently running task for a step to complete but
# for others to still be queued up.
self._active_tasks[0] -= 1
task = worker.task
if returncode:
# worker did not finish successfully
if (
worker.cleaned
or returncode == METAFLOW_EXIT_DISALLOW_RETRY
):
self._logger(
"This failed task will not be retried.",
system_msg=True,
)
else:
if (
task.retries
< task.user_code_retries + task.error_retries
):
self._retry_worker(worker)
else:
raise TaskFailed(task)
else:
# worker finished successfully
yield task
def _launch_workers(self):
while self._run_queue and self._active_tasks[0] < self._max_workers:
step, task_kwargs = self._queue_pop()
# Initialize the task (which can be expensive using remote datastores)
# before launching the worker so that cost is amortized over time, instead
# of doing it during _queue_push.
task = self._new_task(step, **task_kwargs)
self._launch_worker(task)
def _retry_worker(self, worker):
worker.task.retries += 1
if worker.task.retries >= MAX_ATTEMPTS:
# any results with an attempt ID >= MAX_ATTEMPTS will be ignored
# by datastore, so running a task with such a retry_could would
# be pointless and dangerous
raise MetaflowInternalError(
"Too many task attempts (%d)! "
"MAX_ATTEMPTS exceeded." % worker.task.retries
)
worker.task.new_attempt()
self._launch_worker(worker.task)
def _launch_worker(self, task):
if self._clone_only and not task.is_cloned:
# We don't launch a worker here
self._logger(
"Not executing non-cloned task for step '%s' in clone-only resume"
% "/".join([task.flow_name, task.run_id, task.step]),
system_msg=True,
)
return
worker = Worker(task, self._max_log_size)
for fd in worker.fds():
self._workers[fd] = worker
self._poll.add(fd)
active_step_counts = self._active_tasks.setdefault(task.step, [0, 0])
# We have an additional task for this step running
active_step_counts[0] += 1
# One more task actively running
self._active_tasks[0] += 1
class Task(object):
clone_pathspec_mapping = {}
def __init__(
self,
flow_datastore,
flow,
step,
run_id,
metadata,
environment,
entrypoint,
event_logger,
monitor,
input_paths=None,
may_clone=False,
clone_run_id=None,
clone_only=False,
reentrant=False,
origin_ds_set=None,
decos=None,
logger=None,
# Anything below this is passed as part of kwargs
split_index=None,
ubf_context=None,
ubf_iter=None,
join_type=None,
task_id=None,
resume_identifier=None,
pathspec_index=None,
):
self.step = step
self.flow = flow
self.flow_name = flow.name
self.run_id = run_id
self.task_id = None
self._path = None
self.input_paths = input_paths
self.split_index = split_index
self.ubf_context = ubf_context
self.ubf_iter = ubf_iter
self.decos = [] if decos is None else decos
self.entrypoint = entrypoint
self.environment = environment
self.environment_type = self.environment.TYPE
self.clone_run_id = clone_run_id
self.clone_origin = None
self.origin_ds_set = origin_ds_set
self.metadata = metadata
self.event_logger = event_logger
self.monitor = monitor
self._logger = logger
self.retries = 0
self.user_code_retries = 0
self.error_retries = 0
self.tags = metadata.sticky_tags
self.event_logger_type = self.event_logger.TYPE
self.monitor_type = monitor.TYPE
self.metadata_type = metadata.TYPE
self.datastore_type = flow_datastore.TYPE
self._flow_datastore = flow_datastore
self.datastore_sysroot = flow_datastore.datastore_root
self._results_ds = None
# Only used in clone-only resume.
self._is_resume_leader = None
self._resume_done = None
self._resume_identifier = resume_identifier
origin = None
if clone_run_id and may_clone:
origin = self._find_origin_task(clone_run_id, join_type, pathspec_index)
if origin and origin["_task_ok"]:
# At this point, we know we are going to clone
self._is_cloned = True
task_id_exists_already = False
task_completed = False
if reentrant:
# A re-entrant clone basically allows multiple concurrent processes
# to perform the clone at the same time to the same new run id. Let's