Debian Codegraph @

cylc/flow/taskdef.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Task definition."""
18
19 from collections import deque
20 from typing import (
21 TYPE_CHECKING,
22 Dict,
23 List,
24 NamedTuple,
25 Set,
26 Tuple,
27 )
28
29 from cylc.flow.exceptions import TaskDefError
30 import cylc.flow.flags
31 from cylc.flow.task_id import TaskID
32 from cylc.flow.task_outputs import (
33 SORT_ORDERS,
34 TASK_OUTPUT_FAILED,
35 TASK_OUTPUT_SUBMITTED,
36 TASK_OUTPUT_SUCCEEDED,
37 )
38
39 if TYPE_CHECKING:
40 from cylc.flow.cycling import (
41 PointBase,
42 SequenceBase,
43 )
44 from cylc.flow.task_trigger import (
45 Dependency,
46 TaskTrigger,
47 )
48
49
50 class TaskTuple(NamedTuple):
51 name: str
52 point: 'PointBase'
53 is_abs: bool
54
55
56 def generate_graph_children(
57 tdef: 'TaskDef', point: 'PointBase'
58 ) -> Dict[str, List[TaskTuple]]:
59 """Determine graph children of this task at point."""
60 graph_children: Dict[str, List[TaskTuple]] = {}
61 for seq, dout in tdef.graph_children.items():
62 for output, downs in dout.items():
63 for name, trigger in downs:
64 child_point = trigger.get_child_point(point, seq)
65 is_abs = (
66 trigger.offset_is_absolute or
67 trigger.offset_is_from_icp
68 )
69 if is_abs and trigger.get_parent_point(point) != point:
70 # If 'foo[^] => bar' only spawn off of '^'.
71 continue
72 if seq.is_valid(child_point):
73 # E.g.: foo should trigger only on T06:
74 # PT6H = "waz"
75 # T06 = "waz[-PT6H] => foo"
76 graph_children.setdefault(output, []).append(
77 TaskTuple(name, child_point, is_abs)
78 )
79
80 if tdef.sequential:
81 # Add next-instance child.
82 nexts = []
83 for seq in tdef.sequences:
84 nxt = seq.get_next_point(point)
85 if nxt is not None:
86 # Within sequence bounds.
87 nexts.append(nxt)
88 if nexts:
89 graph_children.setdefault(TASK_OUTPUT_SUCCEEDED, []).append(
90 TaskTuple(tdef.name, min(nexts), False)
91 )
92
93 return graph_children
94
95
96 def generate_graph_parents(
97 tdef: 'TaskDef', point: 'PointBase', taskdefs: dict[str, 'TaskDef']
98 ) -> list[TaskTuple]:
99 """Determine concrete graph parents of task tdef at point.
100
101 Infer parents by reversing upstream triggers that lead to point/task.
102 """
103 graph_parents: list[TaskTuple] = []
104
105 for seq, triggers in tdef.graph_parents.items():
106 if not seq.is_valid(point):
107 # Don't infer parents if the trigger belongs to a sequence that
108 # does not include the child point. E.g.:
109 # T06 = "waz[-PT6H] => foo"
110 # here waz[-PT6H] is a parent of T06/foo but not of T12/foo.
111 continue
112 for parent_name, trigger in triggers:
113 parent_point = trigger.get_parent_point(point)
114 if (
115 parent_point != point and
116 not taskdefs[parent_name].is_valid_point(parent_point)
117 ):
118 # Don't infer inter-cycle parents if the upstream point is
119 # not valid for the parent (which depends on its sequences).
120 # NOTE this includes pre-initial dependence where the offset
121 # extends back beyond the initial point AND erroneous offsets
122 # when different tasks are involved, e.g.:
123 # woo[-Px] => foo
124 # where (point -Px) does not land on a valid point for woo.
125 # TODO ideally validation would flag this as an error.
126 continue
127 is_abs = trigger.offset_is_absolute or trigger.offset_is_from_icp
128 graph_parents.append(
129 TaskTuple(parent_name, parent_point, is_abs)
130 )
131
132 if tdef.sequential:
133 # Add implicit previous-instance parent.
134 closest_prev_point: PointBase | None = max(
135 (
136 prev
137 for seq in tdef.sequences
138 if (prev := seq.get_prev_point(point)) is not None
139 ),
140 default=None,
141 )
142 if closest_prev_point is not None:
143 graph_parents.append(
144 TaskTuple(tdef.name, closest_prev_point, False)
145 )
146
147 return graph_parents
148
149
150 class TaskDef:
151 """Task definition."""
152
153 # Memory optimization - constrain possible attributes to this list.
154 __slots__ = [
155 "rtconfig", "start_point", "initial_point", "sequences",
156 "used_in_offset_trigger", "max_future_prereq_offset",
157 "sequential", "is_coldstart",
158 "workflow_polling_cfg", "expiration_offset",
159 "namespace_hierarchy", "dependencies", "outputs", "param_var",
160 "graph_children", "graph_parents", "has_abs_triggers",
161 "external_triggers", "xtrig_labels", "name", "elapsed_times"]
162
163 # Store the elapsed times for a maximum of 10 cycles
164 MAX_LEN_ELAPSED_TIMES = 10
165
166 def __init__(self, name, rtcfg, start_point, initial_point):
167 if not TaskID.is_valid_name(name):
168 raise TaskDefError("Illegal task name: %s" % name)
169 self.name: str = name
170 self.rtconfig = rtcfg
171 self.start_point = start_point
172 self.initial_point = initial_point
173
174 self.sequences: List[SequenceBase] = []
175 self.used_in_offset_trigger = False
176
177 # some defaults
178 self.max_future_prereq_offset = None
179 self.sequential = False
180 self.workflow_polling_cfg = {}
181
182 self.expiration_offset = None
183 self.namespace_hierarchy = []
184 self.dependencies: Dict[SequenceBase, List[Dependency]] = {}
185 self.outputs = {} # {output: (message, is_required)}
186 self.graph_children: Dict[
187 SequenceBase, Dict[str, Set[Tuple[str, TaskTrigger]]]
188 ] = {}
189 self.graph_parents: Dict[
190 SequenceBase, Set[Tuple[str, TaskTrigger]]
191 ] = {}
192 self.param_var = {}
193 self.external_triggers = []
194 self.xtrig_labels = {} # {sequence: [labels]}
195
196 self.elapsed_times = deque(maxlen=self.MAX_LEN_ELAPSED_TIMES)
197 self._add_std_outputs()
198 self.has_abs_triggers = False
199
200 def add_output(self, output, message):
201 """Add a new task output as defined under [runtime]."""
202 # optional/required is None until defined by the graph
203 self.outputs[output] = (message, None)
204
205 def get_output(self, message):
206 """Return output name corresponding to task message."""
207 for name, (msg, _) in self.outputs.items():
208 if msg == message:
209 return name
210 raise KeyError(f"Unknown task output message: {message}")
211
212 def _add_std_outputs(self):
213 """Add the standard outputs."""
214 # optional/required is None until defined by the graph
215 for output in SORT_ORDERS:
216 self.outputs[output] = (output, None)
217
218 def set_required_output(self, output, required):
219 """Set outputs to required or optional."""
220 # (Note outputs and associated messages are already defined.)
221 message, _ = self.outputs[output]
222 self.outputs[output] = (message, required)
223
224 def tweak_outputs(self):
225 """Output consistency checking and tweaking."""
226 # If :succeed or :fail not set, assume success is required.
227 if (
228 self.outputs[TASK_OUTPUT_SUCCEEDED][1] is None
229 and self.outputs[TASK_OUTPUT_FAILED][1] is None
230 ):
231 self.set_required_output(TASK_OUTPUT_SUCCEEDED, True)
232
233 # In Cylc 7 back compat mode, make all success outputs required.
234 if cylc.flow.flags.cylc7_back_compat:
235 for output in [
236 TASK_OUTPUT_SUBMITTED,
237 TASK_OUTPUT_SUCCEEDED
238 ]:
239 self.set_required_output(output, True)
240
241 def add_graph_child(
242 self, trigger: 'TaskTrigger', taskname: str, sequence: 'SequenceBase'
243 ) -> None:
244 """Record child task instances that depend on my outputs.
245 {sequence:
246 {
247 output: [(a,t1), (b,t2), ...] # (task-name, trigger)
248 }
249 }
250 """
251 self.graph_children.setdefault(
252 sequence, {}
253 ).setdefault(
254 trigger.output, set()
255 ).add((taskname, trigger))
256
257 def add_graph_parent(
258 self, trigger: 'TaskTrigger', parent: str, sequence: 'SequenceBase'
259 ) -> None:
260 """Record task instances that I depend on.
261 {
262 sequence: set([(a,t1), (b,t2), ...]) # (task-name, trigger)
263 }
264 """
265 self.graph_parents.setdefault(sequence, set()).add((parent, trigger))
266
267 def add_dependency(self, dependency, sequence):
268 """Add a dependency to a named sequence.
269
270 Args:
271 dependency (cylc.flow.task_trigger.Dependency): The dependency to
272 add.
273 sequence (cylc.flow.cycling.SequenceBase): The sequence for which
274 this dependency applies.
275
276 """
277 self.dependencies.setdefault(sequence, []).append(dependency)
278 if any(
279 trig.offset_is_from_icp or
280 trig.offset_is_absolute
281 for trig in dependency.task_triggers
282 ):
283 self.has_abs_triggers = True
284
285 def add_xtrig_label(self, xtrig_label, sequence):
286 """Add an xtrigger to a named sequence.
287
288 Args:
289 xtrig_label: The xtrigger label to add.
290 sequence (cylc.cycling.SequenceBase): The sequence for which this
291 xtrigger applies.
292
293 """
294 self.xtrig_labels.setdefault(sequence, []).append(xtrig_label)
295
296 def add_sequence(self, sequence):
297 """Add a sequence."""
298 if sequence not in self.sequences:
299 self.sequences.append(sequence)
300
301 def describe(self):
302 """Return title and description of the current task."""
303 return self.rtconfig['meta']
304
305 def check_for_explicit_cycling(self):
306 """Check for explicitly somewhere.
307
308 Must be called after all graph sequences added.
309 """
310 if len(self.sequences) == 0 and self.used_in_offset_trigger:
311 raise TaskDefError(
312 "No cycling sequences defined for %s" % self.name)
313
314 def get_parent_points(self, point):
315 """Return the cycle points of my parents, at point."""
316 parent_points = set()
317 for seq in self.sequences:
318 if not seq.is_valid(point):
319 continue
320 if seq in self.dependencies:
321 # task has prereqs in this sequence
322 for dep in self.dependencies[seq]:
323 if dep.suicide:
324 continue
325 for trig in dep.task_triggers:
326 parent_points.add(trig.get_parent_point(point))
327 return parent_points
328
329 def get_prereqs(self, point):
330 """Return my prereqs, at point."""
331 prereqs = set()
332 for seq in self.sequences:
333 if not seq.is_valid(point):
334 continue
335 if seq in self.dependencies:
336 # task has prereqs in this sequence
337 for dep in self.dependencies[seq]:
338 if dep.suicide:
339 continue
340 prereqs.add(dep.get_prerequisite(point, self))
341 return prereqs
342
343 def get_xtrigs(self, point):
344 """Return my xtrigger labels, at point."""
345 xlabels = set()
346 for seq in self.sequences:
347 if not seq.is_valid(point):
348 continue
349 if seq in self.xtrig_labels:
350 # task has xtriggers in this sequence
351 xlabels.update(self.xtrig_labels[seq])
352 return xlabels
353
354 def get_triggers(self, point):
355 """Return my triggers, at point."""
356 triggers = set()
357 for seq in self.sequences:
358 if not seq.is_valid(point):
359 continue
360 if seq in self.dependencies:
361 # task has prereqs in this sequence
362 for dep in self.dependencies[seq]:
363 if dep.suicide:
364 continue
365 for trig in dep.task_triggers:
366 triggers.add(trig)
367 return triggers
368
369 def has_only_abs_triggers(self, point):
370 """Return whether I have only absolute triggers at point."""
371 if not self.has_abs_triggers:
372 return False
373 # Has abs triggers somewhere, but need to check at point.
374 has_abs = False
375 for seq in self.sequences:
376 if not seq.is_valid(point) or seq not in self.dependencies:
377 continue
378 for dep in self.dependencies[seq]:
379 for trig in dep.task_triggers:
380 if (
381 trig.offset_is_absolute or
382 trig.offset_is_from_icp or
383 # Don't count suicide as a normal trigger:
384 dep.suicide
385 ):
386 has_abs = True
387 else:
388 return False
389 return has_abs
390
391 def is_valid_point(self, point: 'PointBase') -> bool:
392 """Return True if point is on-sequence and within bounds."""
393 return any(
394 sequence.is_valid(point) for sequence in self.sequences
395 )
396
397 def first_point(self, icp):
398 """Return the first point for this task."""
399 point = None
400 adjusted = []
401 for seq in self.sequences:
402 pt = seq.get_first_point(icp)
403 if pt:
404 # may be None if beyond the sequence bounds
405 adjusted.append(pt)
406 if adjusted:
407 point = min(adjusted)
408 return point
409
410 def next_point_parentless(
411 self, cutoff: 'PointBase', point: 'PointBase | None' = None
412 ):
413 """Return next cycle point for which I'm parentless.
414
415 For a given recurrence, a task is either parented or parentless.
416
417 If point is None, return the first parentless cycle; otherwise
418 the first parentless cycle > point.
419
420 Cutoff is the start cycle point, prior to which we ignore parents.
421
422 """
423 adjusted = []
424 for seq in self.sequences:
425 next_point = (
426 seq.get_first_point(cutoff)
427 if point is None
428 else seq.get_next_point(point)
429 )
430 if next_point and self.is_parentless(next_point, cutoff):
431 adjusted.append(next_point)
432 if adjusted:
433 return min(adjusted)
434 return None
435
436 def is_parentless(self, point: 'PointBase', cutoff: 'PointBase') -> bool:
437 """Return True if task has no parents at the given point.
438
439 Tasks are considered parentless if they have:
440 - no parents at all
441 - all parents < cutoff cycle point
442 - only absolute triggers
443
444 Absolute-triggered tasks are auto-spawned like true parentless tasks,
445 (once the trigger is satisfied they are effectively parentless) but
446 with a prerequisite that gets satisfied when the absolute output is
447 completed at runtime.
448
449 Args:
450 point: The cycle point to check.
451 cutoff: This should be the start cycle point for the startup
452 spawning, or the intial cycle point for manually triggered
453 tasks.
454 """
455 if not self.graph_parents:
456 # No parents at any point
457 return True
458 if self.sequential:
459 # Implicit parents
460 return False
461 parent_points = self.get_parent_points(point)
462 return (
463 not parent_points
464 or all(x < cutoff for x in parent_points)
465 or self.has_only_abs_triggers(point)
466 )
467
468 def __repr__(self) -> str:
469 """
470 >>> TaskDef(
471 ... name='oliver', rtcfg={}, start_point='1',
472 ... initial_point='1'
473 ... )
474 <TaskDef 'oliver'>
475 """
476 return f"<TaskDef '{self.name}'>"